repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
omiz/In-Air
refs/heads/master
In Air/Source/Helper/Extension/UIView.swift
apache-2.0
1
// // UIView.swift // Clouds // // Created by Omar Allaham on 3/19/17. // Copyright © 2017 Bemaxnet. All rights reserved. // import UIKit extension UIView { class func load(fromNib nib: String, bundle : Bundle? = nil) -> UIView? { return UINib( nibName: nib, bundle: bundle ).instantiate(withOwner: nil, options: nil)[0] as? UIView } enum ShadowDirection: Int { case horizontal case vertical } func addShadow(_ direction: ShadowDirection = .vertical) { layer.shadowColor = UIColor.darkGray.cgColor layer.shadowOffset = CGSize(width: direction == .vertical ? 0 : -0.5, height: 0.5) layer.shadowOpacity = 0.2 layer.shouldRasterize = false clipsToBounds = false layer.masksToBounds = false } }
4d8bb3c328c47e7a50128e05d8f09e79
23.606061
88
0.623153
false
false
false
false
MNTDeveloppement/MNTAppAnimations
refs/heads/master
MNTApp/Transitions/TransitionPresentationController.swift
mit
1
// // TransitionController.swift // MNTApp // // Created by Mehdi Sqalli on 30/12/14. // Copyright (c) 2014 MNT Developpement. All rights reserved. // import UIKit import QuartzCore class TransitionPresentationController: NSObject, UIViewControllerAnimatedTransitioning { let animationDuration = 1.0 var animating = false var operation:UINavigationControllerOperation = .Push weak var storedContext: UIViewControllerContextTransitioning? = nil func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return animationDuration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! let containerView = transitionContext.containerView() let animationDuration = self .transitionDuration(transitionContext) // take a snapshot of the detail ViewController so we can do whatever with it (cause it's only a view), and don't have to care about breaking constraints let snapshotView = toViewController.view.resizableSnapshotViewFromRect(toViewController.view.frame, afterScreenUpdates: true, withCapInsets: UIEdgeInsetsZero) snapshotView.transform = CGAffineTransformMakeScale(0.1, 0.1) snapshotView.center = fromViewController.view.center containerView.addSubview(snapshotView) // hide the detail view until the snapshot is being animated toViewController.view.alpha = 0.0 containerView.addSubview(toViewController.view) UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 20.0, options: nil, animations: { () -> Void in snapshotView.transform = CGAffineTransformIdentity }, completion: { (finished) -> Void in snapshotView.removeFromSuperview() toViewController.view.alpha = 1.0 transitionContext.completeTransition(finished) }) // storedContext = transitionContext // // let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as FirstViewController // let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as HomeViewController // // transitionContext.containerView().addSubview(toVC.view) // // // grow logo // // let animation = CABasicAnimation(keyPath: "transform") // // animation.toValue = NSValue(CATransform3D: CATransform3DMakeScale(8.0, 10.0, 1.0) //// CATransform3DConcat( ////// CATransform3DMakeTranslation(0.0, 0.0, 0.0), //// CATransform3DMakeScale(15.0, 10.0, 10.0) //// ) // ) // // animation.duration = animationDuration // animation.delegate = self // animation.fillMode = kCAFillModeForwards // animation.removedOnCompletion = false // delay(seconds: animationDuration) { () -> () in // fromVC.mntLogo.layer.removeAllAnimations() // //transitionContext.containerView().addSubview(toVC.view) // } // // fromVC.mntLogo.layer.addAnimation(animation, forKey: nil) // // toVC.logo.layer.opacity = 0.0 // //// let fadeIn = CABasicAnimation(keyPath: "opacity") //// fadeIn.duration = animationDuration //// fadeIn.toValue = 3.0 // //// toVC.logo.layer.addAnimation(fadeIn, forKey: "fadeIn") //// toVC.logo.layer.addAnimation(animation, forKey: nil) } override func animationDidStop(anim: CAAnimation!, finished flag: Bool) { if let context = storedContext { // let toVC = context.viewControllerForKey(UITransitionContextToViewControllerKey) as HomeViewController // toVC.logo.layer.opacity = 0 context.completeTransition(!context.transitionWasCancelled()) } storedContext = nil animating = false } }
9e245cce3c1a241aaf0e24a5a71b5bf5
40.913462
166
0.664373
false
false
false
false
ALHariPrasad/iOS-9-Sampler
refs/heads/master
iOS9Sampler/SampleViewControllers/SpringViewController.swift
mit
110
// // SpringViewController.swift // iOS9Sampler // // Created by Shuichi Tsutsumi on 9/13/15. // Copyright © 2015 Shuichi Tsutsumi. All rights reserved. // // Thanks to // http://qiita.com/kaway/items/b9e85403a4d78c11f8df import UIKit class SpringViewController: UIViewController { @IBOutlet weak var massSlider: UISlider! @IBOutlet weak var massLabel: UILabel! @IBOutlet weak var stiffnessSlider: UISlider! @IBOutlet weak var stiffnessLabel: UILabel! @IBOutlet weak var dampingSlider: UISlider! @IBOutlet weak var dampingLabel: UILabel! @IBOutlet weak var durationLabel: UILabel! @IBOutlet weak var animateBtn: UIButton! @IBOutlet weak var imageView: UIImageView! let animation = CASpringAnimation(keyPath: "position") override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) animation.initialVelocity = -5.0 animation.removedOnCompletion = false animation.fillMode = kCAFillModeForwards animation.delegate = self // update labels self.massChanged(massSlider) self.stiffnessChanged(stiffnessSlider) self.dampingChanged(dampingSlider) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let fromPos = CGPoint(x: CGRectGetMidX(view.bounds) + 100, y: imageView.center.y) let toPos = CGPoint(x: fromPos.x - 200, y: fromPos.y) animation.fromValue = NSValue(CGPoint: fromPos) animation.toValue = NSValue(CGPoint: toPos) imageView.center = fromPos } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func updateDurationLabel() { durationLabel.text = String(format: "settlingDuration:%.1f", animation.settlingDuration) } // ========================================================================= // MARK: - CAAnimation Delegate override func animationDidStop(anim: CAAnimation, finished flag: Bool) { print(__FUNCTION__+"\n") animateBtn.enabled = true } // ========================================================================= // MARK: - Actions @IBAction func massChanged(sender: UISlider) { massLabel.text = String(format: "%.1f", sender.value) animation.mass = CGFloat(sender.value) self.updateDurationLabel() } @IBAction func stiffnessChanged(sender: UISlider) { stiffnessLabel.text = String(format: "%.1f", sender.value) animation.stiffness = CGFloat(sender.value) self.updateDurationLabel() } @IBAction func dampingChanged(sender: UISlider) { dampingLabel.text = String(format: "%.1f", sender.value) animation.damping = CGFloat(sender.value) self.updateDurationLabel() } @IBAction func animateBtnTapped(sender: UIButton) { animateBtn.enabled = false animation.duration = animation.settlingDuration imageView.layer.addAnimation(animation, forKey: nil) } }
af515f7b66dd4d95fa47e1a0cc9c7a34
28.733945
96
0.62851
false
false
false
false
rvanmelle/LeetSwift
refs/heads/master
Problems.playground/Pages/Reverse Integer.xcplaygroundpage/Contents.swift
mit
1
//: hello /* https://leetcode.com/problems/reverse-integer/#/description Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows. */ import Foundation import XCTest //: [Next](@next) func reverse(_ x: Int) -> Int { guard x >= 0 else { return -reverse(abs(x)) } let s = x.description let charsReversed : [Character] = Array(s.characters).reversed() let sreversed = charsReversed.map { $0.description }.joined(separator:"") return Int(sreversed)! } XCTAssert( reverse(928374987234) == 432789473829 ) XCTAssert( reverse(-23412341423423123) == -32132432414321432 )
b209865863d84d28f1e4be579f69982a
23.03125
119
0.689207
false
false
false
false
GrandCentralBoard/GrandCentralBoard
refs/heads/develop
Pods/Operations/Sources/Features/Shared/Capability.swift
gpl-3.0
2
// // Capability.swift // Operations // // Created by Daniel Thorpe on 01/10/2015. // Copyright © 2015 Dan Thorpe. All rights reserved. // import Foundation /** # CapabilityType This is the high level definition for device/user/system capabilities which typically would require the user's permission to access. For example, location, calendars, photos, health kit etc. */ public protocol CapabilityType { /// A type which indicates the current status of the capability associatedtype Status: AuthorizationStatusType /// - returns: a String, the name of the capability var name: String { get } /** A requirement of the capability. This is generic, and it allows for granuality in the capabilities permissions. For example, with Location, we either request a "when in use" or "always" permission. - returns: the necessary Status.Requirement */ var requirement: Status.Requirement { get } /** Initialize a new capability with the requirement and a registrar. Implementations should provide a default registrar - it is here to support injection & unit testing. - parameter requirement: the needed Status.Requirement */ init(_ requirement: Status.Requirement) /** Query the capability to see if it's available on the device. - returns: true Bool value if the capability is available. */ func isAvailable() -> Bool /** Get the current authorization status of the capability. This can be performed asynchronously. The status is returns as the argument to a completion block. - parameter completion: a Status -> Void closure. */ func authorizationStatus(completion: Status -> Void) /** Request authorization with the requirement of the capability. Again, this is designed to be performed asynchronously. More than likely the registrar will present a dialog and wait for the user. When control is returned, the completion block should be called. - parameter completion: a dispatch_block_t closure. */ func requestAuthorizationWithCompletion(completion: dispatch_block_t) } /** A protocol to define the authorization status of a device capability. Typically this will be an enum, like CLAuthorizationStatus. Note that it is itself generic over the Requirement. This allows for another (or existing) enum to be used to define granular levels of permissions. Use Void if not needed. */ public protocol AuthorizationStatusType { /// A generic type for the requirement associatedtype Requirement /** Given the current authorization status (i.e. self) this function should determine whether or not the provided Requirement has been met or not. Therefore this function should consider the overall authorization state, and if *authorized* - whether the authorization is enough for the Requirement. - see: CLAuthorizationStatus extension for example. - parameter requirement: the necessary Requirement - returns: a Bool indicating whether or not the requirements are met. */ func isRequirementMet(requirement: Requirement) -> Bool } /** Protocol for the underlying capabiltiy registrar. */ public protocol CapabilityRegistrarType { /// The only requirement is that it can be initialized with /// no parameters. init() } /** Capability is a namespace to nest as aliases the various device capability types. */ public struct Capability { } extension Capability { /** Some device capabilities might not have the need for an authorization level, but still might not be available. For example PassKit. In which case, use VoidStatus as the nested Status type. */ public struct VoidStatus: AuthorizationStatusType { /// - returns: true, VoidStatus cannot fail to meet requirements. public func isRequirementMet(requirement: Void) -> Bool { return true } } } /** # Get Authorization Status Operation This is a generic operation which will get the current authorization status for any CapabilityType. */ public class GetAuthorizationStatus<Capability: CapabilityType>: Operation { /// the StatusResponse is a tuple for the capabilities availability and status public typealias StatusResponse = (Bool, Capability.Status) /// the Completion is a closure which receives a StatusResponse public typealias Completion = StatusResponse -> Void /** After the operation has executed, this property will be set either true or false. - returns: a Bool indicating whether or not the capability is available. */ public var isAvailable: Bool? = .None /** After the operation has executed, this property will be set to the current status of the capability. - returns: a StatusResponse of the current status. */ public var status: Capability.Status? = .None let capability: Capability let completion: Completion /** Initialize the operation with a CapabilityType and completion. A default completion is set which does nothing. The status is also available using properties. - parameter capability: the Capability. - parameter completion: the Completion closure. */ public init(_ capability: Capability, completion: Completion = { _ in }) { self.capability = capability self.completion = completion super.init() name = "Get Authorization Status for \(capability.name)" } func determineState(completion: StatusResponse -> Void) { isAvailable = capability.isAvailable() capability.authorizationStatus { status in self.status = status completion((self.isAvailable!, self.status!)) } } /// The execute function required by Operation public override func execute() { determineState { response in self.completion(response) self.finish() } } } /** # Authorize Operation This is a generic operation which will request authorization for any CapabilityType. */ public class Authorize<Capability: CapabilityType>: GetAuthorizationStatus<Capability> { /** Initialize the operation with a CapabilityType and completion. A default completion is set which does nothing. The status is also available using properties. - parameter capability: the Capability. - parameter completion: the Completion closure. */ public override init(_ capability: Capability, completion: Completion = { _ in }) { super.init(capability, completion: completion) name = "Authorize \(capability.name).\(capability.requirement)" addCondition(MutuallyExclusive<Capability>()) } /// The execute function required by Operation public override func execute() { capability.requestAuthorizationWithCompletion { super.execute() } } } /** An generic ErrorType used by the AuthorizedFor condition. */ public enum CapabilityError<Capability: CapabilityType>: ErrorType { /// If the capability is not available case NotAvailable /// If authorization for the capability was not granted. case AuthorizationNotGranted((Capability.Status, Capability.Status.Requirement?)) } /** This is a generic OperationCondition which can be used to allow or deny operations to execute depending on the authorization status of a capability. By default, the condition will add an Authorize operation as a dependency which means that potentially the user will be prompted to grant authorization. Suppress this from happening with SilentCondition. */ public struct AuthorizedFor<Capability: CapabilityType>: OperationCondition { /// - returns: a String, the name of the condition public let name: String /// - returns: false, is not mutually exclusive public let isMutuallyExclusive = false let capability: Capability /** Initialize the condition using a capability. For example ```swift let myOperation = MyOperation() // etc etc // Present the user with a permission dialog only if the authorization // status has not yet been determined. // If previously granted - operation will be executed with no dialog. // If previously denied - operation will fail with // CapabilityError<Capability.Location>.AuthorizationNotGranted myOperation.addCondition(AuthorizedFor(Capability.Location(.WhenInUse))) ``` - parameter capability: the Capability. */ public init(_ capability: Capability) { self.capability = capability self.name = capability.name } /// Returns an Authorize operation as a dependency public func dependencyForOperation(operation: Operation) -> NSOperation? { return Authorize(capability) } /// Evaluated the condition public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) { if !capability.isAvailable() { completion(.Failed(CapabilityError<Capability>.NotAvailable)) } else { capability.authorizationStatus { [requirement = self.capability.requirement] status in if status.isRequirementMet(requirement) { completion(.Satisfied) } else { completion(.Failed(CapabilityError<Capability>.AuthorizationNotGranted((status, requirement)))) } } } } } extension Capability.VoidStatus: Equatable { } /// Equality check for Capability.VoidStatus public func == (_: Capability.VoidStatus, _: Capability.VoidStatus) -> Bool { return true }
030fb6d208594fb404e6aa92df95ed5c
29.779874
115
0.697998
false
false
false
false
mgingras/garagr
refs/heads/master
garagrIOS/ViewController.swift
mit
1
// // ViewController.swift // garagrIOS // // Created by Martin Gingras on 2014-12-01. // Copyright (c) 2014 mgingras. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var formUsername: UITextField! @IBOutlet weak var formPassword: UITextField! @IBOutlet weak var feedback: UILabel! var userId: NSNumber? var username: NSString? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func validateUsernameAndPassword(){ if formUsername.hasText() && formPassword.hasText() { getUserInfo(formUsername.text, formPassword: formPassword.text, handleFormInput) } } func handleFormInput(isValid: Bool){ if(isValid){ self.performSegueWithIdentifier("moveToUserViewSegue", sender: self) } } func getUserInfo(formUsername: String, formPassword: String, callback: (Bool)-> Void){ let url = NSURL(string: "http://localhost:3000/login?username=" + formUsername + "&password=" + formPassword) var request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST" let task = NSURLSession.sharedSession().dataTaskWithRequest(request){(data, response, error) in println(NSString(data: data, encoding: NSUTF8StringEncoding)) var err: NSError? var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary if (err != nil) { println("JSON Error \(err!.localizedDescription)") } let status: String! = jsonResult["status"] as NSString if status != "ok" { let message: String! = jsonResult["message"] as NSString NSOperationQueue.mainQueue().addOperationWithBlock(){ self.feedback.text = message callback(false) } } else{ NSOperationQueue.mainQueue().addOperationWithBlock(){ self.userId = jsonResult["userId"] as? NSNumber self.username = formUsername callback(true) } } } task.resume() } @IBAction func showSignUpAlert(){ showAlert("Enter details below") } func showAlert(message :NSString){ var alert = UIAlertController(title: "Create new account", message: message, preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in textField.placeholder = "Username" }) alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in textField.placeholder = "Password" textField.secureTextEntry = true }) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel){ UIAlertAction in }) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in let desiredUsername = alert.textFields![0] as UITextField let desiredPassword = alert.textFields![1] as UITextField if !desiredPassword.hasText() || !desiredUsername.hasText() { self.showAlert("Please enter your desired Username and Password") }else{ var url = NSURL(string: "http://localhost:3000/users?username=" + desiredUsername.text + "&password=" + desiredPassword.text) var request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST" let task = NSURLSession.sharedSession().dataTaskWithRequest(request){(data, response, error) in println(NSString(data: data, encoding: NSUTF8StringEncoding)) var err: NSError? var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary if (err != nil) { println("JSON Error \(err!.localizedDescription)") } let status: String! = jsonResult["status"] as NSString if status != "ok" { let message: String! = jsonResult["message"] as NSString self.showAlert(message) }else{ self.userId = jsonResult["userId"] as? NSNumber NSOperationQueue.mainQueue().addOperationWithBlock(){ self.formUsername.text = desiredUsername.text } } } task.resume() } })) self.presentViewController(alert, animated: true, completion: nil) } override func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!) { if segue.identifier == "moveToUserViewSegue" { let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate appDelegate.userId = self.userId appDelegate.username = self.username } } }
5294819f54bfe1b8c2ec676b30d686e4
38.624113
159
0.578844
false
false
false
false
artsy/eigen
refs/heads/main
ios/Artsy/Views/Core/TextStack.swift
mit
1
import UIKit class TextStack: ORStackView { @discardableResult func addArtistName(_ string: String) -> UILabel { let artistNameLabel = UILabel() artistNameLabel.text = string artistNameLabel.font = UIFont.serifSemiBoldFont(withSize: 16) addSubview(artistNameLabel, withTopMargin: "0", sideMargin: "0") return artistNameLabel } @discardableResult func addArtworkName(_ string: String, date: String?) -> ARArtworkTitleLabel { let title = ARArtworkTitleLabel() title.setTitle(string, date: date) addSubview(title, withTopMargin: "4", sideMargin: "0") return title } @discardableResult func addSmallHeading(_ string: String, sideMargin: String = "0") -> UILabel { let heading = ARSansSerifLabel() heading.font = .sansSerifFont(withSize: 12) heading.text = string addSubview(heading, withTopMargin: "10", sideMargin: sideMargin) return heading } @discardableResult func addBigHeading(_ string: String, sideMargin: String = "0") -> UILabel { let heading = ARSerifLabel() heading.font = .serifFont(withSize: 26) heading.text = string addSubview(heading, withTopMargin: "20", sideMargin:sideMargin) return heading } @discardableResult func addSmallLineBreak(_ sideMargin: String = "0") -> UIView { let line = UIView() line.backgroundColor = .artsyGrayRegular() addSubview(line, withTopMargin: "20", sideMargin: sideMargin) line.constrainHeight("1") return line } @discardableResult func addThickLineBreak(_ sideMargin: String = "0") -> UIView { let line = UIView() line.backgroundColor = .black addSubview(line, withTopMargin: "20", sideMargin: sideMargin) line.constrainHeight("2") return line } @discardableResult func addBodyText(_ string: String, topMargin: String = "20", sideMargin: String = "0") -> UILabel { let serif = ARSerifLabel() serif.font = .serifFont(withSize: 16) serif.numberOfLines = 0 serif.text = string addSubview(serif, withTopMargin: topMargin, sideMargin: sideMargin) return serif } @discardableResult func addBodyMarkdown(_ string: MarkdownString, topMargin: String = "20", sideMargin: String = "0") -> ARTextView { let text = ARTextView() text.plainLinks = true text.setMarkdownString(string) addSubview(text, withTopMargin: topMargin, sideMargin: sideMargin) return text } @discardableResult func addLinkedBodyMarkdown(_ string: MarkdownString, topMargin: String = "20", sideMargin: String = "0") -> ARTextView { let text = ARTextView() text.setMarkdownString(string) addSubview(text, withTopMargin: topMargin, sideMargin: sideMargin) return text } }
5a5b291146eef5a0c8a109948289c634
34.421687
124
0.647959
false
false
false
false
breadwallet/breadwallet-ios
refs/heads/master
breadwallet/src/Constants/Constants.swift
mit
1
// // Constants.swift // breadwallet // // Created by Adrian Corscadden on 2016-10-24. // Copyright © 2016-2019 Breadwinner AG. All rights reserved. // import UIKit import WalletKit let π: CGFloat = .pi struct Padding { var increment: CGFloat subscript(multiplier: Int) -> CGFloat { return CGFloat(multiplier) * increment } static var half: CGFloat { return C.padding[1]/2.0 } } // swiftlint:disable type_name /// Constants struct C { static let padding = Padding(increment: 8.0) struct Sizes { static let buttonHeight: CGFloat = 48.0 static let headerHeight: CGFloat = 48.0 static let largeHeaderHeight: CGFloat = 220.0 static let logoAspectRatio: CGFloat = 125.0/417.0 static let cutoutLogoAspectRatio: CGFloat = 342.0/553.0 static let roundedCornerRadius: CGFloat = 6.0 static let homeCellCornerRadius: CGFloat = 6.0 static let brdLogoHeight: CGFloat = 32.0 static let brdLogoTopMargin: CGFloat = E.isIPhoneX ? C.padding[9] + 35.0 : C.padding[9] + 20.0 } static var defaultTintColor: UIColor = { return UIView().tintColor }() static let animationDuration: TimeInterval = 0.3 static let secondsInDay: TimeInterval = 86400 static let secondsInMinute: TimeInterval = 60 static let maxMoney: UInt64 = 21000000*100000000 static let satoshis: UInt64 = 100000000 static let walletQueue = "com.breadwallet.walletqueue" static let null = "(null)" static let maxMemoLength = 250 static let feedbackEmail = "[email protected]" static let iosEmail = "[email protected]" static let reviewLink = "https://itunes.apple.com/app/breadwallet-bitcoin-wallet/id885251393?action=write-review" static var standardPort: Int { return E.isTestnet ? 18333 : 8333 } static let bip39CreationTime = TimeInterval(1388534400) - NSTimeIntervalSince1970 static let bCashForkBlockHeight: UInt32 = E.isTestnet ? 1155876 : 478559 static let bCashForkTimeStamp: TimeInterval = E.isTestnet ? (1501597117 - NSTimeIntervalSince1970) : (1501568580 - NSTimeIntervalSince1970) static let txUnconfirmedHeight = Int32.max /// Path where core library stores its persistent data static var coreDataDirURL: URL { let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! return documentsURL.appendingPathComponent("core-data", isDirectory: true) } static let consoleLogFileName = "log.txt" static let previousConsoleLogFileName = "previouslog.txt" // Returns the console log file path for the current instantiation of the app. static var logFilePath: URL { let cachesURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! return cachesURL.appendingPathComponent(consoleLogFileName) } // Returns the console log file path for the previous instantiation of the app. static var previousLogFilePath: URL { let cachesURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! return cachesURL.appendingPathComponent(previousConsoleLogFileName) } static let usdCurrencyCode = "USD" static let euroCurrencyCode = "EUR" static let britishPoundCurrencyCode = "GBP" static let danishKroneCurrencyCode = "DKK" static let erc20Prefix = "erc20:" static var backendHost: String { if let debugBackendHost = UserDefaults.debugBackendHost { return debugBackendHost } else { return (E.isDebug || E.isTestFlight) ? "stage2.breadwallet.com" : "api.breadwallet.com" } } static var webBundle: String { if let debugWebBundle = UserDefaults.debugWebBundleName { return debugWebBundle } else { // names should match AssetBundles.plist return (E.isDebug || E.isTestFlight) ? "brd-web-3-staging" : "brd-web-3" } } static var bdbHost: String { return "api.blockset.com" } static let bdbClientTokenRecordId = "BlockchainDBClientID" static let daiContractAddress = "0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359" static let daiContractCode = "DAI" static let tusdContractAddress = "0x0000000000085d4780B73119b644AE5ecd22b376" static let tusdContractCode = "TUSD" static let fixerAPITokenRecordId = "FixerAPIToken" } enum Words { //Returns the wordlist of the current localization static var wordList: [NSString]? { guard let path = Bundle.main.path(forResource: "BIP39Words", ofType: "plist") else { return nil } return NSArray(contentsOfFile: path) as? [NSString] } //Returns the wordlist that matches to localization of the phrase static func wordList(forPhrase phrase: String) -> [NSString]? { var result = [NSString]() Bundle.main.localizations.forEach { lang in if let path = Bundle.main.path(forResource: "BIP39Words", ofType: "plist", inDirectory: nil, forLocalization: lang) { if let words = NSArray(contentsOfFile: path) as? [NSString], Account.validatePhrase(phrase, words: words.map { String($0) }) { result = words } } } return result } }
12c4ce98bdc80639ed80e8afc47e3b2b
36.922535
143
0.676695
false
false
false
false
1d4Nf6/RazzleDazzle
refs/heads/develop
Carthage/Checkouts/Nimble/Nimble/Matchers/BeEmpty.swift
apache-2.0
45
import Foundation /// A Nimble matcher that succeeds when a value is "empty". For collections, this /// means the are no items in that collection. For strings, it is an empty string. public func beEmpty<S: SequenceType>() -> NonNilMatcherFunc<S> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be empty" let actualSeq = actualExpression.evaluate() if actualSeq == nil { return true } var generator = actualSeq!.generate() return generator.next() == nil } } /// A Nimble matcher that succeeds when a value is "empty". For collections, this /// means the are no items in that collection. For strings, it is an empty string. public func beEmpty() -> NonNilMatcherFunc<String> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be empty" let actualString = actualExpression.evaluate() return actualString == nil || (actualString! as NSString).length == 0 } } /// A Nimble matcher that succeeds when a value is "empty". For collections, this /// means the are no items in that collection. For NSString instances, it is an empty string. public func beEmpty() -> NonNilMatcherFunc<NSString> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be empty" let actualString = actualExpression.evaluate() return actualString == nil || actualString!.length == 0 } } // Without specific overrides, beEmpty() is ambiguous for NSDictionary, NSArray, // etc, since they conform to SequenceType as well as NMBCollection. /// A Nimble matcher that succeeds when a value is "empty". For collections, this /// means the are no items in that collection. For strings, it is an empty string. public func beEmpty() -> NonNilMatcherFunc<NSDictionary> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be empty" let actualDictionary = actualExpression.evaluate() return actualDictionary == nil || actualDictionary!.count == 0 } } /// A Nimble matcher that succeeds when a value is "empty". For collections, this /// means the are no items in that collection. For strings, it is an empty string. public func beEmpty() -> NonNilMatcherFunc<NSArray> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be empty" let actualArray = actualExpression.evaluate() return actualArray == nil || actualArray!.count == 0 } } /// A Nimble matcher that succeeds when a value is "empty". For collections, this /// means the are no items in that collection. For strings, it is an empty string. public func beEmpty() -> NonNilMatcherFunc<NMBCollection> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be empty" let actual = actualExpression.evaluate() return actual == nil || actual!.count == 0 } } extension NMBObjCMatcher { public class func beEmptyMatcher() -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let location = actualExpression.location let actualValue = actualExpression.evaluate() failureMessage.postfixMessage = "be empty" if let value = actualValue as? NMBCollection { let expr = Expression(expression: ({ value as NMBCollection }), location: location) return beEmpty().matches(expr, failureMessage: failureMessage) } else if let value = actualValue as? NSString { let expr = Expression(expression: ({ value as String }), location: location) return beEmpty().matches(expr, failureMessage: failureMessage) } else if let actualValue = actualValue { failureMessage.postfixMessage = "be empty (only works for NSArrays, NSSets, NSDictionaries, NSHashTables, and NSStrings)" failureMessage.actualValue = "\(NSStringFromClass(actualValue.dynamicType)) type" } return false } } }
e9ac752f0dd4cb26ced9cef2f93c12c5
45.544444
137
0.699212
false
false
false
false
xmkevinchen/CKMessagesKit
refs/heads/master
CKMessagesKit/Sources/Factories/CKMessagesAvatarImageFactory.swift
mit
1
// // CKMessagesAvatarImageFactory.swift // CKMessagesKit // // Created by Kevin Chen on 9/2/16. // Copyright © 2016 Kevin Chen. All rights reserved. // import Foundation public class CKMessagesAvatarImageFactory { private let diameter: UInt public init(diameter: UInt = 30) { self.diameter = diameter } public func avatar(placeholder: UIImage) -> CKMessagesAvatarImage { let image = placeholder.circular(diameter: diameter) return CKMessagesAvatarImage.avater(placeholder: image) } public func avatar(image: UIImage) -> CKMessagesAvatarImage { let normal = image.circular(diameter: diameter) let highlighted = image.circular(diameter: diameter, highlighted: UIColor(white: 0.1, alpha: 0.3)) return CKMessagesAvatarImage(avatar: normal, highlighted: highlighted, placeholder: normal) } public func avatar(initials: String, backgroundColor: UIColor, textColor: UIColor, font: UIFont) -> CKMessagesAvatarImage { let image = self.image(initials: initials, backgroundColor: backgroundColor, textColor: textColor, font: font) let normal = image.circular(diameter: diameter) let highlighted = image.circular(diameter: diameter, highlighted: UIColor(white: 0.1, alpha: 0.3)) return CKMessagesAvatarImage(avatar: normal, highlighted: highlighted, placeholder: normal) } private func image(initials: String, backgroundColor: UIColor, textColor: UIColor, font: UIFont) -> UIImage { let frame = CGRect(x: 0, y: 0, width: Int(diameter), height: Int(diameter)) let attributes = [ NSFontAttributeName: font, NSForegroundColorAttributeName: textColor ] let textFrame = NSString(string: initials).boundingRect(with: frame.size, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil) let dx = frame.midX - textFrame.midX let dy = frame.midY - textFrame.midY let drawPoint = CGPoint(x: dx, y: dy) UIGraphicsBeginImageContextWithOptions(frame.size, false, 0) let context = UIGraphicsGetCurrentContext()! context.setFillColor(backgroundColor.cgColor) context.fill(frame) NSString(string: initials).draw(at: drawPoint, withAttributes: attributes) let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } }
f53fcea6ed691599fddc0b415529affc
37.472222
127
0.618051
false
false
false
false
mrgerych/Cuckoo
refs/heads/master
Generator/Source/CuckooGeneratorFramework/Tokens/Key.swift
mit
1
// // Key.swift // CuckooGenerator // // Created by Filip Dolnik on 30.05.16. // Copyright © 2016 Brightify. All rights reserved. // public enum Key: String { case Substructure = "key.substructure" case Kind = "key.kind" case Accessibility = "key.accessibility" case SetterAccessibility = "key.setter_accessibility" case Name = "key.name" case TypeName = "key.typename" case InheritedTypes = "key.inheritedtypes" case Length = "key.length" case Offset = "key.offset" case NameLength = "key.namelength" case NameOffset = "key.nameoffset" case BodyLength = "key.bodylength" case BodyOffset = "key.bodyoffset" }
8ab63ff26e26ec4bbda40acc88984bc5
25.038462
57
0.667651
false
false
false
false
wordpress-mobile/AztecEditor-iOS
refs/heads/develop
Example/Example/MediaInserter.swift
gpl-2.0
2
import Foundation import UIKit import Aztec import AVFoundation class MediaInserter { fileprivate var mediaErrorMode = false struct MediaProgressKey { static let mediaID = ProgressUserInfoKey("mediaID") static let videoURL = ProgressUserInfoKey("videoURL") } let richTextView: TextView var attachmentTextAttributes: [NSAttributedString.Key: Any] init(textView: TextView, attachmentTextAttributes: [NSAttributedString.Key: Any]) { self.richTextView = textView self.attachmentTextAttributes = attachmentTextAttributes } func insertImage(_ image: UIImage) { let fileURL = image.saveToTemporaryFile() let attachment = richTextView.replaceWithImage(at: richTextView.selectedRange, sourceURL: fileURL, placeHolderImage: image) attachment.size = .full attachment.alignment = ImageAttachment.Alignment.none if let attachmentRange = richTextView.textStorage.ranges(forAttachment: attachment).first { richTextView.setLink(fileURL, inRange: attachmentRange) } let imageID = attachment.identifier let progress = Progress(parent: nil, userInfo: [MediaProgressKey.mediaID: imageID]) progress.totalUnitCount = 100 Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(MediaInserter.timerFireMethod(_:)), userInfo: progress, repeats: true) } func insertVideo(_ videoURL: URL) { let asset = AVURLAsset(url: videoURL, options: nil) let imgGenerator = AVAssetImageGenerator(asset: asset) imgGenerator.appliesPreferredTrackTransform = true guard let cgImage = try? imgGenerator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil) else { return } let posterImage = UIImage(cgImage: cgImage) let posterURL = posterImage.saveToTemporaryFile() let attachment = richTextView.replaceWithVideo(at: richTextView.selectedRange, sourceURL: URL(string:"placeholder://")!, posterURL: posterURL, placeHolderImage: posterImage) let mediaID = attachment.identifier let progress = Progress(parent: nil, userInfo: [MediaProgressKey.mediaID: mediaID, MediaProgressKey.videoURL:videoURL]) progress.totalUnitCount = 100 Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(MediaInserter.timerFireMethod(_:)), userInfo: progress, repeats: true) } @objc func timerFireMethod(_ timer: Timer) { guard let progress = timer.userInfo as? Progress, let imageId = progress.userInfo[MediaProgressKey.mediaID] as? String, let attachment = richTextView.attachment(withId: imageId) else { timer.invalidate() return } progress.completedUnitCount += 1 attachment.progress = progress.fractionCompleted if mediaErrorMode && progress.fractionCompleted >= 0.25 { timer.invalidate() let message = NSAttributedString(string: "Upload failed!", attributes: attachmentTextAttributes) attachment.message = message attachment.overlayImage = UIImage.systemImage("arrow.clockwise") } if progress.fractionCompleted >= 1 { timer.invalidate() attachment.progress = nil if let videoAttachment = attachment as? VideoAttachment, let videoURL = progress.userInfo[MediaProgressKey.videoURL] as? URL { videoAttachment.updateURL(videoURL, refreshAsset: false) } } richTextView.refresh(attachment, overlayUpdateOnly: true) } }
c4feaceb973c0c0d0bc2cddc8611620c
41.964706
181
0.68839
false
false
false
false
See-Ku/SK4Toolkit
refs/heads/master
SK4ToolkitTests/StringExtensionTests.swift
mit
1
// // StringExtensionTests.swift // SK4Toolkit // // Created by See.Ku on 2016/03/30. // Copyright (c) 2016 AxeRoad. All rights reserved. // import XCTest import SK4Toolkit class StringExtensionTests: XCTestCase { func testString() { let base = "12345678" // ///////////////////////////////////////////////////////////// // sk4SubstringToIndex // 先頭から4文字を取得 XCTAssert(base.sk4SubstringToIndex(4) == "1234") // 先頭から0文字を取得 = "" XCTAssert(base.sk4SubstringToIndex(0) == "") // 文字列の長さを超えた場合、全体を返す XCTAssert(base.sk4SubstringToIndex(12) == "12345678") // 先頭より前を指定された場合、""を返す XCTAssert(base.sk4SubstringToIndex(-4) == "") // ///////////////////////////////////////////////////////////// // sk4SubstringFromIndex // 4文字目以降を取得 XCTAssert(base.sk4SubstringFromIndex(4) == "5678") // 0文字目以降をを取得 XCTAssert(base.sk4SubstringFromIndex(0) == "12345678") // 文字列の長さを超えた場合""を返す XCTAssert(base.sk4SubstringFromIndex(12) == "") // 先頭より前を指定された場合、全体を返す XCTAssert(base.sk4SubstringFromIndex(-4) == "12345678") // ///////////////////////////////////////////////////////////// // sk4SubstringWithRange // 2文字目から6文字目までを取得 XCTAssert(base.sk4SubstringWithRange(start: 2, end: 6) == "3456") // 0文字目から4文字目までを取得 XCTAssert(base.sk4SubstringWithRange(start: 0, end: 4) == "1234") // 4文字目から8文字目までを取得 XCTAssert(base.sk4SubstringWithRange(start: 4, end: 8) == "5678") // 範囲外の指定は範囲内に丸める XCTAssert(base.sk4SubstringWithRange(start: -2, end: 3) == "123") XCTAssert(base.sk4SubstringWithRange(start: 5, end: 12) == "678") XCTAssert(base.sk4SubstringWithRange(start: -3, end: 15) == "12345678") // Rangeでの指定も可能 XCTAssert(base.sk4SubstringWithRange(1 ..< 4) == "234") // ///////////////////////////////////////////////////////////// // sk4TrimSpace // 文字列の前後から空白文字を取り除く XCTAssert(" abc def\n ".sk4TrimSpace() == "abc def\n") // 文字列の前後から空白文字と改行を取り除く XCTAssert(" abc def\n ".sk4TrimSpaceNL() == "abc def") // 全角空白も対応 XCTAssert("  どうかな?  ".sk4TrimSpaceNL() == "どうかな?") // 何も残らない場合は""になる XCTAssert(" \n \n ".sk4TrimSpaceNL() == "") XCTAssert("".sk4TrimSpaceNL() == "") } func testConvert() { let str = "1234" // utf8エンコードでNSDataに変換 if let data = str.sk4ToNSData() { // println(data1) XCTAssert(data.description == "<31323334>") } else { XCTFail("Fail") } // Base64をデコードしてNSDataに変換 if let data = str.sk4Base64Decode() { // println(data2) XCTAssert(data.description == "<d76df8>") } else { XCTFail("Fail") } let empty = "" // utf8エンコードでNSDataに変換 if let data = empty.sk4ToNSData() { XCTAssert(data.length == 0) } else { XCTFail("Fail") } // Base64をデコードしてNSDataに変換 if let data = empty.sk4Base64Decode() { XCTAssert(data.length == 0) } else { XCTFail("Fail") } } } // eof
0324ce3ec2f26e8ca01175c33dd32072
22.04878
73
0.595767
false
false
false
false
vapor/vapor
refs/heads/main
Sources/Vapor/Concurrency/FileIO+Concurrency.swift
mit
1
#if compiler(>=5.5) && canImport(_Concurrency) import NIOCore @available(macOS 12, iOS 15, watchOS 8, tvOS 15, *) extension FileIO { /// Reads the contents of a file at the supplied path. /// /// let data = try await req.fileio().read(file: "/path/to/file.txt") /// print(data) // file data /// /// - parameters: /// - path: Path to file on the disk. /// - returns: `ByteBuffer` containing the file data. public func collectFile(at path: String) async throws -> ByteBuffer { return try await self.collectFile(at: path).get() } /// Reads the contents of a file at the supplied path in chunks. /// /// try await req.fileio().readChunked(file: "/path/to/file.txt") { chunk in /// print("chunk: \(data)") /// } /// /// - parameters: /// - path: Path to file on the disk. /// - chunkSize: Maximum size for the file data chunks. /// - onRead: Closure to be called sequentially for each file data chunk. /// - returns: `Void` when the file read is finished. // public func readFile(at path: String, chunkSize: Int = NonBlockingFileIO.defaultChunkSize, onRead: @escaping (ByteBuffer) async throws -> Void) async throws { // // TODO // // We should probably convert the internal private read function to async as well rather than wrapping it at this top level // let promise = self.request.eventLoop.makePromise(of: Void.self) // promise.completeWithTask { // try await onRead // } // let closureFuture = promise.futureResult // return try self.readFile(at: path, onRead: closureFuture).get() // } /// Write the contents of buffer to a file at the supplied path. /// /// let data = ByteBuffer(string: "ByteBuffer") /// try await req.fileio.writeFile(data, at: "/path/to/file.txt") /// /// - parameters: /// - path: Path to file on the disk. /// - buffer: The `ByteBuffer` to write. /// - returns: `Void` when the file write is finished. public func writeFile(_ buffer: ByteBuffer, at path: String) async throws { return try await self.writeFile(buffer, at: path).get() } } #endif
b72e003d094c98679730577f9913418f
41.603774
165
0.60496
false
false
false
false
kesun421/firefox-ios
refs/heads/master
Client/Frontend/Browser/BrowserViewController.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Photos import UIKit import WebKit import Shared import Storage import SnapKit import XCGLogger import Alamofire import Account import ReadingList import MobileCoreServices import SDWebImage import SwiftyJSON import Telemetry import Sentry private let KVOLoading = "loading" private let KVOEstimatedProgress = "estimatedProgress" private let KVOURL = "URL" private let KVOTitle = "title" private let KVOCanGoBack = "canGoBack" private let KVOCanGoForward = "canGoForward" private let KVOContentSize = "contentSize" private let ActionSheetTitleMaxLength = 120 private struct BrowserViewControllerUX { fileprivate static let BackgroundColor = UIConstants.AppBackgroundColor fileprivate static let ShowHeaderTapAreaHeight: CGFloat = 32 fileprivate static let BookmarkStarAnimationDuration: Double = 0.5 fileprivate static let BookmarkStarAnimationOffset: CGFloat = 80 } class BrowserViewController: UIViewController { var homePanelController: HomePanelViewController? var webViewContainer: UIView! var urlBar: URLBarView! var clipboardBarDisplayHandler: ClipboardBarDisplayHandler? var readerModeBar: ReaderModeBarView? var readerModeCache: ReaderModeCache let webViewContainerToolbar = UIView() var statusBarOverlay: UIView! fileprivate(set) var toolbar: TabToolbar? fileprivate var searchController: SearchViewController? fileprivate var screenshotHelper: ScreenshotHelper! fileprivate var homePanelIsInline = false fileprivate var searchLoader: SearchLoader! fileprivate let snackBars = UIView() fileprivate var findInPageBar: FindInPageBar? fileprivate let findInPageContainer = UIView() lazy var mailtoLinkHandler: MailtoLinkHandler = MailtoLinkHandler() lazy fileprivate var customSearchEngineButton: UIButton = { let searchButton = UIButton() searchButton.setImage(UIImage(named: "AddSearch")?.withRenderingMode(.alwaysTemplate), for: UIControlState()) searchButton.addTarget(self, action: #selector(BrowserViewController.addCustomSearchEngineForFocusedElement), for: .touchUpInside) searchButton.accessibilityIdentifier = "BrowserViewController.customSearchEngineButton" return searchButton }() fileprivate var customSearchBarButton: UIBarButtonItem? // popover rotation handling fileprivate var displayedPopoverController: UIViewController? fileprivate var updateDisplayedPopoverProperties: (() -> Void)? var openInHelper: OpenInHelper? // location label actions fileprivate var pasteGoAction: AccessibleAction! fileprivate var pasteAction: AccessibleAction! fileprivate var copyAddressAction: AccessibleAction! fileprivate weak var tabTrayController: TabTrayController! let profile: Profile let tabManager: TabManager // These views wrap the urlbar and toolbar to provide background effects on them var header: UIView! var footer: UIView! fileprivate var topTouchArea: UIButton! let urlBarTopTabsContainer = UIView(frame: CGRect.zero) var topTabsVisible: Bool { return topTabsViewController != nil } // Backdrop used for displaying greyed background for private tabs var webViewContainerBackdrop: UIView! var scrollController = TabScrollingController() fileprivate var keyboardState: KeyboardState? var didRemoveAllTabs: Bool = false var pendingToast: ButtonToast? // A toast that might be waiting for BVC to appear before displaying let WhiteListedUrls = ["\\/\\/itunes\\.apple\\.com\\/"] // Tracking navigation items to record history types. // TODO: weak references? var ignoredNavigation = Set<WKNavigation>() var typedNavigation = [WKNavigation: VisitType]() var navigationToolbar: TabToolbarProtocol { return toolbar ?? urlBar } var topTabsViewController: TopTabsViewController? let topTabsContainer = UIView(frame: CGRect.zero) init(profile: Profile, tabManager: TabManager) { self.profile = profile self.tabManager = tabManager self.readerModeCache = DiskReaderModeCache.sharedInstance super.init(nibName: nil, bundle: nil) didInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return UIInterfaceOrientationMask.allButUpsideDown } else { return UIInterfaceOrientationMask.all } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) displayedPopoverController?.dismiss(animated: true) { self.displayedPopoverController = nil } if let _ = self.presentedViewController as? PhotonActionSheet { self.presentedViewController?.dismiss(animated: true, completion: nil) } coordinator.animate(alongsideTransition: { context in self.scrollController.updateMinimumZoom() self.topTabsViewController?.scrollToCurrentTab(false, centerCell: false) if let popover = self.displayedPopoverController { self.updateDisplayedPopoverProperties?() self.present(popover, animated: true, completion: nil) } }, completion: { _ in self.scrollController.setMinimumZoom() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } fileprivate func didInit() { screenshotHelper = ScreenshotHelper(controller: self) tabManager.addDelegate(self) tabManager.addNavigationDelegate(self) } override var preferredStatusBarStyle: UIStatusBarStyle { let isPrivate = tabManager.selectedTab?.isPrivate ?? false let isIpad = shouldShowTopTabsForTraitCollection(traitCollection) return (isPrivate || isIpad) ? UIStatusBarStyle.lightContent : UIStatusBarStyle.default } func shouldShowFooterForTraitCollection(_ previousTraitCollection: UITraitCollection) -> Bool { return previousTraitCollection.verticalSizeClass != .compact && previousTraitCollection.horizontalSizeClass != .regular } func shouldShowTopTabsForTraitCollection(_ newTraitCollection: UITraitCollection) -> Bool { return newTraitCollection.verticalSizeClass == .regular && newTraitCollection.horizontalSizeClass == .regular } func toggleSnackBarVisibility(show: Bool) { if show { UIView.animate(withDuration: 0.1, animations: { self.snackBars.isHidden = false }) } else { snackBars.isHidden = true } } fileprivate func updateToolbarStateForTraitCollection(_ newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator? = nil) { let showToolbar = shouldShowFooterForTraitCollection(newCollection) let showTopTabs = shouldShowTopTabsForTraitCollection(newCollection) urlBar.topTabsIsShowing = showTopTabs urlBar.setShowToolbar(!showToolbar) toolbar?.removeFromSuperview() toolbar?.tabToolbarDelegate = nil toolbar = nil if showToolbar { toolbar = TabToolbar() footer.addSubview(toolbar!) toolbar?.tabToolbarDelegate = self let theme = (tabManager.selectedTab?.isPrivate ?? false) ? Theme.PrivateMode : Theme.NormalMode toolbar?.applyTheme(theme) updateTabCountUsingTabManager(self.tabManager) } if showTopTabs { if topTabsViewController == nil { let topTabsViewController = TopTabsViewController(tabManager: tabManager) topTabsViewController.delegate = self addChildViewController(topTabsViewController) topTabsViewController.view.frame = topTabsContainer.frame topTabsContainer.addSubview(topTabsViewController.view) topTabsViewController.view.snp.makeConstraints { make in make.edges.equalTo(topTabsContainer) make.height.equalTo(TopTabsUX.TopTabsViewHeight) } self.topTabsViewController = topTabsViewController } topTabsContainer.snp.updateConstraints { make in make.height.equalTo(TopTabsUX.TopTabsViewHeight) } } else { topTabsContainer.snp.updateConstraints { make in make.height.equalTo(0) } topTabsViewController?.view.removeFromSuperview() topTabsViewController?.removeFromParentViewController() topTabsViewController = nil } view.setNeedsUpdateConstraints() if let home = homePanelController { home.view.setNeedsUpdateConstraints() } if let tab = tabManager.selectedTab, let webView = tab.webView { updateURLBarDisplayURL(tab) navigationToolbar.updateBackStatus(webView.canGoBack) navigationToolbar.updateForwardStatus(webView.canGoForward) navigationToolbar.updateReloadStatus(tab.loading) } } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { super.willTransition(to: newCollection, with: coordinator) // During split screen launching on iPad, this callback gets fired before viewDidLoad gets a chance to // set things up. Make sure to only update the toolbar state if the view is ready for it. if isViewLoaded { updateToolbarStateForTraitCollection(newCollection, withTransitionCoordinator: coordinator) } displayedPopoverController?.dismiss(animated: true, completion: nil) coordinator.animate(alongsideTransition: { context in self.scrollController.showToolbars(animated: false) if self.isViewLoaded { self.statusBarOverlay.backgroundColor = self.shouldShowTopTabsForTraitCollection(self.traitCollection) ? UIColor(rgb: 0x272727) : self.urlBar.backgroundColor self.setNeedsStatusBarAppearanceUpdate() } }, completion: nil) } func SELappDidEnterBackgroundNotification() { displayedPopoverController?.dismiss(animated: false) { self.displayedPopoverController = nil } } func SELtappedTopArea() { scrollController.showToolbars(animated: true) } func SELappWillResignActiveNotification() { // Dismiss any popovers that might be visible displayedPopoverController?.dismiss(animated: false) { self.displayedPopoverController = nil } // If we are displying a private tab, hide any elements in the tab that we wouldn't want shown // when the app is in the home switcher guard let privateTab = tabManager.selectedTab, privateTab.isPrivate else { return } webViewContainerBackdrop.alpha = 1 webViewContainer.alpha = 0 urlBar.locationContainer.alpha = 0 topTabsViewController?.switchForegroundStatus(isInForeground: false) presentedViewController?.popoverPresentationController?.containerView?.alpha = 0 presentedViewController?.view.alpha = 0 } func SELappDidBecomeActiveNotification() { // Re-show any components that might have been hidden because they were being displayed // as part of a private mode tab UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: { self.webViewContainer.alpha = 1 self.urlBar.locationContainer.alpha = 1 self.topTabsViewController?.switchForegroundStatus(isInForeground: true) self.presentedViewController?.popoverPresentationController?.containerView?.alpha = 1 self.presentedViewController?.view.alpha = 1 self.view.backgroundColor = UIColor.clear }, completion: { _ in self.webViewContainerBackdrop.alpha = 0 }) // Re-show toolbar which might have been hidden during scrolling (prior to app moving into the background) scrollController.showToolbars(animated: false) } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELBookmarkStatusDidChange(_:)), name: NSNotification.Name(rawValue: BookmarkStatusChangedNotification), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELappWillResignActiveNotification), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELappDidBecomeActiveNotification), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELappDidEnterBackgroundNotification), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) KeyboardHelper.defaultHelper.addDelegate(self) webViewContainerBackdrop = UIView() webViewContainerBackdrop.backgroundColor = UIColor.gray webViewContainerBackdrop.alpha = 0 view.addSubview(webViewContainerBackdrop) webViewContainer = UIView() webViewContainer.addSubview(webViewContainerToolbar) view.addSubview(webViewContainer) // Temporary work around for covering the non-clipped web view content statusBarOverlay = UIView() view.addSubview(statusBarOverlay) topTouchArea = UIButton() topTouchArea.isAccessibilityElement = false topTouchArea.addTarget(self, action: #selector(BrowserViewController.SELtappedTopArea), for: UIControlEvents.touchUpInside) view.addSubview(topTouchArea) // Setup the URL bar, wrapped in a view to get transparency effect urlBar = URLBarView() urlBar.translatesAutoresizingMaskIntoConstraints = false urlBar.delegate = self urlBar.tabToolbarDelegate = self header = urlBarTopTabsContainer urlBarTopTabsContainer.addSubview(urlBar) urlBarTopTabsContainer.addSubview(topTabsContainer) view.addSubview(header) // UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC pasteGoAction = AccessibleAction(name: NSLocalizedString("Paste & Go", comment: "Paste the URL into the location bar and visit"), handler: { () -> Bool in if let pasteboardContents = UIPasteboard.general.string { self.urlBar(self.urlBar, didSubmitText: pasteboardContents) return true } return false }) pasteAction = AccessibleAction(name: NSLocalizedString("Paste", comment: "Paste the URL into the location bar"), handler: { () -> Bool in if let pasteboardContents = UIPasteboard.general.string { // Enter overlay mode and make the search controller appear. self.urlBar.enterOverlayMode(pasteboardContents, pasted: true, search: true) return true } return false }) copyAddressAction = AccessibleAction(name: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), handler: { () -> Bool in if let url = self.urlBar.currentURL { UIPasteboard.general.url = url as URL } return true }) searchLoader = SearchLoader(profile: profile, urlBar: urlBar) footer = UIView() self.view.addSubview(footer) self.view.addSubview(snackBars) snackBars.backgroundColor = UIColor.clear self.view.addSubview(findInPageContainer) if AppConstants.MOZ_CLIPBOARD_BAR { clipboardBarDisplayHandler = ClipboardBarDisplayHandler(prefs: profile.prefs, tabManager: tabManager) clipboardBarDisplayHandler?.delegate = self } scrollController.urlBar = urlBar scrollController.header = header scrollController.footer = footer scrollController.snackBars = snackBars scrollController.webViewContainerToolbar = webViewContainerToolbar self.updateToolbarStateForTraitCollection(self.traitCollection) setupConstraints() } fileprivate func setupConstraints() { topTabsContainer.snp.makeConstraints { make in make.leading.trailing.equalTo(self.header) make.top.equalTo(urlBarTopTabsContainer) } urlBar.snp.makeConstraints { make in make.leading.trailing.bottom.equalTo(urlBarTopTabsContainer) make.height.equalTo(UIConstants.TopToolbarHeight) make.top.equalTo(topTabsContainer.snp.bottom) } header.snp.makeConstraints { make in scrollController.headerTopConstraint = make.top.equalTo(self.topLayoutGuide.snp.bottom).constraint make.left.right.equalTo(self.view) } webViewContainerBackdrop.snp.makeConstraints { make in make.edges.equalTo(webViewContainer) } webViewContainerToolbar.snp.makeConstraints { make in make.left.right.top.equalTo(webViewContainer) make.height.equalTo(0) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() statusBarOverlay.snp.remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(self.topLayoutGuide.length) } } override var canBecomeFirstResponder: Bool { return true } override func becomeFirstResponder() -> Bool { // Make the web view the first responder so that it can show the selection menu. return tabManager.selectedTab?.webView?.becomeFirstResponder() ?? false } func loadQueuedTabs(receivedURLs: [URL]? = nil) { // Chain off of a trivial deferred in order to run on the background queue. succeed().upon() { res in self.dequeueQueuedTabs(receivedURLs: receivedURLs ?? []) } } fileprivate func dequeueQueuedTabs(receivedURLs: [URL]) { assert(!Thread.current.isMainThread, "This must be called in the background.") self.profile.queue.getQueuedTabs() >>== { cursor in // This assumes that the DB returns rows in some kind of sane order. // It does in practice, so WFM. if cursor.count > 0 { // Filter out any tabs received by a push notification to prevent dupes. let urls = cursor.flatMap { $0?.url.asURL }.filter { !receivedURLs.contains($0) } if !urls.isEmpty { DispatchQueue.main.async { self.tabManager.addTabsForURLs(urls, zombie: false) } } // Clear *after* making an attempt to open. We're making a bet that // it's better to run the risk of perhaps opening twice on a crash, // rather than losing data. self.profile.queue.clearQueuedTabs() } // Then, open any received URLs from push notifications. if !receivedURLs.isEmpty { DispatchQueue.main.async { let unopenedReceivedURLs = receivedURLs.filter { self.tabManager.getTabForURL($0) == nil } self.tabManager.addTabsForURLs(unopenedReceivedURLs, zombie: false) if let lastURL = receivedURLs.last, let tab = self.tabManager.getTabForURL(lastURL) { self.tabManager.selectTab(tab) } } } } } // Because crashedLastLaunch is sticky, it does not get reset, we need to remember its // value so that we do not keep asking the user to restore their tabs. var displayedRestoreTabsAlert = false override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // On iPhone, if we are about to show the On-Boarding, blank out the tab so that it does // not flash before we present. This change of alpha also participates in the animation when // the intro view is dismissed. if UIDevice.current.userInterfaceIdiom == .phone { self.view.alpha = (profile.prefs.intForKey(IntroViewControllerSeenProfileKey) != nil) ? 1.0 : 0.0 } if !displayedRestoreTabsAlert && !cleanlyBackgrounded() && crashedLastLaunch() { displayedRestoreTabsAlert = true showRestoreTabsAlert() } else { tabManager.restoreTabs() } updateTabCountUsingTabManager(tabManager, animated: false) clipboardBarDisplayHandler?.checkIfShouldDisplayBar() } fileprivate func crashedLastLaunch() -> Bool { return Sentry.crashedLastLaunch } fileprivate func cleanlyBackgrounded() -> Bool { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return false } return appDelegate.applicationCleanlyBackgrounded } fileprivate func showRestoreTabsAlert() { if !canRestoreTabs() { self.tabManager.addTabAndSelect() return } let alert = UIAlertController.restoreTabsAlert( okayCallback: { _ in self.tabManager.restoreTabs() self.updateTabCountUsingTabManager(self.tabManager, animated: false) }, noCallback: { _ in self.tabManager.addTabAndSelect() self.updateTabCountUsingTabManager(self.tabManager, animated: false) } ) self.present(alert, animated: true, completion: nil) } fileprivate func canRestoreTabs() -> Bool { guard let tabsToRestore = TabManager.tabsToRestore() else { return false } return tabsToRestore.count > 0 } override func viewDidAppear(_ animated: Bool) { presentIntroViewController() self.webViewContainerToolbar.isHidden = false screenshotHelper.viewIsVisible = true screenshotHelper.takePendingScreenshots(tabManager.tabs) super.viewDidAppear(animated) if shouldShowWhatsNewTab() { // Only display if the SUMO topic has been configured in the Info.plist (present and not empty) if let whatsNewTopic = AppInfo.whatsNewTopic, whatsNewTopic != "" { if let whatsNewURL = SupportUtils.URLForTopic(whatsNewTopic) { self.openURLInNewTab(whatsNewURL, isPrivileged: false) profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey) } } } if let toast = self.pendingToast { self.pendingToast = nil show(buttonToast: toast, afterWaiting: ButtonToastUX.ToastDelay) } showQueuedAlertIfAvailable() } fileprivate func shouldShowWhatsNewTab() -> Bool { guard let latestMajorAppVersion = profile.prefs.stringForKey(LatestAppVersionProfileKey)?.components(separatedBy: ".").first else { return DeviceInfo.hasConnectivity() } return latestMajorAppVersion != AppInfo.majorAppVersion && DeviceInfo.hasConnectivity() } fileprivate func showQueuedAlertIfAvailable() { if let queuedAlertInfo = tabManager.selectedTab?.dequeueJavascriptAlertPrompt() { let alertController = queuedAlertInfo.alertController() alertController.delegate = self present(alertController, animated: true, completion: nil) } } override func viewWillDisappear(_ animated: Bool) { screenshotHelper.viewIsVisible = false super.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } func resetBrowserChrome() { // animate and reset transform for tab chrome urlBar.updateAlphaForSubviews(1) footer.alpha = 1 [header, footer, readerModeBar].forEach { view in view?.transform = CGAffineTransform.identity } statusBarOverlay.isHidden = false } override func updateViewConstraints() { super.updateViewConstraints() topTouchArea.snp.remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight) } readerModeBar?.snp.remakeConstraints { make in make.top.equalTo(self.header.snp.bottom) make.height.equalTo(UIConstants.ToolbarHeight) make.leading.trailing.equalTo(self.view) } webViewContainer.snp.remakeConstraints { make in make.left.right.equalTo(self.view) if let readerModeBarBottom = readerModeBar?.snp.bottom { make.top.equalTo(readerModeBarBottom) } else { make.top.equalTo(self.header.snp.bottom) } let findInPageHeight = (findInPageBar == nil) ? 0 : UIConstants.ToolbarHeight if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp.top).offset(-findInPageHeight) } else { make.bottom.equalTo(self.view).offset(-findInPageHeight) } } // Setup the bottom toolbar toolbar?.snp.remakeConstraints { make in make.edges.equalTo(self.footer) make.height.equalTo(UIConstants.BottomToolbarHeight) } footer.snp.remakeConstraints { make in scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp.bottom).constraint make.leading.trailing.equalTo(self.view) } updateSnackBarConstraints() urlBar.setNeedsUpdateConstraints() // Remake constraints even if we're already showing the home controller. // The home controller may change sizes if we tap the URL bar while on about:home. homePanelController?.view.snp.remakeConstraints { make in make.top.equalTo(self.urlBar.snp.bottom) make.left.right.equalTo(self.view) if self.homePanelIsInline { make.bottom.equalTo(self.toolbar?.snp.top ?? self.view.snp.bottom) } else { make.bottom.equalTo(self.view.snp.bottom) } } findInPageContainer.snp.remakeConstraints { make in make.left.right.equalTo(self.view) if let keyboardHeight = keyboardState?.intersectionHeightForView(self.view), keyboardHeight > 0 { make.bottom.equalTo(self.view).offset(-keyboardHeight) } else if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp.top) } else { make.bottom.equalTo(self.view) } } } fileprivate func showHomePanelController(inline: Bool) { homePanelIsInline = inline if homePanelController == nil { let homePanelController = HomePanelViewController() homePanelController.profile = profile homePanelController.delegate = self homePanelController.url = tabManager.selectedTab?.url?.displayURL homePanelController.view.alpha = 0 self.homePanelController = homePanelController addChildViewController(homePanelController) view.addSubview(homePanelController.view) homePanelController.didMove(toParentViewController: self) } guard let homePanelController = self.homePanelController else { assertionFailure("homePanelController is still nil after assignment.") return } let isPrivate = tabManager.selectedTab?.isPrivate ?? false homePanelController.applyTheme(isPrivate ? Theme.PrivateMode : Theme.NormalMode) let panelNumber = tabManager.selectedTab?.url?.fragment // splitting this out to see if we can get better crash reports when this has a problem var newSelectedButtonIndex = 0 if let numberArray = panelNumber?.components(separatedBy: "=") { if let last = numberArray.last, let lastInt = Int(last) { newSelectedButtonIndex = lastInt } } homePanelController.selectedPanel = HomePanelType(rawValue: newSelectedButtonIndex) // We have to run this animation, even if the view is already showing because there may be a hide animation running // and we want to be sure to override its results. UIView.animate(withDuration: 0.2, animations: { () -> Void in homePanelController.view.alpha = 1 }, completion: { finished in if finished { self.webViewContainer.accessibilityElementsHidden = true UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } }) view.setNeedsUpdateConstraints() } fileprivate func hideHomePanelController() { if let controller = homePanelController { self.homePanelController = nil UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in controller.view.alpha = 0 }, completion: { _ in controller.willMove(toParentViewController: nil) controller.view.removeFromSuperview() controller.removeFromParentViewController() self.webViewContainer.accessibilityElementsHidden = false UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // Refresh the reading view toolbar since the article record may have changed if let readerMode = self.tabManager.selectedTab?.getHelper(name: ReaderMode.name()) as? ReaderMode, readerMode.state == .active { self.showReaderModeBar(animated: false) } }) } } fileprivate func updateInContentHomePanel(_ url: URL?) { if !urlBar.inOverlayMode { guard let url = url else { hideHomePanelController() return } if url.isAboutHomeURL { showHomePanelController(inline: true) } else if !url.isLocalUtility || url.isReaderModeURL { hideHomePanelController() } } } fileprivate func showSearchController() { if searchController != nil { return } let isPrivate = tabManager.selectedTab?.isPrivate ?? false searchController = SearchViewController(isPrivate: isPrivate) searchController!.searchEngines = profile.searchEngines searchController!.searchDelegate = self searchController!.profile = self.profile searchLoader.addListener(searchController!) addChildViewController(searchController!) view.addSubview(searchController!.view) searchController!.view.snp.makeConstraints { make in make.top.equalTo(self.urlBar.snp.bottom) make.left.right.bottom.equalTo(self.view) return } homePanelController?.view?.isHidden = true searchController!.didMove(toParentViewController: self) } fileprivate func hideSearchController() { if let searchController = searchController { searchController.willMove(toParentViewController: nil) searchController.view.removeFromSuperview() searchController.removeFromParentViewController() self.searchController = nil homePanelController?.view?.isHidden = false } } fileprivate func finishEditingAndSubmit(_ url: URL, visitType: VisitType) { urlBar.currentURL = url urlBar.leaveOverlayMode() guard let tab = tabManager.selectedTab else { return } if let webView = tab.webView { resetSpoofedUserAgentIfRequired(webView, newURL: url) } if let nav = tab.loadRequest(PrivilegedRequest(url: url) as URLRequest) { self.recordNavigationInTab(tab, navigation: nav, visitType: visitType) } } func addBookmark(_ tabState: TabState) { guard let url = tabState.url else { return } let absoluteString = url.absoluteString let shareItem = ShareItem(url: absoluteString, title: tabState.title, favicon: tabState.favicon) profile.bookmarks.shareItem(shareItem) var userData = [QuickActions.TabURLKey: shareItem.url] if let title = shareItem.title { userData[QuickActions.TabTitleKey] = title } QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark, withUserData: userData, toApplication: UIApplication.shared) if let tab = tabManager.getTabForURL(url) { tab.isBookmarked = true } } func SELBookmarkStatusDidChange(_ notification: Notification) { if let bookmark = notification.object as? BookmarkItem { if bookmark.url == urlBar.currentURL?.absoluteString { if let userInfo = notification.userInfo as? Dictionary<String, Bool> { if userInfo["added"] != nil { if let tab = self.tabManager.getTabForURL(urlBar.currentURL!) { tab.isBookmarked = false } } } } } } override func accessibilityPerformEscape() -> Bool { if urlBar.inOverlayMode { urlBar.SELdidClickCancel() return true } else if let selectedTab = tabManager.selectedTab, selectedTab.canGoBack { selectedTab.goBack() return true } return false } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { let webView = object as! WKWebView guard let path = keyPath else { assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")"); return } switch path { case KVOEstimatedProgress: guard webView == tabManager.selectedTab?.webView, let progress = change?[NSKeyValueChangeKey.newKey] as? Float else { break } if !(webView.url?.isLocalUtility ?? false) { urlBar.updateProgressBar(progress) } else { urlBar.hideProgressBar() } case KVOLoading: guard let loading = change?[NSKeyValueChangeKey.newKey] as? Bool else { break } if webView == tabManager.selectedTab?.webView { navigationToolbar.updateReloadStatus(loading) } if !loading { runScriptsOnWebView(webView) } case KVOURL: guard let tab = tabManager[webView] else { break } // To prevent spoofing, only change the URL immediately if the new URL is on // the same origin as the current URL. Otherwise, do nothing and wait for // didCommitNavigation to confirm the page load. if tab.url?.origin == webView.url?.origin { tab.url = webView.url if tab === tabManager.selectedTab && !tab.restoring { updateUIForReaderHomeStateForTab(tab) } } case KVOTitle: guard let tab = tabManager[webView] else { break } // Ensure that the tab title *actually* changed to prevent repeated calls // to navigateInTab(tab:). guard let title = tab.title else { break } if !title.isEmpty && title != tab.lastTitle { navigateInTab(tab: tab) } case KVOCanGoBack: guard webView == tabManager.selectedTab?.webView, let canGoBack = change?[NSKeyValueChangeKey.newKey] as? Bool else { break } navigationToolbar.updateBackStatus(canGoBack) case KVOCanGoForward: guard webView == tabManager.selectedTab?.webView, let canGoForward = change?[NSKeyValueChangeKey.newKey] as? Bool else { break } navigationToolbar.updateForwardStatus(canGoForward) default: assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")") } } fileprivate func runScriptsOnWebView(_ webView: WKWebView) { webView.evaluateJavaScript("__firefox__.favicons.getFavicons()", completionHandler: nil) webView.evaluateJavaScript("__firefox__.metadata.extractMetadata()", completionHandler: nil) if #available(iOS 11, *) { if NoImageModeHelper.isActivated(profile.prefs) { webView.evaluateJavaScript("__firefox__.NoImageMode.setEnabled(true)", completionHandler: nil) } } } func updateUIForReaderHomeStateForTab(_ tab: Tab) { updateURLBarDisplayURL(tab) scrollController.showToolbars(animated: false) if let url = tab.url { if url.isReaderModeURL { showReaderModeBar(animated: false) NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELDynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil) } else { hideReaderModeBar(animated: false) NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil) } updateInContentHomePanel(url as URL) } } fileprivate func isWhitelistedUrl(_ url: URL) -> Bool { for entry in WhiteListedUrls { if let _ = url.absoluteString.range(of: entry, options: .regularExpression) { return UIApplication.shared.canOpenURL(url) } } return false } /// Updates the URL bar text and button states. /// Call this whenever the page URL changes. fileprivate func updateURLBarDisplayURL(_ tab: Tab) { urlBar.currentURL = tab.url?.displayURL let isPage = tab.url?.displayURL?.isWebPage() ?? false navigationToolbar.updatePageStatus(isPage) guard let url = tab.url?.displayURL?.absoluteString else { return } profile.bookmarks.modelFactory >>== { $0.isBookmarked(url).uponQueue(DispatchQueue.main) { [weak tab] result in guard let bookmarked = result.successValue else { print("Error getting bookmark status: \(result.failureValue ??? "nil").") return } tab?.isBookmarked = bookmarked } } } // MARK: Opening New Tabs func switchToPrivacyMode(isPrivate: Bool ) { // applyTheme(isPrivate ? Theme.PrivateMode : Theme.NormalMode) let tabTrayController = self.tabTrayController ?? TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self) if tabTrayController.privateMode != isPrivate { tabTrayController.changePrivacyMode(isPrivate) } self.tabTrayController = tabTrayController } func switchToTabForURLOrOpen(_ url: URL, isPrivate: Bool = false, isPrivileged: Bool) { popToBVC() if let tab = tabManager.getTabForURL(url) { tabManager.selectTab(tab) } else { openURLInNewTab(url, isPrivate: isPrivate, isPrivileged: isPrivileged) } } func openURLInNewTab(_ url: URL?, isPrivate: Bool = false, isPrivileged: Bool) { if let selectedTab = tabManager.selectedTab { screenshotHelper.takeScreenshot(selectedTab) } let request: URLRequest? if let url = url { request = isPrivileged ? PrivilegedRequest(url: url) as URLRequest : URLRequest(url: url) } else { request = nil } switchToPrivacyMode(isPrivate: isPrivate) _ = tabManager.addTabAndSelect(request, isPrivate: isPrivate) if url == nil && NewTabAccessors.getNewTabPage(profile.prefs) == .blankPage { urlBar.tabLocationViewDidTapLocation(urlBar.locationView) } } func openBlankNewTab(focusLocationField: Bool, isPrivate: Bool = false) { popToBVC() openURLInNewTab(nil, isPrivate: isPrivate, isPrivileged: true) if focusLocationField { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) { // Without a delay, the text field fails to become first responder self.urlBar.tabLocationViewDidTapLocation(self.urlBar.locationView) } } } fileprivate func popToBVC() { guard let currentViewController = navigationController?.topViewController else { return } currentViewController.dismiss(animated: true, completion: nil) if currentViewController != self { _ = self.navigationController?.popViewController(animated: true) } else if urlBar.inOverlayMode { urlBar.SELdidClickCancel() } } // MARK: User Agent Spoofing func resetSpoofedUserAgentIfRequired(_ webView: WKWebView, newURL: URL) { // Reset the UA when a different domain is being loaded if webView.url?.host != newURL.host { webView.customUserAgent = nil } } func restoreSpoofedUserAgentIfRequired(_ webView: WKWebView, newRequest: URLRequest) { // Restore any non-default UA from the request's header let ua = newRequest.value(forHTTPHeaderField: "User-Agent") webView.customUserAgent = ua != UserAgent.defaultUserAgent() ? ua : nil } fileprivate func presentActivityViewController(_ url: URL, tab: Tab? = nil, sourceView: UIView?, sourceRect: CGRect, arrowDirection: UIPopoverArrowDirection) { let helper = ShareExtensionHelper(url: url, tab: tab) let controller = helper.createActivityViewController({ [unowned self] completed, _ in // After dismissing, check to see if there were any prompts we queued up self.showQueuedAlertIfAvailable() // Usually the popover delegate would handle nil'ing out the references we have to it // on the BVC when displaying as a popover but the delegate method doesn't seem to be // invoked on iOS 10. See Bug 1297768 for additional details. self.displayedPopoverController = nil self.updateDisplayedPopoverProperties = nil }) if let popoverPresentationController = controller.popoverPresentationController { popoverPresentationController.sourceView = sourceView popoverPresentationController.sourceRect = sourceRect popoverPresentationController.permittedArrowDirections = arrowDirection popoverPresentationController.delegate = self } present(controller, animated: true, completion: nil) LeanplumIntegration.sharedInstance.track(eventName: .userSharedWebpage) } func updateFindInPageVisibility(visible: Bool) { if visible { if findInPageBar == nil { let findInPageBar = FindInPageBar() self.findInPageBar = findInPageBar findInPageBar.delegate = self findInPageContainer.addSubview(findInPageBar) findInPageBar.snp.makeConstraints { make in make.edges.equalTo(findInPageContainer) make.height.equalTo(UIConstants.ToolbarHeight) } updateViewConstraints() // We make the find-in-page bar the first responder below, causing the keyboard delegates // to fire. This, in turn, will animate the Find in Page container since we use the same // delegate to slide the bar up and down with the keyboard. We don't want to animate the // constraints added above, however, so force a layout now to prevent these constraints // from being lumped in with the keyboard animation. findInPageBar.layoutIfNeeded() } self.findInPageBar?.becomeFirstResponder() } else if let findInPageBar = self.findInPageBar { findInPageBar.endEditing(true) guard let webView = tabManager.selectedTab?.webView else { return } webView.evaluateJavaScript("__firefox__.findDone()", completionHandler: nil) findInPageBar.removeFromSuperview() self.findInPageBar = nil updateViewConstraints() } } @objc fileprivate func openSettings() { assert(Thread.isMainThread, "Opening settings requires being invoked on the main thread") let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = profile settingsTableViewController.tabManager = tabManager settingsTableViewController.settingsDelegate = self let controller = SettingsNavigationController(rootViewController: settingsTableViewController) controller.popoverDelegate = self controller.modalPresentationStyle = UIModalPresentationStyle.formSheet self.present(controller, animated: true, completion: nil) } fileprivate func postLocationChangeNotificationForTab(_ tab: Tab, navigation: WKNavigation?) { let notificationCenter = NotificationCenter.default var info = [AnyHashable: Any]() info["url"] = tab.url?.displayURL info["title"] = tab.title if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue { info["visitType"] = visitType } info["isPrivate"] = tab.isPrivate notificationCenter.post(name: NotificationOnLocationChange, object: self, userInfo: info) } func navigateInTab(tab: Tab, to navigation: WKNavigation? = nil) { tabManager.expireSnackbars() guard let webView = tab.webView else { print("Cannot navigate in tab without a webView") return } if let url = webView.url, !url.isErrorPageURL && !url.isAboutHomeURL { tab.lastExecutedTime = Date.now() postLocationChangeNotificationForTab(tab, navigation: navigation) // Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore // because that event wil not always fire due to unreliable page caching. This will either let us know that // the currently loaded page can be turned into reading mode or if the page already is in reading mode. We // ignore the result because we are being called back asynchronous when the readermode status changes. webView.evaluateJavaScript("\(ReaderModeNamespace).checkReadability()", completionHandler: nil) // Re-run additional scripts in webView to extract updated favicons and metadata. runScriptsOnWebView(webView) } if tab === tabManager.selectedTab { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // must be followed by LayoutChanged, as ScreenChanged will make VoiceOver // cursor land on the correct initial element, but if not followed by LayoutChanged, // VoiceOver will sometimes be stuck on the element, not allowing user to move // forward/backward. Strange, but LayoutChanged fixes that. UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } else { // To Screenshot a tab that is hidden we must add the webView, // then wait enough time for the webview to render. if let webView = tab.webView { view.insertSubview(webView, at: 0) DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) { self.screenshotHelper.takeScreenshot(tab) if webView.superview == self.view { webView.removeFromSuperview() } } } } // Remember whether or not a desktop site was requested tab.desktopSite = webView.customUserAgent?.isEmpty == false } // MARK: open in helper utils func addViewForOpenInHelper(_ openInHelper: OpenInHelper) { guard let view = openInHelper.openInView else { return } webViewContainerToolbar.addSubview(view) webViewContainerToolbar.snp.updateConstraints { make in make.height.equalTo(OpenInViewUX.ViewHeight) } view.snp.makeConstraints { make in make.edges.equalTo(webViewContainerToolbar) } self.openInHelper = openInHelper } func removeOpenInView() { guard let _ = self.openInHelper else { return } webViewContainerToolbar.subviews.forEach { $0.removeFromSuperview() } webViewContainerToolbar.snp.updateConstraints { make in make.height.equalTo(0) } self.openInHelper = nil } } extension BrowserViewController: ClipboardBarDisplayHandlerDelegate { func shouldDisplay(clipboardBar bar: ButtonToast) { show(buttonToast: bar, duration: ClipboardBarToastUX.ToastDelay) } } extension BrowserViewController: QRCodeViewControllerDelegate { func scanSuccessOpenNewTabWithData(data: String) { self.openBlankNewTab(focusLocationField: false) self.urlBar(self.urlBar, didSubmitText: data) } } extension BrowserViewController: SettingsDelegate { func settingsOpenURLInNewTab(_ url: URL) { self.openURLInNewTab(url, isPrivileged: false) } } extension BrowserViewController: PresentingModalViewControllerDelegate { func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) { self.dismiss(animated: animated, completion: nil) } } /** * History visit management. * TODO: this should be expanded to track various visit types; see Bug 1166084. */ extension BrowserViewController { func ignoreNavigationInTab(_ tab: Tab, navigation: WKNavigation) { self.ignoredNavigation.insert(navigation) } func recordNavigationInTab(_ tab: Tab, navigation: WKNavigation, visitType: VisitType) { self.typedNavigation[navigation] = visitType } /** * Untrack and do the right thing. */ func getVisitTypeForTab(_ tab: Tab, navigation: WKNavigation?) -> VisitType? { guard let navigation = navigation else { // See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390 return VisitType.link } if let _ = self.ignoredNavigation.remove(navigation) { return nil } return self.typedNavigation.removeValue(forKey: navigation) ?? VisitType.link } } extension BrowserViewController: URLBarDelegate { func showTabTray() { webViewContainerToolbar.isHidden = true updateFindInPageVisibility(visible: false) let tabTrayController = TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self) if let tab = tabManager.selectedTab { screenshotHelper.takeScreenshot(tab) } navigationController?.pushViewController(tabTrayController, animated: true) self.tabTrayController = tabTrayController } func urlBarDidPressReload(_ urlBar: URLBarView) { tabManager.selectedTab?.reload() } func urlBarDidPressQRButton(_ urlBar: URLBarView) { let qrCodeViewController = QRCodeViewController() qrCodeViewController.qrCodeDelegate = self let controller = QRCodeNavigationController(rootViewController: qrCodeViewController) self.present(controller, animated: true, completion: nil) } func urlBarDidPressPageOptions(_ urlBar: URLBarView, from button: UIButton) { let actionMenuPresenter: (URL, Tab, UIView, UIPopoverArrowDirection) -> Void = { (url, tab, view, _) in self.presentActivityViewController(url, tab: tab, sourceView: view, sourceRect: view.bounds, arrowDirection: .up) } let findInPageAction = { self.updateFindInPageVisibility(visible: true) } let successCallback: (String) -> Void = { (successMessage) in SimpleToast().showAlertWithText(successMessage, bottomContainer: self.webViewContainer) } guard let tab = tabManager.selectedTab, tab.url != nil else { return } // The logic of which actions appear when isnt final. let pageActions = getTabActions(tab: tab, buttonView: button, presentShareMenu: actionMenuPresenter, findInPage: findInPageAction, presentableVC: self, success: successCallback) presentSheetWith(actions: pageActions, on: self, from: button) } func urlBarDidLongPressPageOptions(_ urlBar: URLBarView, from button: UIButton) { guard let tab = tabManager.selectedTab else { return } guard let url = tab.canonicalURL?.displayURL else { return } presentActivityViewController(url, tab: tab, sourceView: button, sourceRect: button.bounds, arrowDirection: .up) } func urlBarDidPressStop(_ urlBar: URLBarView) { tabManager.selectedTab?.stop() } func urlBarDidPressTabs(_ urlBar: URLBarView) { showTabTray() } func urlBarDidPressReaderMode(_ urlBar: URLBarView) { if let tab = tabManager.selectedTab { if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode { switch readerMode.state { case .available: enableReaderMode() LeanplumIntegration.sharedInstance.track(eventName: .useReaderView) case .active: disableReaderMode() case .unavailable: break } } } } func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool { guard let tab = tabManager.selectedTab, let url = tab.url?.displayURL, let result = profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) else { UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed.")) return false } switch result { case .success: UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action.")) // TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback? case .failure(let error): UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it’s already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures.")) print("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)") } return true } func locationActionsForURLBar(_ urlBar: URLBarView) -> [AccessibleAction] { if UIPasteboard.general.string != nil { return [pasteGoAction, pasteAction, copyAddressAction] } else { return [copyAddressAction] } } func urlBarDisplayTextForURL(_ url: URL?) -> (String?, Bool) { // use the initial value for the URL so we can do proper pattern matching with search URLs var searchURL = self.tabManager.selectedTab?.currentInitialURL if searchURL?.isErrorPageURL ?? true { searchURL = url } if let query = profile.searchEngines.queryForSearchURL(searchURL as URL?) { return (query, true) } else { return (url?.absoluteString, false) } } func urlBarDidLongPressLocation(_ urlBar: URLBarView) { let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) for action in locationActionsForURLBar(urlBar) { longPressAlertController.addAction(action.alertAction(style: .default)) } let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: { (alert: UIAlertAction) -> Void in }) longPressAlertController.addAction(cancelAction) let setupPopover = { [unowned self] in if let popoverPresentationController = longPressAlertController.popoverPresentationController { popoverPresentationController.sourceView = urlBar popoverPresentationController.sourceRect = urlBar.frame popoverPresentationController.permittedArrowDirections = .any popoverPresentationController.delegate = self } } setupPopover() if longPressAlertController.popoverPresentationController != nil { displayedPopoverController = longPressAlertController updateDisplayedPopoverProperties = setupPopover } self.present(longPressAlertController, animated: true, completion: nil) } func urlBarDidPressScrollToTop(_ urlBar: URLBarView) { if let selectedTab = tabManager.selectedTab { // Only scroll to top if we are not showing the home view controller if homePanelController == nil { selectedTab.webView?.scrollView.setContentOffset(CGPoint.zero, animated: true) } } } func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? { return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction } } func urlBar(_ urlBar: URLBarView, didEnterText text: String) { searchLoader.query = text if text.isEmpty { hideSearchController() } else { showSearchController() searchController!.searchQuery = text } } func urlBar(_ urlBar: URLBarView, didSubmitText text: String) { if let fixupURL = URIFixup.getURL(text) { // The user entered a URL, so use it. finishEditingAndSubmit(fixupURL, visitType: VisitType.typed) return } // We couldn't build a URL, so check for a matching search keyword. let trimmedText = text.trimmingCharacters(in: CharacterSet.whitespaces) guard let possibleKeywordQuerySeparatorSpace = trimmedText.characters.index(of: " ") else { submitSearchText(text) return } let possibleKeyword = trimmedText.substring(to: possibleKeywordQuerySeparatorSpace) let possibleQuery = trimmedText.substring(from: trimmedText.index(after: possibleKeywordQuerySeparatorSpace)) profile.bookmarks.getURLForKeywordSearch(possibleKeyword).uponQueue(DispatchQueue.main) { result in if var urlString = result.successValue, let escapedQuery = possibleQuery.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed), let range = urlString.range(of: "%s") { urlString.replaceSubrange(range, with: escapedQuery) if let url = URL(string: urlString) { self.finishEditingAndSubmit(url, visitType: VisitType.typed) return } } self.submitSearchText(text) } } fileprivate func submitSearchText(_ text: String) { let engine = profile.searchEngines.defaultEngine if let searchURL = engine.searchURLForQuery(text) { // We couldn't find a matching search keyword, so do a search query. Telemetry.default.recordSearch(location: .actionBar, searchEngine: engine.engineID ?? "other") finishEditingAndSubmit(searchURL, visitType: VisitType.typed) } else { // We still don't have a valid URL, so something is broken. Give up. print("Error handling URL entry: \"\(text)\".") assertionFailure("Couldn't generate search URL: \(text)") } } func urlBarDidEnterOverlayMode(_ urlBar: URLBarView) { if .blankPage == NewTabAccessors.getNewTabPage(profile.prefs) { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } else { if let toast = clipboardBarDisplayHandler?.clipboardToast { toast.removeFromSuperview() } showHomePanelController(inline: false) } LeanplumIntegration.sharedInstance.track(eventName: .interactWithURLBar) } func urlBarDidLeaveOverlayMode(_ urlBar: URLBarView) { hideSearchController() updateInContentHomePanel(tabManager.selectedTab?.url as URL?) } } extension BrowserViewController: TabToolbarDelegate, PhotonActionSheetProtocol { func tabToolbarDidPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goBack() } func tabToolbarDidLongPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) { showBackForwardList() } func tabToolbarDidPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.reload() } func tabToolbarDidLongPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) { guard let tab = tabManager.selectedTab, tab.webView?.url != nil && (tab.getHelper(name: ReaderMode.name()) as? ReaderMode)?.state != .active else { return } let toggleActionTitle: String if tab.desktopSite { toggleActionTitle = NSLocalizedString("Request Mobile Site", comment: "Action Sheet Button for Requesting the Mobile Site") } else { toggleActionTitle = NSLocalizedString("Request Desktop Site", comment: "Action Sheet Button for Requesting the Desktop Site") } let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) controller.addAction(UIAlertAction(title: toggleActionTitle, style: .default, handler: { _ in tab.toggleDesktopSite() })) controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: nil)) controller.popoverPresentationController?.sourceView = toolbar ?? urlBar controller.popoverPresentationController?.sourceRect = button.frame present(controller, animated: true, completion: nil) } func tabToolbarDidPressStop(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.stop() } func tabToolbarDidPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goForward() } func tabToolbarDidLongPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) { showBackForwardList() } func tabToolbarDidPressMenu(_ tabToolbar: TabToolbarProtocol, button: UIButton) { // ensure that any keyboards or spinners are dismissed before presenting the menu UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) var actions: [[PhotonActionSheetItem]] = [] actions.append(getHomePanelActions()) actions.append(getOtherPanelActions(vcDelegate: self)) // force a modal if the menu is being displayed in compact split screen let shouldSupress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad presentSheetWith(actions: actions, on: self, from: button, supressPopover: shouldSupress) } func tabToolbarDidPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) { showTabTray() } func tabToolbarDidLongPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) { let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) controller.addAction(UIAlertAction(title: Strings.NewTabTitle, style: .default, handler: { _ in self.tabManager.addTabAndSelect(isPrivate: false) })) controller.addAction(UIAlertAction(title: Strings.NewPrivateTabTitle, style: .default, handler: { _ in self.tabManager.addTabAndSelect(isPrivate: true) })) controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: nil)) controller.popoverPresentationController?.sourceView = toolbar ?? urlBar controller.popoverPresentationController?.sourceRect = button.frame present(controller, animated: true, completion: nil) } func showBackForwardList() { if let backForwardList = tabManager.selectedTab?.webView?.backForwardList { let backForwardViewController = BackForwardListViewController(profile: profile, backForwardList: backForwardList) backForwardViewController.tabManager = tabManager backForwardViewController.bvc = self backForwardViewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext backForwardViewController.backForwardTransitionDelegate = BackForwardListAnimator() self.present(backForwardViewController, animated: true, completion: nil) } } } extension BrowserViewController: TabDelegate { func tab(_ tab: Tab, didCreateWebView webView: WKWebView) { webView.frame = webViewContainer.frame // Observers that live as long as the tab. Make sure these are all cleared // in willDeleteWebView below! webView.addObserver(self, forKeyPath: KVOEstimatedProgress, options: .new, context: nil) webView.addObserver(self, forKeyPath: KVOLoading, options: .new, context: nil) webView.addObserver(self, forKeyPath: KVOCanGoBack, options: .new, context: nil) webView.addObserver(self, forKeyPath: KVOCanGoForward, options: .new, context: nil) tab.webView?.addObserver(self, forKeyPath: KVOURL, options: .new, context: nil) tab.webView?.addObserver(self, forKeyPath: KVOTitle, options: .new, context: nil) webView.scrollView.addObserver(self.scrollController, forKeyPath: KVOContentSize, options: .new, context: nil) webView.uiDelegate = self let readerMode = ReaderMode(tab: tab) readerMode.delegate = self tab.addHelper(readerMode, name: ReaderMode.name()) let favicons = FaviconManager(tab: tab, profile: profile) tab.addHelper(favicons, name: FaviconManager.name()) // only add the logins helper if the tab is not a private browsing tab if !tab.isPrivate { let logins = LoginsHelper(tab: tab, profile: profile) tab.addHelper(logins, name: LoginsHelper.name()) } let contextMenuHelper = ContextMenuHelper(tab: tab) contextMenuHelper.delegate = self tab.addHelper(contextMenuHelper, name: ContextMenuHelper.name()) let errorHelper = ErrorPageHelper() tab.addHelper(errorHelper, name: ErrorPageHelper.name()) let sessionRestoreHelper = SessionRestoreHelper(tab: tab) sessionRestoreHelper.delegate = self tab.addHelper(sessionRestoreHelper, name: SessionRestoreHelper.name()) let findInPageHelper = FindInPageHelper(tab: tab) findInPageHelper.delegate = self tab.addHelper(findInPageHelper, name: FindInPageHelper.name()) let noImageModeHelper = NoImageModeHelper(tab: tab) tab.addHelper(noImageModeHelper, name: NoImageModeHelper.name()) let printHelper = PrintHelper(tab: tab) tab.addHelper(printHelper, name: PrintHelper.name()) let customSearchHelper = CustomSearchHelper(tab: tab) tab.addHelper(customSearchHelper, name: CustomSearchHelper.name()) let nightModeHelper = NightModeHelper(tab: tab) tab.addHelper(nightModeHelper, name: NightModeHelper.name()) // XXX: Bug 1390200 - Disable NSUserActivity/CoreSpotlight temporarily // let spotlightHelper = SpotlightHelper(tab: tab) // tab.addHelper(spotlightHelper, name: SpotlightHelper.name()) tab.addHelper(LocalRequestHelper(), name: LocalRequestHelper.name()) let historyStateHelper = HistoryStateHelper(tab: tab) historyStateHelper.delegate = self tab.addHelper(historyStateHelper, name: HistoryStateHelper.name()) if #available(iOS 11, *) { (tab.contentBlocker as? ContentBlockerHelper)?.setupForWebView() } let metadataHelper = MetadataParserHelper(tab: tab, profile: profile) tab.addHelper(metadataHelper, name: MetadataParserHelper.name()) } func tab(_ tab: Tab, willDeleteWebView webView: WKWebView) { tab.cancelQueuedAlerts() webView.removeObserver(self, forKeyPath: KVOEstimatedProgress) webView.removeObserver(self, forKeyPath: KVOLoading) webView.removeObserver(self, forKeyPath: KVOCanGoBack) webView.removeObserver(self, forKeyPath: KVOCanGoForward) webView.scrollView.removeObserver(self.scrollController, forKeyPath: KVOContentSize) webView.removeObserver(self, forKeyPath: KVOURL) webView.removeObserver(self, forKeyPath: KVOTitle) webView.uiDelegate = nil webView.scrollView.delegate = nil webView.removeFromSuperview() } fileprivate func findSnackbar(_ barToFind: SnackBar) -> Int? { let bars = snackBars.subviews for (index, bar) in bars.enumerated() where bar === barToFind { return index } return nil } fileprivate func updateSnackBarConstraints() { snackBars.snp.remakeConstraints { make in make.bottom.equalTo(findInPageContainer.snp.top) let bars = self.snackBars.subviews if bars.count > 0 { let view = bars[bars.count-1] make.top.equalTo(view.snp.top) } else { make.height.equalTo(0) } if traitCollection.horizontalSizeClass != .regular { make.leading.trailing.equalTo(self.view) self.snackBars.layer.borderWidth = 0 } else { make.centerX.equalTo(self.view) make.width.equalTo(SnackBarUX.MaxWidth) self.snackBars.layer.borderColor = UIConstants.BorderColor.cgColor self.snackBars.layer.borderWidth = 1 } } } // This removes the bar from its superview and updates constraints appropriately fileprivate func finishRemovingBar(_ bar: SnackBar) { // If there was a bar above this one, we need to remake its constraints. if let index = findSnackbar(bar) { // If the bar being removed isn't on the top of the list let bars = snackBars.subviews if index < bars.count-1 { // Move the bar above this one let nextbar = bars[index+1] as! SnackBar nextbar.snp.makeConstraints { make in // If this wasn't the bottom bar, attach to the bar below it if index > 0 { let bar = bars[index-1] as! SnackBar nextbar.bottom = make.bottom.equalTo(bar.snp.top).constraint } else { // Otherwise, we attach it to the bottom of the snackbars nextbar.bottom = make.bottom.equalTo(self.snackBars.snp.bottom).constraint } } } } // Really remove the bar bar.removeFromSuperview() } fileprivate func finishAddingBar(_ bar: SnackBar) { snackBars.addSubview(bar) bar.snp.makeConstraints { make in // If there are already bars showing, add this on top of them let bars = self.snackBars.subviews // Add the bar on top of the stack // We're the new top bar in the stack, so make sure we ignore ourself if bars.count > 1 { let view = bars[bars.count - 2] bar.bottom = make.bottom.equalTo(view.snp.top).offset(0).constraint } else { bar.bottom = make.bottom.equalTo(self.snackBars.snp.bottom).offset(0).constraint } make.leading.trailing.equalTo(self.snackBars) } } func showBar(_ bar: SnackBar, animated: Bool) { finishAddingBar(bar) updateSnackBarConstraints() bar.hide() view.layoutIfNeeded() UIView.animate(withDuration: animated ? 0.25 : 0, animations: { () -> Void in bar.show() self.view.layoutIfNeeded() }) } func removeBar(_ bar: SnackBar, animated: Bool) { if let _ = findSnackbar(bar) { UIView.animate(withDuration: animated ? 0.25 : 0, animations: { () -> Void in bar.hide() self.view.layoutIfNeeded() }, completion: { success in // Really remove the bar self.finishRemovingBar(bar) self.updateSnackBarConstraints() }) } } func removeAllBars() { let bars = snackBars.subviews for bar in bars { if let bar = bar as? SnackBar { bar.removeFromSuperview() } } self.updateSnackBarConstraints() } func tab(_ tab: Tab, didAddSnackbar bar: SnackBar) { showBar(bar, animated: true) } func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar) { removeBar(bar, animated: true) } func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String) { updateFindInPageVisibility(visible: true) findInPageBar?.text = selection } } extension BrowserViewController: HomePanelViewControllerDelegate { func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectURL url: URL, visitType: VisitType) { finishEditingAndSubmit(url, visitType: visitType) } func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) { if let url = tabManager.selectedTab?.url, url.isAboutHomeURL { tabManager.selectedTab?.webView?.evaluateJavaScript("history.replaceState({}, '', '#panel=\(panel)')", completionHandler: nil) } } func homePanelViewControllerDidRequestToCreateAccount(_ homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } func homePanelViewControllerDidRequestToSignIn(_ homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } func homePanelViewControllerDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) { let tab = self.tabManager.addTab(PrivilegedRequest(url: url) as URLRequest, afterTab: self.tabManager.selectedTab, isPrivate: isPrivate) // If we are showing toptabs a user can just use the top tab bar // If in overlay mode switching doesnt correctly dismiss the homepanels guard !topTabsVisible, !self.urlBar.inOverlayMode else { return } // We're not showing the top tabs; show a toast to quick switch to the fresh new tab. let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in if buttonPressed { self.tabManager.selectTab(tab) } }) self.show(buttonToast: toast) } } extension BrowserViewController: SearchViewControllerDelegate { func searchViewController(_ searchViewController: SearchViewController, didSelectURL url: URL) { finishEditingAndSubmit(url, visitType: VisitType.typed) } func searchViewController(_ searchViewController: SearchViewController, didLongPressSuggestion suggestion: String) { self.urlBar.setLocation(suggestion, search: true) } func presentSearchSettingsController() { let settingsNavigationController = SearchSettingsTableViewController() settingsNavigationController.model = self.profile.searchEngines settingsNavigationController.profile = self.profile let navController = ModalSettingsNavigationController(rootViewController: settingsNavigationController) self.present(navController, animated: true, completion: nil) } } extension BrowserViewController: TabManagerDelegate { func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) { // Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it // and having multiple views with the same label confuses tests. if let wv = previous?.webView { removeOpenInView() wv.endEditing(true) wv.accessibilityLabel = nil wv.accessibilityElementsHidden = true wv.accessibilityIdentifier = nil wv.removeFromSuperview() } if let tab = selected, let webView = tab.webView { updateURLBarDisplayURL(tab) if tab.isPrivate != previous?.isPrivate { applyTheme(tab.isPrivate ? Theme.PrivateMode : Theme.NormalMode) } if tab.isPrivate { readerModeCache = MemoryReaderModeCache.sharedInstance } else { readerModeCache = DiskReaderModeCache.sharedInstance } if let privateModeButton = topTabsViewController?.privateModeButton, previous != nil && previous?.isPrivate != tab.isPrivate { privateModeButton.setSelected(tab.isPrivate, animated: true) } ReaderModeHandlers.readerModeCache = readerModeCache scrollController.tab = selected webViewContainer.addSubview(webView) webView.snp.makeConstraints { make in make.top.equalTo(webViewContainerToolbar.snp.bottom) make.left.right.bottom.equalTo(self.webViewContainer) } webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.accessibilityIdentifier = "contentView" webView.accessibilityElementsHidden = false if let url = webView.url { let absoluteString = url.absoluteString // Don't bother fetching bookmark state for about/sessionrestore and about/home. if url.isAboutURL { // Indeed, because we don't show the toolbar at all, don't even blank the star. } else { profile.bookmarks.modelFactory >>== { [weak tab] in $0.isBookmarked(absoluteString) .uponQueue(DispatchQueue.main) { guard let isBookmarked = $0.successValue else { print("Error getting bookmark status: \($0.failureValue ??? "nil").") return } tab?.isBookmarked = isBookmarked } } } } else { // The web view can go gray if it was zombified due to memory pressure. // When this happens, the URL is nil, so try restoring the page upon selection. tab.reload() } } if let selected = selected, let previous = previous, selected.isPrivate != previous.isPrivate { updateTabCountUsingTabManager(tabManager) } removeAllBars() if let bars = selected?.bars { for bar in bars { showBar(bar, animated: true) } } updateFindInPageVisibility(visible: false) navigationToolbar.updateReloadStatus(selected?.loading ?? false) navigationToolbar.updateBackStatus(selected?.canGoBack ?? false) navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false) if !(selected?.webView?.url?.isLocalUtility ?? false) { self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0)) } if let readerMode = selected?.getHelper(name: ReaderMode.name()) as? ReaderMode { urlBar.updateReaderModeState(readerMode.state) if readerMode.state == .active { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } else { urlBar.updateReaderModeState(ReaderModeState.unavailable) } updateInContentHomePanel(selected?.url as URL?) } func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) { } func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) { // If we are restoring tabs then we update the count once at the end if !tabManager.isRestoring { updateTabCountUsingTabManager(tabManager) } tab.tabDelegate = self } func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) { } func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) { updateTabCountUsingTabManager(tabManager) // tabDelegate is a weak ref (and the tab's webView may not be destroyed yet) // so we don't expcitly unset it. if let url = tab.url, !url.isAboutURL && !tab.isPrivate { profile.recentlyClosedTabs.addTab(url as URL, title: tab.title, faviconURL: tab.displayFavicon?.url) } } func tabManagerDidAddTabs(_ tabManager: TabManager) { updateTabCountUsingTabManager(tabManager) } func tabManagerDidRestoreTabs(_ tabManager: TabManager) { updateTabCountUsingTabManager(tabManager) } func show(buttonToast: ButtonToast, afterWaiting delay: DispatchTimeInterval = SimpleToastUX.ToastDelayBefore, duration: DispatchTimeInterval = SimpleToastUX.ToastDismissAfter) { // If BVC isnt visible hold on to this toast until viewDidAppear if self.view.window == nil { self.pendingToast = buttonToast return } DispatchQueue.main.asyncAfter(deadline: .now() + delay) { self.view.addSubview(buttonToast) buttonToast.snp.makeConstraints { make in make.left.right.equalTo(self.view) make.bottom.equalTo(self.webViewContainer) } buttonToast.showToast(duration: duration) } } func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) { guard let toast = toast, !tabTrayController.privateMode else { return } show(buttonToast: toast, afterWaiting: ButtonToastUX.ToastDelay) } fileprivate func updateTabCountUsingTabManager(_ tabManager: TabManager, animated: Bool = true) { if let selectedTab = tabManager.selectedTab { let count = selectedTab.isPrivate ? tabManager.privateTabs.count : tabManager.normalTabs.count toolbar?.updateTabCount(count, animated: animated) urlBar.updateTabCount(count, animated: !urlBar.inOverlayMode) topTabsViewController?.updateTabCount(count, animated: animated) } } } /// List of schemes that are allowed to open a popup window private let SchemesAllowedToOpenPopups = ["http", "https", "javascript", "data"] extension BrowserViewController: WKUIDelegate { func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { guard let parentTab = tabManager[webView] else { return nil } if !navigationAction.isAllowed { print("Denying unprivileged request: \(navigationAction.request)") return nil } if let currentTab = tabManager.selectedTab { screenshotHelper.takeScreenshot(currentTab) } // If the page uses window.open() or target="_blank", open the page in a new tab. let newTab = tabManager.addTab(navigationAction.request, configuration: configuration, afterTab: parentTab, isPrivate: parentTab.isPrivate) tabManager.selectTab(newTab) // If the page we just opened has a bad scheme, we return nil here so that JavaScript does not // get a reference to it which it can return from window.open() - this will end up as a // CFErrorHTTPBadURL being presented. guard let scheme = (navigationAction.request as NSURLRequest).url?.scheme?.lowercased(), SchemesAllowedToOpenPopups.contains(scheme) else { return nil } return newTab.webView } fileprivate func canDisplayJSAlertForWebView(_ webView: WKWebView) -> Bool { // Only display a JS Alert if we are selected and there isn't anything being shown return ((tabManager.selectedTab == nil ? false : tabManager.selectedTab!.webView == webView)) && (self.presentedViewController == nil) } func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let messageAlert = MessageAlert(message: message, frame: frame, completionHandler: completionHandler) if canDisplayJSAlertForWebView(webView) { present(messageAlert.alertController(), animated: true, completion: nil) } else if let promptingTab = tabManager[webView] { promptingTab.queueJavascriptAlertPrompt(messageAlert) } else { // This should never happen since an alert needs to come from a web view but just in case call the handler // since not calling it will result in a runtime exception. completionHandler() } } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let confirmAlert = ConfirmPanelAlert(message: message, frame: frame, completionHandler: completionHandler) if canDisplayJSAlertForWebView(webView) { present(confirmAlert.alertController(), animated: true, completion: nil) } else if let promptingTab = tabManager[webView] { promptingTab.queueJavascriptAlertPrompt(confirmAlert) } else { completionHandler(false) } } func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { let textInputAlert = TextInputAlert(message: prompt, frame: frame, completionHandler: completionHandler, defaultText: defaultText) if canDisplayJSAlertForWebView(webView) { present(textInputAlert.alertController(), animated: true, completion: nil) } else if let promptingTab = tabManager[webView] { promptingTab.queueJavascriptAlertPrompt(textInputAlert) } else { completionHandler(nil) } } /// Invoked when an error occurs while starting to load data for the main frame. func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { // Ignore the "Frame load interrupted" error that is triggered when we cancel a request // to open an external application and hand it over to UIApplication.openURL(). The result // will be that we switch to the external app, for example the app store, while keeping the // original web page in the tab instead of replacing it with an error page. let error = error as NSError if error.domain == "WebKitErrorDomain" && error.code == 102 { return } if checkIfWebContentProcessHasCrashed(webView, error: error as NSError) { return } if error.code == Int(CFNetworkErrors.cfurlErrorCancelled.rawValue) { if let tab = tabManager[webView], tab === tabManager.selectedTab { urlBar.currentURL = tab.url?.displayURL } return } if let url = error.userInfo[NSURLErrorFailingURLErrorKey] as? URL { ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView) // If the local web server isn't working for some reason (Firefox cellular data is // disabled in settings, for example), we'll fail to load the session restore URL. // We rely on loading that page to get the restore callback to reset the restoring // flag, so if we fail to load that page, reset it here. if url.aboutComponent == "sessionrestore" { tabManager.tabs.filter { $0.webView == webView }.first?.restoring = false } } } fileprivate func checkIfWebContentProcessHasCrashed(_ webView: WKWebView, error: NSError) -> Bool { if error.code == WKError.webContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" { print("WebContent process has crashed. Trying to reloadFromOrigin to restart it.") webView.reloadFromOrigin() return true } return false } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { let helperForURL = OpenIn.helperForResponse(navigationResponse.response) if navigationResponse.canShowMIMEType { if let openInHelper = helperForURL { addViewForOpenInHelper(openInHelper) } decisionHandler(WKNavigationResponsePolicy.allow) return } guard var openInHelper = helperForURL else { let error = NSError(domain: ErrorPageHelper.MozDomain, code: Int(ErrorPageHelper.MozErrorDownloadsNotEnabled), userInfo: [NSLocalizedDescriptionKey: Strings.UnableToDownloadError]) ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.url!, inWebView: webView) return decisionHandler(WKNavigationResponsePolicy.allow) } if openInHelper.openInView == nil { openInHelper.openInView = navigationToolbar.menuButton } openInHelper.open() decisionHandler(WKNavigationResponsePolicy.cancel) } func webViewDidClose(_ webView: WKWebView) { if let tab = tabManager[webView] { self.tabManager.removeTab(tab) } } } extension BrowserViewController: ReaderModeDelegate { func readerMode(_ readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forTab tab: Tab) { // If this reader mode availability state change is for the tab that we currently show, then update // the button. Otherwise do nothing and the button will be updated when the tab is made active. if tabManager.selectedTab === tab { urlBar.updateReaderModeState(state) } } func readerMode(_ readerMode: ReaderMode, didDisplayReaderizedContentForTab tab: Tab) { self.showReaderModeBar(animated: true) tab.showContent(true) } } // MARK: - UIPopoverPresentationControllerDelegate extension BrowserViewController: UIPopoverPresentationControllerDelegate { func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { displayedPopoverController = nil updateDisplayedPopoverProperties = nil } } extension BrowserViewController: UIAdaptivePresentationControllerDelegate { // Returning None here makes sure that the Popover is actually presented as a Popover and // not as a full-screen modal, which is the default on compact device classes. func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return UIModalPresentationStyle.none } } // MARK: - ReaderModeStyleViewControllerDelegate extension BrowserViewController: ReaderModeStyleViewControllerDelegate { func readerModeStyleViewController(_ readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) { // Persist the new style to the profile let encodedStyle: [String: Any] = style.encodeAsDictionary() profile.prefs.setObject(encodedStyle, forKey: ReaderModeProfileKeyStyle) // Change the reader mode style on all tabs that have reader mode active for tabIndex in 0..<tabManager.count { if let tab = tabManager[tabIndex] { if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode { if readerMode.state == ReaderModeState.active { readerMode.style = style } } } } } } extension BrowserViewController { func updateReaderModeBar() { if let readerModeBar = readerModeBar { if let tab = self.tabManager.selectedTab, tab.isPrivate { readerModeBar.applyTheme(Theme.PrivateMode) } else { readerModeBar.applyTheme(Theme.NormalMode) } if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, let record = successValue { readerModeBar.unread = record.unread readerModeBar.added = true } else { readerModeBar.unread = true readerModeBar.added = false } } else { readerModeBar.unread = true readerModeBar.added = false } } } func showReaderModeBar(animated: Bool) { if self.readerModeBar == nil { let readerModeBar = ReaderModeBarView(frame: CGRect.zero) readerModeBar.delegate = self view.insertSubview(readerModeBar, belowSubview: header) self.readerModeBar = readerModeBar } updateReaderModeBar() self.updateViewConstraints() } func hideReaderModeBar(animated: Bool) { if let readerModeBar = self.readerModeBar { readerModeBar.removeFromSuperview() self.readerModeBar = nil self.updateViewConstraints() } } /// There are two ways we can enable reader mode. In the simplest case we open a URL to our internal reader mode /// and be done with it. In the more complicated case, reader mode was already open for this page and we simply /// navigated away from it. So we look to the left and right in the BackForwardList to see if a readerized version /// of the current page is there. And if so, we go there. func enableReaderMode() { guard let tab = tabManager.selectedTab, let webView = tab.webView else { return } let backList = webView.backForwardList.backList let forwardList = webView.backForwardList.forwardList guard let currentURL = webView.backForwardList.currentItem?.url, let readerModeURL = currentURL.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) else { return } if backList.count > 1 && backList.last?.url == readerModeURL { webView.go(to: backList.last!) } else if forwardList.count > 0 && forwardList.first?.url == readerModeURL { webView.go(to: forwardList.first!) } else { // Store the readability result in the cache and load it. This will later move to the ReadabilityHelper. webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in if let readabilityResult = ReadabilityResult(object: object as AnyObject?) { do { try self.readerModeCache.put(currentURL, readabilityResult) } catch _ { } if let nav = webView.load(PrivilegedRequest(url: readerModeURL) as URLRequest) { self.ignoreNavigationInTab(tab, navigation: nav) } } }) } } /// Disabling reader mode can mean two things. In the simplest case we were opened from the reading list, which /// means that there is nothing in the BackForwardList except the internal url for the reader mode page. In that /// case we simply open a new page with the original url. In the more complicated page, the non-readerized version /// of the page is either to the left or right in the BackForwardList. If that is the case, we navigate there. func disableReaderMode() { if let tab = tabManager.selectedTab, let webView = tab.webView { let backList = webView.backForwardList.backList let forwardList = webView.backForwardList.forwardList if let currentURL = webView.backForwardList.currentItem?.url { if let originalURL = currentURL.decodeReaderModeURL { if backList.count > 1 && backList.last?.url == originalURL { webView.go(to: backList.last!) } else if forwardList.count > 0 && forwardList.first?.url == originalURL { webView.go(to: forwardList.first!) } else { if let nav = webView.load(URLRequest(url: originalURL)) { self.ignoreNavigationInTab(tab, navigation: nav) } } } } } } func SELDynamicFontChanged(_ notification: Notification) { guard notification.name == NotificationDynamicFontChanged else { return } var readerModeStyle = DefaultReaderModeStyle if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) { if let style = ReaderModeStyle(dict: dict as [String: AnyObject]) { readerModeStyle = style } } readerModeStyle.fontSize = ReaderModeFontSize.defaultSize self.readerModeStyleViewController(ReaderModeStyleViewController(), didConfigureStyle: readerModeStyle) } } extension BrowserViewController: ReaderModeBarViewDelegate { func readerModeBar(_ readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) { switch buttonType { case .settings: if let readerMode = tabManager.selectedTab?.getHelper(name: "ReaderMode") as? ReaderMode, readerMode.state == ReaderModeState.active { var readerModeStyle = DefaultReaderModeStyle if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) { if let style = ReaderModeStyle(dict: dict as [String: AnyObject]) { readerModeStyle = style } } let readerModeStyleViewController = ReaderModeStyleViewController() readerModeStyleViewController.delegate = self readerModeStyleViewController.readerModeStyle = readerModeStyle readerModeStyleViewController.modalPresentationStyle = UIModalPresentationStyle.popover let setupPopover = { [unowned self] in if let popoverPresentationController = readerModeStyleViewController.popoverPresentationController { popoverPresentationController.backgroundColor = UIColor.white popoverPresentationController.delegate = self popoverPresentationController.sourceView = readerModeBar popoverPresentationController.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: UIConstants.ToolbarHeight, width: 1, height: 1) popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.up } } setupPopover() if readerModeStyleViewController.popoverPresentationController != nil { displayedPopoverController = readerModeStyleViewController updateDisplayedPopoverProperties = setupPopover } self.present(readerModeStyleViewController, animated: true, completion: nil) } case .markAsRead: if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, let record = successValue { profile.readingList?.updateRecord(record, unread: false) // TODO Check result, can this fail? readerModeBar.unread = false } } case .markAsUnread: if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, let record = successValue { profile.readingList?.updateRecord(record, unread: true) // TODO Check result, can this fail? readerModeBar.unread = true } } case .addToReadingList: if let tab = tabManager.selectedTab, let rawURL = tab.url, rawURL.isReaderModeURL, let url = rawURL.decodeReaderModeURL { profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) // TODO Check result, can this fail? readerModeBar.added = true readerModeBar.unread = true } case .removeFromReadingList: if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url), let successValue = result.successValue, let record = successValue { profile.readingList?.deleteRecord(record) // TODO Check result, can this fail? readerModeBar.added = false readerModeBar.unread = false } } } } extension BrowserViewController: IntroViewControllerDelegate { @discardableResult func presentIntroViewController(_ force: Bool = false, animated: Bool = true) -> Bool { if let deeplink = self.profile.prefs.stringForKey("AdjustDeeplinkKey"), let url = URL(string: deeplink) { self.launchFxAFromDeeplinkURL(url) return true } if force || profile.prefs.intForKey(IntroViewControllerSeenProfileKey) == nil { let introViewController = IntroViewController() introViewController.delegate = self // On iPad we present it modally in a controller if topTabsVisible { introViewController.preferredContentSize = CGSize(width: IntroViewControllerUX.Width, height: IntroViewControllerUX.Height) introViewController.modalPresentationStyle = UIModalPresentationStyle.formSheet } present(introViewController, animated: animated) { // On first run (and forced) open up the homepage in the background. if let homePageURL = HomePageAccessors.getHomePage(self.profile.prefs), let tab = self.tabManager.selectedTab, DeviceInfo.hasConnectivity() { tab.loadRequest(URLRequest(url: homePageURL)) } } return true } return false } func launchFxAFromDeeplinkURL(_ url: URL) { self.profile.prefs.removeObjectForKey("AdjustDeeplinkKey") var query = url.getQuery() query["entrypoint"] = "adjust_deepklink_ios" let fxaParams: FxALaunchParams fxaParams = FxALaunchParams(query: query) self.presentSignInViewController(fxaParams) } func introViewControllerDidFinish(_ introViewController: IntroViewController, requestToLogin: Bool) { self.profile.prefs.setInt(1, forKey: IntroViewControllerSeenProfileKey) introViewController.dismiss(animated: true) { finished in if self.navigationController?.viewControllers.count ?? 0 > 1 { _ = self.navigationController?.popToRootViewController(animated: true) } if requestToLogin { self.presentSignInViewController() } } } func presentSignInViewController(_ fxaOptions: FxALaunchParams? = nil) { // Show the settings page if we have already signed in. If we haven't then show the signin page let vcToPresent: UIViewController if profile.hasAccount() { let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = profile settingsTableViewController.tabManager = tabManager vcToPresent = settingsTableViewController } else { let signInVC = FxAContentViewController(profile: profile, fxaOptions: fxaOptions) signInVC.delegate = self signInVC.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(BrowserViewController.dismissSignInViewController)) vcToPresent = signInVC } let settingsNavigationController = SettingsNavigationController(rootViewController: vcToPresent) settingsNavigationController.modalPresentationStyle = .formSheet settingsNavigationController.navigationBar.isTranslucent = false self.present(settingsNavigationController, animated: true, completion: nil) } func dismissSignInViewController() { self.dismiss(animated: true, completion: nil) } } extension BrowserViewController: FxAContentViewControllerDelegate { func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags flags: FxALoginFlags) { if flags.verified { self.dismiss(animated: true, completion: nil) } } func contentViewControllerDidCancel(_ viewController: FxAContentViewController) { self.dismiss(animated: true, completion: nil) } } extension BrowserViewController: ContextMenuHelperDelegate { func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UIGestureRecognizer) { // locationInView can return (0, 0) when the long press is triggered in an invalid page // state (e.g., long pressing a link before the document changes, then releasing after a // different page loads). let touchPoint = gestureRecognizer.location(in: view) guard touchPoint != CGPoint.zero else { return } let touchSize = CGSize(width: 0, height: 16) let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet) var dialogTitle: String? if let url = elements.link, let currentTab = tabManager.selectedTab { dialogTitle = url.absoluteString let isPrivate = currentTab.isPrivate let addTab = { (rURL: URL, isPrivate: Bool) in let tab = self.tabManager.addTab(URLRequest(url: rURL as URL), afterTab: currentTab, isPrivate: isPrivate) LeanplumIntegration.sharedInstance.track(eventName: .openedNewTab, withParameters: ["Source": "Long Press Context Menu" as AnyObject]) guard !self.topTabsVisible else { return } // We're not showing the top tabs; show a toast to quick switch to the fresh new tab. let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in if buttonPressed { self.tabManager.selectTab(tab) } }) self.show(buttonToast: toast) } if !isPrivate { let newTabTitle = NSLocalizedString("Open in New Tab", comment: "Context menu item for opening a link in a new tab") let openNewTabAction = UIAlertAction(title: newTabTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) in addTab(url, false) } actionSheetController.addAction(openNewTabAction) } let openNewPrivateTabTitle = NSLocalizedString("Open in New Private Tab", tableName: "PrivateBrowsing", comment: "Context menu option for opening a link in a new private tab") let openNewPrivateTabAction = UIAlertAction(title: openNewPrivateTabTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) in addTab(url, true) } actionSheetController.addAction(openNewPrivateTabAction) let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard") let copyAction = UIAlertAction(title: copyTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in UIPasteboard.general.url = url as URL } actionSheetController.addAction(copyAction) let shareTitle = NSLocalizedString("Share Link", comment: "Context menu item for sharing a link URL") let shareAction = UIAlertAction(title: shareTitle, style: UIAlertActionStyle.default) { _ in self.presentActivityViewController(url as URL, sourceView: self.view, sourceRect: CGRect(origin: touchPoint, size: touchSize), arrowDirection: .any) } actionSheetController.addAction(shareAction) } if let url = elements.image { if dialogTitle == nil { dialogTitle = url.absoluteString } let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus() let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image") let saveImageAction = UIAlertAction(title: saveImageTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in if photoAuthorizeStatus == PHAuthorizationStatus.authorized || photoAuthorizeStatus == PHAuthorizationStatus.notDetermined { self.getImage(url as URL) { UIImageWriteToSavedPhotosAlbum($0, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil) } } else { let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: UIAlertControllerStyle.alert) let dismissAction = UIAlertAction(title: UIConstants.CancelString, style: UIAlertActionStyle.default, handler: nil) accessDenied.addAction(dismissAction) let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: UIAlertActionStyle.default ) { (action: UIAlertAction!) -> Void in UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:]) } accessDenied.addAction(settingsAction) self.present(accessDenied, animated: true, completion: nil) } } actionSheetController.addAction(saveImageAction) let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard") let copyAction = UIAlertAction(title: copyImageTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in // put the actual image on the clipboard // do this asynchronously just in case we're in a low bandwidth situation let pasteboard = UIPasteboard.general pasteboard.url = url as URL let changeCount = pasteboard.changeCount let application = UIApplication.shared var taskId: UIBackgroundTaskIdentifier = 0 taskId = application.beginBackgroundTask (expirationHandler: { _ in application.endBackgroundTask(taskId) }) Alamofire.request(url) .validate(statusCode: 200..<300) .response { response in // Only set the image onto the pasteboard if the pasteboard hasn't changed since // fetching the image; otherwise, in low-bandwidth situations, // we might be overwriting something that the user has subsequently added. if changeCount == pasteboard.changeCount, let imageData = response.data, response.error == nil { pasteboard.addImageWithData(imageData, forURL: url) } application.endBackgroundTask(taskId) } } actionSheetController.addAction(copyAction) } // If we're showing an arrow popup, set the anchor to the long press location. if let popoverPresentationController = actionSheetController.popoverPresentationController { popoverPresentationController.sourceView = view popoverPresentationController.sourceRect = CGRect(origin: touchPoint, size: touchSize) popoverPresentationController.permittedArrowDirections = .any popoverPresentationController.delegate = self } if actionSheetController.popoverPresentationController != nil { displayedPopoverController = actionSheetController } actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength) let cancelAction = UIAlertAction(title: UIConstants.CancelString, style: UIAlertActionStyle.cancel, handler: nil) actionSheetController.addAction(cancelAction) self.present(actionSheetController, animated: true, completion: nil) } fileprivate func getImage(_ url: URL, success: @escaping (UIImage) -> Void) { Alamofire.request(url) .validate(statusCode: 200..<300) .response { response in if let data = response.data, let image = UIImage.dataIsGIF(data) ? UIImage.imageFromGIFDataThreadSafe(data) : UIImage.imageFromDataThreadSafe(data) { success(image) } } } func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didCancelGestureRecognizer: UIGestureRecognizer) { displayedPopoverController?.dismiss(animated: true) { self.displayedPopoverController = nil } } } extension BrowserViewController { func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) { if error == nil { LeanplumIntegration.sharedInstance.track(eventName: .saveImage) } } } extension BrowserViewController: HistoryStateHelperDelegate { func historyStateHelper(_ historyStateHelper: HistoryStateHelper, didPushOrReplaceStateInTab tab: Tab) { navigateInTab(tab: tab) tabManager.storeChanges() } } /** A third party search engine Browser extension **/ extension BrowserViewController { func addCustomSearchButtonToWebView(_ webView: WKWebView) { //check if the search engine has already been added. let domain = webView.url?.domainURL.host let matches = self.profile.searchEngines.orderedEngines.filter {$0.shortName == domain} if !matches.isEmpty { self.customSearchEngineButton.tintColor = UIColor.gray self.customSearchEngineButton.isUserInteractionEnabled = false } else { self.customSearchEngineButton.tintColor = UIConstants.SystemBlueColor self.customSearchEngineButton.isUserInteractionEnabled = true } /* This is how we access hidden views in the WKContentView Using the public headers we can find the keyboard accessoryView which is not usually available. Specific values here are from the WKContentView headers. https://github.com/JaviSoto/iOS9-Runtime-Headers/blob/master/Frameworks/WebKit.framework/WKContentView.h */ guard let webContentView = UIView.findSubViewWithFirstResponder(webView) else { /* In some cases the URL bar can trigger the keyboard notification. In that case the webview isnt the first responder and a search button should not be added. */ return } guard let input = webContentView.perform(#selector(getter: UIResponder.inputAccessoryView)), let inputView = input.takeUnretainedValue() as? UIInputView, let nextButton = inputView.value(forKey: "_nextItem") as? UIBarButtonItem, let nextButtonView = nextButton.value(forKey: "view") as? UIView else { //failed to find the inputView instead lets use the inputAssistant addCustomSearchButtonToInputAssistant(webContentView) return } inputView.addSubview(self.customSearchEngineButton) self.customSearchEngineButton.snp.remakeConstraints { make in make.leading.equalTo(nextButtonView.snp.trailing).offset(20) make.width.equalTo(inputView.snp.height) make.top.equalTo(nextButtonView.snp.top) make.height.equalTo(inputView.snp.height) } } /** This adds the customSearchButton to the inputAssistant for cases where the inputAccessoryView could not be found for example on the iPad where it does not exist. However this only works on iOS9 **/ func addCustomSearchButtonToInputAssistant(_ webContentView: UIView) { guard customSearchBarButton == nil else { return //The searchButton is already on the keyboard } let inputAssistant = webContentView.inputAssistantItem let item = UIBarButtonItem(customView: customSearchEngineButton) customSearchBarButton = item inputAssistant.trailingBarButtonGroups.last?.barButtonItems.append(item) } func addCustomSearchEngineForFocusedElement() { guard let webView = tabManager.selectedTab?.webView else { return } webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in guard let searchQuery = result as? String, let favicon = self.tabManager.selectedTab!.displayFavicon else { //Javascript responded with an incorrectly formatted message. Show an error. let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } self.addSearchEngine(searchQuery, favicon: favicon) self.customSearchEngineButton.tintColor = UIColor.gray self.customSearchEngineButton.isUserInteractionEnabled = false } } func addSearchEngine(_ searchQuery: String, favicon: Favicon) { guard searchQuery != "", let iconURL = URL(string: favicon.url), let url = URL(string: searchQuery.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!), let shortName = url.domainURL.host else { let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } let alert = ThirdPartySearchAlerts.addThirdPartySearchEngine { alert in self.customSearchEngineButton.tintColor = UIColor.gray self.customSearchEngineButton.isUserInteractionEnabled = false SDWebImageManager.shared().loadImage(with: iconURL, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in guard let image = image else { let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } self.profile.searchEngines.addSearchEngine(OpenSearchEngine(engineID: nil, shortName: shortName, image: image, searchTemplate: searchQuery, suggestTemplate: nil, isCustomEngine: true)) let Toast = SimpleToast() Toast.showAlertWithText(Strings.ThirdPartySearchEngineAdded, bottomContainer: self.webViewContainer) } } self.present(alert, animated: true, completion: {}) } } extension BrowserViewController: KeyboardHelperDelegate { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { keyboardState = state updateViewConstraints() UIView.animate(withDuration: state.animationDuration) { UIView.setAnimationCurve(state.animationCurve) self.findInPageContainer.layoutIfNeeded() self.snackBars.layoutIfNeeded() } if let webView = tabManager.selectedTab?.webView { webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in guard let _ = result as? String else { return } self.addCustomSearchButtonToWebView(webView) } } } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { keyboardState = nil updateViewConstraints() //If the searchEngineButton exists remove it form the keyboard if let buttonGroup = customSearchBarButton?.buttonGroup { buttonGroup.barButtonItems = buttonGroup.barButtonItems.filter { $0 != customSearchBarButton } customSearchBarButton = nil } if self.customSearchEngineButton.superview != nil { self.customSearchEngineButton.removeFromSuperview() } UIView.animate(withDuration: state.animationDuration) { UIView.setAnimationCurve(state.animationCurve) self.findInPageContainer.layoutIfNeeded() self.snackBars.layoutIfNeeded() } } } extension BrowserViewController: SessionRestoreHelperDelegate { func sessionRestoreHelper(_ helper: SessionRestoreHelper, didRestoreSessionForTab tab: Tab) { tab.restoring = false if let tab = tabManager.selectedTab, tab.webView === tab.webView { updateUIForReaderHomeStateForTab(tab) } } } extension BrowserViewController: TabTrayDelegate { // This function animates and resets the tab chrome transforms when // the tab tray dismisses. func tabTrayDidDismiss(_ tabTray: TabTrayController) { resetBrowserChrome() } func tabTrayDidAddBookmark(_ tab: Tab) { guard let url = tab.url?.absoluteString, url.characters.count > 0 else { return } self.addBookmark(tab.tabState) } func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord? { guard let url = tab.url?.absoluteString, url.characters.count > 0 else { return nil } return profile.readingList?.createRecordWithURL(url, title: tab.title ?? url, addedBy: UIDevice.current.name).successValue } func tabTrayRequestsPresentationOf(_ viewController: UIViewController) { self.present(viewController, animated: false, completion: nil) } } // MARK: Browser Chrome Theming extension BrowserViewController: Themeable { func applyTheme(_ themeName: String) { let ui: [Themeable?] = [urlBar, toolbar, readerModeBar, topTabsViewController] ui.forEach { $0?.applyTheme(themeName) } statusBarOverlay.backgroundColor = shouldShowTopTabsForTraitCollection(traitCollection) ? UIColor(rgb: 0x272727) : urlBar.backgroundColor setNeedsStatusBarAppearanceUpdate() } } protocol Themeable { func applyTheme(_ themeName: String) } extension BrowserViewController: FindInPageBarDelegate, FindInPageHelperDelegate { func findInPage(_ findInPage: FindInPageBar, didTextChange text: String) { find(text, function: "find") } func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String) { findInPageBar?.endEditing(true) find(text, function: "findNext") } func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String) { findInPageBar?.endEditing(true) find(text, function: "findPrevious") } func findInPageDidPressClose(_ findInPage: FindInPageBar) { updateFindInPageVisibility(visible: false) } fileprivate func find(_ text: String, function: String) { guard let webView = tabManager.selectedTab?.webView else { return } let escaped = text.replacingOccurrences(of: "\\", with: "\\\\") .replacingOccurrences(of: "\"", with: "\\\"") webView.evaluateJavaScript("__firefox__.\(function)(\"\(escaped)\")", completionHandler: nil) } func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateCurrentResult currentResult: Int) { findInPageBar?.currentResult = currentResult } func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateTotalResults totalResults: Int) { findInPageBar?.totalResults = totalResults } } extension BrowserViewController: JSPromptAlertControllerDelegate { func promptAlertControllerDidDismiss(_ alertController: JSPromptAlertController) { showQueuedAlertIfAvailable() } } extension BrowserViewController: TopTabsDelegate { func topTabsDidPressTabs() { urlBar.leaveOverlayMode(didCancel: true) self.urlBarDidPressTabs(urlBar) } func topTabsDidPressNewTab(_ isPrivate: Bool) { openBlankNewTab(focusLocationField: false, isPrivate: isPrivate) } func topTabsDidTogglePrivateMode() { guard let selectedTab = tabManager.selectedTab else { return } urlBar.leaveOverlayMode() } func topTabsDidChangeTab() { urlBar.leaveOverlayMode(didCancel: true) } } extension BrowserViewController: ClientPickerViewControllerDelegate, InstructionsViewControllerDelegate { func instructionsViewControllerDidClose(_ instructionsViewController: InstructionsViewController) { self.popToBVC() } func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) { self.popToBVC() } func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) { guard let tab = tabManager.selectedTab, let url = tab.canonicalURL?.displayURL?.absoluteString else { return } let shareItem = ShareItem(url: url, title: tab.title, favicon: tab.displayFavicon) guard shareItem.isShareable else { let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.popToBVC()}) present(alert, animated: true, completion: nil) return } profile.sendItems([shareItem], toClients: clients).uponQueue(DispatchQueue.main) { _ in self.popToBVC() } } }
883e3118117e0330282c6ba68576aee4
43.348398
406
0.65786
false
false
false
false
CSSE497/pathfinder-ios
refs/heads/master
examples/Chimney Swap/Chimney Swap/EmployeeLoginViewController.swift
mit
1
// // EmployeeLoginViewController.swift // Chimney Swap // // Created by Adam Michael on 11/8/15. // Copyright © 2015 Pathfinder. All rights reserved. // import Foundation class EmployeeLoginViewController : UIViewController { @IBAction func signInEmployee() { let interfaceManager = GITInterfaceManager() interfaceManager.delegate = self GITClient.sharedInstance().delegate = self interfaceManager.startSignIn() } } extension EmployeeLoginViewController : GITInterfaceManagerDelegate, GITClientDelegate { func client(client: GITClient!, didFinishSignInWithToken token: String!, account: GITAccount!, error: NSError!) { print("GIT finished sign in and returned token \(token) for account \(account) with error \(error)") let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setObject(token, forKey: "employeeToken") userDefaults.synchronize() self.performSegueWithIdentifier("signInEmployee", sender: token) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let destination = (segue.destinationViewController) as! EmployeeViewController destination.idToken = sender as! String } }
d5ed37dbd3dc5e60e10c2f60a0be6523
33.114286
115
0.760268
false
false
false
false
ifabijanovic/RxBattleNet
refs/heads/master
RxBattleNet/WoW/Model/GuildReward.swift
mit
1
// // GuildReward.swift // RxBattleNet // // Created by Ivan Fabijanović on 06/08/16. // Copyright © 2016 Ivan Fabijanovic. All rights reserved. // import SwiftyJSON public extension WoW { public struct GuildReward: Model { // MARK: - Properties public let minGuildLevel: Int public let minGuildRepLevel: Int public let races: [Int] public let achievement: WoW.Achievement public let item: WoW.Item // MARK: - Init internal init(json: JSON) { self.minGuildLevel = json["minGuildLevel"].intValue self.minGuildRepLevel = json["minGuildRepLevel"].intValue self.races = json["races"].map { $1.intValue } self.achievement = WoW.Achievement(json: json["achievement"]) self.item = WoW.Item(json: json["item"]) } } }
77342a0c51a35d0ba9684d77839c5f02
25
73
0.579121
false
false
false
false
JTExperiments/SwiftBoxCollectionViewLayout
refs/heads/master
SwiftBox/Layout.swift
bsd-3-clause
4
// // Layout.swift // SwiftBox // // Created by Josh Abernathy on 1/30/15. // Copyright (c) 2015 Josh Abernathy. All rights reserved. // import Foundation /// An evaluated layout. /// /// Layouts may not be created manually. They only ever come from laying out a /// Node. See Node.layout. public struct Layout { public let frame: CGRect public let children: [Layout] internal init(frame: CGRect, children: [Layout]) { self.frame = frame self.children = children } } extension Layout: Printable { public var description: String { return descriptionForDepth(0) } private func descriptionForDepth(depth: Int) -> String { let selfDescription = "{origin={\(frame.origin.x), \(frame.origin.y)}, size={\(frame.size.width), \(frame.size.height)}}" if children.count > 0 { let indentation = reduce(0...depth, "\n") { accum, _ in accum + "\t" } let childrenDescription = indentation.join(children.map { $0.descriptionForDepth(depth + 1) }) return "\(selfDescription)\(indentation)\(childrenDescription)" } else { return selfDescription } } }
5271951a5b6e8a9198ae768b345aa660
25.95
123
0.687384
false
false
false
false
Azuritul/AZDropdownMenu
refs/heads/develop
Example/AZDropdownMenu/AppDelegate.swift
mit
1
// // AppDelegate.swift // AZDropdownMenu // // Created by Chris Wu on 01/05/2016. // Copyright (c) 2016 Chris Wu. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let rootViewController = ViewController() let nav = UINavigationController(rootViewController: rootViewController) self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.tintColor = UIColor.black self.window!.rootViewController = nav self.window!.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } }
7f9136072dc34d184e38a6a482ce0d56
24.354167
144
0.714873
false
false
false
false
Urinx/SomeCodes
refs/heads/master
Swift/swiftDemo/SpriteKit/hello/hello/GameViewController.swift
gpl-2.0
1
// // GameViewController.swift // hello // // Created by Eular on 15/4/23. // Copyright (c) 2015年 Eular. All rights reserved. // import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : String) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)! var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
597ddf5bcb9270aac1e2858ecb72db09
29.898551
104
0.621951
false
false
false
false
acumenrev/CANNavApp
refs/heads/master
CANNavApp/CANNavApp/Classes/ViewControllers/SearchViewController.swift
apache-2.0
1
// // SearchViewController.swift // CANNavApp // // Created by Tri Vo on 7/15/16. // Copyright © 2016 acumenvn. All rights reserved. // import UIKit import QuartzCore import CoreLocation import Alamofire protocol SearchViewControllerDelegate { func searchViewController(viewController: SearchViewController, choseLocation location : MyLocation, forFromAddress boolValue : Bool) -> Void } class SearchViewController: UIViewController { var mSearchRequest : Alamofire.Request? = nil var mLastTimeSendRequest : NSTimeInterval = 0 @IBOutlet var mViewMap: UIView! @IBOutlet var mMapView: GMSMapView! @IBOutlet var mViewPick: UIView! @IBOutlet var mTblViewMain: UITableView! @IBOutlet var mViewSearchAddress: UIView! @IBOutlet var mTxtSearch: UITextField! @IBOutlet var mViewSearchModeText: UIView! @IBOutlet var mViewSearchModeMap: UIView! var mMarker : GMSMarker? = nil var mListAddress : Array<QueryLocationResultModel> = Array<QueryLocationResultModel>() var mDelegate : SearchViewControllerDelegate? = nil var mMyLocation : MyLocation? var mSearchForFromAddress : Bool = false var bSearchModeMapActive : Bool = true let mSelectedColor : UIColor = UIColor(red: 255/255, green: 214/255, blue: 92/255, alpha: 1) init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?, delegate: SearchViewControllerDelegate?, locationInfo : MyLocation?, searchForFromAddress : Bool) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.mDelegate = delegate self.mMyLocation = locationInfo self.mSearchForFromAddress = searchForFromAddress } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. registerNibs() // setup UI setupUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Other methods /** Setup UI */ func setupUI() -> Void { mViewPick.layer.cornerRadius = 12.0 mViewPick.clipsToBounds = true refreshSearchModeBar() setupMapView() // setup marker setupMarker() self.view.sendSubviewToBack(mViewSearchAddress) self.view.bringSubviewToFront(mViewMap) } /** Setup MapView */ func setupMapView() -> Void { // config Google Maps mMapView.userInteractionEnabled = true mMapView.mapType = kGMSTypeNormal mMapView.settings.myLocationButton = false mMapView.myLocationEnabled = false mMapView.settings.compassButton = true mMapView.settings.zoomGestures = true mMapView.settings.scrollGestures = true mMapView.settings.indoorPicker = false mMapView.settings.tiltGestures = false mMapView.settings.rotateGestures = true mMapView.delegate = self } /** Setup marker */ func setupMarker() -> Void { if mMarker == nil { mMarker = GMSMarker() mMarker?.map = mMapView mMarker?.icon = UIImage(named: "default_marker") mMarker?.title = "" mMarker?.zIndex = 1 if mMyLocation != nil { mMarker?.position = (mMyLocation?.mLocationCoordinate)! // animate map move to user location mMapView.camera = GMSCameraPosition.cameraWithTarget((mMyLocation?.mLocationCoordinate)!, zoom: 16) } else { recenterMarkerInMapView() } } } /** Register nibs for table view */ func registerNibs() -> Void { mTblViewMain.registerCellNib(SearchTableViewCell.self) } /** Refresh search mode bar */ func refreshSearchModeBar() -> Void { mViewSearchModeMap.backgroundColor = UIColor.clearColor() mViewSearchModeText.backgroundColor = UIColor.clearColor() if bSearchModeMapActive == false { mViewSearchModeText.backgroundColor = mSelectedColor } else { mViewSearchModeMap.backgroundColor = mSelectedColor } } // MARK: - Actions @IBAction func btnSet_Touched(sender: AnyObject) { let newLocation = MyLocation(location: mMarker!.position, name: mTxtSearch.text!) if self.mDelegate != nil { self.mDelegate?.searchViewController(self, choseLocation: newLocation, forFromAddress: mSearchForFromAddress) } self.dismissViewControllerAnimated(true) { } } @IBAction func btnBack_Touched(sender: AnyObject) { self.view.endEditing(true) self.dismissViewControllerAnimated(true) { } } @IBAction func btnSearchMap_Touched(sender: AnyObject) { bSearchModeMapActive = true mViewSearchAddress.hidden = true mViewMap.hidden = false self.view.sendSubviewToBack(mViewSearchAddress) self.view.bringSubviewToFront(mViewMap) self.view.endEditing(true) refreshSearchModeBar() } @IBAction func btnSearchAddress_Touched(sender: AnyObject) { bSearchModeMapActive = false mViewSearchAddress.hidden = false mViewMap.hidden = true self.view.sendSubviewToBack(mViewMap) self.view.bringSubviewToFront(mViewSearchAddress) refreshSearchModeBar() // active keyboard mTxtSearch.becomeFirstResponder() } } // MARK: - TextField Delegate extension SearchViewController : UITextFieldDelegate { func textFieldShouldBeginEditing(textField: UITextField) -> Bool { mViewSearchAddress.hidden = false mViewMap.hidden = true bSearchModeMapActive = false refreshSearchModeBar() return true } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let range = range.stringRangeForText(textField.text!) let output = textField.text!.stringByReplacingCharactersInRange(range, withString: string) if output.length > 3 { // send request let currentTimeInMs = NSDate().timeIntervalSince1970 if (currentTimeInMs - mLastTimeSendRequest) > 2 { // time gap between 2 requests must be greater than 2 seconds if TUtilsSwift.appDelegate().bCanReachInternet == true { NetworkManager.sharedInstance.queryLatLongBasedOnAddress(output, completion: { (locationResults) in if self.mListAddress.count > 0 { self.mListAddress.removeAll() } self.mListAddress += locationResults // reload table data self.mTblViewMain.reloadData() }, fail: { (failError) in }) } else { self.navigationController?.presentViewController(self.showNoInternetConnectionMessage(), animated: true, completion: nil) } } } else { mListAddress.removeAll() mTblViewMain.reloadData() } return true } } // MARK: - GMSMapView Delegate extension SearchViewController : GMSMapViewDelegate { func mapView(mapView: GMSMapView, willMove gesture: Bool) { mViewPick.hidden = true self.recenterMarkerInMapView() // resign text field self.view.endEditing(true) } func mapView(mapView: GMSMapView, idleAtCameraPosition position: GMSCameraPosition) { mViewPick.hidden = false if mSearchRequest != nil { // cancel previous request mSearchRequest?.cancel() } // request location if TUtilsSwift.appDelegate().bCanReachInternet == true { // request NetworkManager.sharedInstance.queryAddressBasedOnLatLng(position.target.latitude, lngValue: position.target.longitude, completion: { (locationResult) in self.mTxtSearch.text = locationResult?.formattedAddress }, fail: { (failError) in }) } } func mapView(mapView: GMSMapView, didChangeCameraPosition position: GMSCameraPosition) { self.recenterMarkerInMapView() } func recenterMarkerInMapView() -> Void { // get the center of mapview let center = mMapView.convertPoint(mMapView.center, fromView: mViewMap) // reset ther marker position so it moves without animation mMapView.clear() mMarker?.appearAnimation = kGMSMarkerAnimationNone mMarker?.position = mMapView.projection.coordinateForPoint(center) mMarker?.map = mMapView } } // MARK: - UIScrollView Delegate extension SearchViewController : UIScrollViewDelegate { func scrollViewWillBeginDragging(scrollView: UIScrollView) { self.view.endEditing(true) } } // MARK: - UITableView Delegate extension SearchViewController : UITableViewDelegate, UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mListAddress.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("SearchTableViewCell", forIndexPath: indexPath) as! SearchTableViewCell cell.selectionStyle = .Gray let location = self.mListAddress[indexPath.row] cell.setAddress(location.formattedAddress!) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) self.view.endEditing(true) let location = self.mListAddress[indexPath.row] if self.mDelegate != nil { self.mDelegate?.searchViewController(self, choseLocation: MyLocation(location: CLLocationCoordinate2DMake(location.lat!, location.lng!), name: location.formattedAddress!), forFromAddress: self.mSearchForFromAddress) } self.dismissViewControllerAnimated(true) { } } }
5d2f4d7e454ad191d603d78ed39ebaab
31.242775
227
0.625224
false
false
false
false
tjw/swift
refs/heads/master
test/SILGen/indirect_enum.swift
apache-2.0
1
// RUN: %target-swift-frontend -module-name indirect_enum -Xllvm -sil-print-debuginfo -emit-silgen %s | %FileCheck %s indirect enum TreeA<T> { case Nil case Leaf(T) case Branch(left: TreeA<T>, right: TreeA<T>) } // CHECK-LABEL: sil hidden @$S13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF : $@convention(thin) <T> (@in_guaranteed T, @guaranteed TreeA<T>, @guaranteed TreeA<T>) -> () { func TreeA_cases<T>(_ t: T, l: TreeA<T>, r: TreeA<T>) { // CHECK: bb0([[ARG1:%.*]] : $*T, [[ARG2:%.*]] : $TreeA<T>, [[ARG3:%.*]] : $TreeA<T>): // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[NIL:%.*]] = enum $TreeA<T>, #TreeA.Nil!enumelt // CHECK-NOT: destroy_value [[NIL]] let _ = TreeA<T>.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: copy_addr [[ARG1]] to [initialization] [[PB]] // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<T>, #TreeA.Leaf!enumelt.1, [[BOX]] // CHECK-NEXT: destroy_value [[LEAF]] let _ = TreeA<T>.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 0 // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 1 // CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] // CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]] // CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]] // CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]] // CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeA<T>, #TreeA.Branch!enumelt.1, [[BOX]] // CHECK-NEXT: destroy_value [[BRANCH]] let _ = TreeA<T>.Branch(left: l, right: r) } // CHECK: // end sil function '$S13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF' // CHECK-LABEL: sil hidden @$S13indirect_enum16TreeA_reabstractyyS2icF : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> Int) -> () { func TreeA_reabstract(_ f: @escaping (Int) -> Int) { // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed (Int) -> Int): // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<(Int) -> Int>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <(Int) -> Int> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[THUNK:%.*]] = function_ref @$SS2iIegyd_S2iIegnr_TR // CHECK-NEXT: [[FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[ARG_COPY]]) // CHECK-NEXT: store [[FN]] to [init] [[PB]] // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<(Int) -> Int>, #TreeA.Leaf!enumelt.1, [[BOX]] // CHECK-NEXT: destroy_value [[LEAF]] // CHECK: return let _ = TreeA<(Int) -> Int>.Leaf(f) } // CHECK: } // end sil function '$S13indirect_enum16TreeA_reabstractyyS2icF' enum TreeB<T> { case Nil case Leaf(T) indirect case Branch(left: TreeB<T>, right: TreeB<T>) } // CHECK-LABEL: sil hidden @$S13indirect_enum11TreeB_cases_1l1ryx_AA0C1BOyxGAGtlF func TreeB_cases<T>(_ t: T, l: TreeB<T>, r: TreeB<T>) { // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK: [[NIL:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: inject_enum_addr [[NIL]] : $*TreeB<T>, #TreeB.Nil!enumelt // CHECK-NEXT: destroy_addr [[NIL]] // CHECK-NEXT: dealloc_stack [[NIL]] let _ = TreeB<T>.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK-NEXT: [[LEAF:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt // CHECK-NEXT: destroy_addr [[LEAF]] // CHECK-NEXT: dealloc_stack [[LEAF]] let _ = TreeB<T>.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeB<τ_0_0>, right: TreeB<τ_0_0>) } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: copy_addr %1 to [initialization] [[LEFT]] : $*TreeB<T> // CHECK-NEXT: copy_addr %2 to [initialization] [[RIGHT]] : $*TreeB<T> // CHECK-NEXT: [[BRANCH:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[BRANCH]] // CHECK-NEXT: store [[BOX]] to [init] [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[BRANCH]] : $*TreeB<T>, #TreeB.Branch!enumelt.1 // CHECK-NEXT: destroy_addr [[BRANCH]] // CHECK-NEXT: dealloc_stack [[BRANCH]] let _ = TreeB<T>.Branch(left: l, right: r) // CHECK: return } // CHECK-LABEL: sil hidden @$S13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF : $@convention(thin) (Int, @guaranteed TreeInt, @guaranteed TreeInt) -> () func TreeInt_cases(_ t: Int, l: TreeInt, r: TreeInt) { // CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $TreeInt, [[ARG3:%.*]] : $TreeInt): // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[NIL:%.*]] = enum $TreeInt, #TreeInt.Nil!enumelt // CHECK-NOT: destroy_value [[NIL]] let _ = TreeInt.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeInt, #TreeInt.Leaf!enumelt.1, [[ARG1]] // CHECK-NOT: destroy_value [[LEAF]] let _ = TreeInt.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box ${ var (left: TreeInt, right: TreeInt) } // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] // CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]] // CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]] // CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]] // CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeInt, #TreeInt.Branch!enumelt.1, [[BOX]] // CHECK-NEXT: destroy_value [[BRANCH]] let _ = TreeInt.Branch(left: l, right: r) } // CHECK: } // end sil function '$S13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF' enum TreeInt { case Nil case Leaf(Int) indirect case Branch(left: TreeInt, right: TreeInt) } enum TrivialButIndirect { case Direct(Int) indirect case Indirect(Int) } func a() {} func b<T>(_ x: T) {} func c<T>(_ x: T, _ y: T) {} func d() {} // CHECK-LABEL: sil hidden @$S13indirect_enum11switchTreeAyyAA0D1AOyxGlF : $@convention(thin) <T> (@guaranteed TreeA<T>) -> () { func switchTreeA<T>(_ x: TreeA<T>) { // CHECK: bb0([[ARG:%.*]] : $TreeA<T>): // -- x +2 // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, // CHECK: case #TreeA.Nil!enumelt: [[NIL_CASE:bb1]], // CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE:bb2]], // CHECK: case #TreeA.Branch!enumelt.1: [[BRANCH_CASE:bb3]], switch x { // CHECK: [[NIL_CASE]]: // CHECK: function_ref @$S13indirect_enum1ayyF // CHECK: br [[OUTER_CONT:bb[0-9]+]] case .Nil: a() // CHECK: [[LEAF_CASE]]([[LEAF_BOX:%.*]] : $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[VALUE:%.*]] = project_box [[LEAF_BOX]] // CHECK: copy_addr [[VALUE]] to [initialization] [[X:%.*]] : $*T // CHECK: function_ref @$S13indirect_enum1b{{[_0-9a-zA-Z]*}}F // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // -- x +1 // CHECK: destroy_value [[LEAF_BOX]] // CHECK: br [[OUTER_CONT]] case .Leaf(let x): b(x) // CHECK: [[BRANCH_CASE]]([[NODE_BOX:%.*]] : $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>): // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[NODE_BOX]] // CHECK: [[TUPLE:%.*]] = load_borrow [[TUPLE_ADDR]] // CHECK: [[LEFT:%.*]] = tuple_extract [[TUPLE]] {{.*}}, 0 // CHECK: [[RIGHT:%.*]] = tuple_extract [[TUPLE]] {{.*}}, 1 // CHECK: switch_enum [[LEFT]] : $TreeA<T>, // CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE_LEFT:bb[0-9]+]], // CHECK: default [[FAIL_LEFT:bb[0-9]+]] // CHECK: [[LEAF_CASE_LEFT]]([[LEFT_LEAF_BOX:%.*]] : $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[LEFT_LEAF_VALUE:%.*]] = project_box [[LEFT_LEAF_BOX]] // CHECK: switch_enum [[RIGHT]] : $TreeA<T>, // CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE_RIGHT:bb[0-9]+]], // CHECK: default [[FAIL_RIGHT:bb[0-9]+]] // CHECK: [[LEAF_CASE_RIGHT]]([[RIGHT_LEAF_BOX:%.*]] : $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[RIGHT_LEAF_VALUE:%.*]] = project_box [[RIGHT_LEAF_BOX]] // CHECK: copy_addr [[LEFT_LEAF_VALUE]] // CHECK: copy_addr [[RIGHT_LEAF_VALUE]] // -- x +1 // CHECK: destroy_value [[NODE_BOX]] // CHECK: br [[OUTER_CONT]] // CHECK: [[FAIL_RIGHT]]: // CHECK: br [[DEFAULT:bb[0-9]+]] // CHECK: [[FAIL_LEFT]]: // CHECK: br [[DEFAULT]] case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) // CHECK: [[DEFAULT]]: // -- x +1 // CHECK: destroy_value [[ARG_COPY]] default: d() } // CHECK: [[OUTER_CONT:%.*]]: // -- x +0 } // CHECK: } // end sil function '$S13indirect_enum11switchTreeAyyAA0D1AOyxGlF' // CHECK-LABEL: sil hidden @$S13indirect_enum11switchTreeB{{[_0-9a-zA-Z]*}}F func switchTreeB<T>(_ x: TreeB<T>) { // CHECK: copy_addr %0 to [initialization] [[SCRATCH:%.*]] : // CHECK: switch_enum_addr [[SCRATCH]] switch x { // CHECK: bb{{.*}}: // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: function_ref @$S13indirect_enum1ayyF // CHECK: br [[OUTER_CONT:bb[0-9]+]] case .Nil: a() // CHECK: bb{{.*}}: // CHECK: copy_addr [[SCRATCH]] to [initialization] [[LEAF_COPY:%.*]] : // CHECK: [[LEAF_ADDR:%.*]] = unchecked_take_enum_data_addr [[LEAF_COPY]] // CHECK: copy_addr [take] [[LEAF_ADDR]] to [initialization] [[LEAF:%.*]] : // CHECK: function_ref @$S13indirect_enum1b{{[_0-9a-zA-Z]*}}F // CHECK: destroy_addr [[LEAF]] // CHECK: dealloc_stack [[LEAF]] // CHECK-NOT: destroy_addr [[LEAF_COPY]] // CHECK: dealloc_stack [[LEAF_COPY]] // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: br [[OUTER_CONT]] case .Leaf(let x): b(x) // CHECK: bb{{.*}}: // CHECK: copy_addr [[SCRATCH]] to [initialization] [[TREE_COPY:%.*]] : // CHECK: [[TREE_ADDR:%.*]] = unchecked_take_enum_data_addr [[TREE_COPY]] // -- box +1 immutable // CHECK: [[BOX:%.*]] = load [take] [[TREE_ADDR]] // CHECK: [[TUPLE:%.*]] = project_box [[BOX]] // CHECK: [[LEFT:%.*]] = tuple_element_addr [[TUPLE]] // CHECK: [[RIGHT:%.*]] = tuple_element_addr [[TUPLE]] // CHECK: switch_enum_addr [[LEFT]] {{.*}}, default [[LEFT_FAIL:bb[0-9]+]] // CHECK: bb{{.*}}: // CHECK: copy_addr [[LEFT]] to [initialization] [[LEFT_COPY:%.*]] : // CHECK: [[LEFT_LEAF:%.*]] = unchecked_take_enum_data_addr [[LEFT_COPY]] : $*TreeB<T>, #TreeB.Leaf // CHECK: switch_enum_addr [[RIGHT]] {{.*}}, default [[RIGHT_FAIL:bb[0-9]+]] // CHECK: bb{{.*}}: // CHECK: copy_addr [[RIGHT]] to [initialization] [[RIGHT_COPY:%.*]] : // CHECK: [[RIGHT_LEAF:%.*]] = unchecked_take_enum_data_addr [[RIGHT_COPY]] : $*TreeB<T>, #TreeB.Leaf // CHECK: copy_addr [take] [[LEFT_LEAF]] to [initialization] [[X:%.*]] : // CHECK: copy_addr [take] [[RIGHT_LEAF]] to [initialization] [[Y:%.*]] : // CHECK: function_ref @$S13indirect_enum1c{{[_0-9a-zA-Z]*}}F // CHECK: destroy_addr [[Y]] // CHECK: dealloc_stack [[Y]] // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // CHECK-NOT: destroy_addr [[RIGHT_COPY]] // CHECK: dealloc_stack [[RIGHT_COPY]] // CHECK-NOT: destroy_addr [[LEFT_COPY]] // CHECK: dealloc_stack [[LEFT_COPY]] // -- box +0 // CHECK: destroy_value [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) // CHECK: [[RIGHT_FAIL]]: // CHECK: destroy_addr [[LEFT_LEAF]] // CHECK-NOT: destroy_addr [[LEFT_COPY]] // CHECK: dealloc_stack [[LEFT_COPY]] // CHECK: destroy_value [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[LEFT_FAIL]]: // CHECK: destroy_value [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[INNER_CONT]]: // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: function_ref @$S13indirect_enum1dyyF // CHECK: br [[OUTER_CONT]] default: d() } // CHECK: [[OUTER_CONT]]: // CHECK: return } // CHECK-LABEL: sil hidden @$S13indirect_enum10guardTreeA{{[_0-9a-zA-Z]*}}F func guardTreeA<T>(_ tree: TreeA<T>) { // CHECK: bb0([[ARG:%.*]] : $TreeA<T>): do { // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]: guard case .Nil = tree else { return } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]([[BOX:%.*]] : $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]] // CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]] // CHECK: destroy_value [[BOX]] guard case .Leaf(let x) = tree else { return } // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]([[BOX:%.*]] : $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TUPLE:%.*]] = load [take] [[VALUE_ADDR]] // CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]] // CHECK: [[BORROWED_TUPLE_COPY:%.*]] = begin_borrow [[TUPLE_COPY]] // CHECK: [[L:%.*]] = tuple_extract [[BORROWED_TUPLE_COPY]] // CHECK: [[COPY_L:%.*]] = copy_value [[L]] // CHECK: [[R:%.*]] = tuple_extract [[BORROWED_TUPLE_COPY]] // CHECK: [[COPY_R:%.*]] = copy_value [[R]] // CHECK: end_borrow [[BORROWED_TUPLE_COPY]] from [[TUPLE_COPY]] // CHECK: destroy_value [[TUPLE_COPY]] // CHECK: destroy_value [[BOX]] guard case .Branch(left: let l, right: let r) = tree else { return } // CHECK: destroy_value [[COPY_R]] // CHECK: destroy_value [[COPY_L]] // CHECK: destroy_addr [[X]] } do { // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]: // CHECK: br if case .Nil = tree { } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]([[BOX:%.*]] : $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]] // CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]] // CHECK: destroy_value [[BOX]] // CHECK: destroy_addr [[X]] if case .Leaf(let x) = tree { } // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]([[BOX:%.*]] : $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TUPLE:%.*]] = load [take] [[VALUE_ADDR]] // CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]] // CHECK: [[BORROWED_TUPLE_COPY:%.*]] = begin_borrow [[TUPLE_COPY]] // CHECK: [[L:%.*]] = tuple_extract [[BORROWED_TUPLE_COPY]] // CHECK: [[COPY_L:%.*]] = copy_value [[L]] // CHECK: [[R:%.*]] = tuple_extract [[BORROWED_TUPLE_COPY]] // CHECK: [[COPY_R:%.*]] = copy_value [[R]] // CHECK: end_borrow [[BORROWED_TUPLE_COPY]] from [[TUPLE_COPY]] // CHECK: destroy_value [[TUPLE_COPY]] // CHECK: destroy_value [[BOX]] // CHECK: destroy_value [[COPY_R]] // CHECK: destroy_value [[COPY_L]] if case .Branch(left: let l, right: let r) = tree { } } } // CHECK-LABEL: sil hidden @$S13indirect_enum10guardTreeB{{[_0-9a-zA-Z]*}}F func guardTreeB<T>(_ tree: TreeB<T>) { do { // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: destroy_addr [[TMP]] guard case .Nil = tree else { return } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]] // CHECK: dealloc_stack [[TMP]] guard case .Leaf(let x) = tree else { return } // CHECK: [[L:%.*]] = alloc_stack $TreeB // CHECK: [[R:%.*]] = alloc_stack $TreeB // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]] // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]] // CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] : // CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]] // CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]] // CHECK: destroy_value [[BOX]] guard case .Branch(left: let l, right: let r) = tree else { return } // CHECK: destroy_addr [[R]] // CHECK: destroy_addr [[L]] // CHECK: destroy_addr [[X]] } do { // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: destroy_addr [[TMP]] if case .Nil = tree { } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]] // CHECK: dealloc_stack [[TMP]] // CHECK: destroy_addr [[X]] if case .Leaf(let x) = tree { } // CHECK: [[L:%.*]] = alloc_stack $TreeB // CHECK: [[R:%.*]] = alloc_stack $TreeB // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]] // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]] // CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] : // CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]] // CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]] // CHECK: destroy_value [[BOX]] // CHECK: destroy_addr [[R]] // CHECK: destroy_addr [[L]] if case .Branch(left: let l, right: let r) = tree { } } } // SEMANTIC ARC TODO: This test needs to be made far more comprehensive. // CHECK-LABEL: sil hidden @$S13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF : $@convention(thin) (@guaranteed TrivialButIndirect) -> () { func dontDisableCleanupOfIndirectPayload(_ x: TrivialButIndirect) { // CHECK: bb0([[ARG:%.*]] : $TrivialButIndirect): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Direct!enumelt.1: [[YES:bb[0-9]+]], case #TrivialButIndirect.Indirect!enumelt.1: [[NO:bb[0-9]+]] // // CHECK: [[NO]]([[PAYLOAD:%.*]] : ${ var Int }): // CHECK: destroy_value [[PAYLOAD]] guard case .Direct(let foo) = x else { return } // CHECK: [[YES]]({{%.*}} : $Int): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Indirect!enumelt.1: [[YES:bb[0-9]+]], case #TrivialButIndirect.Direct!enumelt.1: [[NO:bb[0-9]+]] // CHECK: [[NO]]({{%.*}} : $Int): // CHECK-NOT: destroy_value // CHECK: [[YES]]([[BOX:%.*]] : ${ var Int }): // CHECK: destroy_value [[BOX]] guard case .Indirect(let bar) = x else { return } } // CHECK: } // end sil function '$S13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF'
c51c42c2967c1f3b2161f432fc8f160d
44.92278
184
0.536447
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Legacy/Neocom/Neocom/DgmTypePickerPresenter.swift
lgpl-2.1
2
// // DgmTypePickerPresenter.swift // Neocom // // Created by Artem Shimanski on 11/30/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import CloudData class DgmTypePickerPresenter: Presenter { typealias View = DgmTypePickerViewController typealias Interactor = DgmTypePickerInteractor weak var view: View? lazy var interactor: Interactor! = Interactor(presenter: self) required init(view: View) { self.view = view } func configure() { interactor.configure() applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in self?.applicationWillEnterForeground() } } private var applicationWillEnterForegroundObserver: NotificationObserver? }
48704af8871e012657cb30c3f07f097c
26.290323
200
0.776596
false
true
false
false
hirohisa/PageController
refs/heads/master
Example project/Example/UseStoryboardContentViewController.swift
mit
1
// // UseStoryboardContentViewController.swift // Example // // Created by Hirohisa Kawasaki on 2018/08/23. // Copyright © 2018 Hirohisa Kawasaki. All rights reserved. // import UIKit class TableViewCell: UITableViewCell { @IBOutlet weak var label: UILabel! } class UseStoryboardContentViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false tableView.backgroundColor = .blue view.backgroundColor = .red print(#function) print(tableView.frame) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print(#function) print(tableView.frame) print(tableView.contentInset) print(tableView.contentOffset) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // XXX: index 0, set wrong frame size to tableView if #available(iOS 11.0, *) {} else { if tableView.frame != view.bounds { tableView.frame = view.bounds } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 30 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell cell.label.text = String(indexPath.row) return cell } }
ba3de3d893589b5923a86107fa5b13d5
27.964286
106
0.665228
false
false
false
false
NghiaTranUIT/Titan
refs/heads/master
TitanCore/TitanCore/SlackReporter.swift
mit
2
// // SlackReporter.swift // TitanCore // // Created by Nghia Tran on 4/4/17. // Copyright © 2017 nghiatran. All rights reserved. // import Foundation import Alamofire enum SlackReporterDataType { case Error case Response } struct SlackReporterData { let type: SlackReporterDataType // Slack private lazy var usernameSlack: String = { switch self.type { case .Error: return "Susu" case .Response: return "Rolex" } }() private lazy var icon_emoji: String = { switch self.type { case .Error: return ":dog:" case .Response: return ":stopwatch:" } }() // Data private var error: NSError? private var responseTime: CGFloat? = 0 private var apiName: String = "" private var fileName: String = "" private var functionName: String = "" private var line: String = "" private var additionInfo: String = "" private lazy var buildNumber: String? = { guard let appInfo = Bundle.main.infoDictionary else {return nil} let appVersion = appInfo[kCFBundleVersionKey as String] as? String return appVersion }() init(error: NSError?, fileName: String, functionName: String, line: Int) { self.type = .Error self.error = error self.functionName = functionName self.line = String(line) // Filename let componment = fileName.components(separatedBy: "/") if let _fileName = componment.last { self.fileName = _fileName } else { self.fileName = "Unknow" } } init(responseTime: CGFloat?, apiName: String, response: Alamofire.DataResponse<AnyObject>?) { self.type = .Response self.responseTime = responseTime ?? 0 self.apiName = apiName self.additionInfo = self.infoTextFromResponse(response: response) } mutating func toParam() -> [String: String] { let text = self.toLog() let username = self.usernameSlack let icon = self.icon_emoji let param: [String: String] = ["username": username, "icon_emoji": icon, "text": text] return param } private func infoTextFromResponse(response: Alamofire.DataResponse<AnyObject>?) -> String { guard let response = response else {return ""} var text: String = "" if let URL = response.request?.url?.absoluteString { text += " *URL* = \(URL)" } return text } private mutating func toLog() -> String { // Current User first var text: String = "" text += ":dark_sunglasses: " // Build version if let buildVersion = self.buildNumber { text += " :macOS: \(buildVersion)" } // Info switch self.type { case .Error: text += ":round_pushpin:\(fileName):\(line) :mag_right:\(functionName)" if let error = self.error { text += " 👉 \(error.localizedDescription)" } else { text += " 👉 Unknow" } return text case .Response: text += ":round_pushpin:\(self.apiName):" if let responseTime = self.responseTime { text += " 👉 \(responseTime)" } else { text += " 👉 Unknow" } text += " :rocket: \(self.additionInfo)" return text } } } class SlackReporter: NSObject { // MARK: // MARK: Variable private let Token = Constants.Logger.Slack.Token private let ErrorChannel = Constants.Logger.Slack.ErrorChannel private let ResponseChannel = Constants.Logger.Slack.ResponseChannel private lazy var URLErrorChannel: String = { return Constants.Logger.Slack.ErrorChannel_Webhook }() private lazy var URLResponseChannel: String = { return Constants.Logger.Slack.ResponseChannel_Webhook }() // MARK: // MARK: Public func reportErrorData(_ data: SlackReporterData) { // Build param var data = data let param = data.toParam() Alamofire.request(self.URLErrorChannel, method: .post, parameters: param, encoding: JSONEncoding.default).responseJSON { (_) in } } func reportResponseData(data: SlackReporterData) { // Build param var data = data let param = data.toParam() Alamofire.request(self.self.URLResponseChannel, method: .post, parameters: param, encoding: JSONEncoding.default).responseJSON { (_) in } } // MARK: // MARK: Private static let shareInstance = SlackReporter() } extension SlackReporter { // Test func testSlackReport() { let error = NSError.errorWithMessage(message: "Hi, I'm from Error Report") let data = SlackReporterData(error: error, fileName: #file, functionName: #function, line:#line) self.reportErrorData(data) } // Test func testSlackResponseReport() { let data = SlackReporterData(responseTime: 0.2, apiName: "TestAPIName", response: nil) self.reportResponseData(data: data) } }
9b35892478e7f37a30ec503a9181e236
27.292308
143
0.556462
false
false
false
false
Crebs/WSCloudKitController
refs/heads/master
WSCloudKitController/CKRecord+Extension.swift
mit
1
// // CKRecord+Extension.swift // WSCloudKitController // // Created by Riley Crebs on 11/6/15. // Copyright (c) 2015 Incravo. All rights reserved. // import Foundation import CloudKit public extension CKRecord { /** Updates the CKRecord object from a basic NSObject. Will only update properties that conform to CKRecordValue, will skip the rest. @param object NSObject to update the responder with. */ public func updateFromObject(object :AnyObject?) { let objectsClass: AnyClass = object!.classForCoder; self.updateFromObject(object, objectClass: objectsClass) } /** Class method To make a CKRecord object from a basic NSObject. Will only handle properties that CKRecord can handle, will skip the rest. @param object NSObject to convert into a CKRecord object. @param recordId Record id use to create the CKRecord. @return returns a CKRecord object created from basic NSObject */ public class func recordFromObject(object :AnyObject?, recordId :CKRecordID) -> CKRecord { let objectsClass: AnyClass = object!.classForCoder; let typeName: String = NSStringFromClass(objectsClass).componentsSeparatedByString(".").last! let record: CKRecord = CKRecord(recordType: typeName, recordID: recordId) record.updateFromObject(object, objectClass: objectsClass) return record } private func updateFromObject(object: AnyObject?, objectClass: AnyClass) { var count:UInt32 = 0 let properties = class_copyPropertyList(objectClass, &count) for (var i:UInt32 = 0; i < count; ++i) { let property = properties[Int(i)] let cname = property_getName(property) let name: String = String.fromCString(cname)! let value: AnyObject? = object?.valueForKeyPath(name) if CKRecord.isValidCloudKitClass(value!) { self.setValue(value, forKey: name) } } } private class func isValidCloudKitClass(object: AnyObject) -> Bool { return (object.isKindOfClass(NSNumber.self) || object.isKindOfClass(NSString.self) || object.isKindOfClass(NSDate.self) || object.isKindOfClass(CKAsset.self) || object.isKindOfClass(NSData.self) || object.isKindOfClass(CLLocation.self) || object.isKindOfClass(CKReference.self) || object.isKindOfClass(NSArray.self)) } }
a0ac7095eaa86666faaf286c5ca8d12c
36
101
0.658449
false
false
false
false
groue/GRDB.swift
refs/heads/master
Tests/GRDBTests/NumericOverflowTests.swift
mit
1
import XCTest import GRDB // I think those there is no double between those two, and this is the exact threshold: private let maxInt64ConvertibleDouble = Double(9223372036854775295 as Int64) private let minInt64NonConvertibleDouble = Double(9223372036854775296 as Int64) // Not sure about the exact threshold private let minInt64ConvertibleDouble = Double(Int64.min) private let maxInt64NonConvertibleDouble: Double = -9.223372036854777e+18 // Not sure about the exact threshold private let maxInt32ConvertibleDouble: Double = 2147483647.999999 private let minInt32NonConvertibleDouble: Double = 2147483648 // Not sure about the exact threshold private let minInt32ConvertibleDouble: Double = -2147483648.999999 private let maxInt32NonConvertibleDouble: Double = -2147483649 class NumericOverflowTests: GRDBTestCase { func testHighInt64FromDoubleOverflows() { XCTAssertEqual(Int64.fromDatabaseValue(maxInt64ConvertibleDouble.databaseValue)!, 9223372036854774784) XCTAssertTrue(Int64.fromDatabaseValue((minInt64NonConvertibleDouble).databaseValue) == nil) } func testLowInt64FromDoubleOverflows() { XCTAssertEqual(Int64.fromDatabaseValue(minInt64ConvertibleDouble.databaseValue)!, Int64.min) XCTAssertTrue(Int64.fromDatabaseValue(maxInt64NonConvertibleDouble.databaseValue) == nil) } func testHighInt32FromDoubleOverflows() { XCTAssertEqual(Int32.fromDatabaseValue(maxInt32ConvertibleDouble.databaseValue)!, Int32.max) XCTAssertTrue(Int32.fromDatabaseValue(minInt32NonConvertibleDouble.databaseValue) == nil) } func testLowInt32FromDoubleOverflows() { XCTAssertEqual(Int32.fromDatabaseValue(minInt32ConvertibleDouble.databaseValue)!, Int32.min) XCTAssertTrue(Int32.fromDatabaseValue(maxInt32NonConvertibleDouble.databaseValue) == nil) } func testHighIntFromDoubleOverflows() { #if arch(i386) || arch(arm) // 32 bits Int XCTAssertEqual(Int.fromDatabaseValue(maxInt32ConvertibleDouble.databaseValue)!, Int.max) XCTAssertTrue(Int.fromDatabaseValue(minInt32NonConvertibleDouble.databaseValue) == nil) #elseif arch(x86_64) || arch(arm64) // 64 bits Int XCTAssertEqual(Int64(Int.fromDatabaseValue(maxInt64ConvertibleDouble.databaseValue)!), 9223372036854774784) XCTAssertTrue(Int.fromDatabaseValue((minInt64NonConvertibleDouble).databaseValue) == nil) #else fatalError("Unknown architecture") #endif } func testLowIntFromDoubleOverflows() { #if arch(i386) || arch(arm) // 32 bits Int XCTAssertEqual(Int.fromDatabaseValue(minInt32ConvertibleDouble.databaseValue)!, Int.min) XCTAssertTrue(Int.fromDatabaseValue(maxInt32NonConvertibleDouble.databaseValue) == nil) #elseif arch(x86_64) || arch(arm64) // 64 bits Int XCTAssertEqual(Int.fromDatabaseValue(minInt64ConvertibleDouble.databaseValue)!, Int.min) XCTAssertTrue(Int.fromDatabaseValue(maxInt64NonConvertibleDouble.databaseValue) == nil) #else fatalError("Unknown architecture") #endif } }
aca2a3339b2b642d237ee45cd4b2218a
44.914286
119
0.74051
false
true
false
false
finder39/Swignals
refs/heads/master
Source/Swignal4Args.swift
mit
1
// // Swignal4Args.swift // Plug // // Created by Joseph Neuman on 7/6/16. // Copyright © 2016 Plug. All rights reserved. // import Foundation open class Swignal4Args<A,B,C,D>: SwignalBase { public override init() { } open func addObserver<L: AnyObject>(_ observer: L, callback: @escaping (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C, _ arg4: D) -> ()) { let observer = Observer4Args(swignal: self, observer: observer, callback: callback) addSwignalObserver(observer) } open func fire(_ arg1: A, arg2: B, arg3: C, arg4: D) { synced(self) { for watcher in self.swignalObservers { watcher.fire(arg1, arg2, arg3, arg4) } } } } private class Observer4Args<L: AnyObject,A,B,C,D>: ObserverGenericBase<L> { let callback: (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C, _ arg4: D) -> () init(swignal: SwignalBase, observer: L, callback: @escaping (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C, _ arg4: D) -> ()) { self.callback = callback super.init(swignal: swignal, observer: observer) } override func fire(_ args: Any...) { if let arg1 = args[0] as? A, let arg2 = args[1] as? B, let arg3 = args[2] as? C, let arg4 = args[3] as? D { fire(arg1: arg1, arg2: arg2, arg3: arg3, arg4: arg4) } else { assert(false, "Types incorrect") } } fileprivate func fire(arg1: A, arg2: B, arg3: C, arg4: D) { if let observer = observer { callback(observer, arg1, arg2, arg3, arg4) } } }
ace54959ee6b7b95507fadb95cb8204b
29.722222
143
0.545509
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Location/MapKit+Helper.swift
gpl-3.0
1
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import MapKit import WireDataModel extension CLLocationCoordinate2D { var location: CLLocation { return CLLocation(latitude: latitude, longitude: longitude) } } extension CLPlacemark { func formattedAddress(_ includeCountry: Bool) -> String? { let lines: [String]? lines = [subThoroughfare, thoroughfare, locality, subLocality, administrativeArea, postalCode, country].compactMap { $0 } return includeCountry ? lines?.joined(separator: ", ") : lines?.dropLast().joined(separator: ", ") } } extension MKMapView { var zoomLevel: Int { get { let float = log2(360 * (Double(frame.height / 256) / region.span.longitudeDelta)) // MKMapView does not like NaN and Infinity, so we return 16 as a default, as 0 would represent the whole world guard float.isNormal else { return 16 } return Int(float) } set { setCenterCoordinate(centerCoordinate, zoomLevel: newValue) } } func setCenterCoordinate(_ coordinate: CLLocationCoordinate2D, zoomLevel: Int, animated: Bool = false) { guard CLLocationCoordinate2DIsValid(coordinate) else { return } let region = MKCoordinateRegion(center: coordinate, span: MKCoordinateSpan(zoomLevel: zoomLevel, viewSize: Float(frame.height))) setRegion(region, animated: animated) } } extension MKCoordinateSpan { init(zoomLevel: Int, viewSize: Float) { self.init(latitudeDelta: min(360 / pow(2, Double(zoomLevel)) * Double(viewSize) / 256, 180), longitudeDelta: 0) } } extension LocationData { var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude)) } } extension MKMapView { func locationData(name: String?) -> LocationData { return .locationData( withLatitude: Float(centerCoordinate.latitude), longitude: Float(centerCoordinate.longitude), name: name, zoomLevel: Int32(zoomLevel) ) } func storeLocation() { let location: LocationData = locationData(name: nil) Settings.shared[.lastUserLocation] = location } func restoreLocation(animated: Bool) { guard let location: LocationData = Settings.shared[.lastUserLocation] else { return } setCenterCoordinate(location.coordinate, zoomLevel: Int(location.zoomLevel), animated: animated) } }
ef3bef0526085b9ca1e3cc97f495aeba
31.06
136
0.685278
false
false
false
false
Ivacker/swift
refs/heads/master
test/NameBinding/Inputs/accessibility_other.swift
apache-2.0
10
import has_accessibility public let a = 0 internal let b = 0 private let c = 0 extension Foo { public static func a() {} internal static func b() {} private static func c() {} } struct PrivateInit { private init() {} } extension Foo { private func method() {} private typealias TheType = Float } extension OriginallyEmpty { func method() {} typealias TheType = Float } private func privateInBothFiles() {} func privateInPrimaryFile() {} // expected-note {{previously declared here}} private func privateInOtherFile() {} // expected-error {{invalid redeclaration}}
845ecd935454003797c7f2dab885b628
19.206897
80
0.704778
false
false
false
false
aschwaighofer/swift
refs/heads/master
test/IDE/structure.swift
apache-2.0
2
// RUN: %swift-ide-test -structure -source-filename %s | %FileCheck %s // CHECK: <class>class <name>MyCls</name> : <inherited><elem-typeref>OtherClass</elem-typeref></inherited> { // CHECK: <property>var <name>bar</name> : <type>Int</type></property> // CHECK: <property>var <name>anotherBar</name> : <type>Int</type> = 42</property> // CHECK: <cvar>class var <name>cbar</name> : <type>Int</type> = 0</cvar> class MyCls : OtherClass { var bar : Int var anotherBar : Int = 42 class var cbar : Int = 0 // CHECK: <ifunc>func <name>foo(<param>_ arg1: <type>Int</type></param>, <param><name>name</name>: <type>String</type></param>, <param><name>param</name> par: <type>String</type></param>)</name> { // CHECK: <lvar>var <name>abc</name></lvar> // CHECK: <if>if <elem-condexpr>1</elem-condexpr> <brace>{ // CHECK: <call><name>foo</name>(<arg>1</arg>, <arg><name>name</name>:"test"</arg>, <arg><name>param</name>:"test2"</arg>)</call> // CHECK: }</brace> // CHECK: }</ifunc> func foo(_ arg1: Int, name: String, param par: String) { var abc if 1 { foo(1, name:"test", param:"test2") } } // CHECK: <ifunc><name>init (<param><name>x</name>: <type>Int</type></param>)</name></ifunc> init (x: Int) // CHECK: <cfunc>class func <name>cfoo()</name></cfunc> class func cfoo() // CHECK: }</class> } // CHECK: <struct>struct <name>MyStruc</name> { // CHECK: <property>var <name>myVar</name>: <type>Int</type></property> // CHECK: <svar>static var <name>sbar</name> : <type>Int</type> = 0</svar> // CHECK: <sfunc>static func <name>cfoo()</name></sfunc> // CHECK: }</struct> struct MyStruc { var myVar: Int static var sbar : Int = 0 static func cfoo() } // CHECK: <protocol>protocol <name>MyProt</name> { // CHECK: <ifunc>func <name>foo()</name></ifunc> // CHECK: <ifunc>func <name>foo2()</name> throws</ifunc> // CHECK: <ifunc>func <name>foo3()</name> throws -> <type>Int</type></ifunc> // CHECK: <ifunc>func <name>foo4<<generic-param><name>T</name></generic-param>>()</name> where T: MyProt</ifunc> // CHECK: <ifunc><name>init()</name></ifunc> // CHECK: <ifunc><name>init(<param><name>a</name>: <type>Int</type></param>)</name> throws</ifunc> // CHECK: <ifunc><name>init<<generic-param><name>T</name></generic-param>>(<param><name>a</name>: <type>T</type></param>)</name> where T: MyProt</ifunc> // CHECK: }</protocol> protocol MyProt { func foo() func foo2() throws func foo3() throws -> Int func foo4<T>() where T: MyProt init() init(a: Int) throws init<T>(a: T) where T: MyProt } // CHECK: <extension>extension <name>MyStruc</name> { // CHECK: <ifunc>func <name>foo()</name> { // CHECK: }</ifunc> // CHECK: }</extension> extension MyStruc { func foo() { } } // CHECK: <gvar>var <name>gvar</name> : <type>Int</type> = 0</gvar> var gvar : Int = 0 // CHECK: <ffunc>func <name>ffoo()</name> {}</ffunc> func ffoo() {} // CHECK: <foreach>for <elem-id><lvar><name>i</name></lvar></elem-id> in <elem-expr>0...5</elem-expr> <brace>{}</brace></foreach> for i in 0...5 {} // CHECK: <foreach>for <elem-id>var (<lvar><name>i</name></lvar>, <lvar><name>j</name></lvar>)</elem-id> in <elem-expr>array</elem-expr> <brace>{}</brace></foreach> for var (i, j) in array {} // CHECK: <while>while <elem-condexpr>var <lvar><name>v</name></lvar> = o, <lvar><name>z</name></lvar> = o where v > z</elem-condexpr> <brace>{}</brace></while> while var v = o, z = o where v > z {} // CHECK: <while>while <elem-condexpr>v == 0</elem-condexpr> <brace>{}</brace></while> while v == 0 {} // CHECK: <repeat-while>repeat <brace>{}</brace> while <elem-expr>v == 0</elem-expr></repeat-while> repeat {} while v == 0 // CHECK: <if>if <elem-condexpr>var <lvar><name>v</name></lvar> = o, <lvar><name>z</name></lvar> = o where v > z</elem-condexpr> <brace>{}</brace></if> if var v = o, z = o where v > z {} // CHECK: <switch>switch <elem-expr>v</elem-expr> { // CHECK: <case>case <elem-pattern>1</elem-pattern>: break;</case> // CHECK: <case>case <elem-pattern>2</elem-pattern>, <elem-pattern>3</elem-pattern>: break;</case> // CHECK: <case>case <elem-pattern><call><name>Foo</name>(<arg>var <lvar><name>x</name></lvar></arg>, <arg>var <lvar><name>y</name></lvar></arg>)</call> where x < y</elem-pattern>: break;</case> // CHECK: <case>case <elem-pattern>2 where <call><name>foo</name>()</call></elem-pattern>, <elem-pattern>3 where <call><name>bar</name>()</call></elem-pattern>: break;</case> // CHECK: <case><elem-pattern>default</elem-pattern>: break;</case> // CHECK: }</switch> switch v { case 1: break; case 2, 3: break; case Foo(var x, var y) where x < y: break; case 2 where foo(), 3 where bar(): break; default: break; } // CHECK: <gvar>let <name>myArray</name> = <array>[<elem-expr>1</elem-expr>, <elem-expr>2</elem-expr>, <elem-expr>3</elem-expr>]</array></gvar> let myArray = [1, 2, 3] // CHECK: <gvar>let <name>myDict</name> = <dictionary>[<elem-expr>1</elem-expr>:<elem-expr>1</elem-expr>, <elem-expr>2</elem-expr>:<elem-expr>2</elem-expr>, <elem-expr>3</elem-expr>:<elem-expr>3</elem-expr>]</dictionary></gvar> let myDict = [1:1, 2:2, 3:3] // CHECK: <gvar>let <name>myArray2</name> = <array>[<elem-expr>1</elem-expr>]</array></gvar> let myArray2 = [1] // CHECK: <gvar>let <name>myDict2</name> = <dictionary>[<elem-expr>1</elem-expr>:<elem-expr>1</elem-expr>]</dictionary></gvar> let myDict2 = [1:1] // CHECK: <foreach>for <brace>{}</brace></foreach> for {} // CHECK: <class>class <name><#MyCls#></name> : <inherited><elem-typeref><#OtherClass#></elem-typeref></inherited> {} class <#MyCls#> : <#OtherClass#> {} // CHECK: <ffunc>func <name><#test1#> ()</name> { // CHECK: <foreach>for <elem-id><lvar><name><#name#></name></lvar></elem-id> in <elem-expr><#items#></elem-expr> <brace>{}</brace></foreach> // CHECK: }</ffunc> func <#test1#> () { for <#name#> in <#items#> {} } // CHECK: <gvar>let <name>myArray</name> = <array>[<elem-expr><#item1#></elem-expr>, <elem-expr><#item2#></elem-expr>]</array></gvar> let myArray = [<#item1#>, <#item2#>] // CHECK: <ffunc>func <name>test1()</name> { // CHECK: <call><name>dispatch_async</name>(<arg><call><name>dispatch_get_main_queue</name>()</call></arg>, <arg><closure><brace>{}</brace></closure></arg>)</call> // CHECK: <call><name>dispatch_async</name>(<arg><call><name>dispatch_get_main_queue</name>()</call></arg>) <arg><closure><brace>{}</brace></closure></arg></call> // CHECK: }</ffunc> func test1() { dispatch_async(dispatch_get_main_queue(), {}) dispatch_async(dispatch_get_main_queue()) {} } // CHECK: <enum>enum <name>SomeEnum</name> { // CHECK: <enum-case>case <enum-elem><name>North</name></enum-elem></enum-case> // CHECK: <enum-case>case <enum-elem><name>South</name></enum-elem>, <enum-elem><name>East</name></enum-elem></enum-case> // CHECK: <enum-case>case <enum-elem><name>QRCode(<param><type>String</type></param>)</name></enum-elem></enum-case> // CHECK: <enum-case>case</enum-case> // CHECK: }</enum> enum SomeEnum { case North case South, East case QRCode(String) case } // CHECK: <enum>enum <name>Rawness</name> : <inherited><elem-typeref>Int</elem-typeref></inherited> { // CHECK: <enum-case>case <enum-elem><name>One</name> = <elem-initexpr>1</elem-initexpr></enum-elem></enum-case> // CHECK: <enum-case>case <enum-elem><name>Two</name> = <elem-initexpr>2</elem-initexpr></enum-elem>, <enum-elem><name>Three</name> = <elem-initexpr>3</elem-initexpr></enum-elem></enum-case> // CHECK: }</enum> enum Rawness : Int { case One = 1 case Two = 2, Three = 3 } // CHECK: <ffunc>func <name>rethrowFunc(<param>_ f: <type>() throws -> ()</type> = <closure><brace>{}</brace></closure></param>)</name> rethrows {}</ffunc> func rethrowFunc(_ f: () throws -> () = {}) rethrows {} class NestedPoundIf{ func foo1() { #if os(macOS) var a = 1 #if USE_METAL var b = 2 #if os(iOS) var c = 3 #else var c = 3 #endif #else var b = 2 #endif #else var a = 1 #endif } func foo2() {} func foo3() {} } // CHECK: <ifunc>func <name>foo2()</name> {}</ifunc> // CHECK: <ifunc>func <name>foo3()</name> {}</ifunc> class A { func foo(_ i : Int, animations: () -> ()) {} func perform() {foo(5, animations: {})} // CHECK: <ifunc>func <name>perform()</name> {<call><name>foo</name>(<arg>5</arg>, <arg><name>animations</name>: <closure><brace>{}</brace></closure></arg>)</call>}</ifunc> } // CHECK: <typealias>typealias <name>OtherA</name> = A</typealias> typealias OtherA = A // CHECK: <typealias>typealias <name>EqBox</name><<generic-param><name>Boxed</name></generic-param>> = Box<Boxed> where Boxed: Equatable</typealias> typealias EqBox<Boxed> = Box<Boxed> where Boxed: Equatable class SubscriptTest { subscript(index: Int) -> Int { return 0 } // CHECK: <subscript><name>subscript(<param>index: <type>Int</type></param>)</name> -> <type>Int</type> { // CHECK: return 0 // CHECK: }</subscript> subscript(string: String) -> Int { get { return 0 } set(value) { print(value) } } // CHECK: <subscript><name>subscript(<param>string: <type>String</type></param>)</name> -> <type>Int</type> { // CHECK: get { // CHECK: return 0 // CHECK: } // CHECK: set(<param>value</param>) { // CHECK: <call><name>print</name>(value)</call> // CHECK: }</subscript> } class ReturnType { func foo() -> Int { return 0 } // CHECK: <ifunc>func <name>foo()</name> -> <type>Int</type> { // CHECK: return 0 // CHECK: }</ifunc> func foo2<T>() -> T {} // CHECK: <ifunc>func <name>foo2<<generic-param><name>T</name></generic-param>>()</name> -> <type>T</type> {}</ifunc> func foo3() -> () -> Int {} // CHECK: <ifunc>func <name>foo3()</name> -> <type>() -> Int</type> {}</ifunc> } protocol FooProtocol { associatedtype Bar // CHECK: <associatedtype>associatedtype <name>Bar</name></associatedtype> associatedtype Baz: Equatable // CHECK: <associatedtype>associatedtype <name>Baz</name>: Equatable</associatedtype> associatedtype Qux where Qux: Equatable // CHECK: <associatedtype>associatedtype <name>Qux</name> where Qux: Equatable</associatedtype> associatedtype Bar2 = Int // CHECK: <associatedtype>associatedtype <name>Bar2</name> = Int</associatedtype> associatedtype Baz2: Equatable = Int // CHECK: <associatedtype>associatedtype <name>Baz2</name>: Equatable = Int</associatedtype> associatedtype Qux2 = Int where Qux2: Equatable // CHECK: <associatedtype>associatedtype <name>Qux2</name> = Int where Qux2: Equatable</associatedtype> } // CHECK: <struct>struct <name>Generic</name><<generic-param><name>T</name>: <inherited><elem-typeref>Comparable</elem-typeref></inherited></generic-param>, <generic-param><name>X</name></generic-param>> { // CHECK: <subscript><name>subscript<<generic-param><name>U</name></generic-param>>(<param>generic: <type>U</type></param>)</name> -> <type>Int</type> { return 0 }</subscript> // CHECK: <typealias>typealias <name>Foo</name><<generic-param><name>Y</name></generic-param>> = Bar<Y></typealias> // CHECK: }</struct> struct Generic<T: Comparable, X> { subscript<U>(generic: U) -> Int { return 0 } typealias Foo<Y> = Bar<Y> } a.b(c: d?.e?.f, g: h) // CHECK: <call><name>a.b</name>(<arg><name>c</name>: d?.e?.f</arg>, <arg><name>g</name>: h</arg>)</call> struct Tuples { var foo: (Int, String) { return (1, "test") // CHECK: <tuple>(<elem-expr>1</elem-expr>, <elem-expr>"test"</elem-expr>)</tuple> } func foo2() { foo3(x: (1, 20)) // CHECK: <call><name>foo3</name>(<arg><name>x</name>: <tuple>(<elem-expr>1</elem-expr>, <elem-expr>20</elem-expr>)</tuple></arg>)</call> let y = (x, foo4(a: 0)) // CHECK: <lvar>let <name>y</name> = <tuple>(<elem-expr>x</elem-expr>, <elem-expr><call><name>foo4</name>(<arg><name>a</name>: 0</arg>)</call></elem-expr>)</tuple></lvar> let z = (name1: 1, name2: 2) // CHECK: <lvar>let <name>z</name> = <tuple>(name1: <elem-expr>1</elem-expr>, name2: <elem-expr>2</elem-expr>)</tuple></lvar> } } completion(a: 1) { (x: Any, y: Int) -> Int in return x as! Int + y } // CHECK: <call><name>completion</name>(<arg><name>a</name>: 1</arg>) <arg><closure>{ (<param>x: <type>Any</type></param>, <param>y: <type>Int</type></param>) -> <type>Int</type> in // CHECK: return x as! Int + y // CHECK: }</closure></arg></call> myFunc(foo: 0, bar: baz == 0) // CHECK: <call><name>myFunc</name>(<arg><name>foo</name>: 0</arg>, // CHECK: <arg><name>bar</name>: baz == 0</arg>)</call> enum FooEnum { // CHECK: <enum>enum <name>FooEnum</name> { case blah(x: () -> () = { // CHECK: <enum-case>case <enum-elem><name>blah(<param><name>x</name>: <type>() -> ()</type> = <closure><brace>{ @Tuples func foo(x: MyStruc) {} // CHECK: @Tuples <ffunc>func <name>foo(<param><name>x</name>: <type>MyStruc</type></param>)</name> {}</ffunc> }) // CHECK: }</brace></closure></param>)</name></enum-elem></enum-case> } // CHECK: }</enum> firstCall("\(1)", 1) // CHECK: <call><name>firstCall</name>(<arg>"\(1)"</arg>, <arg>1</arg>)</call> secondCall("\(a: {struct Foo {let x = 10}; return Foo().x}())", 1) // CHECK: <call><name>secondCall</name>(<arg>"\(a: <call><name><closure><brace>{<struct>struct <name>Foo</name> {<property>let <name>x</name> = 10</property>}</struct>; return <call><name>Foo</name>()</call>.x}</brace></closure></name>()</call>)"</arg>, <arg>1</arg>)</call> thirdCall(""" \(""" \({ return a() }()) """) """) // CHECK: <call><name>thirdCall</name>(""" // CHECK-NEXT: \(""" // CHECK-NEXT: \(<call><name><closure>{ // CHECK-NEXT: return <call><name>a</name>()</call> // CHECK-NEXT: }</closure></name>()</call>) // CHECK-NEXT: """) // CHECK-NEXT: """)</call> fourthCall(a: @escaping () -> Int) // CHECK: <call><name>fourthCall</name>(<arg><name>a</name>: @escaping () -> Int</arg>)</call> // CHECK: <call><name>foo</name> <closure>{ [unowned <lvar><name>self</name></lvar>, <lvar><name>x</name></lvar>] in _ }</closure></call> foo { [unowned self, x] in _ }
1ed66e6dfa7ca799fdeb1dd5ba1b3f64
41.607784
274
0.603612
false
false
false
false
chernyog/CYWeibo
refs/heads/master
CYWeibo/CYWeibo/CYWeibo/Classes/UI/OAuth/OAuthViewController.swift
mit
1
// // OAuthViewController.swift // 04-TDD // // Created by 陈勇 on 15/3/3. // Copyright (c) 2015年 zhssit. All rights reserved. // import UIKit // 定义全局常量 /// 登录成功的通知 let WB_Login_Successed_Notification = "WB_Login_Successed_Notification" class OAuthViewController: UIViewController { @IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() self.webView.delegate = self // 加载授权界面 loadAuthPage() } /// 加载授权界面 func loadAuthPage() { // url let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUri)" let request = NSURLRequest(URL: NSURL(string: urlString)!) webView.loadRequest(request) } } // MARK:- 常量区 let appKey = "2013929282" let appSecret = "a8ef9f6c61af740a6cd5742874f348ff" let redirectUri = "http://zhssit.com/" let grantType = "authorization_code" let WB_API_URL_String = "https://api.weibo.com" let WB_Redirect_URL_String = "http://zhssit.com/" // MARK: - <UIWebViewDelegate> extension OAuthViewController: UIWebViewDelegate { func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { let result = self.checkLoadPageAndRuturnCodeWithUrl(request.URL!) if let code = result.code { // 请求参数 let params = ["client_id": appKey, "client_secret": appSecret, "grant_type": grantType, "redirect_uri": WB_Redirect_URL_String, "code": code] let urlString = "https://api.weibo.com/oauth2/access_token" NetworkManager.sharedManager.requestJSON(.POST, urlString, params, completion: { (result, error) -> () in println("==================================================================") // println(result) // liufan2000 // let accessToken = DictModel4Swift.sharedInstance.objectWithDictionary(result as! NSDictionary, cls: AccessToken.self) as! AccessToken let accessToken = AccessToken(dict: result as! NSDictionary) accessToken.saveAccessToken() println("***********" + accessToken.access_token!) println("==================================================================") // 切换UI NSNotificationCenter.defaultCenter().postNotificationName(WB_Login_Successed_Notification, object: nil) }) } return result.isLoadPage } /// 根据URL判断是否需要加载页面和返回code /// /// :param: url url /// func checkLoadPageAndRuturnCodeWithUrl(url: NSURL)->(isLoadPage: Bool,code: String?,isReloadAuth: Bool) { let urlString = url.absoluteString! if !urlString.hasPrefix(WB_API_URL_String) { if urlString.hasPrefix(WB_Redirect_URL_String) { // http://zhssit.com/?code=584b72d000009d5eca69ed7fd3de103b if let query = url.query { let flag: NSString = "code=" if query.hasPrefix(flag as String) // 授权 { // 截取字符串 let code = (query as NSString).substringFromIndex(flag.length) return (false, code, false) } else // 取消授权 { return (false, nil, true) } } } return (false, nil,false) } return (true, nil, false) } } /* 系统URL 登录 加载页面 https://api.weibo.com/oauth2/authorize?client_id=2013929282&redirect_uri=http://zhssit.com/ 登录成功 加载页面 https://api.weibo.com/oauth2/authorize 注册 不加载页面 http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&appsrc=3fgubw&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D2013929282%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fzhssit.com%252F%26from%3D%26with_cookie%3D 切换账号 不加载页面 http://login.sina.com.cn/sso/logout.php?entry=openapi&r=http%3A%2F%2Flogin.sina.com.cn%2Fsso%2Flogout.php%3Fentry%3Dopenapi%26r%3Dhttps%253A%252F%252Fapi.weibo.com%252Foauth2%252Fauthorize%253Fclient_id%253D2013929282%2526redirect_uri%253Dhttp%253A%252F%252Fzhssit.com%252F 取消授权 不加载页面,加载授权界面 http://zhssit.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330 授权 不加载页面 返回code http://zhssit.com/?code=584b72d000009d5eca69ed7fd3de103b */
482704b3c75f6d76ce714ff1e0344dcd
33.637037
273
0.597647
false
false
false
false
edstewbob/cs193p-winter-2015
refs/heads/master
Calculator/Calculator/ViewController.swift
mit
2
// // ViewController.swift // Calculator // // Created by jrm on 3/5/15. // Copyright (c) 2015 Riesam LLC. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var history: UILabel! @IBOutlet weak var display: UILabel! var userIsInTheMiddleOfTypingANumber = false var numberHasADecimalPoint = false @IBAction func back(sender: UIButton) { if userIsInTheMiddleOfTypingANumber { if count(display.text!) > 0 { var text = display.text! text = dropLast(text) if count(text) > 0 { display.text = text }else{ display.text = "0" } } } addToHistory("🔙") } @IBAction func plusMinus(sender: UIButton) { if userIsInTheMiddleOfTypingANumber { //change the sign of the number and allow typing to continue var text = display.text! if(text[text.startIndex] == "-"){ display.text = dropFirst(text) }else{ display.text = "-" + text } addToHistory("±") }else{ operate(sender) } } @IBAction func appendDigit(sender: UIButton) { if let digit = sender.currentTitle{ if( numberHasADecimalPoint && digit == "."){ // do nothing; additional decimal point is not allowed }else { if (digit == "."){ numberHasADecimalPoint = true } if userIsInTheMiddleOfTypingANumber { var text = display.text! if(text[text.startIndex] == "0"){ text = dropFirst(text) } display.text = text + digit } else { display.text = digit userIsInTheMiddleOfTypingANumber = true } } //println("digit = \(digit)") addToHistory(digit) } } @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddleOfTypingANumber { performEnter("") } addToHistory(operation) switch operation { case "×": performBinaryOperation { $0 * $1 } case "÷": performBinaryOperation { $1 / $0 } case "+": performBinaryOperation { $0 + $1 } case "−": performBinaryOperation { $1 - $0 } case "√": performUnaryOperation { sqrt($0) } case "sin": performUnaryOperation { sin($0) } case "cos": performUnaryOperation { cos($0) } case "π": displayValue = M_PI //enter() performEnter("constant") case "±": performUnaryOperation { -$0 } default: break } } @IBAction func clear(sender: UIButton) { display.text = "0" history.text = " " operandStack.removeAll() history.text = " " //println("operandStack = \(operandStack)") } /* * NOTE: I renamed the overloaded performOperation() functions to be two separate functions because * Objective-C does not support method overloading. The the overloaded functions were working in Xcode 6.2 * but generate errors in Xcode 6.3. See stackover flow * http://stackoverflow.com/questions/29457720/swift-compiler-error-which-i-dont-understand */ func performBinaryOperation(operation: (Double, Double) -> Double) { if operandStack.count >= 2 { displayValue = operation(operandStack.removeLast(), operandStack.removeLast()) performEnter("operation") } } func performUnaryOperation(operation: Double -> Double) { if operandStack.count >= 1 { displayValue = operation(operandStack.removeLast()) performEnter("operation") //enter() } } func addToHistory(value: String) { if let oldText = history.text { history.text = oldText + " " + value }else { history.text = value } //get rid of any extra = chars if let historyText = history.text { let endIndex = advance(historyText.endIndex, -1) let range = Range(start: historyText.startIndex, end: endIndex) let newhistory = historyText.stringByReplacingOccurrencesOfString( " =", withString: "", options: nil, range: range) history.text = newhistory } } var operandStack = Array<Double>() @IBAction func enter() { performEnter("enterButtonClicked") } func performEnter(type: String){ switch(type){ case "operation": addToHistory("=") case "enterButtonClicked": addToHistory("⏎") case "contant": addToHistory("⏎") default: break } userIsInTheMiddleOfTypingANumber = false numberHasADecimalPoint = false if let value = displayValue{ operandStack.append(value) }else { displayValue = 0 } //println("operandStack = \(operandStack)") } var displayValue: Double? { get { return NSNumberFormatter().numberFromString(display.text!)!.doubleValue } set { if let value = newValue{ display.text = "\(value)" }else{ display.text = "0" } //display.text = "\(newValue)" userIsInTheMiddleOfTypingANumber = false } } }
af19ae36f3450126e38eb23ab63040b0
29.546392
111
0.515862
false
false
false
false
klaus01/Centipede
refs/heads/master
Centipede/UIKit/CE_UIWebView.swift
mit
1
// // CE_UIWebView.swift // Centipede // // Created by kelei on 2016/9/15. // Copyright (c) 2016年 kelei. All rights reserved. // import UIKit extension UIWebView { private struct Static { static var AssociationKey: UInt8 = 0 } private var _delegate: UIWebView_Delegate? { get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? UIWebView_Delegate } set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } private var ce: UIWebView_Delegate { if let obj = _delegate { return obj } if let obj: AnyObject = self.delegate { if obj is UIWebView_Delegate { return obj as! UIWebView_Delegate } } let obj = getDelegateInstance() _delegate = obj return obj } private func rebindingDelegate() { let delegate = ce self.delegate = nil self.delegate = delegate } internal func getDelegateInstance() -> UIWebView_Delegate { return UIWebView_Delegate() } @discardableResult public func ce_webView_shouldStartLoadWith(handle: @escaping (UIWebView, URLRequest, UIWebViewNavigationType) -> Bool) -> Self { ce._webView_shouldStartLoadWith = handle rebindingDelegate() return self } @discardableResult public func ce_webViewDidStartLoad(handle: @escaping (UIWebView) -> Void) -> Self { ce._webViewDidStartLoad = handle rebindingDelegate() return self } @discardableResult public func ce_webViewDidFinishLoad(handle: @escaping (UIWebView) -> Void) -> Self { ce._webViewDidFinishLoad = handle rebindingDelegate() return self } @discardableResult public func ce_webView_didFailLoadWithError(handle: @escaping (UIWebView, Error) -> Void) -> Self { ce._webView_didFailLoadWithError = handle rebindingDelegate() return self } } internal class UIWebView_Delegate: NSObject, UIWebViewDelegate { var _webView_shouldStartLoadWith: ((UIWebView, URLRequest, UIWebViewNavigationType) -> Bool)? var _webViewDidStartLoad: ((UIWebView) -> Void)? var _webViewDidFinishLoad: ((UIWebView) -> Void)? var _webView_didFailLoadWithError: ((UIWebView, Error) -> Void)? override func responds(to aSelector: Selector!) -> Bool { let funcDic1: [Selector : Any?] = [ #selector(webView(_:shouldStartLoadWith:navigationType:)) : _webView_shouldStartLoadWith, #selector(webViewDidStartLoad(_:)) : _webViewDidStartLoad, #selector(webViewDidFinishLoad(_:)) : _webViewDidFinishLoad, #selector(webView(_:didFailLoadWithError:)) : _webView_didFailLoadWithError, ] if let f = funcDic1[aSelector] { return f != nil } return super.responds(to: aSelector) } @objc func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { return _webView_shouldStartLoadWith!(webView, request, navigationType) } @objc func webViewDidStartLoad(_ webView: UIWebView) { _webViewDidStartLoad!(webView) } @objc func webViewDidFinishLoad(_ webView: UIWebView) { _webViewDidFinishLoad!(webView) } @objc func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { _webView_didFailLoadWithError!(webView, error) } }
79aaac71218109ea68eb2d01e9baeda3
32.943396
136
0.643691
false
false
false
false
huangboju/Moots
refs/heads/master
UICollectionViewLayout/Blueprints-master/Example-OSX/Scenes/LayoutExampleSceneViewController+VerticalMosaicBlueprintLayout.swift
mit
1
import Blueprints import Cocoa extension LayoutExampleSceneViewController { func configureMosaicLayout() { let mosaicBlueprintLayout = VerticalMosaicBlueprintLayout( patternHeight: 400, minimumInteritemSpacing: minimumInteritemSpacing, minimumLineSpacing: minimumLineSpacing, sectionInset: sectionInsets, patterns: [ MosaicPattern(alignment: .left, direction: .vertical, amount: 2, multiplier: 0.6), MosaicPattern(alignment: .left, direction: .horizontal, amount: 2, multiplier: 0.33), MosaicPattern(alignment: .left, direction: .vertical, amount: 1, multiplier: 0.5), MosaicPattern(alignment: .left, direction: .vertical, amount: 1, multiplier: 0.5) ]) let titleCollectionReusableViewSize = CGSize(width: view.bounds.width, height: 61) mosaicBlueprintLayout.headerReferenceSize = titleCollectionReusableViewSize mosaicBlueprintLayout.footerReferenceSize = titleCollectionReusableViewSize NSView.animate(withDuration: 0.5) { [weak self] in self?.layoutExampleCollectionView.collectionViewLayout = mosaicBlueprintLayout self?.scrollLayoutExampleCollectionViewToTopItem() } } }
75c739081992ea7ecc6d702a358c36d3
40.4
90
0.539251
false
false
false
false
natecook1000/Euler
refs/heads/master
Euler.swift
mit
1
// Euler.swift // // Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // Custom Operators Using Math Symbols // See: https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/AdvancedOperators.html#//apple_ref/doc/uid/TP40014097-CH27-XID_85 // MARK: - Mathematical Constants - // MARK: Pi let π = M_PI // MARK: Tau let 𝝉 = M_PI * 2 // MARK: e let 𝑒 = M_E // MARK: - Logic - // MARK: Negation prefix operator ¬ {} prefix func ¬ (value: Bool) -> Bool { return !value } prefix operator ~ {} prefix func ~ (value: Bool) -> Bool { return !value } // MARK: Logical Conjunction infix operator ∧ { associativity left precedence 120 } func ∧ (left: Bool, @autoclosure right: () -> Bool) -> Bool { return left && right() } // MARK: Logical Disjunction infix operator ∨ { associativity left precedence 110 } func ∨ (left: Bool, @autoclosure right: () -> Bool) -> Bool { return left || right() } // MARK: Logical XOR infix operator ⊻ { associativity left precedence 140 } func ⊻ (left: Bool, @autoclosure right: () -> Bool) -> Bool { return left != right() } infix operator ⊕ { associativity left precedence 140 } func ⊕ (left: Bool, @autoclosure right: () -> Bool) -> Bool { return left != right() } infix operator ↮ { associativity left precedence 140 } func ↮ (left: Bool, @autoclosure right: () -> Bool) -> Bool { return left != right() } infix operator ≢ { associativity left precedence 140 } func ≢ (left: Bool, @autoclosure right: () -> Bool) -> Bool { return left != right() } // MARK: Logical NAND infix operator ⊼ { associativity left precedence 120 } func ⊼ (left: Bool, @autoclosure right: () -> Bool) -> Bool { return ¬(left ∧ right()) } infix operator ↑ { associativity left precedence 120 } func ↑ (left: Bool, @autoclosure right: () -> Bool) -> Bool { return ¬(left ∧ right()) } // MARK: Logical NOR infix operator ⊽ { associativity left precedence 110 } func ⊽ (left: Bool, @autoclosure right: () -> Bool) -> Bool { return ¬(left ∨ right()) } infix operator ↓ { associativity left precedence 110 } func ↓ (left: Bool, @autoclosure right: () -> Bool) -> Bool { return ¬(left ∨ right()) } // MARK: Logical Assertion prefix operator ⊦ {} prefix func ⊦ (@autoclosure condition: () -> Bool) { assert(condition(), "Assertion Failed") } // MARK: - Arithmetic - // MARK: Multiplication infix operator × { associativity left precedence 150 } func × (left: Double, right: Double) -> Double { return left * right } // MARK: Division infix operator ÷ { associativity left precedence 150 } func ÷ (left: Double, right: Double) -> Double { return left / right } infix operator ∕ { associativity left precedence 150 } func ∕ (left: Double, right: Double) -> Double { return left / right } // MARK: Square Root prefix operator √ {} prefix func √ (number: Double) -> Double { return sqrt(number) } // MARK: Cube Root prefix operator ∛ {} prefix func ∛ (number: Double) -> Double { return cbrt(number) } // MARK: Tesseract Root prefix operator ∜ {} prefix func ∜ (number: Double) -> Double { return pow(number, 1.0 / 4.0) } // MARK: Plus / Minus infix operator ± { associativity left precedence 140 } func ± (left: Double, right: Double) -> (Double, Double) { return (left + right, left - right) } prefix operator ± {} prefix func ± (value: Double) -> (Double, Double) { return 0 ± value } // MARK: Minus / Plus infix operator ∓ { associativity left precedence 140 } func ∓ (left: Double, right: Double) -> (Double, Double) { return (left - right, left + right) } prefix operator ∓ {} prefix func ∓ (value: Double) -> (Double, Double) { return 0 ∓ value } // MARK: Divides infix operator ∣ { associativity left precedence 150 } func ∣ (left: Int, right: Int) -> Bool { return left % right == 0 } // MARK: Does Not Divide infix operator ∤ { associativity left } func ∤ (left: Int, right: Int) -> Bool { return ¬(left ∣ right) } // MARK: Sets - // MARK: Set Membership infix operator ∈ { associativity left } func ∈<T: Equatable> (left: T, right: [T]) -> Bool { return right.contains(left) } func ∈<T> (left: T, right: Set<T>) -> Bool { return right.contains(left) } // MARK: Set Non-Membership infix operator ∉ { associativity left } func ∉<T: Equatable> (left: T, right: [T]) -> Bool { return ¬(left ∈ right) } func ∉<T> (left: T, right: Set<T>) -> Bool { return ¬(left ∈ right) } // MARK: Converse Set Membership infix operator ∋ { associativity left } func ∋<T: Equatable> (left: [T], right: T) -> Bool { return right ∈ left } func ∋<T> (left: Set<T>, right: T) -> Bool { return right ∈ left } // MARK: Converse Set Non-Membership infix operator ∌ { associativity left } func ∌<T: Equatable> (left: [T], right: T) -> Bool { return right ∉ left } func ∌<T> (left: Set<T>, right: T) -> Bool { return right ∉ left } // MARK: Set Intersection infix operator ∩ { associativity left } func ∩<T: Equatable> (left: [T], right: [T]) -> [T] { var intersection: [T] = [] for value in left { if value ∈ right { intersection.append(value) } } return intersection } func ∩<T> (left: Set<T>, right: Set<T>) -> Set<T> { return left.intersect(right) } // MARK: Set Union infix operator ∪ { associativity left } func ∪<T: Equatable> (left: [T], right: [T]) -> [T] { var union: [T] = [] for value in left + right { if ¬(value ∈ union) { union.append(value) } } return union } func ∪<T> (left: Set<T>, right: Set<T>) -> Set<T> { return left.union(right) } // MARK: Subset infix operator ⊆ { associativity left } func ⊆<T: Equatable> (left: [T], right: [T]) -> Bool { return left == right || (left ⊂ right) } func ⊆<T> (left: Set<T>, right: Set<T>) -> Bool { return left.isSubsetOf(right) } // MARK: Proper Subset infix operator ⊂ { associativity left } func ⊂<T: Equatable> (left: [T], right: [T]) -> Bool { for value in left { if ¬(value ∈ right) { return false } } return true } func ⊂<T> (left: Set<T>, right: Set<T>) -> Bool { return left.isStrictSubsetOf(right) } // MARK: Not A Subset Of infix operator ⊄ { associativity left } func ⊄<T: Equatable> (left: [T], right: [T]) -> Bool { return ¬(left ⊂ right) } func ⊄<T> (left: Set<T>, right: Set<T>) -> Bool { return ¬(left ⊂ right) } // MARK: Superset infix operator ⊇ { associativity left } func ⊇<T: Equatable> (left: [T], right: [T]) -> Bool { return right ⊆ left } func ⊇<T> (left: Set<T>, right: Set<T>) -> Bool { return right ⊆ left } // MARK: Proper Superset infix operator ⊃ { associativity left } func ⊃<T: Equatable> (left: [T], right: [T]) -> Bool { return right ⊂ left } func ⊃<T> (left: Set<T>, right: Set<T>) -> Bool { return right ⊂ left } // MARK: Not A Superset Of infix operator ⊅ { associativity left } func ⊅<T: Equatable> (left: [T], right: [T]) -> Bool { return ¬(left ⊃ right) } func ⊅<T> (left: Set<T>, right: Set<T>) -> Bool { return ¬(left ⊃ right) } // MARK: - Sequences - // MARK: Summation prefix operator ∑ {} prefix func ∑ (values: [Double]) -> Double { return values.reduce(0.0, combine: +) } // MARK: Cartesian Product prefix operator ∏ {} prefix func ∏ (values: [Double]) -> Double { return values.reduce(1.0, combine: *) } // MARK: - Vectors - // MARK: Dot Product infix operator ⋅ {} func ⋅ (left: [Double], right: [Double]) -> Double { precondition(left.count == right.count, "arguments must have same count") let product = zip(left, right).map { (l, r) in l * r } return ∑product } // MARK: Cross Product func × (left: (Double, Double, Double), right: (Double, Double, Double)) -> (Double, Double, Double) { let a = left.1 * right.2 - left.2 * right.1 let b = left.2 * right.0 - left.0 * right.2 let c = left.0 * right.1 - left.1 * right.0 return (a, b, c) } // Mark: Norm prefix operator ‖ {} prefix func ‖ (vector: [Double]) -> Double { return √(∑vector.map({$0 * $0})) } // MARK: Angle infix operator ⦡ {} func ⦡ (left: [Double], right: [Double]) -> Double { return acos((left ⋅ right) / (‖left * ‖right)) } // MARK: - Comparison - // MARK: Equality infix operator ⩵ { associativity left } func ⩵<T: Equatable> (left: T, right: T) -> Bool { return left == right } // MARK: Inequality infix operator ≠ { associativity left } func ≠<T: Equatable> (left: T, right: T) -> Bool { return left != right } // MARK: Less Than Or Equal To infix operator ≤ { associativity left } func ≤<T: Comparable> (left: T, right: T) -> Bool { return left <= right } // MARK: Less Than And Not Equal To infix operator ≨ { associativity left } func ≨<T: Comparable> (left: T, right: T) -> Bool { return left < right && left != right } // MARK: Greater Than Or Equal To infix operator ≥ { associativity left } func ≥<T: Comparable> (left: T, right: T) -> Bool { return left >= right } // MARK: Greater Than And Not Equal To infix operator ≩ { associativity left } func ≩<T: Comparable> (left: T, right: T) -> Bool { return left > right && left != right } // MARK: Between infix operator ≬ { associativity left } func ≬<T: Comparable> (left: T, right: (T, T)) -> Bool { return left > right.0 && left < right.1 } // MARK: Approximate Equality infix operator ≈ { associativity left } func ≈(left: Double, right: Double) -> Bool { let 𝜺 = 1e-3 return abs(nextafter(left, right) - right) < 𝜺 } // MARK: Approximate Inequality infix operator ≉ { associativity left } func ≉(left: Double, right: Double) -> Bool { return !(left ≈ right) } // MARK: - Calculus - // MARK: 1st Derivative postfix operator ′ {} postfix func ′(function: (Double) -> (Double)) -> (Double) -> (Double) { let h = 1e-3 return { (x) in return round((function(x + h) - function(x - h)) / (2 * h) / h) * h } } // MARK: 2nd Derivative postfix operator ′′ {} postfix func ′′(function: (Double) -> (Double)) -> (Double) -> (Double) { return (function′)′ } // MARK: 3rd Derivative postfix operator ′′′ {} postfix func ′′′(function: (Double) -> (Double)) -> (Double) -> (Double) { return ((function′)′)′ } // MARK: Nth Derivative infix operator ′ { associativity left } func ′(left: (Double -> Double), right: UInt) -> (Double) -> (Double) { return (0 ..< right).reduce(left) { (function, _) in return function′ } } // MARK: Definite Integral infix operator ∫ { associativity left } func ∫(left: (a: Double, b: Double), right: (Double) -> (Double)) -> Double { let n = Int(1e2 + 1) let h = (left.b - left.a) / Double(n) return (h / 3.0) * (1 ..< n).reduce(right(left.a)) { let coefficient = $1 % 2 == 0 ? 4.0 : 2.0 return $0 + coefficient * right(left.a + Double($1) * h) } + right(left.b) } // MARK: Indefinite Integral / Antiderivative prefix operator ∫ {} prefix func ∫(function: (Double) -> (Double)) -> (Double) -> (Double) { return { x in return (0, x)∫function } } // MARK: - Functions - // MARK: Composition infix operator ∘ { associativity left } func ∘<T, U, V>(left: (U) -> (V), right: (T) -> (U)) -> (T) -> (V) { return { (x) in left(right(x)) } }
d7600ccc14b3b78c7a503e8f195d6402
22.009225
182
0.619277
false
false
false
false
xu6148152/binea_project_for_ios
refs/heads/master
helloworld1/helloworld1/ViewController.swift
mit
1
// // ViewController.swift // helloworld1 // // Created by Binea Xu on 15/2/20. // Copyright (c) 2015年 Binea Xu. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // println("Hello, world") // let implicitFloat:Float = 4 // println(implicitFloat) // let label = "The width is" // let width = 94 // let widthLabel = label // println(widthLabel) let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25], ] var largest = 0 var largestType:String = "" for (kind, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number largestType = kind } } } // var result = "largestType \(largestType) largest \(largest)" println("largestType \(largestType) largest \(largest)") // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
ae5ed804bfafb6123de67a70957164a5
26.14
80
0.540162
false
false
false
false
IngmarStein/swift
refs/heads/master
test/SILGen/specialize_attr.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen -emit-verbose-sil %s | %FileCheck %s // CHECK-LABEL: @_specialize(Int, Float) // CHECK-NEXT: func specializeThis<T, U>(_ t: T, u: U) @_specialize(Int, Float) func specializeThis<T, U>(_ t: T, u: U) {} public protocol PP { associatedtype PElt } public protocol QQ { associatedtype QElt } public struct RR : PP { public typealias PElt = Float } public struct SS : QQ { public typealias QElt = Int } public struct GG<T : PP> {} // CHECK-LABEL: public class CC<T : PP> { // CHECK-NEXT: @_specialize(RR, SS) // CHECK-NEXT: @inline(never) public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) public class CC<T : PP> { @inline(never) @_specialize(RR, SS) public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) { return (u, g) } } // CHECK-LABEL: sil hidden [_specialize <Int, Float>] @_TF15specialize_attr14specializeThisu0_rFTx1uq__T_ : $@convention(thin) <T, U> (@in T, @in U) -> () { // CHECK-LABEL: sil [noinline] [_specialize <RR, SS, Float, Int>] @_TFC15specialize_attr2CC3foouRd__S_2QQrfTqd__1gGVS_2GGx__Tqd__GS2_x__ : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) { // ----------------------------------------------------------------------------- // Test user-specialized subscript accessors. public protocol TestSubscriptable { associatedtype Element subscript(i: Int) -> Element { get set } } public class ASubscriptable<Element> : TestSubscriptable { var storage: UnsafeMutablePointer<Element> init(capacity: Int) { storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity) } public subscript(i: Int) -> Element { @_specialize(Int) get { return storage[i] } @_specialize(Int) set(rhs) { storage[i] = rhs } } } // ASubscriptable.subscript.getter with _specialize // CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr14ASubscriptableg9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed ASubscriptable<Element>) -> @out Element { // ASubscriptable.subscript.setter with _specialize // CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr14ASubscriptables9subscriptFSix : $@convention(method) <Element> (@in Element, Int, @guaranteed ASubscriptable<Element>) -> () { // ASubscriptable.subscript.materializeForSet with no attribute // CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr14ASubscriptablem9subscriptFSix : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed ASubscriptable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { public class Addressable<Element> : TestSubscriptable { var storage: UnsafeMutablePointer<Element> init(capacity: Int) { storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity) } public subscript(i: Int) -> Element { @_specialize(Int) unsafeAddress { return UnsafePointer<Element>(storage + i) } @_specialize(Int) unsafeMutableAddress { return UnsafeMutablePointer<Element>(storage + i) } } } // Addressable.subscript.unsafeAddressor with _specialize // CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr11Addressablelu9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafePointer<Element> { // Addressable.subscript.unsafeMutableAddressor with _specialize // CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr11Addressableau9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafeMutablePointer<Element> { // Addressable.subscript.getter with no attribute // CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr11Addressableg9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> @out Element { // Addressable.subscript.setter with no attribute // CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr11Addressables9subscriptFSix : $@convention(method) <Element> (@in Element, Int, @guaranteed Addressable<Element>) -> () { // Addressable.subscript.materializeForSet with no attribute // CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr11Addressablem9subscriptFSix : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed Addressable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
0d46df8dfc5e81222d8603f2e8cd917a
40.194444
283
0.70263
false
false
false
false
square/wire
refs/heads/master
wire-library/wire-runtime-swift/src/main/swift/ProtoIntCodable+Implementations.swift
apache-2.0
1
/* * Copyright 2020 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation // MARK: - extension Int32: ProtoIntCodable { // MARK: - ProtoIntDecodable public init(from reader: ProtoReader, encoding: ProtoIntEncoding) throws { switch encoding { case .fixed: // sfixed32 fields self = try Int32(bitPattern: reader.readFixed32()) case .signed: // sint32 fields self = try reader.readVarint32().zigZagDecoded() case .variable: // int32 fields self = try Int32(bitPattern: reader.readVarint32()) } } // MARK: - ProtoIntEncodable /** Encode an `int32`, `sfixed32`, or `sint32` field */ public func encode(to writer: ProtoWriter, encoding: ProtoIntEncoding) throws { switch encoding { case .fixed: // sfixed32 fields writer.writeFixed32(self) case .signed: // sint32 fields writer.writeVarint(zigZagEncoded()) case .variable: // int32 fields writer.writeVarint(UInt32(bitPattern: self)) } } } // MARK: - extension UInt32: ProtoIntCodable { // MARK: - ProtoIntDecodable public init(from reader: ProtoReader, encoding: ProtoIntEncoding) throws { switch encoding { case .fixed: // fixed32 fields self = try reader.readFixed32() case .signed: fatalError("Unsupported") case .variable: // uint32 fields self = try reader.readVarint32() } } // MARK: - ProtoIntEncodable /** Encode a `uint32` or `fixed32` field */ public func encode(to writer: ProtoWriter, encoding: ProtoIntEncoding) throws { switch encoding { case .fixed: // fixed32 fields writer.writeFixed32(self) case .signed: fatalError("Unsupported") case .variable: // uint32 fields writer.writeVarint(self) } } } // MARK: - extension Int64: ProtoIntCodable { // MARK: - ProtoIntDecodable public init(from reader: ProtoReader, encoding: ProtoIntEncoding) throws { switch encoding { case .fixed: // sfixed64 fields self = try Int64(bitPattern: reader.readFixed64()) case .signed: // sint64 fields self = try reader.readVarint64().zigZagDecoded() case .variable: // int64 fields self = try Int64(bitPattern: reader.readVarint64()) } } // MARK: - ProtoIntEncodable /** Encode `int64`, `sint64`, or `sfixed64` field */ public func encode(to writer: ProtoWriter, encoding: ProtoIntEncoding) throws { switch encoding { case .fixed: // sfixed64 fields writer.writeFixed64(self) case .signed: // sint64 fields writer.writeVarint(zigZagEncoded()) case .variable: // int64 fields writer.writeVarint(UInt64(bitPattern: self)) } } } // MARK: - extension UInt64: ProtoIntCodable { // MARK: - ProtoIntDecodable public init(from reader: ProtoReader, encoding: ProtoIntEncoding) throws { switch encoding { case .fixed: // fixed64 fields self = try reader.readFixed64() case .signed: fatalError("Unsupported") case .variable: // uint64 fields self = try reader.readVarint64() } } // MARK: - ProtoIntEncodable /** Encode a `uint64` or `fixed64` field */ public func encode(to writer: ProtoWriter, encoding: ProtoIntEncoding) throws { switch encoding { case .fixed: // fixed64 fields writer.writeFixed64(self) case .signed: fatalError("Unsupported") case .variable: // uint64 fields writer.writeVarint(self) } } }
a0103106e519d388634967bc135f1ba3
26.005917
83
0.584575
false
false
false
false
watson-developer-cloud/ios-sdk
refs/heads/master
Sources/DiscoveryV1/Models/SourceOptions.swift
apache-2.0
1
/** * (C) Copyright IBM Corp. 2018, 2020. * * 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 /** The **options** object defines which items to crawl from the source system. */ public struct SourceOptions: Codable, Equatable { /** Array of folders to crawl from the Box source. Only valid, and required, when the **type** field of the **source** object is set to `box`. */ public var folders: [SourceOptionsFolder]? /** Array of Salesforce document object types to crawl from the Salesforce source. Only valid, and required, when the **type** field of the **source** object is set to `salesforce`. */ public var objects: [SourceOptionsObject]? /** Array of Microsoft SharePointoint Online site collections to crawl from the SharePoint source. Only valid and required when the **type** field of the **source** object is set to `sharepoint`. */ public var siteCollections: [SourceOptionsSiteColl]? /** Array of Web page URLs to begin crawling the web from. Only valid and required when the **type** field of the **source** object is set to `web_crawl`. */ public var urls: [SourceOptionsWebCrawl]? /** Array of cloud object store buckets to begin crawling. Only valid and required when the **type** field of the **source** object is set to `cloud_object_store`, and the **crawl_all_buckets** field is `false` or not specified. */ public var buckets: [SourceOptionsBuckets]? /** When `true`, all buckets in the specified cloud object store are crawled. If set to `true`, the **buckets** array must not be specified. */ public var crawlAllBuckets: Bool? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case folders = "folders" case objects = "objects" case siteCollections = "site_collections" case urls = "urls" case buckets = "buckets" case crawlAllBuckets = "crawl_all_buckets" } /** Initialize a `SourceOptions` with member variables. - parameter folders: Array of folders to crawl from the Box source. Only valid, and required, when the **type** field of the **source** object is set to `box`. - parameter objects: Array of Salesforce document object types to crawl from the Salesforce source. Only valid, and required, when the **type** field of the **source** object is set to `salesforce`. - parameter siteCollections: Array of Microsoft SharePointoint Online site collections to crawl from the SharePoint source. Only valid and required when the **type** field of the **source** object is set to `sharepoint`. - parameter urls: Array of Web page URLs to begin crawling the web from. Only valid and required when the **type** field of the **source** object is set to `web_crawl`. - parameter buckets: Array of cloud object store buckets to begin crawling. Only valid and required when the **type** field of the **source** object is set to `cloud_object_store`, and the **crawl_all_buckets** field is `false` or not specified. - parameter crawlAllBuckets: When `true`, all buckets in the specified cloud object store are crawled. If set to `true`, the **buckets** array must not be specified. - returns: An initialized `SourceOptions`. */ public init( folders: [SourceOptionsFolder]? = nil, objects: [SourceOptionsObject]? = nil, siteCollections: [SourceOptionsSiteColl]? = nil, urls: [SourceOptionsWebCrawl]? = nil, buckets: [SourceOptionsBuckets]? = nil, crawlAllBuckets: Bool? = nil ) { self.folders = folders self.objects = objects self.siteCollections = siteCollections self.urls = urls self.buckets = buckets self.crawlAllBuckets = crawlAllBuckets } }
a52436bf7f15588841e7cce3cdb0d5a5
41.140187
119
0.674872
false
false
false
false
apple/swift-nio
refs/heads/main
Sources/NIOCore/IPProtocol.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// /// In the Internet Protocol version 4 (IPv4) [RFC791] there is a field /// called "Protocol" to identify the next level protocol. This is an 8 /// bit field. In Internet Protocol version 6 (IPv6) [RFC8200], this field /// is called the "Next Header" field. public struct NIOIPProtocol: RawRepresentable, Hashable { public typealias RawValue = UInt8 public var rawValue: RawValue @inlinable public init(rawValue: RawValue) { self.rawValue = rawValue } } extension NIOIPProtocol { /// - precondition: `rawValue` must fit into an `UInt8` public init(_ rawValue: Int) { self.init(rawValue: UInt8(rawValue)) } } // Subset of https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml with an RFC extension NIOIPProtocol { /// IPv6 Hop-by-Hop Option - [RFC8200] public static let hopopt = Self(rawValue: 0) /// Internet Control Message - [RFC792] public static let icmp = Self(rawValue: 1) /// Internet Group Management - [RFC1112] public static let igmp = Self(rawValue: 2) /// Gateway-to-Gateway - [RFC823] public static let ggp = Self(rawValue: 3) /// IPv4 encapsulation - [RFC2003] public static let ipv4 = Self(rawValue: 4) /// Stream - [RFC1190][RFC1819] public static let st = Self(rawValue: 5) /// Transmission Control - [RFC9293] public static let tcp = Self(rawValue: 6) /// Exterior Gateway Protocol - [RFC888][David_Mills] public static let egp = Self(rawValue: 8) /// Network Voice Protocol - [RFC741][Steve_Casner] public static let nvpIi = Self(rawValue: 11) /// User Datagram - [RFC768][Jon_Postel] public static let udp = Self(rawValue: 17) /// Host Monitoring - [RFC869][Bob_Hinden] public static let hmp = Self(rawValue: 20) /// Reliable Data Protocol - [RFC908][Bob_Hinden] public static let rdp = Self(rawValue: 27) /// Internet Reliable Transaction - [RFC938][Trudy_Miller] public static let irtp = Self(rawValue: 28) /// ISO Transport Protocol Class 4 - [RFC905][<mystery contact>] public static let isoTp4 = Self(rawValue: 29) /// Bulk Data Transfer Protocol - [RFC969][David_Clark] public static let netblt = Self(rawValue: 30) /// Datagram Congestion Control Protocol - [RFC4340] public static let dccp = Self(rawValue: 33) /// IPv6 encapsulation - [RFC2473] public static let ipv6 = Self(rawValue: 41) /// Reservation Protocol - [RFC2205][RFC3209][Bob_Braden] public static let rsvp = Self(rawValue: 46) /// Generic Routing Encapsulation - [RFC2784][Tony_Li] public static let gre = Self(rawValue: 47) /// Dynamic Source Routing Protocol - [RFC4728] public static let dsr = Self(rawValue: 48) /// Encap Security Payload - [RFC4303] public static let esp = Self(rawValue: 50) /// Authentication Header - [RFC4302] public static let ah = Self(rawValue: 51) /// NBMA Address Resolution Protocol - [RFC1735] public static let narp = Self(rawValue: 54) /// ICMP for IPv6 - [RFC8200] public static let ipv6Icmp = Self(rawValue: 58) /// No Next Header for IPv6 - [RFC8200] public static let ipv6Nonxt = Self(rawValue: 59) /// Destination Options for IPv6 - [RFC8200] public static let ipv6Opts = Self(rawValue: 60) /// EIGRP - [RFC7868] public static let eigrp = Self(rawValue: 88) /// OSPFIGP - [RFC1583][RFC2328][RFC5340][John_Moy] public static let ospfigp = Self(rawValue: 89) /// Ethernet-within-IP Encapsulation - [RFC3378] public static let etherip = Self(rawValue: 97) /// Encapsulation Header - [RFC1241][Robert_Woodburn] public static let encap = Self(rawValue: 98) /// Protocol Independent Multicast - [RFC7761][Dino_Farinacci] public static let pim = Self(rawValue: 103) /// IP Payload Compression Protocol - [RFC2393] public static let ipcomp = Self(rawValue: 108) /// Virtual Router Redundancy Protocol - [RFC5798] public static let vrrp = Self(rawValue: 112) /// Layer Two Tunneling Protocol - [RFC3931][Bernard_Aboba] public static let l2tp = Self(rawValue: 115) /// Fibre Channel - [Murali_Rajagopal][RFC6172] public static let fc = Self(rawValue: 133) /// MANET Protocols - [RFC5498] public static let manet = Self(rawValue: 138) /// Host Identity Protocol - [RFC7401] public static let hip = Self(rawValue: 139) /// Shim6 Protocol - [RFC5533] public static let shim6 = Self(rawValue: 140) /// Wrapped Encapsulating Security Payload - [RFC5840] public static let wesp = Self(rawValue: 141) /// Robust Header Compression - [RFC5858] public static let rohc = Self(rawValue: 142) /// Ethernet - [RFC8986] public static let ethernet = Self(rawValue: 143) /// AGGFRAG encapsulation payload for ESP - [RFC-ietf-ipsecme-iptfs-19] public static let aggfrag = Self(rawValue: 144) } extension NIOIPProtocol: CustomStringConvertible { private var name: String? { switch self { case .hopopt: return "IPv6 Hop-by-Hop Option" case .icmp: return "Internet Control Message" case .igmp: return "Internet Group Management" case .ggp: return "Gateway-to-Gateway" case .ipv4: return "IPv4 encapsulation" case .st: return "Stream" case .tcp: return "Transmission Control" case .egp: return "Exterior Gateway Protocol" case .nvpIi: return "Network Voice Protocol" case .udp: return "User Datagram" case .hmp: return "Host Monitoring" case .rdp: return "Reliable Data Protocol" case .irtp: return "Internet Reliable Transaction" case .isoTp4: return "ISO Transport Protocol Class 4" case .netblt: return "Bulk Data Transfer Protocol" case .dccp: return "Datagram Congestion Control Protocol" case .ipv6: return "IPv6 encapsulation" case .rsvp: return "Reservation Protocol" case .gre: return "Generic Routing Encapsulation" case .dsr: return "Dynamic Source Routing Protocol" case .esp: return "Encap Security Payload" case .ah: return "Authentication Header" case .narp: return "NBMA Address Resolution Protocol" case .ipv6Icmp: return "ICMP for IPv6" case .ipv6Nonxt: return "No Next Header for IPv6" case .ipv6Opts: return "Destination Options for IPv6" case .eigrp: return "EIGRP" case .ospfigp: return "OSPFIGP" case .etherip: return "Ethernet-within-IP Encapsulation" case .encap: return "Encapsulation Header" case .pim: return "Protocol Independent Multicast" case .ipcomp: return "IP Payload Compression Protocol" case .vrrp: return "Virtual Router Redundancy Protocol" case .l2tp: return "Layer Two Tunneling Protocol" case .fc: return "Fibre Channel" case .manet: return "MANET Protocols" case .hip: return "Host Identity Protocol" case .shim6: return "Shim6 Protocol" case .wesp: return "Wrapped Encapsulating Security Payload" case .rohc: return "Robust Header Compression" case .ethernet: return "Ethernet" case .aggfrag: return "AGGFRAG encapsulation payload for ESP" default: return nil } } public var description: String { let name = self.name ?? "Unknown Protocol" return "\(name) - \(rawValue)" } }
8b31644b4ffef748ee3ca8bc65826909
43.779661
97
0.655816
false
false
false
false
bigscreen/mangindo-ios
refs/heads/master
Mangindo/Modules/Contents/ContentsModule.swift
mit
1
// // ContentsModule.swift // Mangindo // // Created by Gallant Pratama on 27/11/18. // Copyright © 2018 Gallant Pratama. All rights reserved. // import UIKit class ContentsModule { private let segue: UIStoryboardSegue init(segue: UIStoryboardSegue) { self.segue = segue } func instantiate(pageTitle: String, mangaTitleId: String, chapter: Int) { let controller = segue.destination as! ContentsViewController let presenter = ContentsPresenter(view: controller, service: NetworkService.shared, mangaTitleId: mangaTitleId, chapter: chapter) controller.pageTitle = pageTitle controller.presenter = presenter } }
a13f4f8ff108cd376f9cd67b299a903c
26.6
137
0.694203
false
false
false
false
vapor/vapor
refs/heads/main
Sources/Vapor/HTTP/Headers/HTTPHeaderExpires.swift
mit
1
import NIO extension HTTPHeaders { public struct Expires { /// The date represented by the header. public let expires: Date internal static func parse(_ dateString: String) -> Expires? { // https://tools.ietf.org/html/rfc7231#section-7.1.1.1 let fmt = DateFormatter() fmt.locale = Locale(identifier: "en_US_POSIX") fmt.timeZone = TimeZone(secondsFromGMT: 0) fmt.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz" if let date = fmt.date(from: dateString) { return .init(expires: date) } // Obsolete RFC 850 format fmt.dateFormat = "EEEE, dd-MMM-yy HH:mm:ss zzz" if let date = fmt.date(from: dateString) { return .init(expires: date) } // Obsolete ANSI C asctime() format fmt.dateFormat = "EEE MMM d HH:mm:s yyyy" if let date = fmt.date(from: dateString) { return .init(expires: date) } return nil } init(expires: Date) { self.expires = expires } /// Generates the header string for this instance. public func serialize() -> String { let fmt = DateFormatter() fmt.locale = Locale(identifier: "en_US_POSIX") fmt.timeZone = TimeZone(secondsFromGMT: 0) fmt.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz" return fmt.string(from: expires) } } /// Gets the value of the `Expires` header, if present. /// ### Note ### /// `Expires` is legacy and you should switch to using `CacheControl` if possible. public var expires: Expires? { get { self.first(name: .expires).flatMap(Expires.parse) } set { if let new = newValue?.serialize() { self.replaceOrAdd(name: .expires, value: new) } else { self.remove(name: .expires) } } } }
a0963e5291c0aa430ec637cbb1a1bb6c
31.596774
86
0.531915
false
true
false
false
simonkim/AVCapture
refs/heads/master
AVCapture/AVEncoderVideoToolbox/CoreMedia.swift
apache-2.0
1
// // CMVideoFormatDescription.swift // AVCapture // // Created by Simon Kim on 2016. 9. 10.. // Copyright © 2016 DZPub.com. All rights reserved. // import Foundation import CoreMedia extension CMVideoFormatDescription { /* * returns number of parameter sets and size of NALUnitLength in bytes */ func getH264ParameterSetInfo() -> (status: OSStatus, count: Int, NALHeaderLength: Int32) { var count: Int = 0 var NALHeaderLength: Int32 = 0 // get parameter set count and nal header length let status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( self, 0, nil, nil, &count, &NALHeaderLength) return (status: status, count: count, NALHeaderLength: NALHeaderLength) } func getH264ParameterSet(at index:Int) -> (status: OSStatus, p: UnsafePointer<UInt8>?, length: Int){ var pParamSet: UnsafePointer<UInt8>? = nil var length: Int = 0 let status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( self, index, &pParamSet, &length, nil, nil) return (status: status, p: pParamSet, length: length) } } public extension CMSampleBuffer { public var formatDescription: CMFormatDescription? { return CMSampleBufferGetFormatDescription(self) } public var sampleTimingInfo: CMSampleTimingInfo? { get { var timingInfo: CMSampleTimingInfo? = CMSampleTimingInfo() let status = CMSampleBufferGetSampleTimingInfo(self, 0, &timingInfo!) if ( status != noErr ) { timingInfo = nil } return timingInfo } } public var presentationTimeStamp: CMTime { return CMSampleBufferGetPresentationTimeStamp(self) } public var decodeTimeStamp: CMTime { return CMSampleBufferGetDecodeTimeStamp(self) } public func makeDataReady() -> OSStatus { return CMSampleBufferMakeDataReady(self) } } extension CMFormatDescription { public var mediaSubType: FourCharCode { return CMFormatDescriptionGetMediaSubType(self) } } extension CMVideoDimensions: Equatable { public static func == (lhs: CMVideoDimensions, rhs: CMVideoDimensions) -> Bool { return lhs.width == rhs.width && lhs.height == rhs.height } }
eb0a44d089b1a39c40561729301d5228
28.580247
104
0.642738
false
false
false
false
nslogo/DouYuZB
refs/heads/master
DouYuZB/DouYuZB/Classes/Home/Controller/RecommendViewController.swift
mit
1
// // RecommendViewController.swift // DouYuZB // // Created by nie on 16/9/21. // Copyright © 2016年 ZoroNie. All rights reserved. // import UIKit fileprivate let kItemMargin : CGFloat = 10 fileprivate let kItemW = (kScreenW - 3 * kItemMargin) / 2 fileprivate let kNormalItemH = kItemW * 3 / 4 fileprivate let kPrettyItemH = kItemW * 4 / 3 fileprivate let kHeaderViewH : CGFloat = 50 fileprivate let kNormalCellID = "kNormalCellID" fileprivate let kPrettyCellID = "kPrettyCellID" fileprivate let kHeaderViewID = "KHeaderViewID" class RecommendViewController: UIViewController { //懒加载 fileprivate lazy var collectionView : UICollectionView = { [unowned self] in //创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)//头 //创建uicollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]//设置页面随着父控件的缩小尔缩小 collectionView.dataSource = self collectionView.delegate = self //注册cell //代码创建默认cell注册 //collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kNormalCellID) //NIB创建默认cell注册 collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil) , forCellWithReuseIdentifier: kNormalCellID) //NIB创建颜值cell注册 collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil) , forCellWithReuseIdentifier: kPrettyCellID) //注册header //代码创建注册 //collectionView.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KHeaderViewID) //NIB创建注册 collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) collectionView.backgroundColor = UIColor.white return collectionView }() //系统回调函数 override func viewDidLoad() { super.viewDidLoad() //创建UI setUpUI() // UINib(nibName: "CollectionNormalCell", bundle: nil) } } // MARK: - 设置 UI extension RecommendViewController { fileprivate func setUpUI() { view.addSubview(collectionView) } } // MARK: - UICollectionViewDataSource extension RecommendViewController : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 12 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { return 8 } return 4 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kItemW, height: kPrettyItemH) } return CGSize(width: kItemW, height: kNormalItemH) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var cell : UICollectionViewCell! if indexPath.section == 1 { cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) } else { cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) } //cell.backgroundColor = UIColor.blue return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView return headerView } }
7040adae92a924e7cd65fbd0b1e0c99f
36.279661
186
0.700386
false
false
false
false
edragoev1/pdfjet
refs/heads/master
Sources/PDFjet/Courier_BoldOblique.swift
mit
1
class Courier_BoldOblique { static let name = "Courier-BoldOblique" static let bBoxLLx: Int16 = -57 static let bBoxLLy: Int16 = -250 static let bBoxURx: Int16 = 869 static let bBoxURy: Int16 = 801 static let underlinePosition: Int16 = -100 static let underlineThickness: Int16 = 50 static let notice = "Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved." static let metrics = Array<[Int16]>(arrayLiteral: [32,600], [33,600], [34,600], [35,600], [36,600], [37,600], [38,600], [39,600], [40,600], [41,600], [42,600], [43,600], [44,600], [45,600], [46,600], [47,600], [48,600], [49,600], [50,600], [51,600], [52,600], [53,600], [54,600], [55,600], [56,600], [57,600], [58,600], [59,600], [60,600], [61,600], [62,600], [63,600], [64,600], [65,600], [66,600], [67,600], [68,600], [69,600], [70,600], [71,600], [72,600], [73,600], [74,600], [75,600], [76,600], [77,600], [78,600], [79,600], [80,600], [81,600], [82,600], [83,600], [84,600], [85,600], [86,600], [87,600], [88,600], [89,600], [90,600], [91,600], [92,600], [93,600], [94,600], [95,600], [96,600], [97,600], [98,600], [99,600], [100,600], [101,600], [102,600], [103,600], [104,600], [105,600], [106,600], [107,600], [108,600], [109,600], [110,600], [111,600], [112,600], [113,600], [114,600], [115,600], [116,600], [117,600], [118,600], [119,600], [120,600], [121,600], [122,600], [123,600], [124,600], [125,600], [126,600], [127,600], [128,600], [129,600], [130,600], [131,600], [132,600], [133,600], [134,600], [135,600], [136,600], [137,600], [138,600], [139,600], [140,600], [141,600], [142,600], [143,600], [144,600], [145,600], [146,600], [147,600], [148,600], [149,600], [150,600], [151,600], [152,600], [153,600], [154,600], [155,600], [156,600], [157,600], [158,600], [159,600], [160,600], [161,600], [162,600], [163,600], [164,600], [165,600], [166,600], [167,600], [168,600], [169,600], [170,600], [171,600], [172,600], [173,600], [174,600], [175,600], [176,600], [177,600], [178,600], [179,600], [180,600], [181,600], [182,600], [183,600], [184,600], [185,600], [186,600], [187,600], [188,600], [189,600], [190,600], [191,600], [192,600], [193,600], [194,600], [195,600], [196,600], [197,600], [198,600], [199,600], [200,600], [201,600], [202,600], [203,600], [204,600], [205,600], [206,600], [207,600], [208,600], [209,600], [210,600], [211,600], [212,600], [213,600], [214,600], [215,600], [216,600], [217,600], [218,600], [219,600], [220,600], [221,600], [222,600], [223,600], [224,600], [225,600], [226,600], [227,600], [228,600], [229,600], [230,600], [231,600], [232,600], [233,600], [234,600], [235,600], [236,600], [237,600], [238,600], [239,600], [240,600], [241,600], [242,600], [243,600], [244,600], [245,600], [246,600], [247,600], [248,600], [249,600], [250,600], [251,600], [252,600], [253,600], [254,600], [255,600] ) }
87c4365eba0cc68b11c6a7e771b4245d
18.817797
117
0.345734
false
false
false
false
dipen30/Qmote
refs/heads/master
KodiRemote/KodiRemote/Controllers/MovieDetailsViewController.swift
apache-2.0
1
// // MovieDetailsViewController.swift // Kodi Remote // // Created by Quixom Technology on 19/08/16. // Copyright © 2016 Quixom Technology. All rights reserved. // import UIKit class MovieDetailsViewController: UIViewController { @IBOutlet var movieArtImage: UIImageView! @IBOutlet var movieImage: UIImageView! @IBOutlet var movieName: UILabel! @IBOutlet var movieTagline: UILabel! @IBOutlet var movieRuntime: UILabel! @IBOutlet var movieGenre: UILabel! @IBOutlet var movieRatings: UILabel! @IBOutlet var moviePlot: UITextView! @IBOutlet weak var movieDirectors: UILabel! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var playButtonTop: NSLayoutConstraint! @IBOutlet weak var downloadButton: UIButton! var url: URL! var videoTitle: String! var fileHash: String! var movieid = Int() var moviefile = String() var movieView: UIView! var rc: RemoteCalls! override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.rc = RemoteCalls(ipaddress: global_ipaddress, port: global_port) movie_id = movieid self.rc.jsonRpcCall("VideoLibrary.GetMovieDetails", params: "{\"movieid\":\(movieid),\"properties\":[\"genre\",\"year\",\"rating\",\"director\",\"trailer\",\"tagline\",\"plot\",\"imdbnumber\",\"runtime\",\"votes\",\"thumbnail\",\"art\"]}"){(response: AnyObject?) in DispatchQueue.main.async { self.generateResponse(response as! NSDictionary) self.playButton.isHidden = false self.downloadButton.isHidden = false } } self.moviefile = self.moviefile.replacingOccurrences(of: "\\", with: "/") self.rc.jsonRpcCall("Files.PrepareDownload", params: "{\"path\":\"\(self.moviefile)\"}"){ (response: AnyObject?) in let data = response as! NSDictionary let path = "/" + String(describing: (data["details"] as! NSDictionary)["path"]!) let host = "http://" + global_ipaddress + ":" + global_port self.url = URL(string: host + path) // if Same video is already in progress then do not allow user // to download the video self.fileHash = md5(string: self.url.lastPathComponent) if downloadQueue[self.fileHash] != nil{ DispatchQueue.main.async { self.downloadButton.isEnabled = false } downloadQueue[self.fileHash] = self.downloadButton } // change the color of download icon if file exists if is_file_exists("Videos", filename: self.url!.lastPathComponent){ DispatchQueue.main.async { self.downloadButton.tintColor = UIColor(red:0.01, green:0.66, blue:0.96, alpha:1.0) } } } } deinit { movie_id = 0 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.updateViewBasedOnScreenSize() self.playButton.layer.cornerRadius = 0.5 * self.playButton.bounds.size.width self.playButton.layer.borderWidth = 2.0 self.playButton.layer.borderColor = UIColor(red:0.00, green:0.80, blue:1.00, alpha:1.0).cgColor self.playButton.clipsToBounds = true self.movieName.text = "" self.movieTagline.text = "" self.movieRuntime.text = "" self.movieGenre.text = "" self.movieRatings.text = "" self.moviePlot.text = "" self.movieDirectors.text = "" } func updateViewBasedOnScreenSize(){ // Updated constrains based on screen size let viewWidth = self.view.bounds.size.width if viewWidth < 350 { self.playButtonTop.constant = 135.0 }else if viewWidth > 350 && viewWidth < 400 { self.playButtonTop.constant = 145.0 }else if viewWidth > 400 { self.playButtonTop.constant = 160.0 } } @IBAction func playMovie(_ sender: AnyObject) { self.rc.jsonRpcCall("Player.Open", params: "{\"item\":{\"movieid\":\(self.movieid)}}"){ (response: AnyObject?) in } } func generateResponse(_ jsonData: AnyObject){ let movieDetails = jsonData["moviedetails"] as! NSDictionary self.movieName.text = String(describing: movieDetails["label"]!) self.videoTitle = String(describing: movieDetails["label"]!) self.movieTagline.text = String(describing: movieDetails["tagline"]!) self.movieRuntime.text = String((movieDetails["runtime"]! as! Int) / 60) + " min | " + String(describing: movieDetails["year"]!) self.movieGenre.text = String((movieDetails["genre"]! as AnyObject).componentsJoined(by: ", ")) self.movieRatings.text = String(format: "%.1f", movieDetails["rating"]! as! Double) + "/10" self.moviePlot.text = String(describing: movieDetails["plot"]!) self.movieDirectors.text = "Directors: " + String((movieDetails["director"]! as AnyObject).componentsJoined(by: ", ")) self.movieImage.contentMode = .scaleAspectFit self.movieImage.layer.zPosition = 1 let thumbnail = String(describing: movieDetails["thumbnail"]!) if thumbnail != "" { let url = URL(string: getThumbnailUrl(thumbnail)) self.movieImage.kf.setImage(with: url!) } self.movieArtImage.contentMode = .scaleAspectFill let art = movieDetails["art"] as! NSDictionary if (art as AnyObject).count != 0 { let fanart = art["fanart"] as! String if fanart != "" { let url = URL(string: getThumbnailUrl(fanart)) self.movieArtImage.kf.setImage(with: url!) } } } @IBAction func downloadMovie(_ sender: AnyObject) { if is_file_exists("Videos", filename: self.url!.lastPathComponent){ print("Play Video locally") // let videoUrl = getLocalFilePath("Videos", filename: self.url!.lastPathComponent!) // let playerVC = MobilePlayerViewController(contentURL: videoUrl) // playerVC.title = self.videoTitle // playerVC.activityItems = [videoUrl] // presentMoviePlayerViewControllerAnimated(playerVC) }else{ if downloadQueue[self.fileHash] != nil{ print("Downloading for this file is in progress") }else{ downloadQueue.setValue(self.downloadButton, forKey: self.fileHash) Downloader(destdirname: "Videos").download(self.url!) self.downloadButton.isEnabled = false } } } }
a1b50ed9a679029bcdcb8a32867be411
38.056497
273
0.59728
false
false
false
false
rnystrom/GitHawk
refs/heads/master
Classes/Issues/DiffHunk/IssueDiffHunkPathCell.swift
mit
1
// // IssueDiffHunkPathCell.swift // Freetime // // Created by Ryan Nystrom on 7/3/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit final class IssueDiffHunkPathCell: UICollectionViewCell, ListBindable { let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) contentView.backgroundColor = Styles.Colors.Gray.lighter.color label.adjustsFontSizeToFitWidth = true label.textColor = Styles.Colors.Gray.dark.color label.font = Styles.Text.code.preferredFont contentView.addSubview(label) label.snp.makeConstraints { make in make.centerY.equalToSuperview() make.left.equalToSuperview() make.width.lessThanOrEqualToSuperview().offset(-Styles.Sizes.rowSpacing) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() layoutContentView() } // MARK: ListBindable func bindViewModel(_ viewModel: Any) { guard let viewModel = viewModel as? String else { return } label.text = viewModel } }
483e28c11e6029f49a6b14080248893a
24.916667
84
0.662379
false
false
false
false
NemProject/NEMiOSApp
refs/heads/develop
NEMWallet/Models/BlockModel.swift
mit
1
// // BlockModel.swift // // This file is covered by the LICENSE file in the root of this project. // Copyright (c) 2016 NEM // import Foundation import SwiftyJSON /** Represents a block on the NEM blockchain. Visit the [documentation](http://bob.nem.ninja/docs/#harvestInfo) for more information. */ public class Block: SwiftyJSONMappable { // MARK: - Model Properties /// The id of the block. public var id: Int! /// The height of the block. public var height: Int! /// The total fee collected by harvesting the block. public var totalFee: Int! /// The number of seconds elapsed since the creation of the nemesis block. public var timeStamp: Int! /// The block difficulty. public var difficulty: Int! // MARK: - Model Lifecycle public required init?(jsonData: JSON) { id = jsonData["id"].intValue height = jsonData["height"].intValue totalFee = jsonData["totalFee"].intValue timeStamp = jsonData["timeStamp"].intValue difficulty = jsonData["difficulty"].intValue } }
049f1d66b939a52fb22616f8c9719cb7
24.155556
78
0.634276
false
false
false
false
red-spotted-newts-2014/rest-less-ios
refs/heads/master
Rest Less/workoutClass.playground/section-1.swift
mit
1
import UIKit class WorkoutLogger { var userName: String var workoutName: String var reps = [String]() var plannedTimes: [Int] var actualTimes = [Double]() var finalTime = Double() var missedReps: Int { get { return reps.count - actualTimes.count } } init(userName:String, workoutName:String, plannedTimes:[Int]) { self.userName = userName self.workoutName = workoutName self.plannedTimes = plannedTimes } func addRestTime(val:Double) -> Double { self.actualTimes.append(val) return self.actualTimes.last! } func returnDictInfo() -> [String:String]{ return ["userName": self.userName, "workoutName": self.workoutName, "times": "\(self.actualTimes)", "finalTime" : "\(self.finalTime)", "missedReps" : "\(self.missedReps)"] } }
5bafcb397513592130c89723c569c125
19.041667
67
0.557173
false
false
false
false
CNKCQ/oschina
refs/heads/master
Pods/Foundation+/Foundation+/String+.swift
mit
1
// // String+.swift // Elegant // // Created by Steve on 2017/5/18. // Copyright © 2017年 KingCQ. All rights reserved. // import Foundation public extension String { /// Returns floatValue var float: Float? { let numberFormatter = NumberFormatter() return numberFormatter.number(from: self)?.floatValue } /// Returns doubleValue var double: Double? { let numberFormatter = NumberFormatter() return numberFormatter.number(from: self)?.doubleValue } /// The string length property returns the count of character in the string. var length: Int { return characters.count } /// Returns a localized string, using the main bundle. var locale: String { return NSLocalizedString(self, tableName: "Default", bundle: Bundle.main, value: "", comment: "") } /// Returns a lowercase version of the string. var lowercased: String { return lowercased() } /// Returns an uppercase version of the string. var uppercased: String { return uppercased() } /// Returns a new string made from the receiver by replacing all characters not in the unreservedCharset with percent-encoded characters. var encoding: String? { let unreservedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" let unreservedCharset = CharacterSet(charactersIn: unreservedChars) return addingPercentEncoding(withAllowedCharacters: unreservedCharset) } /// Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters. var decoding: String? { return removingPercentEncoding } } public extension String { /// Accesses the element at the specified position. Support "abc"[-1] == "c" /// /// - Parameter index: The position of the element to access. subscript(index: Int) -> Character { let idx = index < 0 ? (length - abs(index)) : index return self[self.index(startIndex, offsetBy: idx)] } /// Accesses a contiguous subrange of the string's characters. /// /// - Parameter range: A range of integers. subscript(range: Range<Int>) -> String { return substring(with: index(startIndex, offsetBy: range.lowerBound) ..< index(startIndex, offsetBy: range.upperBound)) } /// Returns a new string made by removing from both ends of the String characters contained in a given character set. /// /// - Parameter set: Character set, default is .whitespaces. /// - Returns: A new string func trimmed(set: CharacterSet = .whitespaces) -> String { return trimmingCharacters(in: set) } /// Returns a new camelCaseString /// /// - Parameter separator: A specail character /// - Returns: camelCaseString func camelCaseString(separator: String = "_") -> String { if isEmpty { return self } let first = self[0] var rest = capitalized.replacingOccurrences(of: separator, with: "") rest.remove(at: startIndex) return "\(first)\(rest)" } }
1e57a3c0b807af4846aa8d4fbf0c60f2
31.739583
141
0.657334
false
false
false
false
JGiola/swift-corelibs-foundation
refs/heads/master
Foundation/NSDecimalNumber.swift
apache-2.0
1
// 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 // /*************** Exceptions ***********/ public struct NSExceptionName : RawRepresentable, Equatable, Hashable { public private(set) var rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return self.rawValue.hashValue } public static func ==(_ lhs: NSExceptionName, _ rhs: NSExceptionName) -> Bool { return lhs.rawValue == rhs.rawValue } } extension NSExceptionName { public static let decimalNumberExactnessException = NSExceptionName(rawValue: "NSDecimalNumberExactnessException") public static let decimalNumberOverflowException = NSExceptionName(rawValue: "NSDecimalNumberOverflowException") public static let decimalNumberUnderflowException = NSExceptionName(rawValue: "NSDecimalNumberUnderflowException") public static let decimalNumberDivideByZeroException = NSExceptionName(rawValue: "NSDecimalNumberDivideByZeroException") } /*************** Rounding and Exception behavior ***********/ // Rounding policies : // Original // value 1.2 1.21 1.25 1.35 1.27 // Plain 1.2 1.2 1.3 1.4 1.3 // Down 1.2 1.2 1.2 1.3 1.2 // Up 1.2 1.3 1.3 1.4 1.3 // Bankers 1.2 1.2 1.2 1.4 1.3 /*************** Type definitions ***********/ extension NSDecimalNumber { public enum RoundingMode : UInt { case plain // Round up on a tie case down // Always down == truncate case up // Always up case bankers // on a tie round so last digit is even } public enum CalculationError : UInt { case noError case lossOfPrecision // Result lost precision case underflow // Result became 0 case overflow // Result exceeds possible representation case divideByZero } } public protocol NSDecimalNumberBehaviors { func roundingMode() -> NSDecimalNumber.RoundingMode func scale() -> Int16 } // Receiver can raise, return a new value, or return nil to ignore the exception. fileprivate func handle(_ error: NSDecimalNumber.CalculationError, _ handler: NSDecimalNumberBehaviors) { // handle the error condition, such as throwing an error for over/underflow } /*************** NSDecimalNumber: the class ***********/ open class NSDecimalNumber : NSNumber { fileprivate let decimal: Decimal public convenience init(mantissa: UInt64, exponent: Int16, isNegative: Bool) { var d = Decimal(mantissa) d._exponent += Int32(exponent) d._isNegative = isNegative ? 1 : 0 self.init(decimal: d) } public init(decimal dcm: Decimal) { self.decimal = dcm super.init() } public convenience init(string numberValue: String?) { self.init(decimal: Decimal(string: numberValue ?? "") ?? Decimal.nan) } public convenience init(string numberValue: String?, locale: Any?) { self.init(decimal: Decimal(string: numberValue ?? "", locale: locale as? Locale) ?? Decimal.nan) } public required init?(coder: NSCoder) { guard coder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } let exponent:Int32 = coder.decodeInt32(forKey: "NS.exponent") let length:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.length")) let isNegative:UInt32 = UInt32(coder.decodeBool(forKey: "NS.negative") ? 1 : 0) let isCompact:UInt32 = UInt32(coder.decodeBool(forKey: "NS.compact") ? 1 : 0) // let byteOrder:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.bo")) guard let mantissaData: Data = coder.decodeObject(forKey: "NS.mantissa") as? Data else { return nil // raise "Critical NSDecimalNumber archived data is missing" } guard mantissaData.count == Int(NSDecimalMaxSize * 2) else { return nil // raise "Critical NSDecimalNumber archived data is wrong size" } // Byte order? let mantissa:(UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16) = ( UInt16(mantissaData[0]) << 8 & UInt16(mantissaData[1]), UInt16(mantissaData[2]) << 8 & UInt16(mantissaData[3]), UInt16(mantissaData[4]) << 8 & UInt16(mantissaData[5]), UInt16(mantissaData[6]) << 8 & UInt16(mantissaData[7]), UInt16(mantissaData[8]) << 8 & UInt16(mantissaData[9]), UInt16(mantissaData[10]) << 8 & UInt16(mantissaData[11]), UInt16(mantissaData[12]) << 8 & UInt16(mantissaData[13]), UInt16(mantissaData[14]) << 8 & UInt16(mantissaData[15]) ) self.decimal = Decimal(_exponent: exponent, _length: length, _isNegative: isNegative, _isCompact: isCompact, _reserved: 0, _mantissa: mantissa) super.init() } public init(value: Int) { decimal = Decimal(value) super.init() } public init(value: UInt) { decimal = Decimal(value) super.init() } public init(value: Int8) { decimal = Decimal(value) super.init() } public init(value: UInt8) { decimal = Decimal(value) super.init() } public init(value: Int16) { decimal = Decimal(value) super.init() } public init(value: UInt16) { decimal = Decimal(value) super.init() } public init(value: Int32) { decimal = Decimal(value) super.init() } public init(value: UInt32) { decimal = Decimal(value) super.init() } public init(value: Int64) { decimal = Decimal(value) super.init() } public init(value: UInt64) { decimal = Decimal(value) super.init() } public init(value: Bool) { decimal = Decimal(value ? 1 : 0) super.init() } public init(value: Float) { decimal = Decimal(Double(value)) super.init() } public init(value: Double) { decimal = Decimal(value) super.init() } public required convenience init(floatLiteral value: Double) { self.init(decimal:Decimal(value)) } public required convenience init(booleanLiteral value: Bool) { if value { self.init(integerLiteral: 1) } else { self.init(integerLiteral: 0) } } public required convenience init(integerLiteral value: Int) { self.init(decimal:Decimal(value)) } public required convenience init(bytes buffer: UnsafeRawPointer, objCType type: UnsafePointer<Int8>) { NSRequiresConcreteImplementation() } open override var description: String { return self.decimal.description } open override func description(withLocale locale: Locale?) -> String { guard locale == nil else { fatalError("Locale not supported: \(locale!)") } return self.decimal.description } open class var zero: NSDecimalNumber { return NSDecimalNumber(integerLiteral: 0) } open class var one: NSDecimalNumber { return NSDecimalNumber(integerLiteral: 1) } open class var minimum: NSDecimalNumber { return NSDecimalNumber(decimal:Decimal.leastFiniteMagnitude) } open class var maximum: NSDecimalNumber { return NSDecimalNumber(decimal:Decimal.greatestFiniteMagnitude) } open class var notANumber: NSDecimalNumber { return NSDecimalNumber(decimal: Decimal.nan) } open func adding(_ other: NSDecimalNumber) -> NSDecimalNumber { return adding(other, withBehavior: nil) } open func adding(_ other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var left = self.decimal var right = other.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalAdd(&result, &left, &right, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func subtracting(_ other: NSDecimalNumber) -> NSDecimalNumber { return subtracting(other, withBehavior: nil) } open func subtracting(_ other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var left = self.decimal var right = other.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalSubtract(&result, &left, &right, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func multiplying(by other: NSDecimalNumber) -> NSDecimalNumber { return multiplying(by: other, withBehavior: nil) } open func multiplying(by other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var left = self.decimal var right = other.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalMultiply(&result, &left, &right, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func dividing(by other: NSDecimalNumber) -> NSDecimalNumber { return dividing(by: other, withBehavior: nil) } open func dividing(by other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var left = self.decimal var right = other.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalDivide(&result, &left, &right, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func raising(toPower power: Int) -> NSDecimalNumber { return raising(toPower:power, withBehavior: nil) } open func raising(toPower power: Int, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var input = self.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalPower(&result, &input, power, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func multiplying(byPowerOf10 power: Int16) -> NSDecimalNumber { return multiplying(byPowerOf10: power, withBehavior: nil) } open func multiplying(byPowerOf10 power: Int16, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var input = self.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalPower(&result, &input, Int(power), roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } // Round to the scale of the behavior. open func rounding(accordingToBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var input = self.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let scale = behavior.scale() NSDecimalRound(&result, &input, Int(scale), roundingMode) return NSDecimalNumber(decimal: result) } // compare two NSDecimalNumbers open override func compare(_ decimalNumber: NSNumber) -> ComparisonResult { if let num = decimalNumber as? NSDecimalNumber { return decimal.compare(to:num.decimal) } else { return decimal.compare(to:Decimal(decimalNumber.doubleValue)) } } open class var defaultBehavior: NSDecimalNumberBehaviors { return NSDecimalNumberHandler.defaultBehavior } // One behavior per thread - The default behavior is // rounding mode: NSRoundPlain // scale: No defined scale (full precision) // ignore exactnessException // raise on overflow, underflow and divide by zero. static let OBJC_TYPE = "d".utf8CString open override var objCType: UnsafePointer<Int8> { return NSDecimalNumber.OBJC_TYPE.withUnsafeBufferPointer{ $0.baseAddress! } } // return 'd' for double open override var int8Value: Int8 { return Int8(exactly: decimal.doubleValue) ?? 0 as Int8 } open override var uint8Value: UInt8 { return UInt8(exactly: decimal.doubleValue) ?? 0 as UInt8 } open override var int16Value: Int16 { return Int16(exactly: decimal.doubleValue) ?? 0 as Int16 } open override var uint16Value: UInt16 { return UInt16(exactly: decimal.doubleValue) ?? 0 as UInt16 } open override var int32Value: Int32 { return Int32(exactly: decimal.doubleValue) ?? 0 as Int32 } open override var uint32Value: UInt32 { return UInt32(exactly: decimal.doubleValue) ?? 0 as UInt32 } open override var int64Value: Int64 { return Int64(exactly: decimal.doubleValue) ?? 0 as Int64 } open override var uint64Value: UInt64 { return UInt64(exactly: decimal.doubleValue) ?? 0 as UInt64 } open override var floatValue: Float { return Float(decimal.doubleValue) } open override var doubleValue: Double { return decimal.doubleValue } open override var boolValue: Bool { return !decimal.isZero } open override var intValue: Int { return Int(exactly: decimal.doubleValue) ?? 0 as Int } open override var uintValue: UInt { return UInt(exactly: decimal.doubleValue) ?? 0 as UInt } open override func isEqual(_ value: Any?) -> Bool { guard let other = value as? NSDecimalNumber else { return false } return self.decimal == other.decimal } override var _swiftValueOfOptimalType: Any { return decimal } } // return an approximate double value /*********** A class for defining common behaviors *******/ open class NSDecimalNumberHandler : NSObject, NSDecimalNumberBehaviors, NSCoding { static let defaultBehavior = NSDecimalNumberHandler() let _roundingMode: NSDecimalNumber.RoundingMode let _scale:Int16 let _raiseOnExactness: Bool let _raiseOnOverflow: Bool let _raiseOnUnderflow: Bool let _raiseOnDivideByZero: Bool public override init() { _roundingMode = .plain _scale = Int16(NSDecimalNoScale) _raiseOnExactness = false _raiseOnOverflow = true _raiseOnUnderflow = true _raiseOnDivideByZero = true } public required init?(coder: NSCoder) { guard coder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } _roundingMode = NSDecimalNumber.RoundingMode(rawValue: UInt(coder.decodeInteger(forKey: "NS.roundingMode")))! if coder.containsValue(forKey: "NS.scale") { _scale = Int16(coder.decodeInteger(forKey: "NS.scale")) } else { _scale = Int16(NSDecimalNoScale) } _raiseOnExactness = coder.decodeBool(forKey: "NS.raise.exactness") _raiseOnOverflow = coder.decodeBool(forKey: "NS.raise.overflow") _raiseOnUnderflow = coder.decodeBool(forKey: "NS.raise.underflow") _raiseOnDivideByZero = coder.decodeBool(forKey: "NS.raise.dividebyzero") } open func encode(with coder: NSCoder) { guard coder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if _roundingMode != .plain { coder.encode(Int(_roundingMode.rawValue), forKey: "NS.roundingmode") } if _scale != Int16(NSDecimalNoScale) { coder.encode(_scale, forKey:"NS.scale") } if _raiseOnExactness { coder.encode(_raiseOnExactness, forKey:"NS.raise.exactness") } if _raiseOnOverflow { coder.encode(_raiseOnOverflow, forKey:"NS.raise.overflow") } if _raiseOnUnderflow { coder.encode(_raiseOnUnderflow, forKey:"NS.raise.underflow") } if _raiseOnDivideByZero { coder.encode(_raiseOnDivideByZero, forKey:"NS.raise.dividebyzero") } } open class var `default`: NSDecimalNumberHandler { return defaultBehavior } // rounding mode: NSRoundPlain // scale: No defined scale (full precision) // ignore exactnessException (return nil) // raise on overflow, underflow and divide by zero. public init(roundingMode: NSDecimalNumber.RoundingMode, scale: Int16, raiseOnExactness exact: Bool, raiseOnOverflow overflow: Bool, raiseOnUnderflow underflow: Bool, raiseOnDivideByZero divideByZero: Bool) { _roundingMode = roundingMode _scale = scale _raiseOnExactness = exact _raiseOnOverflow = overflow _raiseOnUnderflow = underflow _raiseOnDivideByZero = divideByZero } open func roundingMode() -> NSDecimalNumber.RoundingMode { return _roundingMode } // The scale could return NoScale for no defined scale. open func scale() -> Int16 { return _scale } } extension NSNumber { public var decimalValue: Decimal { if let d = self as? NSDecimalNumber { return d.decimal } else { return Decimal(self.doubleValue) } } }
775fd11cfbcf4d25ac7954cf7f3f2ca4
34.288499
211
0.644865
false
false
false
false
soapyigu/LeetCode_Swift
refs/heads/master
DFS/SubsetsII.swift
mit
1
/** * Question Link: https://leetcode.com/problems/subsets-ii/ * Primary idea: Classic Depth-first Search, avoid duplicates by adopting the first occurrence * * Time Complexity: O(n^n), Space Complexity: O(n) * */ class SubsetsII { func subsetsWithDup(nums: [Int]) -> [[Int]] { var res = [[Int]]() var path = [Int]() let nums = nums.sorted(by: <) _dfs(&res, &path, nums, 0) return res } private func _dfs(inout res: [[Int]], inout _ path:[Int], _ nums: [Int], _ index: Int) { res.append(Array(path)) for i in index..<nums.count { if i > 0 && nums[i] == nums[i - 1] && i != index { continue } path.append(nums[i]) _dfs(&res, &path, nums, i + 1) path.removeLast() } } }
7f7894dd3f1735f831764a99e26efb4d
25.058824
94
0.479096
false
false
false
false
iSapozhnik/FamilyPocket
refs/heads/master
FamilyPocket/Data/CategoryManager/CategoryManager.swift
mit
1
// // CategoryManager.swift // FamilyPocket // // Created by Ivan Sapozhnik on 5/14/17. // Copyright © 2017 Ivan Sapozhnik. All rights reserved. // import Foundation import RealmSwift class CategoryManager: Persistable { typealias ObjectClass = Category func allObjects(withCompletion completion: @escaping ([Category]?) -> ()) { let realm = try! Realm() let dataImporter = RealmDataImporter() if !dataImporter.initialDataImported() { dataImporter.importCategories() } let categories = realm.objects(Category.self).sorted(byKeyPath: "popularity", ascending: false) completion(Array(categories)) } func canAdd(object: Object) -> Bool { if let category = object as? Category { let realm = try! Realm() let predicate = NSPredicate(format: "name = %@", category.name!) let categories = realm.objects(Category.self).filter(predicate) return categories.count == 0 } else { return true } } func add(object: Object) { let realm = try! Realm() try! realm.write { realm.add(object) } } func delete(object: Object) { let realm = try! Realm() try! realm.write { realm.delete(object) } } func update(object: Category, name: String, colorString: String) { let realm = try! Realm() try! realm.write { object.name = name object.color = colorString realm.add(object, update: true) } } } class IncomeCategoryManager: Persistable { typealias ObjectClass = IncomeCategory func allObjects(withCompletion completion: @escaping ([IncomeCategory]?) -> ()) { let realm = try! Realm() let dataImporter = RealmDataImporter() if !dataImporter.initialDataImported() { dataImporter.importCategories() } let categories = realm.objects(IncomeCategory.self).sorted(byKeyPath: "popularity", ascending: false) completion(Array(categories)) } func add(object: Object) { } func delete(object: Object) { } }
0370e4a23a7f4e74bb13298237fe5954
23.947368
109
0.557384
false
false
false
false
remirobert/TextDrawer
refs/heads/master
Source/TextEditView.swift
mit
1
// // TextEditView.swift // // // Created by Remi Robert on 11/07/15. // // import UIKit import Masonry protocol TextEditViewDelegate { func textEditViewFinishedEditing(text: String) } public class TextEditView: UIView { private var textView: UITextView! private var textContainer: UIView! var delegate: TextEditViewDelegate? var textSize: Int! = 42 var textEntry: String! { set { textView.text = newValue } get { return textView.text } } var isEditing: Bool! { didSet { if isEditing == true { textContainer.hidden = false; userInteractionEnabled = true; backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.65) textView.becomeFirstResponder() } else { backgroundColor = UIColor.clearColor() textView.resignFirstResponder() textContainer.hidden = true; userInteractionEnabled = false; delegate?.textEditViewFinishedEditing(textView.text) } } } init() { super.init(frame: CGRectZero) isEditing = false textContainer = UIView() textContainer.layer.masksToBounds = true addSubview(textContainer) textContainer.mas_makeConstraints { (make: MASConstraintMaker!) -> Void in make.edges.equalTo()(self) } textView = UITextView() textView.tintColor = UIColor.whiteColor() textView.font = UIFont.systemFontOfSize(44) textView.textColor = UIColor.whiteColor() textView.backgroundColor = UIColor.clearColor() textView.returnKeyType = UIReturnKeyType.Done textView.clipsToBounds = true textView.delegate = self textContainer.addSubview(textView) textView.mas_makeConstraints { (make: MASConstraintMaker!) -> Void in make.edges.equalTo()(self.textContainer) } textContainer.hidden = true userInteractionEnabled = false keyboardNotification() } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } } extension TextEditView: UITextViewDelegate { public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { if text == "\n" { isEditing = false return false } if textView.text.characters.count + text.characters.count > textSize { return false } return true } } extension TextEditView { func keyboardNotification() { NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillChangeFrameNotification, object: nil, queue: nil) { (notification: NSNotification!) -> Void in if let userInfo = notification.userInfo { self.textContainer.layer.removeAllAnimations() if let keyboardRectEnd = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue(), let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey]?.floatValue { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.textContainer.mas_updateConstraints({ (make: MASConstraintMaker!) -> Void in make.bottom.offset()(-CGRectGetHeight(keyboardRectEnd)) }) UIView.animateWithDuration(NSTimeInterval(duration), delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in self.textContainer.layoutIfNeeded() }, completion: nil) }) } } } } }
78342ee7d8fc483635c13768814cb118
31.244094
173
0.582662
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/Classes/ViewRelated/Site Creation/Final Assembly/LandInTheEditorHelper.swift
gpl-2.0
1
typealias HomepageEditorCompletion = () -> Void class LandInTheEditorHelper { /// Land in the editor, or continue as usual - Used to branch on the feature flag for landing in the editor from the site creation flow /// - Parameter blog: Blog (which was just created) for which to show the home page editor /// - Parameter navigationController: UINavigationController used to present the home page editor /// - Parameter completion: HomepageEditorCompletion callback to be invoked after the user finishes editing the home page, or immediately iwhen the feature flag is disabled static func landInTheEditorOrContinue(for blog: Blog, navigationController: UINavigationController, completion: @escaping HomepageEditorCompletion) { // branch here for feature flag if FeatureFlag.landInTheEditor.enabled { landInTheEditor(for: blog, navigationController: navigationController, completion: completion) } else { completion() } } private static func landInTheEditor(for blog: Blog, navigationController: UINavigationController, completion: @escaping HomepageEditorCompletion) { fetchAllPages(for: blog, success: { _ in DispatchQueue.main.async { if let homepage = blog.homepage { let editorViewController = EditPageViewController(homepage: homepage, completion: completion) navigationController.present(editorViewController, animated: false) WPAnalytics.track(.landingEditorShown) } } }, failure: { _ in NSLog("Fetching all pages failed after site creation!") }) } // This seems to be necessary before casting `AbstractPost` to `Page`. private static func fetchAllPages(for blog: Blog, success: @escaping PostServiceSyncSuccess, failure: @escaping PostServiceSyncFailure) { let options = PostServiceSyncOptions() options.number = 20 let context = ContextManager.sharedInstance().mainContext let postService = PostService(managedObjectContext: context) postService.syncPosts(ofType: .page, with: options, for: blog, success: success, failure: failure) } }
7272418a1870454783117df21e151827
56.461538
176
0.698349
false
false
false
false
TruckMuncher/TruckMuncher-iOS
refs/heads/master
TruckMuncher/LoginViewController.swift
gpl-2.0
1
// // LoginViewController.swift // TruckMuncher // // Created by Josh Ault on 9/18/14. // Copyright (c) 2014 TruckMuncher. All rights reserved. // import UIKit import Alamofire import TwitterKit class LoginViewController: UIViewController, FBSDKLoginButtonDelegate { @IBOutlet var fbLoginView: FBSDKLoginButton! @IBOutlet weak var btnTwitterLogin: TWTRLogInButton! var twitterKey: String = "" var twitterSecretKey: String = "" var twitterName: String = "" var twitterCallback: String = "" let authManager = AuthManager() let truckManager = TrucksManager() override func viewDidLoad() { super.viewDidLoad() btnTwitterLogin.logInCompletion = { (session: TWTRSession!, error: NSError!) in if error == nil { #if DEBUG self.loginToAPI("oauth_token=tw985c9758-e11b-4d02-9b39-98aa8d00d429, oauth_secret=munch") #elseif RELEASE self.loginToAPI("oauth_token=\(session.authToken), oauth_secret=\(session.authTokenSecret)") #endif } else { let alert = UIAlertController(title: "Oops!", message: "We couldn't log you in right now, please try again", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) MBProgressHUD.hideHUDForView(self.view, animated: true) } } navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancelTapped") fbLoginView.delegate = self fbLoginView.readPermissions = ["public_profile", "email", "user_friends"] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func loginTapped(sender: AnyObject) { MBProgressHUD.showHUDAddedTo(view, animated: true) } func cancelTapped() { dismissViewControllerAnimated(true, completion: nil) } func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { if error == nil && !result.isCancelled { #if DEBUG loginToAPI("access_token=fb985c9758-e11b-4d02-9b39|FBUser") #elseif RELEASE loginToAPI("access_token=\(FBSDKAccessToken.currentAccessToken().tokenString)") #endif } else { let alert = UIAlertController(title: "Oops!", message: "We couldn't log you in right now, please try again", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) presentViewController(alert, animated: true, completion: nil) MBProgressHUD.hideHUDForView(view, animated: true) } } func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) { println("User logged out from Facebook") MBProgressHUD.hideHUDForView(view, animated: true) } func successfullyLoggedInAsTruck() { MBProgressHUD.hideHUDForView(view, animated: true) navigationController?.dismissViewControllerAnimated(true, completion: { () -> Void in NSNotificationCenter.defaultCenter().postNotificationName("loggedInNotification", object: self, userInfo: nil) }) } func attemptSessionTokenRefresh(error: (Error?) -> ()) { truckManager.getTrucksForVendor(success: { (response) -> () in self.successfullyLoggedInAsTruck() }, error: error) } func loginToAPI(authorizationHeader: String) { authManager.signIn(authorization: authorizationHeader, success: { (response) -> () in NSUserDefaults.standardUserDefaults().setValue(response.sessionToken, forKey: "sessionToken") NSUserDefaults.standardUserDefaults().synchronize() self.attemptSessionTokenRefresh({ (error) -> () in MBProgressHUD.hideHUDForView(self.view, animated: true) let alert = UIAlertController(title: "Oops!", message: "We couldn't log you in right now, please try again", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) println("error \(error)") println("error message \(error?.userMessage)") }) }) { (error) -> () in println("error \(error)") println("error message \(error?.userMessage)") let alert = UIAlertController(title: "Oops!", message: "We couldn't log you in right now, please try again", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) NSUserDefaults.standardUserDefaults().removeObjectForKey("sessionToken") NSUserDefaults.standardUserDefaults().synchronize() MBProgressHUD.hideHUDForView(self.view, animated: true) } } }
f99062578f9d7ebd2aea80587fb722fb
43.806723
148
0.64066
false
false
false
false
SwiftyVK/SwiftyVK
refs/heads/master
Library/Sources/Networking/Attempt/Attempt.swift
mit
2
import Foundation protocol Attempt: class, OperationConvertible { init( request: URLRequest, session: VKURLSession, callbacks: AttemptCallbacks ) } final class AttemptImpl: Operation, Attempt { private let request: URLRequest private var task: VKURLSessionTask? private let urlSession: VKURLSession private let callbacks: AttemptCallbacks init( request: URLRequest, session: VKURLSession, callbacks: AttemptCallbacks ) { self.request = request self.urlSession = session self.callbacks = callbacks super.init() } override func main() { let semaphore = DispatchSemaphore(value: 0) let completion: (Data?, URLResponse?, Error?) -> () = { [weak self] data, response, error in /// Because URLSession executes completions in their own serial queue DispatchQueue.global(qos: .utility).async { defer { semaphore.signal() } guard let strongSelf = self, !strongSelf.isCancelled else { return } if let error = error as NSError?, error.code != NSURLErrorCancelled { strongSelf.callbacks.onFinish(.error(.urlRequestError(error))) } else if let data = data { strongSelf.callbacks.onFinish(Response(data)) } else { strongSelf.callbacks.onFinish(.error(.unexpectedResponse)) } } } task = urlSession.dataTask(with: request, completionHandler: completion) task?.addObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesReceived), options: .new, context: nil) task?.addObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesSent), options: .new, context: nil) task?.resume() semaphore.wait() } override func observeValue( forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer? ) { guard let keyPath = keyPath else { return } guard let task = task else { return } switch keyPath { case (#keyPath(URLSessionTask.countOfBytesSent)): guard task.countOfBytesExpectedToSend > 0 else { return } callbacks.onSent(task.countOfBytesSent, task.countOfBytesExpectedToSend) case(#keyPath(URLSessionTask.countOfBytesReceived)): guard task.countOfBytesExpectedToReceive > 0 else { return } callbacks.onRecive(task.countOfBytesReceived, task.countOfBytesExpectedToReceive) default: break } } override func cancel() { super.cancel() task?.cancel() } deinit { task?.removeObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesReceived)) task?.removeObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesSent)) } } struct AttemptCallbacks { let onFinish: (Response) -> () let onSent: (_ total: Int64, _ of: Int64) -> () let onRecive: (_ total: Int64, _ of: Int64) -> () init( onFinish: @escaping ((Response) -> ()) = { _ in }, onSent: @escaping ((_ total: Int64, _ of: Int64) -> ()) = { _, _ in }, onRecive: @escaping ((_ total: Int64, _ of: Int64) -> ()) = { _, _ in } ) { self.onFinish = onFinish self.onSent = onSent self.onRecive = onRecive } static var `default`: AttemptCallbacks { return AttemptCallbacks() } }
58b4dc1932718fa8f814a083f9404e51
32.603604
119
0.582842
false
false
false
false
BlenderSleuth/Circles
refs/heads/master
Circles/SKTUtils/SKAction+SpecialEffects.swift
gpl-3.0
1
/* * Copyright (c) 2013-2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import SpriteKit public extension SKAction { /** * Creates a screen shake animation. * * @param node The node to shake. You cannot apply this effect to an SKScene. * @param amount The vector by which the node is displaced. * @param oscillations The number of oscillations; 10 is a good value. * @param duration How long the effect lasts. Shorter is better. */ public class func screenShakeWithNode(_ node: SKNode, amount: CGPoint, oscillations: Int, duration: TimeInterval) -> SKAction { let oldPosition = node.position let newPosition = oldPosition + amount let effect = SKTMoveEffect(node: node, duration: duration, startPosition: newPosition, endPosition: oldPosition) effect.timingFunction = SKTCreateShakeFunction(oscillations) return SKAction.actionWithEffect(effect) } /** * Creates a screen rotation animation. * * @param node You usually want to apply this effect to a pivot node that is * centered in the scene. You cannot apply the effect to an SKScene. * @param angle The angle in radians. * @param oscillations The number of oscillations; 10 is a good value. * @param duration How long the effect lasts. Shorter is better. */ public class func screenRotateWithNode(_ node: SKNode, angle: CGFloat, oscillations: Int, duration: TimeInterval) -> SKAction { let oldAngle = node.zRotation let newAngle = oldAngle + angle let effect = SKTRotateEffect(node: node, duration: duration, startAngle: newAngle, endAngle: oldAngle) effect.timingFunction = SKTCreateShakeFunction(oscillations) return SKAction.actionWithEffect(effect) } /** * Creates a screen zoom animation. * * @param node You usually want to apply this effect to a pivot node that is * centered in the scene. You cannot apply the effect to an SKScene. * @param amount How much to scale the node in the X and Y directions. * @param oscillations The number of oscillations; 10 is a good value. * @param duration How long the effect lasts. Shorter is better. */ public class func screenZoomWithNode(_ node: SKNode, amount: CGPoint, oscillations: Int, duration: TimeInterval) -> SKAction { let oldScale = CGPoint(x: node.xScale, y: node.yScale) let newScale = oldScale * amount let effect = SKTScaleEffect(node: node, duration: duration, startScale: newScale, endScale: oldScale) effect.timingFunction = SKTCreateShakeFunction(oscillations) return SKAction.actionWithEffect(effect) } /** * Causes the scene background to flash for duration seconds. */ public class func colorGlitchWithScene(_ scene: SKScene, originalColor: SKColor, duration: TimeInterval) -> SKAction { return SKAction.customAction(withDuration: duration) {(node, elapsedTime) in if elapsedTime < CGFloat(duration) { let random = Int.random(0..<256) scene.backgroundColor = SKColorWithRGB(random, g: random, b: random) } else { scene.backgroundColor = originalColor } } } }
d8b8f9ac85a71e61187887b7a33b8ee5
42.915789
129
0.72675
false
false
false
false
kaler/SmartRouter
refs/heads/master
SmartRouterTests/RouterTests.swift
mit
1
// // RouterTests.swift // RouterTests // // Created by Parveen Kaler on 9/7/15. // Copyright © 2015 Smartful Studios Inc. All rights reserved. // import XCTest @testable import Router class RouterTests: XCTestCase { var router: Router? override func setUp() { super.setUp() router = Router() } func testBase() { let expectation = expectationWithDescription("Plain") router?.route("/foo") { _ in expectation.fulfill() } router?.route("/bar") { _ in XCTAssert(false, "Should not match bar") } let url = NSURL(string: "/foo")! router?.match(url) waitForExpectationsWithTimeout(0.001) { (error) -> Void in print(error) } } func testURLParameter() { let expectation = expectationWithDescription("URL Parameters") router?.route("/foo/:id") { (urlParams, queryParams) in XCTAssert(urlParams.first?.name == ":id") XCTAssert(urlParams.first?.value == "1234") expectation.fulfill() } let url = NSURL(string: "/foo/1234")! router?.match(url) waitForExpectationsWithTimeout(0.001) { (error) -> Void in print(error) } } func testParameters() { let e = expectationWithDescription("Parameter expectation") router?.route("/foo") { (urlParams, queryParams) in XCTAssert(queryParams.first?.name == "param") XCTAssert(queryParams.first?.value == "12345") e.fulfill() } let url = NSURL(string: "/foo?param=12345")! router?.match(url) waitForExpectationsWithTimeout(0.001) { (error) -> Void in print(error) } } }
e0fbab3b057b0398d60697470119c31f
25.5
70
0.54124
false
true
false
false
akaralar/siesta
refs/heads/master
Examples/GithubBrowser/Source/UI/SiestaTheme.swift
mit
1
import UIKit import Siesta enum SiestaTheme { static let darkColor = UIColor(red: 0.180, green: 0.235, blue: 0.266, alpha: 1), darkerColor = UIColor(red: 0.161, green: 0.208, blue: 0.235, alpha: 1), lightColor = UIColor(red: 0.964, green: 0.721, blue: 0.329, alpha: 1), linkColor = UIColor(red: 0.321, green: 0.901, blue: 0.882, alpha: 1), selectedColor = UIColor(red: 0.937, green: 0.400, blue: 0.227, alpha: 1), textColor = UIColor(red: 0.623, green: 0.647, blue: 0.663, alpha: 1), boldColor = UIColor(red: 0.906, green: 0.902, blue: 0.894, alpha: 1) static func applyAppearanceDefaults() { UITextField.appearance().keyboardAppearance = .dark UITextField.appearance().textColor = UIColor.black UITextField.appearance().backgroundColor = textColor UINavigationBar.appearance().barStyle = UIBarStyle.black UINavigationBar.appearance().barTintColor = darkColor UINavigationBar.appearance().tintColor = linkColor UITableView.appearance().backgroundColor = darkerColor UITableView.appearance().separatorColor = UIColor.black UITableViewCell.appearance().backgroundColor = darkerColor UITableViewCell.appearance().selectedBackgroundView = emptyView(withBackground: selectedColor) UIButton.appearance().backgroundColor = darkColor UIButton.appearance().tintColor = linkColor UISearchBar.appearance().backgroundColor = darkColor UISearchBar.appearance().barTintColor = darkColor UISearchBar.appearance().searchBarStyle = .minimal UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = lightColor UILabel.appearance(whenContainedInInstancesOf: [ResourceStatusOverlay.self]).textColor = textColor UIActivityIndicatorView.appearance(whenContainedInInstancesOf: [ResourceStatusOverlay.self]).activityIndicatorViewStyle = .whiteLarge } static private func emptyView(withBackground color: UIColor) -> UIView { let view = UIView() view.backgroundColor = color return view } }
7f99a64d20dff878e9646ea51ee2a75e
47.088889
141
0.694547
false
false
false
false
wdkk/CAIM
refs/heads/master
AR/caimar00/CAIMMetal/CAIMMetal.swift
mit
15
// // CAIMMetal.swift // CAIM Project // https://kengolab.net/CreApp/wiki/ // // Copyright (c) Watanabe-DENKI Inc. // https://wdkk.co.jp/ // // This software is released under the MIT License. // https://opensource.org/licenses/mit-license.php // #if os(macOS) || (os(iOS) && !arch(x86_64)) import Foundation import Metal open class CAIMMetal { public static var device:MTLDevice? = MTLCreateSystemDefaultDevice() private static var _command_queue:MTLCommandQueue? public static var commandQueue:MTLCommandQueue? { if( CAIMMetal._command_queue == nil ) { CAIMMetal._command_queue = device?.makeCommandQueue() } return CAIMMetal._command_queue } // セマフォ public static let semaphore = DispatchSemaphore( value: 0 ) // コマンド実行 public static func execute( prev:( _ commandBuffer:MTLCommandBuffer )->() = { _ in }, main:( _ commandBuffer:MTLCommandBuffer )->(), post:( _ commandBuffer:MTLCommandBuffer )->() = { _ in }, completion: (( _ commandBuffer:MTLCommandBuffer )->())? = nil ) { // 描画コマンドエンコーダ guard let command_buffer:MTLCommandBuffer = CAIMMetal.commandQueue?.makeCommandBuffer() else { print("cannot get Metal command buffer.") return } // 完了時の処理 command_buffer.addCompletedHandler { _ in CAIMMetal.semaphore.signal() completion?( command_buffer ) } // 事前処理の実行(コンピュートシェーダなどで使える) prev( command_buffer ) main( command_buffer ) // コマンドバッファの確定 command_buffer.commit() // セマフォ待機のチェック _ = CAIMMetal.semaphore.wait( timeout: DispatchTime.distantFuture ) // 事後処理の関数の実行(command_buffer.waitUntilCompletedの呼び出しなど) post( command_buffer ) } } #endif
0f7338cbb3130011152c0bd317c79682
30
103
0.592092
false
false
false
false
EvsenevDev/SmartReceiptsiOS
refs/heads/master
SmartReceipts/Persistence/Helpers/RefreshTripPriceHandler.swift
agpl-3.0
2
// // RefreshTripPriceHandler.swift // SmartReceipts // // Created by Jaanus Siim on 01/06/16. // Copyright © 2016 Will Baumann. All rights reserved. // import Foundation import FMDB protocol RefreshTripPriceHandler { func refreshPriceForTrip(_ trip: WBTrip, inDatabase database: FMDatabase); } extension RefreshTripPriceHandler { func refreshPriceForTrip(_ trip: WBTrip, inDatabase database: FMDatabase) { Logger.debug("Refresh price on \(trip.name!)") timeMeasured("Price update") { //TODO jaanus: maybe lighter query - only price/currency/exchangeRate? let receipts = database.fetchUnmarkedForDeletionReceiptsForTrip(trip) let distances: [Distance] if WBPreferences.isTheDistancePriceBeIncludedInReports() { //lighter query also here? distances = database.fetchAllDistancesForTrip(trip) } else { distances = [] } let collection = PricesCollection() // just so that when no receipts we would not end up with blank price collection.addPrice(Price(amount: .zero, currency: trip.defaultCurrency)) for receipt in receipts { collection.addPrice(receipt.targetPrice()) } for distance in distances { collection.addPrice(distance.totalRate()) } trip.pricesSummary = collection } } }
0d726195c242b592de0c3ff5f375ef1d
34.261905
85
0.625253
false
false
false
false
JasonChen2015/Paradise-Lost
refs/heads/master
Paradise Lost/Classes/DataStructures/Color.swift
mit
3
// // Color.swift // Paradise Lost // // Created by Jason Chen on 5/17/16. // Copyright © 2016 Jason Chen. All rights reserved. // import Foundation import UIKit struct Color { // refer: https://en.wikipedia.org/wiki/Beige var FrechBeige = UIColor(hex: 0xa67b5b) var CosmicLatte = UIColor(hex: 0xfff8e7) // japanese tradictional color // refer: https://en.wikipedia.org/wiki/Traditional_colors_of_Japan var Kokiake = UIColor(hex: 0x7b3b3a) var Kurotobi = UIColor(hex: 0x351e1c) var Kakitsubata = UIColor(hex: 0x491e3c) // refer: https://github.com/gabrielecirulli/2048 (under License MIT) // for 2048 tile color var TileBackground = UIColor(hex: 0x8F7a66) var TileColor = UIColor(hex: 0xeee4da) var TileGoldColor = UIColor(hex: 0xedc22e) var DarkGrayishOrange = UIColor(hex: 0x776e65) // dark text color var LightGrayishOrange = UIColor(hex: 0xf9f6f2) // light text color // for 2048 special tile color var BrightOrange = UIColor(hex: 0xf78e48) // 8 var BrightRed = UIColor(hex: 0xfc5e2e) // 16 var VividRed = UIColor(hex: 0xff3333) // 32 var PureRed = UIColor(hex: 0xff0000) // 64 // var LightGray = UIColor(hex: 0xcccccc) func mixColorBetween(_ colorA: UIColor, weightA: CGFloat = 0.5, colorB: UIColor, weightB: CGFloat = 0.5) -> UIColor { let c1 = colorA.RGBComponents let c2 = colorB.RGBComponents let red = (c1.red * weightA + c2.red * weightB) / (weightA + weightB) let green = (c1.green * weightA + c2.green * weightB) / (weightA + weightB) let blue = (c1.blue * weightA + c2.blue * weightB) / (weightA + weightB) let alpha = (c1.alpha * weightA + c2.alpha * weightB) / (weightA + weightB) return UIColor(red: red, green: green, blue: blue, alpha: alpha) } } extension UIColor { var RGBComponents:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) return (r, g, b, a) } // refer: https://github.com/yannickl/DynamicColor (under License MIT) // create a color from hex number (e.g. UIColor(hex: 0xaabbcc)) convenience init(hex: UInt32) { let mask = 0x000000FF let r = Int(hex >> 16) & mask let g = Int(hex >> 8) & mask let b = Int(hex >> 0) & mask let red = CGFloat(r) / 255 let green = CGFloat(g) / 255 let blue = CGFloat(b) / 255 self.init(red: red, green: green, blue: blue, alpha: 1) } }
66eb05411546a411233a05e650a1d9d6
34.342105
121
0.612435
false
false
false
false
YauheniYarotski/APOD
refs/heads/master
APOD/ApodDescriptionVC.swift
mit
1
// // ApodDescriptionVC.swift // APOD // // Created by Yauheni Yarotski on 25.04.16. // Copyright © 2016 Yauheni_Yarotski. All rights reserved. // import UIKit protocol ApodDescriptionVCDelegate { func apodDescriptionVCDidFinsh(_ apodDescriptionVC: ApodDescriptionVC?) func apodDescriptionVCDidFinshByDateBarPressed(_ apodDescriptionVC: ApodDescriptionVC) } class ApodDescriptionVC: UIViewController { var apodDateString: String! var apodTitle: String! var apodDescription: String! let apodDateBar = TopBar() let titleView = ApodTitleView(frame: CGRect(x:0, y:0, width:0, height:60)) let apodDescriptionTextView = UITextView() var delegate: ApodDescriptionVCDelegate? var swipeDismiser = SwipeDismiser() // MARK: - UIViewController override var preferredStatusBarStyle : UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() apodDateBar.translatesAutoresizingMaskIntoConstraints = false apodDateBar.backgroundColor = UIColor.clear view.addSubview(apodDateBar) apodDateBar.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(20) make.leading.trailing.equalToSuperview() make.height.equalTo(60) } titleView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(titleView) titleView.title.text = apodTitle titleView.snp.makeConstraints { (make) in make.height.equalTo(60) make.leading.trailing.equalToSuperview() make.top.equalTo(apodDateBar.snp.bottom) } apodDescriptionTextView.translatesAutoresizingMaskIntoConstraints = false apodDescriptionTextView.backgroundColor = UIColor.clear apodDescriptionTextView.textColor = UIColor.white view.addSubview(apodDescriptionTextView) apodDescriptionTextView.text = apodDescription apodDescriptionTextView.isEditable = false apodDescriptionTextView.snp.makeConstraints { (make) in make.leading.equalToSuperview().offset(20) make.trailing.equalToSuperview().offset(-20) make.bottom.equalToSuperview() make.top.equalTo(titleView.snp.bottom) } setupDateHandler() setupViewHandler() setupSwipeHandler() } func controllerIsDone() { delegate?.apodDescriptionVCDidFinsh(self) } //MARK: - Setup func setupViewHandler() { let tap = UITapGestureRecognizer(target: self, action: #selector(ApodDescriptionVC.viewPressed(_:))) tap.numberOfTapsRequired = 1 view.addGestureRecognizer(tap) } func setupDateHandler() { let tap = UITapGestureRecognizer(target: self, action: #selector(ApodDescriptionVC.datePressed(_:))) tap.numberOfTapsRequired = 1 apodDateBar.addGestureRecognizer(tap) } func setupSwipeHandler() { let pan = UIPanGestureRecognizer(target: self, action: #selector(ApodDescriptionVC.didPan(_:))) view.addGestureRecognizer(pan) } //MARK: - ActionHandlers func viewPressed(_ tap: UITapGestureRecognizer) { controllerIsDone() } func datePressed(_ tap: UITapGestureRecognizer) { delegate?.apodDescriptionVCDidFinshByDateBarPressed(self) } func didPan(_ pan: UIPanGestureRecognizer) { switch pan.state { case .began: swipeDismiser.interactionInProgress = true controllerIsDone() default: swipeDismiser.handlePan(pan) } } }
a7a68778425349100686c8c1695d6e70
28.822034
108
0.703041
false
false
false
false
mercadopago/px-ios
refs/heads/develop
MercadoPagoSDK/MercadoPagoSDK/Models/PXPaymentData+Tracking.swift
mit
1
import Foundation // MARK: Tracking extension PXPaymentData { func getPaymentDataForTracking() -> [String: Any] { guard let paymentMethod = paymentMethod else { return [:] } let cardIdsEsc = PXTrackingStore.sharedInstance.getData(forKey: PXTrackingStore.cardIdsESC) as? [String] ?? [] var properties: [String: Any] = [:] properties["payment_method_type"] = paymentMethod.getPaymentTypeForTracking() properties["payment_method_id"] = paymentMethod.getPaymentIdForTracking() var extraInfo: [String: Any] = [:] if paymentMethod.isCard { if let cardId = token?.cardId { extraInfo["card_id"] = cardId extraInfo["has_esc"] = cardIdsEsc.contains(cardId) } extraInfo["selected_installment"] = payerCost?.getPayerCostForTracking() if let issuerId = issuer?.id { extraInfo["issuer_id"] = Int64(issuerId) } properties["extra_info"] = extraInfo } else if paymentMethod.isAccountMoney { // TODO: When account money becomes FCM // var extraInfo: [String: Any] = [:] // extraInfo["balance"] = // properties["extra_info"] = extraInfo } else if paymentMethod.isDigitalCurrency { extraInfo["selected_installment"] = payerCost?.getPayerCostForTracking(isDigitalCurrency: true) properties["extra_info"] = extraInfo } return properties } }
ed4093c65e61530710623acb5eb6f6fc
40.351351
118
0.601307
false
false
false
false
atrick/swift
refs/heads/main
stdlib/public/Concurrency/AsyncThrowingPrefixWhileSequence.swift
apache-2.0
3
//===----------------------------------------------------------------------===// // // 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 the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift @available(SwiftStdlib 5.1, *) extension AsyncSequence { /// Returns an asynchronous sequence, containing the initial, consecutive /// elements of the base sequence that satisfy the given error-throwing /// predicate. /// /// Use `prefix(while:)` to produce values while elements from the base /// sequence meet a condition you specify. The modified sequence ends when /// the predicate closure returns `false` or throws an error. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `prefix(_:)` method causes the modified /// sequence to pass through values less than `8`, but throws an /// error when it receives a value that's divisible by `5`: /// /// do { /// let stream = try Counter(howHigh: 10) /// .prefix { /// if $0 % 5 == 0 { /// throw MyError() /// } /// return $0 < 8 /// } /// for try await number in stream { /// print("\(number) ", terminator: " ") /// } /// } catch { /// print("Error: \(error)") /// } /// // Prints: 1 2 3 4 Error: MyError() /// /// - Parameter predicate: A error-throwing closure that takes an element of /// the asynchronous sequence as its argument and returns a Boolean value /// that indicates whether to include the element in the modified sequence. /// - Returns: An asynchronous sequence that contains, in order, the elements /// of the base sequence that satisfy the given predicate. If the predicate /// throws an error, the sequence contains only values produced prior to /// the error. @preconcurrency @inlinable public __consuming func prefix( while predicate: @Sendable @escaping (Element) async throws -> Bool ) rethrows -> AsyncThrowingPrefixWhileSequence<Self> { return AsyncThrowingPrefixWhileSequence(self, predicate: predicate) } } /// An asynchronous sequence, containing the initial, consecutive /// elements of the base sequence that satisfy the given error-throwing /// predicate. @available(SwiftStdlib 5.1, *) public struct AsyncThrowingPrefixWhileSequence<Base: AsyncSequence> { @usableFromInline let base: Base @usableFromInline let predicate: (Base.Element) async throws -> Bool @usableFromInline init( _ base: Base, predicate: @escaping (Base.Element) async throws -> Bool ) { self.base = base self.predicate = predicate } } @available(SwiftStdlib 5.1, *) extension AsyncThrowingPrefixWhileSequence: AsyncSequence { /// The type of element produced by this asynchronous sequence. /// /// The prefix-while sequence produces whatever type of element its base /// iterator produces. public typealias Element = Base.Element /// The type of iterator that produces elements of the sequence. public typealias AsyncIterator = Iterator /// The iterator that produces elements of the prefix-while sequence. public struct Iterator: AsyncIteratorProtocol { @usableFromInline var predicateHasFailed = false @usableFromInline var baseIterator: Base.AsyncIterator @usableFromInline let predicate: (Base.Element) async throws -> Bool @usableFromInline init( _ baseIterator: Base.AsyncIterator, predicate: @escaping (Base.Element) async throws -> Bool ) { self.baseIterator = baseIterator self.predicate = predicate } /// Produces the next element in the prefix-while sequence. /// /// If the predicate hasn't failed yet, this method gets the next element /// from the base sequence and calls the predicate with it. If this call /// succeeds, this method passes along the element. Otherwise, it returns /// `nil`, ending the sequence. If calling the predicate closure throws an /// error, the sequence ends and `next()` rethrows the error. @inlinable public mutating func next() async throws -> Base.Element? { if !predicateHasFailed, let nextElement = try await baseIterator.next() { do { if try await predicate(nextElement) { return nextElement } else { predicateHasFailed = true } } catch { predicateHasFailed = true throw error } } return nil } } @inlinable public __consuming func makeAsyncIterator() -> Iterator { return Iterator(base.makeAsyncIterator(), predicate: predicate) } } @available(SwiftStdlib 5.1, *) extension AsyncThrowingPrefixWhileSequence: @unchecked Sendable where Base: Sendable, Base.Element: Sendable { } @available(SwiftStdlib 5.1, *) extension AsyncThrowingPrefixWhileSequence.Iterator: @unchecked Sendable where Base.AsyncIterator: Sendable, Base.Element: Sendable { }
db69c6741a6050c2e5e4368d8879bc68
34.625
80
0.646907
false
false
false
false
apple/swift
refs/heads/main
test/Generics/issue-51450.swift
apache-2.0
2
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module %S/Inputs/issue-51450-other.swift -emit-module-path %t/other.swiftmodule -module-name other // RUN: %target-swift-frontend -emit-silgen %s -I%t -debug-generic-signatures 2>&1 | %FileCheck %s // https://github.com/apple/swift/issues/51450 import other public class C : P { public typealias T = Int } public func takesInt(_: Int) {} // CHECK-LABEL: .foo@ // CHECK-NEXT: Generic signature: <T, S where T : C, S : Sequence, S.[Sequence]Element == Int> public func foo<T : C, S : Sequence>(_: T, _ xs: S) where S.Element == T.T { for x in xs { takesInt(x) } }
361ebf1e07b54c990c8b3d88ab7a7290
29.619048
135
0.662519
false
false
false
false
Jerry0523/JWIntent
refs/heads/master
Intent/Internal/NCProxyDelegate.swift
mit
1
// // NCProxyDelegate.swift // // Copyright (c) 2015 Jerry Wong // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class NCProxyDelegate : NSObject { weak var target: UINavigationControllerDelegate? weak var currentTransition: Transition? class func addProxy(forNavigationController nc: UINavigationController) { if (nc.delegate as? NCProxyDelegate) != nil { return } let proxyDelegate = NCProxyDelegate() proxyDelegate.target = nc.delegate nc.delegate = proxyDelegate objc_setAssociatedObject(nc, &NCProxyDelegate.proxyDelegateKey, proxyDelegate, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if nc.interactivePopGestureRecognizer != nil { objc_setAssociatedObject(nc.interactivePopGestureRecognizer!, &NCProxyDelegate.instanceNCKey, nc, .OBJC_ASSOCIATION_ASSIGN) } } @objc private func handleInteractivePopGesture(recognizer: UIPanGestureRecognizer) { currentTransition?.handle(recognizer, gestureDidBegin: { let nc: UINavigationController = objc_getAssociatedObject(recognizer, &NCProxyDelegate.instanceNCKey) as! UINavigationController nc.popViewController(animated: true) }) } open override func forwardingTarget(for aSelector: Selector!) -> Any? { if target?.responds(to: aSelector) ?? false { return target } return super.forwardingTarget(for: aSelector) } override func responds(to aSelector: Selector!) -> Bool { return (target?.responds(to:aSelector) ?? false) || super.responds(to: aSelector) } private static var instanceNCKey: Void? private static var proxyDelegateKey: Void? private static var oldInteractivePopTargetKey: Void? } extension NCProxyDelegate : UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { if viewController.pushTransition != nil { if objc_getAssociatedObject(navigationController, &NCProxyDelegate.oldInteractivePopTargetKey) == nil { let allTargets = navigationController.interactivePopGestureRecognizer?.value(forKey: "_targets") as? NSMutableArray objc_setAssociatedObject(navigationController, &NCProxyDelegate.oldInteractivePopTargetKey, allTargets?.firstObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } navigationController.interactivePopGestureRecognizer?.removeTarget(nil, action: nil) navigationController.interactivePopGestureRecognizer?.addTarget(self, action: #selector(handleInteractivePopGesture(recognizer:))) } else { navigationController.interactivePopGestureRecognizer?.removeTarget(nil, action: nil) let oldInteractivePopTarget = objc_getAssociatedObject(navigationController, &NCProxyDelegate.oldInteractivePopTargetKey) if oldInteractivePopTarget != nil { let allTargets = navigationController.interactivePopGestureRecognizer?.value(forKey: "_targets") as? NSMutableArray allTargets?.add(oldInteractivePopTarget!) } } currentTransition = viewController.pushTransition target?.navigationController?(navigationController, didShow: viewController, animated: animated) } func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { let transitionOwner = (operation == .push ? toVC : fromVC) let transition = transitionOwner.pushTransition if transition != nil { return transition } return target?.navigationController?(navigationController, animationControllerFor:operation, from:fromVC, to:toVC) } func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if let transition = animationController as? Transition { return transition.interactiveController } return currentTransition?.interactiveController } }
08889fd83ea78e4d46928116f81f3d4b
48.234234
247
0.725892
false
false
false
false
jbrudvik/swift-playgrounds
refs/heads/master
structs-and-classes.playground/section-1.swift
mit
1
// Swift has both structs and classes. // Structs and classes are very similar. The main difference is the copy semantics (on assign or parameter passing): // - Structs are copied by value (instance variables are copied) // - Classes are copied by reference // Class instances may use the === and !== operators to test reference equality (i.e., are they the same object. // Struct instances do not respond to these operators (by default). // Addtionally, == and != are generally used to compare class instance value equality, but these need to be defined per-object. // Stack is probably better-suited as a class than a struct, but we'll use this for illustration struct Stack<T> { var items = [T]() var isEmpty: Bool { return items.isEmpty } // By default, struct instance methods may not modify state. Use the `mutating` keyword to force this behavior mutating func push(item: T) { items.append(item) } mutating func pop() -> T { return items.removeLast() } } // Demonstration of Stacks var s = Stack<Int>() for i in 0..<3 { s.push(i) } s var s2 = s // s2 is a distinct copy of s s2 while !s.isEmpty { println(s.pop()) } s // no longer contains any values s2 // still contains all added values // Both structs and classes may adopt (multiple) protocols (similar to implementing Java interfaces), // but only classes may inherit (and be inherited). Classes may also include deinitializers, among other details. class Queue<T> { var items = [T]() var isEmpty: Bool { return items.isEmpty } // Initializer is called when class instance is constructed init() { println("initializing Queue") println("done initializing Queue") } // Class instance methods can mutate by default. In fact, the `mutating` keyword is not allowed in classes func push(item: T) { items.append(item) } func pop() -> T { return items.removeAtIndex(0) } } // EquatableQueue<T> inherits from Queue<T> and adopts the Equatable protocol. // According to EquatableQueue's definition of equality (all contained elements are equal), it // also requires elements to be Equatable class EquatableQueue<T: Equatable>: Queue<T>, Equatable { override init() { println("initializing EquatableQueue") super.init() // Call the super initializer (otherwise it will be called afterward) println("done initializing EquatableQueue") } } // Although the Equatable protocol can be adopted by in the initial class definition, the == function required to (functionally) adopt the protocol must be defined in the global scope. func ==<T>(lhs: EquatableQueue<T>, rhs: EquatableQueue<T>) -> Bool { let lhsItems = lhs.items let rhsItems = rhs.items let lhsItemCount = lhsItems.count let rhsItemCount = rhsItems.count if lhsItemCount != rhsItemCount { return false } for i in 0..<lhsItemCount { if lhsItems[i] != rhsItems[i] { return false } } return true } // Demonstration of Queues var q = Queue<Int>() for i in 0..<3 { q.push(i) } q var q2 = q // q2 is a new reference to the same object referenced by q q2 q2 === q // true, because q and q2 refer to the same object instance while !q.isEmpty { println(q.pop()) } q q2 // q == q2 // Although we know q and q2 are equal, they cannot be compared using == because the function for the operator is not implemented. Most classes that implement this adopt the Equatable Protocol. // EquatableQueue instances can be compared var eq = EquatableQueue<Int>() for i in 0..<3 { eq.push(i) } var eq2 = eq eq === eq2 eq == eq2 // Because EquatableQueue is Equatable, we can compare the inner values var eq3 = EquatableQueue<Int>() eq3 != eq // eq3 is not equal to eq, because it has different contents for i in 0..<3 { eq3.push(i) } eq3 != eq // eq3 is now equal to eq by value, even though they are different object instances eq3 !== eq // not the same objects while !eq.isEmpty { println(eq.pop()) } eq == eq2 // Still equal // If we knew that a Queue was really constructed as an EquatableQueue, we could downcast it var qAsEq: Queue<Int> = EquatableQueue<Int>() var qAsEq2 = qAsEq qAsEq as! EquatableQueue == qAsEq2 as! EquatableQueue
cc0051b08a5ce217db49af67c4e84fa4
29.06993
204
0.686744
false
false
false
false
rumana1411/Giphying
refs/heads/master
SwappingCollectionView/BackTableViewController.swift
mit
1
// // BackTableViewController.swift // swRevealSlidingMenu // // Created by Rumana Nazmul on 20/6/17. // Copyright © 2017 ALFA. All rights reserved. // import UIKit class BackTableViewController: UITableViewController { var menuArray = ["Home","Level","Album","Score","About", "Help"] var controllers = ["ViewController","LvlViewController","AlbumViewController","ScrViewController","AboutViewController","HelpViewController"] var menuIcon = ["iconsHome","iconsLevel","iconsAbout","iconsScore","iconsAbout","iconsHelp"] var frontNVC: UINavigationController? var frontVC: ViewController? override func viewDidLoad() { super.viewDidLoad() let logo = UIImage(named: "Logo.png") let logoImgView = UIImageView(image: logo) logoImgView.frame = CGRect(x: 100, y: 10, width: 10, height: 40 ) self.navigationItem.titleView = logoImgView } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell var imgName = menuIcon[indexPath.row] + ".png" cell.myImgView.image = UIImage(named: imgName) cell.myLbl.text = menuArray[indexPath.row] return cell } // override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // // let revealViewController: SWRevealViewController = self.revealViewController() // // let cell:CustomTableViewCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell // // // // // if cell.myLbl.text == "Home"{ // // let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController // let newFrontViewController = UINavigationController.init(rootViewController: destVC) // revealViewController.pushFrontViewController(newFrontViewController, animated: true) // // } // // if cell.myLbl.text == "Level"{ // // let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "LvlViewController") as! LvlViewController // let newFrontViewController = UINavigationController.init(rootViewController: destVC) // revealViewController.pushFrontViewController(newFrontViewController, animated: true) // // } // if cell.myLbl.text == "Album"{ // // let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "AlbumViewController") as! AlbumViewController // let newFrontViewController = UINavigationController.init(rootViewController: destVC) // revealViewController.pushFrontViewController(newFrontViewController, animated: true) // // } // // if cell.myLbl.text == "Score"{ // // let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "ScrViewController") as! ScrViewController // let newFrontViewController = UINavigationController.init(rootViewController: destVC) // revealViewController.pushFrontViewController(newFrontViewController, animated: true) // // } // // if cell.myLbl.text == "About"{ // // let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "AboutViewController") as! AboutViewController // let newFrontViewController = UINavigationController.init(rootViewController: destVC) // revealViewController.pushFrontViewController(newFrontViewController, animated: true) // } // // } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //tableView.deselectRow(at: indexPath, animated: true) var controller: UIViewController? = nil switch indexPath.row { case 0: controller = frontVC default: // Instantiate the controller to present let storyboard = UIStoryboard(name: "Main", bundle: nil) controller = storyboard.instantiateViewController(withIdentifier: controllers[indexPath.row]) break } if controller != nil { // Prevent stacking the same controller multiple times _ = frontNVC?.popViewController(animated: false) // Prevent pushing twice FrontTableViewController if !(controller is ViewController) { // Show the controller with the front view controller's navigation controller frontNVC!.pushViewController(controller!, animated: false) } // Set front view controller's position to left revealViewController().setFrontViewPosition(.left, animated: true) } } // override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // // var headerTitle: String! // headerTitle = "Giphying" // return headerTitle // } // override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // // // let headerView = UIView() // // // headerView.backgroundColor = UIColor.white // let viewImg = UIImage(named: "Logo.png") // let headerImgView = UIImageView(image: viewImg) // headerImgView.frame = CGRect(x: 60, y: 10, width: 120, height: 100) // headerView.addSubview(headerImgView) // // return headerView // // // } // // override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // // // return 110 // } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 112 } }
128342708edf08f934535971409faea2
36.271739
145
0.62438
false
false
false
false
abunur/quran-ios
refs/heads/master
Quran/TextRenderPreloadingOperation.swift
gpl-3.0
2
// // TextRenderPreloadingOperation.swift // Quran // // Created by Mohamed Afifi on 3/28/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import PromiseKit import UIKit class TextRenderPreloadingOperation: AbstractPreloadingOperation<UIImage> { let layout: TranslationTextLayout init(layout: TranslationTextLayout) { self.layout = layout } override func main() { autoreleasepool { guard let textLayout = layout.longTextLayout else { fatalError("Cannot use \(type(of: self)) with nil longTextLayout") } let layoutManager = NSLayoutManager() let textStorage = NSTextStorage(attributedString: layout.text.attributedText) textStorage.addLayoutManager(layoutManager) layoutManager.addTextContainer(textLayout.textContainer) // make sure the layout and glyph generations occurred. layoutManager.ensureLayout(for: textLayout.textContainer) layoutManager.ensureGlyphs(forGlyphRange: NSRange(location: 0, length: textLayout.numberOfGlyphs)) let image = imageFromText(layoutManager: layoutManager, numberOfGlyphs: textLayout.numberOfGlyphs, size: layout.size) fulfill(image) } } private func imageFromText(layoutManager: NSLayoutManager, numberOfGlyphs: Int, size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) let range = NSRange(location: 0, length: numberOfGlyphs) layoutManager.drawGlyphs(forGlyphRange: range, at: .zero) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return cast(image) } }
89170d81c0f85fbef8e6b4a352a20bab
35.276923
110
0.680237
false
false
false
false
zavsby/ProjectHelpersSwift
refs/heads/master
Classes/Categories/UIView+Extensions.swift
mit
1
// // UIView+Extensions.swift // ProjectHelpers-Swift // // Created by Sergey on 02.11.15. // Copyright © 2015 Sergey Plotkin. All rights reserved. // import Foundation import UIKit public extension UIView { //MARK: View frame and dimensions public var top: Float { get { return Float(self.frame.origin.y) } set(top) { var frame = self.frame frame.origin.y = CGFloat(top) self.frame = frame } } public var left: Float { get { return Float(self.frame.origin.x) } set(left) { var frame = self.frame frame.origin.x = CGFloat(left) self.frame = frame } } public var bottom: Float { get { return Float(self.frame.origin.y + self.frame.size.height) } set(bottom) { var frame = self.frame frame.origin.y = CGFloat(bottom) - frame.size.height self.frame = frame } } public var right: Float { get { return Float(self.frame.origin.x + self.frame.size.width) } set(right) { var frame = self.frame frame.origin.x = CGFloat(right) - frame.size.width self.frame = frame } } public var height: Float { get { return Float(self.frame.size.height) } set(height) { var frame = self.frame frame.size.height = CGFloat(height) self.frame = frame } } public var width: Float { get { return Float(self.frame.size.width) } set(width) { var frame = self.frame frame.size.width = CGFloat(width) self.frame = frame; } } //MARK: Addtional methods public func screenImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0) self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true) let copiedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return copiedImage } }
b33794480c64fab75bf84fdba98578de
23.402174
75
0.528966
false
false
false
false
Den-Ree/InstagramAPI
refs/heads/master
src/InstagramAPI/InstagramAPI/Example/ViewControllers/Relationship/RelationshipTableViewController.swift
mit
2
// // TableViewController.swift // InstagramAPI // // Created by Admin on 02.06.17. // Copyright © 2017 ConceptOffice. All rights reserved. // import UIKit import Alamofire enum RelationshipTableControllerType { case follows case followedBy case requestedBy case unknown } class RelationshipTableViewController: UITableViewController { var type: RelationshipTableControllerType = .unknown fileprivate var dataSource: [InstagramUser] = [] override func viewDidLoad() { super.viewDidLoad() let relationshipTableViewModel = RelationshipTableViewModel.init(type: self.type) let request = relationshipTableViewModel.request() relationshipTableViewModel.getDataSource(request: request!, completion: { (dataSource: [InstagramUser]?) in if dataSource != nil { self.dataSource = dataSource! self.tableView.reloadData() } }) } } extension RelationshipTableViewController { // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSource.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "RelationshipCell", for: indexPath) as!RelationshipCell let user = dataSource[indexPath.row] cell.fullNameLabel.text = user.fullName cell.userNameLabel.text = user.username cell.avatarImage.af_setImage(withURL: user.profilePictureUrl!) return cell } }
c044cd3cb8d1c66a358c2af46590ee6f
28.40678
120
0.701441
false
false
false
false
palle-k/SyntaxKit
refs/heads/master
SyntaxKit/SKLayoutManager.swift
mit
1
// // SKLayoutManager.swift // SyntaxKit // // Created by Palle Klewitz on 24.04.16. // Copyright © 2016 Palle Klewitz. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is furnished // to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import Foundation import UIKit @available(*, deprecated:1.0, renamed:"LineNumberLayoutManager") typealias SKLayoutManager = LineNumberLayoutManager class LineNumberLayoutManager : NSLayoutManager { fileprivate var lastParagraphNumber: Int = 0 fileprivate var lastParagraphLocation: Int = 0 internal let lineNumberWidth: CGFloat = 30.0 override func processEditing(for textStorage: NSTextStorage, edited editMask: NSTextStorageEditActions, range newCharRange: NSRange, changeInLength delta: Int, invalidatedRange invalidatedCharRange: NSRange) { super.processEditing(for: textStorage, edited: editMask, range: newCharRange, changeInLength: delta, invalidatedRange: invalidatedCharRange) if invalidatedCharRange.location < lastParagraphLocation { lastParagraphLocation = 0 lastParagraphNumber = 0 } } override func drawBackground(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) { super.drawBackground(forGlyphRange: glyphsToShow, at: origin) let font = UIFont(name: "Menlo", size: 10.0)! let color = UIColor.lightGray let attributes = [NSFontAttributeName : font, NSForegroundColorAttributeName : color] var numberRect = CGRect.zero var paragraphNumber = 0 let ctx = UIGraphicsGetCurrentContext() ctx?.setFillColor(UIColor.white.withAlphaComponent(0.1).cgColor) ctx?.fill(CGRect(x: 0, y: 0, width: lineNumberWidth, height: self.textContainers[0].size.height)) self.enumerateLineFragments(forGlyphRange: glyphsToShow) { (rect, usedRect, textContainer, glyphRange, stop) in let charRange = self.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil) let paragraphRange = (self.textStorage!.string as NSString).paragraphRange(for: charRange) if charRange.location == paragraphRange.location { numberRect = CGRect(x: 0, y: rect.origin.y, width: self.lineNumberWidth, height: rect.size.height).offsetBy(dx: origin.x, dy: origin.y) paragraphNumber = self.paragraphNumber(forRange: charRange) let lineNumber = "\(paragraphNumber + 1)" as NSString let size = lineNumber.size(attributes: attributes) lineNumber.draw(in: numberRect.offsetBy(dx: numberRect.width - 4 - size.width, dy: (numberRect.height - size.height) * 0.5 + 1.0), withAttributes: attributes) } } if NSMaxRange(glyphsToShow) > self.numberOfGlyphs { let lineNumber = "\(paragraphNumber + 2)" as NSString let size = lineNumber.size(attributes: attributes) numberRect = numberRect.offsetBy(dx: 0, dy: numberRect.height) lineNumber.draw(in: numberRect.offsetBy(dx: numberRect.width - 4 - size.width, dy: (numberRect.height - size.height) * 0.5 + 1.0), withAttributes: attributes) } } fileprivate func paragraphNumber(forRange charRange: NSRange) -> Int { if charRange.location == lastParagraphLocation { return lastParagraphNumber } else if charRange.location < lastParagraphLocation { let string = textStorage!.string as NSString var paragraphNumber = lastParagraphNumber string.enumerateSubstrings( in: NSRange( location: charRange.location, length: lastParagraphLocation - charRange.location), options: [.byParagraphs, .substringNotRequired, .reverse]) { (substring, substringRange, enclosingRange, stop) in if enclosingRange.location <= charRange.location { stop.pointee = true } paragraphNumber -= 1 } lastParagraphNumber = paragraphNumber lastParagraphLocation = charRange.location return paragraphNumber } else { let string = textStorage!.string as NSString var paragraphNumber = lastParagraphNumber string.enumerateSubstrings( in: NSRange( location: lastParagraphLocation, length: charRange.location - lastParagraphLocation), options: [.byParagraphs, .substringNotRequired]) { (substring, substringRange, enclosingRange, stop) in if enclosingRange.location >= charRange.location { stop.pointee = true } paragraphNumber += 1 } lastParagraphNumber = paragraphNumber lastParagraphLocation = charRange.location return paragraphNumber } } }
5e8f4775ba09731c3116100ae76c695b
37.05
208
0.745823
false
false
false
false
FredCox3/public-jss
refs/heads/master
Swift-Groups/Just.swift
mit
1
// // Just.swift // Just // // Created by Daniel Duan on 4/21/15. // Copyright (c) 2015 JustHTTP. All rights reserved. // import Foundation extension Just { public class func delete( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, cookies:[String:String] = [:], allowRedirects:Bool = true, timeout:Double? = nil, URLQuery:String? = nil, requestBody:NSData? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .DELETE, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout:timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } public class func get( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, allowRedirects:Bool = true, cookies:[String:String] = [:], timeout:Double? = nil, requestBody:NSData? = nil, URLQuery:String? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .GET, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout:timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } public class func head( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, cookies:[String:String] = [:], allowRedirects:Bool = true, timeout:Double? = nil, requestBody:NSData? = nil, URLQuery:String? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .HEAD, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } public class func options( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, cookies:[String:String] = [:], allowRedirects:Bool = true, timeout:Double? = nil, requestBody:NSData? = nil, URLQuery:String? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .OPTIONS, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } public class func patch( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, cookies:[String:String] = [:], allowRedirects:Bool = true, timeout:Double? = nil, requestBody:NSData? = nil, URLQuery:String? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .OPTIONS, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } public class func post( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, cookies:[String:String] = [:], allowRedirects:Bool = true, timeout:Double? = nil, requestBody:NSData? = nil, URLQuery:String? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .POST, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } public class func put( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, cookies:[String:String] = [:], allowRedirects:Bool = true, timeout:Double? = nil, requestBody:NSData? = nil, URLQuery:String? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .PUT, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } } public enum HTTPFile { case URL(NSURL,String?) // URL to a file, mimetype case Data(String,NSData,String?) // filename, data, mimetype case Text(String,String,String?) // filename, text, mimetype } // Supported request types enum HTTPMethod: String { case DELETE = "DELETE" case GET = "GET" case HEAD = "HEAD" case OPTIONS = "OPTIONS" case PATCH = "PATCH" case POST = "POST" case PUT = "PUT" } /// The only reason this is not a struct is the requirements for /// lazy evaluation of `headers` and `cookies`, which is mutating the /// struct. This would make those properties unusable with `HTTPResult`s /// declared with `let` public final class HTTPResult : NSObject { public final var content:NSData? public var response:NSURLResponse? public var error:NSError? public var request:NSURLRequest? public var encoding = NSUTF8StringEncoding public var JSONReadingOptions = NSJSONReadingOptions(rawValue: 0) public var reason:String { if let code = self.statusCode, let text = statusCodeDescriptions[code] { return text } if let error = self.error { return error.localizedDescription } return "Unkown" } public var isRedirect:Bool { if let code = self.statusCode { return code >= 300 && code < 400 } return false } public var isPermanentRedirect:Bool { return self.statusCode == 301 } public override var description:String { if let status = statusCode, urlString = request?.URL?.absoluteString, method = request?.HTTPMethod { return "\(method) \(urlString) \(status)" } else { return "<Empty>" } } init(data:NSData?, response:NSURLResponse?, error:NSError?, request:NSURLRequest?) { self.content = data self.response = response self.error = error self.request = request } public var json:AnyObject? { if let theData = self.content { do { return try NSJSONSerialization.JSONObjectWithData(theData, options: JSONReadingOptions) } catch _ { return nil } } return nil } public var statusCode: Int? { if let theResponse = self.response as? NSHTTPURLResponse { return theResponse.statusCode } return nil } public var text:String? { if let theData = self.content { return NSString(data:theData, encoding:encoding) as? String } return nil } public lazy var headers:CaseInsensitiveDictionary<String,String> = { return CaseInsensitiveDictionary<String,String>(dictionary: (self.response as? NSHTTPURLResponse)?.allHeaderFields as? [String:String] ?? [:]) }() public lazy var cookies:[String:NSHTTPCookie] = { let foundCookies: [NSHTTPCookie] if let responseHeaders = (self.response as? NSHTTPURLResponse)?.allHeaderFields as? [String: String] { foundCookies = NSHTTPCookie.cookiesWithResponseHeaderFields(responseHeaders, forURL:NSURL(string:"")!) as [NSHTTPCookie] } else { foundCookies = [] } var result:[String:NSHTTPCookie] = [:] for cookie in foundCookies { result[cookie.name] = cookie } return result }() public var ok:Bool { return statusCode != nil && !(statusCode! >= 400 && statusCode! < 600) } public var url:NSURL? { return response?.URL } } public struct CaseInsensitiveDictionary<Key: Hashable, Value>: CollectionType, DictionaryLiteralConvertible { private var _data:[Key: Value] = [:] private var _keyMap: [String: Key] = [:] typealias Element = (Key, Value) typealias Index = DictionaryIndex<Key, Value> public var startIndex: Index public var endIndex: Index public var count: Int { assert(_data.count == _keyMap.count, "internal keys out of sync") return _data.count } public var isEmpty: Bool { return _data.isEmpty } public init() { startIndex = _data.startIndex endIndex = _data.endIndex } public init(dictionaryLiteral elements: (Key, Value)...) { for (key, value) in elements { _keyMap["\(key)".lowercaseString] = key _data[key] = value } startIndex = _data.startIndex endIndex = _data.endIndex } public init(dictionary:[Key:Value]) { for (key, value) in dictionary { _keyMap["\(key)".lowercaseString] = key _data[key] = value } startIndex = _data.startIndex endIndex = _data.endIndex } public subscript (position: Index) -> Element { return _data[position] } public subscript (key: Key) -> Value? { get { if let realKey = _keyMap["\(key)".lowercaseString] { return _data[realKey] } return nil } set(newValue) { let lowerKey = "\(key)".lowercaseString if _keyMap[lowerKey] == nil { _keyMap[lowerKey] = key } _data[_keyMap[lowerKey]!] = newValue } } public func generate() -> DictionaryGenerator<Key, Value> { return _data.generate() } // public var keys: LazyForwardCollection<MapCollection<[Key : Value], Key>> { // return _data.keys // } // public var values: LazyForwardCollection<MapCollection<[Key : Value], Value>> { // return _data.values // } } typealias TaskID = Int typealias Credentials = (username:String, password:String) typealias TaskProgressHandler = (HTTPProgress!) -> Void typealias TaskCompletionHandler = (HTTPResult) -> Void struct TaskConfiguration { let credential:Credentials? let redirects:Bool let originalRequest: NSURLRequest? var data: NSMutableData let progressHandler: TaskProgressHandler? let completionHandler: TaskCompletionHandler? } public struct JustSessionDefaults { public var JSONReadingOptions = NSJSONReadingOptions(rawValue: 0) public var JSONWritingOptions = NSJSONWritingOptions(rawValue: 0) public var headers:[String:String] = [:] public var multipartBoundary = "Ju5tH77P15Aw350m3" public var encoding = NSUTF8StringEncoding } public struct HTTPProgress { public enum Type { case Upload case Download } public let type:Type public let bytesProcessed:Int64 public let bytesExpectedToProcess:Int64 public var percent: Float { return Float(bytesProcessed) / Float(bytesExpectedToProcess) } } let errorDomain = "net.justhttp.Just" public class Just: NSObject, NSURLSessionDelegate { private struct Shared { static let instance = Just() } class var shared: Just { return Shared.instance } public init(session:NSURLSession? = nil, defaults:JustSessionDefaults? = nil) { super.init() if let initialSession = session { self.session = initialSession } else { self.session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate:self, delegateQueue:nil) } if let initialDefaults = defaults { self.defaults = initialDefaults } else { self.defaults = JustSessionDefaults() } } var taskConfigs:[TaskID:TaskConfiguration]=[:] var defaults:JustSessionDefaults! var session: NSURLSession! var invalidURLError = NSError( domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey:"[Just] URL is invalid"] ) var syncResultAccessError = NSError( domain: errorDomain, code: 1, userInfo: [NSLocalizedDescriptionKey:"[Just] You are accessing asynchronous result synchronously."] ) func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)", value) } } else { components.extend([(percentEncodeString(key), percentEncodeString("\(value)"))]) } return components } func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sort(<) { let value: AnyObject! = parameters[key] components += self.queryComponents(key, value) } return "&".join(components.map{"\($0)=\($1)"} as [String]) } func percentEncodeString(originalObject: AnyObject) -> String { if originalObject is NSNull { return "null" } else { return "\(originalObject)".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) ?? "" } } func makeTask(request:NSURLRequest, configuration: TaskConfiguration) -> NSURLSessionDataTask? { if let task = session.dataTaskWithRequest(request) { taskConfigs[task.taskIdentifier] = configuration return task } return nil } func synthesizeMultipartBody(data:[String:AnyObject], files:[String:HTTPFile]) -> NSData? { let body = NSMutableData() let boundary = "--\(self.defaults.multipartBoundary)\r\n".dataUsingEncoding(defaults.encoding)! for (k,v) in data { let valueToSend:AnyObject = v is NSNull ? "null" : v body.appendData(boundary) body.appendData("Content-Disposition: form-data; name=\"\(k)\"\r\n\r\n".dataUsingEncoding(defaults.encoding)!) body.appendData("\(valueToSend)\r\n".dataUsingEncoding(defaults.encoding)!) } for (k,v) in files { body.appendData(boundary) var partContent: NSData? = nil var partFilename:String? = nil var partMimetype:String? = nil switch v { case let .URL(URL, mimetype): if let component = URL.lastPathComponent { partFilename = component } if let URLContent = NSData(contentsOfURL: URL) { partContent = URLContent } partMimetype = mimetype case let .Text(filename, text, mimetype): partFilename = filename if let textData = text.dataUsingEncoding(defaults.encoding) { partContent = textData } partMimetype = mimetype case let .Data(filename, data, mimetype): partFilename = filename partContent = data partMimetype = mimetype } if let content = partContent, let filename = partFilename { body.appendData(NSData(data: "Content-Disposition: form-data; name=\"\(k)\"; filename=\"\(filename)\"\r\n".dataUsingEncoding(defaults.encoding)!)) if let type = partMimetype { body.appendData("Content-Type: \(type)\r\n\r\n".dataUsingEncoding(defaults.encoding)!) } else { body.appendData("\r\n".dataUsingEncoding(defaults.encoding)!) } body.appendData(content) body.appendData("\r\n".dataUsingEncoding(defaults.encoding)!) } } if body.length > 0 { body.appendData("--\(self.defaults.multipartBoundary)--\r\n".dataUsingEncoding(defaults.encoding)!) } return body } func synthesizeRequest( method:HTTPMethod, URLString:String, params:[String:AnyObject], data:[String:AnyObject], json:[String:AnyObject]?, headers:CaseInsensitiveDictionary<String,String>, files:[String:HTTPFile], timeout:Double?, requestBody:NSData?, URLQuery:String? ) -> NSURLRequest? { if let urlComponent = NSURLComponents(string: URLString) { let queryString = query(params) if queryString.characters.count > 0 { urlComponent.percentEncodedQuery = queryString } var finalHeaders = headers var contentType:String? = nil var body:NSData? if let requestData = requestBody { body = requestData } else if files.count > 0 { body = synthesizeMultipartBody(data, files:files) contentType = "multipart/form-data; boundary=\(self.defaults.multipartBoundary)" } else { if let requestJSON = json { contentType = "application/json" do { body = try NSJSONSerialization.dataWithJSONObject(requestJSON, options: defaults.JSONWritingOptions) } catch _ { body = nil } } else { if data.count > 0 { if headers["content-type"]?.lowercaseString == "application/json" { // assume user wants JSON if she is using this header do { body = try NSJSONSerialization.dataWithJSONObject(data, options: defaults.JSONWritingOptions) } catch _ { body = nil } } else { contentType = "application/x-www-form-urlencoded" body = query(data).dataUsingEncoding(defaults.encoding) } } } } if let contentTypeValue = contentType { finalHeaders["Content-Type"] = contentTypeValue } if let URL = urlComponent.URL { let request = NSMutableURLRequest(URL: URL) request.cachePolicy = .ReloadIgnoringLocalCacheData request.HTTPBody = body request.HTTPMethod = method.rawValue if let requestTimeout = timeout { request.timeoutInterval = requestTimeout } for (k,v) in defaults.headers { request.addValue(v, forHTTPHeaderField: k) } for (k,v) in finalHeaders { request.addValue(v, forHTTPHeaderField: k) } return request } } return nil } func request( method:HTTPMethod, URLString:String, params:[String:AnyObject], data:[String:AnyObject], json:[String:AnyObject]?, headers:[String:String], files:[String:HTTPFile], auth:Credentials?, cookies: [String:String], redirects:Bool, timeout:Double?, URLQuery:String?, requestBody:NSData?, asyncProgressHandler:TaskProgressHandler?, asyncCompletionHandler:((HTTPResult!) -> Void)?) -> HTTPResult { let isSync = asyncCompletionHandler == nil let semaphore = dispatch_semaphore_create(0) var requestResult:HTTPResult = HTTPResult(data: nil, response: nil, error: syncResultAccessError, request: nil) let caseInsensitiveHeaders = CaseInsensitiveDictionary<String,String>(dictionary:headers) if let request = synthesizeRequest( method, URLString: URLString, params: params, data: data, json: json, headers: caseInsensitiveHeaders, files: files, timeout:timeout, requestBody:requestBody, URLQuery: URLQuery ) { addCookies(request.URL!, newCookies: cookies) let config = TaskConfiguration( credential:auth, redirects:redirects, originalRequest:request, data:NSMutableData(), progressHandler: asyncProgressHandler ) { (result) in if let handler = asyncCompletionHandler { handler(result) } if isSync { requestResult = result dispatch_semaphore_signal(semaphore) } } if let task = makeTask(request, configuration:config) { task.resume() } if isSync { dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) return requestResult } } else { let erronousResult = HTTPResult(data: nil, response: nil, error: invalidURLError, request: nil) if let handler = asyncCompletionHandler { handler(erronousResult) } else { return erronousResult } } return requestResult } func addCookies(URL:NSURL, newCookies:[String:String]) { for (k,v) in newCookies { if let cookie = NSHTTPCookie(properties: [ NSHTTPCookieName: k, NSHTTPCookieValue: v, NSHTTPCookieOriginURL: URL, NSHTTPCookiePath: "/" ]) { session.configuration.HTTPCookieStorage?.setCookie(cookie) } } } } extension Just: NSURLSessionTaskDelegate, NSURLSessionDataDelegate { public func URLSession( session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void ) { var endCredential:NSURLCredential? = nil if let credential = taskConfigs[task.taskIdentifier]?.credential { if !(challenge.previousFailureCount > 0) { endCredential = NSURLCredential(user: credential.0, password: credential.1, persistence: .ForSession) } } completionHandler(.UseCredential, endCredential) } public func URLSession( session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest?) -> Void ) { if let allowRedirects = taskConfigs[task.taskIdentifier]?.redirects { if !allowRedirects { completionHandler(nil) return } completionHandler(request) } else { completionHandler(request) } } public func URLSession( session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64 ) { if let handler = taskConfigs[task.taskIdentifier]?.progressHandler { handler( HTTPProgress( type: .Upload, bytesProcessed: totalBytesSent, bytesExpectedToProcess: totalBytesExpectedToSend ) ) } } public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if let handler = taskConfigs[dataTask.taskIdentifier]?.progressHandler { handler( HTTPProgress( type: .Download, bytesProcessed: dataTask.countOfBytesReceived, bytesExpectedToProcess: dataTask.countOfBytesExpectedToReceive ) ) } if taskConfigs[dataTask.taskIdentifier]?.data != nil { taskConfigs[dataTask.taskIdentifier]?.data.appendData(data) } } public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let config = taskConfigs[task.taskIdentifier], let handler = config.completionHandler { let result = HTTPResult( data: config.data, response: task.response, error: error, request: config.originalRequest ?? task.originalRequest ) result.JSONReadingOptions = self.defaults.JSONReadingOptions result.encoding = self.defaults.encoding handler(result) } taskConfigs.removeValueForKey(task.taskIdentifier) } } // stolen from python-requests let statusCodeDescriptions = [ // Informational. 100: "continue" , 101: "switching protocols" , 102: "processing" , 103: "checkpoint" , 122: "uri too long" , 200: "ok" , 201: "created" , 202: "accepted" , 203: "non authoritative info" , 204: "no content" , 205: "reset content" , 206: "partial content" , 207: "multi status" , 208: "already reported" , 226: "im used" , // Redirection. 300: "multiple choices" , 301: "moved permanently" , 302: "found" , 303: "see other" , 304: "not modified" , 305: "use proxy" , 306: "switch proxy" , 307: "temporary redirect" , 308: "permanent redirect" , // Client Error. 400: "bad request" , 401: "unauthorized" , 402: "payment required" , 403: "forbidden" , 404: "not found" , 405: "method not allowed" , 406: "not acceptable" , 407: "proxy authentication required" , 408: "request timeout" , 409: "conflict" , 410: "gone" , 411: "length required" , 412: "precondition failed" , 413: "request entity too large" , 414: "request uri too large" , 415: "unsupported media type" , 416: "requested range not satisfiable" , 417: "expectation failed" , 418: "im a teapot" , 422: "unprocessable entity" , 423: "locked" , 424: "failed dependency" , 425: "unordered collection" , 426: "upgrade required" , 428: "precondition required" , 429: "too many requests" , 431: "header fields too large" , 444: "no response" , 449: "retry with" , 450: "blocked by windows parental controls" , 451: "unavailable for legal reasons" , 499: "client closed request" , // Server Error. 500: "internal server error" , 501: "not implemented" , 502: "bad gateway" , 503: "service unavailable" , 504: "gateway timeout" , 505: "http version not supported" , 506: "variant also negotiates" , 507: "insufficient storage" , 509: "bandwidth limit exceeded" , 510: "not extended" , ]
c88590ed24c28deb292d0b72f982f5f6
35.554098
162
0.532155
false
false
false
false
carlosgrossi/ExtensionKit
refs/heads/master
ExtensionKit/ExtensionKit/Foundation/NumberFormatter.swift
mit
1
// // NumberFormatter.swift // Pods // // Created by Carlos Grossi on 19/06/17. // // public extension NumberFormatter { /// Convenience Initializer that sets number style, minimum and maximum fraction digits and locale /// /// - Parameters: /// - numberStyle: The number style used by the receiver. /// - maximumFractionDigits: The maximum number of digits after the decimal separator allowed as input and output by the receiver. /// - minimumFractionDigits: The minimum number of digits after the decimal separator allowed as input and output by the receiver. /// - locale: The locale of the receiver. convenience init(numberStyle: NumberFormatter.Style, maximumFractionDigits: Int = 0, minimumFractionDigits: Int = 0, locale: Locale = Locale.current) { self.init() self.numberStyle = numberStyle self.maximumFractionDigits = maximumFractionDigits self.minimumFractionDigits = minimumFractionDigits self.locale = Locale.current } }
644c8ce97f51fa457b3774797912fdc3
36.269231
152
0.747162
false
false
false
false
TwoRingSoft/shared-utils
refs/heads/master
Examples/Pippin/Pippin-iOS/AppDelegate.swift
mit
1
// // AppDelegate.swift // PippinTestHarness // // Created by Andrew McKnight on 4/3/17. // // import Pippin import PippinAdapters #if DEBUG import PippinDebugging #endif import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var environment: Environment = { let environment = Environment.default( bugReportRecipients: ["[email protected]"], touchVizRootVC: ViewController(nibName: nil, bundle: nil) ) environment.crashReporter = CrashlyticsAdapter(debug: true) #if !targetEnvironment(simulator) environment.locator = CoreLocationAdapter(locatorDelegate: self) #endif #if DEBUG environment.model?.debuggingDelegate = self environment.debugging = DebugFlowController(databaseFileName: "PippinTestHarnessDatabase") #endif environment.connectEnvironment() return environment }() internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { #if DEBUG environment.debugging?.installViews(appControlPanel: nil) #endif environment.touchVisualizer?.installViews() return true } } #if DEBUG extension AppDelegate: ModelDebugging { func importFixtures(coreDataController: Model) { environment.alerter?.showAlert(title: "Import database fixtures", message: "This is where your app would imports its database from other instances of itself, like on another test device.", type: .info, dismissal: .interactive, occlusion: .weak) } func exported(coreDataController: Model) { environment.alerter?.showAlert(title: "Exporting database", message: "This is where your app would export its database to transport to other instances of itself, like on another test device.", type: .info, dismissal: .interactive, occlusion: .weak) } func generateTestModels(coreDataController: Model) { environment.alerter?.showAlert(title: "Generating test models", message: "This is where your app would generate some test model entities.", type: .info, dismissal: .interactive, occlusion: .strong) } func deleteModels(coreDataController: Model) { environment.alerter?.showAlert(title: "Deleting models", message: "This is where your app would delete its model entities.", type: .info, dismissal: .interactive, occlusion: .strong) } } #endif #if !targetEnvironment(simulator) extension AppDelegate: LocatorDelegate { func locator(locator: Locator, updatedToLocation location: Location) { environment.logger?.logInfo(message: "locator \(locator) updated to location \(location)") } func locator(locator: Locator, encounteredError: LocatorError) { environment.logger?.logError(message: "Locator \(locator) encountered error \(encounteredError)", error: encounteredError) } } #endif
2f22c6c4aa80d4a136a7f1a2be2b7c86
36.148148
256
0.71552
false
true
false
false
burhanaksendir/swift-disk-status
refs/heads/master
DiskStatus/DiskStatus.swift
mit
1
// // DiskStatus.swift // DiskStatus // // Created by Cuong Lam on 3/29/15. // Copyright (c) 2015 BE Studio. All rights reserved. // import UIKit class DiskStatus { //MARK: Formatter MB only class func MBFormatter(bytes: Int64) -> String { var formatter = NSByteCountFormatter() formatter.allowedUnits = NSByteCountFormatterUnits.UseMB formatter.countStyle = NSByteCountFormatterCountStyle.Decimal formatter.includesUnit = false return formatter.stringFromByteCount(bytes) as String } //MARK: Get String Value class var totalDiskSpace:String { get { return NSByteCountFormatter.stringFromByteCount(totalDiskSpaceInBytes, countStyle: NSByteCountFormatterCountStyle.Binary) } } class var freeDiskSpace:String { get { return NSByteCountFormatter.stringFromByteCount(freeDiskSpaceInBytes, countStyle: NSByteCountFormatterCountStyle.Binary) } } class var usedDiskSpace:String { get { return NSByteCountFormatter.stringFromByteCount(usedDiskSpaceInBytes, countStyle: NSByteCountFormatterCountStyle.Binary) } } //MARK: Get raw value class var totalDiskSpaceInBytes:Int64 { get { let systemAttributes = NSFileManager.defaultManager().attributesOfFileSystemForPath(NSHomeDirectory() as String, error: nil) let space = (systemAttributes?[NSFileSystemSize] as? NSNumber)?.longLongValue return space! } } class var freeDiskSpaceInBytes:Int64 { get { let systemAttributes = NSFileManager.defaultManager().attributesOfFileSystemForPath(NSHomeDirectory() as String, error: nil) let freeSpace = (systemAttributes?[NSFileSystemFreeSize] as? NSNumber)?.longLongValue return freeSpace! } } class var usedDiskSpaceInBytes:Int64 { get { let usedSpace = totalDiskSpaceInBytes - freeDiskSpaceInBytes return usedSpace } } }
cd1dbe788e922d02786bdf76e73a1e96
30.681818
136
0.663797
false
false
false
false
JOCR10/iOS-Curso
refs/heads/master
Tareas/Tarea 4/TareaDogsWithCoreData/TareaDogsWithCoreData/AddDogViewController.swift
mit
1
import UIKit class AddDogViewController: UITableViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var nombreTextField: UITextField! @IBOutlet weak var colorTextField: UITextField! @IBOutlet weak var dogImageView: UIImageView! var imagePicker = UIImagePickerController() var dogImage : NSData? override func viewDidLoad() { super.viewDidLoad() addSaveDogs() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func addSaveDogs() { let saveAction = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(saveDogsAction)) navigationItem.rightBarButtonItem = saveAction } func saveDogsAction() { guard let _ = dogImage else { mostrarAlerta(msj: "Debe seleccionar una imagen", titulo: "Alerta") return } if nombreTextField.text!.characters.count > 0 && colorTextField.text!.characters.count > 0 { CoreDataManager.createDog(name: nombreTextField.text!, color: colorTextField.text!, image: dogImage!) navigationController?.popViewController(animated: true) } else { mostrarAlerta(msj: "Debe digitar el nombre y el color del perro", titulo: "Alerta") } } func mostrarAlerta(msj: String, titulo: String){ let alertController = UIAlertController(title: titulo, message: msj, preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(action) present(alertController, animated: true, completion: nil) } @IBAction func examinarButton(_ sender: Any) { if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) { imagePicker.delegate = self imagePicker.sourceType = .photoLibrary self.present(imagePicker, animated: true, completion: nil) } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let image = info[UIImagePickerControllerOriginalImage]as! UIImage dogImageView.image = image dogImage = UIImagePNGRepresentation(image) as NSData? self.dismiss(animated: true, completion: nil); } }
f93d2d4c39b15b0a67f6258625c4373c
30.582278
117
0.646493
false
false
false
false
pkx0128/UIKit
refs/heads/master
MPickerInTextField/MPickerInTextField/ViewController.swift
mit
1
// // ViewController.swift // MPickerInTextField // // Created by pankx on 2017/9/22. // Copyright © 2017年 pankx. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { //定义picker的数据数组 let week = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"] //定义mytext fileprivate var mytext: UITextField! override func viewDidLoad() { super.viewDidLoad() //创建myicker let mypicker = UIPickerView() //设置代理 mypicker.delegate = self //设置数据源 mypicker.dataSource = self //创建mytext mytext = UITextField(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 80)) //设置位置 mytext.center = CGPoint(x: view.bounds.width * 0.5, y: view.bounds.height * 0.3) //设置内容居中 mytext.textAlignment = .center //设置键盘为mypicker mytext.inputView = mypicker //设置初始值为week[0]的值 mytext.text = week[0] //设置背景颜色 mytext.backgroundColor = UIColor.darkGray view.addSubview(mytext) } //设置picker的列数 func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } //设置picker内容行数据 func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return week.count } //设置picker内容 func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return week[row] } //把picker选中的内容设置到mytext func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { mytext.text = week[row] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
f1f6e772038a4359fecf42d42f0d693b
27.78125
111
0.631379
false
false
false
false
WhisperSystems/Signal-iOS
refs/heads/master
SignalServiceKit/src/Account/PreKeyRefreshOperation.swift
gpl-3.0
1
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit // We generate 100 one-time prekeys at a time. We should replenish // whenever ~2/3 of them have been consumed. let kEphemeralPreKeysMinimumCount: UInt = 35 @objc(SSKRefreshPreKeysOperation) public class RefreshPreKeysOperation: OWSOperation { private var tsAccountManager: TSAccountManager { return TSAccountManager.sharedInstance() } private var accountServiceClient: AccountServiceClient { return SSKEnvironment.shared.accountServiceClient } private var signedPreKeyStore: SSKSignedPreKeyStore { return SSKEnvironment.shared.signedPreKeyStore } private var preKeyStore: SSKPreKeyStore { return SSKEnvironment.shared.preKeyStore } private var identityKeyManager: OWSIdentityManager { return OWSIdentityManager.shared() } public override func run() { Logger.debug("") guard tsAccountManager.isRegistered else { Logger.debug("skipping - not registered") return } firstly { self.accountServiceClient.getPreKeysCount() }.then(on: DispatchQueue.global()) { preKeysCount -> Promise<Void> in Logger.debug("preKeysCount: \(preKeysCount)") guard preKeysCount < kEphemeralPreKeysMinimumCount || self.signedPreKeyStore.currentSignedPrekeyId() == nil else { Logger.debug("Available keys sufficient: \(preKeysCount)") return Promise.value(()) } let identityKey: Data = self.identityKeyManager.identityKeyPair()!.publicKey let signedPreKeyRecord: SignedPreKeyRecord = self.signedPreKeyStore.generateRandomSignedRecord() let preKeyRecords: [PreKeyRecord] = self.preKeyStore.generatePreKeyRecords() self.signedPreKeyStore.storeSignedPreKey(signedPreKeyRecord.id, signedPreKeyRecord: signedPreKeyRecord) self.preKeyStore.storePreKeyRecords(preKeyRecords) return firstly { self.accountServiceClient.setPreKeys(identityKey: identityKey, signedPreKeyRecord: signedPreKeyRecord, preKeyRecords: preKeyRecords) }.done { signedPreKeyRecord.markAsAcceptedByService() self.signedPreKeyStore.storeSignedPreKey(signedPreKeyRecord.id, signedPreKeyRecord: signedPreKeyRecord) self.signedPreKeyStore.setCurrentSignedPrekeyId(signedPreKeyRecord.id) TSPreKeyManager.clearPreKeyUpdateFailureCount() TSPreKeyManager.clearSignedPreKeyRecords() } }.done { Logger.debug("done") self.reportSuccess() }.catch { error in self.reportError(withUndefinedRetry: error) }.retainUntilComplete() } public override func didSucceed() { TSPreKeyManager.refreshPreKeysDidSucceed() } override public func didFail(error: Error) { switch error { case let networkManagerError as NetworkManagerError: guard !networkManagerError.isNetworkError else { Logger.debug("don't report SPK rotation failure w/ network error") return } guard networkManagerError.statusCode >= 400 && networkManagerError.statusCode <= 599 else { Logger.debug("don't report SPK rotation failure w/ non application error") return } TSPreKeyManager.incrementPreKeyUpdateFailureCount() default: Logger.debug("don't report SPK rotation failure w/ non NetworkManager error: \(error)") } } }
3c6a8e09da8e2f2176dd99ce57bf309f
36.434343
148
0.670264
false
false
false
false
caiodias/CleanerSkeeker
refs/heads/master
CleanerSeeker/CleanerSeeker/ResetPasswordViewController.swift
mit
1
// // ResetPasswordViewController.swift // CleanerSeeker // // Created by Orest Hazda on 03/04/17. // Copyright © 2017 Caio Dias. All rights reserved. // import UIKit class ResetPasswordViewController: BasicVC { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var email: UITextField! @IBOutlet weak var resetBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() //Disable resetBtn resetBtn.isEnabled = false // Do any additional setup after loading the view. email.addTarget(self, action: #selector(emailFieldDidChanged), for: .editingChanged) self.baseScrollView = self.scrollView } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func resetPassword(_ sender: UIButton) { if let userEmail = email.text { Utilities.showLoading() Facade.shared.resetPassword(email: userEmail, onSuccess: showSuccessAlert, onFail: showFailAlert) } } func emailFieldDidChanged(_ email: UITextField) { resetBtn.isEnabled = email.text != nil } private func showSuccessAlert(success:Any) { Utilities.dismissLoading() let action = UIAlertAction(title: "Return to Login screen", style: .default) { (_) in self.dismiss(animated: true, completion: nil) _ = self.navigationController?.popToRootViewController(animated: true) } Utilities.displayAlert(title: "Password Reset", message: "Check your email to proceed the progress.", okAction: action) } private func showFailAlert(error: Error) { Utilities.dismissLoading() Utilities.displayAlert(error) } }
8a185afb6b48bf055e0b3a9f469bd849
30.508772
127
0.669822
false
false
false
false
huonw/swift
refs/heads/master
test/SwiftSyntax/DeserializeFile.swift
apache-2.0
3
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: OS=macosx // REQUIRES: objc_interop import StdlibUnittest import Foundation import SwiftSyntax import SwiftLang func getInput(_ file: String) -> URL { var result = URL(fileURLWithPath: #file) result.deleteLastPathComponent() result.appendPathComponent("Inputs") result.appendPathComponent(file) return result } var DecodeTests = TestSuite("DecodeSyntax") DecodeTests.test("Basic") { expectDoesNotThrow({ let content = try SwiftLang.parse(getInput("visitor.swift")) let source = try String(contentsOf: getInput("visitor.swift")) let parsed = try SourceFileSyntax.decodeSourceFileSyntax(content) expectEqual("\(parsed)", source) }) } runAllTests()
8f5b173c0fad1952372560c10d115242
24.2
69
0.746032
false
true
false
false
Jnosh/swift
refs/heads/master
test/IRGen/objc.swift
apache-2.0
2
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation import gizmo // CHECK: [[TYPE:%swift.type]] = type // CHECK: [[BLAMMO:%T4objc6BlammoC]] = type // CHECK: [[MYBLAMMO:%T4objc8MyBlammoC]] = type // CHECK: [[TEST2:%T4objc5Test2C]] = type // CHECK: [[OBJC:%objc_object]] = type // CHECK: [[ID:%T4objc2idV]] = type <{ %AnyObject }> // CHECK: [[GIZMO:%TSo5GizmoC]] = type // CHECK: [[RECT:%TSC4RectV]] = type // CHECK: [[FLOAT:%TSf]] = type // CHECK: @"\01L_selector_data(bar)" = private global [4 x i8] c"bar\00", section "__TEXT,__objc_methname,cstring_literals", align 1 // CHECK: @"\01L_selector(bar)" = private externally_initialized global i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(bar)", i64 0, i64 0), section "__DATA,__objc_selrefs,literal_pointers,no_dead_strip", align 8 // CHECK: @_T0SC4RectVMn = linkonce_odr hidden constant // CHECK: @_T0SC4RectVN = linkonce_odr hidden global // CHECK: @"\01L_selector_data(acquiesce)" // CHECK-NOT: @"\01L_selector_data(disharmonize)" // CHECK: @"\01L_selector_data(eviscerate)" struct id { var data : AnyObject } // Exporting something as [objc] doesn't make it an ObjC class. @objc class Blammo { } // Class and methods are [objc] by inheritance. class MyBlammo : Blammo { func foo() {} // CHECK: define hidden swiftcc void @_T04objc8MyBlammoC3fooyyF([[MYBLAMMO]]* swiftself) {{.*}} { // CHECK: call {{.*}} @swift_rt_swift_release // CHECK: ret void } // Class and methods are [objc] by inheritance. class Test2 : Gizmo { func foo() {} // CHECK: define hidden swiftcc void @_T04objc5Test2C3fooyyF([[TEST2]]* swiftself) {{.*}} { // CHECK: call {{.*}} @objc_release // CHECK: ret void dynamic func bar() {} } // Test @nonobjc. class Contrarian : Blammo { func acquiesce() {} @nonobjc func disharmonize() {} @nonobjc func eviscerate() {} } class Octogenarian : Contrarian { // Override of @nonobjc is @objc again unless made @nonobjc. @nonobjc override func disharmonize() {} // Override of @nonobjc can be @objc. @objc override func eviscerate() {} } @_silgen_name("unknown") func unknown(_ x: id) -> id // CHECK: define hidden swiftcc %objc_object* @_T04objc5test0{{[_0-9a-zA-Z]*}}F(%objc_object*) // CHECK-NOT: call {{.*}} @swift_unknownRetain // CHECK: call {{.*}} @swift_unknownRetain // CHECK-NOT: call {{.*}} @swift_unknownRelease // CHECK: call {{.*}} @swift_unknownRelease // CHECK: ret %objc_object* func test0(_ arg: id) -> id { var x : id x = arg unknown(x) var y = x return y } func test1(_ cell: Blammo) {} // CHECK: define hidden swiftcc void @_T04objc5test1{{[_0-9a-zA-Z]*}}F([[BLAMMO]]*) {{.*}} { // CHECK: call {{.*}} @swift_rt_swift_release // CHECK: ret void // FIXME: These ownership convention tests should become SILGen tests. func test2(_ v: Test2) { v.bar() } func test3() -> NSObject { return Gizmo() } // Normal message send with argument, no transfers. func test5(_ g: Gizmo) { Gizmo.inspect(g) } // The argument to consume: is __attribute__((ns_consumed)). func test6(_ g: Gizmo) { Gizmo.consume(g) } // fork is __attribute__((ns_consumes_self)). func test7(_ g: Gizmo) { g.fork() } // clone is __attribute__((ns_returns_retained)). func test8(_ g: Gizmo) { g.clone() } // duplicate has an object returned at +0. func test9(_ g: Gizmo) { g.duplicate() } func test10(_ g: Gizmo, r: Rect) { Gizmo.run(with: r, andGizmo:g); } // Force the emission of the Rect metadata. func test11_helper<T>(_ t: T) {} // NSRect's metadata needs to be uniqued at runtime using getForeignTypeMetadata. // CHECK-LABEL: define hidden swiftcc void @_T04objc6test11ySC4RectVF // CHECK: call %swift.type* @swift_getForeignTypeMetadata({{.*}} @_T0SC4RectVN func test11(_ r: Rect) { test11_helper(r) } class WeakObjC { weak var obj: NSObject? weak var id: AnyObject? init() { var foo = obj var bar: AnyObject? = id } } // rdar://17528908 // CHECK: i32 1, !"Objective-C Version", i32 2} // CHECK: i32 1, !"Objective-C Image Info Version", i32 0} // CHECK: i32 1, !"Objective-C Image Info Section", !"__DATA, __objc_imageinfo, regular, no_dead_strip"} // 1280 == (5 << 8). 5 is the Swift ABI version. // CHECK: i32 4, !"Objective-C Garbage Collection", i32 1280} // CHECK: i32 1, !"Swift Version", i32 5}
a4285f9dda9170ef563eac6f83f5d632
29.972789
234
0.647924
false
true
false
false
ryanherman/intro
refs/heads/master
intro/LeftViewController.swift
mit
1
// // LeftViewController.swift // SlideMenuControllerSwift // // Created by Yuji Hato on 12/3/14. // import UIKit enum LeftMenu: Int { case Main = 0 case Introduction case Ask case About } protocol LeftMenuProtocol : class { func changeViewController(menu: LeftMenu) } class LeftViewController : UIViewController, LeftMenuProtocol { @IBOutlet weak var tableView: UITableView! var menus = ["Main", "Introduction", "Ask your Rabbi","About"] var mainViewController: UIViewController! var swiftViewController: UIViewController! var aboutViewController: UIViewController! var introductionViewController: UIViewController! var askViewController: UIViewController! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.tableView.separatorColor = UIColor(red: 224/255, green: 224/255, blue: 224/255, alpha: 1.0) let storyboard = UIStoryboard(name: "Main", bundle: nil) let mainViewController = storyboard.instantiateViewControllerWithIdentifier("MainViewController") as! MainViewController self.mainViewController = UINavigationController(rootViewController: mainViewController) let introductionViewController = storyboard.instantiateViewControllerWithIdentifier("IntroductionViewController") as! IntroductionViewController self.introductionViewController = UINavigationController(rootViewController: introductionViewController) let aboutViewController = storyboard.instantiateViewControllerWithIdentifier("AboutViewController") as! AboutViewController self.aboutViewController = UINavigationController(rootViewController: aboutViewController) let askViewController = storyboard.instantiateViewControllerWithIdentifier("AskViewController") as! AskViewController self.askViewController = UINavigationController(rootViewController: askViewController) self.tableView.registerCellClass(BaseTableViewCell.self) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menus.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: BaseTableViewCell = BaseTableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: BaseTableViewCell.identifier) cell.backgroundColor = UIColor(red: 64/255, green: 170/255, blue: 239/255, alpha: 1.0) cell.textLabel?.font = UIFont.italicSystemFontOfSize(18) cell.textLabel?.textColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0) cell.textLabel?.text = menus[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let menu = LeftMenu(rawValue: indexPath.item) { self.changeViewController(menu) } } func changeViewController(menu: LeftMenu) { switch menu { case .Main: self.slideMenuController()?.changeMainViewController(self.mainViewController, close: true) case .Introduction: self.slideMenuController()?.changeMainViewController(self.introductionViewController, close: true) break case .About: self.slideMenuController()?.changeMainViewController(self.aboutViewController, close: true) break case .Ask: self.slideMenuController()?.changeMainViewController(self.askViewController, close: true) break default: break } } }
b2f004efc7ff79f5fd787635c69feabe
37.979798
152
0.705547
false
false
false
false
criticalmaps/criticalmaps-ios
refs/heads/main
CriticalMapsKit/Sources/AppFeature/NetworkConnectionObserver.swift
mit
1
import ComposableArchitecture import Foundation import Logger import PathMonitorClient import SharedDependencies public struct NetworkConnectionObserver: ReducerProtocol { public init() {} @Dependency(\.pathMonitorClient) public var pathMonitorClient public struct State: Equatable { var isNetworkAvailable = true } public enum Action: Equatable { case observeConnection case observeConnectionResponse(NetworkPath) } public func reduce(into state: inout State, action: Action) -> Effect<Action, Never> { switch action { case .observeConnection: return .run { send in for await path in await pathMonitorClient.networkPathPublisher() { await send(.observeConnectionResponse(path)) } } .cancellable(id: ObserveConnectionIdentifier()) case let .observeConnectionResponse(networkPath): state.isNetworkAvailable = networkPath.status == .satisfied SharedDependencies._isNetworkAvailable = state.isNetworkAvailable logger.info("Is network available: \(state.isNetworkAvailable)") return .none } } } struct ObserveConnectionIdentifier: Hashable {}
869c24c6c1f6c4391257f2a1ef212e71
27.756098
88
0.724343
false
false
false
false
behoernchen/Iconizer
refs/heads/master
Iconizer/Models/ContentsJSON.swift
mit
1
// // JSONFile.swift // Iconizer // https://github.com/raphaelhanneken/iconizer // // The MIT License (MIT) // // Copyright (c) 2015 Raphael Hanneken // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Cocoa /// Reads and writes the Contents JSON files. struct ContentsJSON { /// Holds the image data from <AssetType>.json var images: Array<[String : String]> /// Holds the complete information required for Contents.json var contents: [String : AnyObject] = [:] // MARK: Initializers /// Initializes the JSONData struct. /// /// - returns: The initialized JSONData struct. init() { // Init the images array. self.images = [] // Init the contents array, with general information. self.contents["author"] = "Iconizer" self.contents["version"] = "1.0" self.contents["images"] = [] } /// Initializes the JSONData struct with a specified AssetType and /// selected platforms. /// /// - parameter type: The AssetType for the required JSON data /// - parameter platforms: Selected platforms /// /// - returns: The initialized JSONData specified for an AssetType and platforms. init(forType type: AssetType, andPlatforms platforms: [String]) { // Basic initialization. self.init() // Initialize the data object. for platform in platforms { // Add the image information for each platform to our images array. do { images += try JSONObjectForType(type, andPlatform: platform) } catch { print(error) } } } // MARK: Methods /// Gets the JSON data for the given AssetType. /// /// - parameter type: AssetType to get the json file for. /// /// - returns: The JSON data for the given AssetType. func JSONObjectForType(type: AssetType, andPlatform platform: String) throws -> Array<[String : String]> { // Holds the path to the required JSON file. let resourcePath : String? // Get the correct JSON file for the given AssetType. switch (type) { case .AppIcon: resourcePath = NSBundle.mainBundle().pathForResource("AppIcon_" + platform, ofType: "json") case .ImageSet: resourcePath = NSBundle.mainBundle().pathForResource("ImageSet", ofType: "json") case .LaunchImage: resourcePath = NSBundle.mainBundle().pathForResource("LaunchImage_" + platform, ofType: "json") } // Unwrap the JSON file path. guard let path = resourcePath else { throw ContentsJSONError.FileNotFound } // Create a new NSData object from the contents of the selected JSON file. let JSONData = try NSData(contentsOfFile: path, options: .DataReadingMappedAlways) // Create a new JSON object from the given data. let JSONObject = try NSJSONSerialization.JSONObjectWithData(JSONData, options: .AllowFragments) // Convert the JSON object into a Dictionary. guard let contentsDict = JSONObject as? Dictionary<String, AnyObject> else { throw ContentsJSONError.CastingJSONToDictionaryFailed } // Get the image information from the JSON dictionary. guard let images = contentsDict["images"] as? Array<[String : String]> else { throw ContentsJSONError.GettingImagesArrayFailed } // Return image information. return images } /// Saves the Contents.json to the appropriate folder. /// /// - parameter url: File url to save the Contents.json to. mutating func saveToURL(url: NSURL) throws { // Add the image information to the contents dictionary. contents["images"] = images // Serialize the contents as JSON object. let data = try NSJSONSerialization.dataWithJSONObject(self.contents, options: .PrettyPrinted) // Write the JSON object to the HD. try data.writeToURL(url.URLByAppendingPathComponent("Contents.json", isDirectory: false), options: .DataWritingAtomic) } }
a70249b26924b50b1ab81c5cb43afeaf
34.122302
122
0.703195
false
false
false
false
shlyren/ONE-Swift
refs/heads/master
ONE_Swift/Classes/Main-主要/Controller/JENPastListViewController.swift
mit
1
// // JENPastListViewController.swift // ONE_Swift // // Created by 任玉祥 on 16/4/28. // Copyright © 2016年 任玉祥. All rights reserved. // import UIKit class JENPastListViewController: UITableViewController { var endMonth = "" var pastLists: [String] { get { return arrayFromStr(endMonth) } } override func viewDidLoad() { super.viewDidLoad() title = "往期列表" } private func arrayFromStr(endDate: String) -> [String] { if !endDate.containsString("-") {return []} let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM" var currentDate = formatter.stringFromDate(NSDate()) as NSString let currentYear = currentDate.integerValue let range = currentDate.rangeOfString("-") if range.location != NSNotFound { currentDate = currentDate.stringByReplacingCharactersInRange(NSMakeRange(0, range.location + range.length), withString: "") } let currentMonth = currentDate.integerValue var endDataStr = endDate as NSString let endYear = endDataStr.integerValue if range.location != NSNotFound { endDataStr = endDataStr.stringByReplacingCharactersInRange(NSMakeRange(0, range.location + range.length), withString: "") } let endMonth = endDataStr.integerValue var maxMonth = 0 var minMonth = 0 var monthArr = [String]() var resYear = currentYear while resYear >= endYear { maxMonth = resYear == currentYear ? currentMonth: 12; minMonth = resYear == endYear ? endMonth: 1; var resMonth = maxMonth while resMonth >= minMonth { monthArr.append(String(format: "%zd-%02d", arguments: [resYear, resMonth])) resMonth -= 1 } resYear -= 1 } // for var resYear = currentYear; resYear >= endYear; resYear -= 1 { // maxMonth = resYear == currentYear ? currentMonth: 12; // minMonth = resYear == endYear ? endMonth: 1; // // for var resMonth = maxMonth; resMonth >= minMonth; resMonth -= 1 { // monthArr.append(String(format: "%zd-%02d", arguments: [resYear, resMonth])) // } // } return monthArr } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { tableView.tableViewWithNoData(nil, rowCount: pastLists.count) return pastLists.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { tableView.tableViewSetExtraCellLineHidden() var cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier") if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: "reuseIdentifier") } if indexPath.row == 0 { cell?.textLabel?.text = "本月" } else { cell?.textLabel?.text = pastLists[indexPath.row] } return cell! } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
4654559f01cde6eb96e38cb93393226c
31.877358
135
0.588235
false
false
false
false
jonnguy/HSTracker
refs/heads/master
HSTracker/Logging/Parsers/TagChangeActions.swift
mit
1
// // TagChanceActions.swift // HSTracker // // Created by Benjamin Michotte on 9/03/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation struct TagChangeActions { func findAction(eventHandler: PowerEventHandler, tag: GameTag, id: Int, value: Int, prevValue: Int) -> (() -> Void)? { switch tag { case .zone: return { self.zoneChange(eventHandler: eventHandler, id: id, value: value, prevValue: prevValue) } case .playstate: return { self.playstateChange(eventHandler: eventHandler, id: id, value: value) } case .cardtype: return { self.cardTypeChange(eventHandler: eventHandler, id: id, value: value) } case .last_card_played: return { self.lastCardPlayedChange(eventHandler: eventHandler, value: value) } case .defending: return { self.defendingChange(eventHandler: eventHandler, id: id, value: value) } case .attacking: return { self.attackingChange(eventHandler: eventHandler, id: id, value: value) } case .proposed_defender: return { self.proposedDefenderChange(eventHandler: eventHandler, value: value) } case .proposed_attacker: return { self.proposedAttackerChange(eventHandler: eventHandler, value: value) } case .predamage: return { self.predamageChange(eventHandler: eventHandler, id: id, value: value) } case .num_turns_in_play: return { self.numTurnsInPlayChange(eventHandler: eventHandler, id: id, value: value) } case .num_attacks_this_turn: return { self.numAttacksThisTurnChange(eventHandler: eventHandler, id: id, value: value) } case .zone_position: return { self.zonePositionChange(eventHandler: eventHandler, id: id) } case .card_target: return { self.cardTargetChange(eventHandler: eventHandler, id: id, value: value) } //case .equipped_weapon: return { self.equippedWeaponChange(eventHandler: eventHandler, id: id, value: value) } case .exhausted: return { self.exhaustedChange(eventHandler: eventHandler, id: id, value: value) } case .controller: return { self.controllerChange(eventHandler: eventHandler, id: id, prevValue: prevValue, value: value) } case .fatigue: return { self.fatigueChange(eventHandler: eventHandler, value: value, id: id) } case .step: return { self.stepChange(eventHandler: eventHandler) } case .turn: return { self.turnChange(eventHandler: eventHandler) } case .state: return { self.stateChange(eventHandler: eventHandler, value: value) } case .transformed_from_card: return { self.transformedFromCardChange(eventHandler: eventHandler, id: id, value: value) } default: return nil } } private func transformedFromCardChange(eventHandler: PowerEventHandler, id: Int, value: Int) { if value == 0 { return } guard let entity = eventHandler.entities[id] else { return } entity.info.set(originalCardId: value) } private func lastCardPlayedChange(eventHandler: PowerEventHandler, value: Int) { eventHandler.lastCardPlayed = value guard let playerEntity = eventHandler.playerEntity else { return } guard playerEntity.isCurrentPlayer else { return } if let entity = eventHandler.entities[value] { if !entity.isMinion { return } // check if it is a magnet buff, rather than a minion if entity.has(tag: GameTag.modular) { let pos = entity.tags[GameTag.zone_position]! let neighbor = eventHandler.player.board.first(where: { $0.tags[GameTag.zone_position] == pos + 1 }) if neighbor?.card.race == Race.mechanical { return } } eventHandler.playerMinionPlayed(entity: entity) } } private func defendingChange(eventHandler: PowerEventHandler, id: Int, value: Int) { guard let entity = eventHandler.entities[id] else { return } eventHandler.defending(entity: value == 1 ? entity : nil) } private func attackingChange(eventHandler: PowerEventHandler, id: Int, value: Int) { guard let entity = eventHandler.entities[id] else { return } eventHandler.attacking(entity: value == 1 ? entity : nil) } private func proposedDefenderChange(eventHandler: PowerEventHandler, value: Int) { eventHandler.proposedDefenderEntityId = value } private func proposedAttackerChange(eventHandler: PowerEventHandler, value: Int) { eventHandler.proposedAttackerEntityId = value } private func predamageChange(eventHandler: PowerEventHandler, id: Int, value: Int) { guard value > 0 else { return } guard let playerEntity = eventHandler.playerEntity, let entity = eventHandler.entities[id] else { return } if playerEntity.isCurrentPlayer { eventHandler.opponentDamage(entity: entity) } } private func numTurnsInPlayChange(eventHandler: PowerEventHandler, id: Int, value: Int) { guard value > 0 else { return } guard let entity = eventHandler.entities[id] else { return } eventHandler.turnsInPlayChange(entity: entity, turn: eventHandler.turnNumber()) } private func fatigueChange(eventHandler: PowerEventHandler, value: Int, id: Int) { guard let entity = eventHandler.entities[id] else { return } let controller = entity[.controller] if controller == eventHandler.player.id { eventHandler.playerFatigue(value: value) } else if controller == eventHandler.opponent.id { eventHandler.opponentFatigue(value: value) } } private func controllerChange(eventHandler: PowerEventHandler, id: Int, prevValue: Int, value: Int) { guard let entity = eventHandler.entities[id] else { return } if prevValue <= 0 { entity.info.originalController = value return } guard !entity.has(tag: .player_id) else { return } if value == eventHandler.player.id { if entity.isInZone(zone: .secret) { eventHandler.opponentStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber()) } else if entity.isInZone(zone: .play) { eventHandler.opponentStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber()) } } else if value == eventHandler.opponent.id && prevValue != value { if entity.isInZone(zone: .secret) { eventHandler.playerStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber()) } else if entity.isInZone(zone: .play) { eventHandler.playerStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber()) } } } private func exhaustedChange(eventHandler: PowerEventHandler, id: Int, value: Int) { guard value > 0 else { return } guard let entity = eventHandler.entities[id] else { return } guard entity[.cardtype] == CardType.hero_power.rawValue else { return } } private func equippedWeaponChange(eventHandler: PowerEventHandler, id: Int, value: Int) { } private func cardTargetChange(eventHandler: PowerEventHandler, id: Int, value: Int) { } private func zonePositionChange(eventHandler: PowerEventHandler, id: Int) { } private func numAttacksThisTurnChange(eventHandler: PowerEventHandler, id: Int, value: Int) { } private func stateChange(eventHandler: PowerEventHandler, value: Int) { if value != State.complete.rawValue { return } eventHandler.gameEnd() eventHandler.gameEnded = true } private func turnChange(eventHandler: PowerEventHandler) { guard eventHandler.setupDone && eventHandler.playerEntity != nil else { return } guard let playerEntity = eventHandler.playerEntity else { return } let activePlayer: PlayerType = playerEntity.has(tag: .current_player) ? .player : .opponent if activePlayer == .player { eventHandler.playerUsedHeroPower = false } else { eventHandler.opponentUsedHeroPower = false } } private func stepChange(eventHandler: PowerEventHandler) { guard !eventHandler.setupDone && eventHandler.entities.first?.1.name == "GameEntity" else { return } logger.info("Game was already in progress.") eventHandler.wasInProgress = true } private func cardTypeChange(eventHandler: PowerEventHandler, id: Int, value: Int) { if value == CardType.hero.rawValue { setHeroAsync(eventHandler: eventHandler, id: id) } } private func playstateChange(eventHandler: PowerEventHandler, id: Int, value: Int) { if value == PlayState.conceded.rawValue { eventHandler.concede() } guard !eventHandler.gameEnded else { return } if let entity = eventHandler.entities[id], !entity.isPlayer(eventHandler: eventHandler) { return } if let value = PlayState(rawValue: value) { switch value { case .won: eventHandler.win() case .lost: eventHandler.loss() case .tied: eventHandler.tied() default: break } } } private func zoneChange(eventHandler: PowerEventHandler, id: Int, value: Int, prevValue: Int) { guard id > 3 else { return } guard let entity = eventHandler.entities[id] else { return } if entity.info.originalZone == nil { if prevValue != Zone.invalid.rawValue && prevValue != Zone.setaside.rawValue { entity.info.originalZone = Zone(rawValue: prevValue) } else if value != Zone.invalid.rawValue && value != Zone.setaside.rawValue { entity.info.originalZone = Zone(rawValue: value) } } let controller = entity[.controller] guard let zoneValue = Zone(rawValue: prevValue) else { return } switch zoneValue { case .deck: zoneChangeFromDeck(eventHandler: eventHandler, id: id, value: value, prevValue: prevValue, controller: controller, cardId: entity.cardId) case .hand: zoneChangeFromHand(eventHandler: eventHandler, id: id, value: value, prevValue: prevValue, controller: controller, cardId: entity.cardId) case .play: zoneChangeFromPlay(eventHandler: eventHandler, id: id, value: value, prevValue: prevValue, controller: controller, cardId: entity.cardId) case .secret: zoneChangeFromSecret(eventHandler: eventHandler, id: id, value: value, prevValue: prevValue, controller: controller, cardId: entity.cardId) case .invalid: let maxId = getMaxHeroPowerId(eventHandler: eventHandler) if !eventHandler.setupDone && (id <= maxId || eventHandler.gameEntity?[.step] == Step.invalid.rawValue && entity[.zone_position] < 5) { entity.info.originalZone = .deck simulateZoneChangesFromDeck(eventHandler: eventHandler, id: id, value: value, cardId: entity.cardId, maxId: maxId) } else { zoneChangeFromOther(eventHandler: eventHandler, id: id, rawValue: value, prevValue: prevValue, controller: controller, cardId: entity.cardId) } case .graveyard, .setaside, .removedfromgame: zoneChangeFromOther(eventHandler: eventHandler, id: id, rawValue: value, prevValue: prevValue, controller: controller, cardId: entity.cardId) } } // The last heropower is created after the last hero, therefore +1 private func getMaxHeroPowerId(eventHandler: PowerEventHandler) -> Int { return max(eventHandler.playerEntity?[.hero_entity] ?? 66, eventHandler.opponentEntity?[.hero_entity] ?? 66) + 1 } private func simulateZoneChangesFromDeck(eventHandler: PowerEventHandler, id: Int, value: Int, cardId: String?, maxId: Int) { if value == Zone.deck.rawValue { return } guard let entity = eventHandler.entities[id] else { return } if value == Zone.setaside.rawValue { entity.info.created = true return } if entity.isHero && !entity.isPlayableHero || entity.isHeroPower || entity.has(tag: .player_id) || entity[.cardtype] == CardType.game.rawValue || entity.has(tag: .creator) { return } zoneChangeFromDeck(eventHandler: eventHandler, id: id, value: Zone.hand.rawValue, prevValue: Zone.deck.rawValue, controller: entity[.controller], cardId: cardId) if value == Zone.hand.rawValue { return } zoneChangeFromHand(eventHandler: eventHandler, id: id, value: Zone.play.rawValue, prevValue: Zone.hand.rawValue, controller: entity[.controller], cardId: cardId) if value == Zone.play.rawValue { return } zoneChangeFromPlay(eventHandler: eventHandler, id: id, value: value, prevValue: Zone.play.rawValue, controller: entity[.controller], cardId: cardId) } private func zoneChangeFromOther(eventHandler: PowerEventHandler, id: Int, rawValue: Int, prevValue: Int, controller: Int, cardId: String?) { guard let value = Zone(rawValue: rawValue), let entity = eventHandler.entities[id] else { return } if entity.info.originalZone == .deck && rawValue != Zone.deck.rawValue { // This entity was moved from DECK to SETASIDE to HAND, e.g. by Tracking entity.info.discarded = false zoneChangeFromDeck(eventHandler: eventHandler, id: id, value: rawValue, prevValue: prevValue, controller: controller, cardId: cardId) return } entity.info.created = true switch value { case .play: if controller == eventHandler.player.id { eventHandler.playerCreateInPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } else if controller == eventHandler.opponent.id { eventHandler.opponentCreateInPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } case .deck: if controller == eventHandler.player.id { if eventHandler.joustReveals > 0 { break } eventHandler.playerGetToDeck(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } else if controller == eventHandler.opponent.id { if eventHandler.joustReveals > 0 { break } eventHandler.opponentGetToDeck(entity: entity, turn: eventHandler.turnNumber()) } case .hand: if controller == eventHandler.player.id { eventHandler.playerGet(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } else if controller == eventHandler.opponent.id { eventHandler.opponentGet(entity: entity, turn: eventHandler.turnNumber(), id: id) } case .secret: if controller == eventHandler.player.id { if let prevZone = Zone(rawValue: prevValue) { eventHandler.playerSecretPlayed(entity: entity, cardId: cardId, turn: eventHandler.turnNumber(), fromZone: prevZone) } } else if controller == eventHandler.opponent.id { if let prevZone = Zone(rawValue: prevValue) { eventHandler.opponentSecretPlayed(entity: entity, cardId: cardId, from: -1, turn: eventHandler.turnNumber(), fromZone: prevZone, otherId: id) } } case .setaside: if controller == eventHandler.player.id { eventHandler.playerCreateInSetAside(entity: entity, turn: eventHandler.turnNumber()) } else if controller == eventHandler.opponent.id { eventHandler.opponentCreateInSetAside(entity: entity, turn: eventHandler.turnNumber()) } default: break } } private func zoneChangeFromSecret(eventHandler: PowerEventHandler, id: Int, value: Int, prevValue: Int, controller: Int, cardId: String?) { guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return } switch zoneValue { case .secret, .graveyard: if controller == eventHandler.opponent.id { eventHandler.opponentSecretTrigger(entity: entity, cardId: cardId, turn: eventHandler.turnNumber(), otherId: id) } default: break } } private func zoneChangeFromPlay(eventHandler: PowerEventHandler, id: Int, value: Int, prevValue: Int, controller: Int, cardId: String?) { guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return } switch zoneValue { case .hand: if controller == eventHandler.player.id { eventHandler.playerBackToHand(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } else if controller == eventHandler.opponent.id { eventHandler.opponentPlayToHand(entity: entity, cardId: cardId, turn: eventHandler.turnNumber(), id: id) } case .deck: if controller == eventHandler.player.id { eventHandler.playerPlayToDeck(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } else if controller == eventHandler.opponent.id { eventHandler.opponentPlayToDeck(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } case .graveyard: if controller == eventHandler.player.id { eventHandler.playerPlayToGraveyard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber(), playersTurn: eventHandler.playerEntity?.isCurrentPlayer ?? false) } else if controller == eventHandler.opponent.id { eventHandler.opponentPlayToGraveyard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber(), playersTurn: eventHandler.playerEntity?.isCurrentPlayer ?? false) } case .removedfromgame, .setaside: if controller == eventHandler.player.id { eventHandler.playerRemoveFromPlay(entity: entity, turn: eventHandler.turnNumber()) } else if controller == eventHandler.opponent.id { eventHandler.opponentRemoveFromPlay(entity: entity, turn: eventHandler.turnNumber()) } case .play: break default: break } } private func zoneChangeFromHand(eventHandler: PowerEventHandler, id: Int, value: Int, prevValue: Int, controller: Int, cardId: String?) { guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return } switch zoneValue { case .play: if controller == eventHandler.player.id { eventHandler.playerPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } else if controller == eventHandler.opponent.id { eventHandler.opponentPlay(entity: entity, cardId: cardId, from: entity[.zone_position], turn: eventHandler.turnNumber()) } case .removedfromgame, .setaside, .graveyard: if controller == eventHandler.player.id { eventHandler.playerHandDiscard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } else if controller == eventHandler.opponent.id { eventHandler.opponentHandDiscard(entity: entity, cardId: cardId, from: entity[.zone_position], turn: eventHandler.turnNumber()) } case .secret: if controller == eventHandler.player.id { if let prevZone = Zone(rawValue: prevValue) { eventHandler.playerSecretPlayed(entity: entity, cardId: cardId, turn: eventHandler.turnNumber(), fromZone: prevZone) } } else if controller == eventHandler.opponent.id { if let prevZone = Zone(rawValue: prevValue) { eventHandler.opponentSecretPlayed(entity: entity, cardId: cardId, from: entity[.zone_position], turn: eventHandler.turnNumber(), fromZone: prevZone, otherId: id) } } case .deck: if controller == eventHandler.player.id { eventHandler.playerMulligan(entity: entity, cardId: cardId) } else if controller == eventHandler.opponent.id { eventHandler.opponentMulligan(entity: entity, from: entity[.zone_position]) } default: break } } private func zoneChangeFromDeck(eventHandler: PowerEventHandler, id: Int, value: Int, prevValue: Int, controller: Int, cardId: String?) { guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return } switch zoneValue { case .hand: if controller == eventHandler.player.id { eventHandler.playerDraw(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } else if controller == eventHandler.opponent.id { eventHandler.opponentDraw(entity: entity, turn: eventHandler.turnNumber()) } case .setaside, .removedfromgame: if !eventHandler.setupDone { entity.info.created = true return } if controller == eventHandler.player.id { if eventHandler.joustReveals > 0 { eventHandler.joustReveals -= 1 break } eventHandler.playerRemoveFromDeck(entity: entity, turn: eventHandler.turnNumber()) } else if controller == eventHandler.opponent.id { if eventHandler.joustReveals > 0 { eventHandler.joustReveals -= 1 break } eventHandler.opponentRemoveFromDeck(entity: entity, turn: eventHandler.turnNumber()) } case .graveyard: if controller == eventHandler.player.id { eventHandler.playerDeckDiscard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } else if controller == eventHandler.opponent.id { eventHandler.opponentDeckDiscard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } case .play: if controller == eventHandler.player.id { eventHandler.playerDeckToPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } else if controller == eventHandler.opponent.id { eventHandler.opponentDeckToPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber()) } case .secret: if controller == eventHandler.player.id { if let prevZone = Zone(rawValue: prevValue) { eventHandler.playerSecretPlayed(entity: entity, cardId: cardId, turn: eventHandler.turnNumber(), fromZone: prevZone) } } else if controller == eventHandler.opponent.id { if let prevZone = Zone(rawValue: prevValue) { eventHandler.opponentSecretPlayed(entity: entity, cardId: cardId, from: -1, turn: eventHandler.turnNumber(), fromZone: prevZone, otherId: id) } } default: break } } // TODO: this is essentially blocking the global queue! private func setHeroAsync(eventHandler: PowerEventHandler, id: Int) { logger.info("Found hero with id \(id) ") DispatchQueue.global().async { if eventHandler.playerEntity == nil { logger.info("Waiting for playerEntity") while eventHandler.playerEntity == nil { Thread.sleep(forTimeInterval: 0.1) } } if let playerEntity = eventHandler.playerEntity, let entity = eventHandler.entities[id] { logger.info("playerEntity found playerClass : " + "\(String(describing: eventHandler.player.playerClass)), " + "\(id) -> \(playerEntity[.hero_entity]) -> \(entity) ") if id == playerEntity[.hero_entity] { let cardId = entity.cardId DispatchQueue.main.async { eventHandler.set(playerHero: cardId) } return } } if eventHandler.opponentEntity == nil { logger.info("Waiting for opponentEntity") while eventHandler.opponentEntity == nil { Thread.sleep(forTimeInterval: 0.1) } } if let opponentEntity = eventHandler.opponentEntity, let entity = eventHandler.entities[id] { logger.info("opponentEntity found playerClass : " + "\(String(describing: eventHandler.opponent.playerClass))," + " \(id) -> \(opponentEntity[.hero_entity]) -> \(entity) ") if id == opponentEntity[.hero_entity] { let cardId = entity.cardId DispatchQueue.main.async { eventHandler.set(opponentHero: cardId) } return } } } } }
9f237f2607fb1a19946f758d8a48e9aa
44.897227
181
0.571104
false
false
false
false
featherweightlabs/FeatherweightRouter
refs/heads/master
Tests/CachedPresenterTests.swift
apache-2.0
1
import XCTest @testable import FeatherweightRouter class CachedPresenterTests: XCTestCase { typealias TestPresenter = Presenter<ViewController> class ViewController { init() {} } func testCreation() { var callCount = 0 let presenter: TestPresenter = cachedPresenter { () -> ViewController in callCount += 1 return ViewController() } XCTAssertEqual(callCount, 0) var x: ViewController! = presenter.presentable XCTAssertEqual(callCount, 1) var y: ViewController! = presenter.presentable XCTAssertEqual(callCount, 1) XCTAssert(x === y) x = nil y = nil x = presenter.presentable XCTAssertEqual(callCount, 2) y = presenter.presentable XCTAssertEqual(callCount, 2) XCTAssert(x === y) } }
55a2810ad8a05a83328108178e564806
23.166667
80
0.610345
false
true
false
false
hooman/swift
refs/heads/main
stdlib/public/core/Sequence.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that supplies the values of a sequence one at a time. /// /// The `IteratorProtocol` protocol is tightly linked with the `Sequence` /// protocol. Sequences provide access to their elements by creating an /// iterator, which keeps track of its iteration process and returns one /// element at a time as it advances through the sequence. /// /// Whenever you use a `for`-`in` loop with an array, set, or any other /// collection or sequence, you're using that type's iterator. Swift uses a /// sequence's or collection's iterator internally to enable the `for`-`in` /// loop language construct. /// /// Using a sequence's iterator directly gives you access to the same elements /// in the same order as iterating over that sequence using a `for`-`in` loop. /// For example, you might typically use a `for`-`in` loop to print each of /// the elements in an array. /// /// let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"] /// for animal in animals { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// Behind the scenes, Swift uses the `animals` array's iterator to loop over /// the contents of the array. /// /// var animalIterator = animals.makeIterator() /// while let animal = animalIterator.next() { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// The call to `animals.makeIterator()` returns an instance of the array's /// iterator. Next, the `while` loop calls the iterator's `next()` method /// repeatedly, binding each element that is returned to `animal` and exiting /// when the `next()` method returns `nil`. /// /// Using Iterators Directly /// ======================== /// /// You rarely need to use iterators directly, because a `for`-`in` loop is the /// more idiomatic approach to traversing a sequence in Swift. Some /// algorithms, however, may call for direct iterator use. /// /// One example is the `reduce1(_:)` method. Similar to the `reduce(_:_:)` /// method defined in the standard library, which takes an initial value and a /// combining closure, `reduce1(_:)` uses the first element of the sequence as /// the initial value. /// /// Here's an implementation of the `reduce1(_:)` method. The sequence's /// iterator is used directly to retrieve the initial value before looping /// over the rest of the sequence. /// /// extension Sequence { /// func reduce1( /// _ nextPartialResult: (Element, Element) -> Element /// ) -> Element? /// { /// var i = makeIterator() /// guard var accumulated = i.next() else { /// return nil /// } /// /// while let element = i.next() { /// accumulated = nextPartialResult(accumulated, element) /// } /// return accumulated /// } /// } /// /// The `reduce1(_:)` method makes certain kinds of sequence operations /// simpler. Here's how to find the longest string in a sequence, using the /// `animals` array introduced earlier as an example: /// /// let longestAnimal = animals.reduce1 { current, element in /// if current.count > element.count { /// return current /// } else { /// return element /// } /// } /// print(longestAnimal) /// // Prints Optional("Butterfly") /// /// Using Multiple Iterators /// ======================== /// /// Whenever you use multiple iterators (or `for`-`in` loops) over a single /// sequence, be sure you know that the specific sequence supports repeated /// iteration, either because you know its concrete type or because the /// sequence is also constrained to the `Collection` protocol. /// /// Obtain each separate iterator from separate calls to the sequence's /// `makeIterator()` method rather than by copying. Copying an iterator is /// safe, but advancing one copy of an iterator by calling its `next()` method /// may invalidate other copies of that iterator. `for`-`in` loops are safe in /// this regard. /// /// Adding IteratorProtocol Conformance to Your Type /// ================================================ /// /// Implementing an iterator that conforms to `IteratorProtocol` is simple. /// Declare a `next()` method that advances one step in the related sequence /// and returns the current element. When the sequence has been exhausted, the /// `next()` method returns `nil`. /// /// For example, consider a custom `Countdown` sequence. You can initialize the /// `Countdown` sequence with a starting integer and then iterate over the /// count down to zero. The `Countdown` structure's definition is short: It /// contains only the starting count and the `makeIterator()` method required /// by the `Sequence` protocol. /// /// struct Countdown: Sequence { /// let start: Int /// /// func makeIterator() -> CountdownIterator { /// return CountdownIterator(self) /// } /// } /// /// The `makeIterator()` method returns another custom type, an iterator named /// `CountdownIterator`. The `CountdownIterator` type keeps track of both the /// `Countdown` sequence that it's iterating and the number of times it has /// returned a value. /// /// struct CountdownIterator: IteratorProtocol { /// let countdown: Countdown /// var times = 0 /// /// init(_ countdown: Countdown) { /// self.countdown = countdown /// } /// /// mutating func next() -> Int? { /// let nextNumber = countdown.start - times /// guard nextNumber > 0 /// else { return nil } /// /// times += 1 /// return nextNumber /// } /// } /// /// Each time the `next()` method is called on a `CountdownIterator` instance, /// it calculates the new next value, checks to see whether it has reached /// zero, and then returns either the number, or `nil` if the iterator is /// finished returning elements of the sequence. /// /// Creating and iterating over a `Countdown` sequence uses a /// `CountdownIterator` to handle the iteration. /// /// let threeTwoOne = Countdown(start: 3) /// for count in threeTwoOne { /// print("\(count)...") /// } /// // Prints "3..." /// // Prints "2..." /// // Prints "1..." public protocol IteratorProtocol { /// The type of element traversed by the iterator. associatedtype Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Repeatedly calling this method returns, in order, all the elements of the /// underlying sequence. As soon as the sequence has run out of elements, all /// subsequent calls return `nil`. /// /// You must not call this method if any other copy of this iterator has been /// advanced with a call to its `next()` method. /// /// The following example shows how an iterator can be used explicitly to /// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and /// then call the iterator's `next()` method until it returns `nil`. /// /// let numbers = [2, 3, 5, 7] /// var numbersIterator = numbers.makeIterator() /// /// while let num = numbersIterator.next() { /// print(num) /// } /// // Prints "2" /// // Prints "3" /// // Prints "5" /// // Prints "7" /// /// - Returns: The next element in the underlying sequence, if a next element /// exists; otherwise, `nil`. mutating func next() -> Element? } /// A type that provides sequential, iterated access to its elements. /// /// A sequence is a list of values that you can step through one at a time. The /// most common way to iterate over the elements of a sequence is to use a /// `for`-`in` loop: /// /// let oneTwoThree = 1...3 /// for number in oneTwoThree { /// print(number) /// } /// // Prints "1" /// // Prints "2" /// // Prints "3" /// /// While seemingly simple, this capability gives you access to a large number /// of operations that you can perform on any sequence. As an example, to /// check whether a sequence includes a particular value, you can test each /// value sequentially until you've found a match or reached the end of the /// sequence. This example checks to see whether a particular insect is in an /// array. /// /// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// var hasMosquito = false /// for bug in bugs { /// if bug == "Mosquito" { /// hasMosquito = true /// break /// } /// } /// print("'bugs' has a mosquito: \(hasMosquito)") /// // Prints "'bugs' has a mosquito: false" /// /// The `Sequence` protocol provides default implementations for many common /// operations that depend on sequential access to a sequence's values. For /// clearer, more concise code, the example above could use the array's /// `contains(_:)` method, which every sequence inherits from `Sequence`, /// instead of iterating manually: /// /// if bugs.contains("Mosquito") { /// print("Break out the bug spray.") /// } else { /// print("Whew, no mosquitos!") /// } /// // Prints "Whew, no mosquitos!" /// /// Repeated Access /// =============== /// /// The `Sequence` protocol makes no requirement on conforming types regarding /// whether they will be destructively consumed by iteration. As a /// consequence, don't assume that multiple `for`-`in` loops on a sequence /// will either resume iteration or restart from the beginning: /// /// for element in sequence { /// if ... some condition { break } /// } /// /// for element in sequence { /// // No defined behavior /// } /// /// In this case, you cannot assume either that a sequence will be consumable /// and will resume iteration, or that a sequence is a collection and will /// restart iteration from the first element. A conforming sequence that is /// not a collection is allowed to produce an arbitrary sequence of elements /// in the second `for`-`in` loop. /// /// To establish that a type you've created supports nondestructive iteration, /// add conformance to the `Collection` protocol. /// /// Conforming to the Sequence Protocol /// =================================== /// /// Making your own custom types conform to `Sequence` enables many useful /// operations, like `for`-`in` looping and the `contains` method, without /// much effort. To add `Sequence` conformance to your own custom type, add a /// `makeIterator()` method that returns an iterator. /// /// Alternatively, if your type can act as its own iterator, implementing the /// requirements of the `IteratorProtocol` protocol and declaring conformance /// to both `Sequence` and `IteratorProtocol` are sufficient. /// /// Here's a definition of a `Countdown` sequence that serves as its own /// iterator. The `makeIterator()` method is provided as a default /// implementation. /// /// struct Countdown: Sequence, IteratorProtocol { /// var count: Int /// /// mutating func next() -> Int? { /// if count == 0 { /// return nil /// } else { /// defer { count -= 1 } /// return count /// } /// } /// } /// /// let threeToGo = Countdown(count: 3) /// for i in threeToGo { /// print(i) /// } /// // Prints "3" /// // Prints "2" /// // Prints "1" /// /// Expected Performance /// ==================== /// /// A sequence should provide its iterator in O(1). The `Sequence` protocol /// makes no other requirements about element access, so routines that /// traverse a sequence should be considered O(*n*) unless documented /// otherwise. public protocol Sequence { /// A type representing the sequence's elements. associatedtype Element /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. associatedtype Iterator: IteratorProtocol where Iterator.Element == Element /// A type that represents a subsequence of some of the sequence's elements. // associatedtype SubSequence: Sequence = AnySequence<Element> // where Element == SubSequence.Element, // SubSequence.SubSequence == SubSequence // typealias SubSequence = AnySequence<Element> /// Returns an iterator over the elements of this sequence. __consuming func makeIterator() -> Iterator /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// The default implementation returns 0. If you provide your own /// implementation, make sure to compute the value nondestructively. /// /// - Complexity: O(1), except if the sequence also conforms to `Collection`. /// In this case, see the documentation of `Collection.underestimatedCount`. var underestimatedCount: Int { get } func _customContainsEquatableElement( _ element: Element ) -> Bool? /// Create a native array buffer containing the elements of `self`, /// in the same order. __consuming func _copyToContiguousArray() -> ContiguousArray<Element> /// Copy `self` into an unsafe buffer, initializing its memory. /// /// The default implementation simply iterates over the elements of the /// sequence, initializing the buffer one item at a time. /// /// For sequences whose elements are stored in contiguous chunks of memory, /// it may be more efficient to copy them in bulk, using the /// `UnsafeMutablePointer.initialize(from:count:)` method. /// /// - Parameter ptr: An unsafe buffer addressing uninitialized memory. The /// buffer must be of sufficient size to accommodate /// `source.underestimatedCount` elements. (Some implementations trap /// if given a buffer that's smaller than this.) /// /// - Returns: `(it, c)`, where `c` is the number of elements copied into the /// buffer, and `it` is a partially consumed iterator that can be used to /// retrieve elements that did not fit into the buffer (if any). (This can /// only happen if `underestimatedCount` turned out to be an actual /// underestimate, and the buffer did not contain enough space to hold the /// entire sequence.) /// /// On return, the memory region in `buffer[0 ..< c]` is initialized to /// the first `c` elements in the sequence. __consuming func _copyContents( initializing ptr: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) /// Call `body(p)`, where `p` is a pointer to the collection's /// contiguous storage. If no such storage exists, it is /// first created. If the collection does not support an internal /// representation in a form of contiguous storage, `body` is not /// called and `nil` is returned. /// /// A `Collection` that provides its own implementation of this method /// must also guarantee that an equivalent buffer of its `SubSequence` /// can be generated by advancing the pointer by the distance to the /// slice's `startIndex`. func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? } // Provides a default associated type witness for Iterator when the // Self type is both a Sequence and an Iterator. extension Sequence where Self: IteratorProtocol { // @_implements(Sequence, Iterator) public typealias _Default_Iterator = Self } /// A default makeIterator() function for `IteratorProtocol` instances that /// are declared to conform to `Sequence` extension Sequence where Self.Iterator == Self { /// Returns an iterator over the elements of this sequence. @inlinable public __consuming func makeIterator() -> Self { return self } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. @frozen public struct DropFirstSequence<Base: Sequence> { @usableFromInline internal let _base: Base @usableFromInline internal let _limit: Int @inlinable public init(_ base: Base, dropping limit: Int) { _precondition(limit >= 0, "Can't drop a negative number of elements from a sequence") _base = base _limit = limit } } extension DropFirstSequence: Sequence { public typealias Element = Base.Element public typealias Iterator = Base.Iterator public typealias SubSequence = AnySequence<Element> @inlinable public __consuming func makeIterator() -> Iterator { var it = _base.makeIterator() var dropped = 0 while dropped < _limit, it.next() != nil { dropped &+= 1 } return it } @inlinable public __consuming func dropFirst(_ k: Int) -> DropFirstSequence<Base> { // If this is already a _DropFirstSequence, we need to fold in // the current drop count and drop limit so no data is lost. // // i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to // [1,2,3,4].dropFirst(2). return DropFirstSequence(_base, dropping: _limit + k) } } /// A sequence that only consumes up to `n` elements from an underlying /// `Base` iterator. /// /// The underlying iterator's sequence may be infinite. @frozen public struct PrefixSequence<Base: Sequence> { @usableFromInline internal var _base: Base @usableFromInline internal let _maxLength: Int @inlinable public init(_ base: Base, maxLength: Int) { _precondition(maxLength >= 0, "Can't take a prefix of negative length") _base = base _maxLength = maxLength } } extension PrefixSequence { @frozen public struct Iterator { @usableFromInline internal var _base: Base.Iterator @usableFromInline internal var _remaining: Int @inlinable internal init(_ base: Base.Iterator, maxLength: Int) { _base = base _remaining = maxLength } } } extension PrefixSequence.Iterator: IteratorProtocol { public typealias Element = Base.Element @inlinable public mutating func next() -> Element? { if _remaining != 0 { _remaining &-= 1 return _base.next() } else { return nil } } } extension PrefixSequence: Sequence { @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_base.makeIterator(), maxLength: _maxLength) } @inlinable public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Base> { let length = Swift.min(maxLength, self._maxLength) return PrefixSequence(_base, maxLength: length) } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. @frozen public struct DropWhileSequence<Base: Sequence> { public typealias Element = Base.Element @usableFromInline internal var _iterator: Base.Iterator @usableFromInline internal var _nextElement: Element? @inlinable internal init(iterator: Base.Iterator, predicate: (Element) throws -> Bool) rethrows { _iterator = iterator _nextElement = _iterator.next() while let x = _nextElement, try predicate(x) { _nextElement = _iterator.next() } } @inlinable internal init(_ base: Base, predicate: (Element) throws -> Bool) rethrows { self = try DropWhileSequence(iterator: base.makeIterator(), predicate: predicate) } } extension DropWhileSequence { @frozen public struct Iterator { @usableFromInline internal var _iterator: Base.Iterator @usableFromInline internal var _nextElement: Element? @inlinable internal init(_ iterator: Base.Iterator, nextElement: Element?) { _iterator = iterator _nextElement = nextElement } } } extension DropWhileSequence.Iterator: IteratorProtocol { public typealias Element = Base.Element @inlinable public mutating func next() -> Element? { guard let next = _nextElement else { return nil } _nextElement = _iterator.next() return next } } extension DropWhileSequence: Sequence { @inlinable public func makeIterator() -> Iterator { return Iterator(_iterator, nextElement: _nextElement) } @inlinable public __consuming func drop( while predicate: (Element) throws -> Bool ) rethrows -> DropWhileSequence<Base> { guard let x = _nextElement, try predicate(x) else { return self } return try DropWhileSequence(iterator: _iterator, predicate: predicate) } } //===----------------------------------------------------------------------===// // Default implementations for Sequence //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercased() } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func map<T>( _ transform: (Element) throws -> T ) rethrows -> [T] { let initialCapacity = underestimatedCount var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity) var iterator = self.makeIterator() // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { result.append(try transform(iterator.next()!)) } // Add remaining elements, if any. while let element = iterator.next() { result.append(try transform(element)) } return Array(result) } /// Returns an array containing, in order, the elements of the sequence /// that satisfy the given predicate. /// /// In this example, `filter(_:)` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `isIncluded` allowed. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] { return try _filter(isIncluded) } @_transparent public func _filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] { var result = ContiguousArray<Element>() var iterator = self.makeIterator() while let element = iterator.next() { if try isIncluded(element) { result.append(element) } } return Array(result) } /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// The default implementation returns 0. If you provide your own /// implementation, make sure to compute the value nondestructively. /// /// - Complexity: O(1), except if the sequence also conforms to `Collection`. /// In this case, see the documentation of `Collection.underestimatedCount`. @inlinable public var underestimatedCount: Int { return 0 } @inlinable @inline(__always) public func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? { return nil } /// Calls the given closure on each element in the sequence in the same order /// as a `for`-`in` loop. /// /// The two loops in the following example produce the same output: /// /// let numberWords = ["one", "two", "three"] /// for word in numberWords { /// print(word) /// } /// // Prints "one" /// // Prints "two" /// // Prints "three" /// /// numberWords.forEach { word in /// print(word) /// } /// // Same as above /// /// Using the `forEach` method is distinct from a `for`-`in` loop in two /// important ways: /// /// 1. You cannot use a `break` or `continue` statement to exit the current /// call of the `body` closure or skip subsequent calls. /// 2. Using the `return` statement in the `body` closure will exit only from /// the current call to `body`, not from any outer scope, and won't skip /// subsequent calls. /// /// - Parameter body: A closure that takes an element of the sequence as a /// parameter. @_semantics("sequence.forEach") @inlinable public func forEach( _ body: (Element) throws -> Void ) rethrows { for element in self { try body(element) } } } extension Sequence { /// Returns the first element of the sequence that satisfies the given /// predicate. /// /// The following example uses the `first(where:)` method to find the first /// negative number in an array of integers: /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// if let firstNegative = numbers.first(where: { $0 < 0 }) { /// print("The first negative number is \(firstNegative).") /// } /// // Prints "The first negative number is -2." /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element is a match. /// - Returns: The first element of the sequence that satisfies `predicate`, /// or `nil` if there is no element that satisfies `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func first( where predicate: (Element) throws -> Bool ) rethrows -> Element? { for element in self { if try predicate(element) { return element } } return nil } } extension Sequence where Element: Equatable { /// Returns the longest possible subsequences of the sequence, in order, /// around elements equal to the given element. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string at each /// space character (" "). The first use of `split` returns each word that /// was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(separator: " ") /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print(line.split(separator: " ", maxSplits: 1) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.split(separator: " ", omittingEmptySubsequences: false) /// .map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - separator: The element that should be split upon. /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each consecutive pair of `separator` /// elements in the sequence and for each instance of `separator` at the /// start or end of the sequence. If `true`, only nonempty subsequences /// are returned. The default value is `true`. /// - Returns: An array of subsequences, split from this sequence's elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func split( separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true ) -> [ArraySlice<Element>] { return split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: { $0 == separator }) } } extension Sequence { /// Returns the longest possible subsequences of the sequence, in order, that /// don't contain elements satisfying the given predicate. Elements that are /// used to split the sequence are not returned as part of any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.split(maxSplits: 1, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `true` for the `allowEmptySlices` parameter, so /// the returned array contains empty strings where spaces were repeated. /// /// print( /// line.split( /// omittingEmptySubsequences: false, /// whereSeparator: { $0 == " " } /// ).map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - isSeparator: A closure that returns `true` if its argument should be /// used to split the sequence; otherwise, `false`. /// - Returns: An array of subsequences, split from this sequence's elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Element) throws -> Bool ) rethrows -> [ArraySlice<Element>] { _precondition(maxSplits >= 0, "Must take zero or more splits") let whole = Array(self) return try whole.split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: isSeparator) } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the sequence. /// /// The sequence must be finite. If the maximum length exceeds the number of /// elements in the sequence, the result contains all the elements in the /// sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func suffix(_ maxLength: Int) -> [Element] { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence") guard maxLength != 0 else { return [] } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements into a ring buffer to save space. Once all // elements are consumed, reorder the ring buffer into a copy and return it. // This saves memory for sequences particularly longer than `maxLength`. var ringBuffer = ContiguousArray<Element>() ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount)) var i = 0 for element in self { if ringBuffer.count < maxLength { ringBuffer.append(element) } else { ringBuffer[i] = element i = (i + 1) % maxLength } } if i != ringBuffer.startIndex { var rotated = ContiguousArray<Element>() rotated.reserveCapacity(ringBuffer.count) rotated += ringBuffer[i..<ringBuffer.endIndex] rotated += ringBuffer[0..<i] return Array(rotated) } else { return Array(ringBuffer) } } /// Returns a sequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter k: The number of elements to drop from the beginning of /// the sequence. `k` must be greater than or equal to zero. /// - Returns: A sequence starting after the specified number of /// elements. /// /// - Complexity: O(1), with O(*k*) deferred to each iteration of the result, /// where *k* is the number of elements to drop from the beginning of /// the sequence. @inlinable public __consuming func dropFirst(_ k: Int = 1) -> DropFirstSequence<Self> { return DropFirstSequence(self, dropping: k) } /// Returns a sequence containing all but the given number of final /// elements. /// /// The sequence must be finite. If the number of elements to drop exceeds /// the number of elements in the sequence, the result is an empty /// sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// sequence. `n` must be greater than or equal to zero. /// - Returns: A sequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func dropLast(_ k: Int = 1) -> [Element] { _precondition(k >= 0, "Can't drop a negative number of elements from a sequence") guard k != 0 else { return Array(self) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements from this sequence in a holding tank, a ring buffer // of size <= k. If more elements keep coming in, pull them out of the // holding tank into the result, an `Array`. This saves // `k` * sizeof(Element) of memory, because slices keep the entire // memory of an `Array` alive. var result = ContiguousArray<Element>() var ringBuffer = ContiguousArray<Element>() var i = ringBuffer.startIndex for element in self { if ringBuffer.count < k { ringBuffer.append(element) } else { result.append(ringBuffer[i]) ringBuffer[i] = element i = (i + 1) % k } } return Array(result) } /// Returns a sequence by skipping the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `drop(while:)` method to skip over the /// positive numbers at the beginning of the `numbers` array. The result /// begins with the first element of `numbers` that does not satisfy /// `predicate`. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let startingWithNegative = numbers.drop(while: { $0 > 0 }) /// // startingWithNegative == [-2, 9, -6, 10, 1] /// /// If `predicate` matches every element in the sequence, the result is an /// empty sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A sequence starting after the initial, consecutive elements /// that satisfy `predicate`. /// /// - Complexity: O(*k*), where *k* is the number of elements to drop from /// the beginning of the sequence. @inlinable public __consuming func drop( while predicate: (Element) throws -> Bool ) rethrows -> DropWhileSequence<Self> { return try DropWhileSequence(self, predicate: predicate) } /// Returns a sequence, up to the specified maximum length, containing the /// initial elements of the sequence. /// /// If the maximum length exceeds the number of elements in the sequence, /// the result contains all the elements in the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A sequence starting at the beginning of this sequence /// with at most `maxLength` elements. /// /// - Complexity: O(1) @inlinable public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Self> { return PrefixSequence(self, maxLength: maxLength) } /// Returns a sequence containing the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `prefix(while:)` method to find the /// positive numbers at the beginning of the `numbers` array. Every element /// of `numbers` up to, but not including, the first negative value is /// included in the result. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let positivePrefix = numbers.prefix(while: { $0 > 0 }) /// // positivePrefix == [3, 7, 4] /// /// If `predicate` matches every element in the sequence, the resulting /// sequence contains every element of the sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A sequence of the initial, consecutive elements that /// satisfy `predicate`. /// /// - Complexity: O(*k*), where *k* is the length of the result. @inlinable public __consuming func prefix( while predicate: (Element) throws -> Bool ) rethrows -> [Element] { var result = ContiguousArray<Element>() for element in self { guard try predicate(element) else { break } result.append(element) } return Array(result) } } extension Sequence { /// Copy `self` into an unsafe buffer, initializing its memory. /// /// The default implementation simply iterates over the elements of the /// sequence, initializing the buffer one item at a time. /// /// For sequences whose elements are stored in contiguous chunks of memory, /// it may be more efficient to copy them in bulk, using the /// `UnsafeMutablePointer.initialize(from:count:)` method. /// /// - Parameter ptr: An unsafe buffer addressing uninitialized memory. The /// buffer must be of sufficient size to accommodate /// `source.underestimatedCount` elements. (Some implementations trap /// if given a buffer that's smaller than this.) /// /// - Returns: `(it, c)`, where `c` is the number of elements copied into the /// buffer, and `it` is a partially consumed iterator that can be used to /// retrieve elements that did not fit into the buffer (if any). (This can /// only happen if `underestimatedCount` turned out to be an actual /// underestimate, and the buffer did not contain enough space to hold the /// entire sequence.) /// /// On return, the memory region in `buffer[0 ..< c]` is initialized to /// the first `c` elements in the sequence. @inlinable public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { return _copySequenceContents(initializing: buffer) } @_alwaysEmitIntoClient internal __consuming func _copySequenceContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { var it = self.makeIterator() guard var ptr = buffer.baseAddress else { return (it,buffer.startIndex) } for idx in buffer.startIndex..<buffer.count { guard let x = it.next() else { return (it, idx) } ptr.initialize(to: x) ptr += 1 } return (it,buffer.endIndex) } @inlinable public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { return nil } } // FIXME(ABI)#182 // Pending <rdar://problem/14011860> and <rdar://problem/14396120>, // pass an IteratorProtocol through IteratorSequence to give it "Sequence-ness" /// A sequence built around an iterator of type `Base`. /// /// Useful mostly to recover the ability to use `for`...`in`, /// given just an iterator `i`: /// /// for x in IteratorSequence(i) { ... } @frozen public struct IteratorSequence<Base: IteratorProtocol> { @usableFromInline internal var _base: Base /// Creates an instance whose iterator is a copy of `base`. @inlinable public init(_ base: Base) { _base = base } } extension IteratorSequence: IteratorProtocol, Sequence { /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. @inlinable public mutating func next() -> Base.Element? { return _base.next() } } extension IteratorSequence: Sendable where Base: Sendable { } /* FIXME: ideally for compatibility we would declare extension Sequence { @available(swift, deprecated: 5, message: "") public typealias SubSequence = AnySequence<Element> } */
17943a0da206d1d4997d31825582cae0
36.060181
100
0.6409
false
false
false
false
nodes-ios/Blobfish
refs/heads/master
Blobfish/Classes/Reachability.swift
mit
1
/* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Reachability.swift version 2.2beta2 import SystemConfiguration import Foundation public enum ReachabilityError: ErrorProtocol { case FailedToCreateWithAddress(sockaddr_in) case FailedToCreateWithHostname(String) case UnableToSetCallback case UnableToSetDispatchQueue } public let ReachabilityChangedNotification = "ReachabilityChangedNotification" as NSNotification.Name func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutablePointer<Void>?) { guard let info = info else { return } let reachability = Unmanaged<Reachability>.fromOpaque(OpaquePointer(info)).takeUnretainedValue() DispatchQueue.main.async { reachability.reachabilityChanged(flags:flags) } } public class Reachability: NSObject { public typealias NetworkReachable = (Reachability) -> () public typealias NetworkUnreachable = (Reachability) -> () public enum NetworkStatus: CustomStringConvertible { case NotReachable, ReachableViaWiFi, ReachableViaWWAN public var description: String { switch self { case .ReachableViaWWAN: return "Cellular" case .ReachableViaWiFi: return "WiFi" case .NotReachable: return "No Connection" } } } // MARK: - *** Public properties *** public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? public var reachableOnWWAN: Bool public var notificationCenter = NotificationCenter.default public var currentReachabilityStatus: NetworkStatus { if isReachable() { if isReachableViaWiFi() { return .ReachableViaWiFi } if isRunningOnDevice { return .ReachableViaWWAN } } return .NotReachable } public var currentReachabilityString: String { return "\(currentReachabilityStatus)" } private var previousFlags: SCNetworkReachabilityFlags? // MARK: - *** Initialisation methods *** required public init(reachabilityRef: SCNetworkReachability) { reachableOnWWAN = true self.reachabilityRef = reachabilityRef } public convenience init(hostname: String) throws { guard let nodename = (hostname as NSString).utf8String, ref = SCNetworkReachabilityCreateWithName(nil, nodename) else { throw ReachabilityError.FailedToCreateWithHostname(hostname) } self.init(reachabilityRef: ref) } public class func reachabilityForInternetConnection() throws -> Reachability { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let ref = withUnsafePointer(&zeroAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { throw ReachabilityError.FailedToCreateWithAddress(zeroAddress) } return Reachability(reachabilityRef: ref) } public class func reachabilityForLocalWiFi() throws -> Reachability { var localWifiAddress: sockaddr_in = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) localWifiAddress.sin_len = UInt8(sizeofValue(localWifiAddress)) localWifiAddress.sin_family = sa_family_t(AF_INET) // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0 let address: UInt32 = 0xA9FE0000 localWifiAddress.sin_addr.s_addr = in_addr_t(address.bigEndian) guard let ref = withUnsafePointer(&localWifiAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { throw ReachabilityError.FailedToCreateWithAddress(localWifiAddress) } return Reachability(reachabilityRef: ref) } // MARK: - *** Notifier methods *** public func startNotifier() throws { guard let reachabilityRef = reachabilityRef where !notifierRunning else { return } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutablePointer<Void>(OpaquePointer(bitPattern: Unmanaged<Reachability>.passUnretained(self))) if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) { stopNotifier() throw ReachabilityError.UnableToSetCallback } if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) { stopNotifier() throw ReachabilityError.UnableToSetDispatchQueue } // Perform an intial check reachabilitySerialQueue.async { let flags = self.reachabilityFlags self.reachabilityChanged(flags: flags) } notifierRunning = true } public func stopNotifier() { defer { notifierRunning = false } guard let reachabilityRef = reachabilityRef else { return } SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } // MARK: - *** Connection test methods *** public func isReachable() -> Bool { let flags = reachabilityFlags return isReachableWithFlags(flags:flags) } public func isReachableViaWWAN() -> Bool { let flags = reachabilityFlags // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return isRunningOnDevice && isReachable(flags:flags) && isOnWWAN(flags:flags) } public func isReachableViaWiFi() -> Bool { let flags = reachabilityFlags // Check we're reachable if !isReachable(flags:flags) { return false } // Must be on WiFi if reachable but not on an iOS device (i.e. simulator) if !isRunningOnDevice { return true } // Check we're NOT on WWAN return !isOnWWAN(flags:flags) } // MARK: - *** Private methods *** private var isRunningOnDevice: Bool = { #if (arch(i386) || arch(x86_64)) && os(iOS) return false #else return true #endif }() private var notifierRunning = false private var reachabilityRef: SCNetworkReachability? private let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", attributes: .serial, target: nil) private func reachabilityChanged(flags:SCNetworkReachabilityFlags) { guard previousFlags != flags else { return } if isReachableWithFlags(flags:flags) { if let block = whenReachable { block(self) } } else { if let block = whenUnreachable { block(self) } } notificationCenter.post(name: ReachabilityChangedNotification, object:self) previousFlags = flags } private func isReachableWithFlags(flags:SCNetworkReachabilityFlags) -> Bool { if !isReachable(flags: flags) { return false } if isConnectionRequiredOrTransient(flags: flags) { return false } if isRunningOnDevice { if isOnWWAN(flags: flags) && !reachableOnWWAN { // We don't want to connect when on 3G. return false } } return true } // WWAN may be available, but not active until a connection has been established. // WiFi may require a connection for VPN on Demand. private func isConnectionRequired() -> Bool { return connectionRequired() } private func connectionRequired() -> Bool { let flags = reachabilityFlags return isConnectionRequired(flags: flags) } // Dynamic, on demand connection? private func isConnectionOnDemand() -> Bool { let flags = reachabilityFlags return isConnectionRequired(flags: flags) && isConnectionOnTrafficOrDemand(flags: flags) } // Is user intervention required? private func isInterventionRequired() -> Bool { let flags = reachabilityFlags return isConnectionRequired(flags: flags) && isInterventionRequired(flags: flags) } private func isOnWWAN(flags:SCNetworkReachabilityFlags) -> Bool { #if os(iOS) return flags.contains(.iswwan) #else return false #endif } private func isReachable(flags:SCNetworkReachabilityFlags) -> Bool { return flags.contains(.reachable) } private func isConnectionRequired(flags:SCNetworkReachabilityFlags) -> Bool { return flags.contains(.connectionRequired) } private func isInterventionRequired(flags:SCNetworkReachabilityFlags) -> Bool { return flags.contains(.interventionRequired) } private func isConnectionOnTraffic(flags:SCNetworkReachabilityFlags) -> Bool { return flags.contains(.connectionOnTraffic) } private func isConnectionOnDemand(flags:SCNetworkReachabilityFlags) -> Bool { return flags.contains(.connectionOnDemand) } func isConnectionOnTrafficOrDemand(flags:SCNetworkReachabilityFlags) -> Bool { return !flags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty } private func isTransientConnection(flags:SCNetworkReachabilityFlags) -> Bool { return flags.contains(.transientConnection) } private func isLocalAddress(flags:SCNetworkReachabilityFlags) -> Bool { return flags.contains(.isLocalAddress) } private func isDirect(flags:SCNetworkReachabilityFlags) -> Bool { return flags.contains(.isDirect) } private func isConnectionRequiredOrTransient(flags:SCNetworkReachabilityFlags) -> Bool { let testcase:SCNetworkReachabilityFlags = [.connectionRequired, .transientConnection] return flags.intersection(testcase) == testcase } private var reachabilityFlags: SCNetworkReachabilityFlags { guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() } var flags = SCNetworkReachabilityFlags() let gotFlags = withUnsafeMutablePointer(&flags) { SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0)) } if gotFlags { return flags } else { return SCNetworkReachabilityFlags() } } override public var description: String { var W: String if isRunningOnDevice { W = isOnWWAN(flags: reachabilityFlags) ? "W" : "-" } else { W = "X" } let R = isReachable(flags: reachabilityFlags) ? "R" : "-" let c = isConnectionRequired(flags: reachabilityFlags) ? "c" : "-" let t = isTransientConnection(flags: reachabilityFlags) ? "t" : "-" let i = isInterventionRequired(flags: reachabilityFlags) ? "i" : "-" let C = isConnectionOnTraffic(flags: reachabilityFlags) ? "C" : "-" let D = isConnectionOnDemand(flags: reachabilityFlags) ? "D" : "-" let l = isLocalAddress(flags: reachabilityFlags) ? "l" : "-" let d = isDirect(flags: reachabilityFlags) ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } deinit { stopNotifier() reachabilityRef = nil whenReachable = nil whenUnreachable = nil } }
b1fe81159b46f58f0512df5072a1bc0d
34.420054
196
0.661821
false
false
false
false
CosmicMind/Motion
refs/heads/develop
Pods/Motion/Sources/Extensions/Motion+CALayer.swift
gpl-3.0
3
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit internal extension CALayer { /// Swizzle the `add(_:forKey:) selector. static var motionAddedAnimations: [(CALayer, String, CAAnimation)]? = { let swizzling: (AnyClass, Selector, Selector) -> Void = { forClass, originalSelector, swizzledSelector in if let originalMethod = class_getInstanceMethod(forClass, originalSelector), let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector) { method_exchangeImplementations(originalMethod, swizzledMethod) } } swizzling(CALayer.self, #selector(add(_:forKey:)), #selector(motionAdd(anim:forKey:))) return nil }() @objc dynamic func motionAdd(anim: CAAnimation, forKey: String?) { if nil == CALayer.motionAddedAnimations { motionAdd(anim: anim, forKey: forKey) } else { let copiedAnim = anim.copy() as! CAAnimation copiedAnim.delegate = nil // having delegate resulted some weird animation behavior CALayer.motionAddedAnimations?.append((self, forKey!, copiedAnim)) } } /// Retrieves all currently running animations for the layer. var animations: [(String, CAAnimation)] { guard let keys = animationKeys() else { return [] } return keys.map { return ($0, self.animation(forKey: $0)!.copy() as! CAAnimation) } } /** Concats transforms and returns the result. - Parameters layer: A CALayer. - Returns: A CATransform3D. */ func flatTransformTo(layer: CALayer) -> CATransform3D { var l = layer var t = l.transform while let sl = l.superlayer, self != sl { t = CATransform3DConcat(sl.transform, t) l = sl } return t } /// Removes all Motion animations. func removeAllMotionAnimations() { guard let keys = animationKeys() else { return } for animationKey in keys where animationKey.hasPrefix("motion.") { removeAnimation(forKey: animationKey) } } } public extension CALayer { /** A function that accepts CAAnimation objects and executes them on the view's backing layer. - Parameter animation: A CAAnimation instance. */ func animate(_ animations: CAAnimation...) { animate(animations) } /** A function that accepts CAAnimation objects and executes them on the view's backing layer. - Parameter animation: A CAAnimation instance. */ func animate(_ animations: [CAAnimation]) { for animation in animations { if let a = animation as? CABasicAnimation { a.fromValue = (presentation() ?? self).value(forKeyPath: a.keyPath!) } updateModel(animation) if let a = animation as? CAPropertyAnimation { add(a, forKey: a.keyPath!) } else if let a = animation as? CAAnimationGroup { add(a, forKey: nil) } else if let a = animation as? CATransition { add(a, forKey: kCATransition) } } } /** A function that accepts a list of MotionAnimation values and executes them. - Parameter animations: A list of MotionAnimation values. */ func animate(_ animations: MotionAnimation...) { animate(animations) } /** A function that accepts an Array of MotionAnimation values and executes them. - Parameter animations: An Array of MotionAnimation values. - Parameter completion: An optional completion block. */ func animate(_ animations: [MotionAnimation], completion: (() -> Void)? = nil) { startAnimations(animations, completion: completion) } } fileprivate extension CALayer { /** A function that executes an Array of MotionAnimation values. - Parameter _ animations: An Array of MotionAnimations. - Parameter completion: An optional completion block. */ func startAnimations(_ animations: [MotionAnimation], completion: (() -> Void)? = nil) { let ts = MotionAnimationState(animations: animations) Motion.delay(ts.delay) { [weak self, ts = ts, completion = completion] in guard let `self` = self else { return } var anims = [CABasicAnimation]() var duration = 0 == ts.duration ? 0.01 : ts.duration if let v = ts.backgroundColor { let a = MotionCAAnimation.background(color: UIColor(cgColor: v)) a.fromValue = self.backgroundColor anims.append(a) } if let v = ts.borderColor { let a = MotionCAAnimation.border(color: UIColor(cgColor: v)) a.fromValue = self.borderColor anims.append(a) } if let v = ts.borderWidth { let a = MotionCAAnimation.border(width: v) a.fromValue = NSNumber(floatLiteral: Double(self.borderWidth)) anims.append(a) } if let v = ts.cornerRadius { let a = MotionCAAnimation.corner(radius: v) a.fromValue = NSNumber(floatLiteral: Double(self.cornerRadius)) anims.append(a) } if let v = ts.transform { let a = MotionCAAnimation.transform(v) a.fromValue = NSValue(caTransform3D: self.transform) anims.append(a) } if let v = ts.spin { var a = MotionCAAnimation.spin(x: v.x) a.fromValue = NSNumber(floatLiteral: 0) anims.append(a) a = MotionCAAnimation.spin(y: v.y) a.fromValue = NSNumber(floatLiteral: 0) anims.append(a) a = MotionCAAnimation.spin(z: v.z) a.fromValue = NSNumber(floatLiteral: 0) anims.append(a) } if let v = ts.position { let a = MotionCAAnimation.position(v) a.fromValue = NSValue(cgPoint: self.position) anims.append(a) } if let v = ts.opacity { let a = MotionCAAnimation.fade(v) a.fromValue = self.value(forKeyPath: MotionAnimationKeyPath.opacity.rawValue) ?? NSNumber(floatLiteral: 1) anims.append(a) } if let v = ts.zPosition { let a = MotionCAAnimation.zPosition(v) a.fromValue = self.value(forKeyPath: MotionAnimationKeyPath.zPosition.rawValue) ?? NSNumber(floatLiteral: 0) anims.append(a) } if let v = ts.size { let a = MotionCAAnimation.size(v) a.fromValue = NSValue(cgSize: self.bounds.size) anims.append(a) } if let v = ts.shadowPath { let a = MotionCAAnimation.shadow(path: v) a.fromValue = self.shadowPath anims.append(a) } if let v = ts.shadowColor { let a = MotionCAAnimation.shadow(color: UIColor(cgColor: v)) a.fromValue = self.shadowColor anims.append(a) } if let v = ts.shadowOffset { let a = MotionCAAnimation.shadow(offset: v) a.fromValue = NSValue(cgSize: self.shadowOffset) anims.append(a) } if let v = ts.shadowOpacity { let a = MotionCAAnimation.shadow(opacity: v) a.fromValue = NSNumber(floatLiteral: Double(self.shadowOpacity)) anims.append(a) } if let v = ts.shadowRadius { let a = MotionCAAnimation.shadow(radius: v) a.fromValue = NSNumber(floatLiteral: Double(self.shadowRadius)) anims.append(a) } if #available(iOS 9.0, *), let (stiffness, damping) = ts.spring { for i in 0..<anims.count where nil != anims[i].keyPath { let v = anims[i] guard "cornerRadius" != v.keyPath else { continue } let a = MotionCAAnimation.convert(animation: v, stiffness: stiffness, damping: damping) anims[i] = a if a.settlingDuration > duration { duration = a.settlingDuration } } } let g = Motion.animate(group: anims, timingFunction: ts.timingFunction, duration: duration) self.animate(g) if let v = ts.completion { Motion.delay(duration, execute: v) } if let v = completion { Motion.delay(duration, execute: v) } } } } private extension CALayer { /** Updates the model with values provided in animation. - Parameter animation: A CAAnimation. */ func updateModel(_ animation: CAAnimation) { if let a = animation as? CABasicAnimation { setValue(a.toValue, forKeyPath: a.keyPath!) } else if let a = animation as? CAAnimationGroup { a.animations?.forEach { updateModel($0) } } } }
abd74b1213d973680720522290509605
30.633987
157
0.631302
false
false
false
false
tobbi/projectgenerator
refs/heads/master
target_includes/ios_bridges/Button.swift
gpl-2.0
1
// // Button.swift // MobileApplicationsSwiftAufgabe1 // // Created by Tobias Markus on 21.04.15. // Copyright (c) 2015 Tobias Markus. All rights reserved. // import Foundation import UIKit /** * Class that represents a button * @author tobiasmarkus */ public class Button { private var innerButton: UIButton; private var x: CGFloat = 0, y: CGFloat = 0; /** * Specifies the place where the textfield goes. */ private var parentUIContext: UIViewController; /** * Specifies the place where the handlers are defined */ private var parentEventContext: UIResponder; /** * Public constructor of class "Button" */ public init(context: UIViewController!, eventContext: UIResponder!) { // Set parent context: self.parentUIContext = context; self.parentEventContext = eventContext; // Initialize button self.innerButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 30)); // Set the default look for this button self.innerButton.backgroundColor = UIColor.whiteColor(); self.innerButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal); self.innerButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Selected); self.innerButton.layer.borderWidth = 1; self.innerButton.layer.cornerRadius = 5; if let titleLabel = self.innerButton.titleLabel { titleLabel.font = UIFont(name: "Arial", size: 12); } } /** * Returns the label for this button * @return String The label for this element */ public func getLabel() -> String { if let titleLabel = self.innerButton.titleLabel { if let text = titleLabel.text { return text; } } return ""; } /** * Sets the label for this button * @param String The label to set */ public func setLabel(label: String) { self.innerButton.setTitle(label, forState: UIControlState.Normal); } /** * Sets the size of this element * @param width The width of this element in percent * @param height The height of this element in percent */ public func setSize(width: CGFloat, height: CGFloat) { var screenWidth = (self.parentUIContext as! ApplicationView).getWidth(); var screenHeight = (self.parentUIContext as! ApplicationView).getHeight(); var newWidth = (screenWidth / 100) * width; var newHeight = (screenHeight / 100) * height; self.innerButton.frame = CGRectMake(self.x, self.y, newWidth, newHeight); } /** * Sets the size of this element * @param width The width of this element in percent * @param height The height of this element in percent */ public func setSize(width: Int, height: Int) { var f_width = CGFloat(width); var f_height = CGFloat(height); setSize(f_width, height: f_height); } /** * Sets the position of this element * @param x The x position of this element * @param y The y position of this element */ public func setPosition(x: CGFloat, y: CGFloat) { var screenWidth = (self.parentUIContext as! ApplicationView).getWidth(); var screenHeight = (self.parentUIContext as! ApplicationView).getHeight(); var newX = (screenWidth / 100) * x; var newY = (screenHeight / 100) * y; self.x = newX; self.y = newY; self.innerButton.frame = CGRectMake(newX, newY, self.innerButton.frame.width, self.innerButton.frame.height); } /** * Sets the position of this element * @param x The x position of this element * @param y The y position of this element */ public func setPosition(x: Int, y: Int) { var f_x = CGFloat(x); var f_y = CGFloat(y); setPosition(f_x, y: f_y); } /** * Gets the wrapped element */ public func getWrappedElement() -> UIButton { return innerButton; } /** * Adds this button to the specified application view */ public func addToApplicationView() { parentUIContext.view.addSubview(getWrappedElement()); } /** * Adds an onClick listener to this button * @param listenerName Function name of the listener */ public func addOnClickListener(methodName: String) { // add a target innerButton.addTarget(parentEventContext, action: Selector(methodName + ":"), forControlEvents: UIControlEvents.TouchUpInside); } }
7afa9ac6e9305c87a6721d65ebd04ee9
28.08642
135
0.614601
false
false
false
false
mirrorinf/Mathematicus
refs/heads/master
Mathematicus/Polynomial.swift
apache-2.0
1
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 public struct Polynomial<Field: Number> { public var coffcient: [Int : Field] public internal(set) var maxexp: Int public static func identityPolynomial() -> Polynomial<Field> { return Polynomial<Field>(coffcient: [1 : Field.identity], maxexp: 1) } public static func zeroPolynomial() -> Polynomial<Field> { return Polynomial<Field>(coffcient: [0 : Field.zero], maxexp: 0) } public static func constantPolynomial(c: Field) -> Polynomial<Field> { return Polynomial<Field>(coffcient: [0 : c], maxexp: 0) } public static func findOrder<T>(of p: [Int : T], maxiumTrial: Int) -> Int { for i in (1...maxiumTrial).reversed() { if p[i] != nil { return i } } return 0 } } public func +<U>(lhs: Polynomial<U>, rhs: Polynomial<U>) -> Polynomial<U> { let e = max(lhs.maxexp, rhs.maxexp) var coff: [Int : U] = [ : ] for i in 0...e { if lhs.coffcient[i] != nil { coff[i] = lhs.coffcient[i]! if rhs.coffcient[i] != nil { coff[i] = rhs.coffcient[i]! + coff[i]! } } else { coff[i] = rhs.coffcient[i] } if let j = coff[i] { if j == U.zero { coff[i] = nil } } } var rst = Polynomial<U>.identityPolynomial() rst.coffcient = coff rst.maxexp = Polynomial<U>.findOrder(of: coff, maxiumTrial: e) return rst } public func *<U>(lhs: U, rhs: Polynomial<U>) -> Polynomial<U> { if lhs == U.zero { return Polynomial<U>.zeroPolynomial() } var newcoff = rhs.coffcient for i in 0...rhs.maxexp { if let c = newcoff[i] { newcoff[i] = c * lhs } } return Polynomial<U>(coffcient: newcoff, maxexp: rhs.maxexp) } public func *<U>(lhs: Polynomial<U>, rhs: U) -> Polynomial<U> { return rhs * lhs } public func *<U>(lhs: Polynomial<U>, rhs: Polynomial<U>) -> Polynomial<U> { var rst = Polynomial<U>.zeroPolynomial() for (i, c) in lhs.coffcient { var newcoff: [Int : U] = [ : ] for (j, m) in rhs.coffcient { newcoff[i + j] = c * m } let newpoly = Polynomial<U>(coffcient: newcoff, maxexp: rhs.maxexp + i) rst = rst + newpoly } return rst } public func -<U>(lhs: Polynomial<U>, rhs: Polynomial<U>) -> Polynomial<U> { let minusOne = -U.identity let s = minusOne * rhs return lhs + s } public extension Polynomial { func evaluate(at x: Field) -> Field { var rst = Field.zero var run = Field.identity for i in 0...self.maxexp { if let c = self.coffcient[i] { rst = rst + c * run } run = run * x } return rst } } public extension Polynomial { func isZeroPolynomial() -> Bool { let n = self.maxexp var s: [Field] = [Field.randomElement()] for _ in 0..<n { var flag = true var new: Field = Field.randomElement() while flag { flag = s.map { $0 == new } .reduce(false) { $0 || $1 } new = Field.randomElement() } s.append(new) } let test = s.map { self.evaluate(at: $0) }.map { $0 == Field.zero } .reduce(true) { $0 && $1 } return test } }
3072282dd2e4a36eb5fa9c27321395ec
25.034965
76
0.641955
false
false
false
false
nakau1/Formations
refs/heads/master
Formations/Sources/Models/Json.swift
apache-2.0
1
// ============================================================================= // Formations // Copyright 2017 yuichi.nakayasu All rights reserved. // ============================================================================= import UIKit enum Json: FileType { case formation(teamId: String) var directory: String { switch self { case .formation: return "formations" } } var name: String { switch self { case let .formation(teamId): return teamId } } var extensionName: String { return "json" } } extension Json { func save(_ jsonString: String?) { makeDirectoryIfNeeded() if let string = jsonString { try? string.write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8) } else { delete() } } func load() -> String? { guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { return nil } return String(data: data, encoding: .utf8) } }
8789d750c336174f0cb09922cb0dade8
23.795455
96
0.472044
false
false
false
false
radvansky-tomas/NutriFacts
refs/heads/master
nutri-facts/nutri-facts/Model/User.swift
gpl-2.0
1
// // User.swift // nutri-facts // // Created by Tomas Radvansky on 20/05/2015. // Copyright (c) 2015 Tomas Radvansky. All rights reserved. // import UIKit import RealmSwift class User: Object { dynamic var userID:Int = 0 dynamic var gender:Bool = false dynamic var age:Int = 0 dynamic var height:Int = 0 dynamic var weight:Double = 0.0 dynamic var desiredWeight:Double = 0.0 override static func primaryKey() -> String? { return "userID" } }
12696ae1aeac0a21fd8e03e5c04019aa
20.478261
60
0.651822
false
false
false
false
samodom/TestableUIKit
refs/heads/master
TestableUIKit/UIResponder/UIView/UITableView/UITableViewReloadDataSpy.swift
mit
1
// // UITableViewReloadDataSpy.swift // TestableUIKit // // Created by Sam Odom on 2/22/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import FoundationSwagger import TestSwagger public extension UITableView { private static let reloadDataCalledString = UUIDKeyString() private static let reloadDataCalledKey = ObjectAssociationKey(reloadDataCalledString) private static let reloadDataCalledReference = SpyEvidenceReference(key: reloadDataCalledKey) /// Spy controller for ensuring a table view has had `reloadData` called on it. public enum ReloadDataSpyController: SpyController { public static let rootSpyableClass: AnyClass = UITableView.self public static let vector = SpyVector.direct public static let coselectors = [ SpyCoselectors( methodType: .instance, original: #selector(UITableView.reloadData), spy: #selector(UITableView.spy_reloadData) ) ] as Set public static let evidence = [reloadDataCalledReference] as Set public static let forwardsInvocations = true } /// Spy method that replaces the true implementation of `reloadData` public func spy_reloadData() { reloadDataCalled = true spy_reloadData() } /// Indicates whether the `reloadData` method has been called on this object. public final var reloadDataCalled: Bool { get { return loadEvidence(with: UITableView.reloadDataCalledReference) as? Bool ?? false } set { saveEvidence(true, with: UITableView.reloadDataCalledReference) } } }
27a70e3bec52f59b92eaf8c29410283e
30.660377
97
0.67938
false
false
false
false
Minitour/WWDC-Collaborators
refs/heads/master
Macintosh.playground/Sources/Interface/OSApplicationWindow.swift
mit
1
import UIKit public protocol OSApplicationWindowDelegate{ /// Delegate function called when window is about to be dragged. /// /// - Parameters: /// - applicationWindow: The current application window. /// - container: The application's view. func applicationWindow(_ applicationWindow: OSApplicationWindow, willStartDraggingContainer container: UIView) /// Delegate function called when window has finished dragging /// /// - Parameters: /// - applicationWindow: The current application window. /// - container: The application's view. func applicationWindow(_ applicationWindow: OSApplicationWindow, didFinishDraggingContainer container: UIView) /// Delegate function, called when users taps the panel of the OSApplicationWindow. /// /// - Parameters: /// - applicationWindow: The current application window. /// - panel: The window panel view instance that was tapped. /// - point: The location of the tap. func applicationWindow(_ applicationWindow: OSApplicationWindow, didTapWindowPanel panel: WindowPanel,atPoint point: CGPoint) /// Delegate function, called when user clicks the "close" button in the panel. /// /// - Parameters: /// - application: The current application window. /// - panel: The window panel view instance which holds the button that was clicked. func applicationWindow(_ application: OSApplicationWindow, didCloseWindowWithPanel panel: WindowPanel) /// Delegate function, called after user has finished dragging. note that `point` parameter is an `inout`. This is to allow the class which conforms to this delegate the option to modify the point incase the point that was given isn't good. /// /// - Parameters: /// - application: The current application window. /// - point: The panel which the user dragged with. /// - Returns: return true to allow the movment of the window to the point, and false to ignore the movment. func applicationWindow(_ application: OSApplicationWindow, canMoveToPoint point: inout CGPoint)->Bool } public class OSApplicationWindow: UIView{ fileprivate var lastLocation = CGPoint(x: 0, y: 0) open var windowOrigin: MacAppDesktopView? open var delegate: OSApplicationWindowDelegate? open var dataSource: MacApp?{ didSet{ tabBar?.contentStyle = dataSource?.contentMode tabBar?.requestContentStyleUpdate() windowTitle = dataSource?.windowTitle backgroundColor = dataSource?.contentMode ?? .default == .default ? .white : .black } } open var container: UIView? open var windowTitle: String?{ set{ tabBar?.title = newValue }get{ return tabBar?.title } } open var containerSize: CGSize?{ return dataSource?.sizeForWindow() } fileprivate (set) open var tabBar: WindowPanel?{ didSet{ let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan(sender:))) tabBar?.addGestureRecognizer(gestureRecognizer) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:))) tabBar?.addGestureRecognizer(tapGesture) } } fileprivate var transitionWindowFrame: MovingWindow? public convenience init(delegate: OSApplicationWindowDelegate,dataSource: MacApp){ self.init() self.delegate = delegate self.dataSource = dataSource tabBar?.contentStyle = self.dataSource?.contentMode tabBar?.requestContentStyleUpdate() windowTitle = self.dataSource?.windowTitle backgroundColor = self.dataSource?.contentMode ?? .default == .default ? .white : .black } public convenience init(){ self.init(frame: CGRect.zero) } override public init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func handleTap(sender: UITapGestureRecognizer){ delegate?.applicationWindow(self, didTapWindowPanel: tabBar!, atPoint: sender.location(in: tabBar)) } func handlePan(sender: UIPanGestureRecognizer){ if dataSource?.shouldDragApplication == false{ return } let translation = sender.translation(in: self.superview!) switch sender.state{ case .began: transitionWindowFrame?.isHidden = false transitionWindowFrame?.frame = CGRect(origin: CGPoint(x: 0 , y: 0), size: bounds.size) transitionWindowFrame?.lastLocation = (self.transitionWindowFrame?.center)! delegate?.applicationWindow(self, willStartDraggingContainer: container!) dataSource?.macApp(self, willStartDraggingContainer: container!) break case .ended: transitionWindowFrame?.isHidden = true var point = convert(transitionWindowFrame!.center, to: superview!) if delegate?.applicationWindow(self, canMoveToPoint: &point) ?? true{ self.center = point } delegate?.applicationWindow(self, didFinishDraggingContainer: container!) dataSource?.macApp(self, didFinishDraggingContainer: container!) return default: break } let point = CGPoint(x: (transitionWindowFrame?.lastLocation.x)! + translation.x , y: (transitionWindowFrame?.lastLocation.y)! + translation.y) transitionWindowFrame?.layer.shadowOpacity = 0 transitionWindowFrame?.center = point } func setup(){ backgroundColor = .white tabBar = WindowPanel() tabBar?.backgroundColor = .clear tabBar?.delegate = self addSubview(tabBar!) container = UIView() container?.backgroundColor = .clear addSubview(container!) transitionWindowFrame = MovingWindow() transitionWindowFrame?.isHidden = true transitionWindowFrame?.backgroundColor = .clear addSubview(transitionWindowFrame!) } override public func layoutSubviews() { super.layoutSubviews() self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOpacity = 1 self.layer.shadowOffset = CGSize.zero self.layer.shadowRadius = 5 self.layer.cornerRadius = 2 transitionWindowFrame?.bounds = CGRect(origin: CGPoint(x: 0 , y: 0), size: bounds.size) frame.size = CGSize(width: containerSize?.width ?? 0, height: (containerSize?.height ?? 0) + CGFloat(20)) tabBar?.frame = CGRect(x: 0, y: 0, width: containerSize?.width ?? 0, height: 20) container?.frame = CGRect(x: 0, y: tabBar?.bounds.size.height ?? 20, width: containerSize?.width ?? 0, height: containerSize?.height ?? 0) } public override func didMoveToSuperview() { tabBar?.frame = CGRect(x: 0, y: 0, width: containerSize?.width ?? 0, height: 20) tabBar?.setNeedsDisplay() container?.frame = CGRect(x: 0, y: tabBar?.bounds.size.height ?? 20, width: containerSize?.width ?? 0, height: containerSize?.height ?? 0) frame.size = CGSize(width: containerSize?.width ?? 0, height: (containerSize?.height ?? 0 ) + CGFloat(20)) if let view = dataSource?.container{ view.frame = container!.bounds container!.addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false view.topAnchor.constraint(equalTo: container!.topAnchor).isActive = true view.bottomAnchor.constraint(equalTo: container!.bottomAnchor).isActive = true view.leftAnchor.constraint(equalTo: container!.leftAnchor).isActive = true view.rightAnchor.constraint(equalTo: container!.rightAnchor).isActive = true } } override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { lastLocation = self.center super.touchesBegan(touches, with: event) } open func close(){ self.dataSource?.willTerminateApplication() self.delegate?.applicationWindow(self, didCloseWindowWithPanel: tabBar!) self.removeFromSuperview() } } public class MovingWindow: UIView{ var lastLocation = CGPoint(x: 0, y: 0) open var borderColor: UIColor = .gray override public func draw(_ rect: CGRect) { borderColor.setStroke() let path = UIBezierPath(rect: rect) path.lineWidth = 4 path.stroke() } } extension OSApplicationWindow: WindowPanelDelegate{ public func didSelectCloseMenu(_ windowPanel: WindowPanel, panelButton button: PanelButton) { self.dataSource?.willTerminateApplication() self.delegate?.applicationWindow(self, didCloseWindowWithPanel: windowPanel) self.removeFromSuperview() } }
a2bdc2f685102b25bc98454776fb0ffe
37.236515
244
0.648508
false
false
false
false