repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
L3-DANT/findme-app
findme/Service/JsonSerializer.swift
1
8493
// // JsonSerializer.swift // findme // // Created by Maxime Signoret on 29/05/16. // Copyright © 2016 Maxime Signoret. All rights reserved. // import Foundation /// Handles Convertion from instances of objects to JSON strings. Also helps with casting strings of JSON to Arrays or Dictionaries. public class JSONSerializer { /** Errors that indicates failures of JSONSerialization - JsonIsNotDictionary: - - JsonIsNotArray: - - JsonIsNotValid: - */ public enum JSONSerializerError: ErrorType { case JsonIsNotDictionary case JsonIsNotArray case JsonIsNotValid } //http://stackoverflow.com/questions/30480672/how-to-convert-a-json-string-to-a-dictionary /** Tries to convert a JSON string to a NSDictionary. NSDictionary can be easier to work with, and supports string bracket referencing. E.g. personDictionary["name"]. - parameter jsonString: JSON string to be converted to a NSDictionary. - throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotDictionary. JsonIsNotDictionary will typically be thrown if you try to parse an array of JSON objects. - returns: A NSDictionary representation of the JSON string. */ public static func toDictionary(jsonString: String) throws -> NSDictionary { if let dictionary = try jsonToAnyObject(jsonString) as? NSDictionary { return dictionary } else { throw JSONSerializerError.JsonIsNotDictionary } } /** Tries to convert a JSON string to a NSArray. NSArrays can be iterated and each item in the array can be converted to a NSDictionary. - parameter jsonString: The JSON string to be converted to an NSArray - throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotArray. JsonIsNotArray will typically be thrown if you try to parse a single JSON object. - returns: NSArray representation of the JSON objects. */ public static func toArray(jsonString: String) throws -> NSArray { if let array = try jsonToAnyObject(jsonString) as? NSArray { return array } else { throw JSONSerializerError.JsonIsNotArray } } /** Tries to convert a JSON string to AnyObject. AnyObject can then be casted to either NSDictionary or NSArray. - parameter jsonString: JSON string to be converted to AnyObject - throws: Throws error of type JSONSerializerError. - returns: Returns the JSON string as AnyObject */ private static func jsonToAnyObject(jsonString: String) throws -> AnyObject? { var any: AnyObject? if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding) { do { any = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) } catch let error as NSError { let sError = String(error) NSLog(sError) throw JSONSerializerError.JsonIsNotValid } } return any } /** Generates the JSON representation given any custom object of any custom class. Inherited properties will also be represented. - parameter object: The instantiation of any custom class to be represented as JSON. - returns: A string JSON representation of the object. */ public static func toJson(object: Any) -> String { var json = "{" let mirror = Mirror(reflecting: object) var children = [(label: String?, value: Any)]() let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children)! children += mirrorChildrenCollection var currentMirror = mirror while let superclassChildren = currentMirror.superclassMirror()?.children { let randomCollection = AnyRandomAccessCollection(superclassChildren)! children += randomCollection currentMirror = currentMirror.superclassMirror()! } var filteredChildren = [(label: String?, value: Any)]() for (optionalPropertyName, value) in children { if !optionalPropertyName!.containsString("notMapped_") { filteredChildren += [(optionalPropertyName, value)] } } let size = filteredChildren.count var index = 0 for (optionalPropertyName, value) in filteredChildren { /*let type = value.dynamicType let typeString = String(type) print("SELF: \(type)")*/ let propertyName = optionalPropertyName! let property = Mirror(reflecting: value) var handledValue = String() if value is Int || value is Double || value is Float || value is Bool { handledValue = String(value ?? "null") } else if let array = value as? [Int?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? String(value!) : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [Double?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? String(value!) : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [Float?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? String(value!) : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [Bool?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? String(value!) : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [String?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? "\"\(value!)\"" : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [String] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += "\"\(value)\"" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? NSArray { handledValue += "[" for (index, value) in array.enumerate() { if !(value is Int) && !(value is Double) && !(value is Float) && !(value is Bool) && !(value is String) { handledValue += toJson(value) } else { handledValue += "\(value)" } handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if property.displayStyle == Mirror.DisplayStyle.Class { handledValue = toJson(value) } else if property.displayStyle == Mirror.DisplayStyle.Optional { let str = String(value) if str != "nil" { handledValue = String(str).substringWithRange(str.startIndex.advancedBy(9)..<str.endIndex.advancedBy(-1)) } else { handledValue = "null" } } else { handledValue = String(value) != "nil" ? "\"\(value)\"" : "null" } json += "\"\(propertyName)\": \(handledValue)" + (index < size-1 ? ", " : "") index += 1 } json += "}" return json } }
mit
1eef7a487adf400c1b83fe32386c9339
41.253731
193
0.543099
5.398601
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/AnimationDescriptors/ShotCellLikeActionAnimationDescriptor.swift
1
1793
// // ShotCellLikeActionAnimationDescriptor.swift // Inbbbox // // Created by Lukasz Wolanczyk on 2/8/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import UIKit struct ShotCellLikeActionAnimationDescriptor: AnimationDescriptor { weak var shotCell: ShotCollectionViewCell? var animationType = AnimationType.plain var delay = 0.0 var options: UIViewAnimationOptions = [] var animations: () -> Void var completion: ((Bool) -> Void)? init(shotCell: ShotCollectionViewCell, swipeCompletion: (() -> ())?) { self.shotCell = shotCell animations = { let contentViewWidht = shotCell.contentView.bounds.width shotCell.likeImageViewLeftConstraint?.constant = round(contentViewWidht / 2 - shotCell.likeImageView.intrinsicContentSize.width / 2) shotCell.likeImageViewWidthConstraint?.constant = shotCell.likeImageView.intrinsicContentSize.width shotCell.contentView.layoutIfNeeded() shotCell.likeImageView.alpha = 1.0 shotCell.shotImageView.transform = CGAffineTransform.identity.translatedBy(x: contentViewWidht, y: 0) shotCell.likeImageView.displaySecondImageView() shotCell.messageLabel.alpha = 1 } completion = { _ in var delayedRestoreInitialStateAnimationDescriptor = ShotCellInitialStateAnimationDescriptor(shotCell: shotCell, swipeCompletion: swipeCompletion) delayedRestoreInitialStateAnimationDescriptor.delay = 0.5 shotCell.viewClass.animateWithDescriptor(delayedRestoreInitialStateAnimationDescriptor) } } }
gpl-3.0
f61f8510f3c7f26b1b47297f430e7934
39.727273
99
0.65346
5.670886
false
false
false
false
Mykhailo-Vorontsov-owo/OfflineCommute
DataOperationKit/Sources/Operations/ImageNetworkOperation.swift
1
1189
// // ImageNetworkOperation.swift // SwiftWeather // // Created by Mykhailo Vorontsov on 12/04/2016. // Copyright © 2016 Mykhailo Vorontsov. All rights reserved. // /** Operation for loading image from cache or remote location. Actually is a general kind of operations and can be moved to DataRetrievalKit */ public class ImageNetworkOperation: NetCacheDataRetrievalOperation { private let imagePath:String public init(imagePath:String) { self.imagePath = imagePath super.init() } public override func prepareForRetrieval() throws { cache = true // If path contains ':/' then it is a full address, // else it is a local address and should by added to endpoint if imagePath.containsString(":/") { requestEndPoint = imagePath } else { requestPath = imagePath } try super.prepareForRetrieval() } // Convert and parse data public override func convertData() throws { // stage = .Converting // guard let data = data, // let image = UIImage(data: data) else { // throw DataRetrievalOperationError.WrongDataFormat(error: nil) // } // stage = .Parsing // results = [image] } }
mit
daa6e3ece56d9f083a3576b47ccca5ae
24.276596
78
0.675084
4.227758
false
false
false
false
laerador/barista
Barista/Application/AdvancedPreferencesView.swift
1
990
// // AdvancedPreferencesView.swift // Barista // // Created by Franz Greiling on 23.07.18. // Copyright © 2018 Franz Greiling. All rights reserved. // import Cocoa class AdvancedPreferencesView: NSView { // MARK: - Outlets @IBOutlet weak var displayModeStack: NSStackView! // MARK: - Lifecycle override func awakeFromNib() { super.awakeFromNib() displayModeStack.views.forEach {view in let rb = view as! NSButton rb.state = rb.tag == UserDefaults.standard.appListDetail ? .on : .off rb.isEnabled = UserDefaults.standard.showAppList } } // MARK: - Actions @IBAction func showAppList(_ sender: NSButton) { displayModeStack.views.forEach {rb in (rb as? NSButton)?.isEnabled = sender.state == NSControl.StateValue.on } } @IBAction func displayModeSelected(_ sender: NSButton) { UserDefaults.standard.appListDetail = sender.tag } }
bsd-2-clause
5368de03d75c4c664e60381dd8291846
24.358974
82
0.631951
4.454955
false
false
false
false
FearfulFox/sacred-tiles
Sacred Tiles/CommonSKSpriteNode.swift
1
4239
// // CommonSKSpriteNode.swift // Sacred Tiles // // Created by Fox on 2/17/15. // Copyright (c) 2015 eCrow. All rights reserved. // import SpriteKit; // Sprite frames are intended to all in one image. class CommonSKSpriteNode: SKSpriteNode { // The number of frames in this sprite. // Important for defining the textures we need. internal var frames: Int = 1; // Texture frames internal var textures: [SKTexture] = [SKTexture](); // Percentage locations var pPosition = CGPoint(x: 0.0, y: 0.0); init(texture: SKTexture, size: CGSize, frames: Int){ let reSize = CGSize(width: (size.width * POINT_SIZE.width), height: (size.height * POINT_SIZE.height)); super.init(texture: texture, color: UIColor.whiteColor(), size: reSize); if(frames > 0){ self.frames = frames; } self.position = self.pPosition; self.generateFrameTextures(); //self.xScale = 1.0; //self.yScale = 1.0; } convenience init(imageNamed: NSString, size: CGSize, frames: Int){ self.init(texture: SKTexture(imageNamed: imageNamed as String), size: size, frames: frames); } convenience init(imageNamed: NSString, size: CGSize){ self.init(imageNamed: imageNamed, size: size, frames: 1); } // Generates the textures that belong to this sprite private func generateFrameTextures(){ // Top Tile Frames for var i = 0; i <= self.frames; i++ { let xSize:Double = 1.0 / Double(self.frames); let xShift:Double = xSize * Double(i); let frame:SKTexture = SKTexture(rect: CGRect(x: xShift, y: 0, width: xSize, height: 1.0), inTexture: self.texture!); self.textures.append(frame); } self.texture = self.textures[0]; } // Set the frame of the sprite. func setFrame(index: Int){ if(index >= 0 && index < self.frames){ self.texture = self.textures[index]; } } // Centers the sprite on the scene. func center(area: CGRect){ self.setPosition(x: 0.5, y: 0.5); } // Sets the position based on a percentage. func setPosition(#x: CGFloat, y: CGFloat){ let xPos = x * POINT_SIZE.width; let yPos = y * POINT_SIZE.height; self.position = CGPoint(x: xPos, y: yPos); } // Get the percentile position of the sprite. func getPosition() -> CGPoint { return ( CGPoint(x: (self.position.x / POINT_SIZE.width), y: (self.position.y / POINT_SIZE.height)) ); } // Set the size func setSize(#width: CGFloat, height: CGFloat) { let reSize = CGSize(width: (width * POINT_SIZE.width), height: (height * POINT_SIZE.height)); self.size = reSize; } // Gets the size of the sprite. func getSize() -> CGSize { return ( CGSize (width: (size.width / POINT_SIZE.width), height: (size.height / POINT_SIZE.height))) } // Returns the x percentage value from a pixel size in 4:3 ratio. class func iPadXAspect(x: CGFloat) -> CGFloat { let percent = x / POINT_SIZE_IPAD.width; return (percent * POINT_SIZE.width); } // Returns the y percentage value from a pixel size in 4:3 ratio. class func iPadYAspect(y: CGFloat) -> CGFloat { let percent = y / POINT_SIZE_IPAD.height; return (percent * POINT_SIZE.height); } // Returns the x percentage value from a pixel size in 16:9 ratio. class func iPhoneXAspect(x: CGFloat) -> CGFloat { let percent = x / POINT_SIZE_IPHONE.width; return (percent * POINT_SIZE.width); } // Returns the y percentage value from a pixel size in 16:9 ratio. class func iPhoneYAspect(y: CGFloat) -> CGFloat { let percent = y / POINT_SIZE_IPHONE.height; return (percent * POINT_SIZE.height); } class func makePosition(x:CGFloat, y:CGFloat) -> CGPoint { let xPos = x * POINT_SIZE.width; let yPos = y * POINT_SIZE.height; return CGPoint(x: xPos, y: yPos); } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
b91d3445337f2ab3c325bce838191002
33.185484
128
0.601557
3.903315
false
false
false
false
aiwalle/LiveProject
LiveProject/Mine/View/LJMineCell.swift
1
1748
// // LJMineCell.swift // LiveProject // // Created by liang on 2017/10/24. // Copyright © 2017年 liang. All rights reserved. // import UIKit class LJMineCell: UITableViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var arrowImageView: UIImageView! @IBOutlet weak var hintLabel: UILabel! @IBOutlet weak var onSwitch: UISwitch! @IBOutlet weak var contentLabelCons: NSLayoutConstraint! class func cellWithTableView(_ tableView : UITableView) -> LJMineCell { // 这里如何通过类名来获取Identifier let cell = tableView.dequeueReusableCell(withIdentifier: "\(self)") as! LJMineCell return cell } var itemModel : LJSettingsItemModel? { didSet { guard let itemModel = itemModel else { return } itemModel.iconName == "" ? (iconImageView.isHidden = true) : (iconImageView.image = UIImage(named: itemModel.iconName)) contentLabelCons.constant = itemModel.iconName == "" ? -15 : 10 contentLabel.text = itemModel.contentText switch itemModel.accessoryType { case .arrow: onSwitch.isHidden = true hintLabel.isHidden = true case .arrowHint: onSwitch.isHidden = true hintLabel.isHidden = false hintLabel.text = itemModel.hintText case .onswitch: onSwitch.isHidden = false hintLabel.isHidden = true arrowImageView.isHidden = true } } } }
mit
079ae545c5f0a714141fb93da3d1b28c
29.22807
131
0.573999
5.452532
false
false
false
false
slightair/SwiftGraphics
Playgrounds/ConvexHull.playground/contents.swift
2
976
// Playground - noun: a place where people can play import Cocoa import SwiftGraphics import SwiftGraphicsPlayground import XCPlayground import SwiftUtilities let context = CGContextRef.bitmapContext(CGSize(w: 480, h: 320), origin: CGPoint(x: 0.0, y: 0.0)) context.style let bad_points = [ CGPoint(x: 101.15234375, y: 243.140625), CGPoint(x: 101.15234375, y: 241.05859375), CGPoint(x: 101.15234375, y: 237.93359375), CGPoint(x: 101.15234375, y: 235.8515625), ] let bad_hull = monotoneChain(bad_points) let rng = SwiftUtilities.random var points = random.arrayOfRandomPoints(50, range: CGRect(w: 480, h: 320)) points.count //let hull = grahamScan(points) for (index, point) in points.enumerate() { context.strokeCross(CGRect(center: point, radius: 5)) context.drawLabel("\(index)", point: point + CGPoint(x: 2, y: 0), size: 10) } let hull = monotoneChain(points, sorted: false) hull.count context.strokeLine(hull, closed: true) context.nsimage
bsd-2-clause
17b15bf142e8173914e4861bad0d9c3b
26.111111
97
0.723361
3.210526
false
false
false
false
calkinssean/woodshopBMX
WoodshopBMX/Pods/Charts/Charts/Classes/Jobs/ChartViewPortJob.swift
13
1103
// // ChartViewPortJob.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics // This defines a viewport modification job, used for delaying or animating viewport changes public class ChartViewPortJob { internal var point: CGPoint = CGPoint() internal weak var viewPortHandler: ChartViewPortHandler? internal var xIndex: CGFloat = 0.0 internal var yValue: Double = 0.0 internal weak var transformer: ChartTransformer? internal weak var view: ChartViewBase? public init( viewPortHandler: ChartViewPortHandler, xIndex: CGFloat, yValue: Double, transformer: ChartTransformer, view: ChartViewBase) { self.viewPortHandler = viewPortHandler self.xIndex = xIndex self.yValue = yValue self.transformer = transformer self.view = view } public func doJob() { // Override this } }
apache-2.0
1ed6859fb40ffd0591f6dc8d09295fe6
24.674419
92
0.675431
4.902222
false
false
false
false
adelinofaria/Buildasaur
BuildaUtils/Script.swift
2
4243
// // Script.swift // Buildasaur // // Created by Honza Dvorsky on 12/05/15. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation /** * A utility class for running terminal Scripts from your Mac app. */ public class Script { public typealias ScriptResponse = (terminationStatus: Int, standardOutput: String, standardError: String) /** * Run a script by passing in a name of the script (e.g. if you use just 'git', it will first * resolve by using the 'git' at path `which git`) or the full path (such as '/usr/bin/git'). * Optional arguments are passed in as an array of Strings and an optional environment dictionary * as a map from String to String. * Back you get a 'ScriptResponse', which is a tuple around the termination status and outputs (standard and error). */ public class func run(name: String, arguments: [String] = [], environment: [String: String] = [:]) -> ScriptResponse { //first resolve the name of the script to a path with `which` let resolved = self.runResolved("/usr/bin/which", arguments: [name], environment: [:]) //which returns the path + \n, so strip the newline var path = resolved.standardOutput.stripTrailingNewline() //if resolving failed, just abort and propagate the failed run up if (resolved.terminationStatus != 0) || (count(path) == 0) { return resolved } //ok, we have a valid path, run the script let result = self.runResolved(path, arguments: arguments, environment: environment) return result } /** * An alternative to Script.run is Script.runInTemporaryScript, which first dumps the passed in script * string into a temporary file, runs it and then deletes it. More useful for more complex script that involve * piping data between multiple scripts etc. Might be slower than Script.run, however. */ public class func runTemporaryScript(script: String) -> ScriptResponse { var resp: ScriptResponse! self.runInTemporaryScript(script, block: { (scriptPath, error) -> () in resp = Script.run("/bin/bash", arguments: [scriptPath]) }) return resp } private class func runInTemporaryScript(script: String, block: (scriptPath: String, error: NSError?) -> ()) { let uuid = NSUUID().UUIDString let tempPath = NSTemporaryDirectory().stringByAppendingPathComponent(uuid) var error: NSError? //write the script to file let success = script.writeToFile(tempPath, atomically: true, encoding: NSUTF8StringEncoding, error: &error) block(scriptPath: tempPath, error: error) //delete the temp script NSFileManager.defaultManager().removeItemAtPath(tempPath, error: nil) } private class func runResolved(path: String, arguments: [String], environment: [String: String]) -> ScriptResponse { let outputPipe = NSPipe() let errorPipe = NSPipe() let outputFile = outputPipe.fileHandleForReading let errorFile = errorPipe.fileHandleForReading let task = NSTask() task.launchPath = path task.arguments = arguments var env = NSProcessInfo.processInfo().environment for (let index, let keyValue) in enumerate(environment) { env[keyValue.0] = keyValue.1 } task.environment = env task.standardOutput = outputPipe task.standardError = errorPipe task.launch() task.waitUntilExit() let terminationStatus = Int(task.terminationStatus) let output = self.stringFromFileAndClose(outputFile) let error = self.stringFromFileAndClose(errorFile) return (terminationStatus, output, error) } private class func stringFromFileAndClose(file: NSFileHandle) -> String { let data = file.readDataToEndOfFile() file.closeFile() let output = NSString(data: data, encoding: NSUTF8StringEncoding) as String? return output ?? "" } }
mit
3e25e31e67c1349aaa7deef4f1a5ad48
37.572727
122
0.637756
4.871412
false
false
false
false
doncl/shortness-of-pants
ModalPopup/BaseModalPopup.swift
1
8920
// // BaseModalPopup.swift // BaseModalPopup // // Created by Don Clore on 5/21/18. // Copyright © 2018 Beer Barrel Poker Studios. All rights reserved. // import UIKit enum PointerDirection { case up case down } enum AvatarMode { case leftTopLargeProtruding case leftTopMediumInterior } fileprivate struct AvatarLayoutInfo { var width : CGFloat var offset : CGFloat var constraintsMaker : (UIImageView, UIView, CGFloat, CGFloat) -> () func layout(avatar : UIImageView, popup : UIView) { constraintsMaker(avatar, popup, width, offset) } } class BaseModalPopup: UIViewController { var loaded : Bool = false var presenting : Bool = true static let pointerHeight : CGFloat = 16.0 static let pointerBaseWidth : CGFloat = 24.0 static let horzFudge : CGFloat = 15.0 var origin : CGPoint weak var referenceView : UIView? private var width : CGFloat private var height : CGFloat let popupView : UIView = UIView() let avatar : UIImageView = UIImageView() let pointer : CAShapeLayer = CAShapeLayer() var avatarMode : AvatarMode? var avatarUserId : String? var avatarImage : UIImage? var avatarOffset : CGFloat { var offset : CGFloat = 0 if let avatarMode = avatarMode, let layoutInfo = avatarModeSizeMap[avatarMode] { offset = layoutInfo.offset } return offset } private let avatarModeSizeMap : [AvatarMode : AvatarLayoutInfo] = [ .leftTopLargeProtruding : AvatarLayoutInfo(width: 48.0, offset: 16.0, constraintsMaker: { (avatar, popup, width, offset) in avatar.snp.remakeConstraints { make in make.width.equalTo(width) make.height.equalTo(width) make.left.equalTo(popup.snp.left).offset(offset) make.top.equalTo(popup.snp.top).offset(-offset) } }), .leftTopMediumInterior : AvatarLayoutInfo(width: 32.0, offset: 16.0, constraintsMaker: { (avatar, popup, width, offset) in avatar.snp.remakeConstraints { make in make.width.equalTo(width) make.height.equalTo(width) make.left.equalTo(popup.snp.left).offset(offset) make.top.equalTo(popup.snp.top).offset(offset) } }) ] required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(origin : CGPoint, referenceView : UIView, size: CGSize, avatarUserId: String? = nil, avatarImage : UIImage?, avatarMode : AvatarMode?) { self.origin = origin self.width = size.width self.height = size.height self.referenceView = referenceView super.init(nibName: nil, bundle: nil) self.avatarMode = avatarMode self.avatarUserId = avatarUserId if let image = avatarImage { self.avatarImage = image.deepCopy() } } override func viewDidLoad() { if loaded { return } loaded = true super.viewDidLoad() if let ref = referenceView { origin = view.convert(origin, from: ref) } view.addSubview(popupView) view.backgroundColor = .clear popupView.backgroundColor = .white popupView.layer.shadowOffset = CGSize(width: 2.0, height: 3.0) popupView.layer.shadowRadius = 5.0 popupView.layer.shadowOpacity = 0.5 popupView.addSubview(avatar) popupView.clipsToBounds = false popupView.layer.masksToBounds = false if let userId = avatarUserId, let avatarMode = avatarMode, let layoutInfo = avatarModeSizeMap[avatarMode] { if let image = avatarImage { avatar.image = image.deepCopy() avatar.createRoundedImageView(diameter: layoutInfo.width, borderColor: UIColor.clear) } else { avatar.setAvatarImage(fromId: userId, avatarVersion: nil, diameter: layoutInfo.width, bustCache: false, placeHolderImageURL: nil, useImageProxy: true, completion: nil) } popupView.bringSubview(toFront: avatar) } view.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(BaseModalPopup.tap)) view.addGestureRecognizer(tap) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let tuple = getPopupFrameAndPointerDirection(size: view.frame.size) let popupFrame = tuple.0 let direction = tuple.1 let pointerPath = makePointerPath(direction: direction, popupFrame: popupFrame) pointer.path = pointerPath.cgPath pointer.fillColor = UIColor.white.cgColor pointer.lineWidth = 0.5 pointer.masksToBounds = false popupView.layer.addSublayer(pointer) remakeConstraints(popupFrame) let bounds = UIScreen.main.bounds let width = view.frame.width + avatarOffset if bounds.width < width && width > 0 { let ratio = (bounds.width / width) * 0.9 let xform = CGAffineTransform(scaleX: ratio, y: ratio) popupView.transform = xform } else { popupView.transform = .identity } } private func getPopupFrameAndPointerDirection(size: CGSize) -> (CGRect, PointerDirection) { let y : CGFloat let direction : PointerDirection if origin.y > size.height / 2 { y = origin.y - (height + BaseModalPopup.pointerHeight) direction = .down } else { y = origin.y + BaseModalPopup.pointerHeight direction = .up } var rc : CGRect = CGRect(x: 30.0, y: y, width: width, height: height) let rightmost = rc.origin.x + rc.width let center = rc.center if origin.x > rightmost { let offset = origin.x - center.x rc = rc.offsetBy(dx: offset, dy: 0) } else if origin.x < rc.origin.x { let offset = center.x - origin.x rc = rc.offsetBy(dx: -offset, dy: 0) } let bounds = UIScreen.main.bounds let popupWidth = rc.width + avatarOffset if bounds.width <= popupWidth { rc = CGRect(x: 0, y: rc.origin.y, width: rc.width, height: rc.height) } return (rc, direction) } fileprivate func remakeConstraints(_ popupFrame: CGRect) { popupView.snp.remakeConstraints { make in make.leading.equalTo(view).offset(popupFrame.origin.x) make.top.equalTo(view).offset(popupFrame.origin.y) make.width.equalTo(popupFrame.width) make.height.equalTo(popupFrame.height) } if let _ = avatar.image, let avatarMode = avatarMode, let layoutInfo = avatarModeSizeMap[avatarMode] { layoutInfo.layout(avatar: avatar, popup: popupView) } } private func makePointerPath(direction: PointerDirection, popupFrame : CGRect) -> UIBezierPath { let path = UIBezierPath() path.lineJoinStyle = CGLineJoin.bevel // previous code is supposed to assure that the popupFrame is not outside the origin. assert(popupFrame.origin.x < origin.x && popupFrame.origin.x + popupFrame.width > origin.x) let adjustedX = origin.x - popupFrame.origin.x if direction == .down { let adjustedApex = CGPoint(x: adjustedX, y: popupFrame.height + BaseModalPopup.pointerHeight - 1) path.move(to: adjustedApex) // down is up. let leftBase = CGPoint(x: adjustedApex.x - (BaseModalPopup.pointerBaseWidth / 2), y: adjustedApex.y - BaseModalPopup.pointerHeight) path.addLine(to: leftBase) let rightBase = CGPoint(x: adjustedApex.x + (BaseModalPopup.pointerBaseWidth / 2), y: adjustedApex.y - BaseModalPopup.pointerHeight) path.addLine(to: rightBase) path.close() } else { let adjustedApex = CGPoint(x: adjustedX, y: -BaseModalPopup.pointerHeight + 1) path.move(to: adjustedApex) let leftBase = CGPoint(x: adjustedApex.x - (BaseModalPopup.pointerBaseWidth / 2), y: adjustedApex.y + BaseModalPopup.pointerHeight) path.addLine(to: leftBase) let rightBase = CGPoint(x: adjustedApex.x + (BaseModalPopup.pointerBaseWidth / 2), y: adjustedApex.y + BaseModalPopup.pointerHeight) path.addLine(to: rightBase) path.close() } return path } @objc func tap() { dismiss(animated: true, completion: nil) } } //MARK: - rotation extension BaseModalPopup { override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { dismiss(animated: true, completion: nil) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { dismiss(animated: true, completion: nil) } }
mit
479b890143d8cf5651458d1f0f90e007
31.198556
103
0.641664
4.450599
false
false
false
false
hyperoslo/Catalog
Source/Models/Item.swift
1
654
import Wall public class Item: NSObject { public var title: String? public var attachments: [Attachment]? public var serialNumber: String? public var text: String? public var price: Double? public var oldPrice: Double? public var discount: String? public init( title: String? = nil, serialNumber: String? = nil, attachments: [Attachment]? = nil, price: Double? = nil, oldPrice: Double? = nil, discount: String? = nil) { self.title = title self.serialNumber = serialNumber self.attachments = attachments self.price = price self.oldPrice = price self.discount = discount } }
mit
d1b1204cbfa6794931929b4b7efa1c9c
23.222222
39
0.659021
4.192308
false
false
false
false
collegboi/MBaaSKit
MBaaSKit/Classes/Protocols/ImageLoad.swift
1
1699
// // ImageLoad.swift // Remote Config // // Created by Timothy Barnard on 23/10/2016. // Copyright © 2016 Timothy Barnard. All rights reserved. // import UIKit public protocol ImageLoad {} public extension ImageLoad where Self: UIImageView { public func setupImageView( className: UIViewController, name: String = "" ) { self.setup(className: String(describing: type(of: className)), tagValue: name ) } public func setupImageView( className: UIView, name: String = "") { self.setup(className: String(describing: type(of: className)), tagValue: name) } private func setup( className: String, tagValue : String ) { var viewName = tagValue if tagValue.isEmpty { viewName = String(self.tag) } let dict = RCConfigManager.getObjectProperties(className: className, objectName: viewName ) for (key, value) in dict { switch key { case "image" where dict.tryConvert(forKey: key) != "": self.image = UIImage(named: value as! String) break case "contentMode" where dict.tryConvert(forKey: key) != "": self.contentMode = UIViewContentMode(rawValue: (value as! Int))! case "isHidden" where dict.tryConvert(forKey: key) != "": self.isHidden = ((value as! Int) == 1) ? true : false break case "isUserInteractionEnabled" where dict.tryConvert(forKey: key) != "": self.isUserInteractionEnabled = ((value as! Int) == 1) ? true : false break default: break } } } }
mit
76b20ea9a9612ac6f701f9e350580b8f
32.96
99
0.578916
4.743017
false
false
false
false
xaphod/Bluepeer
HotPotato/HotPotatoNetwork.swift
1
47754
// // HotPotatoNetwork.swift // // Created by Tim Carr on 2017-03-07. // Copyright © 2017 Tim Carr. All rights reserved. import Foundation import xaphodObjCUtils import ObjectMapper public protocol HandlesHotPotatoMessages { var isActiveAsHandler: Bool { get } func handleHotPotatoMessage(message: HotPotatoMessage, peer: BPPeer, HPN: HotPotatoNetwork) } public protocol HandlesPotato { func youStartThePotato() -> Data? // one of the peers will be asked to start the potato-passing; this function provides the data func youHaveThePotato(potato: Potato, finishBlock: @escaping (_ potato: Potato)->Void) } public protocol HandlesStateChanges { func didChangeState(from: HotPotatoNetwork.State, to: HotPotatoNetwork.State) func showError(type: HotPotatoNetwork.HPNError, title: String, message: String) func thesePeersAreMissing(peerNames: [String], dropBlock: @escaping ()->Void, keepWaitingBlock: @escaping ()->Void) func didChangeRoster() // call activePeerNamesIncludingSelf() to get roster } open class HotPotatoNetwork: CustomStringConvertible { open var bluepeer: BluepeerObject? open var logDelegate: BluepeerLoggingDelegate? open var messageHandlers = [String:HandlesHotPotatoMessages]() // dict of message TYPE -> HotPotatoMessageHandler (one per message.type) open var potatoDelegate: HandlesPotato? open var stateDelegate: HandlesStateChanges? public enum State: Int { case buildup = 1 case live case disconnect case finished // done, cannot start again } public enum HPNError: Error { case versionMismatch case startClientCountMismatch case noCustomData } fileprivate var messageReplyQueue = [String:Queue<(HotPotatoMessage)->Void>]() // dict of message TYPE -> an queue of blocks that take a HotPotatoMessage. These are put here when people SEND data, as replyHandlers - they run max once. fileprivate var deviceIdentifier: String = UIDevice.current.name open var livePeerNames = [String:Int64]() // name->customdata[id]. peers that were included when Start button was pressed. Includes self, unlike bluepeer.peers which does not! fileprivate var livePeerStatus = [String:Bool]() // name->true meaning is active (not paused) fileprivate var potatoLastPassedDates = [String:Date]() fileprivate var potato: Potato? { didSet { potatoLastSeen = Date.init() } } fileprivate var potatoLastSeen: Date = Date.init(timeIntervalSince1970: 0) fileprivate let payloadHeader = "[:!Payload Header Start!:]".data(using: .utf8)! fileprivate var potatoTimer: Timer? fileprivate var potatoTimerSeconds: TimeInterval! fileprivate var networkName: String! fileprivate var dataVersion: String! // ISO 8601 date fileprivate var state: State = .buildup { didSet { if oldValue == state { return } if oldValue == .finished && state != .finished { assert(false, "ERROR: must not transition from finished to something else") return } if oldValue == .buildup && state == .live { self.logDelegate?.logString("*** BUILDUP -> LIVE ***") } else if oldValue == .live && state == .disconnect { self.logDelegate?.logString("*** LIVE -> DISCONNECT ***") } else if oldValue == .disconnect && state == .live { self.logDelegate?.logString("*** DISCONNECT -> LIVE ***") } else if state == .finished { self.logDelegate?.logString("*** STATE = FINISHED ***") } else { assert(false, "ERROR: invalid state transition") } self.stateDelegate?.didChangeState(from: oldValue, to: state) } } fileprivate var _messageID: Int = Int(arc4random_uniform(10000)) // start a random number so that IDs don't collide from different originators fileprivate var messageID: Int { get { return _messageID } set(newID) { if newID == Int.max-1 { _messageID = 0 } else { _messageID = newID } } } // START message fileprivate var livePeersOnStart = 0 fileprivate var startRepliesReceived = 0 fileprivate var startHotPotatoMessageID = 0 // BUILDGRAPH message fileprivate var buildGraphHotPotatoMessageID = 0 fileprivate var missingPeersFromLiveList: [String]? // RECEIVING A POTATO -> PAYLOAD fileprivate var pendingPotatoHotPotatoMessage: PotatoHotPotatoMessage? // if not nil, then the next received data is the potato's data payload // TELLING PEERS TO PAUSE ME WHEN I GO TO BACKGROUND. I send a PauseMeMessage, wait for responses from connected peers, then end bgTask fileprivate var backgroundTask = UIBackgroundTaskInvalid // if not UIBackgroundTaskInvalid, then we backgrounded a live session fileprivate var pauseMeMessageID = 0 fileprivate var pauseMeMessageNumExpectedResponses = 0 fileprivate var pauseMeMessageResponsesSeen = 0 fileprivate var onConnectUnpauseBlock: (()->Bool)? fileprivate var didSeeWillEnterForeground = false // all peers in this network must use the same name and version to connect and start. timeout is the amount of time the potato must be seen within, until it is considered a disconnect required public init(networkName: String, dataVersion: Date, timeout: TimeInterval? = 15.0) { self.networkName = networkName self.dataVersion = DateFormatter.ISO8601DateFormatter().string(from: dataVersion) self.potatoTimerSeconds = timeout NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground), name: Notification.Name.UIApplicationDidEnterBackground, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: Notification.Name.UIApplicationDidBecomeActive, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } // removes me from the network, doesn't stop others from continuing in the network open func stop() { // TODO: implement new IAmLeaving Message so the others don't have to wait self.logDelegate?.logString("HPN: STOP() CALLED, DISCONNECTING SESSION") self.potatoTimer?.invalidate() self.potatoTimer = nil self.state = .finished self.bluepeer!.stopAdvertising() self.bluepeer!.stopBrowsing() self.bluepeer!.dataDelegate = nil self.bluepeer!.membershipRosterDelegate = nil self.bluepeer!.membershipAdminDelegate = nil self.bluepeer!.logDelegate = nil self.bluepeer!.disconnectSession() } open func startLookingForPotatoPeers(interfaces: BluepeerInterfaces) { var bluepeerServiceName = self.networkName! if bluepeerServiceName.count > 15 { bluepeerServiceName = bluepeerServiceName.substring(to: bluepeerServiceName.index(bluepeerServiceName.startIndex, offsetBy:14)) } self.logDelegate?.logString("HPN: startConnecting, Bluepeer service name: \(bluepeerServiceName), device: \(self.deviceIdentifier) / \(self.deviceIdentifier.hashValue)") self.bluepeer = BluepeerObject.init(serviceType: bluepeerServiceName, displayName: deviceIdentifier, queue: nil, serverPort: XaphodUtils.getFreeTCPPort(), interfaces: interfaces, bluetoothBlock: nil)! if let logDel = self.logDelegate { self.bluepeer?.logDelegate = logDel } self.bluepeer!.dataDelegate = self self.bluepeer!.membershipAdminDelegate = self self.bluepeer!.membershipRosterDelegate = self self.bluepeer!.startBrowsing() self.bluepeer!.startAdvertising(.any, customData: ["id":String(self.deviceIdentifier.hashValue)]) } open var description: String { return self.bluepeer?.description ?? "Bluepeer not initialized" } // per Apple: "Your implementation of this method has approximately five seconds to perform any tasks and return. If you need additional time to perform any final tasks, you can request additional execution time from the system by calling beginBackgroundTask(expirationHandler:)" @objc fileprivate func didEnterBackground() { guard self.state != .buildup, self.state != .finished, let bluepeer = self.bluepeer else { return } self.logDelegate?.logString("HPN: didEnterBackground() with live session, sending PauseMeMessage") if let timer = self.potatoTimer { timer.invalidate() self.potatoTimer = nil } guard bluepeer.connectedPeers().count > 0 else { self.logDelegate?.logString("HPN: didEnterBackground() with live session but NO CONNECTED PEERS, no-op") self.backgroundTask = 10 // Must be anything != UIBackgroundTaskInvalid return } self.backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "HotPotatoNetwork") { self.logDelegate?.logString("HPN WARNING: backgroundTask expirationHandler() called! We're not fast enough..?") assert(false, "ERROR") } messageID += 1 pauseMeMessageID = messageID pauseMeMessageResponsesSeen = 0 pauseMeMessageNumExpectedResponses = bluepeer.connectedPeers().count let message = PauseMeMessage.init(ID: pauseMeMessageID, isPause: true, livePeerNames: nil) self.sendHotPotatoMessage(message: message, replyBlock: nil) } @objc fileprivate func willEnterForeground() { guard self.backgroundTask != UIBackgroundTaskInvalid, self.state != .buildup, state != .finished, let _ = self.bluepeer else { return } self.backgroundTask = UIBackgroundTaskInvalid self.didSeeWillEnterForeground = true } @objc fileprivate func didBecomeActive() { guard self.didSeeWillEnterForeground == true else { return } self.didSeeWillEnterForeground = false self.logDelegate?.logString("HPN: didBecomeActive() with backgrounded live session, recovery expected. Restarting potato timer, and sending UNPAUSE PauseMeMessage...") self.restartPotatoTimer() self.pauseMeMessageNumExpectedResponses = 0 self.pauseMeMessageResponsesSeen = 0 messageID += 1 if self.bluepeer!.connectedPeers().count >= 1 { self.logDelegate?.logString("HPN: unpausing") self.pauseMeMessageID = messageID self.sendHotPotatoMessage(message: PauseMeMessage.init(ID: messageID, isPause: false, livePeerNames: nil), replyBlock: nil) } else { self.logDelegate?.logString("HPN: can't unpause yet, waiting for a connection...") self.onConnectUnpauseBlock = { self.logDelegate?.logString("HPN: >=1 connection back, unpausing (PauseMeNow message)") self.pauseMeMessageID = self.messageID self.sendHotPotatoMessage(message: PauseMeMessage.init(ID: self.messageID, isPause: false, livePeerNames: nil), replyBlock: nil) return true } } } open func activePeerNamesIncludingSelf() -> [String] { let peers = self.bluepeer!.connectedPeers().filter { if let status = self.livePeerStatus[$0.displayName] { if let _ = self.livePeerNames[$0.displayName] { return status == true } } return false } var retval = peers.map({ return $0.displayName }) retval.append(self.bluepeer!.displayNameSanitized) return retval } // MARK: // MARK: SENDING MESSAGES & CONNECTIONS // MARK: open func sendHotPotatoMessage(message: HotPotatoMessage, replyBlock: ((HotPotatoMessage)->Void)?) { guard let str: String = message.toJSONString(prettyPrint: false), let data = str.data(using: .utf8) else { assert(false, "ERROR can't make data out of HotPotatoMessage") return } do { self.prepReplyQueueWith(replyBlock: replyBlock, message: message) try self.bluepeer!.sendData([data], toRole: .any) if let message = message as? PotatoHotPotatoMessage, let payload = message.potato?.payload { var headeredPayload = payloadHeader headeredPayload.append(payload) try self.bluepeer!.sendData([headeredPayload], toRole: .any) } } catch { assert(false, "ERROR got error on sendData: \(error)") } } open func sendHotPotatoMessage(message: HotPotatoMessage, toPeer: BPPeer, replyBlock: ((HotPotatoMessage)->Void)?) { guard let str: String = message.toJSONString(prettyPrint: false), let data = str.data(using: .utf8) else { assert(false, "ERROR can't make data out of HotPotatoMessage") return } do { self.prepReplyQueueWith(replyBlock: replyBlock, message: message) try self.bluepeer!.sendData([data], toPeers: [toPeer]) if let message = message as? PotatoHotPotatoMessage, let payload = message.potato?.payload { var headeredPayload = payloadHeader headeredPayload.append(payload) try self.bluepeer!.sendData([headeredPayload], toPeers: [toPeer]) } } catch { assert(false, "ERROR got error on sendData: \(error)") } } fileprivate func prepReplyQueueWith(replyBlock: ((HotPotatoMessage)->Void)?, message: HotPotatoMessage) { if let replyBlock = replyBlock { let key = message.classNameAsString() if self.messageReplyQueue[key] == nil { self.messageReplyQueue[key] = Queue<(HotPotatoMessage)->Void>() } self.messageReplyQueue[key]!.enqueue(replyBlock) } } fileprivate func connectionAllowedFrom(peer: BPPeer) -> Bool { if self.livePeerNames.count > 0 { if let _ = self.livePeerNames[peer.displayName] { self.logDelegate?.logString(("HPN: livePeerNames contains this peer, allowing connection")) return true } else { self.logDelegate?.logString(("HPN: livePeerNames is non-empty and DOES NOT contain \(peer.displayName), NOT ALLOWING CONNECTION")) return false } } else { self.logDelegate?.logString(("HPN: no livePeerNames so we're in buildup phase - allowing all connections")) return true } } fileprivate func connectToPeer(_ peer: BPPeer) { if self.connectionAllowedFrom(peer: peer) == false { return } guard let remoteID = peer.customData["id"] as? String, let remoteIDInt = Int64(remoteID) else { self.logDelegate?.logString("HPN: ERROR, remote ID missing/invalid - \(String(describing: peer.customData["id"]))") return } if remoteIDInt > Int64(self.deviceIdentifier.hashValue) { self.logDelegate?.logString("HPN: remote ID(\(remoteIDInt)) bigger than mine(\(self.deviceIdentifier.hashValue)), initiating connection...") let _ = peer.connect!() } else { self.logDelegate?.logString("HPN: remote ID(\(remoteIDInt)) smaller than mine(\(self.deviceIdentifier.hashValue)), no-op.") } } // MARK: // MARK: POTATO // MARK: fileprivate func startPotatoNow() { assert(livePeerNames.count > 0, "ERROR") guard let payload = self.potatoDelegate?.youStartThePotato() else { assert(false, "ERROR set potatoDelegate first, and make sure it can always give me a copy of the payload Data") return } for peerName in livePeerNames { potatoLastPassedDates[peerName.0] = Date.init(timeIntervalSince1970: 0) } potatoLastPassedDates.removeValue(forKey: self.bluepeer!.displayNameSanitized) // highest hash of peernames wins var winner: (String, Int64) = livePeerNames.reduce(("",Int64.min)) { (result, element) -> (String,Int64) in guard let status = self.livePeerStatus[element.key] else { assert(false, "no status ERROR") return result } if status == false { // element is a paused peer, can't win return result } return element.value >= result.1 ? element : result } if winner.0 == "" { self.logDelegate?.logString("startPotatoNow: no one to start the potato so i'll do it") winner.0 = self.bluepeer!.displayNameSanitized } if self.bluepeer!.displayNameSanitized == winner.0 { self.logDelegate?.logString("startPotatoNow: I'M THE WINNER") let firstVisit = self.generatePotatoVisit() self.potato = Potato.init(payload: payload, visits: [firstVisit], sentFromBackground: false) self.passPotato() } else { self.logDelegate?.logString("startPotatoNow: I didn't win, \(winner) did") self.restartPotatoTimer() } } fileprivate func passPotato() { if state == .disconnect || state == .finished { self.logDelegate?.logString("NOT passing potato as state=disconnect/finished") return } let oldestPeer: (String,Date) = self.potatoLastPassedDates.reduce(("", Date.distantFuture)) { (result, element) -> (String, Date) in let peers = self.bluepeer!.peers.filter({ $0.displayName == element.0 }) guard peers.count == 1 else { return result // this can happen during reconnect, because dupe peer is being removed just at the moment this gets hit } let peer = peers.first! guard peer.state == .authenticated else { self.logDelegate?.logString("passPotato: \(peer.displayName) not connected, not passing to them...") return result } guard let status = livePeerStatus[element.0], status == true else { self.logDelegate?.logString("passPotato: \(peer.displayName) is paused, not passing to them...") return result } return result.1 < element.1 ? result : element } if oldestPeer.0 == "" { self.logDelegate?.logString("potatoPassBlock: FOUND NO PEER TO PASS TO, EATING POTATO AGAIN") self.potatoDelegate?.youHaveThePotato(potato: self.potato!, finishBlock: { (potato) in self.potato = potato self.passPotato() }) return } self.logDelegate?.logString("potatoPassBlock: passing to \(oldestPeer.0)") // update potato meta self.potatoLastPassedDates[oldestPeer.0] = Date.init() var visits: [PotatoVisit] = Array(potato!.visits!.suffix(MaxPotatoVisitLength-1)) visits.append(self.generatePotatoVisit()) potato!.visits = visits potato!.sentFromBackground = UIApplication.shared.applicationState == .background let potatoHotPotatoMessage = PotatoHotPotatoMessage.init(potato: potato!) self.sendHotPotatoMessage(message: potatoHotPotatoMessage, toPeer: self.bluepeer!.peers.filter({ $0.displayName == oldestPeer.0 }).first!, replyBlock: nil) self.restartPotatoTimer() } // TODO: remove potatoVisits if they are not in use fileprivate func generatePotatoVisit() -> PotatoVisit { var visitNum = 1 if let potato = self.potato { // should be true every time except the first one visitNum = potato.visits!.last!.visitNum! + 1 } let connectedPeers = self.bluepeer!.connectedPeers().map({ $0.displayName }) let visit = PotatoVisit.init(peerName: self.bluepeer!.displayNameSanitized, visitNum: visitNum, connectedPeers: connectedPeers) self.logDelegate?.logString("generatePotatoVisit: generated \(visit)") return visit } fileprivate func restartPotatoTimer() { guard self.backgroundTask == UIBackgroundTaskInvalid else { return } // don't reschedule the timer when we're in the background if let timer = self.potatoTimer { timer.invalidate() self.potatoTimer = nil } self.potatoTimer = Timer.scheduledTimer(timeInterval: potatoTimerSeconds, target: self, selector: #selector(potatoTimerFired(timer:)), userInfo: nil, repeats: false) } @objc fileprivate func potatoTimerFired(timer: Timer) { guard self.state != .finished else { timer.invalidate() self.potatoTimer = nil return } let timeSincePotatoLastSeen = abs(self.potatoLastSeen.timeIntervalSinceNow) self.logDelegate?.logString("Potato Timer Fired. Last seen: \(timeSincePotatoLastSeen)") if timeSincePotatoLastSeen > potatoTimerSeconds { // state: disconnect self.logDelegate?.logString("POTATO TIMER SETS STATE=DISCONNECT, sending BuildGraph messages") self.state = .disconnect DispatchQueue.main.asyncAfter(deadline: .now() + potatoTimerSeconds, execute: { // delay so that all devices can get to disconnect state before they respond to our BuildGraph message! self.sendBuildGraphHotPotatoMessage() }) } } fileprivate func handlePotatoHotPotatoMessage(_ potatoHotPotatoMessage: PotatoHotPotatoMessage, peer: BPPeer) { self.potato = potatoHotPotatoMessage.potato! self.logDelegate?.logString("HPN: got potato from \(peer.displayName).") assert(self.potatoLastPassedDates[peer.displayName] != nil, "ERROR") self.potatoLastPassedDates[peer.displayName] = Date.init() if self.potato!.sentFromBackground == false { let oldVal = self.livePeerStatus[peer.displayName] self.livePeerStatus[peer.displayName] = true if oldVal == false { self.stateDelegate?.didChangeRoster() } } // if we're disconnected, then consider this a reconnection self.state = .live guard self.backgroundTask == UIBackgroundTaskInvalid else { self.logDelegate?.logString("HPN: WARNING, got potato in background, passing it off quickly...") self.passPotato() return } self.potatoDelegate?.youHaveThePotato(potato: self.potato!, finishBlock: { (potato) in self.potato = potato self.passPotato() }) } // MARK: // MARK: BUILDGRAPH - used on disconnects to ping and find out who is still around // MARK: fileprivate func sendBuildGraphHotPotatoMessage() { guard state == .disconnect else { return } self.missingPeersFromLiveList = self.livePeerNames.map { $0.key } self.missingPeersFromLiveList = self.missingPeersFromLiveList!.filter { // filter out paused peers if self.livePeerStatus[$0] == true { return true } else { self.logDelegate?.logString("HPN: sendBuildGraphHotPotatoMessage(), ignoring paused peer \($0)") return false } } // if all other peers are paused, then i'll pass the potato to myself guard self.missingPeersFromLiveList!.count != 0 else { self.state = .live self.startPotatoNow() return } if let index = self.missingPeersFromLiveList!.index(of: bluepeer!.displayNameSanitized) { self.missingPeersFromLiveList!.remove(at: index) // remove myself from the list of missing peers } let _ = bluepeer!.connectedPeers().map { // remove peers im already connected to if let index = self.missingPeersFromLiveList!.index(of: $0.displayName) { self.missingPeersFromLiveList!.remove(at: index) } } guard bluepeer!.connectedPeers().count > 0 else { self.logDelegate?.logString("HPN: sendBuildGraphHotPotatoMessage(), missing peers: \(self.missingPeersFromLiveList!.joined(separator: ", "))\nNOT CONNECTED to anything, so showing kickoutImmediately") self.prepareToDropPeers() return } self.logDelegate?.logString("HPN: sendBuildGraphHotPotatoMessage(), missing peers: \(self.missingPeersFromLiveList!.joined(separator: ", "))") // important: don't call sendRecoverHotPotatoMessage already even if there are no missing peers, because we might be the only one disconnected from a fully-connnected network. Wait for responses first. self.buildGraphHotPotatoMessageID = messageID + 1 let buildgraph = BuildGraphHotPotatoMessage.init(myConnectedPeers: bluepeer!.connectedPeers().map({ $0.displayName }), myState: state, livePeerNames: self.livePeerNames, ID: self.buildGraphHotPotatoMessageID) sendHotPotatoMessage(message: buildgraph, replyBlock: nil) } fileprivate func sendRecoverHotPotatoMessage(withLivePeers: [String:Int64]) { if state != .disconnect { self.logDelegate?.logString("HPN: WARNING, skipping sendRecoverHotPotatoMessage() since we're not state=disconnect!") return } self.logDelegate?.logString("HPN: sendRecoverHotPotatoMessage, withLivePeers: \(withLivePeers)") self.livePeerNames = withLivePeers assert(livePeerNames.count > 0, "ERROR") self.state = .live // get .live before sending out to others. // send RecoverHotPotatoMessage, with live peers messageID += 1 let recover = RecoverHotPotatoMessage.init(ID: messageID, livePeerNames: withLivePeers) // don't just call handleRecoverHotPotatoMessage, as we want to ensure the recoverMessage arrives at the remote side before the actual potato does (in the case where we win the startPotato election) sendHotPotatoMessage(message: recover, replyBlock: nil) startPotatoNow() } fileprivate func handleBuildGraphHotPotatoMessage(message: BuildGraphHotPotatoMessage, peer: BPPeer) { self.logDelegate?.logString("HPN: handleBuildGraphHotPotatoMessage from \(peer.displayName). remoteConnectedPeers: \(message.myConnectedPeers!.joined(separator: ", ")), state=\(String(describing: State(rawValue: message.myState!.rawValue)!)), livePeerNames: \(message.livePeerNames!)") if message.ID! == self.buildGraphHotPotatoMessageID { self.logDelegate?.logString("... handling \(peer.displayName)'s response to my BuildGraphHotPotatoMessage") if state != .disconnect { self.logDelegate?.logString("HPN: state!=disconnect, so no-op") return } if message.myState! != .disconnect { // expectation: they've seen the potato recently and we're connected to them, so just wait for potato to be passed to me self.logDelegate?.logString("HPN: \(peer.displayName)'s state!=disconnect, so no-op") return } guard var missing = self.missingPeersFromLiveList else { assert(false, "ERROR") return } if let index = missing.index(of: peer.displayName) { missing.remove(at: index) } let _ = message.myConnectedPeers!.map { // remote side's connected peers if let index = missing.index(of: $0) { missing.remove(at: index) } } self.missingPeersFromLiveList = missing if self.missingPeersFromLiveList!.count == 0 { // restart the potato self.sendRecoverHotPotatoMessage(withLivePeers: self.livePeerNames) } else { self.prepareToDropPeers() } } else { self.logDelegate?.logString("... replying to BuildGraphHotPotatoMessage from \(peer.displayName)") let reply = BuildGraphHotPotatoMessage.init(myConnectedPeers: bluepeer!.connectedPeers().map({ $0.displayName }), myState: state, livePeerNames: self.livePeerNames, ID: message.ID!) sendHotPotatoMessage(message: reply, toPeer: peer, replyBlock: nil) } } fileprivate func prepareToDropPeers() { // tell delegate the updated list self.stateDelegate?.thesePeersAreMissing(peerNames: self.missingPeersFromLiveList!, dropBlock: { // this code will get run if these peers are supposed to be dropped. var updatedLivePeers = self.livePeerNames let _ = self.missingPeersFromLiveList!.map { updatedLivePeers.removeValue(forKey: $0) self.livePeerStatus.removeValue(forKey: $0) } self.sendRecoverHotPotatoMessage(withLivePeers: updatedLivePeers) }, keepWaitingBlock: { // this code will get run if the user wants to keep waiting self.sendBuildGraphHotPotatoMessage() }) } fileprivate func handleRecoverHotPotatoMessage(message: RecoverHotPotatoMessage, peer: BPPeer?) { let name = peer?.displayName ?? "myself" self.livePeerNames = message.livePeerNames! self.logDelegate?.logString("Got handleRecoverHotPotatoMessage from \(name), new livePeers are \(message.livePeerNames!), going live and starting potato now") if state != .disconnect { self.logDelegate?.logString("handleRecoverHotPotatoMessage: not .disconnect, no-op") return } self.state = .live startPotatoNow() } fileprivate func handlePauseMeMessage(message: PauseMeMessage, peer: BPPeer?) { if message.ID! == pauseMeMessageID { // it's a reply to mine. if message.isPause == true { // I'm pausing. Once i've seen enough responses, I just end my bgTask. pauseMeMessageResponsesSeen += 1 if pauseMeMessageResponsesSeen >= pauseMeMessageNumExpectedResponses { DispatchQueue.main.asyncAfter(deadline: .now()+2.0, execute: { // some extra time to get the last potato out self.logDelegate?.logString("handlePauseMeMessage: got all responses, ending BGTask") UIApplication.shared.endBackgroundTask(self.backgroundTask) // don't set backgroundTask to invalid, as we want potatoes to get handed off without processing until we foreground }) } else { self.logDelegate?.logString("handlePauseMeMessage: \(pauseMeMessageResponsesSeen) responses out of \(pauseMeMessageNumExpectedResponses)") } } else { // i'm unpausing. Update my live peer list assert(message.livePeerNames != nil, "ERROR") guard let _ = livePeerNames[bluepeer!.displayNameSanitized] else { // shouldn't be possible self.logDelegate?.logString("handlePauseMeMessage: ERROR, i'm not in the livepeers in unpause response") assert(false, "ERROR") state = .disconnect return } self.livePeerNames = message.livePeerNames! self.logDelegate?.logString("handlePauseMeMessage: unpause response received, updated livePeerNames") self.stateDelegate?.didChangeRoster() // in case there were comings/goings while we were asleep } } else { // it's from someone else: let's respond guard let _ = self.livePeerNames[peer!.displayName] else { self.logDelegate?.logString("handlePauseMeMessage: !!!!!!!!!! received a pause/unpause message from a peer not in livePeerNames, IGNORING IT") return } self.livePeerStatus[peer!.displayName] = !message.isPause! // if this is a response to an unpause, send my list of livepeers along so remote side is up to date if message.isPause == false { message.livePeerNames = self.livePeerNames } self.logDelegate?.logString("handlePauseMeMessage: HPN SERVICE TO \(peer!.displayName) IS \(message.isPause! ? "PAUSED" : "RESUMED")") self.sendHotPotatoMessage(message: message, toPeer: peer!, replyBlock: nil) // send reply as acknowledgement self.stateDelegate?.didChangeRoster() } } // MARK: // MARK: STARTING // MARK: open func startNetwork() -> Bool { let connectedPeersCount = bluepeer!.connectedPeers().count if connectedPeersCount == 0 { self.logDelegate?.logString("Aborting startButton - no connected peers") return false } self.logDelegate?.logString("Sending initial start message, \(connectedPeersCount) connected peers") self.startRepliesReceived = 0 self.livePeersOnStart = connectedPeersCount messageID += 1 self.startHotPotatoMessageID = messageID let startHotPotatoMessage = StartHotPotatoMessage(remoteDevices: connectedPeersCount, dataVersion: self.dataVersion, ID: messageID, livePeerNames: nil) sendHotPotatoMessage(message: startHotPotatoMessage, replyBlock: nil) return true } fileprivate func handleStartHotPotatoMessage(startHotPotatoMessage: StartHotPotatoMessage, peer: BPPeer) { self.logDelegate?.logString("Received StartHotPotatoMessage, ID: \(String(describing: startHotPotatoMessage.ID))") if state != .buildup { self.logDelegate?.logString("WARNING - ignoring startHotPotatoMessage because state != .buildup") return } if startHotPotatoMessage.dataVersion! != self.dataVersion { let dateformatter = DateFormatter.init() dateformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssSSSSZZZZZ" let remoteVersionDate = dateformatter.date(from: startHotPotatoMessage.dataVersion!)! let myVersionDate = dateformatter.date(from: self.dataVersion)! self.stateDelegate?.showError(type: .versionMismatch, title: "Error", message: "This device has \(myVersionDate < remoteVersionDate ? "an earlier" : "a more recent") version of the data payload than \(peer.displayName).") self.logDelegate?.logString("WARNING - data version mismatch, disconnecting \(peer.displayName)") if startHotPotatoMessage.versionMismatchDetected == false { // so that the other side can detect mismatch also let returnMessage = startHotPotatoMessage returnMessage.dataVersion = self.dataVersion returnMessage.versionMismatchDetected = true self.sendHotPotatoMessage(message: returnMessage, toPeer: peer, replyBlock: nil) } peer.disconnect() return } // go live message - regardless of whether i pressed start or someone else did if let livePeers = startHotPotatoMessage.livePeerNames { if let _ = livePeers[bluepeer!.displayNameSanitized] { livePeerNames = livePeers for peer in livePeers { self.livePeerStatus[peer.key] = true // active } self.state = .live self.logDelegate?.logString("Received StartHotPotatoMessage GO LIVE from \(peer.displayName), set livePeerNames to \(livePeers)") startPotatoNow() } else { self.logDelegate?.logString("Received StartHotPotatoMessage GO LIVE from \(peer.displayName), but I AM NOT INCLUDED IN \(livePeers), disconnecting") peer.disconnect() } return } if startHotPotatoMessage.ID! == self.startHotPotatoMessageID { // this is a reply to me sending START. Looking to see number of replies (ie. from n-1 peers), that we all see the same number of peers, and that the data version matches if startHotPotatoMessage.remoteDevices! != self.livePeersOnStart || self.livePeersOnStart != bluepeer!.connectedPeers().count { self.logDelegate?.logString("WARNING - remote peer count mismatch, or my connCount has changed since start pressed") self.stateDelegate?.showError(type: .startClientCountMismatch, title: "Try Again", message: "Please try again when all devices are connected to each other") return } self.startRepliesReceived += 1 if self.startRepliesReceived == self.livePeersOnStart { // got all the replies self.logDelegate?.logString("Received StartHotPotatoMessage reply from \(peer.displayName), checking customData then going LIVE and telling everyone") let completion = { self.livePeerNames[self.bluepeer!.displayNameSanitized] = Int64(self.deviceIdentifier.hashValue) // add self. self.livePeerStatus[self.bluepeer!.displayNameSanitized] = true // i'm active self.state = .live self.messageID += 1 assert(self.livePeerNames.count > 0, "ERROR") self.logDelegate?.logString("Live peer list has been set to: \(self.livePeerNames)") let golive = StartHotPotatoMessage(remoteDevices: self.livePeersOnStart, dataVersion: self.dataVersion, ID: self.messageID, livePeerNames: self.livePeerNames) self.sendHotPotatoMessage(message: golive, replyBlock: nil) self.startPotatoNow() } let check = { () -> Bool in for peer in self.bluepeer!.connectedPeers() { if let peerId = peer.customData["id"] as? String { let peerIdInt = Int64(peerId)! self.livePeerNames[peer.displayName] = peerIdInt self.livePeerStatus[peer.displayName] = true // active } else { self.logDelegate?.logString("WARNING, FOUND PEER WITH NO CUSTOM DATA[id]: \(peer.displayName)") return false } } self.logDelegate?.logString("All customData accounted for.") return true } // if we received the reply before the TXT data had time to percolate, then wait until it's here if check() == true { completion() } else { DispatchQueue.main.asyncAfter(deadline: .now()+1.5, execute: { if check() == true { completion() } else { DispatchQueue.main.asyncAfter(deadline: .now()+1.5, execute: { if check() == true { completion() } else { assert(false, "ERROR still no customData") self.stateDelegate?.showError(type: .noCustomData, title: "Try Again", message: "Please wait a moment longer after all devices are connected.") } }) } }) } } else { self.logDelegate?.logString("Received StartHotPotatoMessage reply from \(peer.displayName), waiting for \(self.livePeersOnStart - self.startRepliesReceived) more") } } else { // someone else hit START - reply to them with what I know let reply = StartHotPotatoMessage(remoteDevices: bluepeer!.connectedPeers().count, dataVersion: self.dataVersion, ID: startHotPotatoMessage.ID!, livePeerNames: nil) sendHotPotatoMessage(message: reply, toPeer: peer, replyBlock: nil) } } } extension HotPotatoNetwork : BluepeerMembershipAdminDelegate { public func bluepeer(_ bluepeerObject: BluepeerObject, peerConnectionRequest peer: BPPeer, invitationHandler: @escaping (Bool) -> Void) { if self.connectionAllowedFrom(peer: peer) == false { invitationHandler(false) } else { invitationHandler(true) } } public func bluepeer(_ bluepeerObject: BluepeerObject, browserFoundPeer role: RoleType, peer: BPPeer) { self.connectToPeer(peer) } } extension HotPotatoNetwork : BluepeerMembershipRosterDelegate { public func bluepeer(_ bluepeerObject: BluepeerObject, peerDidConnect peerRole: RoleType, peer: BPPeer) { if let block = self.onConnectUnpauseBlock { if block() { // send unpause message self.onConnectUnpauseBlock = nil } } if state == .disconnect { self.sendBuildGraphHotPotatoMessage() } self.stateDelegate?.didChangeRoster() } public func bluepeer(_ bluepeerObject: BluepeerObject, peerDidDisconnect peerRole: RoleType, peer: BPPeer, canConnectNow: Bool) { self.stateDelegate?.didChangeRoster() if canConnectNow { self.logDelegate?.logString("HPN: peerDidDisconnect, canConnectNow - reconnecting...") self.connectToPeer(peer) } } public func bluepeer(_ bluepeerObject: BluepeerObject, peerConnectionAttemptFailed peerRole: RoleType, peer: BPPeer?, isAuthRejection: Bool, canConnectNow: Bool) { self.logDelegate?.logString("HPN: peerConnectionAttemptFailed for \(String(describing: peer?.displayName))!") if (isAuthRejection) { self.logDelegate?.logString("HPN: peerConnectionAttemptFailed, AuthRejection!") } if let peer = peer, canConnectNow == true { DispatchQueue.main.asyncAfter(deadline: .now() + 4.0, execute: { // otherwise it eats 100% CPU when looping fast self.logDelegate?.logString("HPN: peerConnectionAttemptFailed, canConnectNow - reconnecting...") self.connectToPeer(peer) }) } } } extension HotPotatoNetwork : BluepeerDataDelegate { public func bluepeer(_ bluepeerObject: BluepeerObject, didReceiveData data: Data, peer: BPPeer) { if state != .buildup && self.livePeerNames[peer.displayName] == nil { assert(false, "should not be possible") self.logDelegate?.logString("HPN didReceiveData: **** received data from someone not in livePeer list, IGNORING") return } if data.count > self.payloadHeader.count { let mightBePayloadHeader = data.subdata(in: 0..<self.payloadHeader.count) if mightBePayloadHeader == payloadHeader, let pendingPotatoHotPotatoMessage = self.pendingPotatoHotPotatoMessage { let dataWithoutHeader = data.subdata(in: self.payloadHeader.count..<data.count) // then this data is part of the potato message self.logDelegate?.logString("Received potato PAYLOAD") pendingPotatoHotPotatoMessage.potato!.payload = dataWithoutHeader self.pendingPotatoHotPotatoMessage = nil self.handlePotatoHotPotatoMessage(pendingPotatoHotPotatoMessage, peer: peer) return } } guard let stringReceived = String(data: data, encoding: .utf8), let message = Mapper<HotPotatoMessage>().map(JSONString: stringReceived) else { assert(false, "ERROR: received something that isn't UTF8 string, or can't map the string") return } let key = message.classNameAsString() self.logDelegate?.logString("Received message of type \(key)") // HotPotatoMessages I handle if let potatoHotPotatoMessage = message as? PotatoHotPotatoMessage { self.pendingPotatoHotPotatoMessage = potatoHotPotatoMessage return } else if let startmessage = message as? StartHotPotatoMessage { self.handleStartHotPotatoMessage(startHotPotatoMessage: startmessage, peer: peer) return } else if let buildgraphmessage = message as? BuildGraphHotPotatoMessage { self.handleBuildGraphHotPotatoMessage(message: buildgraphmessage, peer: peer) return } else if let recovermessage = message as? RecoverHotPotatoMessage { self.handleRecoverHotPotatoMessage(message: recovermessage, peer: peer) return } else if let pausemessage = message as? PauseMeMessage { self.handlePauseMeMessage(message: pausemessage, peer: peer) return } // HotPotatoMessages handled elsewhere if var queue = self.messageReplyQueue[key], let replyBlock = queue.dequeue() { //self.logDelegate?.logString("Found handler in messageReplyQueue, using that") replyBlock(message) } else if let handler = self.messageHandlers[key], handler.isActiveAsHandler == true { //self.logDelegate?.logString("Found handler in messageHandlers, using that") handler.handleHotPotatoMessage(message: message, peer: peer, HPN: self) } else { assert(false, "ERROR: unhandled message - \(message)") } } } public extension DateFormatter { class func ISO8601DateFormatter() -> DateFormatter { let retval = DateFormatter.init() retval.dateFormat = "yyyy-MM-dd'T'HH:mm:ssSSSSZZZZZ" return retval } } public extension Date { // warning, english only func relativeTimeStringFromNow() -> String { let dateComponents = Calendar.current.dateComponents([.minute, .hour, .day, .weekOfYear], from: self, to: Date.init()) if dateComponents.weekOfYear! == 0 && dateComponents.day! == 0 && dateComponents.hour! == 0 { if dateComponents.minute! <= 1 { return "just now" } // show minutes return "\(dateComponents.minute!) minute(s) ago" } else if dateComponents.weekOfYear! == 0 && dateComponents.day! == 0 { // show hours return "\(dateComponents.hour!) hour(s) ago" } else if dateComponents.weekOfYear! < 2 { // show days let days = dateComponents.weekOfYear! * 7 + dateComponents.day! return "\(days) day(s) ago" } else { // show weeks return "\(dateComponents.weekOfYear!) week(s) ago" } } }
mit
0f7c96b547eafba1e3589173f831c7ff
49.055556
293
0.629385
5.370937
false
false
false
false
qblu/ModelForm
ModelFormTests/PropertyTypeFormFields/BoolTypeFormFieldSpec.swift
1
3715
// // BoolTypeFormFieldSpec.swift // ModelForm // // Created by Rusty Zarse on 7/28/15. // Copyright (c) 2015 LeVous. All rights reserved. // // // IntTypeFormFieldSpec.swift // ModelForm // // Created by Rusty Zarse on 7/27/15. // Copyright (c) 2015 LeVous. All rights reserved. // import Quick import Nimble import ModelForm class BoolTypeFormFieldSpec: QuickSpec { override func spec() { describe(".createFormField") { context("When a bool is passed as value") { it("returns a UISwitch with on state reflecting value") { let field = BoolTypeFormField().createFormField("someName", value: false) as! UISwitch expect(field.on).to(beFalse()) let field2 = BoolTypeFormField().createFormField("someName", value: true) as! UISwitch expect(field.on).to(beFalse()) } } } describe(".getValueFromFormField") { context("When a UISwitch field is passed as formField") { it("returns on state as bool") { let field = UISwitch() field.on = true let (validationResult, value) = BoolTypeFormField().getValueFromFormField(field, forPropertyNamed: "doesnt_matter") expect(validationResult.valid).to(beTrue()) expect((value as! Bool)).to(beTrue()) field.on = false let (validationResult2, value2) = BoolTypeFormField().getValueFromFormField(field, forPropertyNamed: "doesnt_matter") expect(validationResult2.valid).to(beTrue()) expect((value2 as! Bool)).to(beFalse()) } } context("When a switch field is passed as formField") { it("returns 0 or 1 accordingly") { let switchControl = UISwitch() switchControl.on = true let (validationResult, value) = IntTypeFormField().getValueFromFormField(switchControl, forPropertyNamed: "doesnt_matter") expect(validationResult.valid).to(beTrue()) expect((value as! Int)).to(equal(1)) switchControl.on = false let (validationResult2, value2) = IntTypeFormField().getValueFromFormField(switchControl, forPropertyNamed: "doesnt_matter") expect(validationResult2.valid).to(beTrue()) expect((value2 as! Int)).to(equal(0)) } } } describe(".updateValue:") { context("When a UISwitch field is passed as formField") { it("returns on state as bool") { let field = UISwitch() field.on = false let success = BoolTypeFormField().updateValue(true, onFormField: field, forPropertyNamed: "YesMan").valid expect(success).to(beTrue()) expect(field.on).to(beTrue()) let field2 = UISwitch() field2.on = true let success2 = BoolTypeFormField().updateValue(false, onFormField: field2, forPropertyNamed: "YesMan").valid expect(success2).to(beTrue()) expect(field2.on).to(beFalse()) } } } } }
mit
0d87ebebc4be75505d8e3f182a7ccbd1
34.721154
144
0.502826
5.611782
false
false
false
false
hshidara/iOS
Camera/Camera/ViewController.swift
1
24138
// // ViewController.swift // Camera // // Created by Hidekazu Shidara on 8/23/15. // Copyright (c) 2015 Hidekazu Shidara. All rights reserved. // // import UIKit import AVFoundation import AssetsLibrary import MediaPlayer import QuartzCore class ViewController: UIViewController,AVCaptureFileOutputRecordingDelegate,AVCaptureAudioDataOutputSampleBufferDelegate, UITextFieldDelegate{ var sessionQueue: dispatch_queue_t! @IBOutlet weak var takePic: UIButton! @IBOutlet weak var deletePic: UIButton! @IBOutlet weak var flipCamera: UIButton! @IBOutlet weak var caption: UIButton! @IBOutlet weak var cameraButtonWidth: NSLayoutConstraint! @IBOutlet weak var cameraButtonHeight: NSLayoutConstraint! @IBOutlet weak var deletePicWidth: NSLayoutConstraint! @IBOutlet weak var deletePicHeight: NSLayoutConstraint! @IBOutlet weak var flipCameraWidth: NSLayoutConstraint! @IBOutlet weak var flipCameraHeight: NSLayoutConstraint! var picOrVideo:String = " " // @IBOutlet weak var previewView: AVCamPreviewView! @IBOutlet weak var saveToPhotos: UIButton! var captureSession = AVCaptureSession() var selectedDevice: AVCaptureDevice? var stillImageOutput: AVCaptureStillImageOutput? var movieOutput: AVCaptureMovieFileOutput? var audioOutput: AVCaptureAudioDataOutput? var image:UIImage = UIImage(named: "TankLeft.png")! var imageView: UIImageView = UIImageView() var err : NSError? = nil var videoOrientation:AVCaptureVideoOrientation? = nil var moviePlayer : MPMoviePlayerController? let captionField = UITextField() var player = MPMoviePlayerController() var vidURL = NSURL() override func viewDidLoad() { super.viewDidLoad() self.captionField.delegate = self; let sessionQueue: dispatch_queue_t = dispatch_queue_create("session queue",DISPATCH_QUEUE_SERIAL) self.sessionQueue = sessionQueue captureSession.sessionPreset = AVCaptureSessionPresetPhoto selectedDevice = findCameraWithPosition(.Back) if selectedDevice != nil{ // setFocusFlash() startCapture() // processOrientationNotifications() } setButtons() let tapGesture = UITapGestureRecognizer(target: self, action: "Tap") //Tap function will call when user tap on button let longGesture = UILongPressGestureRecognizer(target: self, action: "Long:") //Long function will call when user long press on button. longGesture.minimumPressDuration = 0.8 tapGesture.numberOfTapsRequired = 1 takePic.addGestureRecognizer(tapGesture) takePic.addGestureRecognizer(longGesture) } func Tap(){ picOrVideo = "Pic" takePic.enabled = false dispatch_async(self.sessionQueue, { // Update the orientation on the still image output video connection before capturing. // let videoOrientation = (self.previewLayer! as AVCaptureVideoPreviewLayer).connection.videoOrientation self.videoOrientation = (self.previewLayer! as AVCaptureVideoPreviewLayer).connection.videoOrientation self.stillImageOutput?.connectionWithMediaType(AVMediaTypeVideo).videoOrientation = self.videoOrientation! // Flash set to Auto for Still Capture // ViewController.setFlashMode(AVCaptureFlashMode.Auto, device: self.videoDeviceInput!.device) self.stillImageOutput!.captureStillImageAsynchronouslyFromConnection(self.stillImageOutput!.connectionWithMediaType(AVMediaTypeVideo), completionHandler: { (imageDataSampleBuffer: CMSampleBuffer!, error: NSError!) in if error == nil { let data:NSData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer) self.image = UIImage( data: data)! self.editPic(self.image) } else{ print(error, terminator: "") } }) }) } func Long(sender: UIGestureRecognizer){ let recordingImage = UIImage(named: "cameraButtonRecording.png") takePic.setImage(recordingImage, forState: UIControlState.Normal) if sender.state == UIGestureRecognizerState.Began{ captureSession.beginConfiguration() captureSession.sessionPreset = AVCaptureSessionPresetHigh self.videoOrientation = (self.previewLayer! as AVCaptureVideoPreviewLayer).connection.videoOrientation // self.audioOutput!.connectionWithMediaType(AVMediaTypeVideo).videoOrientation = self.videoOrientation! self.movieOutput!.connectionWithMediaType(AVMediaTypeVideo).videoOrientation = self.videoOrientation! captureSession.commitConfiguration() UIView.animateWithDuration(0.4, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in self.cameraButtonHeight.constant = 90 self.cameraButtonWidth.constant = 90 self.view.layoutIfNeeded() }, completion: nil) dispatch_async(self.sessionQueue, { if !self.movieOutput!.recording{ // self.lockInterfaceRotation = true if UIDevice.currentDevice().multitaskingSupported { // self.backgroundRecordId = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({}) } // Turning OFF flash for video recording // ViewController.setFlashMode(AVCaptureFlashMode.Off, device: self.videoDeviceInput!.device) let outputFilePath: String = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent( ("movie" as NSString).stringByAppendingPathExtension("mov")!) if self.movieOutput!.connectionWithMediaType(AVMediaTypeVideo).active == false { self.movieOutput!.connectionWithMediaType(AVMediaTypeVideo).enabled = true } self.movieOutput!.startRecordingToOutputFileURL(NSURL.fileURLWithPath(outputFilePath), recordingDelegate: self) } }) } else if sender.state == UIGestureRecognizerState.Ended{ self.movieOutput!.stopRecording() } } func findCameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice? { let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) for device in devices as! [AVCaptureDevice] { if(device.position == position) { return device } } return nil } var previewLayer: AVCaptureVideoPreviewLayer? = nil func startCapture() { if let device = selectedDevice { let audioDevice: AVCaptureDevice = AVCaptureDevice.devicesWithMediaType(AVMediaTypeAudio).first as! AVCaptureDevice var audioDeviceInput: AVCaptureDeviceInput? if captureSession.canAddInput(AVCaptureDeviceInput(device: device)){ // captureSession.addInput(AVCaptureDeviceInput(device: device, error: &err)) captureSession.addInput(AVCaptureDeviceInput(device: selectedDevice)) } if captureSession.canAddInput(AVCaptureDeviceInput(device: audioDevice)){ captureSession.addInput(AVCaptureDeviceInput(device: audioDevice)) } if err != nil { print("error: \(err?.localizedDescription)") } previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) // previewLayer?.frame = self.view.layer.frame previewLayer?.frame = self.view.bounds self.view.layer.addSublayer(previewLayer!) // self.previewView.session = captureSession // previewView.frameForAlignmentRect(CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)) // self.view.layer.addSublayer(previewView.layer) var stillImageOutput: AVCaptureStillImageOutput = AVCaptureStillImageOutput() movieOutput = AVCaptureMovieFileOutput() if captureSession.canAddOutput(stillImageOutput){ stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] captureSession.addOutput(stillImageOutput) self.stillImageOutput = stillImageOutput } if captureSession.canAddOutput(movieOutput){ let maxDuration = CMTimeMakeWithSeconds(5, 600) movieOutput?.maxRecordedDuration = maxDuration captureSession.addOutput(movieOutput) } if captureSession.canAddInput(audioDeviceInput){ captureSession.addInput(audioDeviceInput) } if captureSession.canAddOutput(audioOutput){ captureSession.addOutput(audioOutput) } captureSession.startRunning() } } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) if let layer = previewLayer { layer.frame = CGRectMake(0,0,size.width, size.height) } } var observer:NSObjectProtocol? = nil; func processOrientationNotifications() { UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications() observer = NSNotificationCenter.defaultCenter().addObserverForName(UIDeviceOrientationDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue()) { [unowned self](notification: NSNotification!) -> Void in if let layer = self.previewLayer { switch UIDevice.currentDevice().orientation { case .LandscapeLeft: layer.connection.videoOrientation = .LandscapeRight case .LandscapeRight: layer.connection.videoOrientation = .LandscapeLeft default: layer.connection.videoOrientation = .Portrait } } } } deinit { // Cleanup if observer != nil { NSNotificationCenter.defaultCenter().removeObserver(observer!) } UIDevice.currentDevice().endGeneratingDeviceOrientationNotifications() } func setFocusFlash(){ if (selectedDevice?.isFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus) != nil){ selectedDevice?.isFocusModeSupported(.ContinuousAutoFocus) } if (selectedDevice?.isExposureModeSupported(.ContinuousAutoExposure) != nil) { selectedDevice?.isExposureModeSupported(.ContinuousAutoExposure) } if (selectedDevice?.isFlashModeSupported(.Auto) != nil){ selectedDevice?.isFlashModeSupported(.Auto) } if (selectedDevice?.hasTorch == true){ if (selectedDevice?.isTorchModeSupported(.Auto) != nil){ selectedDevice?.isTorchModeSupported(.Auto) } } if (selectedDevice?.isWhiteBalanceModeSupported(.ContinuousAutoWhiteBalance) != nil){ selectedDevice?.isWhiteBalanceModeSupported(.ContinuousAutoWhiteBalance) } } func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) { picOrVideo = "Video" // record.enabled = true if(error != nil){ print(error, terminator: "") } // self.lockInterfaceRotation = false // Note the backgroundRecordingID for use in the ALAssetsLibrary completion handler to end the background task associated with this recording. This allows a new recording to be started, associated with a new UIBackgroundTaskIdentifier, once the movie file output's -isRecording is back to NO — which happens sometime after this method returns. // let backgroundRecordId: UIBackgroundTaskIdentifier = self.backgroundRecordId // self.backgroundRecordId = UIBackgroundTaskInvalid // let path = NSBundle.mainBundle().pathForResource("", ofType:"m4v") // let url = NSURL.fileURLWithPath(path!) moviePlayer = MPMoviePlayerController(contentURL: outputFileURL) player = moviePlayer! player.view.frame = self.view.bounds player.controlStyle = .None player.repeatMode = .One player.prepareToPlay() player.scalingMode = .AspectFill self.view.addSubview(player.view) vidURL = outputFileURL setEditButtonsPic() self.cameraButtonHeight.constant = 80 self.cameraButtonWidth.constant = 80 let regularImage = UIImage(named: "cameraButton.png") takePic.setImage(regularImage, forState: UIControlState.Normal) } func editPic(image: UIImage){ imageView.image = image imageView.frame = self.view.frame self.view.addSubview(imageView) imageView.sendSubviewToBack(imageView) self.setEditButtonsPic() } func setEditButtonsPic(){ self.deletePic.hidden = false self.saveToPhotos.hidden = false self.caption.hidden = false self.deletePic.enabled = true self.saveToPhotos.enabled = true self.caption.enabled = true caption.superview?.bringSubviewToFront(caption) saveToPhotos.superview?.bringSubviewToFront(saveToPhotos) deletePic.superview?.bringSubviewToFront(deletePic) self.takePic.hidden = true self.flipCamera.hidden = true self.takePic.enabled = false self.flipCamera.enabled = false } func resetButtons(){ self.deletePic.hidden = true self.saveToPhotos.hidden = true self.caption.hidden = true self.deletePic.enabled = false self.saveToPhotos.enabled = false self.caption.enabled = false self.takePic.hidden = false self.flipCamera.hidden = false self.takePic.enabled = true self.flipCamera.enabled = true takePic.superview?.bringSubviewToFront(takePic) // Send button to front flipCamera.superview?.bringSubviewToFront(flipCamera) } // override func touchesBegan(touches: NSSet, withEvent event: UIEvent) // { // self.view.endEditing(true) // // if captionField.text == "" { // captionField.removeFromSuperview() // } // else{ // if imageView.image != nil { // imageView.layer.addSublayer(captionField.layer) // } // else { // self.view.addSubview(captionField) // captionField.bringSubviewToFront(captionField) // } // } // } @IBAction func didPressCaption(sender: UIButton) { captionField.frame = CGRectMake(self.view.bounds.width/2, self.view.bounds.height/2, self.view.bounds.width, 40) captionField.backgroundColor = UIColor.blackColor() captionField.textColor = UIColor.whiteColor() captionField.tintColor = UIColor.blueColor() captionField.alpha = 0.6 // Transparency captionField.textAlignment = NSTextAlignment.Center captionField.becomeFirstResponder() if imageView.image != nil { self.imageView.addSubview(captionField) captionField.bringSubviewToFront(captionField) } else { self.view.addSubview(captionField) captionField.bringSubviewToFront(captionField) } let widthConstraint = NSLayoutConstraint(item: captionField, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 250) captionField.addConstraint(widthConstraint) let heightConstraint = NSLayoutConstraint(item: captionField, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100) captionField.addConstraint(heightConstraint) let xConstraint = NSLayoutConstraint(item: captionField, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0) let yConstraint = NSLayoutConstraint(item: captionField, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0) self.view.addConstraint(xConstraint) self.view.addConstraint(yConstraint) } @IBAction func didPressSaveToPhotos(sender: UIButton) { self.view.endEditing(true) if imageView.image != nil { imageView.layer.addSublayer(captionField.layer) UIGraphicsBeginImageContext(self.view.bounds.size) imageView.layer.renderInContext(UIGraphicsGetCurrentContext()!) image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let library:ALAssetsLibrary = ALAssetsLibrary() let orientation: ALAssetOrientation = ALAssetOrientation(rawValue: image.imageOrientation.rawValue)! library.writeImageToSavedPhotosAlbum(image.CGImage, orientation: orientation, completionBlock: nil) } else { player.stop() player.view.layer.addSublayer(captionField.layer) UIGraphicsBeginImageContext(self.view.bounds.size) player.view.layer.renderInContext(UIGraphicsGetCurrentContext()!) UIGraphicsEndImageContext() let composition = AVMutableComposition() vidURL = player.contentURL ALAssetsLibrary().writeVideoAtPathToSavedPhotosAlbum(vidURL, completionBlock: { (assetURL:NSURL!, error:NSError!) in if error != nil{ print(error, terminator: "") } else{ self.resetButtons() } }) // NSFileManager.defaultManager().removeItemAtPath(expandedFilePath, error: nil) player.stop() self.player.view.removeFromSuperview() } print("save to album", terminator: "") imageView.image = nil self.captionField.removeFromSuperview() self.view.sendSubviewToBack(imageView) resetButtons() vidURL.removeAllCachedResourceValues() picOrVideo = " " } @IBAction func didPressDeletePic(sender: UIButton) { UIView.animateWithDuration(0.1, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 10, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.deletePicHeight.constant = 35 self.deletePicWidth.constant = 35 self.view.layoutIfNeeded() }, completion: { (value: Bool) in self.deletePicHeight.constant = 25 self.deletePicWidth.constant = 25 self.view.layoutIfNeeded() }) self.view.endEditing(true) player.stop() self.captionField.removeFromSuperview() self.player.view.removeFromSuperview() imageView.image = nil resetButtons() vidURL.removeAllCachedResourceValues() self.view.sendSubviewToBack(imageView) picOrVideo = " " } @IBAction func didPressFlipCamera(sender: UIButton) { UIView.animateWithDuration(0.1, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 10, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.flipCameraHeight.constant = 40 self.flipCameraWidth.constant = 45 self.view.layoutIfNeeded() }, completion: { (value: Bool) in self.flipCameraHeight.constant = 30 self.flipCameraWidth.constant = 35 self.view.layoutIfNeeded() }) dispatch_async(self.sessionQueue, { if self.selectedDevice == self.findCameraWithPosition(.Back){ self.captureSession.beginConfiguration() let inputs = self.captureSession.inputs for input in inputs { self.captureSession.removeInput(input as! AVCaptureInput) } let audioDevice: AVCaptureDevice = AVCaptureDevice.devicesWithMediaType(AVMediaTypeAudio).first as! AVCaptureDevice let audioDeviceInput: AVCaptureDeviceInput? self.selectedDevice = self.findCameraWithPosition(.Front) if self.captureSession.canAddInput(AVCaptureDeviceInput(device: self.selectedDevice)){ self.captureSession.addInput(AVCaptureDeviceInput(device: self.selectedDevice)) } if self.captureSession.canAddInput(AVCaptureDeviceInput(device: audioDevice)){ self.captureSession.addInput(AVCaptureDeviceInput(device: audioDevice)) } self.captureSession.commitConfiguration() } else if self.selectedDevice == self.findCameraWithPosition(.Front){ self.captureSession.beginConfiguration() let inputs = self.captureSession.inputs for input in inputs { self.captureSession.removeInput(input as! AVCaptureInput) } let audioDevice: AVCaptureDevice = AVCaptureDevice.devicesWithMediaType(AVMediaTypeAudio).first as! AVCaptureDevice let audioDeviceInput: AVCaptureDeviceInput? self.selectedDevice = self.findCameraWithPosition(.Back) if self.captureSession.canAddInput(AVCaptureDeviceInput(device: self.selectedDevice)){ self.captureSession.addInput(AVCaptureDeviceInput(device: self.selectedDevice)) } if self.captureSession.canAddInput(AVCaptureDeviceInput(device: audioDevice)){ self.captureSession.addInput(AVCaptureDeviceInput(device: audioDevice)) } self.captureSession.commitConfiguration() } }) } func setButtons(){ takePic.superview?.bringSubviewToFront(takePic) // Send button to front flipCamera.superview?.bringSubviewToFront(flipCamera) takePic.enabled = true flipCamera.enabled = true saveToPhotos.hidden = true deletePic.hidden = true caption.hidden = true self.saveToPhotos.enabled = false self.deletePic.enabled = false caption.enabled = false } func textFieldShouldBeginEditing(textField: UITextField) -> Bool { textField.returnKeyType = .Done return true } func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) if imageView.image != nil { imageView.layer.addSublayer(captionField.layer) } else { self.view.addSubview(captionField) captionField.bringSubviewToFront(captionField) } return false } override func didReceiveMemoryWarning() { imageView.image = nil } override func viewDidAppear(animated: Bool) { self.view.layoutIfNeeded() } }
mit
3ec00740c040294531e0d3c49f024bc1
42.25448
351
0.638258
5.987596
false
false
false
false
neoneye/SwiftyFORM
Source/Cells/OptionCell.swift
1
1030
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit public class OptionCell: UITableViewCell, SelectRowDelegate { let innerDidSelectOption: () -> Void public init(model: OptionRowFormItem, didSelectOption: @escaping () -> Void) { self.innerDidSelectOption = didSelectOption super.init(style: .default, reuseIdentifier: nil) loadWithModel(model) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func loadWithModel(_ model: OptionRowFormItem) { textLabel?.text = model.title textLabel?.font = model.titleFont textLabel?.textColor = model.titleTextColor if model.selected { accessoryType = .checkmark } else { accessoryType = .none } } public func form_didSelectRow(indexPath: IndexPath, tableView: UITableView) { SwiftyFormLog("will invoke") accessoryType = .checkmark tableView.deselectRow(at: indexPath, animated: true) innerDidSelectOption() SwiftyFormLog("did invoke") } }
mit
82e8f96c5f4c2fdb7a0d5e60cd7055e5
26.837838
79
0.736893
4.007782
false
false
false
false
enlarsen/Tesseract-Box-Editor
Tesseract-Box-Editor/ImageViewWithSelectionRect.swift
1
10896
// // ImageViewWithSelectionRect.swift // Tesseract-Box-Editor // // Created by Erik Larsen on 6/8/14. // // Copyright (c) 2014 Erik Larsen. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation import Cocoa import QuartzCore // Base class for CharacterView and ImageView class ImageViewWithSelectionRect: NSImageView { var selectionLayer: CAShapeLayer! var selectionHandleLayers: [CAShapeLayer] = [] var drawSelectionHandles = false var cropPoint = CGPointZero var selectionRect = NSZeroRect var strokeColor = NSColor.blackColor().CGColor var fillColor = NSColor.clearColor().CGColor var lineDashPattern = [10, 15] var duration = 0.75 var numberHandles = 4 func setupAnimatedSelectionRect(rect: NSRect) { selectionLayer = createAnimationLayer() layer!.addSublayer(selectionLayer) selectionLayer.addAnimation(createAnimation(), forKey: "linePhase") selectionLayer.transform = createTransform(self.cropPoint) // NSLog("Cropped point: \(cropPoint)") if drawSelectionHandles { drawHandles(rect) } drawSelectionRect(rect) return } func drawSelectionRect(rect: NSRect) { let path = CGPathCreateMutable() CGPathMoveToPoint(path, nil, rect.origin.x, rect.origin.y) CGPathAddLineToPoint(path, nil, rect.origin.x, rect.origin.y + rect.size.height) CGPathAddLineToPoint(path, nil, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height) CGPathAddLineToPoint(path, nil, rect.origin.x + rect.size.width, rect.origin.y) CGPathCloseSubpath(path) selectionLayer.path = path } func createAnimationLayer() -> CAShapeLayer { let shapeLayer = CAShapeLayer() shapeLayer.lineWidth = 0.5 shapeLayer.strokeColor = strokeColor shapeLayer.fillColor = fillColor shapeLayer.lineDashPattern = lineDashPattern return shapeLayer } func createAnimation() -> CABasicAnimation { let dashAnimation = CABasicAnimation(keyPath: "lineDashPhase") dashAnimation.fromValue = 0.0 dashAnimation.toValue = 15.0 dashAnimation.duration = duration dashAnimation.cumulative = true dashAnimation.repeatCount = HUGE return dashAnimation } func createTransform(cropPoint: NSPoint) -> CATransform3D { var verticalPadding: CGFloat = 0.0 var horizontalPadding: CGFloat = 0.0 var scaleFactor: CGFloat = 1.0 let horizontalScaleFactor = frame.size.width / image!.size.width let verticalScaleFactor = frame.size.height / image!.size.height // NSLog("horizontal scale: \(horizontalScaleFactor) vertical scale: \(verticalScaleFactor)") if verticalScaleFactor - horizontalScaleFactor < 0 { scaleFactor = verticalScaleFactor let width = image!.size.width * scaleFactor horizontalPadding = (frame.size.width - width) / 2.0 } else { scaleFactor = horizontalScaleFactor let height = image!.size.height * scaleFactor verticalPadding = (frame.size.height - height) / 2.0 } // NSLog("Horizontal padding: \(horizontalPadding), vertical padding: \(verticalPadding)") var transform = CATransform3DIdentity transform = CATransform3DTranslate(transform, horizontalPadding, verticalPadding, 0.0) transform = CATransform3DScale(transform, scaleFactor, scaleFactor, 1.0) transform = CATransform3DTranslate(transform, -cropPoint.x, -cropPoint.y, 0.0) // NSLog("Transformation: \(transform.m11) \(transform.m22) \(transform.m41) \(transform.m42)") return transform } func drawHandles(rect: NSRect) { var handles: [NSPoint] = [] let left = CGFloat(rect.origin.x) let bottom = CGFloat(rect.origin.y) let right = CGFloat(rect.origin.x + rect.size.width) let top = CGFloat(rect.origin.y + rect.size.height) handles.append(NSPoint(x: left, y: bottom + (top - bottom) / 2.0)) // left handles.append(NSPoint(x: right, y: bottom + (top - bottom) / 2.0)) // right handles.append(NSPoint(x: left + (right - left) / 2.0, y: top)) // top handles.append(NSPoint(x: (left + (right - left) / 2.0), y: bottom)) // bottom if selectionHandleLayers.count == 0 { setupSelectionHandleLayers() } for var i = 0; i < handles.count; i++ { drawHandle(handles[i], layer: selectionHandleLayers[i]) } } func drawHandle(point: NSPoint, layer: CAShapeLayer) { let size: CGFloat = 0.5 let path = CGPathCreateMutable() CGPathMoveToPoint(path, nil, point.x - size, point.y - size) CGPathAddLineToPoint(path, nil, point.x - size, point.y + size) CGPathAddLineToPoint(path, nil, point.x + size, point.y + size) CGPathAddLineToPoint(path, nil, point.x + size, point.y - size) CGPathCloseSubpath(path) layer.path = path } func setupSelectionHandleLayers() { for var i = 0; i < numberHandles; i++ { let layer = CAShapeLayer() layer.lineWidth = 0.1 layer.strokeColor = NSColor.blueColor().CGColor layer.fillColor = NSColor.blueColor().CGColor layer.transform = selectionLayer.transform selectionHandleLayers.append(layer) self.layer!.addSublayer(layer) } } func removeAnimatedSelection() { selectionLayer?.removeFromSuperlayer() for layer in selectionHandleLayers { layer.removeFromSuperlayer() } selectionHandleLayers.removeAll(keepCapacity: true) selectionLayer = nil } func computeResizedSelectionRectangle(index: Int, dragPoint: NSPoint) -> NSRect { var left = Int(selectionRect.origin.x) var right = Int(selectionRect.origin.x + selectionRect.size.width) var top = Int(selectionRect.origin.y + selectionRect.size.height) var bottom = Int(selectionRect.origin.y) switch index { case 0: left = Int(dragPoint.x) case 1: right = Int(dragPoint.x) case 2: top = Int(dragPoint.y) default: bottom = Int(dragPoint.y) } return NSRect(x: left, y: bottom, width: right - left, height: top - bottom) } // Coordinates are inverted in this function. (0, 0) is the upper left and y increases down func trimImage(image: NSImage) { let imageRef = image.CGImageForProposedRect(nil, context: nil, hints: nil)?.takeUnretainedValue() let width = CGImageGetWidth(imageRef) let height = CGImageGetHeight(imageRef) let colorSpace = CGColorSpaceCreateDeviceRGB() let bytesPerPixel: Int = 4 let bytesPerComponent: Int = 8 let rawData = calloc(height * width * bytesPerPixel, 1) let pointer = UnsafePointer<UInt8>(rawData) let bytesPerRow = bytesPerPixel * width let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue | CGBitmapInfo.ByteOrder32Big.rawValue) let context = CGBitmapContextCreate(rawData, width, height, bytesPerComponent, bytesPerRow, colorSpace, bitmapInfo.rawValue) CGContextDrawImage(context, CGRect(x: 0, y: 0, width: Int(width), height: Int(height)), imageRef) var top = 0 var left = 0 var right = Int(width) var bottom = Int(height) for var x = 0; x < Int(width); x++ { if scanColumn(x, height: Int(height), width: Int(width), pointer: pointer) { left = x break } } for var x = Int(width) - 1; x >= 0; x-- { if scanColumn(x, height: Int(height), width: Int(width), pointer: pointer) { right = x break } } for var y = 0; y < Int(height); y++ { if scanRow(y, width: Int(width), pointer: pointer) { top = y break } } for var y = Int(height) - 1; y >= 0; y-- { if scanRow(y, width: Int(width), pointer: pointer) { bottom = y break } } // Flip the coordinates to be Mac coordinates and add a border around the cropped image let cropRect = NSRect(x: left - 5, y: Int(height) - bottom - 6, width: right - left + 10, height: bottom - top + 10) free(rawData) image.lockFocus() let bitmapRep = NSBitmapImageRep(focusedViewRect: cropRect) image.unlockFocus() let croppedImage = NSImage(data: bitmapRep!.representationUsingType(.NSPNGFileType, properties: [:])!) cropPoint = cropRect.origin self.image = croppedImage } func scanRow(y: Int, width:Int, pointer: UnsafePointer<UInt8>) -> Bool { for var x = 0; x < width; x++ { if pointer[(x + y * width) * 4] != 0xff // only check red, could cause trouble { return true } } return false } func scanColumn(x: Int, height: Int, width: Int, pointer: UnsafePointer<UInt8>) -> Bool { for var y = 0; y < height; y++ { if pointer[(x + y * width) * 4] != 0xff // only check red { return true } } return false } }
mit
62043aa8eb9669ced7b54d0daef81641
31.332344
132
0.611417
4.587789
false
false
false
false
BBBInc/AlzPrevent-ios
researchline/AdditionWeightTableViewController.swift
1
4349
// // AdditionWeightTableViewController.swift // // Created by jknam on 2015. 11. 30.. // Copyright © 2015년 bbb. All rights reserved. // import UIKit class AdditionWeightTableViewController: UITableViewController { var weight = [Int]() var userWeight: Int = 60 var userWeightIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() userWeight = Constants.userDefaults.integerForKey("weight") if userWeight == 0 { userWeight = 60 } var index = 0 for i in 40...120 { if(userWeight == i){ userWeightIndex = index } weight.append(i) index += 1 } // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return weight.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("AdditionTableCell", forIndexPath: indexPath) cell.textLabel!.text = "\(self.weight[indexPath.row]) kg" // Configure the cell... return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let weight = self.weight[indexPath.row] Constants.userDefaults.setObject(weight, forKey: "weight") tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .Checkmark debugPrint("this indexPath is \(indexPath.row)") } override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .None } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
bsd-3-clause
d07921656e8bf8e047bceae41cbc8517
33.492063
157
0.664059
5.614987
false
false
false
false
LaszloPinter/CircleColorPicker
CircleColorPicker/ColorPicker/RainbowCircleView.swift
1
4087
//Copyright (c) 2017 Laszlo Pinter // //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 class RainbowCircleView: UIView { var rainbowImage: CGImage! var rainbowRadius: CGFloat = 100.0 { didSet{ setNeedsDisplay() } } var rainbowWidth: CGFloat = 8.0 { didSet{ setNeedsDisplay() } } override func layoutSubviews() { super.layoutSubviews() rainbowImage = drawColorCircleImage(withDiameter: Int(min(self.bounds.size.width, self.bounds.size.height))) } func drawColorCircleImage(withDiameter diameter: Int) -> CGImage { let bufferLength: Int = Int(diameter * diameter * 4) let bitmapData: CFMutableData = CFDataCreateMutable(nil, 0) CFDataSetLength(bitmapData, CFIndex(bufferLength)) let bitmap = CFDataGetMutableBytePtr(bitmapData) for y in 0 ... diameter { for x in 0 ... diameter { let angle = CGVector(point: CGPoint(x: x, y: diameter-y) - origo).angle let rgbComponents = UIColor.init(hue: getHue(at: angle), saturation: 1, brightness: 1, alpha: 1).cgColor.components! let offset = Int(4 * (x + y * diameter)) bitmap?[offset] = UInt8(rgbComponents[0]*255) bitmap?[offset + 1] = UInt8(rgbComponents[1]*255) bitmap?[offset + 2] = UInt8(rgbComponents[2]*255) bitmap?[offset + 3] = UInt8(255) } } let colorSpace: CGColorSpace? = CGColorSpaceCreateDeviceRGB() let dataProvider: CGDataProvider? = CGDataProvider(data: bitmapData) let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo().rawValue | CGImageAlphaInfo.last.rawValue) let imageRef: CGImage? = CGImage(width: diameter, height: diameter, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: diameter * 4, space: colorSpace!, bitmapInfo: bitmapInfo, provider: dataProvider!, decode: nil, shouldInterpolate: false, intent: CGColorRenderingIntent.defaultIntent) return imageRef! } override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } let circle = UIBezierPath(ovalIn: CGRect(x: origo.x - rainbowRadius, y: origo.y - rainbowRadius , width: rainbowRadius*2, height: rainbowRadius*2)) let shapeCopyPath = circle.cgPath.copy(strokingWithWidth: rainbowWidth, lineCap: .butt, lineJoin: .bevel, miterLimit: 0) context.addPath(shapeCopyPath) context.clip(using: .winding) context.draw(rainbowImage, in: self.bounds) context.resetClip() } var origo: CGPoint { get{ return CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2) } } func getHue(at radians: CGFloat) -> CGFloat { return ((radians.radiansToDegrees()+360).truncatingRemainder(dividingBy: 360))/360 } }
mit
f7a204e0139bacca161ee4df4b3819e9
41.572917
295
0.659897
4.551225
false
false
false
false
Arcovv/CleanArchitectureRxSwift
Domain/Entries/Company.swift
1
701
// // Company.swift // CleanArchitectureRxSwift // // Created by Andrey Yastrebov on 10.03.17. // Copyright © 2017 sergdort. All rights reserved. // import Foundation public struct Company { public let bs: String public let catchPhrase: String public let name: String public init(bs: String, catchPhrase: String, name: String) { self.bs = bs self.catchPhrase = catchPhrase self.name = name } } extension Company: Equatable { public static func == (lhs: Company, rhs: Company) -> Bool { return lhs.bs == rhs.bs && lhs.catchPhrase == rhs.catchPhrase && lhs.name == rhs.name } }
mit
78bde5c6e44f65deae507f16728179cf
21.580645
64
0.595714
4.166667
false
false
false
false
JGiola/swift-package-manager
Sources/Workspace/UserToolchain.swift
2
9777
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import POSIX import Basic import Build import PackageLoading import protocol Build.Toolchain import Utility #if os(macOS) private let whichArgs: [String] = ["xcrun", "--find"] #else private let whichArgs = ["which"] #endif /// Concrete object for manifest resource provider. public struct UserManifestResources: ManifestResourceProvider { public let swiftCompiler: AbsolutePath public let libDir: AbsolutePath public let sdkRoot: AbsolutePath? public init( swiftCompiler: AbsolutePath, libDir: AbsolutePath, sdkRoot: AbsolutePath? = nil ) { self.swiftCompiler = swiftCompiler self.libDir = libDir self.sdkRoot = sdkRoot } } // FIXME: This is messy and needs a redesign. public final class UserToolchain: Toolchain { /// The manifest resource provider. public let manifestResources: ManifestResourceProvider /// Path of the `swiftc` compiler. public let swiftCompiler: AbsolutePath public let extraCCFlags: [String] public let extraSwiftCFlags: [String] public var extraCPPFlags: [String] { return destination.extraCPPFlags } public var dynamicLibraryExtension: String { return destination.dynamicLibraryExtension } /// Path of the `swift` interpreter. public var swiftInterpreter: AbsolutePath { return swiftCompiler.parentDirectory.appending(component: "swift") } /// Path to the xctest utility. /// /// This is only present on macOS. public let xctest: AbsolutePath? /// Path to llbuild. public let llbuild: AbsolutePath /// The compilation destination object. public let destination: Destination /// Search paths from the PATH environment variable. let envSearchPaths: [AbsolutePath] /// Returns the runtime library for the given sanitizer. public func runtimeLibrary(for sanitizer: Sanitizer) throws -> AbsolutePath { // FIXME: This is only for SwiftPM development time support. It is OK // for now but we shouldn't need to resolve the symlink. We need to lay // down symlinks to runtimes in our fake toolchain as part of the // bootstrap script. let swiftCompiler = resolveSymlinks(self.swiftCompiler) let runtime = swiftCompiler.appending( RelativePath("../../lib/swift/clang/lib/darwin/libclang_rt.\(sanitizer.shortName)_osx_dynamic.dylib")) // Ensure that the runtime is present. guard localFileSystem.exists(runtime) else { throw InvalidToolchainDiagnostic("Missing runtime for \(sanitizer) sanitizer") } return runtime } /// Determines the Swift compiler paths for compilation and manifest parsing. private static func determineSwiftCompilers(binDir: AbsolutePath, lookup: (String) -> AbsolutePath?) throws -> (compile: AbsolutePath, manifest: AbsolutePath) { func validateCompiler(at path: AbsolutePath?) throws { guard let path = path else { return } guard localFileSystem.isExecutableFile(path) else { throw InvalidToolchainDiagnostic("could not find the `swiftc` at expected path \(path.asString)") } } // Get overrides. let SWIFT_EXEC_MANIFEST = lookup("SWIFT_EXEC_MANIFEST") let SWIFT_EXEC = lookup("SWIFT_EXEC") // Validate the overrides. try validateCompiler(at: SWIFT_EXEC) try validateCompiler(at: SWIFT_EXEC_MANIFEST) // We require there is at least one valid swift compiler, either in the // bin dir or SWIFT_EXEC. let resolvedBinDirCompiler: AbsolutePath let binDirCompiler = binDir.appending(component: "swiftc") if localFileSystem.isExecutableFile(binDirCompiler) { resolvedBinDirCompiler = binDirCompiler } else if let SWIFT_EXEC = SWIFT_EXEC { resolvedBinDirCompiler = SWIFT_EXEC } else { throw InvalidToolchainDiagnostic("could not find the `swiftc` at expected path \(binDirCompiler.asString)") } // The compiler for compilation tasks is SWIFT_EXEC or the bin dir compiler. // The compiler for manifest is either SWIFT_EXEC_MANIFEST or the bin dir compiler. return (SWIFT_EXEC ?? resolvedBinDirCompiler, SWIFT_EXEC_MANIFEST ?? resolvedBinDirCompiler) } private static func lookup(variable: String, searchPaths: [AbsolutePath]) -> AbsolutePath? { return lookupExecutablePath(filename: getenv(variable), searchPaths: searchPaths) } /// Environment to use when looking up tools. private let processEnvironment: [String: String] /// Returns the path to clang compiler tool. public func getClangCompiler() throws -> AbsolutePath { // Check if we already computed. if let clang = _clangCompiler { return clang } // Check in the environment variable first. if let toolPath = UserToolchain.lookup(variable: "CC", searchPaths: envSearchPaths) { _clangCompiler = toolPath return toolPath } // Otherwise, lookup the tool on the system. let arguments = whichArgs + ["clang"] let foundPath = try Process.checkNonZeroExit(arguments: arguments, environment: processEnvironment).spm_chomp() guard !foundPath.isEmpty else { throw InvalidToolchainDiagnostic("could not find clang") } let toolPath = try AbsolutePath(validating: foundPath) // If we found clang using xcrun, assume the vendor is Apple. // FIXME: This might not be the best way to determine this. #if os(macOS) __isClangCompilerVendorApple = true #endif _clangCompiler = toolPath return toolPath } private var _clangCompiler: AbsolutePath? private var __isClangCompilerVendorApple: Bool? public func _isClangCompilerVendorApple() throws -> Bool? { // The boolean gets computed as a side-effect of lookup for clang compiler. _ = try getClangCompiler() return __isClangCompilerVendorApple } /// Returns the path to llvm-cov tool. public func getLLVMCov() throws -> AbsolutePath { let toolPath = destination.binDir.appending(component: "llvm-cov") guard localFileSystem.isExecutableFile(toolPath) else { throw InvalidToolchainDiagnostic("could not find llvm-cov at expected path \(toolPath.asString)") } return toolPath } /// Returns the path to llvm-prof tool. public func getLLVMProf() throws -> AbsolutePath { let toolPath = destination.binDir.appending(component: "llvm-profdata") guard localFileSystem.isExecutableFile(toolPath) else { throw InvalidToolchainDiagnostic("could not find llvm-profdata at expected path \(toolPath.asString)") } return toolPath } public init(destination: Destination, environment: [String: String] = Process.env) throws { self.destination = destination self.processEnvironment = environment // Get the search paths from PATH. let searchPaths = getEnvSearchPaths( pathString: getenv("PATH"), currentWorkingDirectory: localFileSystem.currentWorkingDirectory) self.envSearchPaths = searchPaths // Get the binDir from destination. let binDir = destination.binDir let swiftCompilers = try UserToolchain.determineSwiftCompilers(binDir: binDir, lookup: { UserToolchain.lookup(variable: $0, searchPaths: searchPaths) }) self.swiftCompiler = swiftCompilers.compile // Look for llbuild in bin dir. llbuild = binDir.appending(component: "swift-build-tool") guard localFileSystem.exists(llbuild) else { throw InvalidToolchainDiagnostic("could not find `llbuild` at expected path \(llbuild.asString)") } // We require xctest to exist on macOS. #if os(macOS) // FIXME: We should have some general utility to find tools. let xctestFindArgs = ["xcrun", "--sdk", "macosx", "--find", "xctest"] self.xctest = try AbsolutePath(validating: Process.checkNonZeroExit(arguments: xctestFindArgs, environment: environment).spm_chomp()) #else self.xctest = nil #endif self.extraSwiftCFlags = [ "-sdk", destination.sdk.asString ] + destination.extraSwiftCFlags self.extraCCFlags = [ "--sysroot", destination.sdk.asString ] + destination.extraCCFlags // Compute the path of directory containing the PackageDescription libraries. var pdLibDir = binDir.parentDirectory.appending(components: "lib", "swift", "pm") // Look for an override in the env. if let pdLibDirEnvStr = getenv("SWIFTPM_PD_LIBS") { // We pick the first path which exists in a colon seperated list. let paths = pdLibDirEnvStr.split(separator: ":").map(String.init) for pathString in paths { if let path = try? AbsolutePath(validating: pathString), localFileSystem.exists(path) { pdLibDir = path break } } } manifestResources = UserManifestResources( swiftCompiler: swiftCompilers.manifest, libDir: pdLibDir, sdkRoot: self.destination.sdk ) } }
apache-2.0
78450a0c0724c2b1ea76deb8a14c4b39
36.603846
164
0.667485
5.076324
false
false
false
false
stunjiturner/Spring
SpringApp/CodeViewController.swift
2
2570
// // CodeViewController.swift // DesignerNewsApp // // Created by Meng To on 2015-01-05. // Copyright (c) 2015 Meng To. All rights reserved. // import UIKit import Spring class CodeViewController: UIViewController { @IBOutlet weak var modalView: SpringView! @IBOutlet weak var codeTextView: UITextView! @IBOutlet weak var titleLabel: UILabel! var codeText: String = "" var data: SpringView! override func viewDidLoad() { super.viewDidLoad() modalView.transform = CGAffineTransform(translationX: -300, y: 0) if data.animation != "" { codeText += "layer.animation = \"\(data.animation)\"\n" } if data.curve != "" { codeText += "layer.curve = \"\(data.curve)\"\n" } if data.force != 1 { codeText += String(format: "layer.force = %.1f\n", Double(data.force)) } if data.duration != 0.7 { codeText += String(format: "layer.duration = %.1f\n", Double(data.duration)) } if data.delay != 0 { codeText += String(format: "layer.delay = %.1f\n", Double(data.delay)) } if data.scaleX != 1 { codeText += String(format: "layer.scaleX = %.1f\n", Double(data.scaleX)) } if data.scaleY != 1 { codeText += String(format: "layer.scaleY = %.1f\n", Double(data.scaleY)) } if data.rotate != 0 { codeText += String(format: "layer.rotate = %.1f\n", Double(data.rotate)) } if data.damping != 0.7 { codeText += String(format: "layer.damping = %.1f\n", Double(data.damping)) } if data.velocity != 0.7 { codeText += String(format: "layer.velocity = %.1f\n", Double(data.velocity)) } codeText += "layer.animate()" codeTextView.text = codeText } @IBAction func closeButtonPressed(_ sender: AnyObject) { UIApplication.shared.sendAction(#selector(SpringViewController.maximizeView(_:)), to: nil, from: self, for: nil) modalView.animation = "slideRight" modalView.animateFrom = false modalView.animateToNext(completion: { self.dismiss(animated: false, completion: nil) }) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) modalView.animate() UIApplication.shared.sendAction(#selector(SpringViewController.minimizeView(_:)), to: nil, from: self, for: nil) } }
mit
19eb363eda6bb04feb7b1c64014e1b83
31.531646
120
0.567315
4.151858
false
false
false
false
mozilla-magnet/magnet-client
ios/RequestStoreSQLite.swift
1
2084
// // RequestStoreSQLite.swift // Magnet // // Created by Francisco Jordano on 01/11/2016. // Copyright © 2016 Mozilla. All rights reserved. // import Foundation import SQLite import SwiftyJSON class RequestStoreSQLite { private var db: Connection private let requestStore: Table = Table("requeststore") private let url: Expression<String> = Expression<String>("url") private let value: Expression<String> = Expression<String>("value") private let timestamp: Expression<Int64> = Expression<Int64>("timestamp") init() { let path = NSSearchPathForDirectoriesInDomains( .DocumentDirectory, .UserDomainMask, true ).first! db = try! Connection("\(path)/requeststore.sqlite3") try! db.run(requestStore.create(ifNotExists: true) { t in t.column(url, primaryKey: true) t.column(value) t.column(timestamp) }) } func clear() { try! db.run(requestStore.delete()) } func put(_url: String, _value: JSON, _timestamp: Int64?) { let stringValue = _value.rawString()! var time = Int64(NSDate().timeIntervalSince1970) if (_timestamp != nil) { time = _timestamp! } try! db.transaction(block: { let filteredResults = self.requestStore.filter(self.url == _url) if try! self.db.run(filteredResults.update(self.value <- stringValue, self.timestamp <- time)) > 0 { // Updated correctly } else { // Insert let insert = self.requestStore.insert(self.url <- _url, self.value <- stringValue, self.timestamp <- time) try! self.db.run(insert) } }) } func delete(_url: String) { let item = requestStore.filter(url == _url) try! db.run(item.delete()) } func get(_url: String) -> JSON? { let query = requestStore.filter(url == _url).limit(1) let result = Array(try! db.prepare(query)); guard result.count >= 1 else { return JSON([:]) } let jsonString: String = result[0][value] return JSON(data: jsonString.dataUsingEncoding(NSUTF8StringEncoding)!) } }
mpl-2.0
730af43460958c1d9e8d964032c96496
26.407895
114
0.636582
3.886194
false
false
false
false
rechsteiner/Parchment
Parchment/Classes/PageViewManager.swift
1
23916
import UIKit final class PageViewManager { weak var dataSource: PageViewManagerDataSource? weak var delegate: PageViewManagerDelegate? private(set) weak var previousViewController: UIViewController? private(set) weak var selectedViewController: UIViewController? private(set) weak var nextViewController: UIViewController? var state: PageViewState { if previousViewController == nil, nextViewController == nil, selectedViewController == nil { return .empty } else if previousViewController == nil, nextViewController == nil { return .single } else if nextViewController == nil { return .last } else if previousViewController == nil { return .first } else { return .center } } // MARK: - Private Properties private enum AppearanceState { case appearing(animated: Bool) case disappearing(animated: Bool) case disappeared case appeared } private var appearanceState: AppearanceState = .disappeared private var didReload: Bool = false private var didSelect: Bool = false private var initialDirection: PageViewDirection = .none // MARK: - Public Methods func select( viewController: UIViewController, direction: PageViewDirection = .none, animated: Bool = false ) { if state == .empty || animated == false { selectViewController(viewController, animated: animated) return } else { resetState() didSelect = true switch direction { case .forward, .none: if let nextViewController = nextViewController { delegate?.removeViewController(nextViewController) } delegate?.addViewController(viewController) nextViewController = viewController layoutsViews() delegate?.scrollForward() case .reverse: if let previousViewController = previousViewController { delegate?.removeViewController(previousViewController) } delegate?.addViewController(viewController) previousViewController = viewController layoutsViews() delegate?.scrollReverse() } } } func selectNext(animated: Bool) { if animated { resetState() delegate?.scrollForward() } else if let nextViewController = nextViewController, let selectedViewController = selectedViewController { beginAppearanceTransition(false, for: selectedViewController, animated: animated) beginAppearanceTransition(true, for: nextViewController, animated: animated) let newNextViewController = dataSource?.viewControllerAfter(nextViewController) if let previousViewController = previousViewController { delegate?.removeViewController(previousViewController) } if let newNextViewController = newNextViewController { delegate?.addViewController(newNextViewController) } previousViewController = selectedViewController self.selectedViewController = nextViewController self.nextViewController = newNextViewController layoutsViews() endAppearanceTransition(for: selectedViewController) endAppearanceTransition(for: nextViewController) } } func selectPrevious(animated: Bool) { if animated { resetState() delegate?.scrollReverse() } else if let previousViewController = previousViewController, let selectedViewController = selectedViewController { beginAppearanceTransition(false, for: selectedViewController, animated: animated) beginAppearanceTransition(true, for: previousViewController, animated: animated) let newPreviousViewController = dataSource?.viewControllerBefore(previousViewController) if let nextViewController = nextViewController { delegate?.removeViewController(nextViewController) } if let newPreviousViewController = newPreviousViewController { delegate?.addViewController(newPreviousViewController) } self.previousViewController = newPreviousViewController self.selectedViewController = previousViewController nextViewController = selectedViewController layoutsViews() endAppearanceTransition(for: selectedViewController) endAppearanceTransition(for: previousViewController) } } func removeAll() { let oldSelectedViewController = selectedViewController if let selectedViewController = oldSelectedViewController { beginAppearanceTransition(false, for: selectedViewController, animated: false) delegate?.removeViewController(selectedViewController) } if let previousViewController = previousViewController { delegate?.removeViewController(previousViewController) } if let nextViewController = nextViewController { delegate?.removeViewController(nextViewController) } previousViewController = nil selectedViewController = nil nextViewController = nil layoutsViews() if let oldSelectedViewController = oldSelectedViewController { endAppearanceTransition(for: oldSelectedViewController) } } func viewWillLayoutSubviews() { layoutsViews() } func viewWillAppear(_ animated: Bool) { appearanceState = .appearing(animated: animated) if let selectedViewController = selectedViewController { delegate?.beginAppearanceTransition( isAppearing: true, viewController: selectedViewController, animated: animated ) } switch state { case .center, .first, .last, .single: layoutsViews() case .empty: break } } func viewDidAppear(_: Bool) { appearanceState = .appeared if let selectedViewController = selectedViewController { delegate?.endAppearanceTransition(viewController: selectedViewController) } } func viewWillDisappear(_ animated: Bool) { appearanceState = .disappearing(animated: animated) if let selectedViewController = selectedViewController { delegate?.beginAppearanceTransition( isAppearing: false, viewController: selectedViewController, animated: animated ) } } func viewDidDisappear(_: Bool) { appearanceState = .disappeared if let selectedViewController = selectedViewController { delegate?.endAppearanceTransition(viewController: selectedViewController) } } func willBeginDragging() { resetState() } func willEndDragging() { resetState() } func viewWillTransitionSize() { layoutsViews(keepContentOffset: false) } func didScroll(progress: CGFloat) { let currentDirection = PageViewDirection(progress: progress) // MARK: Begin scrolling if initialDirection == .none { switch currentDirection { case .forward: initialDirection = .forward onScroll(progress: progress) willScrollForward() case .reverse: initialDirection = .reverse onScroll(progress: progress) willScrollReverse() case .none: onScroll(progress: progress) } } else { // Check if the transition changed direction in the middle of // the transactions. if didReload == false { switch (currentDirection, initialDirection) { case (.reverse, .forward): initialDirection = .reverse cancelScrollForward() onScroll(progress: progress) willScrollReverse() case (.forward, .reverse): initialDirection = .forward cancelScrollReverse() onScroll(progress: progress) willScrollForward() default: onScroll(progress: progress) } } else { onScroll(progress: progress) } } // MARK: Finished scrolling if didReload == false { if progress >= 1 { didReload = true didScrollForward() } else if progress <= -1 { didReload = true didScrollReverse() } else if progress == 0 { switch initialDirection { case .forward: didReload = true cancelScrollForward() case .reverse: didReload = true cancelScrollReverse() case .none: break } } } } // MARK: - Private Methods private func selectViewController(_ viewController: UIViewController, animated: Bool) { let oldSelectedViewController = selectedViewController let newPreviousViewController = dataSource?.viewControllerBefore(viewController) let newNextViewController = dataSource?.viewControllerAfter(viewController) if let oldSelectedViewController = oldSelectedViewController { beginAppearanceTransition(false, for: oldSelectedViewController, animated: animated) } if viewController !== selectedViewController { beginAppearanceTransition(true, for: viewController, animated: animated) } if let oldPreviosViewController = previousViewController { if oldPreviosViewController !== viewController, oldPreviosViewController !== newPreviousViewController, oldPreviosViewController !== newNextViewController { delegate?.removeViewController(oldPreviosViewController) } } if let oldSelectedViewController = selectedViewController { if oldSelectedViewController !== newPreviousViewController, oldSelectedViewController !== newNextViewController { delegate?.removeViewController(oldSelectedViewController) } } if let oldNextViewController = nextViewController { if oldNextViewController !== viewController, oldNextViewController !== newPreviousViewController, oldNextViewController !== newNextViewController { delegate?.removeViewController(oldNextViewController) } } if let newPreviousViewController = newPreviousViewController { if newPreviousViewController !== selectedViewController, newPreviousViewController !== previousViewController, newPreviousViewController !== nextViewController { delegate?.addViewController(newPreviousViewController) } } if viewController !== nextViewController, viewController !== previousViewController { delegate?.addViewController(viewController) } if let newNextViewController = newNextViewController { if newNextViewController !== selectedViewController, newNextViewController !== previousViewController, newNextViewController !== nextViewController { delegate?.addViewController(newNextViewController) } } previousViewController = newPreviousViewController selectedViewController = viewController nextViewController = newNextViewController layoutsViews() if let oldSelectedViewController = oldSelectedViewController { endAppearanceTransition(for: oldSelectedViewController) } if viewController !== oldSelectedViewController { endAppearanceTransition(for: viewController) } } private func resetState() { if didReload { initialDirection = .none } didReload = false } private func onScroll(progress: CGFloat) { // This means we are overshooting, so we need to continue // reporting the old view controllers. if didReload { switch initialDirection { case .forward: if let previousViewController = previousViewController, let selectedViewController = selectedViewController { delegate?.isScrolling( from: previousViewController, to: selectedViewController, progress: progress ) } case .reverse: if let nextViewController = nextViewController, let selectedViewController = selectedViewController { delegate?.isScrolling( from: nextViewController, to: selectedViewController, progress: progress ) } case .none: break } } else { // Report progress as normally switch initialDirection { case .forward: if let selectedViewController = selectedViewController { delegate?.isScrolling( from: selectedViewController, to: nextViewController, progress: progress ) } case .reverse: if let selectedViewController = selectedViewController { delegate?.isScrolling( from: selectedViewController, to: previousViewController, progress: progress ) } case .none: break } } } private func cancelScrollForward() { guard let selectedViewController = selectedViewController else { return } let oldNextViewController = nextViewController if let nextViewController = oldNextViewController { beginAppearanceTransition(true, for: selectedViewController, animated: true) beginAppearanceTransition(false, for: nextViewController, animated: true) } if didSelect { let newNextViewController = dataSource?.viewControllerAfter(selectedViewController) if let oldNextViewController = oldNextViewController { delegate?.removeViewController(oldNextViewController) } if let newNextViewController = newNextViewController { delegate?.addViewController(newNextViewController) } nextViewController = newNextViewController didSelect = false layoutsViews() } if let oldNextViewController = oldNextViewController { endAppearanceTransition(for: selectedViewController) endAppearanceTransition(for: oldNextViewController) delegate?.didFinishScrolling( from: selectedViewController, to: oldNextViewController, transitionSuccessful: false ) } } private func cancelScrollReverse() { guard let selectedViewController = selectedViewController else { return } let oldPreviousViewController = previousViewController if let previousViewController = oldPreviousViewController { beginAppearanceTransition(true, for: selectedViewController, animated: true) beginAppearanceTransition(false, for: previousViewController, animated: true) } if didSelect { let newPreviousViewController = dataSource?.viewControllerBefore(selectedViewController) if let oldPreviousViewController = oldPreviousViewController { delegate?.removeViewController(oldPreviousViewController) } if let newPreviousViewController = newPreviousViewController { delegate?.addViewController(newPreviousViewController) } previousViewController = newPreviousViewController didSelect = false layoutsViews() } if let oldPreviousViewController = oldPreviousViewController { endAppearanceTransition(for: selectedViewController) endAppearanceTransition(for: oldPreviousViewController) delegate?.didFinishScrolling( from: selectedViewController, to: oldPreviousViewController, transitionSuccessful: false ) } } private func willScrollForward() { if let selectedViewController = selectedViewController, let nextViewController = nextViewController { delegate?.willScroll(from: selectedViewController, to: nextViewController) beginAppearanceTransition(true, for: nextViewController, animated: true) beginAppearanceTransition(false, for: selectedViewController, animated: true) } } private func willScrollReverse() { if let selectedViewController = selectedViewController, let previousViewController = previousViewController { delegate?.willScroll(from: selectedViewController, to: previousViewController) beginAppearanceTransition(true, for: previousViewController, animated: true) beginAppearanceTransition(false, for: selectedViewController, animated: true) } } private func didScrollForward() { guard let oldSelectedViewController = selectedViewController, let oldNextViewController = nextViewController else { return } delegate?.didFinishScrolling( from: oldSelectedViewController, to: oldNextViewController, transitionSuccessful: true ) let newNextViewController = dataSource?.viewControllerAfter(oldNextViewController) if let oldPreviousViewController = previousViewController { if oldPreviousViewController !== newNextViewController { delegate?.removeViewController(oldPreviousViewController) } } if let newNextViewController = newNextViewController { if newNextViewController !== previousViewController { delegate?.addViewController(newNextViewController) } } if didSelect { let newPreviousViewController = dataSource?.viewControllerBefore(oldNextViewController) if let oldSelectedViewController = selectedViewController { delegate?.removeViewController(oldSelectedViewController) } if let newPreviousViewController = newPreviousViewController { delegate?.addViewController(newPreviousViewController) } previousViewController = newPreviousViewController didSelect = false } else { previousViewController = oldSelectedViewController } selectedViewController = oldNextViewController nextViewController = newNextViewController layoutsViews() endAppearanceTransition(for: oldSelectedViewController) endAppearanceTransition(for: oldNextViewController) } private func didScrollReverse() { guard let oldSelectedViewController = selectedViewController, let oldPreviousViewController = previousViewController else { return } delegate?.didFinishScrolling( from: oldSelectedViewController, to: oldPreviousViewController, transitionSuccessful: true ) let newPreviousViewController = dataSource?.viewControllerBefore(oldPreviousViewController) if let oldNextViewController = nextViewController { if oldNextViewController !== newPreviousViewController { delegate?.removeViewController(oldNextViewController) } } if let newPreviousViewController = newPreviousViewController { if newPreviousViewController !== nextViewController { delegate?.addViewController(newPreviousViewController) } } if didSelect { let newNextViewController = dataSource?.viewControllerAfter(oldPreviousViewController) if let oldSelectedViewController = selectedViewController { delegate?.removeViewController(oldSelectedViewController) } if let newNextViewController = newNextViewController { delegate?.addViewController(newNextViewController) } nextViewController = newNextViewController didSelect = false } else { nextViewController = oldSelectedViewController } previousViewController = newPreviousViewController selectedViewController = oldPreviousViewController layoutsViews() endAppearanceTransition(for: oldSelectedViewController) endAppearanceTransition(for: oldPreviousViewController) } private func layoutsViews(keepContentOffset: Bool = true) { var viewControllers: [UIViewController] = [] if let previousViewController = previousViewController { viewControllers.append(previousViewController) } if let selectedViewController = selectedViewController { viewControllers.append(selectedViewController) } if let nextViewController = nextViewController { viewControllers.append(nextViewController) } delegate?.layoutViews(for: viewControllers, keepContentOffset: keepContentOffset) } private func beginAppearanceTransition( _ isAppearing: Bool, for viewController: UIViewController, animated: Bool ) { switch appearanceState { case .appeared: delegate?.beginAppearanceTransition( isAppearing: isAppearing, viewController: viewController, animated: animated ) case let .appearing(animated): // Override the given animated flag with the animated flag of // the parent views appearance transition. delegate?.beginAppearanceTransition( isAppearing: isAppearing, viewController: viewController, animated: animated ) case let .disappearing(animated): // When the parent view is about to disappear we always set // isAppearing to false. delegate?.beginAppearanceTransition( isAppearing: false, viewController: viewController, animated: animated ) default: break } } private func endAppearanceTransition(for viewController: UIViewController) { guard case .appeared = appearanceState else { return } delegate?.endAppearanceTransition(viewController: viewController) } }
mit
d034f9085021cc3726467913e419c008
36.021672
100
0.618205
7.903503
false
false
false
false
ZackKingS/Tasks
task/Classes/Others/Lib/TakePhoto/PhotoPickerConfig.swift
2
1146
// // PhotoPickerConfig.swift // PhotoPicker // // Created by liangqi on 16/3/6. // Copyright © 2016年 dailyios. All rights reserved. // import Foundation import UIKit class PhotoPickerConfig { // tableView Cell height static let AlbumTableViewCellHeight: CGFloat = 90.0 // message when select number more than the max number static let ErrorImageMaxSelect = "图片选择最多超过不能超过#张" // button confirm title static let ButtonConfirmTitle = "确定" // button secelt image done title static let ButtonDone = "完成" // preview view bar background color static let PreviewBarBackgroundColor = UIColor(red: 40/255, green: 40/255, blue: 40/255, alpha: 1) // button green tin color static let GreenTinColor = UIColor(red: 7/255, green: 179/255, blue: 20/255, alpha: 1) // image total per line static let ColNumber: CGFloat = 4 // collceiont cell padding static let MinimumInteritemSpacing: CGFloat = 5 // fethch single large image max width static let PreviewImageMaxFetchMaxWidth:CGFloat = 600 }
apache-2.0
1d725c58a90c891255de3d42064bbbb6
25.428571
102
0.674482
4.092251
false
false
false
false
victorchee/DynamicCollectionView
BookCollectionView/BookCollectionView/BookStoreLayout.swift
2
2735
// // BookStoreLayout.swift // BookCollectionView // // Created by qihaijun on 11/30/15. // Copyright © 2015 VictorChee. All rights reserved. // import UIKit class BookStoreLayout: UICollectionViewFlowLayout { fileprivate let pageSize = CGSize(width: 300, height: 500) required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) scrollDirection = .horizontal itemSize = pageSize minimumInteritemSpacing = 10.0 } override func prepare() { super.prepare() collectionView?.decelerationRate = UIScrollViewDecelerationRateFast collectionView?.contentInset = UIEdgeInsets(top: 0, left: collectionView!.bounds.width / 2.0 - pageSize.width / 2.0, bottom: 0, right: collectionView!.bounds.width / 2.0 - pageSize.width / 2.0) } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let attributes = super.layoutAttributesForElements(in: rect) var copedAttributes = [UICollectionViewLayoutAttributes]() if let attributes = attributes { for attribute in attributes { let copyedAttribute = attribute.copy() as! UICollectionViewLayoutAttributes let frame = attribute.frame let distance = abs(collectionView!.contentOffset.x + collectionView!.contentInset.left - frame.origin.x) // 封面与屏幕中心的距离 let scale = 0.7 * min(max(1 - distance / collectionView!.bounds.width, 0.75), 1) copyedAttribute.transform = CGAffineTransform(scaleX: scale, y: scale) copedAttributes.append(copyedAttribute) } } return copedAttributes } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { // snap cells to centre let layout = collectionView!.collectionViewLayout as! UICollectionViewFlowLayout let width = layout.itemSize.width + layout.minimumLineSpacing var offset = proposedContentOffset.x + collectionView!.contentInset.left if velocity.x > 0 { // 右滑 offset = width * ceil(offset / width) } else if velocity.x == 0 { // 滑动距离不够,保持不变 offset = width * round(offset / width) } else { // 左滑 offset = width * floor(offset / width) } return CGPoint(x: offset - collectionView!.contentInset.left, y: proposedContentOffset.y) } }
mit
8d182fded410a93fcc0c81a4dfa3cd41
40.292308
201
0.650894
5.141762
false
false
false
false
cpk1/fastlane
fastlane/swift/SocketResponse.swift
1
3034
// SocketResponse.swift // Copyright (c) 2021 FastlaneTools // // ** NOTE ** // This file is provided by fastlane and WILL be overwritten in future updates // If you want to add extra functionality to this project, create a new file in a // new group so that it won't be marked for upgrade // import Foundation struct SocketResponse { enum ResponseType { case parseFailure(failureInformation: [String]) case failure(failureInformation: [String]) case readyForNext(returnedObject: String?, closureArgumentValue: String?) case clientInitiatedCancel init(statusDictionary: [String: Any]) { guard let status = statusDictionary["status"] as? String else { self = .parseFailure(failureInformation: ["Message failed to parse from Ruby server"]) return } if status == "ready_for_next" { verbose(message: "ready for next") let returnedObject = statusDictionary["return_object"] as? String let closureArgumentValue = statusDictionary["closure_argument_value"] as? String self = .readyForNext(returnedObject: returnedObject, closureArgumentValue: closureArgumentValue) return } else if status == "cancelled" { self = .clientInitiatedCancel return } else if status == "failure" { guard let failureInformation = statusDictionary["failure_information"] as? [String] else { self = .parseFailure(failureInformation: ["Ruby server indicated failure but Swift couldn't receive it"]) return } self = .failure(failureInformation: failureInformation) return } self = .parseFailure(failureInformation: ["Message status: \(status) not a supported status"]) } } let responseType: ResponseType init(payload: String) { guard let data = SocketResponse.convertToDictionary(text: payload) else { responseType = .parseFailure(failureInformation: ["Unable to parse message from Ruby server"]) return } guard case let statusDictionary? = data["payload"] as? [String: Any] else { responseType = .parseFailure(failureInformation: ["Payload missing from Ruby server response"]) return } responseType = ResponseType(statusDictionary: statusDictionary) } } extension SocketResponse { static func convertToDictionary(text: String) -> [String: Any]? { if let data = text.data(using: .utf8) { do { return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] } catch { log(message: error.localizedDescription) } } return nil } } // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.2]
mit
0849900eaaa45cb0fb0e47e9d23c7634
36
125
0.616348
5.285714
false
false
false
false
AnthonyMDev/QueryGenie
QueryGenie/CoreData/Table.swift
1
2322
// // Table.swift // // Created by Anthony Miller on 1/4/17. // import Foundation import CoreData // A concrete query that can be executed to fetch a collection of core data objects. public struct Table<T: NSManagedObject>: TableProtocol { public typealias Element = T public let context: NSManagedObjectContext public let entityDescription: NSEntityDescription public var offset: Int = 0 public var limit: Int = 0 public var batchSize: Int = 20 public var predicate: NSPredicate? = nil public var sortDescriptors: [NSSortDescriptor]? = nil public init(context: NSManagedObjectContext) { self.context = context self.entityDescription = context.persistentStoreCoordinator! .cachedEntityDescription(for: context, managedObjectType: T.self) } } // MARK: - CachedEntityDescriptions extension NSPersistentStoreCoordinator { private struct AssociatedKeys { static var CachedEntityDescriptions = "QueryGenie_cachedEntityDescriptions" } private var cachedEntityDescriptions: [String : NSEntityDescription] { get { return objc_getAssociatedObject(self, &AssociatedKeys.CachedEntityDescriptions) as? [String : NSEntityDescription] ?? [:] } set { objc_setAssociatedObject( self, &AssociatedKeys.CachedEntityDescriptions, newValue as NSDictionary?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } fileprivate func cachedEntityDescription(for context: NSManagedObjectContext, managedObjectType: NSManagedObject.Type) -> NSEntityDescription { let dataContextClassName = String(describing: type(of: context)) let managedObjectClassName = String(describing: managedObjectType) let cacheKey = "\(dataContextClassName)|\(managedObjectClassName)" let entityDescription: NSEntityDescription if let cachedEntityDescription = cachedEntityDescriptions[cacheKey] { entityDescription = cachedEntityDescription } else { entityDescription = managedObjectModel.entities .filter({ $0.managedObjectClassName.components(separatedBy: ".").last! == managedObjectClassName }) .first! cachedEntityDescriptions[cacheKey] = entityDescription } return entityDescription } }
mit
fb8695b6593b986cfe5ea785434e9445
27.666667
145
0.711886
5.581731
false
false
false
false
Olinguito/YoIntervengoiOS
Yo Intervengo/Views/Login/SignIn.swift
1
1681
// // SignIn.swift // Yo Intervengo // // Created by Jorge Raul Ovalle Zuleta on 2/12/15. // Copyright (c) 2015 Olinguito. All rights reserved. // import UIKit class SignIn: UIViewController { @IBOutlet weak var txtEmail: JOTextField! @IBOutlet weak var btnLogin: UIButton! @IBOutlet weak var btnForget: UIButton! @IBOutlet weak var txtPass: JOTextField! @IBOutlet weak var bg: UIView! var singleTap:UIGestureRecognizer! override func viewDidLoad() { super.viewDidLoad() var myMutableString = NSMutableAttributedString(string: "¡OOPS! OLIVIDÉ MI CONTRASEÑA", attributes: [NSFontAttributeName:UIFont(name: "Roboto-Light", size: 12.5)!]) myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greyDark(), range: NSRange(location:0,length:18)) myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.orangeYI(), range: NSRange(location:18,length:10)) btnForget.titleLabel?.textAlignment = NSTextAlignment.Center btnForget.setAttributedTitle(myMutableString, forState: .Normal) btnLogin.layer.cornerRadius = 5 btnLogin.titleLabel?.font = UIFont(name: "Roboto-Light", size: 16) singleTap = UITapGestureRecognizer(target: self, action: Selector("singleTap:")) self.view.addGestureRecognizer(singleTap) bg.addGestureRecognizer(singleTap) } func singleTap(sender:UITapGestureRecognizer){ txtEmail.resignFirstResponder() txtPass.resignFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
85b5b053887ceac390cca6f12801b298
35.478261
172
0.702026
4.726761
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Core/Managers/ThemeManager.swift
1
6341
import Foundation import MLUI class ThemeManager { static let shared = ThemeManager() fileprivate var currentTheme: PXTheme = PXDefaultTheme(withPrimaryColor: #colorLiteral(red: 0.2196078431, green: 0.5411764706, blue: 0.8156862745, alpha: 1)) { didSet { initialize() } } fileprivate var currentStylesheet = MLStyleSheetManager.styleSheet fileprivate var fontName: String = ".SFUIDisplay-Regular" fileprivate var fontLightName: String = ".SFUIDisplay-Light" fileprivate var fontSemiBoldName: String = ".SFUIDisplay-SemiBold" var navigationControllerMemento: NavigationControllerMemento? } // MARK: - Public methods extension ThemeManager { func initialize() { currentStylesheet = MLStyleSheetManager.styleSheet customizeNavigationBar(theme: currentTheme) customizeToolBar() } func setDefaultColor(color: UIColor) { let customTheme = PXDefaultTheme(withPrimaryColor: color) let customStyleSheet = PXDefaultMLStyleSheet(withPrimaryColor: color) MLStyleSheetManager.styleSheet = customStyleSheet self.currentTheme = customTheme } func setTheme(theme: PXTheme) { self.currentTheme = theme if let externalFont = theme.fontName?() { fontName = externalFont } if let externalLightFont = theme.lightFontName?() { fontLightName = externalLightFont } if let externalSemiBoldFont = theme.semiBoldFontName?() { fontSemiBoldName = externalSemiBoldFont } } func getCurrentTheme() -> PXTheme { return currentTheme } func getFontName() -> String { return fontName } func getLightFontName() -> String { return fontLightName } func getSemiBoldFontName() -> String { return fontSemiBoldName } } extension ThemeManager { func boldLabelTintColor() -> UIColor { return currentStylesheet.blackColor } func labelTintColor() -> UIColor { return currentStylesheet.darkGreyColor } func midLabelTintColor() -> UIColor { return currentStylesheet.midGreyColor } func lightTintColor() -> UIColor { return currentStylesheet.lightGreyColor } func greyColor() -> UIColor { return currentStylesheet.greyColor } func whiteColor() -> UIColor { return currentStylesheet.whiteColor } func successColor() -> UIColor { return currentStylesheet.successColor } func remedyWarningColor() -> UIColor { return #colorLiteral(red: 1, green: 0.4663783312, blue: 0.2018467486, alpha: 1) // currentStylesheet.warningColor } func warningColor() -> UIColor { return currentStylesheet.warningColor } func rejectedColor() -> UIColor { return currentStylesheet.errorColor } func secondaryColor() -> UIColor { return currentStylesheet.secondaryColor } func placeHolderColor() -> UIColor { return #colorLiteral(red: 0.8, green: 0.8, blue: 0.8, alpha: 1) } func iconBackgroundColor() -> UIColor { return #colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9411764706, alpha: 1) } func noTaxAndDiscountLabelTintColor() -> UIColor { return #colorLiteral(red: 0, green: 0.6509803922, blue: 0.3137254902, alpha: 1) } func discountBriefColorML() -> UIColor { return #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.45) } func discountBriefColorMP() -> UIColor { return UIColor.white.withAlphaComponent(0.8) } func disabledCardGray() -> UIColor { return #colorLiteral(red: 0.2862745098, green: 0.2862745098, blue: 0.2862745098, alpha: 1) } } // MARK: - UI design exceptions extension ThemeManager: PXTheme { func navigationBar() -> PXThemeProperty { return currentTheme.navigationBar() } func loadingComponent() -> PXThemeProperty { return currentTheme.loadingComponent() } func highlightBackgroundColor() -> UIColor { return currentTheme.highlightBackgroundColor() } func detailedBackgroundColor() -> UIColor { return currentTheme.detailedBackgroundColor() } func statusBarStyle() -> UIStatusBarStyle { return currentTheme.statusBarStyle() } func getMainColor() -> UIColor { if let theme = currentTheme as? PXDefaultTheme { return theme.primaryColor } return currentTheme.navigationBar().backgroundColor } func getAccentColor() -> UIColor { if let theme = currentTheme as? PXDefaultTheme { return theme.primaryColor } return currentStylesheet.secondaryColor } func getTintColorForIcons() -> UIColor? { if currentTheme is PXDefaultTheme { return getMainColor() } return nil } func getTitleColorForReviewConfirmNavigation() -> UIColor { if currentTheme is PXDefaultTheme { return getMainColor() } if let highlightNavigationTint = currentTheme.highlightNavigationTintColor?() { return highlightNavigationTint } return boldLabelTintColor() } func modalComponent() -> PXThemeProperty { return PXThemeProperty(backgroundColor: currentStylesheet.modalBackgroundColor, tintColor: currentStylesheet.modalTintColor) } } // MARK: - UI Theme customization extension ThemeManager { fileprivate func customizeNavigationBar(theme: PXTheme) { UINavigationBar.appearance(whenContainedInInstancesOf: [MercadoPagoUIViewController.self]).tintColor = theme.navigationBar().tintColor UINavigationBar.appearance(whenContainedInInstancesOf: [MercadoPagoUIViewController.self]).backgroundColor = theme.navigationBar().backgroundColor UIBarButtonItem.appearance(whenContainedInInstancesOf: [MercadoPagoUIViewController.self]).tintColor = theme.navigationBar().tintColor PXNavigationHeaderLabel.appearance().textColor = theme.navigationBar().tintColor } fileprivate func customizeToolBar() { PXToolbar.appearance().tintColor = getAccentColor() PXToolbar.appearance().backgroundColor = lightTintColor() PXToolbar.appearance().alpha = 1 } }
mit
0769e6643e3bbd65409a9233d3f4b9c5
29.195238
163
0.674972
5.240496
false
false
false
false
rob5408/Extensions
Extensions/UIViewControllerExtensions.swift
1
4141
import UIKit extension UIViewController { public func simpleBackButton() { self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) } public func presentViewControllerNow(viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) { self.present( viewControllerToPresent, animated: flag, completion: completion) // http://stackoverflow.com/a/30787046 CFRunLoopWakeUp(CFRunLoopGetCurrent()) } // let alertController = UIAlertController( // title: NSLocalizedString("Spot Award In Progress", comment: ""), // message: NSLocalizedString("Would you like to continue with the spot award or delete it and start over?", comment: ""), // preferredStyle: .Alert) // // let continueAction = UIAlertAction(title: NSLocalizedString("Continue", comment: ""), style: .Default) { (_) in // self.openRecognition(recognition: savedSpotAward) // } // // let startOverAction = UIAlertAction(title: NSLocalizedString("Start over", comment: ""), style: .Default) { (_) in // self.openRecognition() // } // // alertController.addAction(continueAction) // alertController.addAction(startOverAction) // // self.actionMenuViewController?.presentViewController(alertController, animated: true) { // } public func applyConstraintsImmediately() { // http://stackoverflow.com/a/13542580 self.view.setNeedsLayout() self.view.layoutIfNeeded() } public func alert(title title: String? = nil, message message: String? = nil, ok okAlertAction: UIAlertAction? = nil) -> UIAlertController { let useTitle = title ?? Bundle.main.infoDictionary?[kCFBundleNameKey as String] as? String ?? "" let alertController = UIAlertController( title: useTitle, message: message, preferredStyle: .alert) if let okAlertAction = okAlertAction { alertController.addAction(okAlertAction) } else { let okAlertAction = UIAlertAction( title: NSLocalizedString("Ok", comment: ""), style: .default, handler: nil) alertController.addAction(okAlertAction) } self.presentViewControllerNow( viewControllerToPresent: alertController, animated: true, completion: nil) return alertController } public func alertWithError(error: Error?) { self.alert(message: error?.localizedDescription) } public func confirm(title title: String? = nil, message message: String = "", ifOk okAlertAction: UIAlertAction? = nil, ifCancel cancelAlertAction: UIAlertAction? = nil) -> UIAlertController { let useTitle = title ?? Bundle.main.infoDictionary?[kCFBundleNameKey as String] as? String ?? "" let alertController = UIAlertController( title: useTitle, message: message, preferredStyle: .alert) if let okAlertAction = okAlertAction { alertController.addAction(okAlertAction) } else { let okAlertAction = UIAlertAction( title: NSLocalizedString("Ok", comment: ""), style: .default, handler: nil) alertController.addAction(okAlertAction) } if let cancelAlertAction = cancelAlertAction { alertController.addAction(cancelAlertAction) } else { let cancelAlertAction = UIAlertAction( title: NSLocalizedString("Cancel", comment: ""), style: .default, handler: nil) alertController.addAction(cancelAlertAction) } self.presentViewControllerNow( viewControllerToPresent: alertController, animated: true, completion: nil) return alertController } }
mit
e7e214775ac3c1209a73f94763a4a9a4
35.324561
196
0.6071
5.521333
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift
54
3618
// // CurrentThreadScheduler.swift // RxSwift // // Created by Krunoslav Zaher on 8/30/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import Dispatch let CurrentThreadSchedulerKeyInstance = "RxSwift.CurrentThreadScheduler.SchedulerKey" let CurrentThreadSchedulerQueueKeyInstance = "RxSwift.CurrentThreadScheduler.Queue" typealias CurrentThreadSchedulerValue = NSString let CurrentThreadSchedulerValueInstance = "RxSwift.CurrentThreadScheduler.SchedulerKey" as NSString /// Represents an object that schedules units of work on the current thread. /// /// This is the default scheduler for operators that generate elements. /// /// This scheduler is also sometimes called `trampoline scheduler`. public class CurrentThreadScheduler : ImmediateSchedulerType { typealias ScheduleQueue = RxMutableBox<Queue<ScheduledItemType>> /// The singleton instance of the current thread scheduler. public static let instance = CurrentThreadScheduler() static var queue : ScheduleQueue? { get { return Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerQueueKeyInstance) } set { Thread.setThreadLocalStorageValue(newValue, forKey: CurrentThreadSchedulerQueueKeyInstance) } } /// Gets a value that indicates whether the caller must call a `schedule` method. public static fileprivate(set) var isScheduleRequired: Bool { get { let value: CurrentThreadSchedulerValue? = Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerKeyInstance) return value == nil } set(isScheduleRequired) { Thread.setThreadLocalStorageValue(isScheduleRequired ? nil : CurrentThreadSchedulerValueInstance, forKey: CurrentThreadSchedulerKeyInstance) } } /** Schedules an action to be executed as soon as possible on current thread. If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be automatically installed and uninstalled after all work is performed. - parameter state: State passed to the action to be executed. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { if CurrentThreadScheduler.isScheduleRequired { CurrentThreadScheduler.isScheduleRequired = false let disposable = action(state) defer { CurrentThreadScheduler.isScheduleRequired = true CurrentThreadScheduler.queue = nil } guard let queue = CurrentThreadScheduler.queue else { return disposable } while let latest = queue.value.dequeue() { if latest.isDisposed { continue } latest.invoke() } return disposable } let existingQueue = CurrentThreadScheduler.queue let queue: RxMutableBox<Queue<ScheduledItemType>> if let existingQueue = existingQueue { queue = existingQueue } else { queue = RxMutableBox(Queue<ScheduledItemType>(capacity: 1)) CurrentThreadScheduler.queue = queue } let scheduledItem = ScheduledItem(action: action, state: state) queue.value.enqueue(scheduledItem) return scheduledItem } }
apache-2.0
fdf999cb0bfbffda765e719ecb1f7526
34.811881
152
0.683992
6.018303
false
false
false
false
tachi0327/SimpleTimer
DEMO/DEMO/SimpleTimer.swift
1
1688
// // SimpleTimer.swift // DEMO // // Created by yuichiro tachibana on 2017/05/13. // Copyright © 2017年 yuichiro tachibana. All rights reserved. // import Foundation public final class SimpleTimer:SimpleTimerType{ //Properties private weak var _timer:Timer? private var _elapsedTime:Int private let _timeInterval:TimeInterval public var elapsedTime:Int{ return _elapsedTime } public var seconds:Int{ return _elapsedTime % Int(TimerConstant.TIME_DIVISER_60) } public var minutes:Int { return (_elapsedTime % TimerConstant.TIME_DIVISER_3600) / TimerConstant.TIME_DIVISER_60 } public var hours:Int{ return _elapsedTime / TimerConstant.TIME_DIVISER_3600 } /// Create a count up timer. /// /// カウントアップタイマーを生成する。 /// - Parameter timeInterval : The time interval to count up. カウントアップの時間間隔 public init(timeInterval:TimeInterval){ _elapsedTime = 0 _timeInterval = timeInterval } public func start()->Void{ let isValid = _timer?.isValid ?? Bool?(false) if !isValid! { _timer = Timer.scheduledTimer(withTimeInterval: _timeInterval, repeats: true, block: update) } } public func stop()->Void{ _timer?.invalidate() } public func reset()->Void{ _timer?.invalidate() _elapsedTime = 0 } private func update(_ tic:Timer){ _elapsedTime += Int(_timeInterval) print("\(hours)時間 \(minutes)分 \(seconds)秒") } deinit { _timer?.invalidate() } }
mit
8e25bc4a926620b3ebbcd0db8997d1ac
23.907692
104
0.6084
4.151282
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Requests/BatchFollow/BatchFollowRequest.swift
1
2034
// // BatchFollowRequest.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // 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 BatchFollowRequest: Request { override var method: RequestMethod { return .post } override var endpoint: String { return "batch_follow" } override var parameters: Dictionary<String, AnyObject> { return prepareParameters() } fileprivate let idsToFollow: [String] init(idsToFollow: [String]) { self.idsToFollow = idsToFollow } fileprivate func prepareParameters() -> Dictionary<String, AnyObject> { var dataDict = Dictionary<String, AnyObject>() var attributesDict = Dictionary<String, AnyObject>() attributesDict["user_ids"] = self.idsToFollow as AnyObject dataDict["attributes"] = attributesDict as AnyObject? dataDict["type"] = "followings" as AnyObject return ["data": dataDict as AnyObject] } }
mit
b22edb018d2d729c80940945588eced8
40.510204
89
0.716323
4.633257
false
false
false
false
sabyapradhan/IBM-Ready-App-for-Banking
HatchReadyApp/apps/Hatch/iphone/native/Hatch/DataSources/TransactionsDataManager.swift
1
5932
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import Foundation /** * A shared resource manager for obtaining Transactions for a specific account from MobileFirst Platform */ public class TransactionsDataManager: NSObject { // Callback function that will execute after the call returns var callback : ((Bool, [TransactionDay]!)->())! /// The id of the account the call is for var accountID: String! // Class variable that will return a singleton when requested public class var sharedInstance : TransactionsDataManager{ struct Singleton { static let instance = TransactionsDataManager() } return Singleton.instance } /** Calls the MobileFirst Platform server and passes the accountID :param: accountID ID of the account to get the transactions for :param: callback Callback to determine success */ func getTransactions(accountID: String, callback: ((Bool, [TransactionDay]!)->())!){ self.callback = callback self.accountID = accountID let adapterName : String = "SBBAdapter" let procedureName : String = "getTransactions" let caller = WLProcedureCaller(adapterName : adapterName, procedureName: procedureName) let params = [accountID] caller.invokeWithResponse(self, params: params) } /** Method that is fired when a retry is attempted for dashboard data. */ func retryGetTransactions(){ getTransactions(accountID, callback: callback) } /** Parses MobileFirst Platform's response and returns an array of transaction objects. :param: worklightResponseJson JSON response from MobileFirst Platform with Dashboard data. :returns: Array of account objects. */ func parseTransactionsResponse(worklightResponseJson: NSDictionary) -> [TransactionDay]{ let transactionJsonString = worklightResponseJson["result"] as! String let data = transactionJsonString.dataUsingEncoding(NSUTF8StringEncoding) let transactionJsonArray = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(0), error: nil) as! [AnyObject] var transactionDays: [TransactionDay] = [] var transactions: [Transaction] = [] for transactionJson in transactionJsonArray as! [[String: AnyObject]] { var transaction = Transaction() transaction.amount = fabsf(transactionJson["amount"] as! Float) transaction.title = transactionJson["to"] as! String transaction.date = NSDate(timeIntervalSince1970: (transactionJson["date"] as! NSTimeInterval)/1000) if (transactionJson["transactionType"] as! String) == "deposit" { transaction.type = .Deposit }else{ transaction.type = .Withdrawal } transactions.append(transaction) } transactions.sort(sorterForTransactionsDESC) for transaction in transactions { let dayTimePeriodFormatter = NSDateFormatter() dayTimePeriodFormatter.dateFormat = "EEEE M/d/y" let dateString = dayTimePeriodFormatter.stringFromDate(transaction.date) var transactionDay : TransactionDay if transactionDays.last == nil || transactionDays.last!.date != dateString { transactionDay = TransactionDay() transactionDay.date = dateString transactionDay.transactions = [] transactionDay.transactions.append(transaction) transactionDays.append(transactionDay) }else if transactionDays.last!.date == dateString { transactionDay = transactionDays.last! transactionDay.transactions.append(transaction) } } return transactionDays } /** Sorter for the transactions to insure they are in decending order by date :param: transaction1 First transaction :param: transaction2 Second transaction :returns: <#return value description#> */ func sorterForTransactionsDESC(transaction1:Transaction, transaction2:Transaction) -> Bool { return transaction1.date.isLaterThanDate(transaction2.date) } } extension TransactionsDataManager: WLDataDelegate { /** Delegate method for MobileFirst Platform. Called when connection and return is successful :param: response Response from MobileFirst Platform */ public func onSuccess(response: WLResponse!) { let responseJson = response.getResponseJson() as NSDictionary // Parse JSON response into dashboard format and store in accounts let transactionDays = parseTransactionsResponse(responseJson) // Execute the callback from the view controller that instantiated the dashboard call callback(true, transactionDays) } /** Delegate method for MobileFirst Platform. Called when connection or return is unsuccessful :param: response Response from MobileFirst Platform */ public func onFailure(response: WLFailResponse!) { MQALogger.log("Response: \(response.responseText)") if (response.errorCode.value == 0) { MILAlertViewManager.sharedInstance.show("Can not connect to the server, click to refresh", callback: retryGetTransactions) } callback(false, nil) } /** Delegate method for MobileFirst Platform. Task to do before executing a call. */ public func onPreExecute() { } /** Delegate method for MobileFirst Platform. Task to do after executing a call. */ public func onPostExecute() { } }
epl-1.0
d0f3604cec82bc992c3f65ca54157e7c
35.164634
143
0.654527
5.719383
false
false
false
false
darrarski/SwipeToReveal-iOS
ExampleTests/UI/TableExampleViewControllerSpec.swift
1
2387
import Quick import Nimble @testable import SwipeToRevealExample class TableExampleViewControllerSpec: QuickSpec { override func spec() { context("init with coder") { it("should throw asserion") { expect { () -> Void in _ = TableExampleViewController(coder: NSCoder()) }.to(throwAssertion()) } } context("init") { var sut: TableExampleViewController! beforeEach { sut = TableExampleViewController(assembly: Assembly()) } context("load view") { beforeEach { _ = sut.view sut.view.frame = CGRect(x: 0, y: 0, width: 320, height: 240) } describe("table view") { it("should have 1 section") { expect(sut.numberOfSections(in: sut.tableView)).to(equal(1)) } it("should have 100 rows in first section") { expect(sut.tableView(sut.tableView, numberOfRowsInSection: 0)).to(equal(100)) } it("should throw when asked for number of rows in second section") { expect { () -> Void in _ = sut.tableView(sut.tableView, numberOfRowsInSection: 1) }.to(throwAssertion()) } it("shuld not throw when asked for cell at valid index path") { expect { () -> Void in _ = sut.tableView(sut.tableView, cellForRowAt: IndexPath(row: 0, section: 0)) }.notTo(throwAssertion()) } it("should return correct height for a row") { expect(sut.tableView(sut.tableView, heightForRowAt: IndexPath(row: 0, section: 0))) .to(equal(88)) } it("should throw when asked for row height at invalid index path") { expect { () -> Void in _ = sut.tableView(sut.tableView, heightForRowAt: IndexPath(row: 0, section: 1)) }.to(throwAssertion()) } } } } } struct Assembly: TableExampleAssembly {} }
mit
63d1b2253237460a3b65db84de915640
35.723077
110
0.466695
5.512702
false
false
false
false
bearMountain/MovingLetters
Moving Letters/Letter.swift
1
1457
import UIKit struct Letter { let strokes: [Any] } struct BezierPoint { let point: CGPoint let controlPoint1: CGPoint? let controlPoint2: CGPoint? } struct BezierPath { let start: CGPoint let points: [BezierPoint] } struct LineSegment { let start: CGPoint let end: CGPoint } // A let leftLine = LineSegment(start: p(2,10), end: p(5,100)) let points = [ BezierPoint(point: p(17,2), controlPoint1: nil, controlPoint2:p(8,2)), BezierPoint(point: p(40,98), controlPoint1: p(26,1.5), controlPoint2: nil) ] let arch = BezierPath(start: p(5, 100), points: points) let crossLine = LineSegment(start: p(8, 50), end: p(44.5, 47.5)) let A = Letter(strokes: [leftLine, arch, crossLine]) // B let mainShaft = LineSegment(start: p(9, 12), end: p(7, 98)) let secondShaft = LineSegment(start: p(7, 98), end: p(2, 5)) let topBArchPoints = [ BezierPoint(point: p(48, 13), controlPoint1: nil, controlPoint2: p(41, -6)), BezierPoint(point: p(25.5, 41), controlPoint1: p(52.5, 31.5), controlPoint2: nil) ] let topBArch = BezierPath(start: p(2,5), points: topBArchPoints) let bottomBArchPoints = [ BezierPoint(point: p(51, 83), controlPoint1: nil, controlPoint2: p(70, 52)), BezierPoint(point: p(-4.5, 85), controlPoint1: p(32, 114), controlPoint2: nil) ] let bottomBarch = BezierPath(start: p(25.5, 41), points: bottomBArchPoints) let B = Letter(strokes: [mainShaft, secondShaft, topBArch, bottomBarch])
mit
aa330131da84f4d08b63399591048393
23.694915
85
0.678106
3.060924
false
false
false
false
bitpay/cordova-plugin-qrscanner
src/ios/QRScanner.swift
1
19193
import Foundation import AVFoundation @objc(QRScanner) class QRScanner : CDVPlugin, AVCaptureMetadataOutputObjectsDelegate { class CameraView: UIView { var videoPreviewLayer:AVCaptureVideoPreviewLayer? func interfaceOrientationToVideoOrientation(_ orientation : UIInterfaceOrientation) -> AVCaptureVideoOrientation { switch (orientation) { case UIInterfaceOrientation.portrait: return AVCaptureVideoOrientation.portrait; case UIInterfaceOrientation.portraitUpsideDown: return AVCaptureVideoOrientation.portraitUpsideDown; case UIInterfaceOrientation.landscapeLeft: return AVCaptureVideoOrientation.landscapeLeft; case UIInterfaceOrientation.landscapeRight: return AVCaptureVideoOrientation.landscapeRight; default: return AVCaptureVideoOrientation.portraitUpsideDown; } } override func layoutSubviews() { super.layoutSubviews(); if let sublayers = self.layer.sublayers { for layer in sublayers { layer.frame = self.bounds; } } self.videoPreviewLayer?.connection?.videoOrientation = interfaceOrientationToVideoOrientation(UIApplication.shared.statusBarOrientation); } func addPreviewLayer(_ previewLayer:AVCaptureVideoPreviewLayer?) { previewLayer!.videoGravity = AVLayerVideoGravity.resizeAspectFill previewLayer!.frame = self.bounds self.layer.addSublayer(previewLayer!) self.videoPreviewLayer = previewLayer; } func removePreviewLayer() { if self.videoPreviewLayer != nil { self.videoPreviewLayer!.removeFromSuperlayer() self.videoPreviewLayer = nil } } } var cameraView: CameraView! var captureSession:AVCaptureSession? var captureVideoPreviewLayer:AVCaptureVideoPreviewLayer? var metaOutput: AVCaptureMetadataOutput? var currentCamera: Int = 0; var frontCamera: AVCaptureDevice? var backCamera: AVCaptureDevice? var scanning: Bool = false var paused: Bool = false var nextScanningCommand: CDVInvokedUrlCommand? enum QRScannerError: Int32 { case unexpected_error = 0, camera_access_denied = 1, camera_access_restricted = 2, back_camera_unavailable = 3, front_camera_unavailable = 4, camera_unavailable = 5, scan_canceled = 6, light_unavailable = 7, open_settings_unavailable = 8 } enum CaptureError: Error { case backCameraUnavailable case frontCameraUnavailable case couldNotCaptureInput(error: NSError) } enum LightError: Error { case torchUnavailable } override func pluginInitialize() { super.pluginInitialize() NotificationCenter.default.addObserver(self, selector: #selector(pageDidLoad), name: NSNotification.Name.CDVPageDidLoad, object: nil) self.cameraView = CameraView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)) self.cameraView.autoresizingMask = [.flexibleWidth, .flexibleHeight]; } func sendErrorCode(command: CDVInvokedUrlCommand, error: QRScannerError){ let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error.rawValue) commandDelegate!.send(pluginResult, callbackId:command.callbackId) } // utility method @objc func backgroundThread(delay: Double = 0.0, background: (() -> Void)? = nil, completion: (() -> Void)? = nil) { if #available(iOS 8.0, *) { DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { if (background != nil) { background!() } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay * Double(NSEC_PER_SEC)) { if(completion != nil){ completion!() } } } } else { // Fallback for iOS < 8.0 if(background != nil){ background!() } if(completion != nil){ completion!() } } } @objc func prepScanner(command: CDVInvokedUrlCommand) -> Bool{ let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) if (status == AVAuthorizationStatus.restricted) { self.sendErrorCode(command: command, error: QRScannerError.camera_access_restricted) return false } else if status == AVAuthorizationStatus.denied { self.sendErrorCode(command: command, error: QRScannerError.camera_access_denied) return false } do { if (captureSession?.isRunning != true){ cameraView.backgroundColor = UIColor.clear self.webView!.superview!.insertSubview(cameraView, belowSubview: self.webView!) let availableVideoDevices = AVCaptureDevice.devices(for: AVMediaType.video) for device in availableVideoDevices { if device.position == AVCaptureDevice.Position.back { backCamera = device } else if device.position == AVCaptureDevice.Position.front { frontCamera = device } } // older iPods have no back camera if(backCamera == nil){ currentCamera = 1 } let input: AVCaptureDeviceInput input = try self.createCaptureDeviceInput() captureSession = AVCaptureSession() captureSession!.addInput(input) metaOutput = AVCaptureMetadataOutput() captureSession!.addOutput(metaOutput!) metaOutput!.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) metaOutput!.metadataObjectTypes = [AVMetadataObject.ObjectType.qr] captureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!) cameraView.addPreviewLayer(captureVideoPreviewLayer) captureSession!.startRunning() } return true } catch CaptureError.backCameraUnavailable { self.sendErrorCode(command: command, error: QRScannerError.back_camera_unavailable) } catch CaptureError.frontCameraUnavailable { self.sendErrorCode(command: command, error: QRScannerError.front_camera_unavailable) } catch CaptureError.couldNotCaptureInput(let error){ print(error.localizedDescription) self.sendErrorCode(command: command, error: QRScannerError.camera_unavailable) } catch { self.sendErrorCode(command: command, error: QRScannerError.unexpected_error) } return false } @objc func createCaptureDeviceInput() throws -> AVCaptureDeviceInput { var captureDevice: AVCaptureDevice if(currentCamera == 0){ if(backCamera != nil){ captureDevice = backCamera! } else { throw CaptureError.backCameraUnavailable } } else { if(frontCamera != nil){ captureDevice = frontCamera! } else { throw CaptureError.frontCameraUnavailable } } let captureDeviceInput: AVCaptureDeviceInput do { captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice) } catch let error as NSError { throw CaptureError.couldNotCaptureInput(error: error) } return captureDeviceInput } @objc func makeOpaque(){ self.webView?.isOpaque = false self.webView?.backgroundColor = UIColor.clear } @objc func boolToNumberString(bool: Bool) -> String{ if(bool) { return "1" } else { return "0" } } @objc func configureLight(command: CDVInvokedUrlCommand, state: Bool){ var useMode = AVCaptureDevice.TorchMode.on if(state == false){ useMode = AVCaptureDevice.TorchMode.off } do { // torch is only available for back camera if(backCamera == nil || backCamera!.hasTorch == false || backCamera!.isTorchAvailable == false || backCamera!.isTorchModeSupported(useMode) == false){ throw LightError.torchUnavailable } try backCamera!.lockForConfiguration() backCamera!.torchMode = useMode backCamera!.unlockForConfiguration() self.getStatus(command) } catch LightError.torchUnavailable { self.sendErrorCode(command: command, error: QRScannerError.light_unavailable) } catch let error as NSError { print(error.localizedDescription) self.sendErrorCode(command: command, error: QRScannerError.unexpected_error) } } // This method processes metadataObjects captured by iOS. func metadataOutput(_ captureOutput: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { if metadataObjects.count == 0 || scanning == false { // while nothing is detected, or if scanning is false, do nothing. return } let found = metadataObjects[0] as! AVMetadataMachineReadableCodeObject if found.type == AVMetadataObject.ObjectType.qr && found.stringValue != nil { scanning = false let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: found.stringValue) commandDelegate!.send(pluginResult, callbackId: nextScanningCommand?.callbackId!) nextScanningCommand = nil } } @objc func pageDidLoad() { self.webView?.isOpaque = false self.webView?.backgroundColor = UIColor.clear } // ---- BEGIN EXTERNAL API ---- @objc func prepare(_ command: CDVInvokedUrlCommand){ let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) if (status == AVAuthorizationStatus.notDetermined) { // Request permission before preparing scanner AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted) -> Void in // attempt to prepScanner only after the request returns self.backgroundThread(delay: 0, completion: { if(self.prepScanner(command: command)){ self.getStatus(command) } }) }) } else { if(self.prepScanner(command: command)){ self.getStatus(command) } } } @objc func scan(_ command: CDVInvokedUrlCommand){ if(self.prepScanner(command: command)){ nextScanningCommand = command scanning = true } } @objc func cancelScan(_ command: CDVInvokedUrlCommand){ if(self.prepScanner(command: command)){ scanning = false if(nextScanningCommand != nil){ self.sendErrorCode(command: nextScanningCommand!, error: QRScannerError.scan_canceled) } self.getStatus(command) } } @objc func show(_ command: CDVInvokedUrlCommand) { self.webView?.isOpaque = false self.webView?.backgroundColor = UIColor.clear self.getStatus(command) } @objc func hide(_ command: CDVInvokedUrlCommand) { self.makeOpaque() self.getStatus(command) } @objc func pausePreview(_ command: CDVInvokedUrlCommand) { if(scanning){ paused = true; scanning = false; } captureVideoPreviewLayer?.connection?.isEnabled = false self.getStatus(command) } @objc func resumePreview(_ command: CDVInvokedUrlCommand) { if(paused){ paused = false; scanning = true; } captureVideoPreviewLayer?.connection?.isEnabled = true self.getStatus(command) } // backCamera is 0, frontCamera is 1 @objc func useCamera(_ command: CDVInvokedUrlCommand){ let index = command.arguments[0] as! Int if(currentCamera != index){ // camera change only available if both backCamera and frontCamera exist if(backCamera != nil && frontCamera != nil){ // switch camera currentCamera = index if(self.prepScanner(command: command)){ do { captureSession!.beginConfiguration() let currentInput = captureSession?.inputs[0] as! AVCaptureDeviceInput captureSession!.removeInput(currentInput) let input = try self.createCaptureDeviceInput() captureSession!.addInput(input) captureSession!.commitConfiguration() self.getStatus(command) } catch CaptureError.backCameraUnavailable { self.sendErrorCode(command: command, error: QRScannerError.back_camera_unavailable) } catch CaptureError.frontCameraUnavailable { self.sendErrorCode(command: command, error: QRScannerError.front_camera_unavailable) } catch CaptureError.couldNotCaptureInput(let error){ print(error.localizedDescription) self.sendErrorCode(command: command, error: QRScannerError.camera_unavailable) } catch { self.sendErrorCode(command: command, error: QRScannerError.unexpected_error) } } } else { if(backCamera == nil){ self.sendErrorCode(command: command, error: QRScannerError.back_camera_unavailable) } else { self.sendErrorCode(command: command, error: QRScannerError.front_camera_unavailable) } } } else { // immediately return status if camera is unchanged self.getStatus(command) } } @objc func enableLight(_ command: CDVInvokedUrlCommand) { if(self.prepScanner(command: command)){ self.configureLight(command: command, state: true) } } @objc func disableLight(_ command: CDVInvokedUrlCommand) { if(self.prepScanner(command: command)){ self.configureLight(command: command, state: false) } } @objc func destroy(_ command: CDVInvokedUrlCommand) { self.makeOpaque() if(self.captureSession != nil){ backgroundThread(delay: 0, background: { self.captureSession!.stopRunning() self.cameraView.removePreviewLayer() self.captureVideoPreviewLayer = nil self.metaOutput = nil self.captureSession = nil self.currentCamera = 0 self.frontCamera = nil self.backCamera = nil }, completion: { self.getStatus(command) }) } else { self.getStatus(command) } } @objc func getStatus(_ command: CDVInvokedUrlCommand){ let authorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video); var authorized = false if(authorizationStatus == AVAuthorizationStatus.authorized){ authorized = true } var denied = false if(authorizationStatus == AVAuthorizationStatus.denied){ denied = true } var restricted = false if(authorizationStatus == AVAuthorizationStatus.restricted){ restricted = true } var prepared = false if(captureSession?.isRunning == true){ prepared = true } var previewing = false if(captureVideoPreviewLayer != nil){ previewing = captureVideoPreviewLayer!.connection!.isEnabled } var showing = false if(self.webView!.backgroundColor == UIColor.clear){ showing = true } var lightEnabled = false if(backCamera?.torchMode == AVCaptureDevice.TorchMode.on){ lightEnabled = true } var canOpenSettings = false if #available(iOS 8.0, *) { canOpenSettings = true } var canEnableLight = false if(backCamera?.hasTorch == true && backCamera?.isTorchAvailable == true && backCamera?.isTorchModeSupported(AVCaptureDevice.TorchMode.on) == true){ canEnableLight = true } var canChangeCamera = false; if(backCamera != nil && frontCamera != nil){ canChangeCamera = true } let status = [ "authorized": boolToNumberString(bool: authorized), "denied": boolToNumberString(bool: denied), "restricted": boolToNumberString(bool: restricted), "prepared": boolToNumberString(bool: prepared), "scanning": boolToNumberString(bool: scanning), "previewing": boolToNumberString(bool: previewing), "showing": boolToNumberString(bool: showing), "lightEnabled": boolToNumberString(bool: lightEnabled), "canOpenSettings": boolToNumberString(bool: canOpenSettings), "canEnableLight": boolToNumberString(bool: canEnableLight), "canChangeCamera": boolToNumberString(bool: canChangeCamera), "currentCamera": String(currentCamera) ] let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: status) commandDelegate!.send(pluginResult, callbackId:command.callbackId) } @objc func openSettings(_ command: CDVInvokedUrlCommand) { if #available(iOS 10.0, *) { guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in self.getStatus(command) }) } else { self.sendErrorCode(command: command, error: QRScannerError.open_settings_unavailable) } } else { // pre iOS 10.0 if #available(iOS 8.0, *) { UIApplication.shared.openURL(NSURL(string: UIApplication.openSettingsURLString)! as URL) self.getStatus(command) } else { self.sendErrorCode(command: command, error: QRScannerError.open_settings_unavailable) } } } }
mit
fb37295b8b82b02fe072f3023d57e87f
38.089613
162
0.598812
5.883814
false
false
false
false
ffxfiend/IGZQueueManager
IGZQueueManagerTests/IGZQueueManagerPackageTests.swift
1
5585
// // IGZQueueManagerPackageTests.swift // IGZQueueManager // // Created by Jeremiah Poisson on 10/4/16. // // Copyright (c) 2016 Jeremiah Poisson (http://miahpoisson.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest @testable import IGZQueueManager class IGZQueueManagerPackageTests: XCTestCase { var manager : QueueManager? let googleURL = URL(string: "http://www.google.com")! let stubNetworkHandler = StubNetworkHandler() var preparedPackageDefaultQueue : Package? var preparedPackageCustomQueue : Package? override func setUp() { super.setUp() // We want a new manager for each test, not a shared one. manager = IGZQueueManager.QueueManager() preparedPackageDefaultQueue = Package(action: googleURL, method: .get, queue: "GENERAL", parameters: [:], headers: [:], success: { (response: Any?) in }, failure: { (error: NSError?) in }) preparedPackageCustomQueue = Package(action: googleURL, method: .get, queue: "My Custom Queue", parameters: [:], headers: [:], success: { (response: Any?) in }, failure: { (error: NSError?) in }) } override func tearDown() { super.tearDown() manager!.removeAllQueues() } // MARK: - Preferred Create Package Method - func testCreatePackageSuccess() { // Set the network handler manager!.setNetworkHandler(stubNetworkHandler) XCTAssertNotNil(try? manager!.createPackage(googleURL, method: .get, queue: nil, params: [:], success: { (response: Any?) in }, failure: { (error: NSError?) in })) } func testCreatePackageHandlerNotSet() { XCTAssertThrowsError(try manager!.createPackage(googleURL, method: .get, queue: nil, params: [:], success: { (response: Any?) in }, failure: { (error : NSError?) in }), "Package Handler Not Set") { (error) in XCTAssertEqual(error as? IGZ_NetworkErrors, IGZ_NetworkErrors.packageHandlerNotSet) } } func testCreatePackageQueueDoesNotExist() { // Set the network handler manager!.setNetworkHandler(stubNetworkHandler) XCTAssertThrowsError(try manager!.createPackage(googleURL, method: .get, queue: "My Custom Queue", params: [:], success: { (response: Any?) in }, failure: { (error : NSError?) in }), "Queue does not exist") { (error) in XCTAssertEqual(error as? IGZ_NetworkErrors, IGZ_NetworkErrors.queueDoesNotExists) } } // MARK: - Create Package with Package - func testCreatePackageWithPackageSuccess() { // Set the network handler manager!.setNetworkHandler(stubNetworkHandler) XCTAssertNotNil(try? manager!.createPackage(preparedPackageDefaultQueue!)) } func testCreatePackageWithPackageHandlerNotSet() { XCTAssertThrowsError(try manager!.createPackage(preparedPackageDefaultQueue!), "Package Handler Not Set") { (error) in XCTAssertEqual(error as? IGZ_NetworkErrors, IGZ_NetworkErrors.packageHandlerNotSet) } } func testCreatePackageWithPackageQueueDoesNotExist() { // Set the network handler manager!.setNetworkHandler(stubNetworkHandler) XCTAssertThrowsError(try manager!.createPackage(preparedPackageCustomQueue!), "Queue does not exist") { (error) in XCTAssertEqual(error as? IGZ_NetworkErrors, IGZ_NetworkErrors.queueDoesNotExists) } } // MARK: - Success Called - func testPackageSuccessCalled() { // Set the network handler manager!.setNetworkHandler(stubNetworkHandler) let successExpectation = expectation(description: "Network Handler should be called and return a success state.") try! manager!.createPackage(googleURL, method: .get, queue: nil, params: ["success":true], success: { (response: Any?) in successExpectation.fulfill() }, failure: { (error: NSError?) in }) waitForExpectations(timeout: 1) { (error: Error?) in if error != nil { XCTFail("waitForExpectations failed: \(error!.localizedDescription)") } } } func testPackageFailureCalled() { // Set the network handler manager!.setNetworkHandler(stubNetworkHandler) let failureExpectation = expectation(description: "Network Handler should be called and return a failure state.") try! manager!.createPackage(googleURL, method: .get, queue: nil, params: ["success":false], success: { (response: Any?) in }, failure: { (error: NSError?) in failureExpectation.fulfill() }) waitForExpectations(timeout: 1) { (error: Error?) in if error != nil { XCTFail("waitForExpectations failed: \(error!.localizedDescription)") } } } }
mit
1efaa597bebaa8738a0c97d6e658815f
31.283237
159
0.711012
4.266616
false
true
false
false
LYM-mg/MGOFO
MGOFO/MGOFO/Class/Extesion/String+Extension.swift
1
9471
// String+Extension.swift // 解释 /* - mutating: 1、关键字修饰方法是为了能在该方法中修改 struct 或是 enum 的变量,在设计接口的时候,也要考虑到使用者程序的可扩展性 - subscript: 1.可以使用在类,结构体,枚举中 2.提供一种类似于数组或者字典通过下标来访问对象的方式 - final关键字: 1、可以通过把方法,属性或下标标记为final来防止它们被重写,只需要在声明关键字前加上final修饰符即可(例如:final var,final func,final class func,以及final subscript)。如果你重写了final方法,属性或下标,在编译时会报错。 */ import UIKit import Foundation //import CommonDigest> //import <CommonCrypto/CommonDigest.h> // MARK: - 沙盒路径 extension String { /// 沙盒路径之document func document() -> String { let documentPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! return (documentPath as NSString).appendingPathComponent((self as NSString).pathComponents.last!) } /// 沙盒路径之cachePath func cache() -> String { let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! return (cachePath as NSString).appendingPathComponent((self as NSString).pathComponents.last!) } /// 沙盒路径之temp func temp() -> String { let tempPath = NSTemporaryDirectory() return (tempPath as NSString).appendingPathComponent((self as NSString).pathComponents.last!) } } // MARK: - 通过扩展来简化一下,截取字符串 extension String { subscript (range: Range<Int>) -> String { get { let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound) let endIndex = self.index(self.startIndex, offsetBy: range.upperBound) return self[Range(startIndex..<endIndex)] } set { let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound) let endIndex = self.index(self.startIndex, offsetBy: range.upperBound) let strRange = Range(startIndex..<endIndex) self.replaceSubrange(strRange, with: newValue) } } func subString(from: Int) -> String { let end = self.characters.count return self[from..<end] } func subString(from: Int, length: Int) -> String { let end = from + length return self[from..<end] } func subString(from:Int, to:Int) ->String { return self[from..<to] } } // MARK: - 判断手机号 隐藏手机中间四位 正则匹配用户身份证号15或18位 正则RegexKitLite框架 extension String { // 利用正则表达式判断是否是手机号码 mutating func checkTelNumber() -> Bool { let pattern = "^((13[0-9])|(147)|(15[0-3,5-9])|(18[0,0-9])|(17[0-3,5-9]))\\d{8}$" let pred = NSPredicate(format: "SELF MATCHES %@", pattern) return pred.evaluate(with: self) } // 正则匹配用户身份证号15或18位 func validateIdentityCard(identityCard: String) -> Bool { let pattern = "(^[0-9]{15}$)|([0-9]{17}([0-9]|[0-9a-zA-Z])$)" let pred = NSPredicate(format: "SELF MATCHES %@", pattern) return pred.evaluate(with: identityCard) } // 隐藏手机敏感信息 mutating func phoneNumberhideMid() { let startIndex = self.index("".startIndex, offsetBy: 4) let endIndex = self.index("".startIndex, offsetBy: 7) self.replaceSubrange(startIndex...endIndex, with: "****") } // 隐藏敏感信息 mutating func numberHideMidWithOtherChar(form: Int, to: Int,char: String) { // 判断,防止越界 var form = form; var to = to if form < 0 { form = 0 } if to > self.characters.count { to = self.characters.count } var star = "" for _ in form...to { star.append(char) } let startIndex = self.index("".startIndex, offsetBy: form) let endIndex = self.index("".startIndex, offsetBy: to) self.replaceSubrange(startIndex...endIndex, with: star) } } // MARK: - 汉字转拼音 extension String { func transformChineseToPinyin() -> String{ //将NSString装换成NSMutableString let pinyin = NSMutableString(string: self)as CFMutableString //将汉字转换为拼音(带音标) CFStringTransform(pinyin, nil, kCFStringTransformMandarinLatin, false) //去掉拼音的音标 CFStringTransform(pinyin, nil, kCFStringTransformStripCombiningMarks, false) //返回最近结果 return pinyin as String } } // MARK: - MD5 加密 extension String { var md5: String{ let str = self.cString(using: String.Encoding.utf8) let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen); CC_MD5(str!, strLen, result); let hash = NSMutableString(); for i in 0 ..< digestLen { hash.appendFormat("%02x", result[i]); } result.deinitialize(count: Int(strLen)) return String(format: hash as String) } } // MARK: - 加密 HMAC_SHA1/MD5/SHA1/SHA224...... /** 需在桥接文件导入头文件 ,因为C语言的库 * #import <CommonCrypto/CommonDigest.h> * #import <CommonCrypto/CommonHMAC.h> */ enum CryptoAlgorithm { // 2,SHA(安全散列算法:Secure Hash Algorithm) // 不可逆 /// 加密的枚举选项 HMAC case MD5, SHA1, SHA224, SHA256, SHA384, SHA512 var HMACAlgorithm: CCHmacAlgorithm { var result: Int = 0 switch self { case .MD5: result = kCCHmacAlgMD5 case .SHA1: result = kCCHmacAlgSHA1 case .SHA224: result = kCCHmacAlgSHA224 case .SHA256: result = kCCHmacAlgSHA256 case .SHA384: result = kCCHmacAlgSHA384 case .SHA512: result = kCCHmacAlgSHA512 } return CCHmacAlgorithm(result) } var digestLength: Int { var result: Int32 = 0 switch self { case .MD5: result = CC_MD5_DIGEST_LENGTH case .SHA1: result = CC_SHA1_DIGEST_LENGTH case .SHA224: result = CC_SHA224_DIGEST_LENGTH case .SHA256: result = CC_SHA256_DIGEST_LENGTH case .SHA384: result = CC_SHA384_DIGEST_LENGTH case .SHA512: result = CC_SHA512_DIGEST_LENGTH } return Int(result) } } extension String { /** func: 加密方法 - parameter algorithm: 加密方式; - parameter key: 加密的key */ func hmac(algorithm: CryptoAlgorithm, key: String) -> String { let str = self.cString(using: String.Encoding.utf8) let strLen = Int(self.lengthOfBytes(using: String.Encoding.utf8)) let digestLen = algorithm.digestLength let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen) let keyStr = key.cString(using: String.Encoding.utf8) let keyLen = Int(key.lengthOfBytes(using: String.Encoding.utf8)) CCHmac(algorithm.HMACAlgorithm, keyStr!, keyLen, str!, strLen, result) let digest = stringFromResult(result: result, length: digestLen) result.deallocate(capacity: digestLen) return digest } private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String { let hash = NSMutableString() for i in 0..<length { hash.appendFormat("%02x", result[i]) } return String(hash) } } // MARK: - Base64 加密 extension String { /** * Base64 加密 * return 加密字符串 */ func encodeToBase64() -> String { guard let data = self.data(using: String.Encoding.utf8) else { print("加密失败"); return "" } return data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) //系统提供的方法,iOS7之后可用 } /** * Base64 解密 * return 解密字符串 */ func decodeBase64() -> String { guard let data = Data(base64Encoded: self, options: Data.Base64DecodingOptions(rawValue: 0)) else { print("解密失败"); return "" } return String(data: data, encoding: String.Encoding.utf8)! } /* eg: let base64Str = "明哥" // 打印 "明哥" let encodeStr = base64Str.encodeToBase64() // 打印 "5piO5ZOl" let decodeStr = encodeStr.decodeBase64() // 打印 "明哥" */ } // MARK: - 加密 RSA AES Heimdall实际上是混合了AES和RSA这两种加密方式 // MARK: - encoding /* URLFragmentAllowedCharacterSet "#%<>[\]^`{|} URLHostAllowedCharacterSet "#%/<>?@\^`{|} URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|} URLPathAllowedCharacterSet "#%;<>?[\]^`{|} URLQueryAllowedCharacterSet "#%<>[\]^`{|} URLUserAllowedCharacterSet "#%/:<>?@[\]^` */
mit
9c920af7393e746a30086e15157a749b
32.360465
174
0.613919
3.959062
false
false
false
false
ericvergnaud/antlr4
runtime/Swift/Sources/Antlr4/misc/utils/CommonUtil.swift
6
2009
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ // // CommonUtil.swift // antlr.swift // // Created by janyou on 15/9/4. // import Foundation func errPrint(_ msg: String) { fputs(msg + "\n", stderr) } public func +(lhs: String, rhs: Int) -> String { return lhs + String(rhs) } public func +(lhs: Int, rhs: String) -> String { return String(lhs) + rhs } public func +(lhs: String, rhs: Token) -> String { return lhs + rhs.description } public func +(lhs: Token, rhs: String) -> String { return lhs.description + rhs } infix operator >>> : BitwiseShiftPrecedence func >>>(lhs: Int32, rhs: Int32) -> Int32 { return lhs &>> rhs } func >>>(lhs: Int64, rhs: Int64) -> Int64 { return lhs &>> rhs } func >>>(lhs: Int, rhs: Int) -> Int { return lhs &>> rhs } func intChar2String(_ i: Int) -> String { return String(Character(integerLiteral: i)) } func log(_ message: String = "", file: String = #file, function: String = #function, lineNum: Int = #line) { // #if DEBUG print("FILE: \(URL(fileURLWithPath: file).pathComponents.last!),FUNC: \(function), LINE: \(lineNum) MESSAGE: \(message)") // #else // do nothing // #endif } func toInt(_ c: Character) -> Int { return c.unicodeValue } func toInt32(_ data: [Character], _ offset: Int) -> Int { return data[offset].unicodeValue | (data[offset + 1].unicodeValue << 16) } func toLong(_ data: [Character], _ offset: Int) -> Int64 { let mask: Int64 = 0x00000000FFFFFFFF let lowOrder: Int64 = Int64(toInt32(data, offset)) & mask return lowOrder | Int64(toInt32(data, offset + 2) << 32) } func toUUID(_ data: [Character], _ offset: Int) -> UUID { let leastSigBits: Int64 = toLong(data, offset) let mostSigBits: Int64 = toLong(data, offset + 4) return UUID(mostSigBits: mostSigBits, leastSigBits: leastSigBits) }
bsd-3-clause
ab7acbf464422233679c726f369d8f0d
24.1125
125
0.636635
3.293443
false
false
false
false
Yufei-Yan/iOSProjectsAndTest
Ch8_test4/Ch8_test4/ViewController.swift
1
2673
// // ViewController.swift // Ch8_test4 // // Created by Yan on 11/8/16. // Copyright © 2016 Yan. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { let sectionsTableIdentifier = "SectionsTableIndentifier" var names: [String: [String]]! var keys: [String]! @IBOutlet weak var tableView: UITableView! var searchController: UISearchController! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tableView.register(UITableViewCell.self, forCellReuseIdentifier: sectionsTableIdentifier) let path = Bundle.main.path(forResource: "sortednames", ofType: "plist") let namesDict = NSDictionary(contentsOfFile: path!) names = namesDict as! [String: [String]] keys = (namesDict!.allKeys as! [String]).sorted() let resultsController = SearchResultsController() resultsController.names = names resultsController.keys = keys searchController = UISearchController(searchResultsController: resultsController) let searchBar = searchController.searchBar searchBar.scopeButtonTitles = ["All", "Short", "Long"] searchBar.placeholder = "Enter a search term" searchBar.sizeToFit() tableView.tableHeaderView = searchBar searchController.searchResultsUpdater = resultsController } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Table View Data Source Methods func numberOfSections(in tableView: UITableView) -> Int { return keys.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let key = keys[section] let nameSection = names[key]! return nameSection.count } func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return keys[section] } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: sectionsTableIdentifier, for: indexPath as IndexPath) as UITableViewCell let key = keys[indexPath.section] let nameSection = names[key]! cell.textLabel?.text = nameSection[indexPath.row] return cell } func sectionIndexTitles(for tableView: UITableView) -> [String]? { return keys } }
mit
d72eb1d13509a88d4b98fc0542c8606c
33.701299
122
0.665045
5.39798
false
false
false
false
duliodenis/HackingWithSwift
project-07/Whitehouse/Whitehouse/MasterViewController.swift
1
3337
// // MasterViewController.swift // Whitehouse // // Created by Dulio Denis on 1/17/15. // Copyright (c) 2015 ddApps. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var objects = [[String:String]]() override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() var urlString:String if navigationController?.tabBarItem.tag == 0 { urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100" } else { urlString = "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100" } if let url = NSURL(string: urlString) { if let data = NSData(contentsOfURL: url, options: .allZeros, error: nil) { let json = JSON(data: data) if json["metadata"]["responseInfo"]["status"].intValue == 200 { // okay to parse parseJSON(json) } else { showError() } } else { showError() } } else { showError() } } func showError() { let ac = UIAlertController(title: "Loading Error", message: "There was an error loading the petition data. Please check your connection and try again.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) } func parseJSON(json: JSON) { for result in json["results"].arrayValue { let title = result["title"].stringValue let body = result["body"].stringValue let sigs = result["signatureCount"].stringValue let dict = ["title": title, "body": body, "sigs": sigs] objects.append(dict) } tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell let object = objects[indexPath.row] cell.textLabel!.text = object["title"] // let petition = object["sigs"] cell.detailTextLabel!.text = object["body"]//"Petition signatures: \(petition)" return cell } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let object = objects[indexPath.row] (segue.destinationViewController as DetailViewController).detailItem = object } } } }
mit
b184f0c3e8d24d2468bfe50643bcf177
31.398058
184
0.593347
5.133846
false
false
false
false
shepting/AppleToast
Billboard/Toast/SideView.swift
1
819
// // SideView.swift // Toast // // Created by Steven Hepting on 10/20/16. // Copyright © 2016 Hepting. All rights reserved. // import Foundation import UIKit class SideView: UIView { let label = UILabel() } extension SideView { convenience init(message: String) { self.init() backgroundColor = .black label.text = message addSubview(label) label.fillSuperview(padding: 6) label.textColor = .white label.font = UIFont.systemFont(ofSize: 12) layer.cornerRadius = 3 label.translatesAutoresizingMaskIntoConstraints = false translatesAutoresizingMaskIntoConstraints = false } // override func didMoveToSuperview() { // translatesAutoresizingMaskIntoConstraints = false // placeOnRightSide() // } }
mit
96601beefdf4d62df6776505d2712e56
20.526316
63
0.654034
4.621469
false
false
false
false
kellanburket/Passenger
Pod/Classes/Extensions/NSData.swift
1
3667
// // NSData.swift // Pods // // Created by Kellan Cummings on 6/14/15. // // import Foundation import CommonCrypto internal extension NSData { internal func parseJson() -> AnyObject? { var error: NSError? if let json = NSJSONSerialization.JSONObjectWithData(self, options: nil, error: &error) as? [String: AnyObject] { return json } else if let json = NSJSONSerialization.JSONObjectWithData(self, options: nil, error: &error) as? [AnyObject] { return json } else { println("Could not properly parse JSON data: \(error)") return nil } } internal func stringify(encoding: UInt = NSUTF8StringEncoding) -> String? { return NSString(data: self, encoding: encoding) as? String } internal func sign(algorithm: HMACAlgorithm, key: String) -> String? { let string = UnsafePointer<UInt8>(self.bytes) let stringLength = Int(self.length) let digestLength = algorithm.digestLength() if let keyString = key.cStringUsingEncoding(NSUTF8StringEncoding) { let keyLength = Int(key.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) var result = [UInt8](count: digestLength, repeatedValue: 0) CCHmac(algorithm.toCCEnum(), keyString, keyLength, string, stringLength, &result) var hash: String = "" //for i in 0..<digestLength { hash += String(format: "%02x", result[i]) } var base64String: String = "" var binaryString: UInt32 = 0 var mask: [Int: UInt32] = [ 0: 0b111111, 6: 0b111111 << 6, 12: 0b111111 << 12, 18: 0b111111 << 18, ] var iteration = 0; for i in 0..<digestLength { binaryString <<= 8 binaryString |= UInt32(result[i]) iteration = i % 3 if i % 3 == 2 { var b1: Int = Int(binaryString & mask[18]!) var b2: Int = Int(binaryString & mask[12]!) var b3: Int = Int(binaryString & mask[6]!) var b4: Int = Int(binaryString & mask[0]!) var ix1: Int = b1 >> 18 var ix2: Int = b2 >> 12 var ix3: Int = b3 >> 6 var ix4: Int = b4 base64String.append(MIMEBase64Encoding[ix1]) base64String.append(MIMEBase64Encoding[ix2]) base64String.append(MIMEBase64Encoding[ix3]) base64String.append(MIMEBase64Encoding[ix4]) binaryString = 0 } } var padding = "" if binaryString > 0 { let remainder = Int(2 - iteration) for var j = 0; j < remainder; ++j { padding += "=" binaryString <<= 2 } for var k = 18 - (remainder * 6); k >= 0; k -= 6 { var byte: Int = Int(binaryString & mask[k]!) var index: Int = byte >> k base64String.append(MIMEBase64Encoding[index]) } } return base64String + padding } else { return nil } } }
mit
849e5ab12f7de2199245f1a1b3888b05
33.603774
121
0.462776
5.057931
false
false
false
false
wayfair/brickkit-ios
Tests/Cells/AsynchronousResizableBrick.swift
1
1734
// // DummyAsynchronousResizableCell.swift // BrickKit // // Created by Ruben Cagnie on 10/1/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import UIKit import BrickKit class AsynchronousResizableBrick: Brick { var didChangeSizeCallBack: (() -> Void)? var newHeight: CGFloat = 200 } class AsynchronousResizableBrickCell: BrickCell, Bricklike, AsynchronousResizableCell { typealias BrickType = AsynchronousResizableBrick weak var resizeDelegate: AsynchronousResizableDelegate? @IBOutlet weak var heightConstraint: NSLayoutConstraint! var timer: Timer? override func updateContent() { super.updateContent() timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AsynchronousResizableBrickCell.fireTimer), userInfo: nil, repeats: false) } @objc func fireTimer() { self.heightConstraint.constant = brick.newHeight self.resizeDelegate?.performResize(cell: self, completion: { [weak self] in self?.brick.didChangeSizeCallBack?() }) } } class DeinitNotifyingAsyncBrickCell: BrickCell, Bricklike, AsynchronousResizableCell { typealias BrickType = DeinitNotifyingAsyncBrick weak var resizeDelegate: AsynchronousResizableDelegate? override func updateContent() { super.updateContent() self.resizeDelegate?.performResize(cell: self, completion: {}) } deinit { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "DeinitNotifyingAsyncBrickCell.deinit"), object: nil) } } class DeinitNotifyingAsyncBrick: Brick { override class var cellClass: UICollectionViewCell.Type? { return DeinitNotifyingAsyncBrickCell.self } }
apache-2.0
a286176f3fcfe230cf55a80b65d3de6b
28.87931
161
0.729948
4.854342
false
false
false
false
chenyunguiMilook/VisualDebugger
Sources/VisualDebugger/extensions/AppView.swift
1
1108
// // AppView.swift // VisualDebugger // // Created by chenyungui on 2018/3/19. // import Foundation #if os(iOS) || os(tvOS) import UIKit #else import Cocoa #endif #if os(macOS) internal class FlippedView: AppView { override var isFlipped: Bool { return true } } #endif extension AppView { func addSublayer(_ layer:CALayer) { #if os(iOS) self.layer.addSublayer(layer) #elseif os(macOS) if self.layer == nil { self.layer = CALayer() } self.layer?.addSublayer(layer) #endif } } // MARK: - CALayer extension CALayer { func setCenter(_ center:CGPoint) { let bounds = self.bounds let labelCenter = CGPoint(x: bounds.midX, y: bounds.midY) let offset = CGPoint(x: center.x - labelCenter.x, y: center.y - labelCenter.y) self.frame.origin = offset } func applyDefaultContentScale() { #if os(iOS) self.contentsScale = UIScreen.main.scale #elseif os(macOS) self.contentsScale = NSScreen.main?.backingScaleFactor ?? 1 #endif } }
mit
fc78d64b0acca0d542e724a727d4dc33
19.90566
86
0.602888
3.693333
false
false
false
false
longjianjiang/Drizzling
Drizzling/Drizzling/Controller/LJAskNotificationViewController.swift
1
1881
// // LJAskNotificationViewController.swift // Drizzling // // Created by longjianjiang on 2017/10/19. // Copyright © 2017年 Jiang. All rights reserved. // import UIKit import UserNotifications class LJAskNotificationViewController: UIViewController { @IBOutlet weak var msgLabel: UILabel! @IBOutlet weak var yesBtn: UIButton! @IBOutlet weak var noBtn: UIButton! @IBAction func didClickBtn(_ sender: UIButton) { let defaults = UserDefaults.standard if sender == yesBtn { AppDelegate.askNotification() } defaults.setValue(LJConstants.UserDefaultsValue.chooseNotification, forKey: LJConstants.UserDefaultsKey.askNotification) view.window?.rootViewController = LJCityListViewController() } override func viewDidLoad() { super.viewDidLoad() msgLabel.numberOfLines = 0 msgLabel.lineBreakMode = NSLineBreakMode.byWordWrapping msgLabel.text = "Allow us to access notifications so we can alert you to the weather condition everyday" yesBtn.layer.cornerRadius = 20 yesBtn.layer.borderWidth = 1.0 yesBtn.layer.borderColor = UIColor.white.cgColor yesBtn.setTitle("Sounds great", for: .normal) noBtn.setTitle("No, thanks", for: .normal) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
1fd7abc9191c5ecef840ca1039ed20e0
29.786885
128
0.669329
5.103261
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/remove-duplicates-from-sorted-array.swift
2
924
/** * https://leetcode.com/problems/remove-duplicates-from-sorted-array/ * * */ class Solution { func removeDuplicates(_ nums: inout [Int]) -> Int { var index = 0 while index + 1 < nums.count { if nums[index] == nums[index + 1] { nums.remove(at: index + 1) } else { index += 1 } } return nums.count } } /** * https://leetcode.com/problems/remove-duplicates-from-sorted-array/ * * */ // Date: Fri May 1 23:07:50 PDT 2020 class Solution { func removeDuplicates(_ nums: inout [Int]) -> Int { if nums.count < 2 { return nums.count } var start = 1 for index in 1 ..< nums.count { if nums[index] != nums[index - 1] { nums[start] = nums[index] start += 1 } } // print("\(start)") return start } }
mit
0cfe029e96ad10a2f6c4a09ec742b6fa
23.342105
69
0.481602
3.85
false
false
false
false
ifLab/iCampus-iOS
iCampus/AppDelegate.swift
1
6591
// // AppDelegate.swift // iCampus // // Created by Bill Hu on 2017/4/6. // Copyright © 2017年 ifLab. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var navigationController: UINavigationController? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.maininit() // window = UIWindow(frame: UIScreen.main.bounds) // window?.rootViewController = TestViewController() // window?.makeKeyAndVisible() return true } func maininit(){ UITabBar.appearance().isTranslucent = false // init bmobSMS SMSSDK.registerApp(ICNetworkManager.default().smSappKey, withSecret: ICNetworkManager.default().smSappSecret) window = UIWindow(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)) // init tabBarVC let tabBarC = ZKTabBarViewController.init() window?.rootViewController = tabBarC window?.makeKeyAndVisible() // 登录时间判断 let lastTime = UserDefaults.standard.object(forKey: kUserLastLoginTimeDefaultKey) as? Date var loginInterval:Double = 3600 * 24 if let lastTime = lastTime { loginInterval = Date().timeIntervalSince(lastTime) } let timeout = loginInterval >= 3600 * 24 //判断是否登入,不登入弹出登入controller if !UserModel.isLogin() || timeout { if timeout { UserModel.logout() } let controller = ZKLoginViewController.init() tabBarC.present(controller as UIViewController, animated: true, completion: nil) } // UM // // open log // UMSocialManager.default().openLog(true) // // set key // UMSocialManager.default().umSocialAppkey = "59d0e2f69f06fd268d00003e" // UMConfigure.initWithAppkey("59d0e2f69f06fd268d00003e", channel: "App Store") // let _ = MobClick.setScenarioType(eScenarioType(rawValue: 0)!) // /* 设置第三方平台 */ // self.umengSharePlatforms() /* ZK Token刷新机制*/ // let file = NSHomeDirectory() + "/Documents/user.data" // 判断是否user.data文件是否存在 // if (FileManager.default.fileExists(atPath: file)){ // // 用户存在 // // 不是第一次登录 // // 获取用户 // let user:PJUser = NSKeyedUnarchiver.unarchiveObject(withFile: file) as! PJUser // // let formatter = DateFormatter() // formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // let lastTime = formatter.date(from: user.last_login_date)! // let thisTime = Date() // // let timeInterval = thisTime.timeIntervalSince(lastTime) // // //时间差计算 3600 * 24 // if (timeInterval >= 3600 * 24){ // //超过一天未使用app // let alertController = UIAlertController(title: "自动登录失败", message: "您已长时间未使用本APP,为了您的账号安全,请重新登录", preferredStyle: .alert) // let okAction = UIAlertAction(title: "好的", style: .default, handler:{ // (UIAlertAction) -> Void in // //退出账号 // let vc = Bundle.main.loadNibNamed("ICLoginViewController", owner: nil, options: nil)?.first // self.window?.rootViewController?.present(vc as! UIViewController, animated: true, completion: { // ICNetworkManager.default().token = "" //如果没有此句代码,点击个人中心之后首先弹出的是CAS认证而不是账号登录 // PJUser.logOut() // }) // }) // alertController.addAction(okAction) // self.window?.rootViewController?.present(alertController, animated: true, completion: nil) // } // }else{ // print("第一次登录") // } } func umengSharePlatforms() { //微信 UMSocialManager.default().setPlaform(UMSocialPlatformType.wechatSession, appKey: "wx0ef1e170ebdfdc4a", appSecret: "725104c3ba35661df23eb970ce57df47", redirectURL: nil) //新浪微博 UMSocialManager.default().setPlaform(UMSocialPlatformType.sina, appKey: "2449930345", appSecret: "089240e283d1250d819e923de41aabd0", redirectURL: nil) //QQ UMSocialManager.default().setPlaform(UMSocialPlatformType.QQ, appKey: "1106660518", appSecret: "FNDO4FER7ayOhgSW", redirectURL: nil) } //友盟回调机制 func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { let result = UMSocialManager.default().handleOpen(url) if result { print("分享成功") }else{ print("分享失败") } return true } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { // let file = NSHomeDirectory() + "/Documents/user.data" // if (FileManager.default.fileExists(atPath: file)){ // //用户存在 // //不是第一次登录 // //获取用户 // let user:PJUser = NSKeyedUnarchiver.unarchiveObject(withFile: file) as! PJUser // // let formatter = DateFormatter() // formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // let lastTime = formatter.date(from: user.last_login_date)! // let thisTime = Date() // // let timeInterval = thisTime.timeIntervalSince(lastTime) // // //时间差计算 3600 * 24 // if (timeInterval <= 3600 * 24){ // //未超过一天 // //使用现有方法更新Session // ICLoginManager.refreshToken() { // _ in // } // } // } } }
gpl-2.0
689067e9e85907cb87643f9f74d70ba7
36.349398
175
0.582419
4.460432
false
false
false
false
bjarnoldus/textsearchr
textsearchr/String-Extras.swift
1
1067
// // String-Extras.swift // Swift Tools // // Created by Fahim Farook on 23/7/14. // Copyright (c) 2014 RookSoft Pte. Ltd. All rights reserved. // #if os(iOS) import UIKit #else import AppKit #endif extension String { func positionOf(sub:String)->Int { var pos = -1 if let range = self.rangeOfString(sub) { if !range.isEmpty { pos = distance(self.startIndex, range.startIndex) } } return pos } func subStringFrom(pos:Int)->String { var substr = "" let start = advance(self.startIndex, pos) let end = self.endIndex // println("String: \(self), start:\(start), end: \(end)") let range = start..<end substr = self[range] // println("Substring: \(substr)") return substr } func subStringTo(pos:Int)->String { var substr = "" let end = advance(self.startIndex, pos-1) let range = self.startIndex...end substr = self[range] return substr } }
mit
4c02eb0ae13b20fa67e7e0ad57db3007
23.25
67
0.547329
3.894161
false
false
false
false
alsoyay/AYSwift
Pod/Classes/AYSource.swift
1
860
// // Created by Dani Postigo on 9/8/15. // import Foundation public class AYSource: NSObject { public var index: Int = 0 public var items: [AnyObject] public var count:Int { return self.items.count } public subscript(index: Int) -> AnyObject { get { return self.items[index] } set { self.items[index] = newValue } } public init(index: Int, items: [AnyObject] = []) { self.index = index self.items = items } public func move(item: AnyObject, destination: AYSource, index: Int) { let array = (self.items as NSArray) if array.containsObject(item) { let index = array.indexOfObject(item) self.items.removeAtIndex(index) destination.items.insert(item, atIndex: index) } } }
mit
02db7c1f0768901e15a448c88d59119e
19.97561
74
0.566279
4.056604
false
false
false
false
feistydog/FeistyDB
Sources/FeistyDB/DatabaseReadQueue.swift
1
9197
// // Copyright (c) 2018 - 2022 Feisty Dog, LLC // // See https://github.com/feistydog/FeistyDB/blob/master/LICENSE.txt for license information // import Foundation import CSQLite /// A queue providing serialized execution of read operations on a database. /// /// Normally read queues are used for concurrent read access to databases using WAL mode. /// /// A database read queue manages the execution of read-only database operations to /// ensure they occur one at a time in FIFO order. This provides thread-safe /// database access. /// /// Database read operations may be submitted for synchronous or asynchronous execution. /// /// It is possible to maintain a consistent snapshot of a database using read /// transactions. Changes committed to a database are not visible within a read transaction /// until the transaction is updated or restarted. /// /// The interface is similar to `DispatchQueue` and a dispatch queue is used /// internally for work item management. public final class DatabaseReadQueue { /// The underlying database let database: Database /// The dispatch queue used to serialize access to the underlying database connection public let queue: DispatchQueue /// Creates a database read queue for serialized read access to a database from a file. /// /// - parameter url: The location of the SQLite database /// - parameter label: The label to attach to the queue /// - parameter qos: The quality of service class for the work performed by the database queue /// - parameter target: The target dispatch queue on which to execute blocks /// /// - throws: An error if the database could not be opened public init(url: URL, label: String, qos: DispatchQoS = .default, target: DispatchQueue? = nil) throws { self.database = try Database(readingFrom: url) self.queue = DispatchQueue(label: label, qos: qos, target: target) } /// Creates a database read queue for serialized read access to an existing database. /// /// - attention: The database queue takes ownership of `database`. The result of further use of `database` is undefined. /// /// - parameter database: The database to be serialized /// - parameter label: The label to attach to the queue /// - parameter qos: The quality of service class for the work performed by the database queue /// - parameter target: The target dispatch queue on which to execute blocks public init(database: Database, label: String, qos: DispatchQoS = .default, target: DispatchQueue? = nil) { self.database = database self.queue = DispatchQueue(label: label, qos: qos, target: target) } /// Begins a long-running read transaction on the database. /// /// - throws: An error if the transaction could not be started public func beginReadTransaction() throws { try sync { db in try db.beginReadTransaction() } } /// Ends a long-running read transaction on the database. /// /// - throws: An error if the transaction could not be rolled back public func endReadTransaction() throws { try sync { db in try db.endReadTransaction() } } /// Updates a long-running read transaction to make the latest database changes visible. /// /// If there is an active read transaction it is ended before beginning a new read transaction. /// /// - throws: An error if the transaction could not be rolled back or started public func updateReadTransaction() throws { try sync { db in try db.updateReadTransaction() } } /// Performs a synchronous read operation on the database. /// /// - parameter block: A closure performing the database operation /// - parameter database: A `Database` used for database access within `block` /// /// - throws: Any error thrown in `block` /// /// - returns: The value returned by `block` public func sync<T>(block: (_ database: Database) throws -> (T)) rethrows -> T { return try queue.sync { return try block(self.database) } } /// A block called with the result of an asynchronous database operation. /// /// - parameter result: A `Result` object containing the result of the operation. public typealias CompletionHandler<T> = (_ result: Result<T, Swift.Error>) -> Void /// Submits an asynchronous read operation to the database queue. /// /// - parameter group: An optional `DispatchGroup` with which to associate `block` /// - parameter qos: The quality of service for `block` /// - parameter block: A closure performing the database operation /// - parameter database: A `Database` used for database access within `block` /// - parameter completion: A closure called with the result of the operation. public func async<T>(group: DispatchGroup? = nil, qos: DispatchQoS = .unspecified, block: @escaping (_ database: Database) throws -> T, completion: @escaping CompletionHandler<T>) { queue.async(group: group, qos: qos) { do { let result = try block(self.database) completion(.success(result)) } catch let error { completion(.failure(error)) } } } /// Performs a synchronous read transaction on the database. /// /// - parameter block: A closure performing the database operation. /// /// - throws: Any error thrown in `block` or an error if the transaction could not be started or rolled back. /// /// - note: If `block` throws an error the transaction will be rolled back and the error will be re-thrown. public func readTransaction(_ block: (_ database: Database) throws -> Void) throws { try queue.sync { try database.readTransaction(block) } } /// Submits an asynchronous read transaction to the database queue. /// /// - parameter group: An optional `DispatchGroup` with which to associate `block` /// - parameter qos: The quality of service for `block` /// - parameter block: A closure performing the database operation /// - parameter completion: A closure called with the result of the read transaction. public func asyncReadTransaction(group: DispatchGroup? = nil, qos: DispatchQoS = .default, _ block: @escaping (_ database: Database) -> Void, completion: @escaping CompletionHandler<Void>) { queue.async(group: group, qos: qos) { do { try self.database.readTransaction(block) completion(.success(())) } catch let error { completion(.failure(error)) } } } } extension DatabaseReadQueue { /// Creates a database read queue for serialized read access to a database from the file corresponding to the database *main* on a write queue. /// /// - note: The QoS for the database queue is set to the QoS of `writeQueue` /// /// - parameter writeQueue: A database queue for the SQLite database /// - parameter label: The label to attach to the queue /// /// - throws: An error if the database could not be opened public convenience init(writeQueue: DatabaseQueue, label: String) throws { try self.init(writeQueue: writeQueue, label: label, qos: writeQueue.queue.qos) } /// Creates a database read queue for serialized read access to a database from the file corresponding to the database *main* on a write queue. /// /// - parameter writeQueue: A database queue for the SQLite database /// - parameter label: The label to attach to the queue /// - parameter qos: The quality of service class for the work performed by the database queue /// - parameter target: The target dispatch queue on which to execute blocks /// /// - throws: An error if the database could not be opened public convenience init(writeQueue: DatabaseQueue, label: String, qos: DispatchQoS, target: DispatchQueue? = nil) throws { let url = try writeQueue.sync { db in return try db.url(forDatabase: "main") } try self.init(url: url, label: label, qos: qos, target: target) } } extension Database { /// Begins a long-running read transaction on the database. /// /// This is equivalent to the SQL `BEGIN DEFERRED TRANSACTION;` /// /// - throws: An error if the transaction could not be started public func beginReadTransaction() throws { try begin(type: .deferred) } /// Ends a long-running read transaction on the database. /// /// This is equivalent to the SQL `ROLLBACK;` /// /// - throws: An error if the transaction could not be rolled back public func endReadTransaction() throws { try rollback() } /// Updates a long-running read transaction to make the latest database changes visible. /// /// If there is an active read transaction it is ended before beginning a new read transaction. /// /// - throws: An error if the transaction could not be started public func updateReadTransaction() throws { if !isInAutocommitMode { try rollback() } try beginReadTransaction() } /// Performs a read transaction on the database. /// /// - parameter block: A closure performing the database operation. /// /// - throws: Any error thrown in `block` or an error if the transaction could not be started or rolled back. /// /// - note: If `block` throws an error the transaction will be rolled back and the error will be re-thrown. public func readTransaction(_ block: (_ database: Database) throws -> Void) throws { try begin(type: .deferred) do { try block(self) try rollback() } catch let error { if !isInAutocommitMode { try rollback() } throw error } } }
mit
304f03b5310aa8dc592bb259a81d8850
38.13617
191
0.716212
4.032004
false
false
false
false
riamf/BendCell
BendCell/BendCell/BendView.swift
1
2751
// // BendView.swift // BendCell // // Created by Pawel Kowalczuk on 03/05/2017. // Copyright © 2017 Pawel Kowalczuk. All rights reserved. // import Foundation import UIKit class BendView: UIView { enum Constants { static let MaxY: CGFloat = 20.0 static let point3: CGFloat = 0.33 } fileprivate var rectFrame = CAShapeLayer() fileprivate var originalColor: UIColor required init?(coder aDecoder: NSCoder) { fatalError("Should not be initialized this way!") } override init(frame: CGRect) { fatalError("Should not be initialized this way!") } init(frame: CGRect, color: UIColor) { originalColor = color super.init(frame: frame) backgroundColor = nil addRectFrame() } func update(_ color: UIColor) { originalColor = color rectFrame.fillColor = color.cgColor rectFrame.strokeColor = color.cgColor } override var frame: CGRect { didSet { rectFrame.path = UIBezierPath(rect: frame).cgPath } } fileprivate func addRectFrame() { rectFrame.path = UIBezierPath(rect: frame).cgPath rectFrame.strokeColor = originalColor.cgColor rectFrame.lineWidth = 1.0 rectFrame.fillColor = rectFrame.strokeColor layer.addSublayer(rectFrame) } func draw(with velocity: CGFloat, directionUp: Bool) { guard velocity != 0.0 else { rectFrame.path = UIBezierPath(rect: frame).cgPath return } let maxY = min(velocity, Constants.MaxY) let pThirdWidth: CGFloat = frame.size.width * Constants.point3 let maxYWithDirection: CGFloat = directionUp ? -maxY : maxY let path = UIBezierPath() path.move(to: .zero) let ctrlPoint1 = CGPoint(x: pThirdWidth, y: maxYWithDirection) let ctrlPoint2 = CGPoint(x: frame.size.width - pThirdWidth, y: maxYWithDirection) path.addCurve(to: CGPoint(x:frame.size.width, y: 0.0), controlPoint1: ctrlPoint1, controlPoint2: ctrlPoint2) path.addLine(to: CGPoint(x: frame.size.width, y: frame.size.height)) let ctrlPoint3 = CGPoint(x: frame.size.width - pThirdWidth, y: frame.size.height + maxYWithDirection) let ctrlPoint4 = CGPoint(x: pThirdWidth, y: frame.size.height + maxYWithDirection) path.addCurve(to: CGPoint(x: 0.0, y: frame.size.height), controlPoint1: ctrlPoint3, controlPoint2: ctrlPoint4) path.addLine(to: .zero) path.close() rectFrame.path = path.cgPath } }
mit
c12bab7a7e92456b4eafff3a599d242c
29.898876
90
0.602545
4.486134
false
false
false
false
EddieCeausu/Projects
swift/99 Bottles of Beer/99bottlesofbeer.swift
1
454
import Foundation func beer() { var beer: Int = 99 while beer >= 1 { print("\(beer) bottles of beer on the wall") print("\(beer) bottles of beer") print("Take one down, pass it around") print("\(beer -= 1) bottles of beer on the wall") if beer == 1 { print("One bottle of beer on the wall \n One bottle of beer ") print("Take one down, pass it around") print("0 bottles of beer on the wall") } } } beer()
gpl-3.0
9129b93cf964a92a22c888ce6c79a15c
27.375
68
0.596916
3.752066
false
false
false
false
apple/swift-corelibs-foundation
Sources/Foundation/Data.swift
1
130298
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// #if DEPLOYMENT_RUNTIME_SWIFT #if canImport(Glibc) @usableFromInline let calloc = Glibc.calloc @usableFromInline let malloc = Glibc.malloc @usableFromInline let free = Glibc.free @usableFromInline let memset = Glibc.memset @usableFromInline let memcpy = Glibc.memcpy @usableFromInline let memcmp = Glibc.memcmp #elseif canImport(WASILibc) @usableFromInline let calloc = WASILibc.calloc @usableFromInline let malloc = WASILibc.malloc @usableFromInline let free = WASILibc.free @usableFromInline let memset = WASILibc.memset @usableFromInline let memcpy = WASILibc.memcpy @usableFromInline let memcmp = WASILibc.memcmp #endif #if !canImport(Darwin) @inlinable // This is @inlinable as trivially computable. internal func malloc_good_size(_ size: Int) -> Int { return size } #endif @_implementationOnly import CoreFoundation #if canImport(Glibc) import Glibc #elseif canImport(WASILibc) import WASILibc #endif internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) { #if os(Windows) UnmapViewOfFile(mem) #else munmap(mem, length) #endif } internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) { free(mem) } internal func __NSDataIsCompact(_ data: NSData) -> Bool { return data._isCompact() } #else @_exported import Foundation // Clang module import _SwiftFoundationOverlayShims import _SwiftCoreFoundationOverlayShims internal func __NSDataIsCompact(_ data: NSData) -> Bool { if #available(OSX 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) { return data._isCompact() } else { var compact = true let len = data.length data.enumerateBytes { (_, byteRange, stop) in if byteRange.length != len { compact = false } stop.pointee = true } return compact } } #endif @usableFromInline @discardableResult internal func __withStackOrHeapBuffer(_ size: Int, _ block: (UnsafeMutableRawPointer, Int, Bool) -> Void) -> Bool { return _withStackOrHeapBufferWithResultInArguments(size, block) } // Underlying storage representation for medium and large data. // Inlinability strategy: methods from here should not inline into InlineSlice or LargeSlice unless trivial. // NOTE: older overlays called this class _DataStorage. The two must // coexist without a conflicting ObjC class name, so it was renamed. // The old name must not be used in the new runtime. @usableFromInline internal final class __DataStorage { @usableFromInline static let maxSize = Int.max >> 1 @usableFromInline static let vmOpsThreshold = NSPageSize() * 4 @inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer. static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? { if clear { return calloc(1, size) } else { return malloc(size) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) { var dest = dest_ var source = source_ var num = num_ if __DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 { let pages = NSRoundDownToMultipleOfPageSize(num) NSCopyMemoryPages(source!, dest, pages) source = source!.advanced(by: pages) dest = dest.advanced(by: pages) num -= pages } if num > 0 { memmove(dest, source!, num) } } @inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer. static func shouldAllocateCleared(_ size: Int) -> Bool { return (size > (128 * 1024)) } @usableFromInline var _bytes: UnsafeMutableRawPointer? @usableFromInline var _length: Int @usableFromInline var _capacity: Int @usableFromInline var _needToZero: Bool @usableFromInline var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? @usableFromInline var _offset: Int @inlinable // This is @inlinable as trivially computable. var bytes: UnsafeRawPointer? { return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding. @discardableResult func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length))) } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding. @discardableResult func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length))) } @inlinable // This is @inlinable as trivially computable. var mutableBytes: UnsafeMutableRawPointer? { return _bytes?.advanced(by: -_offset) } @inlinable // This is @inlinable as trivially computable. var capacity: Int { return _capacity } @inlinable // This is @inlinable as trivially computable. var length: Int { get { return _length } set { setLength(newValue) } } @inlinable // This is inlinable as trivially computable. var isExternallyOwned: Bool { // all __DataStorages will have some sort of capacity, because empty cases hit the .empty enum _Representation // anything with 0 capacity means that we have not allocated this pointer and consequently mutation is not ours to make. return _capacity == 0 } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. func ensureUniqueBufferReference(growingTo newLength: Int = 0, clear: Bool = false) { guard isExternallyOwned || newLength > _capacity else { return } if newLength == 0 { if isExternallyOwned { let newCapacity = malloc_good_size(_length) let newBytes = __DataStorage.allocate(newCapacity, false) __DataStorage.move(newBytes!, _bytes!, _length) _freeBytes() _bytes = newBytes _capacity = newCapacity _needToZero = false } } else if isExternallyOwned { let newCapacity = malloc_good_size(newLength) let newBytes = __DataStorage.allocate(newCapacity, clear) if let bytes = _bytes { __DataStorage.move(newBytes!, bytes, _length) } _freeBytes() _bytes = newBytes _capacity = newCapacity _length = newLength _needToZero = true } else { let cap = _capacity var additionalCapacity = (newLength >> (__DataStorage.vmOpsThreshold <= newLength ? 2 : 1)) if Int.max - additionalCapacity < newLength { additionalCapacity = 0 } var newCapacity = malloc_good_size(Swift.max(cap, newLength + additionalCapacity)) let origLength = _length var allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity) var newBytes: UnsafeMutableRawPointer? = nil if _bytes == nil { newBytes = __DataStorage.allocate(newCapacity, allocateCleared) if newBytes == nil { /* Try again with minimum length */ allocateCleared = clear && __DataStorage.shouldAllocateCleared(newLength) newBytes = __DataStorage.allocate(newLength, allocateCleared) } } else { let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4) if allocateCleared && tryCalloc { newBytes = __DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { __DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } /* Where calloc/memmove/free fails, realloc might succeed */ if newBytes == nil { allocateCleared = false if _deallocator != nil { newBytes = __DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { __DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } else { newBytes = realloc(_bytes!, newCapacity) } } /* Try again with minimum length */ if newBytes == nil { newCapacity = malloc_good_size(newLength) allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity) if allocateCleared && tryCalloc { newBytes = __DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { __DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } if newBytes == nil { allocateCleared = false newBytes = realloc(_bytes!, newCapacity) } } } if newBytes == nil { /* Could not allocate bytes */ // At this point if the allocation cannot occur the process is likely out of memory // and Bad-Things™ are going to happen anyhow fatalError("unable to allocate memory for length (\(newLength))") } if origLength < newLength && clear && !allocateCleared { memset(newBytes!.advanced(by: origLength), 0, newLength - origLength) } /* _length set by caller */ _bytes = newBytes _capacity = newCapacity /* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */ _needToZero = !allocateCleared } } @inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer. func _freeBytes() { if let bytes = _bytes { if let dealloc = _deallocator { dealloc(bytes, length) } else { free(bytes) } } _deallocator = nil } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed. func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) { var stopv: Bool = false block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.upperBound - range.lowerBound, _length)), 0, &stopv) } @inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer. func setLength(_ length: Int) { let origLength = _length let newLength = length if _capacity < newLength || _bytes == nil { ensureUniqueBufferReference(growingTo: newLength, clear: true) } else if origLength < newLength && _needToZero { memset(_bytes! + origLength, 0, newLength - origLength) } else if newLength < origLength { _needToZero = true } _length = newLength } @inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer. func append(_ bytes: UnsafeRawPointer, length: Int) { precondition(length >= 0, "Length of appending bytes must not be negative") let origLength = _length let newLength = origLength + length if _capacity < newLength || _bytes == nil { ensureUniqueBufferReference(growingTo: newLength, clear: false) } _length = newLength __DataStorage.move(_bytes!.advanced(by: origLength), bytes, length) } @inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed. func get(_ index: Int) -> UInt8 { return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed. func set(_ index: Int, to value: UInt8) { ensureUniqueBufferReference() _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { let offsetPointer = UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length)) UnsafeMutableRawBufferPointer(start: pointer, count: range.upperBound - range.lowerBound).copyMemory(from: offsetPointer) } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) { let range = NSRange(location: range_.location - _offset, length: range_.length) let currentLength = _length let resultingLength = currentLength - range.length + replacementLength let shift = resultingLength - currentLength let mutableBytes: UnsafeMutableRawPointer if resultingLength > currentLength { ensureUniqueBufferReference(growingTo: resultingLength) _length = resultingLength } else { ensureUniqueBufferReference() } mutableBytes = _bytes! /* shift the trailing bytes */ let start = range.location let length = range.length if shift != 0 { memmove(mutableBytes + start + replacementLength, mutableBytes + start + length, currentLength - start - length) } if replacementLength != 0 { if let replacementBytes = replacementBytes { memmove(mutableBytes + start, replacementBytes, replacementLength) } else { memset(mutableBytes + start, 0, replacementLength) } } if resultingLength < currentLength { setLength(resultingLength) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. func resetBytes(in range_: Range<Int>) { let range = NSRange(location: range_.lowerBound - _offset, length: range_.upperBound - range_.lowerBound) if range.length == 0 { return } if _length < range.location + range.length { let newLength = range.location + range.length if _capacity <= newLength { ensureUniqueBufferReference(growingTo: newLength, clear: false) } _length = newLength } else { ensureUniqueBufferReference() } memset(_bytes!.advanced(by: range.location), 0, range.length) } @usableFromInline // This is not @inlinable as a non-trivial, non-convenience initializer. init(length: Int) { precondition(length < __DataStorage.maxSize) var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length if __DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } let clear = __DataStorage.shouldAllocateCleared(length) _bytes = __DataStorage.allocate(capacity, clear)! _capacity = capacity _needToZero = !clear _length = 0 _offset = 0 setLength(length) } @usableFromInline // This is not @inlinable as a non-convenience initializer. init(capacity capacity_: Int = 0) { var capacity = capacity_ precondition(capacity < __DataStorage.maxSize) if __DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = 0 _bytes = __DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _offset = 0 } @usableFromInline // This is not @inlinable as a non-convenience initializer. init(bytes: UnsafeRawPointer?, length: Int) { precondition(length < __DataStorage.maxSize) _offset = 0 if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil } else if __DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = __DataStorage.allocate(length, false)! __DataStorage.move(_bytes!, bytes, length) } else { var capacity = length if __DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = __DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true __DataStorage.move(_bytes!, bytes, length) } } @usableFromInline // This is not @inlinable as a non-convenience initializer. init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) { precondition(length < __DataStorage.maxSize) _offset = offset if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil if let dealloc = deallocator, let bytes_ = bytes { dealloc(bytes_, length) } } else if !copy { _capacity = length _length = length _needToZero = false _bytes = bytes _deallocator = deallocator } else if __DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = __DataStorage.allocate(length, false)! __DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } else { var capacity = length if __DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = __DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true __DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } } @usableFromInline // This is not @inlinable as a non-convenience initializer. init(immutableReference: NSData, offset: Int) { _offset = offset _bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes) _capacity = 0 _needToZero = false _length = immutableReference.length _deallocator = { _, _ in _fixLifetime(immutableReference) } } @usableFromInline // This is not @inlinable as a non-convenience initializer. init(mutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = mutableReference.mutableBytes _capacity = 0 _needToZero = false _length = mutableReference.length _deallocator = { _, _ in _fixLifetime(mutableReference) } } @usableFromInline // This is not @inlinable as a non-convenience initializer. init(customReference: NSData, offset: Int) { _offset = offset _bytes = UnsafeMutableRawPointer(mutating: customReference.bytes) _capacity = 0 _needToZero = false _length = customReference.length _deallocator = { _, _ in _fixLifetime(customReference) } } @usableFromInline // This is not @inlinable as a non-convenience initializer. init(customMutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = customMutableReference.mutableBytes _capacity = 0 _needToZero = false _length = customMutableReference.length _deallocator = { _, _ in _fixLifetime(customMutableReference) } } deinit { _freeBytes() } @inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed. func mutableCopy(_ range: Range<Int>) -> __DataStorage { return __DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, copy: true, deallocator: nil, offset: range.lowerBound) } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially computed. func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T { if range.isEmpty { return try work(NSData()) // zero length data can be optimized as a singleton } return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, freeWhenDone: false)) } @inline(never) // This is not @inlinable to avoid emission of the private `__NSSwiftData` class name into clients. @usableFromInline func bridgedReference(_ range: Range<Int>) -> NSData { if range.isEmpty { return NSData() // zero length data can be optimized as a singleton } return __NSSwiftData(backing: self, range: range) } } // NOTE: older overlays called this _NSSwiftData. The two must // coexist, so it was renamed. The old name must not be used in the new // runtime. internal class __NSSwiftData : NSData { var _backing: __DataStorage! var _range: Range<Data.Index>! override var classForCoder: AnyClass { return NSData.self } override init() { fatalError() } private init(_correctly: Void) { super.init() } convenience init(backing: __DataStorage, range: Range<Data.Index>) { self.init(_correctly: ()) _backing = backing _range = range } public required init?(coder aDecoder: NSCoder) { fatalError("This should have been encoded as NSData.") } override func encode(with aCoder: NSCoder) { // This should encode this object just like NSData does, and .classForCoder should do the rest. super.encode(with: aCoder) } override var length: Int { return _range.upperBound - _range.lowerBound } override var bytes: UnsafeRawPointer { // NSData's byte pointer methods are not annotated for nullability correctly // (but assume non-null by the wrapping macro guards). This placeholder value // is to work-around this bug. Any indirection to the underlying bytes of an NSData // with a length of zero would have been a programmer error anyhow so the actual // return value here is not needed to be an allocated value. This is specifically // needed to live like this to be source compatible with Swift3. Beyond that point // this API may be subject to correction. guard let bytes = _backing.bytes else { return UnsafeRawPointer(bitPattern: 0xBAD0)! } return bytes.advanced(by: _range.lowerBound) } override func copy(with zone: NSZone? = nil) -> Any { return self } override func mutableCopy(with zone: NSZone? = nil) -> Any { return NSMutableData(bytes: bytes, length: length) } #if !DEPLOYMENT_RUNTIME_SWIFT @objc override func _isCompact() -> Bool { return true } #endif #if DEPLOYMENT_RUNTIME_SWIFT override func _providesConcreteBacking() -> Bool { return true } #else @objc(_providesConcreteBacking) func _providesConcreteBacking() -> Bool { return true } #endif } @frozen public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection, MutableDataProtocol, ContiguousBytes { public typealias ReferenceType = NSData public typealias ReadingOptions = NSData.ReadingOptions public typealias WritingOptions = NSData.WritingOptions public typealias SearchOptions = NSData.SearchOptions public typealias Base64EncodingOptions = NSData.Base64EncodingOptions public typealias Base64DecodingOptions = NSData.Base64DecodingOptions public typealias Index = Int public typealias Indices = Range<Int> // A small inline buffer of bytes suitable for stack-allocation of small data. // Inlinability strategy: everything here should be inlined for direct operation on the stack wherever possible. @usableFromInline @frozen internal struct InlineData { #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) @usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) //len //enum @usableFromInline var bytes: Buffer #elseif arch(i386) || arch(arm) || arch(wasm32) @usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) //len //enum @usableFromInline var bytes: Buffer #else #error("This architecture isn't known. Add it to the 32-bit or 64-bit line.") #endif @usableFromInline var length: UInt8 @inlinable // This is @inlinable as trivially computable. static func canStore(count: Int) -> Bool { return count <= MemoryLayout<Buffer>.size } @inlinable // This is @inlinable as a convenience initializer. init(_ srcBuffer: UnsafeRawBufferPointer) { self.init(count: srcBuffer.count) if srcBuffer.count > 0 { Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in dstBuffer.baseAddress?.copyMemory(from: srcBuffer.baseAddress!, byteCount: srcBuffer.count) } } } @inlinable // This is @inlinable as a trivial initializer. init(count: Int = 0) { assert(count <= MemoryLayout<Buffer>.size) #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0)) #elseif arch(i386) || arch(arm) || arch(wasm32) bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0)) #else #error("This architecture isn't known. Add it to the 32-bit or 64-bit line.") #endif length = UInt8(count) } @inlinable // This is @inlinable as a convenience initializer. init(_ slice: InlineSlice, count: Int) { self.init(count: count) Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in slice.withUnsafeBytes { srcBuffer in dstBuffer.copyMemory(from: UnsafeRawBufferPointer(start: srcBuffer.baseAddress, count: count)) } } } @inlinable // This is @inlinable as a convenience initializer. init(_ slice: LargeSlice, count: Int) { self.init(count: count) Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in slice.withUnsafeBytes { srcBuffer in dstBuffer.copyMemory(from: UnsafeRawBufferPointer(start: srcBuffer.baseAddress, count: count)) } } } @inlinable // This is @inlinable as trivially computable. var capacity: Int { return MemoryLayout<Buffer>.size } @inlinable // This is @inlinable as trivially computable. var count: Int { get { return Int(length) } set(newValue) { assert(newValue <= MemoryLayout<Buffer>.size) length = UInt8(newValue) } } @inlinable // This is @inlinable as trivially computable. var startIndex: Int { return 0 } @inlinable // This is @inlinable as trivially computable. var endIndex: Int { return count } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { let count = Int(length) return try Swift.withUnsafeBytes(of: bytes) { (rawBuffer) throws -> Result in return try apply(UnsafeRawBufferPointer(start: rawBuffer.baseAddress, count: count)) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { let count = Int(length) return try Swift.withUnsafeMutableBytes(of: &bytes) { (rawBuffer) throws -> Result in return try apply(UnsafeMutableRawBufferPointer(start: rawBuffer.baseAddress, count: count)) } } @inlinable // This is @inlinable as trivially computable. mutating func append(byte: UInt8) { let count = self.count assert(count + 1 <= MemoryLayout<Buffer>.size) Swift.withUnsafeMutableBytes(of: &bytes) { $0[count] = byte } self.length += 1 } @inlinable // This is @inlinable as trivially computable. mutating func append(contentsOf buffer: UnsafeRawBufferPointer) { guard buffer.count > 0 else { return } assert(count + buffer.count <= MemoryLayout<Buffer>.size) let cnt = count _ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in rawBuffer.baseAddress?.advanced(by: cnt).copyMemory(from: buffer.baseAddress!, byteCount: buffer.count) } length += UInt8(buffer.count) } @inlinable // This is @inlinable as trivially computable. subscript(index: Index) -> UInt8 { get { assert(index <= MemoryLayout<Buffer>.size) precondition(index < length, "index \(index) is out of bounds of 0..<\(length)") return Swift.withUnsafeBytes(of: bytes) { rawBuffer -> UInt8 in return rawBuffer[index] } } set(newValue) { assert(index <= MemoryLayout<Buffer>.size) precondition(index < length, "index \(index) is out of bounds of 0..<\(length)") Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in rawBuffer[index] = newValue } } } @inlinable // This is @inlinable as trivially computable. mutating func resetBytes(in range: Range<Index>) { assert(range.lowerBound <= MemoryLayout<Buffer>.size) assert(range.upperBound <= MemoryLayout<Buffer>.size) precondition(range.lowerBound <= length, "index \(range.lowerBound) is out of bounds of 0..<\(length)") if count < range.upperBound { count = range.upperBound } let _ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in memset(rawBuffer.baseAddress!.advanced(by: range.lowerBound), 0, range.upperBound - range.lowerBound) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. mutating func replaceSubrange(_ subrange: Range<Index>, with replacementBytes: UnsafeRawPointer?, count replacementLength: Int) { assert(subrange.lowerBound <= MemoryLayout<Buffer>.size) assert(subrange.upperBound <= MemoryLayout<Buffer>.size) assert(count - (subrange.upperBound - subrange.lowerBound) + replacementLength <= MemoryLayout<Buffer>.size) precondition(subrange.lowerBound <= length, "index \(subrange.lowerBound) is out of bounds of 0..<\(length)") precondition(subrange.upperBound <= length, "index \(subrange.upperBound) is out of bounds of 0..<\(length)") let currentLength = count let resultingLength = currentLength - (subrange.upperBound - subrange.lowerBound) + replacementLength let shift = resultingLength - currentLength Swift.withUnsafeMutableBytes(of: &bytes) { mutableBytes in /* shift the trailing bytes */ let start = subrange.lowerBound let length = subrange.upperBound - subrange.lowerBound if shift != 0 { memmove(mutableBytes.baseAddress!.advanced(by: start + replacementLength), mutableBytes.baseAddress!.advanced(by: start + length), currentLength - start - length) } if replacementLength != 0 { memmove(mutableBytes.baseAddress!.advanced(by: start), replacementBytes!, replacementLength) } } count = resultingLength } @inlinable // This is @inlinable as trivially computable. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") Swift.withUnsafeBytes(of: bytes) { let cnt = Swift.min($0.count, range.upperBound - range.lowerBound) guard cnt > 0 else { return } pointer.copyMemory(from: $0.baseAddress!.advanced(by: range.lowerBound), byteCount: cnt) } } @inline(__always) // This should always be inlined into _Representation.hash(into:). func hash(into hasher: inout Hasher) { // **NOTE**: this uses `count` (an Int) and NOT `length` (a UInt8) // Despite having the same value, they hash differently. InlineSlice and LargeSlice both use `count` (an Int); if you combine the same bytes but with `length` over `count`, you can get a different hash. // // This affects slices, which are InlineSlice and not InlineData: // // let d = Data([0xFF, 0xFF]) // InlineData // let s = Data([0, 0xFF, 0xFF]).dropFirst() // InlineSlice // assert(s == d) // assert(s.hashValue == d.hashValue) hasher.combine(count) Swift.withUnsafeBytes(of: bytes) { // We have access to the full byte buffer here, but not all of it is meaningfully used (bytes past self.length may be garbage). let bytes = UnsafeRawBufferPointer(start: $0.baseAddress, count: self.count) hasher.combine(bytes: bytes) } } } #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) @usableFromInline internal typealias HalfInt = Int32 #elseif arch(i386) || arch(arm) || arch(wasm32) @usableFromInline internal typealias HalfInt = Int16 #else #error("This architecture isn't known. Add it to the 32-bit or 64-bit line.") #endif // A buffer of bytes too large to fit in an InlineData, but still small enough to fit a storage pointer + range in two words. // Inlinability strategy: everything here should be easily inlinable as large _DataStorage methods should not inline into here. @usableFromInline @frozen internal struct InlineSlice { // ***WARNING*** // These ivars are specifically laid out so that they cause the enum _Representation to be 16 bytes on 64 bit platforms. This means we _MUST_ have the class type thing last @usableFromInline var slice: Range<HalfInt> @usableFromInline var storage: __DataStorage @inlinable // This is @inlinable as trivially computable. static func canStore(count: Int) -> Bool { return count < HalfInt.max } @inlinable // This is @inlinable as a convenience initializer. init(_ buffer: UnsafeRawBufferPointer) { assert(buffer.count < HalfInt.max) self.init(__DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count) } @inlinable // This is @inlinable as a convenience initializer. init(capacity: Int) { assert(capacity < HalfInt.max) self.init(__DataStorage(capacity: capacity), count: 0) } @inlinable // This is @inlinable as a convenience initializer. init(count: Int) { assert(count < HalfInt.max) self.init(__DataStorage(length: count), count: count) } @inlinable // This is @inlinable as a convenience initializer. init(_ inline: InlineData) { assert(inline.count < HalfInt.max) self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, count: inline.count) } @inlinable // This is @inlinable as a convenience initializer. init(_ inline: InlineData, range: Range<Int>) { assert(range.lowerBound < HalfInt.max) assert(range.upperBound < HalfInt.max) self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, range: range) } @inlinable // This is @inlinable as a convenience initializer. init(_ large: LargeSlice) { assert(large.range.lowerBound < HalfInt.max) assert(large.range.upperBound < HalfInt.max) self.init(large.storage, range: large.range) } @inlinable // This is @inlinable as a convenience initializer. init(_ large: LargeSlice, range: Range<Int>) { assert(range.lowerBound < HalfInt.max) assert(range.upperBound < HalfInt.max) self.init(large.storage, range: range) } @inlinable // This is @inlinable as a trivial initializer. init(_ storage: __DataStorage, count: Int) { assert(count < HalfInt.max) self.storage = storage slice = 0..<HalfInt(count) } @inlinable // This is @inlinable as a trivial initializer. init(_ storage: __DataStorage, range: Range<Int>) { assert(range.lowerBound < HalfInt.max) assert(range.upperBound < HalfInt.max) self.storage = storage slice = HalfInt(range.lowerBound)..<HalfInt(range.upperBound) } @inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic). mutating func ensureUniqueReference() { if !isKnownUniquelyReferenced(&storage) { storage = storage.mutableCopy(self.range) } } @inlinable // This is @inlinable as trivially computable. var startIndex: Int { return Int(slice.lowerBound) } @inlinable // This is @inlinable as trivially computable. var endIndex: Int { return Int(slice.upperBound) } @inlinable // This is @inlinable as trivially computable. var capacity: Int { return storage.capacity } @inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic). mutating func reserveCapacity(_ minimumCapacity: Int) { ensureUniqueReference() // the current capacity can be zero (representing externally owned buffer), and count can be greater than the capacity storage.ensureUniqueBufferReference(growingTo: Swift.max(minimumCapacity, count)) } @inlinable // This is @inlinable as trivially computable. var count: Int { get { return Int(slice.upperBound - slice.lowerBound) } set(newValue) { assert(newValue < HalfInt.max) ensureUniqueReference() storage.length = newValue slice = slice.lowerBound..<(slice.lowerBound + HalfInt(newValue)) } } @inlinable // This is @inlinable as trivially computable. var range: Range<Int> { get { return Int(slice.lowerBound)..<Int(slice.upperBound) } set(newValue) { assert(newValue.lowerBound < HalfInt.max) assert(newValue.upperBound < HalfInt.max) slice = HalfInt(newValue.lowerBound)..<HalfInt(newValue.upperBound) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { return try storage.withUnsafeBytes(in: range, apply: apply) } @inlinable // This is @inlinable as a generic, trivially forwarding function. mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { ensureUniqueReference() return try storage.withUnsafeMutableBytes(in: range, apply: apply) } @inlinable // This is @inlinable as reasonably small. mutating func append(contentsOf buffer: UnsafeRawBufferPointer) { assert(endIndex + buffer.count < HalfInt.max) ensureUniqueReference() storage.replaceBytes(in: NSRange(location: range.upperBound, length: storage.length - (range.upperBound - storage._offset)), with: buffer.baseAddress, length: buffer.count) slice = slice.lowerBound..<HalfInt(Int(slice.upperBound) + buffer.count) } @inlinable // This is @inlinable as reasonably small. subscript(index: Index) -> UInt8 { get { assert(index < HalfInt.max) precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") return storage.get(index) } set(newValue) { assert(index < HalfInt.max) precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") ensureUniqueReference() storage.set(index, to: newValue) } } @inlinable // This is @inlinable as trivially forwarding. func bridgedReference() -> NSData { return storage.bridgedReference(self.range) } @inlinable // This is @inlinable as reasonably small. mutating func resetBytes(in range: Range<Index>) { assert(range.lowerBound < HalfInt.max) assert(range.upperBound < HalfInt.max) precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") ensureUniqueReference() storage.resetBytes(in: range) if slice.upperBound < range.upperBound { slice = slice.lowerBound..<HalfInt(range.upperBound) } } @inlinable // This is @inlinable as reasonably small. mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) { precondition(startIndex <= subrange.lowerBound, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(subrange.lowerBound <= endIndex, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= subrange.upperBound, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(subrange.upperBound <= endIndex, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound) ensureUniqueReference() let upper = range.upperBound storage.replaceBytes(in: nsRange, with: bytes, length: cnt) let resultingUpper = upper - nsRange.length + cnt slice = slice.lowerBound..<HalfInt(resultingUpper) } @inlinable // This is @inlinable as reasonably small. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") storage.copyBytes(to: pointer, from: range) } @inline(__always) // This should always be inlined into _Representation.hash(into:). func hash(into hasher: inout Hasher) { hasher.combine(count) // At most, hash the first 80 bytes of this data. let range = startIndex ..< Swift.min(startIndex + 80, endIndex) storage.withUnsafeBytes(in: range) { hasher.combine(bytes: $0) } } } // A reference wrapper around a Range<Int> for when the range of a data buffer is too large to whole in a single word. // Inlinability strategy: everything should be inlinable as trivial. @usableFromInline internal final class RangeReference { @usableFromInline var range: Range<Int> @inlinable @inline(__always) // This is @inlinable as trivially forwarding. var lowerBound: Int { return range.lowerBound } @inlinable @inline(__always) // This is @inlinable as trivially forwarding. var upperBound: Int { return range.upperBound } @inlinable @inline(__always) // This is @inlinable as trivially computable. var count: Int { return range.upperBound - range.lowerBound } @inlinable @inline(__always) // This is @inlinable as a trivial initializer. init(_ range: Range<Int>) { self.range = range } } // A buffer of bytes whose range is too large to fit in a signle word. Used alongside a RangeReference to make it fit into _Representation's two-word size. // Inlinability strategy: everything here should be easily inlinable as large _DataStorage methods should not inline into here. @usableFromInline @frozen internal struct LargeSlice { // ***WARNING*** // These ivars are specifically laid out so that they cause the enum _Representation to be 16 bytes on 64 bit platforms. This means we _MUST_ have the class type thing last @usableFromInline var slice: RangeReference @usableFromInline var storage: __DataStorage @inlinable // This is @inlinable as a convenience initializer. init(_ buffer: UnsafeRawBufferPointer) { self.init(__DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count) } @inlinable // This is @inlinable as a convenience initializer. init(capacity: Int) { self.init(__DataStorage(capacity: capacity), count: 0) } @inlinable // This is @inlinable as a convenience initializer. init(count: Int) { self.init(__DataStorage(length: count), count: count) } @inlinable // This is @inlinable as a convenience initializer. init(_ inline: InlineData) { let storage = inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) } self.init(storage, count: inline.count) } @inlinable // This is @inlinable as a trivial initializer. init(_ slice: InlineSlice) { self.storage = slice.storage self.slice = RangeReference(slice.range) } @inlinable // This is @inlinable as a trivial initializer. init(_ storage: __DataStorage, count: Int) { self.storage = storage self.slice = RangeReference(0..<count) } @inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic). mutating func ensureUniqueReference() { if !isKnownUniquelyReferenced(&storage) { storage = storage.mutableCopy(range) } if !isKnownUniquelyReferenced(&slice) { slice = RangeReference(range) } } @inlinable // This is @inlinable as trivially forwarding. var startIndex: Int { return slice.range.lowerBound } @inlinable // This is @inlinable as trivially forwarding. var endIndex: Int { return slice.range.upperBound } @inlinable // This is @inlinable as trivially forwarding. var capacity: Int { return storage.capacity } @inlinable // This is @inlinable as trivially computable. mutating func reserveCapacity(_ minimumCapacity: Int) { ensureUniqueReference() // the current capacity can be zero (representing externally owned buffer), and count can be greater than the capacity storage.ensureUniqueBufferReference(growingTo: Swift.max(minimumCapacity, count)) } @inlinable // This is @inlinable as trivially computable. var count: Int { get { return slice.count } set(newValue) { ensureUniqueReference() storage.length = newValue slice.range = slice.range.lowerBound..<(slice.range.lowerBound + newValue) } } @inlinable // This is @inlinable as it is trivially forwarding. var range: Range<Int> { return slice.range } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { return try storage.withUnsafeBytes(in: range, apply: apply) } @inlinable // This is @inlinable as a generic, trivially forwarding function. mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { ensureUniqueReference() return try storage.withUnsafeMutableBytes(in: range, apply: apply) } @inlinable // This is @inlinable as reasonably small. mutating func append(contentsOf buffer: UnsafeRawBufferPointer) { ensureUniqueReference() storage.replaceBytes(in: NSRange(location: range.upperBound, length: storage.length - (range.upperBound - storage._offset)), with: buffer.baseAddress, length: buffer.count) slice.range = slice.range.lowerBound..<slice.range.upperBound + buffer.count } @inlinable // This is @inlinable as trivially computable. subscript(index: Index) -> UInt8 { get { precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") return storage.get(index) } set(newValue) { precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") ensureUniqueReference() storage.set(index, to: newValue) } } @inlinable // This is @inlinable as trivially forwarding. func bridgedReference() -> NSData { return storage.bridgedReference(self.range) } @inlinable // This is @inlinable as reasonably small. mutating func resetBytes(in range: Range<Int>) { precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") ensureUniqueReference() storage.resetBytes(in: range) if slice.range.upperBound < range.upperBound { slice.range = slice.range.lowerBound..<range.upperBound } } @inlinable // This is @inlinable as reasonably small. mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) { precondition(startIndex <= subrange.lowerBound, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(subrange.lowerBound <= endIndex, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= subrange.upperBound, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(subrange.upperBound <= endIndex, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound) ensureUniqueReference() let upper = range.upperBound storage.replaceBytes(in: nsRange, with: bytes, length: cnt) let resultingUpper = upper - nsRange.length + cnt slice.range = slice.range.lowerBound..<resultingUpper } @inlinable // This is @inlinable as reasonably small. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") storage.copyBytes(to: pointer, from: range) } @inline(__always) // This should always be inlined into _Representation.hash(into:). func hash(into hasher: inout Hasher) { hasher.combine(count) // Hash at most the first 80 bytes of this data. let range = startIndex ..< Swift.min(startIndex + 80, endIndex) storage.withUnsafeBytes(in: range) { hasher.combine(bytes: $0) } } } // The actual storage for Data's various representations. // Inlinability strategy: almost everything should be inlinable as forwarding the underlying implementations. (Inlining can also help avoid retain-release traffic around pulling values out of enums.) @usableFromInline @frozen internal enum _Representation { case empty case inline(InlineData) case slice(InlineSlice) case large(LargeSlice) @inlinable // This is @inlinable as a trivial initializer. init(_ buffer: UnsafeRawBufferPointer) { if buffer.count == 0 { self = .empty } else if InlineData.canStore(count: buffer.count) { self = .inline(InlineData(buffer)) } else if InlineSlice.canStore(count: buffer.count) { self = .slice(InlineSlice(buffer)) } else { self = .large(LargeSlice(buffer)) } } @inlinable // This is @inlinable as a trivial initializer. init(_ buffer: UnsafeRawBufferPointer, owner: AnyObject) { if buffer.count == 0 { self = .empty } else if InlineData.canStore(count: buffer.count) { self = .inline(InlineData(buffer)) } else { let count = buffer.count let storage = __DataStorage(bytes: UnsafeMutableRawPointer(mutating: buffer.baseAddress), length: count, copy: false, deallocator: { _, _ in _fixLifetime(owner) }, offset: 0) if InlineSlice.canStore(count: count) { self = .slice(InlineSlice(storage, count: count)) } else { self = .large(LargeSlice(storage, count: count)) } } } @inlinable // This is @inlinable as a trivial initializer. init(capacity: Int) { if capacity == 0 { self = .empty } else if InlineData.canStore(count: capacity) { self = .inline(InlineData()) } else if InlineSlice.canStore(count: capacity) { self = .slice(InlineSlice(capacity: capacity)) } else { self = .large(LargeSlice(capacity: capacity)) } } @inlinable // This is @inlinable as a trivial initializer. init(count: Int) { if count == 0 { self = .empty } else if InlineData.canStore(count: count) { self = .inline(InlineData(count: count)) } else if InlineSlice.canStore(count: count) { self = .slice(InlineSlice(count: count)) } else { self = .large(LargeSlice(count: count)) } } @inlinable // This is @inlinable as a trivial initializer. init(_ storage: __DataStorage, count: Int) { if count == 0 { self = .empty } else if InlineData.canStore(count: count) { self = .inline(storage.withUnsafeBytes(in: 0..<count) { InlineData($0) }) } else if InlineSlice.canStore(count: count) { self = .slice(InlineSlice(storage, count: count)) } else { self = .large(LargeSlice(storage, count: count)) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. mutating func reserveCapacity(_ minimumCapacity: Int) { guard minimumCapacity > 0 else { return } switch self { case .empty: if InlineData.canStore(count: minimumCapacity) { self = .inline(InlineData()) } else if InlineSlice.canStore(count: minimumCapacity) { self = .slice(InlineSlice(capacity: minimumCapacity)) } else { self = .large(LargeSlice(capacity: minimumCapacity)) } case .inline(let inline): guard minimumCapacity > inline.capacity else { return } // we know we are going to be heap promoted if InlineSlice.canStore(count: minimumCapacity) { var slice = InlineSlice(inline) slice.reserveCapacity(minimumCapacity) self = .slice(slice) } else { var slice = LargeSlice(inline) slice.reserveCapacity(minimumCapacity) self = .large(slice) } case .slice(var slice): guard minimumCapacity > slice.capacity else { return } if InlineSlice.canStore(count: minimumCapacity) { self = .empty slice.reserveCapacity(minimumCapacity) self = .slice(slice) } else { var large = LargeSlice(slice) large.reserveCapacity(minimumCapacity) self = .large(large) } case .large(var slice): guard minimumCapacity > slice.capacity else { return } self = .empty slice.reserveCapacity(minimumCapacity) self = .large(slice) } } @inlinable // This is @inlinable as reasonably small. var count: Int { get { switch self { case .empty: return 0 case .inline(let inline): return inline.count case .slice(let slice): return slice.count case .large(let slice): return slice.count } } set(newValue) { // HACK: The definition of this inline function takes an inout reference to self, giving the optimizer a unique referencing guarantee. // This allows us to avoid excessive retain-release traffic around modifying enum values, and inlining the function then avoids the additional frame. @inline(__always) func apply(_ representation: inout _Representation, _ newValue: Int) -> _Representation? { switch representation { case .empty: if newValue == 0 { return nil } else if InlineData.canStore(count: newValue) { return .inline(InlineData(count: newValue)) } else if InlineSlice.canStore(count: newValue) { return .slice(InlineSlice(count: newValue)) } else { return .large(LargeSlice(count: newValue)) } case .inline(var inline): if newValue == 0 { return .empty } else if InlineData.canStore(count: newValue) { guard inline.count != newValue else { return nil } inline.count = newValue return .inline(inline) } else if InlineSlice.canStore(count: newValue) { var slice = InlineSlice(inline) slice.count = newValue return .slice(slice) } else { var slice = LargeSlice(inline) slice.count = newValue return .large(slice) } case .slice(var slice): if newValue == 0 && slice.startIndex == 0 { return .empty } else if slice.startIndex == 0 && InlineData.canStore(count: newValue) { return .inline(InlineData(slice, count: newValue)) } else if InlineSlice.canStore(count: newValue + slice.startIndex) { guard slice.count != newValue else { return nil } representation = .empty // TODO: remove this when mgottesman lands optimizations slice.count = newValue return .slice(slice) } else { var newSlice = LargeSlice(slice) newSlice.count = newValue return .large(newSlice) } case .large(var slice): if newValue == 0 && slice.startIndex == 0 { return .empty } else if slice.startIndex == 0 && InlineData.canStore(count: newValue) { return .inline(InlineData(slice, count: newValue)) } else { guard slice.count != newValue else { return nil} representation = .empty // TODO: remove this when mgottesman lands optimizations slice.count = newValue return .large(slice) } } } if let rep = apply(&self, newValue) { self = rep } } } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { switch self { case .empty: let empty = InlineData() return try empty.withUnsafeBytes(apply) case .inline(let inline): return try inline.withUnsafeBytes(apply) case .slice(let slice): return try slice.withUnsafeBytes(apply) case .large(let slice): return try slice.withUnsafeBytes(apply) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { switch self { case .empty: var empty = InlineData() return try empty.withUnsafeMutableBytes(apply) case .inline(var inline): defer { self = .inline(inline) } return try inline.withUnsafeMutableBytes(apply) case .slice(var slice): self = .empty defer { self = .slice(slice) } return try slice.withUnsafeMutableBytes(apply) case .large(var slice): self = .empty defer { self = .large(slice) } return try slice.withUnsafeMutableBytes(apply) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withInteriorPointerReference<T>(_ work: (NSData) throws -> T) rethrows -> T { switch self { case .empty: return try work(NSData()) case .inline(let inline): return try inline.withUnsafeBytes { return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0.baseAddress ?? UnsafeRawPointer(bitPattern: 0xBAD0)!), length: $0.count, freeWhenDone: false)) } case .slice(let slice): return try slice.storage.withInteriorPointerReference(slice.range, work) case .large(let slice): return try slice.storage.withInteriorPointerReference(slice.range, work) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) { switch self { case .empty: var stop = false block(UnsafeBufferPointer<UInt8>(start: nil, count: 0), 0, &stop) case .inline(let inline): inline.withUnsafeBytes { var stop = false block(UnsafeBufferPointer<UInt8>(start: $0.baseAddress?.assumingMemoryBound(to: UInt8.self), count: $0.count), 0, &stop) } case .slice(let slice): slice.storage.enumerateBytes(in: slice.range, block) case .large(let slice): slice.storage.enumerateBytes(in: slice.range, block) } } @inlinable // This is @inlinable as reasonably small. mutating func append(contentsOf buffer: UnsafeRawBufferPointer) { switch self { case .empty: self = _Representation(buffer) case .inline(var inline): if InlineData.canStore(count: inline.count + buffer.count) { inline.append(contentsOf: buffer) self = .inline(inline) } else if InlineSlice.canStore(count: inline.count + buffer.count) { var newSlice = InlineSlice(inline) newSlice.append(contentsOf: buffer) self = .slice(newSlice) } else { var newSlice = LargeSlice(inline) newSlice.append(contentsOf: buffer) self = .large(newSlice) } case .slice(var slice): if InlineSlice.canStore(count: slice.range.upperBound + buffer.count) { self = .empty defer { self = .slice(slice) } slice.append(contentsOf: buffer) } else { self = .empty var newSlice = LargeSlice(slice) newSlice.append(contentsOf: buffer) self = .large(newSlice) } case .large(var slice): self = .empty defer { self = .large(slice) } slice.append(contentsOf: buffer) } } @inlinable // This is @inlinable as reasonably small. mutating func resetBytes(in range: Range<Index>) { switch self { case .empty: if range.upperBound == 0 { self = .empty } else if InlineData.canStore(count: range.upperBound) { precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") self = .inline(InlineData(count: range.upperBound)) } else if InlineSlice.canStore(count: range.upperBound) { precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") self = .slice(InlineSlice(count: range.upperBound)) } else { precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") self = .large(LargeSlice(count: range.upperBound)) } case .inline(var inline): if inline.count < range.upperBound { if InlineSlice.canStore(count: range.upperBound) { var slice = InlineSlice(inline) slice.resetBytes(in: range) self = .slice(slice) } else { var slice = LargeSlice(inline) slice.resetBytes(in: range) self = .large(slice) } } else { inline.resetBytes(in: range) self = .inline(inline) } case .slice(var slice): if InlineSlice.canStore(count: range.upperBound) { self = .empty slice.resetBytes(in: range) self = .slice(slice) } else { self = .empty var newSlice = LargeSlice(slice) newSlice.resetBytes(in: range) self = .large(newSlice) } case .large(var slice): self = .empty slice.resetBytes(in: range) self = .large(slice) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) { switch self { case .empty: precondition(subrange.lowerBound == 0 && subrange.upperBound == 0, "range \(subrange) out of bounds of 0..<0") if cnt == 0 { return } else if InlineData.canStore(count: cnt) { self = .inline(InlineData(UnsafeRawBufferPointer(start: bytes, count: cnt))) } else if InlineSlice.canStore(count: cnt) { self = .slice(InlineSlice(UnsafeRawBufferPointer(start: bytes, count: cnt))) } else { self = .large(LargeSlice(UnsafeRawBufferPointer(start: bytes, count: cnt))) } case .inline(var inline): let resultingCount = inline.count + cnt - (subrange.upperBound - subrange.lowerBound) if resultingCount == 0 { self = .empty } else if InlineData.canStore(count: resultingCount) { inline.replaceSubrange(subrange, with: bytes, count: cnt) self = .inline(inline) } else if InlineSlice.canStore(count: resultingCount) { var slice = InlineSlice(inline) slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .slice(slice) } else { var slice = LargeSlice(inline) slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .large(slice) } case .slice(var slice): let resultingUpper = slice.endIndex + cnt - (subrange.upperBound - subrange.lowerBound) if slice.startIndex == 0 && resultingUpper == 0 { self = .empty } else if slice.startIndex == 0 && InlineData.canStore(count: resultingUpper) { self = .empty slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .inline(InlineData(slice, count: slice.count)) } else if InlineSlice.canStore(count: resultingUpper) { self = .empty slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .slice(slice) } else { self = .empty var newSlice = LargeSlice(slice) newSlice.replaceSubrange(subrange, with: bytes, count: cnt) self = .large(newSlice) } case .large(var slice): let resultingUpper = slice.endIndex + cnt - (subrange.upperBound - subrange.lowerBound) if slice.startIndex == 0 && resultingUpper == 0 { self = .empty } else if slice.startIndex == 0 && InlineData.canStore(count: resultingUpper) { var inline = InlineData(count: resultingUpper) inline.withUnsafeMutableBytes { inlineBuffer in if cnt > 0 { inlineBuffer.baseAddress?.advanced(by: subrange.lowerBound).copyMemory(from: bytes!, byteCount: cnt) } slice.withUnsafeBytes { buffer in if subrange.lowerBound > 0 { inlineBuffer.baseAddress?.copyMemory(from: buffer.baseAddress!, byteCount: subrange.lowerBound) } if subrange.upperBound < resultingUpper { inlineBuffer.baseAddress?.advanced(by: subrange.upperBound).copyMemory(from: buffer.baseAddress!.advanced(by: subrange.upperBound), byteCount: resultingUpper - subrange.upperBound) } } } self = .inline(inline) } else if InlineSlice.canStore(count: slice.startIndex) && InlineSlice.canStore(count: resultingUpper) { self = .empty var newSlice = InlineSlice(slice) newSlice.replaceSubrange(subrange, with: bytes, count: cnt) self = .slice(newSlice) } else { self = .empty slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .large(slice) } } } @inlinable // This is @inlinable as trivially forwarding. subscript(index: Index) -> UInt8 { get { switch self { case .empty: preconditionFailure("index \(index) out of range of 0") case .inline(let inline): return inline[index] case .slice(let slice): return slice[index] case .large(let slice): return slice[index] } } set(newValue) { switch self { case .empty: preconditionFailure("index \(index) out of range of 0") case .inline(var inline): inline[index] = newValue self = .inline(inline) case .slice(var slice): self = .empty slice[index] = newValue self = .slice(slice) case .large(var slice): self = .empty slice[index] = newValue self = .large(slice) } } } @inlinable // This is @inlinable as reasonably small. subscript(bounds: Range<Index>) -> Data { get { switch self { case .empty: precondition(bounds.lowerBound == 0 && (bounds.upperBound - bounds.lowerBound) == 0, "Range \(bounds) out of bounds 0..<0") return Data() case .inline(let inline): precondition(bounds.upperBound <= inline.count, "Range \(bounds) out of bounds 0..<\(inline.count)") if bounds.lowerBound == 0 { var newInline = inline newInline.count = bounds.upperBound return Data(representation: .inline(newInline)) } else { return Data(representation: .slice(InlineSlice(inline, range: bounds))) } case .slice(let slice): precondition(slice.startIndex <= bounds.lowerBound, "Range \(bounds) out of bounds \(slice.range)") precondition(bounds.lowerBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)") precondition(slice.startIndex <= bounds.upperBound, "Range \(bounds) out of bounds \(slice.range)") precondition(bounds.upperBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)") if bounds.lowerBound == 0 && bounds.upperBound == 0 { return Data() } else if bounds.lowerBound == 0 && InlineData.canStore(count: bounds.count) { return Data(representation: .inline(InlineData(slice, count: bounds.count))) } else { var newSlice = slice newSlice.range = bounds return Data(representation: .slice(newSlice)) } case .large(let slice): precondition(slice.startIndex <= bounds.lowerBound, "Range \(bounds) out of bounds \(slice.range)") precondition(bounds.lowerBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)") precondition(slice.startIndex <= bounds.upperBound, "Range \(bounds) out of bounds \(slice.range)") precondition(bounds.upperBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)") if bounds.lowerBound == 0 && bounds.upperBound == 0 { return Data() } else if bounds.lowerBound == 0 && InlineData.canStore(count: bounds.upperBound) { return Data(representation: .inline(InlineData(slice, count: bounds.upperBound))) } else if InlineSlice.canStore(count: bounds.lowerBound) && InlineSlice.canStore(count: bounds.upperBound) { return Data(representation: .slice(InlineSlice(slice, range: bounds))) } else { var newSlice = slice newSlice.slice = RangeReference(bounds) return Data(representation: .large(newSlice)) } } } } @inlinable // This is @inlinable as trivially forwarding. var startIndex: Int { switch self { case .empty: return 0 case .inline: return 0 case .slice(let slice): return slice.startIndex case .large(let slice): return slice.startIndex } } @inlinable // This is @inlinable as trivially forwarding. var endIndex: Int { switch self { case .empty: return 0 case .inline(let inline): return inline.count case .slice(let slice): return slice.endIndex case .large(let slice): return slice.endIndex } } @inlinable // This is @inlinable as trivially forwarding. func bridgedReference() -> NSData { switch self { case .empty: return NSData() case .inline(let inline): return inline.withUnsafeBytes { return NSData(bytes: $0.baseAddress, length: $0.count) } case .slice(let slice): return slice.bridgedReference() case .large(let slice): return slice.bridgedReference() } } @inlinable // This is @inlinable as trivially forwarding. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { switch self { case .empty: precondition(range.lowerBound == 0 && range.upperBound == 0, "Range \(range) out of bounds 0..<0") return case .inline(let inline): inline.copyBytes(to: pointer, from: range) case .slice(let slice): slice.copyBytes(to: pointer, from: range) case .large(let slice): slice.copyBytes(to: pointer, from: range) } } @inline(__always) // This should always be inlined into Data.hash(into:). func hash(into hasher: inout Hasher) { switch self { case .empty: hasher.combine(0) case .inline(let inline): inline.hash(into: &hasher) case .slice(let slice): slice.hash(into: &hasher) case .large(let large): large.hash(into: &hasher) } } } @usableFromInline internal var _representation: _Representation // A standard or custom deallocator for `Data`. /// /// When creating a `Data` with the no-copy initializer, you may specify a `Data.Deallocator` to customize the behavior of how the backing store is deallocated. public enum Deallocator { /// Use a virtual memory deallocator. #if !DEPLOYMENT_RUNTIME_SWIFT case virtualMemory #endif /// Use `munmap`. case unmap /// Use `free`. case free /// Do nothing upon deallocation. case none /// A custom deallocator. case custom((UnsafeMutableRawPointer, Int) -> Void) @usableFromInline internal var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) { #if DEPLOYMENT_RUNTIME_SWIFT switch self { case .unmap: return { __NSDataInvokeDeallocatorUnmap($0, $1) } case .free: return { __NSDataInvokeDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return b } #else switch self { case .virtualMemory: return { NSDataDeallocatorVM($0, $1) } case .unmap: return { NSDataDeallocatorUnmap($0, $1) } case .free: return { NSDataDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return b } #endif } } // MARK: - // MARK: Init methods /// Initialize a `Data` with copied memory content. /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. @inlinable // This is @inlinable as a trivial initializer. public init(bytes: UnsafeRawPointer, count: Int) { _representation = _Representation(UnsafeRawBufferPointer(start: bytes, count: count)) } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. @inlinable // This is @inlinable as a trivial, generic initializer. public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) { _representation = _Representation(UnsafeRawBufferPointer(buffer)) } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. @inlinable // This is @inlinable as a trivial, generic initializer. public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) { _representation = _Representation(UnsafeRawBufferPointer(buffer)) } /// Initialize a `Data` with a repeating byte pattern /// /// - parameter repeatedValue: A byte to initialize the pattern /// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue @inlinable // This is @inlinable as a convenience initializer. public init(repeating repeatedValue: UInt8, count: Int) { self.init(count: count) if count > 0 { withUnsafeMutableBytes { (buffer: UnsafeMutableRawBufferPointer) -> Void in memset(buffer.baseAddress!, Int32(repeatedValue), buffer.count) } } } /// Initialize a `Data` with the specified size. /// /// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. /// /// This method sets the `count` of the data to 0. /// /// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page. /// /// - parameter capacity: The size of the data. @inlinable // This is @inlinable as a trivial initializer. public init(capacity: Int) { _representation = _Representation(capacity: capacity) } /// Initialize a `Data` with the specified count of zeroed bytes. /// /// - parameter count: The number of bytes the data initially contains. @inlinable // This is @inlinable as a trivial initializer. public init(count: Int) { _representation = _Representation(count: count) } /// Initialize an empty `Data`. @inlinable // This is @inlinable as a trivial initializer. public init() { _representation = .empty } /// Initialize a `Data` without copying the bytes. /// /// If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed. /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`. @inlinable // This is @inlinable as a trivial initializer. public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) { let whichDeallocator = deallocator._deallocator if count == 0 { deallocator._deallocator(bytes, count) _representation = .empty } else { _representation = _Representation(__DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0), count: count) } } #if !os(WASI) /// Initialize a `Data` with the contents of a `URL`. /// /// - parameter url: The `URL` to read. /// - parameter options: Options for the read operation. Default value is `[]`. /// - throws: An error in the Cocoa domain, if `url` cannot be read. @inlinable // This is @inlinable as a convenience initializer. public init(contentsOf url: __shared URL, options: Data.ReadingOptions = []) throws { let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue)) self = withExtendedLifetime(d) { return Data(bytes: d.bytes, count: d.length) } } #endif /// Initialize a `Data` from a Base-64 encoded String using the given options. /// /// Returns nil when the input is not recognized as valid Base-64. /// - parameter base64String: The string to parse. /// - parameter options: Encoding options. Default value is `[]`. @inlinable // This is @inlinable as a convenience initializer. public init?(base64Encoded base64String: __shared String, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) { self = withExtendedLifetime(d) { Data(bytes: d.bytes, count: d.length) } } else { return nil } } /// Initialize a `Data` from a Base-64, UTF-8 encoded `Data`. /// /// Returns nil when the input is not recognized as valid Base-64. /// /// - parameter base64Data: Base-64, UTF-8 encoded input data. /// - parameter options: Decoding options. Default value is `[]`. @inlinable // This is @inlinable as a convenience initializer. public init?(base64Encoded base64Data: __shared Data, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) { self = withExtendedLifetime(d) { Data(bytes: d.bytes, count: d.length) } } else { return nil } } /// Initialize a `Data` by adopting a reference type. /// /// You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation. /// /// If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass. /// /// - parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`. public init(referencing reference: __shared NSData) { // This is not marked as inline because _providesConcreteBacking would need to be marked as usable from inline however that is a dynamic lookup in objc contexts. let length = reference.length if length == 0 { _representation = .empty } else { #if DEPLOYMENT_RUNTIME_SWIFT let providesConcreteBacking = reference._providesConcreteBacking() #else let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false #endif if providesConcreteBacking { _representation = _Representation(__DataStorage(immutableReference: reference.copy() as! NSData, offset: 0), count: length) } else { _representation = _Representation(__DataStorage(customReference: reference.copy() as! NSData, offset: 0), count: length) } } } // slightly faster paths for common sequences @inlinable // This is @inlinable as an important generic funnel point, despite being a non-trivial initializer. public init<S: Sequence>(_ elements: S) where S.Element == UInt8 { // If the sequence is already contiguous, access the underlying raw memory directly. if let contiguous = elements as? ContiguousBytes { _representation = contiguous.withUnsafeBytes { return _Representation($0) } return } // The sequence might still be able to provide direct access to typed memory. // NOTE: It's safe to do this because we're already guarding on S's element as `UInt8`. This would not be safe on arbitrary sequences. let representation = elements.withContiguousStorageIfAvailable { return _Representation(UnsafeRawBufferPointer($0)) } if let representation = representation { _representation = representation } else { // Dummy assignment so we can capture below. _representation = _Representation(capacity: 0) // Copy as much as we can in one shot from the sequence. let underestimatedCount = Swift.max(elements.underestimatedCount, 1) __withStackOrHeapBuffer(underestimatedCount) { (memory, capacity, isOnStack) in // In order to copy from the sequence, we have to bind the buffer to UInt8. // This is safe since we'll copy out of this buffer as raw memory later. let base = memory.bindMemory(to: UInt8.self, capacity: capacity) var (iter, endIndex) = elements._copyContents(initializing: UnsafeMutableBufferPointer(start: base, count: capacity)) // Copy the contents of buffer... _representation = _Representation(UnsafeRawBufferPointer(start: base, count: endIndex)) // ... and append the rest byte-wise, buffering through an InlineData. var buffer = InlineData() while let element = iter.next() { buffer.append(byte: element) if buffer.count == buffer.capacity { buffer.withUnsafeBytes { _representation.append(contentsOf: $0) } buffer.count = 0 } } // If we've still got bytes left in the buffer (i.e. the loop ended before we filled up the buffer and cleared it out), append them. if buffer.count > 0 { buffer.withUnsafeBytes { _representation.append(contentsOf: $0) } buffer.count = 0 } } } } @available(swift, introduced: 4.2) @available(swift, deprecated: 5, renamed: "init(_:)") public init<S: Sequence>(bytes elements: S) where S.Iterator.Element == UInt8 { self.init(elements) } @available(swift, obsoleted: 4.2) public init(bytes: Array<UInt8>) { self.init(bytes) } @available(swift, obsoleted: 4.2) public init(bytes: ArraySlice<UInt8>) { self.init(bytes) } @inlinable // This is @inlinable as a trivial initializer. internal init(representation: _Representation) { _representation = representation } // ----------------------------------- // MARK: - Properties and Functions @inlinable // This is @inlinable as trivially forwarding. public mutating func reserveCapacity(_ minimumCapacity: Int) { _representation.reserveCapacity(minimumCapacity) } /// The number of bytes in the data. @inlinable // This is @inlinable as trivially forwarding. public var count: Int { get { return _representation.count } set(newValue) { precondition(newValue >= 0, "count must not be negative") _representation.count = newValue } } @inlinable // This is @inlinable as trivially computable. public var regions: CollectionOfOne<Data> { return CollectionOfOne(self) } /// Access the bytes in the data. /// /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. @available(swift, deprecated: 5, message: "use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead") public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { return try _representation.withUnsafeBytes { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafePointer<ContentType>(bitPattern: 0xBAD0)!) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. public func withUnsafeBytes<ResultType>(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType { return try _representation.withUnsafeBytes(body) } /// Mutate the bytes in the data. /// /// This function assumes that you are mutating the contents. /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. @available(swift, deprecated: 5, message: "use `withUnsafeMutableBytes<R>(_: (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R` instead") public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { return try _representation.withUnsafeMutableBytes { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafeMutablePointer<ContentType>(bitPattern: 0xBAD0)!) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. public mutating func withUnsafeMutableBytes<ResultType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ResultType) rethrows -> ResultType { return try _representation.withUnsafeMutableBytes(body) } // MARK: - // MARK: Copy Bytes /// Copy the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter count: The number of bytes to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes. @inlinable // This is @inlinable as trivially forwarding. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) { precondition(count >= 0, "count of bytes to copy must not be negative") if count == 0 { return } _copyBytesHelper(to: UnsafeMutableRawPointer(pointer), from: startIndex..<(startIndex + count)) } @inlinable // This is @inlinable as trivially forwarding. internal func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { if range.isEmpty { return } _representation.copyBytes(to: pointer, from: range) } /// Copy a subset of the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter range: The range in the `Data` to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes. @inlinable // This is @inlinable as trivially forwarding. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) { _copyBytesHelper(to: pointer, from: range) } // Copy the contents of the data into a buffer. /// /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer. /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called. /// - parameter buffer: A buffer to copy the data into. /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied. /// - returns: Number of bytes copied into the destination buffer. @inlinable // This is @inlinable as generic and reasonably small. public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int { let cnt = count guard cnt > 0 else { return 0 } let copyRange : Range<Index> if let r = range { guard !r.isEmpty else { return 0 } copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.upperBound - r.lowerBound)) } else { copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt) } guard !copyRange.isEmpty else { return 0 } _copyBytesHelper(to: buffer.baseAddress!, from: copyRange) return copyRange.upperBound - copyRange.lowerBound } // MARK: - #if !DEPLOYMENT_RUNTIME_SWIFT private func _shouldUseNonAtomicWriteReimplementation(options: Data.WritingOptions = []) -> Bool { // Avoid a crash that happens on OS X 10.11.x and iOS 9.x or before when writing a bridged Data non-atomically with Foundation's standard write() implementation. if !options.contains(.atomic) { #if os(macOS) return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max) #else return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max) #endif } else { return false } } #endif #if !os(WASI) /// Write the contents of the `Data` to a location. /// /// - parameter url: The location to write the data into. /// - parameter options: Options for writing the data. Default value is `[]`. /// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`. public func write(to url: URL, options: Data.WritingOptions = []) throws { // this should not be marked as inline since in objc contexts we correct atomicity via _shouldUseNonAtomicWriteReimplementation try _representation.withInteriorPointerReference { #if DEPLOYMENT_RUNTIME_SWIFT try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue)) #else if _shouldUseNonAtomicWriteReimplementation(options: options) { var error: NSError? = nil guard __NSDataWriteToURL($0, url, options, &error) else { throw error! } } else { try $0.write(to: url, options: options) } #endif } } #endif // MARK: - /// Find the given `Data` in the content of this `Data`. /// /// - parameter dataToFind: The data to be searched for. /// - parameter options: Options for the search. Default value is `[]`. /// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data. /// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found. /// - precondition: `range` must be in the bounds of the Data. public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? { let nsRange : NSRange if let r = range { nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound) } else { nsRange = NSRange(location: 0, length: count) } let result = _representation.withInteriorPointerReference { $0.range(of: dataToFind, options: options, in: nsRange) } if result.location == NSNotFound { return nil } return (result.location + startIndex)..<((result.location + startIndex) + result.length) } /// Enumerate the contents of the data. /// /// In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontiguously. In those cases, this function invokes the closure for each contiguous region of bytes. /// - parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`. @available(swift, deprecated: 5, message: "use `regions` or `for-in` instead") public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) { _representation.enumerateBytes(block) } @inlinable // This is @inlinable as a generic, trivially forwarding function. internal mutating func _append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { if buffer.isEmpty { return } _representation.append(contentsOf: UnsafeRawBufferPointer(buffer)) } @inlinable // This is @inlinable as a generic, trivially forwarding function. public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) { if count == 0 { return } _append(UnsafeBufferPointer(start: bytes, count: count)) } public mutating func append(_ other: Data) { guard other.count > 0 else { return } other.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in _representation.append(contentsOf: buffer) } } /// Append a buffer of bytes to the data. /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. @inlinable // This is @inlinable as a generic, trivially forwarding function. public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { _append(buffer) } @inlinable // This is @inlinable as trivially forwarding. public mutating func append(contentsOf bytes: [UInt8]) { bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in _append(buffer) } } @inlinable // This is @inlinable as an important generic funnel point, despite being non-trivial. public mutating func append<S: Sequence>(contentsOf elements: S) where S.Element == Element { // If the sequence is already contiguous, access the underlying raw memory directly. if let contiguous = elements as? ContiguousBytes { contiguous.withUnsafeBytes { _representation.append(contentsOf: $0) } return } // The sequence might still be able to provide direct access to typed memory. // NOTE: It's safe to do this because we're already guarding on S's element as `UInt8`. This would not be safe on arbitrary sequences. var appended = false elements.withContiguousStorageIfAvailable { _representation.append(contentsOf: UnsafeRawBufferPointer($0)) appended = true } guard !appended else { return } // The sequence is really not contiguous. // Copy as much as we can in one shot. let underestimatedCount = Swift.max(elements.underestimatedCount, 1) __withStackOrHeapBuffer(underestimatedCount) { (memory, capacity, isOnStack) in // In order to copy from the sequence, we have to bind the temporary buffer to `UInt8`. // This is safe since we're the only owners of the buffer and we copy out as raw memory below anyway. let base = memory.bindMemory(to: UInt8.self, capacity: capacity) var (iter, endIndex) = elements._copyContents(initializing: UnsafeMutableBufferPointer(start: base, count: capacity)) // Copy the contents of the buffer... _representation.append(contentsOf: UnsafeRawBufferPointer(start: base, count: endIndex)) // ... and append the rest byte-wise, buffering through an InlineData. var buffer = InlineData() while let element = iter.next() { buffer.append(byte: element) if buffer.count == buffer.capacity { buffer.withUnsafeBytes { _representation.append(contentsOf: $0) } buffer.count = 0 } } // If we've still got bytes left in the buffer (i.e. the loop ended before we filled up the buffer and cleared it out), append them. if buffer.count > 0 { buffer.withUnsafeBytes { _representation.append(contentsOf: $0) } buffer.count = 0 } } } // MARK: - /// Set a region of the data to `0`. /// /// If `range` exceeds the bounds of the data, then the data is resized to fit. /// - parameter range: The range in the data to set to `0`. @inlinable // This is @inlinable as trivially forwarding. public mutating func resetBytes(in range: Range<Index>) { // it is worth noting that the range here may be out of bounds of the Data itself (which triggers a growth) precondition(range.lowerBound >= 0, "Ranges must not be negative bounds") precondition(range.upperBound >= 0, "Ranges must not be negative bounds") _representation.resetBytes(in: range) } /// Replace a region of bytes in the data with new data. /// /// This will resize the data if required, to fit the entire contents of `data`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append. /// - parameter data: The replacement data. @inlinable // This is @inlinable as trivially forwarding. public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) { data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in _representation.replaceSubrange(subrange, with: buffer.baseAddress, count: buffer.count) } } /// Replace a region of bytes in the data with new bytes from a buffer. /// /// This will resize the data if required, to fit the entire contents of `buffer`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter buffer: The replacement bytes. @inlinable // This is @inlinable as a generic, trivially forwarding function. public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) { guard !buffer.isEmpty else { return } replaceSubrange(subrange, with: buffer.baseAddress!, count: buffer.count * MemoryLayout<SourceType>.stride) } /// Replace a region of bytes in the data with new bytes from a collection. /// /// This will resize the data if required, to fit the entire contents of `newElements`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter newElements: The replacement bytes. @inlinable // This is @inlinable as generic and reasonably small. public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element { let totalCount = Int(newElements.count) __withStackOrHeapBuffer(totalCount) { (memory, capacity, isOnStack) in let buffer = UnsafeMutableBufferPointer(start: memory.assumingMemoryBound(to: UInt8.self), count: totalCount) var (iterator, index) = newElements._copyContents(initializing: buffer) while let byte = iterator.next() { buffer[index] = byte index = buffer.index(after: index) } replaceSubrange(subrange, with: memory, count: totalCount) } } @inlinable // This is @inlinable as trivially forwarding. public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) { _representation.replaceSubrange(subrange, with: bytes, count: cnt) } /// Return a new copy of the data in a specified range. /// /// - parameter range: The range to copy. public func subdata(in range: Range<Index>) -> Data { if isEmpty || range.upperBound - range.lowerBound == 0 { return Data() } let slice = self[range] return slice.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) -> Data in return Data(bytes: buffer.baseAddress!, count: buffer.count) } } // MARK: - // /// Returns a Base-64 encoded string. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded string. public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String { let dataLength = self.count if dataLength == 0 { return "" } let capacity = NSData.estimateBase64Size(length: dataLength) let ptr = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: 4) defer { ptr.deallocate() } let buffer = UnsafeMutableRawBufferPointer(start: ptr, count: capacity) let length = self.withUnsafeBytes { inputBuffer in NSData.base64EncodeBytes(inputBuffer, options: options, buffer: buffer) } return String(decoding: UnsafeRawBufferPointer(start: ptr, count: length), as: Unicode.UTF8.self) } /// Returns a Base-64 encoded `Data`. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded data. public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data { let dataLength = self.count if dataLength == 0 { return Data() } let capacity = NSData.estimateBase64Size(length: dataLength) let ptr = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: 4) let outputBuffer = UnsafeMutableRawBufferPointer(start: ptr, count: capacity) let length = self.withUnsafeBytes { inputBuffer in NSData.base64EncodeBytes(inputBuffer, options: options, buffer: outputBuffer) } return Data(bytesNoCopy: ptr, count: length, deallocator: .custom({ (ptr, length) in ptr.deallocate() })) } // MARK: - // /// The hash value for the data. @inline(never) // This is not inlinable as emission into clients could cause cross-module inconsistencies if they are not all recompiled together. public func hash(into hasher: inout Hasher) { _representation.hash(into: &hasher) } public func advanced(by amount: Int) -> Data { let length = count - amount precondition(length > 0) return withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> Data in return Data(bytes: ptr.baseAddress!.advanced(by: amount), count: length) } } // MARK: - // MARK: - // MARK: Index and Subscript /// Sets or returns the byte at the specified index. @inlinable // This is @inlinable as trivially forwarding. public subscript(index: Index) -> UInt8 { get { return _representation[index] } set(newValue) { _representation[index] = newValue } } @inlinable // This is @inlinable as trivially forwarding. public subscript(bounds: Range<Index>) -> Data { get { return _representation[bounds] } set { replaceSubrange(bounds, with: newValue) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. public subscript<R: RangeExpression>(_ rangeExpression: R) -> Data where R.Bound: FixedWidthInteger { get { let lower = R.Bound(startIndex) let upper = R.Bound(endIndex) let range = rangeExpression.relative(to: lower..<upper) let start = Int(range.lowerBound) let end = Int(range.upperBound) let r: Range<Int> = start..<end return _representation[r] } set { let lower = R.Bound(startIndex) let upper = R.Bound(endIndex) let range = rangeExpression.relative(to: lower..<upper) let start = Int(range.lowerBound) let end = Int(range.upperBound) let r: Range<Int> = start..<end replaceSubrange(r, with: newValue) } } /// The start `Index` in the data. @inlinable // This is @inlinable as trivially forwarding. public var startIndex: Index { get { return _representation.startIndex } } /// The end `Index` into the data. /// /// This is the "one-past-the-end" position, and will always be equal to the `count`. @inlinable // This is @inlinable as trivially forwarding. public var endIndex: Index { get { return _representation.endIndex } } @inlinable // This is @inlinable as trivially computable. public func index(before i: Index) -> Index { return i - 1 } @inlinable // This is @inlinable as trivially computable. public func index(after i: Index) -> Index { return i + 1 } @inlinable // This is @inlinable as trivially computable. public var indices: Range<Int> { get { return startIndex..<endIndex } } @inlinable // This is @inlinable as a fast-path for emitting into generic Sequence usages. public func _copyContents(initializing buffer: UnsafeMutableBufferPointer<UInt8>) -> (Iterator, UnsafeMutableBufferPointer<UInt8>.Index) { guard !isEmpty else { return (makeIterator(), buffer.startIndex) } let cnt = Swift.min(count, buffer.count) if cnt > 0 { withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in _ = memcpy(UnsafeMutableRawPointer(buffer.baseAddress!), bytes.baseAddress!, cnt) } } return (Iterator(self, at: startIndex + cnt), buffer.index(buffer.startIndex, offsetBy: cnt)) } /// An iterator over the contents of the data. /// /// The iterator will increment byte-by-byte. @inlinable // This is @inlinable as trivially computable. public func makeIterator() -> Data.Iterator { return Iterator(self, at: startIndex) } public struct Iterator : IteratorProtocol { @usableFromInline internal typealias Buffer = ( UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) @usableFromInline internal let _data: Data @usableFromInline internal var _buffer: Buffer @usableFromInline internal var _idx: Data.Index @usableFromInline internal let _endIdx: Data.Index @usableFromInline // This is @usableFromInline as a non-trivial initializer. internal init(_ data: Data, at loc: Data.Index) { // The let vars prevent this from being marked as @inlinable _data = data _buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) _idx = loc _endIdx = data.endIndex let bufferSize = MemoryLayout<Buffer>.size Swift.withUnsafeMutableBytes(of: &_buffer) { let ptr = $0.bindMemory(to: UInt8.self) let bufferIdx = (loc - data.startIndex) % bufferSize data.copyBytes(to: ptr, from: (loc - bufferIdx)..<(data.endIndex - (loc - bufferIdx) > bufferSize ? (loc - bufferIdx) + bufferSize : data.endIndex)) } } public mutating func next() -> UInt8? { let idx = _idx let bufferSize = MemoryLayout<Buffer>.size guard idx < _endIdx else { return nil } _idx += 1 let bufferIdx = (idx - _data.startIndex) % bufferSize if bufferIdx == 0 { var buffer = _buffer Swift.withUnsafeMutableBytes(of: &buffer) { let ptr = $0.bindMemory(to: UInt8.self) // populate the buffer _data.copyBytes(to: ptr, from: idx..<(_endIdx - idx > bufferSize ? idx + bufferSize : _endIdx)) } _buffer = buffer } return Swift.withUnsafeMutableBytes(of: &_buffer) { let ptr = $0.bindMemory(to: UInt8.self) return ptr[bufferIdx] } } } // MARK: - // @available(*, unavailable, renamed: "count") public var length: Int { get { fatalError() } set { fatalError() } } @available(*, unavailable, message: "use withUnsafeBytes instead") public var bytes: UnsafeRawPointer { fatalError() } @available(*, unavailable, message: "use withUnsafeMutableBytes instead") public var mutableBytes: UnsafeMutableRawPointer { fatalError() } /// Returns `true` if the two `Data` arguments are equal. @inlinable // This is @inlinable as emission into clients is safe -- the concept of equality on Data will not change. public static func ==(d1 : Data, d2 : Data) -> Bool { let length1 = d1.count if length1 != d2.count { return false } if length1 > 0 { return d1.withUnsafeBytes { (b1: UnsafeRawBufferPointer) in return d2.withUnsafeBytes { (b2: UnsafeRawBufferPointer) in return memcmp(b1.baseAddress!, b2.baseAddress!, b2.count) == 0 } } } return true } } extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { /// A human-readable description for the data. public var description: String { return "\(self.count) bytes" } /// A human-readable debug description for the data. public var debugDescription: String { return self.description } public var customMirror: Mirror { let nBytes = self.count var children: [(label: String?, value: Any)] = [] children.append((label: "count", value: nBytes)) self.withUnsafeBytes { (bytes : UnsafeRawBufferPointer) in children.append((label: "pointer", value: bytes.baseAddress!)) } // Minimal size data is output as an array if nBytes < 64 { children.append((label: "bytes", value: Array(self[startIndex..<Swift.min(nBytes + startIndex, endIndex)]))) } let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.struct) return m } } extension Data { @available(*, unavailable, renamed: "copyBytes(to:count:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, length: Int) { } @available(*, unavailable, renamed: "copyBytes(to:from:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, range: NSRange) { } } /// Provides bridging functionality for struct Data to class NSData and vice-versa. extension Data : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSData { return _representation.bridgedReference() } public static func _forceBridgeFromObjectiveC(_ input: NSData, result: inout Data?) { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) } public static func _conditionallyBridgeFromObjectiveC(_ input: NSData, result: inout Data?) -> Bool { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) return true } // @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ source: NSData?) -> Data { guard let src = source else { return Data() } return Data(referencing: src) } } extension NSData : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self)) } } extension Data : Codable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() // It's more efficient to pre-allocate the buffer if we can. if let count = container.count { self.init(count: count) // Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space. // We don't want to write past the end of what we allocated. for i in 0 ..< count { let byte = try container.decode(UInt8.self) self[i] = byte } } else { self.init() } while !container.isAtEnd { var byte = try container.decode(UInt8.self) self.append(&byte, count: 1) } } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in try container.encode(contentsOf: buffer) } } }
apache-2.0
92651603c95c03a9dc346394e681a8fc
44.069526
352
0.595275
5.107043
false
false
false
false
AlexZd/SwiftUtils
Pod/Utils/Date+Helpers.swift
1
4322
// // NSDate+Helpers.swift // // Created by Alex Zdorovets on 6/17/15. // Copyright (c) 2015 Alex Zdorovets. All rights reserved. // import Foundation extension Date { public var dateOnly: Date { if let date = self.toGregorianString(mask: "dd.MM.yyyy").toDate("dd.MM.yyyy") { return date } fatalError("Date is nil! \(#file) \(#line)") } public var timeOnly: Date { return self.toString("HH:mm").toDate("HH:mm")! } public static func time(_ time: Date, rounded: Int) -> Date { let nextDiff = rounded - Calendar.current.component(.minute, from: time) % rounded return Calendar.current.date(byAdding: .minute, value: nextDiff, to: time) ?? Date() } public func dateWithShift(days: Int, months: Int, years: Int) -> Date? { let unitFlags = Set<Calendar.Component>([.year, .month, .day]) var components = Calendar.current.dateComponents(unitFlags, from: self) components.year = (components.year ?? 0) + years components.month = (components.month ?? 0) + months components.day = (components.day ?? 0) + days return Calendar.current.date(from: components) } /** Converts NSDate to String with mask format */ public func toString(_ mask: String?) -> String { let dateFormatter = DateFormatter() if mask != nil { dateFormatter.dateFormat = mask }else{ dateFormatter.timeStyle = .medium dateFormatter.dateStyle = .medium } return dateFormatter.string(from: self) } /** Converts NSDate to String with mask format in Gregorian format */ public func toGregorianString(mask: String?) -> String { let dateFormatter = DateFormatter() dateFormatter.calendar = Calendar(identifier: .gregorian) dateFormatter.locale = Locale(identifier: "en_US_POSIX") if mask != nil { dateFormatter.dateFormat = mask }else{ dateFormatter.timeStyle = .medium dateFormatter.dateStyle = .medium } return dateFormatter.string(from: self) } public func dateTimeToFormatter(date: DateFormatter.Style, time: DateFormatter.Style) -> String { return DateFormatter(dateStyle: date, timeStyle: time).string(from: self) } public func dateTimeToGregorianFormatter(date: DateFormatter.Style, time: DateFormatter.Style) -> String { let dateFormatter = DateFormatter(dateStyle: date, timeStyle: time) dateFormatter.calendar = Calendar(identifier: .gregorian) return dateFormatter.string(from: self) } public func dateToFormatter(formatter: DateFormatter.Style) -> String{ return self.dateTimeToFormatter(date: formatter, time: .none) } public func dateToGregorianFormatter(formatter: DateFormatter.Style) -> String{ return self.dateTimeToGregorianFormatter(date: formatter, time: .none) } public func timeToFormatter(formatter: DateFormatter.Style) -> String{ return self.dateTimeToFormatter(date: .none, time:formatter) } public func timeToGregorianFormatter(formatter: DateFormatter.Style) -> String{ return self.dateTimeToGregorianFormatter(date: .none, time:formatter) } public func combine(with time: Date) -> Date? { let calendar = NSCalendar.current let dateComponents = calendar.dateComponents([.year, .month, .day], from: self) let timeComponents = calendar.dateComponents([.hour, .minute, .second], from: time) var mergedComponments = DateComponents() mergedComponments.year = dateComponents.year! mergedComponments.month = dateComponents.month! mergedComponments.day = dateComponents.day! mergedComponments.hour = timeComponents.hour! mergedComponments.minute = timeComponents.minute! mergedComponments.second = timeComponents.second! return calendar.date(from: mergedComponments) } public func dateInRange(from: Date, to: Date, include: Bool = false) -> Bool { if include { return from <= self && self <= to } else { return from < self && self < to } } }
mit
e6e0b2f9e812d4febe7232c0dcafcbf2
36.912281
110
0.638362
4.667387
false
false
false
false
huonw/swift
validation-test/compiler_crashers_fixed/00360-swift-parser-parseexprlist.swift
65
1387
// 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 // RUN: not %target-swift-frontend %s -typecheck import h } func e<l { enum e { func e j { } class l: j{ k() -> ()) } func j<o : Boolean>(l: o) { } func p(l: Any, g: Any) -> (((Any, Any) -> Any) -> Any) { return { (p: (Any, Any) -> Any) -> Any in func n<n : l,) { } n(e()) struct d<f : e, g: e where g.h == f.h> {{ } struct B<T : A> { } protocol C { ty } } protocol a { } protocol h : a { } protocol k : a { } protocol g { } struct n : g { } func i<h : h, f : g m f.n == h> (g: f) { } func i<n : g m n.n = o) { } protoc { } protocol f { protocol c : b { func b class A { class func a() -> String { let d: String = { }() } class d<c>: NSObject { init(b: c) { } } protocol A { } class C<D> { init <A: A where A.B == D>(e: A.B) { } } class A { class func a { return static let d: String = { }() func x } ) T} protocol A { } struct B<T : A> { lett D : C { func g<T where T.E == F>(f: B<T>) { } } struct d<f : e, g: e where g.h == f.h> { col P { } } } i struct c { c a(b: Int0) { } class A { class func a() -> Self { return b(self.dy
apache-2.0
34224606e2294fb627d9b3fa3e4d8f3c
14.411111
79
0.568133
2.429072
false
false
false
false
fschoenm/WeatherBar
WeatherBar/WeatherAPI.swift
1
2244
// // WeatherAPI.swift // WeatherBar // // Created by Frank Schönmann on 04.10.17. // Copyright © 2017 Frank Schönmann. All rights reserved. // import Foundation struct Weather: CustomStringConvertible { var city: String var currentTemp: Float var conditions: String var icon: String var description: String { return "\(city): \(currentTemp)°C and \(conditions)" } } class WeatherAPI { let BASE_URL = "http://api.openweathermap.org/data/2.5/weather" func fetchWeather(_ query: String, success: @escaping (Weather) -> Void) { // load API key from property list var API_KEY: String! if let path = Bundle.main.path(forResource: "ApiKeys", ofType: "plist") { let keys = NSDictionary(contentsOfFile: path) API_KEY = keys?["OpenWeatherMap"] as! String } // try to fetch weather let session = URLSession.shared let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) let url = URL(string: "\(BASE_URL)?APPID=\(API_KEY!)&units=metric&q=\(escapedQuery!)") let task = session.dataTask(with: url!) { data, response, err in if let error = err { NSLog("Weather API error: \(error)") } if let httpResponse = response as? HTTPURLResponse { switch httpResponse.statusCode { case 200: if let weather = self.weatherFromJSONData(data!) { success(weather) } case 401: NSLog("Weather API error: Unauthorized") default: NSLog("Weather API error: %d %@", httpResponse.statusCode, HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode)) } } } task.resume() } func weatherFromJSONData(_ data: Data) -> Weather? { typealias JSONDict = [String:AnyObject] let json : JSONDict do { json = try JSONSerialization.jsonObject(with: data, options: []) as! JSONDict } catch { NSLog("JSON parsing failed: \(error)") return nil } var mainDict = json["main"] as! JSONDict var weatherList = json["weather"] as! [JSONDict] var weatherDict = weatherList[0] let weather = Weather( city: json["name"] as! String, currentTemp: mainDict["temp"] as! Float, conditions: weatherDict["main"] as! String, icon: weatherDict["icon"] as! String ) return weather } }
mit
bde7aab797a8270423ed3b538a134bb8
25.046512
136
0.683929
3.624595
false
false
false
false
dylan/colors
Sources/ColorView.swift
1
1196
// // ColorView.swift // Colors // // Created by Dylan Wreggelsworth on 4/11/17. // Copyright © 2017 Colors. All rights reserved. // import Foundation #if os(macOS) import AppKit public typealias View = NSView public typealias OSColor = NSColor public typealias Rect = NSRect #else import UIKit public typealias View = UIView public typealias OSColor = UIColor public typealias Rect = CGRect #endif public class ColorView: View { let colors: [Color] public init(colors: [Color]) { self.colors = colors let frameRect = Rect(x: 0, y: 0, width: colors.count * 24, height: 24) super.init(frame: frameRect) } public required init?(coder: NSCoder) { self.colors = [Color]() super.init(coder: coder) } public override func draw(_ dirtyRect: Rect) { for (i, color) in colors.enumerated() { let rect = Rect(x: i * 24, y: 0, width: 24, height: 24) #if os(macOS) color.NSColor.setFill() rect.fill() #else color.UIColor.setFill() UIRectFill(rect) #endif } super.draw(dirtyRect) } }
mit
f7a26cbb131df032aad19ff886a898b5
23.387755
78
0.588285
3.930921
false
false
false
false
airspeedswift/swift
test/Constraints/keypath.swift
3
6442
// RUN: %target-swift-frontend -typecheck -verify %S/Inputs/keypath.swift -primary-file %s struct S { let i: Int init() { let _: WritableKeyPath<S, Int> = \.i // no error for Swift 3/4 S()[keyPath: \.i] = 1 // expected-error@-1 {{cannot assign through subscript: function call returns immutable value}} } } func test() { let _: WritableKeyPath<C, Int> = \.i // no error for Swift 3/4 C()[keyPath: \.i] = 1 // warning on write with literal keypath // expected-warning@-1 {{forming a writable keypath to property}} let _ = C()[keyPath: \.i] // no warning for a read } // SR-7339 class Some<T, V> { // expected-note {{'V' declared as parameter to type 'Some'}} init(keyPath: KeyPath<T, ((V) -> Void)?>) { } } class Demo { var here: (() -> Void)? } let some = Some(keyPath: \Demo.here) // expected-error@-1 {{cannot convert value of type 'KeyPath<Demo, (() -> Void)?>' to expected argument type 'KeyPath<Demo, ((V) -> Void)?>'}} // expected-note@-2 {{arguments to generic parameter 'Value' ('(() -> Void)?' and '((V) -> Void)?') are expected to be equal}} // expected-error@-3 {{generic parameter 'V' could not be inferred}} // expected-note@-4 {{explicitly specify the generic arguments to fix this issue}} // SE-0249 func testFunc() { let _: (S) -> Int = \.i _ = ([S]()).map(\.i) _ = \S.init // expected-error {{key path cannot refer to initializer 'init()'}} _ = ([S]()).map(\.init) // expected-error {{key path cannot refer to initializer 'init()'}} let kp = \S.i let _: KeyPath<S, Int> = kp // works, because type defaults to KeyPath nominal let f = \S.i let _: (S) -> Int = f // expected-error {{cannot convert value of type 'KeyPath<S, Int>' to specified type '(S) -> Int'}} } struct SR_12432 { static func takesKeyPath(_: KeyPath<SR_12432.S, String>) -> String { "" } struct S { let text: String = takesKeyPath(\.text) // okay } } // SR-11234 public extension Array { func sorted<C: Comparable, K: KeyPath<Element, C>>(by keyPath: K) -> Array<Element> { let sortedA = self.sorted(by: { $0[keyPath: keyPath] < $1[keyPath: keyPath] }) return sortedA } var i: Int { 0 } } func takesVariadicFnWithGenericRet<T>(_ fn: (S...) -> T) {} // rdar://problem/59445486 func testVariadicKeypathAsFunc() { // These are okay, the base type of the KeyPath is inferred to be [S]. let _: (S...) -> Int = \.i let _: (S...) -> Int = \Array.i takesVariadicFnWithGenericRet(\.i) takesVariadicFnWithGenericRet(\Array.i) // These are not okay, the KeyPath should have a base that matches the // internal parameter type of the function, i.e [S]. let _: (S...) -> Int = \S.i // expected-error {{key path value type 'S' cannot be converted to contextual type '[S]'}} takesVariadicFnWithGenericRet(\S.i) // expected-error {{key path value type 'S' cannot be converted to contextual type '[S]'}} } // rdar://problem/54322807 struct X<T> { init(foo: KeyPath<T, Bool>) { } init(foo: KeyPath<T, Bool?>) { } } struct Wibble { var boolProperty = false } struct Bar { var optWibble: Wibble? = nil } class Foo { var optBar: Bar? = nil } func testFoo<T: Foo>(_: T) { let _: X<T> = .init(foo: \.optBar!.optWibble?.boolProperty) } // rdar://problem/56131416 enum Rdar56131416 { struct Pass<T> {} static func f<T, U>(_ value: T, _ prop: KeyPath<T, U>) -> Pass<U> { fatalError() } struct Fail<T> {} static func f<T, U>(_ value: T, _ transform: (T) -> U) -> Fail<U> { fatalError() } static func takesCorrectType(_: Pass<UInt>) {} } func rdar56131416() { // This call should not be ambiguous. let result = Rdar56131416.f(1, \.magnitude) // no-error // This type should be selected correctly. Rdar56131416.takesCorrectType(result) } func test_mismatch_with_contextual_optional_result() { struct A<T> { init<U: Collection>(_ data: T, keyPath: KeyPath<T, U?>) {} } struct B { var arr: [Int] = [] } let _ = A(B(), keyPath: \.arr) // expected-error@-1 {{key path value type '[Int]' cannot be converted to contextual type '[Int]?'}} } // SR-11184 class SR11184 {} func fSR11184(_ c: SR11184!, _ kp: ReferenceWritableKeyPath<SR11184, String?>, _ str: String) { c[keyPath: kp] = str // OK c![keyPath: kp] = str // OK c?[keyPath: kp] = str // OK } func fSR11184_O(_ c: SR11184!, _ kp: ReferenceWritableKeyPath<SR11184, String?>, _ str: String?) { c[keyPath: kp] = str // OK c![keyPath: kp] = str // OK c?[keyPath: kp] = str // OK } class KeyPathBase {} class KeyPathBaseSubtype: KeyPathBase {} class AnotherBase {} class AnotherComposeBase { var member: KeyPathBase? } func key_path_root_mismatch<T>(_ base: KeyPathBase?, subBase: KeyPathBaseSubtype?, _ abase: AnotherComposeBase, _ kp: KeyPath<KeyPathBase, T>, _ kpa: KeyPath<AnotherBase, T>) { let _ : T = base[keyPath: kp] // expected-error {{value of optional type 'KeyPathBase?' must be unwrapped to a value of type 'KeyPathBase'}} // expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{19-19=!}} // expected-note@-2 {{use '?' to access key path subscript only for non-'nil' base values}} {{19-19=?}} let _ : T = base[keyPath: kpa] // expected-error {{key path with root type 'AnotherBase' cannot be applied to a base of type 'KeyPathBase?'}} // Chained root mismatch let _ : T = abase.member[keyPath: kp] // expected-error {{value of optional type 'KeyPathBase?' must be unwrapped to a value of type 'KeyPathBase'}} // expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{27-27=!}} // expected-note@-2 {{use '?' to access key path subscript only for non-'nil' base values}} {{27-27=?}} let _ : T = abase.member[keyPath: kpa] // expected-error {{key path with root type 'AnotherBase' cannot be applied to a base of type 'KeyPathBase?'}} let _ : T = subBase[keyPath: kp] // expected-error {{value of optional type 'KeyPathBaseSubtype?' must be unwrapped to a value of type 'KeyPathBaseSubtype'}} // expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{22-22=!}} // expected-note@-2 {{use '?' to access key path subscript only for non-'nil' base values}} {{22-22=?}} let _ : T = subBase[keyPath: kpa] // expected-error {{key path with root type 'AnotherBase' cannot be applied to a base of type 'KeyPathBaseSubtype?'}} }
apache-2.0
ee3199fce1f7659d315d8641a0a3a49b
34.59116
159
0.639553
3.450455
false
false
false
false
DroidsOnRoids/SwiftCarousel
Source/SwiftCarousel+UIScrollViewDelegate.swift
1
3253
/* * Copyright (c) 2015 Droids on Roids 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. */ extension SwiftCarousel: UIScrollViewDelegate { public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { didSelectItem() } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { didSelectItem() } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { delegate?.willBeginDragging?(withOffset: scrollView.contentOffset) } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { delegate?.didEndDragging?(withOffset: scrollView.contentOffset) } public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { var velocity = velocity.x * 300.0 var targetX = scrollView.frame.width / 2.0 + velocity // When the target is being scrolled and we scroll again, // the position we need to take as base should be the destination // because velocity will stay and if we will take the current position // we won't get correct item because the X distance we skipped in the // last circle wasn't included in the calculations. if let oldTargetX = currentVelocityX { targetX += (oldTargetX - scrollView.contentOffset.x) } else { targetX += scrollView.contentOffset.x } if velocity >= maxVelocity { velocity = maxVelocity } else if velocity <= -maxVelocity { velocity = -maxVelocity } if (targetX > scrollView.contentSize.width || targetX < 0.0) { targetX = scrollView.contentSize.width / 3.0 + velocity } let choiceView = nearestViewAtLocation(CGPoint(x: targetX, y: scrollView.frame.minY)) let newTargetX = choiceView.center.x - scrollView.frame.width / 2.0 currentVelocityX = newTargetX targetContentOffset.pointee.x = newTargetX if case .max(_) = scrollType { scrollView.isScrollEnabled = false } } }
mit
5b7dd40521305fa206aa9578b5a38245
42.959459
155
0.693206
5.122835
false
false
false
false
prey/prey-ios-client
Prey/Classes/FileRetrieval.swift
1
10772
// // FileRetrieval.swift // Prey // // Created by Javier Cala Uribe on 1/08/18. // Copyright © 2018 Prey Inc. All rights reserved. // import Foundation import Photos import Contacts // Prey fileretrieval params enum kTree: String { case name, path, mimetype, size, isFile, hidden } class FileRetrieval : PreyAction { // MARK: Properties // MARK: Functions // Prey command override func get() { isActive = true PreyLogger("Get tree") // Check iOS version guard #available(iOS 9.0, *) else { sendEmptyData() return } // Params struct var files = [[String:Any]]() let contactSize = getSizeContacts() if contactSize != 0 { files.append([ kTree.name.rawValue : "Contacts.vcf", kTree.path.rawValue : "/Contacts.vcf", kTree.mimetype.rawValue : "text/plain", kTree.size.rawValue : contactSize, kTree.isFile.rawValue : true, kTree.hidden.rawValue : false]) } // Create a PHFetchResult object let allPhotosOptions = PHFetchOptions() allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let allPhotos = PHAsset.fetchAssets(with: allPhotosOptions) for index in 0..<allPhotos.count { let resources = PHAssetResource.assetResources(for: allPhotos.object(at: index)) var sizeOnDisk: Int64 = 1024 if let resource = resources.first { if #available(iOS 10.0, *) { if let unsignedInt64 = resource.value(forKey: "fileSize") as? CLong { sizeOnDisk = Int64(bitPattern: UInt64(unsignedInt64)) } } files.append([ kTree.name.rawValue : resource.originalFilename, kTree.path.rawValue : "/" + resource.originalFilename, kTree.mimetype.rawValue : "image/jpeg", kTree.size.rawValue : sizeOnDisk, kTree.isFile.rawValue : true, kTree.hidden.rawValue : false]) } } // Check empty path guard files.count > 0 else { sendEmptyData() return } // Send data sendTreeDataToPanel(files: files) } func sendEmptyData() { var files = [[String:Any]]() files.append([ kTree.name.rawValue : "Empty", kTree.path.rawValue : "/Empty" , kTree.mimetype.rawValue : "image/jpeg", kTree.size.rawValue : 0, kTree.isFile.rawValue : true, kTree.hidden.rawValue : true]) sendTreeDataToPanel(files: files) } func sendTreeDataToPanel(files:[[String:Any]]) { if let jsonData = try? JSONSerialization.data(withJSONObject: files,options: .prettyPrinted), let jsonString = String(data: jsonData,encoding: String.Encoding.ascii) { let params:[String: String] = [ kAction.tree.rawValue : jsonString] self.sendData(params, toEndpoint: dataDeviceEndpoint) isActive = false } } // Prey command override func start() { PreyLogger("Start fileretrieval") isActive = true // Send start action let params = getParamsTo(kAction.fileretrieval.rawValue, command: kCommand.start.rawValue, status: kStatus.started.rawValue) self.sendData(params, toEndpoint: responseDeviceEndpoint) // Check file_id guard let file_id = self.options?.object(forKey: kOptions.file_id.rawValue) as? String else { // Send stop action PreyLogger("Send stop action on Check file_id") self.stopActionFileRetrieval() return } let endpoint = fileRetrievalEndpoint + "?uploadID=" + file_id // Check name_file guard let name_file = self.options?.object(forKey: kOptions.name.rawValue) as? String else { // Send stop action PreyLogger("Send stop action on Check name_file") self.stopActionFileRetrieval() return } // Check contacts name if name_file == "Contacts.vcf" { sendContacts(endpoint: endpoint) return } // Check iOS version guard #available(iOS 9.0, *) else { // Send stop action self.stopActionFileRetrieval() return } // Create a PHFetchResult object let allPhotosOptions = PHFetchOptions() allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let allPhotos = PHAsset.fetchAssets(with: allPhotosOptions) // Search file by name on PHAssets for index in 0..<allPhotos.count { let resources = PHAssetResource.assetResources(for: allPhotos.object(at: index)) if let resource = resources.first { // Compare names guard resource.originalFilename == name_file else { continue } // Found file let manager = PHImageManager.default() if resource.type == .video { // Upload video let option = PHVideoRequestOptions() option.version = .original manager.requestAVAsset(forVideo: allPhotos.object(at: index), options: option, resultHandler: {(avasset, audiomix, info) in // Check avasset guard let avassetURL = avasset as? AVURLAsset else { // Send stop action self.stopActionFileRetrieval() return } // Check videoData guard let videoData = try? Data(contentsOf: avassetURL.url) else { // Send stop action self.stopActionFileRetrieval() return } // Send file self.sendFileToPanel(data:videoData, endpoint: endpoint) }) } else { // Upload image let option = PHImageRequestOptions() option.isSynchronous = true manager.requestImageData(for: allPhotos.object(at: index), options: option, resultHandler:{(imageData, string, imageOrientation, info) in // Check imageData guard let data = imageData else { // Send stop action self.stopActionFileRetrieval() return } // Send file self.sendFileToPanel(data:data, endpoint: endpoint) }) } break } } } func stopActionFileRetrieval() { let params = self.getParamsTo(kAction.fileretrieval.rawValue, command: kCommand.stop.rawValue, status: kStatus.stopped.rawValue) self.sendData(params, toEndpoint: responseDeviceEndpoint) self.isActive = false } func sendFileToPanel(data: Data, endpoint: String) { // Check userApiKey isn't empty if let username = PreyConfig.sharedInstance.userApiKey, PreyConfig.sharedInstance.isRegistered { PreyHTTPClient.sharedInstance.sendFileToPrey(username, password:"x", file:data, messageId:nil, httpMethod:Method.POST.rawValue, endPoint:endpoint, onCompletion:PreyHTTPResponse.checkResponse(RequestType.dataSend, preyAction:self, onCompletion:{(isSuccess: Bool) in PreyLogger("Request fileSend") // Send stop action self.stopActionFileRetrieval() })) } else { PreyLogger("Error send file") // Send stop action self.stopActionFileRetrieval() } } func sendContacts(endpoint: String) { // contacts.vcf guard #available(iOS 9.0, *) else { return } let fetchRequest = CNContactFetchRequest( keysToFetch: [CNContactVCardSerialization.descriptorForRequiredKeys()]) var contacts = [CNContact]() CNContact.localizedString(forKey: CNLabelPhoneNumberiPhone) if #available(iOS 10.0, *) { fetchRequest.mutableObjects = false } fetchRequest.unifyResults = true fetchRequest.sortOrder = .userDefault do { try CNContactStore().enumerateContacts(with: fetchRequest) { (contact, stop) -> Void in contacts.append(contact) } } catch let e as NSError { print(e.localizedDescription) } do { let data = try CNContactVCardSerialization.data(with: contacts) // Send file self.sendFileToPanel(data:data, endpoint: endpoint) } catch let e as NSError { print(e.localizedDescription) } } func getSizeContacts() -> Int { // contacts.vcf guard #available(iOS 9.0, *) else { return 0 } let fetchRequest = CNContactFetchRequest( keysToFetch: [CNContactVCardSerialization.descriptorForRequiredKeys()]) var contacts = [CNContact]() CNContact.localizedString(forKey: CNLabelPhoneNumberiPhone) if #available(iOS 10.0, *) { fetchRequest.mutableObjects = false } fetchRequest.unifyResults = true fetchRequest.sortOrder = .userDefault do { try CNContactStore().enumerateContacts(with: fetchRequest) { (contact, stop) -> Void in contacts.append(contact) } } catch let e as NSError { print(e.localizedDescription) } if contacts.count == 0 { return 0 } do { let data = try CNContactVCardSerialization.data(with: contacts) return data.count } catch let e as NSError { print(e.localizedDescription) } return 0 } }
gpl-3.0
d4a07b3a552cad480ada22a81630d459
35.265993
276
0.535883
5.401705
false
false
false
false
darkdong/DarkSwift
Tests/DarkSwiftTests.swift
1
5308
// // DarkSwiftTests.swift // DarkSwiftTests // // Created by Dark Dong on 2017/3/31. // Copyright © 2017年 Dark Dong. All rights reserved. // import XCTest @testable import DarkSwift class DarkSwiftTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } func testLayout() { let container = UIView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 320, height: 320))) let insets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) let v1 = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 40)) let v2 = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 100)) let v3 = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 80)) var views = [v1, v2, v3] container.layoutSubviews(views, alignment: .horizontal(.center), insets: insets) XCTAssert(v1.frame.center == CGPoint(x: 60, y: 160)) XCTAssert(v2.frame.center == CGPoint(x: 160, y: 160)) XCTAssert(v3.frame.center == CGPoint(x: 260, y: 160)) container.layoutSubviews(views, alignment: .horizontal(.top), insets: insets) XCTAssert(v1.frame.center == CGPoint(x: 60, y: 40)) XCTAssert(v2.frame.center == CGPoint(x: 160, y: 70)) XCTAssert(v3.frame.center == CGPoint(x: 260, y: 60)) container.layoutSubviews(views, alignment: .horizontal(.bottom), insets: insets) XCTAssert(v1.frame.center == CGPoint(x: 60, y: 280)) XCTAssert(v2.frame.center == CGPoint(x: 160, y: 250)) XCTAssert(v3.frame.center == CGPoint(x: 260, y: 260)) container.layoutSubviews(views, alignment: .vertical(.center), insets: insets) XCTAssert(v1.frame.center == CGPoint(x: 160, y: 40)) XCTAssert(v2.frame.center == CGPoint(x: 160, y: 140)) XCTAssert(v3.frame.center == CGPoint(x: 160, y: 260)) container.layoutSubviews(views, alignment: .vertical(.left), insets: insets) XCTAssert(v1.frame.center == CGPoint(x: 60, y: 40)) XCTAssert(v2.frame.center == CGPoint(x: 60, y: 140)) XCTAssert(v3.frame.center == CGPoint(x: 60, y: 260)) container.layoutSubviews(views, alignment: .vertical(.right), insets: insets) XCTAssert(v1.frame.center == CGPoint(x: 260, y: 40)) XCTAssert(v2.frame.center == CGPoint(x: 260, y: 140)) XCTAssert(v3.frame.center == CGPoint(x: 260, y: 260)) let v4 = v3.clone() as! UIView let v5 = v2.clone() as! UIView let v6 = v1.clone() as! UIView views = [v1, v2, v3, v4, v5, v6] container.layoutSubviews(views, alignment: .tabular(2, 3, CGSize(width: 80, height: 80)), insets: insets) XCTAssert(v1.frame.center == CGPoint(x: 60, y: 90)) XCTAssert(v2.frame.center == CGPoint(x: 160, y: 90)) XCTAssert(v3.frame.center == CGPoint(x: 260, y: 90)) XCTAssert(v4.frame.center == CGPoint(x: 60, y: 230)) XCTAssert(v5.frame.center == CGPoint(x: 160, y: 230)) XCTAssert(v6.frame.center == CGPoint(x: 260, y: 230)) } func testDigest() { XCTAssert("".hash(algorithm: .md5) == "d41d8cd98f00b204e9800998ecf8427e") XCTAssert("".hash(algorithm: .sha1) == "da39a3ee5e6b4b0d3255bfef95601890afd80709") XCTAssert("".hash(algorithm: .sha224) == "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f") XCTAssert("".hash(algorithm: .sha256) == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") XCTAssert("".hash(algorithm: .sha384) == "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b") XCTAssert("".hash(algorithm: .sha512) == "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e") XCTAssert("".hmac(algorithm: .md5, key: "") == "74e6f7298a9c2d168935f58c001bad88") XCTAssert("".hmac(algorithm: .sha1, key: "") == "fbdb1d1b18aa6c08324b7d64b71fb76370690e1d") XCTAssert("".hmac(algorithm: .sha256, key: "") == "b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad") let string = "The quick brown fox jumps over the lazy dog" XCTAssert(string.hash(algorithm: .sha1) == "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12") XCTAssert(string.hmac(algorithm: .md5, key: "key") == "80070713463e7749b90c2dc24911e275") XCTAssert(string.hmac(algorithm: .sha1, key: "key") == "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9") XCTAssert(string.hmac(algorithm: .sha256, key: "key") == "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8") } }
mit
4f278f334bffccdc3ff07b4095dffc4b
50.504854
180
0.655796
3.127948
false
true
false
false
rhx/gir2swift
Sources/libgir2swift/models/girtype+xml.swift
1
4233
// // girtype+xml.swift // libgir2swift // // Created by Rene Hexel on 18/7/20. // Copyright © 2020 Rene Hexel. All rights reserved. // import Foundation import SwiftLibXML let whiteSpacesAndAsterisks = CharacterSet(charactersIn: "*").union(.whitespaces) extension SwiftLibXML.XMLElement { /// Return a type reference for an XML node counting the level of indirection /// through `const` and non-`const` pointers var alias: TypeReference { let typeName = attribute(named: "type-name")?.withNormalisedPrefix let ctype = attribute(named: "type")?.withNormalisedPrefix ?? typeName let nameAttr = attribute(named: "name")?.withNormalisedPrefix guard let cAttr = ctype ?? nameAttr, nameAttr != "none" else { return .void } let cReference = decodeIndirection(for: cAttr) let innerType = cReference.innerType let innerName = innerType.isEmpty ? type.type.name : innerType let rawName: String let namespace: String? let prefixedName: String if let n = nameAttr { rawName = n.unprefixed() prefixedName = n.contains(".") ? n : (n == ctype ? n : GIR.dottedPrefix + n) namespace = n == ctype ? "" : String(prefixedName.namespacePrefix) } else { rawName = innerName prefixedName = rawName namespace = nil } let name = rawName.validSwift let cName = ctype ?? name let plainType = (innerName.isEmpty ? nil : innerName) ?? typeName let identifier = attribute(named: "identifier") let isNullable = attribute(named: "nullable").flatMap({ Int($0) }).map({ $0 != 0 }) ?? false let oldN = GIR.namedTypes[prefixedName]?.count ?? 0 let rawTypeRef: TypeReference // // Check if the exact same C type exists without any namespace, // if so, create a namespaced alias // if oldN == 0, let unprefixedType = (GIR.namedTypes[rawName] ?? []).lazy.filter({ $0.ctype == cName }).first { rawTypeRef = typeReference(original: unprefixedType, named: identifier, for: name, in: namespace, swiftName: unprefixedType.swiftName, cType: cName, isOptional: isNullable) } else { rawTypeRef = typeReference(named: identifier, for: name, in: namespace, typeName: plainType, cType: cName, isOptional: isNullable) } let typeRef = GIR.swiftFundamentalReplacements[rawTypeRef] ?? rawTypeRef let newN = GIR.namedTypes[prefixedName]?.count ?? 0 let isNewType = oldN != newN guard isNewType, let typeXMLNode = children.filter({ $0.name == "type" }).first else { return typeRef } let orig = typeRef.type let alias = typeXMLNode.alias // let parent = alias.type let gt = GIRType(name: name, swiftName: orig.swiftName, typeName: orig.typeName, ctype: orig.ctype, superType: alias, isAlias: true) let t = addType(gt) var ref = TypeReference(type: t, identifier: identifier) ref.constPointers = typeRef.constPointers ref.isConst = typeRef.isConst return ref } /// Return a type reference that is tracking the level of indirection /// through `const` and non-`const` pointers var type: TypeReference { guard let typeXMLNode = children.filter({ $0.name == "type" }).first else { return .void } var type = typeXMLNode.alias type.isOptional = attribute(named: "nullable").flatMap({ Int($0) }).map({ $0 != 0 }) ?? type.isOptional return type } /// Return the types contained within the given field/parameter var containedTypes: [GIR.CType] { var index = 0 let containedTypes: [GIR.CType] = children.compactMap { child in switch child.name { case "type": defer { index += 1 } return GIR.CType(node: child, at: index) case "callback": defer { index += 1 } return GIR.Callback(node: child, at: index) default: return nil } } return containedTypes } }
bsd-2-clause
73427c3060ff4d0020d9f5d6f57a3e4d
40.90099
184
0.60586
4.403746
false
false
false
false
kaihoko-kenta/KPCRotateWalkthrough
Example/Tests/Tests.swift
1
1187
// https://github.com/Quick/Quick import Quick import Nimble import KPCRotateWalkthrough class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
e1623397464cc2eb08f50ac1d0c7d9a9
22.62
63
0.369179
5.493023
false
false
false
false
aroyarexs/PASTA
PASTA/Classes/PASTATangible.swift
1
12963
// // PASTATangible.swift // PAD // // Created by Aaron Krämer on 07.08.17. // Copyright © 2017 Aaron Krämer. All rights reserved. // import UIKit import Metron /** This class represents a Tangible of exact 3 markers. Tangible adds itself as subview of `superview` of first marker. It overrides `hitTest(_:with:)` and checks all markers by calling their `hitTest(_:with:)` function. Check function documentation for further details. If you need a Tangible which supports less or more than 3 markers you have to create a subclass. */ public class PASTATangible: PASTAMarker { // TODO: Rename to PassiveTangible public override var useMeanValues: Bool { didSet { markers.forEach { $0.useMeanValues = useMeanValues } } } /// Vector from center to marker 0. Used as initial orientation let initialCenterToMarker0Vector: CGVector /// The orientation as a vector since this Tangible was detected. /// Vector magnitude is 1 such that you can multiply it e.g. with `radius`. public var initialOrientationVector: CGVector { let centerToMarkerVector = CGVector(from: center, to: markers[0].center) let angle = initialCenterToMarker0Vector.angle(between: centerToMarkerVector) return CGVector(angle: angle + Angle(.pi/2 * -1), magnitude: 1) } /// The orientation of this Tangible based on the pattern as a normalized vector. /// `nil` if pattern has no uniquely identifiable marker. public var orientationVector: CGVector? { guard let marker = markerWithAngleSimilarToNone() else { return nil } return CGVector(from: center, to: marker.center).normalized } /// Internal array of marker. Mutable. var internalMarkers: [PASTAMarker] /// Array of `PASTAMarker`. get-only. public var markers: [PASTAMarker] { return internalMarkers } /// Returns an array containing all inactive markers. public var inactiveMarkers: [PASTAMarker] { return markers.filter({ !$0.isActive }) } /// The tangible manager who created this Tangible. public weak var tangibleManager: TangibleManager? /// Set this to get event updates of this Tangible. public weak var eventDelegate: TangibleEvent? /// Dictionary containing mean calculator instances for each marker's angle. var meanAngles = [PASTAMarker: PASTAMeanCalculator]() // FIXME: Currently unused /// Describes the pattern of this Tangible. public internal (set) var pattern: PASTAPattern /// The identifier of the similar pattern which is used in the `patternWhitelist` of `PASTAManager`. public var patternIdentifier: String? { return (tangibleManager?.patternWhitelist.first { pattern.isSimilar(to: $0.value) })?.key } // MARK: - Functions public required init?(markers: [PASTAMarker]) { guard markers.count == 3 else { return nil } internalMarkers = markers pattern = PASTAPattern(marker1: markers[0], marker2: markers[1], marker3: markers[2]) let triangle = Triangle(a: markers[0].center, b: markers[1].center, c: markers[2].center) let radius = CGVector(from: triangle.cicrumcenter, to: markers[0].center).magnitude initialCenterToMarker0Vector = CGVector(from: triangle.cicrumcenter, to: markers[0].center) // TODO: decide if tangible can be formed (min, max radius?) super.init(center: triangle.cicrumcenter, radius: radius) markers.first?.superview?.addSubview(self) isActive = false markers.forEach { $0.tangible = self meanAngles[$0] = PASTAMeanCalculator() isActive = isActive || $0.isActive } } /** Always returns `nil`. Use `init?(markers:)` instead. */ public required convenience init?(coder aDecoder: NSCoder) { self.init(markers: []) } /** Tries to replace the provided `newMarker` with an inactive marker. `newMarker` will have `previousCenter` and `tag` set to the values of the replaced inactive marker. - parameter newMarker: The marker which should replace an inactive. - returns: `true` if `newMarker` has replaced an inactive, otherwise `false`. */ func replaceInactiveMarker(with newMarker: PASTAMarker) -> Bool { let activeMarkers = markers.filter { $0.isActive } var replaceableMarker: PASTAMarker? if activeMarkers.count == 1 { let firstInactiveMarker = inactiveMarkers.first! guard let firstInactiveInPattern = pattern.snapshot(for: firstInactiveMarker) else { return false } let secondInactiveMarker = inactiveMarkers.last! guard let secondInactiveInPattern = pattern.snapshot(for: secondInactiveMarker) else { return false } let activeMarker = activeMarkers.first! let activeToNew = LineSegment(a: activeMarker.center, b: newMarker.center) guard let activeToFirstInactive = pattern.vector(from: activeMarker, to: firstInactiveMarker) else { return false } guard let activeToSecondInactive = pattern.vector(from: activeMarker, to: secondInactiveMarker) else { return false } let isDistanceWithinFirstInactive = abs(activeToNew.length - activeToFirstInactive.magnitude) < firstInactiveInPattern.radius let isDistanceWithinSecondInactive = abs(activeToNew.length - activeToSecondInactive.magnitude) < secondInactiveInPattern.radius if isDistanceWithinFirstInactive && isDistanceWithinSecondInactive { let firstSegment = LineSegment(a: newMarker.center, b: firstInactiveMarker.center) let secondSegment = LineSegment(a: newMarker.center, b: secondInactiveMarker.center) replaceableMarker = firstSegment.length < secondSegment.length ? firstInactiveMarker : secondInactiveMarker } else { replaceableMarker = isDistanceWithinFirstInactive ? firstInactiveMarker : secondInactiveMarker } } else if activeMarkers.count == 2 { let firstMarker = activeMarkers.first! let lastMarker = activeMarkers.last! let newPattern = PASTAPattern(marker1: firstMarker, marker2: lastMarker, marker3: newMarker) if pattern.isSimilar(to: newPattern), let inactive = inactiveMarkers.first { replaceableMarker = inactive } } if let replaceableMarker = replaceableMarker, let index = internalMarkers.index(of: replaceableMarker) { internalMarkers.remove(at: index) internalMarkers.insert(newMarker, at: index) replaceableMarker.removeFromSuperview() newMarker.previousCenter = replaceableMarker.center newMarker.markerSnapshot = replaceableMarker.markerSnapshot markerDidBecomeActive(newMarker) newMarker.tangible = self } return replaceableMarker != nil } /// Searches for the marker which angle is distinguishable from the other two. /// - returns: A marker or `nil`. func markerWithAngleSimilarToNone() -> PASTAMarker? { for marker in internalMarkers { let angle = pattern.angle(atMarkerWith: marker.markerSnapshot.uuidString) var notSimilar = true markers.forEach { comparator in guard marker != comparator else { return } let comparatorId = comparator.markerSnapshot.uuidString notSimilar = notSimilar && pattern.isAngleSimilar(atMarkerWith: comparatorId, to: angle) == false } if notSimilar { return marker } } return nil } // TODO: Is there another way to uniquely select a marker? // MARK: - Static Functions /** Checks if `left` is similar `right`. - parameters: - left: Left hand side. - right: Right hand side. - returns: `true` be similar, else `false`. */ public static func ~ (_ left: PASTATangible, _ right: PASTATangible) -> Bool { return left.pattern.isSimilar(to: right.pattern) } // MARK: - Hit Test Override /** Checks all markers by calling their `hitTest(_:with:)` function. If none found it returns itself if `event ` is `nil`, otherwise it returns `nil`. - parameters: - point: Point tot test. - event: Optional. - returns: A marker or `nil`. */ public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { guard self.point(inside: point, with: event) else { return nil } // TODO: debug let marker = inactiveMarkers.first { $0.hitTest(point, with: event) != nil } return marker ?? event == nil ? self : nil // TODO: may need to consider gestures https://developer.apple.com/documentation/uikit/uievent/1613832-touches // TODO: if no marker return self -> override touches... functions to let the touch run into void // does gestures then still work? } // TODO: do I need to override pointInside() because Tangible is detected as circle // add radius of biggest marker to radius of tangible and check if inside circle } extension PASTATangible: MarkerEvent { // MARK: - MarkerEvent public func markerMoved(_ marker: PASTAMarker) { // updating inactive markers if inactiveMarkers.count == 2 { let translate = marker.center - marker.previousCenter inactiveMarkers.forEach { $0.center = $0.center + translate } center = center + translate } else if inactiveMarkers.count == 1, let inactiveMarker = inactiveMarkers.first, let theOtherActiveMarker = (markers.first { $0 != inactiveMarker && $0 != marker }) { let possibleCenters = CGPoint.circleCenters( point1: marker.center, point2: theOtherActiveMarker.center, radius: radius) center = center.closest(point1: possibleCenters.0, point2: possibleCenters.1) // calculating new position for inactive marker guard let originalActiveVector = pattern.vector(from: theOtherActiveMarker, to: marker) else { return } let currentActiveVector = CGVector(from: theOtherActiveMarker.center, to: marker.center) let angle = originalActiveVector.angle(between: currentActiveVector) guard let inactiveInPattern = pattern.snapshot(for: inactiveMarker), let otherActiveInPattern = pattern.snapshot(for: theOtherActiveMarker) else { return } let newPatternCenter = LineSegment(a: otherActiveInPattern.center, b: .zero).rotatedAroundA(angle).b let newInactiveInPattern = LineSegment(a: otherActiveInPattern.center, b: inactiveInPattern.center).rotatedAroundA(angle).b // TODO: test new implementation inactiveMarker.center = center + LineSegment(a: newPatternCenter, b: newInactiveInPattern).vector } else { center = Triangle(a: markers[0].center, b: markers[1].center, c: markers[2].center).cicrumcenter } radius = CGVector(from: center, to: marker.center).magnitude if center != previousCenter { eventDelegate?.tangibleMoved(self) tangible?.markerMoved(self) } } public func markerDidBecomeActive(_ marker: PASTAMarker) { markerMoved(marker) if isActive == false && markers.count != inactiveMarkers.count { // was inactive and now one active marker isActive = true marker.superview?.addSubview(self) tangibleManager?.tangibleDidBecomeActive(self) eventDelegate?.tangibleDidBecomeActive(self) // tangible used as marker tangible?.markerDidBecomeActive(self) markerManager?.markerDidBecomeActive(self) } tangibleManager?.tangible(self, recovered: marker) eventDelegate?.tangible(self, recovered: marker) } public func markerDidBecomeInactive(_ marker: PASTAMarker) { if inactiveMarkers.count == 1 { pattern = PASTAPattern(marker1: markers[0], marker2: markers[1], marker3: markers[2]) } tangibleManager?.tangible(self, lost: marker) eventDelegate?.tangible(self, lost: marker) if markers.count == inactiveMarkers.count { // all marker inactive -> tangible inactive isActive = false removeFromSuperview() markers.forEach { $0.removeFromSuperview() } tangibleManager?.tangibleDidBecomeInactive(self) eventDelegate?.tangibleDidBecomeInactive(self) // tangible used as marker markerManager?.markerDidBecomeInactive(self) tangible?.markerDidBecomeInactive(self) } } }
mit
52946e4efd5675460fda1abb393ab6a1
44.473684
168
0.659954
4.996145
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/Sections/Message/Private/PrivateMessageModel.swift
1
1121
// // PrivateMessageModel.swift // HiPDA // // Created by leizh007 on 2017/6/30. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation import Argo import Runes import Curry struct PrivateMessageModel: BaseMessageModel { let sender: User let time: String let content: String let isRead: Bool let url: String } // MARK: - Serializable extension PrivateMessageModel: Serializable { } // MARK: - Decodable extension PrivateMessageModel: Decodable { static func decode(_ json: JSON) -> Decoded<PrivateMessageModel> { return curry(PrivateMessageModel.init(sender:time:content:isRead:url:)) <^> json <| "sender" <*> json <| "time" <*> json <| "content" <*> json <| "isRead" <*> json <| "url" } } // MARK: - Equalable extension PrivateMessageModel: Equatable { static func ==(lhs: PrivateMessageModel, rhs: PrivateMessageModel) -> Bool { return lhs.sender == rhs.sender && lhs.time == rhs.time && lhs.content == rhs.content && lhs.url == rhs.url } }
mit
5e7f11c211ae3761881262b8ecf9e048
22.291667
80
0.61449
4.234848
false
false
false
false
brentdax/swift
stdlib/public/core/DictionaryCasting.swift
2
4053
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //===--- Compiler conversion/casting entry points for Dictionary<K, V> ----===// /// Perform a non-bridged upcast that always succeeds. /// /// - Precondition: `BaseKey` and `BaseValue` are base classes or base `@objc` /// protocols (such as `AnyObject`) of `DerivedKey` and `DerivedValue`, /// respectively. @inlinable public func _dictionaryUpCast<DerivedKey, DerivedValue, BaseKey, BaseValue>( _ source: Dictionary<DerivedKey, DerivedValue> ) -> Dictionary<BaseKey, BaseValue> { var result = Dictionary<BaseKey, BaseValue>(minimumCapacity: source.count) for (k, v) in source { result[k as! BaseKey] = (v as! BaseValue) } return result } /// Called by the casting machinery. @_silgen_name("_swift_dictionaryDownCastIndirect") internal func _dictionaryDownCastIndirect<SourceKey, SourceValue, TargetKey, TargetValue>( _ source: UnsafePointer<Dictionary<SourceKey, SourceValue>>, _ target: UnsafeMutablePointer<Dictionary<TargetKey, TargetValue>>) { target.initialize(to: _dictionaryDownCast(source.pointee)) } /// Implements a forced downcast. This operation should have O(1) complexity. /// /// The cast can fail if bridging fails. The actual checks and bridging can be /// deferred. /// /// - Precondition: `DerivedKey` is a subtype of `BaseKey`, `DerivedValue` is /// a subtype of `BaseValue`, and all of these types are reference types. @inlinable public func _dictionaryDownCast<BaseKey, BaseValue, DerivedKey, DerivedValue>( _ source: Dictionary<BaseKey, BaseValue> ) -> Dictionary<DerivedKey, DerivedValue> { #if _runtime(_ObjC) if _isClassOrObjCExistential(BaseKey.self) && _isClassOrObjCExistential(BaseValue.self) && _isClassOrObjCExistential(DerivedKey.self) && _isClassOrObjCExistential(DerivedValue.self) { guard source._variant.isNative else { return Dictionary( _immutableCocoaDictionary: source._variant.asCocoa.object) } // Note: it is safe to treat the buffer as immutable here because // Dictionary will not mutate buffer with reference count greater than 1. return Dictionary( _immutableCocoaDictionary: source._variant.asNative.bridged()) } #endif return _dictionaryDownCastConditional(source)! } /// Called by the casting machinery. @_silgen_name("_swift_dictionaryDownCastConditionalIndirect") internal func _dictionaryDownCastConditionalIndirect<SourceKey, SourceValue, TargetKey, TargetValue>( _ source: UnsafePointer<Dictionary<SourceKey, SourceValue>>, _ target: UnsafeMutablePointer<Dictionary<TargetKey, TargetValue>> ) -> Bool { if let result: Dictionary<TargetKey, TargetValue> = _dictionaryDownCastConditional(source.pointee) { target.initialize(to: result) return true } return false } /// Implements a conditional downcast. /// /// If the cast fails, the function returns `nil`. All checks should be /// performed eagerly. /// /// - Precondition: `DerivedKey` is a subtype of `BaseKey`, `DerivedValue` is /// a subtype of `BaseValue`, and all of these types are reference types. @inlinable public func _dictionaryDownCastConditional< BaseKey, BaseValue, DerivedKey, DerivedValue >( _ source: Dictionary<BaseKey, BaseValue> ) -> Dictionary<DerivedKey, DerivedValue>? { var result = Dictionary<DerivedKey, DerivedValue>() for (k, v) in source { guard let k1 = k as? DerivedKey, let v1 = v as? DerivedValue else { return nil } result[k1] = v1 } return result }
apache-2.0
f4635e865a42af0639889f15cd717216
36.527778
80
0.686405
4.669355
false
false
false
false
brentdax/swift
test/IRGen/closure.swift
2
3350
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // -- partial_apply context metadata // CHECK: [[METADATA:@.*]] = private constant %swift.full_boxmetadata { void (%swift.refcounted*)* @objectdestroy, i8** null, %swift.type { i64 1024 }, i32 16, i8* bitcast ({ i32, i32, i32, i32 }* @"\01l__swift5_reflection_descriptor" to i8*) } func a(i i: Int) -> (Int) -> Int { return { x in i } } // -- Closure entry point // CHECK: define internal swiftcc i64 @"$s7closure1a1iS2icSi_tFS2icfU_"(i64, i64) protocol Ordinable { func ord() -> Int } func b<T : Ordinable>(seq seq: T) -> (Int) -> Int { return { i in i + seq.ord() } } // -- partial_apply stub // CHECK: define internal swiftcc i64 @"$s7closure1a1iS2icSi_tFS2icfU_TA"(i64, %swift.refcounted* swiftself) // CHECK: } // -- Closure entry point // CHECK: define internal swiftcc i64 @"$s7closure1b3seqS2icx_tAA9OrdinableRzlFS2icfU_"(i64, %swift.refcounted*, %swift.type* %T, i8** %T.Ordinable) {{.*}} { // -- partial_apply stub // CHECK: define internal swiftcc i64 @"$s7closure1b3seqS2icx_tAA9OrdinableRzlFS2icfU_TA"(i64, %swift.refcounted* swiftself) {{.*}} { // CHECK: entry: // CHECK: [[CONTEXT:%.*]] = bitcast %swift.refcounted* %1 to <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* // CHECK: [[BINDINGSADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 1 // CHECK: [[TYPEADDR:%.*]] = bitcast [16 x i8]* [[BINDINGSADDR]] // CHECK: [[TYPE:%.*]] = load %swift.type*, %swift.type** [[TYPEADDR]], align 8 // CHECK: [[WITNESSADDR_0:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[TYPEADDR]], i32 1 // CHECK: [[WITNESSADDR:%.*]] = bitcast %swift.type** [[WITNESSADDR_0]] // CHECK: [[WITNESS:%.*]] = load i8**, i8*** [[WITNESSADDR]], align 8 // CHECK: [[BOXADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 2 // CHECK: [[BOX:%.*]] = load %swift.refcounted*, %swift.refcounted** [[BOXADDR]], align 8 // CHECK: [[RES:%.*]] = tail call swiftcc i64 @"$s7closure1b3seqS2icx_tAA9OrdinableRzlFS2icfU_"(i64 %0, %swift.refcounted* [[BOX]], %swift.type* [[TYPE]], i8** [[WITNESS]]) // CHECK: ret i64 [[RES]] // CHECK: } // -- <rdar://problem/14443343> Boxing of tuples with generic elements // CHECK: define hidden swiftcc { i8*, %swift.refcounted* } @"$s7closure14captures_tuple1xx_q_tycx_q_t_tr0_lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U) func captures_tuple<T, U>(x x: (T, U)) -> () -> (T, U) { // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_getTupleTypeMetadata2(i64 0, %swift.type* %T, %swift.type* %U, i8* null, i8** null) // CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NOT: @swift_getTupleTypeMetadata2 // CHECK: [[BOX:%.*]] = call swiftcc { %swift.refcounted*, %swift.opaque* } @swift_allocBox(%swift.type* [[METADATA]]) // CHECK: [[ADDR:%.*]] = extractvalue { %swift.refcounted*, %swift.opaque* } [[BOX]], 1 // CHECK: bitcast %swift.opaque* [[ADDR]] to <{}>* return {x} }
apache-2.0
d8aa5b75ceaf928a621f46ef4caadc20
57.77193
244
0.638806
3.151458
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/swift-protobuf/Sources/PluginLibrary/SwiftProtobufNamer.swift
3
14090
// Sources/PluginLibrary/SwiftProtobufNamer.swift - A helper that generates SwiftProtobuf names. // // Copyright (c) 2014 - 2017 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// A helper that can generate SwiftProtobuf names from types. /// // ----------------------------------------------------------------------------- import Foundation public final class SwiftProtobufNamer { var filePrefixCache = [String:String]() var enumValueRelativeNameCache = [String:String]() var mappings: ProtoFileToModuleMappings var targetModule: String /// Initializes a a new namer, assuming everything will be in the same Swift module. public convenience init() { self.init(protoFileToModuleMappings: ProtoFileToModuleMappings(), targetModule: "") } /// Initializes a a new namer. All names will be generated as from the pov of the /// given file using the provided file to module mapper. public convenience init( currentFile file: FileDescriptor, protoFileToModuleMappings mappings: ProtoFileToModuleMappings ) { let targetModule = mappings.moduleName(forFile: file) ?? "" self.init(protoFileToModuleMappings: mappings, targetModule: targetModule) } /// Internal initializer. init( protoFileToModuleMappings mappings: ProtoFileToModuleMappings, targetModule: String ) { self.mappings = mappings self.targetModule = targetModule } /// Calculate the relative name for the given message. public func relativeName(message: Descriptor) -> String { if message.containingType != nil { return NamingUtils.sanitize(messageName: message.name) } else { let prefix = typePrefix(forFile: message.file) return NamingUtils.sanitize(messageName: prefix + message.name) } } /// Calculate the full name for the given message. public func fullName(message: Descriptor) -> String { let relativeName = self.relativeName(message: message) guard let containingType = message.containingType else { return modulePrefix(file: message.file) + relativeName } return fullName(message:containingType) + "." + relativeName } /// Calculate the relative name for the given enum. public func relativeName(enum e: EnumDescriptor) -> String { if e.containingType != nil { return NamingUtils.sanitize(enumName: e.name) } else { let prefix = typePrefix(forFile: e.file) return NamingUtils.sanitize(enumName: prefix + e.name) } } /// Calculate the full name for the given enum. public func fullName(enum e: EnumDescriptor) -> String { let relativeName = self.relativeName(enum: e) guard let containingType = e.containingType else { return modulePrefix(file: e.file) + relativeName } return fullName(message: containingType) + "." + relativeName } /// Compute the short names to use for the values of this enum. private func computeRelativeNames(enum e: EnumDescriptor) { let stripper = NamingUtils.PrefixStripper(prefix: e.name) /// Determine the initial canidate name for the name before /// doing duplicate checks. func canidateName(_ enumValue: EnumValueDescriptor) -> String { let baseName = enumValue.name if let stripped = stripper.strip(from: baseName) { let camelCased = NamingUtils.toLowerCamelCase(stripped) if isValidSwiftIdentifier(camelCased) { return camelCased } } return NamingUtils.toLowerCamelCase(baseName) } // Bucketed based on candidate names to check for duplicates. var canidates = [String:[EnumValueDescriptor]]() for enumValue in e.values { let canidate = canidateName(enumValue) if var existing = canidates[canidate] { existing.append(enumValue) canidates[canidate] = existing } else { canidates[canidate] = [enumValue] } } for (camelCased, enumValues) in canidates { // If there is only one, sanitize and cache it. guard enumValues.count > 1 else { enumValueRelativeNameCache[enumValues.first!.fullName] = NamingUtils.sanitize(enumCaseName: camelCased) continue } // There are two possible cases: // 1. There is the main entry and then all aliases for it that // happen to be the same after the prefix was stripped. // 2. There are atleast two values (there could also be aliases). // // For the first case, there's no need to do anything, we'll go // with just one Swift version. For the second, append "_#" to // the names to help make the different Swift versions clear // which they are. let firstValue = enumValues.first!.number let hasMultipleValues = enumValues.contains(where: { return $0.number != firstValue }) guard hasMultipleValues else { // Was the first case, all one value, just aliases that mapped // to the same name. let name = NamingUtils.sanitize(enumCaseName: camelCased) for e in enumValues { enumValueRelativeNameCache[e.fullName] = name } continue } for e in enumValues { // Can't put a negative size, so use "n" and make the number // positive. let suffix = e.number >= 0 ? "_\(e.number)" : "_n\(-e.number)" enumValueRelativeNameCache[e.fullName] = NamingUtils.sanitize(enumCaseName: camelCased + suffix) } } } /// Calculate the relative name for the given enum value. public func relativeName(enumValue: EnumValueDescriptor) -> String { if let name = enumValueRelativeNameCache[enumValue.fullName] { return name } computeRelativeNames(enum: enumValue.enumType) return enumValueRelativeNameCache[enumValue.fullName]! } /// Calculate the full name for the given enum value. public func fullName(enumValue: EnumValueDescriptor) -> String { return fullName(enum: enumValue.enumType) + "." + relativeName(enumValue: enumValue) } /// The relative name with a leading dot so it can be used where /// the type is known. public func dottedRelativeName(enumValue: EnumValueDescriptor) -> String { let relativeName = self.relativeName(enumValue: enumValue) return "." + NamingUtils.trimBackticks(relativeName) } /// Filters the Enum's values to those that will have unique Swift /// names. Only poorly named proto enum alias values get filtered /// away, so the assumption is they aren't really needed from an /// api pov. public func uniquelyNamedValues(enum e: EnumDescriptor) -> [EnumValueDescriptor] { return e.values.filter { guard let aliasOf = $0.aliasOf else { return true } let relativeName = self.relativeName(enumValue: $0) let aliasOfRelativeName = self.relativeName(enumValue: aliasOf) return relativeName != aliasOfRelativeName } } /// Calculate the relative name for the given oneof. public func relativeName(oneof: OneofDescriptor) -> String { let camelCase = NamingUtils.toUpperCamelCase(oneof.name) return NamingUtils.sanitize(oneofName: "OneOf_\(camelCase)") } /// Calculate the full name for the given oneof. public func fullName(oneof: OneofDescriptor) -> String { return fullName(message: oneof.containingType) + "." + relativeName(oneof: oneof) } /// Calculate the relative name for the given entension. /// /// - Precondition: `extensionField` must be FieldDescriptor for an extension. public func relativeName(extensionField field: FieldDescriptor) -> String { precondition(field.isExtension) if field.extensionScope != nil { return NamingUtils.sanitize(messageScopedExtensionName: field.namingBase) } else { let swiftPrefix = typePrefix(forFile: field.file) return swiftPrefix + "Extensions_" + field.namingBase } } /// Calculate the full name for the given extension. /// /// - Precondition: `extensionField` must be FieldDescriptor for an extension. public func fullName(extensionField field: FieldDescriptor) -> String { precondition(field.isExtension) let relativeName = self.relativeName(extensionField: field) guard let extensionScope = field.extensionScope else { return modulePrefix(file: field.file) + relativeName } let extensionScopeSwiftFullName = fullName(message: extensionScope) let relativeNameNoBackticks = NamingUtils.trimBackticks(relativeName) return extensionScopeSwiftFullName + ".Extensions." + relativeNameNoBackticks } public typealias MessageFieldNames = (name: String, prefixed: String, has: String, clear: String) /// Calculate the names to use for the Swift fields on the message. /// /// If `prefixed` is not empty, the name prefixed with that will also be included. /// /// If `includeHasAndClear` is False, the has:, clear: values in the result will /// be the empty string. /// /// - Precondition: `field` must be FieldDescriptor that's isn't for an extension. public func messagePropertyNames(field: FieldDescriptor, prefixed: String, includeHasAndClear: Bool) -> MessageFieldNames { precondition(!field.isExtension) let lowerName = NamingUtils.toLowerCamelCase(field.namingBase) let fieldName = NamingUtils.sanitize(fieldName: lowerName) let prefixedFieldName = prefixed.isEmpty ? "" : NamingUtils.sanitize(fieldName: "\(prefixed)\(lowerName)", basedOn: lowerName) if !includeHasAndClear { return MessageFieldNames(name: fieldName, prefixed: prefixedFieldName, has: "", clear: "") } let upperName = NamingUtils.toUpperCamelCase(field.namingBase) let hasName = NamingUtils.sanitize(fieldName: "has\(upperName)", basedOn: lowerName) let clearName = NamingUtils.sanitize(fieldName: "clear\(upperName)", basedOn: lowerName) return MessageFieldNames(name: fieldName, prefixed: prefixedFieldName, has: hasName, clear: clearName) } public typealias OneofFieldNames = (name: String, prefixed: String) /// Calculate the name to use for the Swift field on the message. public func messagePropertyName(oneof: OneofDescriptor, prefixed: String = "_") -> OneofFieldNames { let lowerName = NamingUtils.toLowerCamelCase(oneof.name) let fieldName = NamingUtils.sanitize(fieldName: lowerName) let prefixedFieldName = NamingUtils.sanitize(fieldName: "\(prefixed)\(lowerName)", basedOn: lowerName) return OneofFieldNames(name: fieldName, prefixed: prefixedFieldName) } public typealias MessageExtensionNames = (value: String, has: String, clear: String) /// Calculate the names to use for the Swift Extension on the extended /// message. /// /// - Precondition: `extensionField` must be FieldDescriptor for an extension. public func messagePropertyNames(extensionField field: FieldDescriptor) -> MessageExtensionNames { precondition(field.isExtension) let fieldBaseName = NamingUtils.toLowerCamelCase(field.namingBase) let fieldName: String let hasName: String let clearName: String if let extensionScope = field.extensionScope { let extensionScopeSwiftFullName = fullName(message: extensionScope) // Don't worry about any sanitize api on these names; since there is a // Message name on the front, it should never hit a reserved word. // // fieldBaseName is the lowerCase name even though we put more on the // front, this seems to help make the field name stick out a little // compared to the message name scoping it on the front. fieldName = NamingUtils.periodsToUnderscores(extensionScopeSwiftFullName + "_" + fieldBaseName) let fieldNameFirstUp = NamingUtils.uppercaseFirstCharacter(fieldName) hasName = "has" + fieldNameFirstUp clearName = "clear" + fieldNameFirstUp } else { // If there was no package and no prefix, fieldBaseName could be a reserved // word, so sanitize. These's also the slim chance the prefix plus the // extension name resulted in a reserved word, so the sanitize is always // needed. let swiftPrefix = typePrefix(forFile: field.file) fieldName = NamingUtils.sanitize(fieldName: swiftPrefix + fieldBaseName) if swiftPrefix.isEmpty { // No prefix, so got back to UpperCamelCasing the extension name, and then // sanitize it like we did for the lower form. let upperCleaned = NamingUtils.sanitize(fieldName: NamingUtils.toUpperCamelCase(field.namingBase), basedOn: fieldBaseName) hasName = "has" + upperCleaned clearName = "clear" + upperCleaned } else { // Since there was a prefix, just add has/clear and ensure the first letter // was capitalized. let fieldNameFirstUp = NamingUtils.uppercaseFirstCharacter(fieldName) hasName = "has" + fieldNameFirstUp clearName = "clear" + fieldNameFirstUp } } return MessageExtensionNames(value: fieldName, has: hasName, clear: clearName) } /// Calculate the prefix to use for this file, it is derived from the /// proto package or swift_prefix file option. public func typePrefix(forFile file: FileDescriptor) -> String { if let result = filePrefixCache[file.name] { return result } let result = NamingUtils.typePrefix(protoPackage: file.package, fileOptions: file.fileOptions) filePrefixCache[file.name] = result return result } /// Internal helper to find the module prefix for a symbol given a file. func modulePrefix(file: FileDescriptor) -> String { guard let prefix = mappings.moduleName(forFile: file) else { return String() } if prefix == targetModule { return String() } return "\(prefix)." } }
mit
3c48313f6e7892ffc9d1fef14b0bb372
39.372493
108
0.690703
4.872061
false
false
false
false
mansoor92/MaksabComponents
MaksabComponents/Classes/Rides/RidesOptionsGridView.swift
1
4695
// // RidesOptionsGridView.swift // Pods // // Created by Incubasys on 02/08/2017. // // import UIKit import StylingBoilerPlate public enum RideCapacity: Int { case fourSitter = 1 case sevenSitter = 2 public func getCount() -> Int { switch self { case .fourSitter: return 4 case .sevenSitter: return 7 } } public func carIcon(rideType: RideType) -> UIImage? { var iconName: String = "" switch rideType { case .budget,.economy: iconName = "sedan-economy" case .business,.luxury: iconName = "sedan-business" default: iconName = "sedan-normal" } iconName = carImageName(forCapacity: self, imgName: iconName) return UIImage.image(named: iconName) } private func carImageName(forCapacity: RideCapacity, imgName: String) -> String { switch forCapacity { case .sevenSitter: return imgName.replacingOccurrences(of: "sedan", with: "suv") default: return imgName } } } public enum PaymentMethod: Int { case cash = 0 case card = 1 case wallet = 2 public func getTitle() -> String { switch self { case .card: return Bundle.localizedStringFor(key: "Credit Card") case .cash: return Bundle.localizedStringFor(key: "Cash") case .wallet: return Bundle.localizedStringFor(key: "Wallet") } } } /* public class PaymentInfo{ public var mehtod: PaymentMethod public var cardId: Int? public init(method: PaymentMethod, cardId: Int? = nil) { self.mehtod = method self.cardId = cardId } } public struct PaymentOptions{ var title: String = "" var id: Int = -1 public init(){} public init(title: String, id: Int){ self.title = title self.id = id } static func createPaymentOptions() -> [PaymentOptions] { let optionCash = PaymentOptions(title: Bundle.localizedStringFor(key: "payment-method-cash"), id: -1) let optionWallet = PaymentOptions(title: Bundle.localizedStringFor(key: "ride-options-wallet"), id: -1) return [optionCash,optionWallet] } } */ public protocol RideOptionsGridViewDelegate: class { func rideOptionsGridViewDidSelectMehram() func rideOptionsGridViewDidSelectPayment() } public class RidesOptionsGridView: UIView, CustomView, NibLoadableView, ToggleViewDelegate{ static public func createInstance(x: CGFloat, y: CGFloat, width:CGFloat) -> RidesOptionsGridView{ let inst = RidesOptionsGridView(frame: CGRect(x: x, y: y, width: width, height: 72)) return inst } let bundle = Bundle(for: RidesOptionsGridView.classForCoder()) @IBOutlet weak public var mehramView: ToggleView! @IBOutlet weak var paymentView: ToggleView! var view: UIView! // var capacity = RideCapacity.fourSitter // var availablePayments = PaymentOptions.createPaymentOptions() var selectedPaymentId: Int = 0 public weak var delegate: RideOptionsGridViewDelegate? override public required init(frame: CGRect) { super.init(frame: frame) view = commonInit(bundle: bundle) configView() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) view = commonInit(bundle: bundle) configView() } func configView() { // // mehramView.selectedStateImg = UIImage.image(named: "mehram-selected") // mehramView.unSelectedStateImg = UIImage.image(named: "mehram") // // mehramView.selectedStateTitle = Bundle.localizedStringFor(key: "ride-options-mehram") // mehramView.unSelectedStateTitle = Bundle.localizedStringFor(key: "ride-options-non-mehram") mehramView.title.numberOfLines = 2 mehramView.state = false mehramView.toggeable = self mehramView.autoToggle = false paymentView.icon.image = UIImage.image(named: "cash-circle") paymentView.title.text = Bundle.localizedStringFor(key: "payment-method-cash") paymentView.toggeable = self paymentView.autoToggle = false } //Payment public func setPayment(title: String, image: UIImage?){ paymentView.icon.image = image paymentView.title.text = title } public func setMehram(title: String, image: UIImage?){ mehramView.icon.image = image mehramView.title.text = title } public func viewToggled(state: Bool, view: ToggleView) { if view == paymentView{ delegate?.rideOptionsGridViewDidSelectPayment() }else { delegate?.rideOptionsGridViewDidSelectMehram() } } }
mit
e459600474dc6fc36ad72935823a49b5
26.296512
111
0.652183
4.165927
false
false
false
false
LeoFangQ/CMSwiftUIKit
Source/CMCycleScrollView/PageControl/CMPageControl.swift
1
8989
// // CMPageControl.swift // YFStore // // Created by Fang on 2016/12/20. // Copyright © 2016年 yfdyf. All rights reserved. // import UIKit /** * Default number of pages for initialization */ fileprivate let kDefaultNumberOfPages = 0 /** * Default current page for initialization */ fileprivate let kDefaultCurrentPage = 0 /** * Default setting for hide for single page feature. For initialization */ fileprivate let kDefaultHideForSinglePage = false /** * Default setting for shouldResizeFromCenter. For initialiation */ fileprivate let kDefaultShouldResizeFromCenter = true /** * Default spacing between dots */ fileprivate let kDefaultSpacingBetweenDots = 8 /** * Default dot size */ fileprivate let kDefaultDotSize = CGSize(width: 8, height: 8) protocol CMPageControlDelegate { func pageControl(_ pageControl:CMPageControl, didSelectPageAt index:Int) } class CMPageControl: UIControl { var delegate:CMPageControlDelegate? fileprivate var _dotViewClass:AnyClass = CMAnimatedDotView.self fileprivate var _dotImage:UIImage? fileprivate var _currentDotImage:UIImage? fileprivate var _dotSize:CGSize? var currentDotSize:CGSize? var dotColor:UIColor? fileprivate var _spacingBetweenDots:Int = kDefaultSpacingBetweenDots fileprivate var _numberOfPages:Int = kDefaultNumberOfPages fileprivate var _currentPage:Int = kDefaultCurrentPage var hidesForSinglePage:Bool = kDefaultHideForSinglePage fileprivate var shouldResizeFromCenter:Bool = kDefaultShouldResizeFromCenter lazy fileprivate var dots: NSMutableArray = { let dots = NSMutableArray() return dots }() var numberOfPages : Int { set{ _numberOfPages = newValue resetDotViews() } get{ return _numberOfPages } } var spacingBetweenDots :Int { set{ _spacingBetweenDots = newValue resetDotViews() } get{ return _spacingBetweenDots } } var currentPage : Int{ set{ if self.numberOfPages == 0 || newValue == _currentPage { _currentPage = newValue return } self.changeActivity(false, index: _currentPage) _currentPage = newValue self.changeActivity(true, index: _currentPage) } get{ return _currentPage } } var dotImage : UIImage? { set{ _dotImage = newValue resetDotViews() self.dotViewClass = nil } get{ return _dotImage } } var currentDotImage : UIImage?{ set{ _currentDotImage = newValue resetDotViews() self.dotViewClass = nil } get{ return _currentDotImage! } } var dotViewClass : AnyClass? { set{ _dotViewClass = newValue! self.dotSize = CGSize.zero resetDotViews() } get{ return _dotViewClass } } var dotSize : CGSize{ set{ _dotSize = newValue } get{ if (self.dotImage != nil) && (_dotSize?.equalTo(CGSize.zero))! { _dotSize = self.dotImage?.size }else if _dotSize == nil { _dotSize = kDefaultDotSize return _dotSize! } return _dotSize! } } init() { super.init(frame: CGRect.zero) } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK:Touch event func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) { for touch: AnyObject in touches { let t:UITouch = touch as! UITouch if t.view != self { let index = self.dots.index(of: t.view!) delegate?.pageControl(self, didSelectPageAt: index) } } } //MARK: Layout /** * Resizes and moves the receiver view so it just encloses its subviews. */ override func sizeToFit() { updateFrame(true) } func sizeForNumberOfPages(pageCount:Int) -> CGSize { return CGSize(width: (self.dotSize.width + CGFloat(self.spacingBetweenDots)) * CGFloat(pageCount) - CGFloat(self.spacingBetweenDots), height: self.dotSize.height) } /** * */ func updateDots() { if numberOfPages == 0 { return } for i in 0..<self.numberOfPages { var dot: UIView? if i < self.dots.count { dot = self.dots[i] as? UIView } else { dot = self.generateDotView() } self.updateDotFrame(dot!, index: i) } self.changeActivity(true, index: self.currentPage) self.hideForSinglePage() } /** * Update frame control to fit current number of pages. It will apply required size if authorize and required. * * @param overrideExistingFrame BOOL to allow frame to be overriden. Meaning the required size will be apply no mattter what. */ func updateFrame(_ overrideExistingFrame: Bool) { let center = self.center let requiredSize = self.sizeForNumberOfPages(pageCount: self.numberOfPages) if overrideExistingFrame || ((self.frame.width < requiredSize.width || self.frame.height < requiredSize.height) && !overrideExistingFrame) { self.frame = CGRect(x: CGFloat(self.frame.minX), y: CGFloat(self.frame.minY), width: CGFloat(requiredSize.width), height: CGFloat(requiredSize.height)) if self.shouldResizeFromCenter { self.center = center } } self.resetDotViews() } /** * Update the frame of a specific dot at a specific index * * @param dot Dot view * @param index Page index of dot */ func updateDotFrame(_ dot: UIView, index: Int) { let x: CGFloat = (self.dotSize.width + CGFloat(self.spacingBetweenDots)) * CGFloat(index) + ((self.frame.width - self.sizeForNumberOfPages(pageCount:numberOfPages).width) / 2) let y: CGFloat = (self.frame.height - self.dotSize.height) / 2 dot.frame = CGRect(x: x, y: y, width: self.dotSize.width, height: self.dotSize.height) } //MARK: - Utils /** * Generate a dot view and add it to the collection * * @return The UIView object representing a dot */ func generateDotView() -> UIView? { var dotView : UIView? if self.dotViewClass != nil { if self.dotViewClass is CMAnimatedDotView.Type{ dotView = CMAnimatedDotView(frame: CGRect(x: 0, y: 0, width: self.dotSize.width, height: self.dotSize.height)) }else{ dotView = UIView(frame: CGRect(x: 0, y: 0, width: self.dotSize.width, height: self.dotSize.height)) } if (dotView! is CMAnimatedDotView) && (self.dotColor != nil) { (dotView as! CMAnimatedDotView).dotColor = self.dotColor } } else { dotView = UIImageView(image: self.dotImage) dotView!.frame = CGRect(x: 0, y: 0, width:self.dotSize.width, height:self.dotSize.height) } if dotView != nil { self.addSubview(dotView!) self.dots.add(dotView!) } dotView!.isUserInteractionEnabled = true return dotView } /** * Change activity state of a dot view. Current/not currrent. * * @param active Active state to apply * @param index Index of dot for state update */ func changeActivity(_ active: Bool,index: Int) { if self.dotViewClass != nil { let abstractDotView = self.dots[index] as? CMAbstractDotView abstractDotView?.changeActivityState(active: active) }else if (self.dotImage != nil) && (self.currentDotImage != nil) { let dotView = (self.dots[index] as! UIImageView) dotView.image! = ((active) ? self.currentDotImage : self.dotImage)! dotView.size = (active) ? self.currentDotSize! : kDefaultDotSize } } func resetDotViews() { for dotView in self.dots { ((dotView as AnyObject) as AnyObject).removeFromSuperview() } self.dots.removeAllObjects() self.updateDots() } func hideForSinglePage() { if self.dots.count == 1 && self.hidesForSinglePage { self.isHidden = true } else { self.isHidden = false } } //MARK: - Getters //MARK: - Setters }
mit
b865a1adabb4a30fb4ce2673c8ab7429
28.080906
183
0.578678
4.685089
false
false
false
false
h-n-y/UICollectionView-TheCompleteGuide
chapter-4/Dimensions/Dimensions/CollectionViewCell.swift
1
3513
import UIKit class CollectionViewCell: UICollectionViewCell { // MARK: Instance var image: UIImage? = nil { didSet { imageView.image = image } } private let imageView: UIImageView var layoutMode: CollectionViewFlowLayoutMode = .AspectFill override init(frame: CGRect) { imageView = CollectionViewCell.newImageView() super.init(frame: frame) let dimensionSize: Int = CollectionViewFlowLayout.MAX_ITEM_DIMENSION contentView.addSubview(imageView) imageView.centerInContainer() imageView.constrainWidth(CGFloat(dimensionSize)) imageView.constrainHeight(CGFloat(dimensionSize)) backgroundColor = UIColor.blackColor() } required init?(coder aDecoder: NSCoder) { imageView = CollectionViewCell.newImageView() super.init(coder: aDecoder) contentView.addSubview(imageView) imageView.centerInContainer() backgroundColor = UIColor.blackColor() } override func prepareForReuse() { super.prepareForReuse() image = nil } override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes) { super.applyLayoutAttributes(layoutAttributes) guard let attributes = layoutAttributes as? CollectionViewLayoutAttributes else { return } layoutMode = attributes.layoutMode setImageViewFrame(animate: true) } func setImageViewFrame(animate animate: Bool) { // Start out with the detail image size of the maximum size var imageViewSize: CGSize = bounds.size if layoutMode == .AspectFit, let image = imageView.image { // Determine the size and aspect ratio for the model's image let photoSize: CGSize = image.size let aspectRatio: CGFloat = photoSize.width / photoSize.height if aspectRatio < 1 { // The photo is taller than it is wide, so constrain the width imageViewSize = CGSize(width: self.bounds.width * aspectRatio, height: self.bounds.height) } else if aspectRatio > 1 { // The photo is wider than it is tall, so constrain the height imageViewSize = CGSize(width: self.bounds.width, height: self.bounds.height / aspectRatio) } } // Set the size of the imageView //imageView.bounds = CGRect(x: 0, y: 0, width: imageViewSize.width, height: imageViewSize.height) if let heightConstraint = imageView.constraintWithIdentifier("height"), widthConstraint = imageView.constraintWithIdentifier("width") { // Animate change in constraints. // see: http://stackoverflow.com/questions/25649926/trying-to-animate-a-constraint-in-swift heightConstraint.constant = imageViewSize.height widthConstraint.constant = imageViewSize.width if animate { UIView.animateWithDuration(0.5, animations: { self.layoutIfNeeded() }) } } } // MARK: Class private class func newImageView() -> UIImageView { let imageView = UIImageView(frame: CGRectZero) imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true return imageView } }
mit
89d8706608456a3fb8510c9c2d720d20
34.484848
143
0.61799
5.749591
false
false
false
false
wangshengjia/LeeGo
LeeGoTests/ConvenienceSpec.swift
1
5408
// // ConvenienceSpec.swift // LeeGo // // Created by Victor WANG on 20/02/16. // Copyright © 2016 CocoaPods. All rights reserved. // import XCTest import Foundation import UIKit import Quick import Nimble @testable import LeeGo class ConvenienceSpec: QuickSpec { private enum JSONKey: JSONKeyType { case targetClass } override func spec() { describe("Convenience methods") { // Given let path = Bundle(for: type(of: self)).path(forResource: "brick", ofType: "json")! let json = (try? JSONSerialization.jsonObject(with: NSData(contentsOfFile: path)! as Data, options: JSONSerialization.ReadingOptions(rawValue: 0)) as! JSONDictionary)! context("when parse value from JSON like structure") { it("should get value with a String key correctly.") { // When do { let _: [JSONDictionary] = try json.parse("bricks") } catch { fail("should not fail") } // Then expect{ try json.parse("bricks1") }.to(throwError()) expect{ let _: String = try json.parse("bricks") return "" }.to(throwError()) let targetClass: String = json.parse(JSONKey.targetClass, "") expect(targetClass) == "UIView" let width: CGFloat = json.parse("width1", 10.0) expect(width) == 10.0 let name: String = json.parse("name", "unknown") expect(name) == "article" } } let attributes: [Attributes] = [ [NSAttributedStringKey.font.rawValue: UIFont(name: "Helvetica", size: 16)!, NSAttributedStringKey.foregroundColor.rawValue: UIColor.red], [kCustomAttributeDefaultText: "Test" as AnyObject, NSAttributedStringKey.font.rawValue: UIFont(name: "Avenir", size: 20)!, NSAttributedStringKey.foregroundColor.rawValue: UIColor.darkText], [NSAttributedStringKey.font.rawValue: UIFont(name: "Avenir", size: 16)!, NSAttributedStringKey.foregroundColor.rawValue: UIColor.lightGray] ] it("should set attributed string correctly") { // Given let label = UILabel() let textField = UITextField() let textView = UITextView() let button = UIButton() // When label.lg_setAttributedString(with: attributes) textField.lg_setAttributedString(with: attributes) textView.lg_setAttributedString(with: attributes) button.lg_setAttributedButtonTitle(with: attributes, state: .normal) // Then expect(label.attributedText).notTo(beNil()) expect(textField.attributedText).notTo(beNil()) expect(textView.attributedText).notTo(beNil()) var range = NSRange(location: 1, length: 1) expect(NSDictionary(dictionary: (label.attributedText?.attributes(at: 0, effectiveRange: &range))!)) == attributes[1] as NSDictionary for (attrKey, attrValue) in attributes[1] { let containsAttr = NSDictionary(dictionary: (textField.attributedText?.attributes(at: 0, effectiveRange: &range))!).contains(where: { (key, value) -> Bool in return attrKey == key as! String && (attrValue as AnyObject).isEqual(value) }) expect(containsAttr) == true } expect(NSDictionary(dictionary: (textView.attributedText?.attributes(at: 0, effectiveRange: &range))!)) == attributes[1] as NSDictionary expect(NSDictionary(dictionary: (button.attributedTitle(for: .normal)?.attributes(at: 0, effectiveRange: &range))!)) == attributes[1] as NSDictionary } it("should update attributed string correctly") { // Given let label = UILabel() let textField = UITextField() let textView = UITextView() label.lg_setAttributedString(with: attributes) textField.lg_setAttributedString(with: attributes) textView.lg_setAttributedString(with: attributes) // When label.attributedText = label.lg_updatedAttributedString(with: ["First", "Second", "Third"]) textField.attributedText = textField.lg_updatedAttributedString(with: ["First1", "Second2", "Third3"]) textView.attributedText = textView.lg_updatedAttributedString(with: ["FirstA", "SecondB", "ThirdC"]) // Then expect(label.attributedText?.string) == "FirstSecondThird" expect(textField.attributedText?.string) == "First1Second2Third3" expect(textView.attributedText?.string) == "FirstASecondBThirdC" } it("should formatted json to string correctly.") { // When let jsonStr = formattedStringFromJSON(json) // Then expect(jsonStr).notTo(beNil()) } } } }
mit
35fd5b96e4aff0ff257c53186b09163c
41.912698
205
0.55909
5.306183
false
false
false
false
mozilla-mobile/firefox-ios
Sync/CleartextPayloadJSON.swift
2
1629
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Shared import SwiftyJSON open class BasePayloadJSON { let json: JSON required public init(_ jsonString: String) { self.json = JSON(parseJSON: jsonString) } public init(_ json: JSON) { self.json = json } // Override me. public func isValid() -> Bool { return self.json.type != .unknown && self.json.error == nil } subscript(key: String) -> JSON { return json[key] } } /** * http://docs.services.mozilla.com/sync/objectformats.html * "In addition to these custom collection object structures, the * Encrypted DataObject adds fields like id and deleted." */ open class CleartextPayloadJSON: BasePayloadJSON { required public override init(_ json: JSON) { super.init(json) } required public init(_ jsonString: String) { super.init(jsonString) } // Override me. override open func isValid() -> Bool { return super.isValid() && self["id"].isString() } open var id: String { return self["id"].string! } open var deleted: Bool { let d = self["deleted"] if let bool = d.bool { return bool } else { return false } } // Override me. // Doesn't check id. Should it? open func equalPayloads (_ obj: CleartextPayloadJSON) -> Bool { return self.deleted == obj.deleted } }
mpl-2.0
d9b7b6f7a672b7151a2b218e4bbb7f50
24.061538
70
0.61019
4.198454
false
false
false
false
somegeekintn/SimDirs
SimDirs/Views/SourceItem Views/SourceItemGroup.swift
1
1880
// // SourceItemGroup.swift // SimDirs // // Created by Casey Fleser on 6/20/22. // import SwiftUI struct SourceItemGroup<Item: SourceItem>: View { @StateObject var item : Item @Binding var selection : UUID? var body: some View { HStack(spacing: 0) { let button = Button(action: { let optionActive = NSApplication.shared.currentEvent?.modifierFlags.contains(.option) == true withAnimation(.easeInOut(duration: 0.2)) { item.toggleExpanded(deep: optionActive) } }, label: { Image(systemName: "chevron.right") .padding(.horizontal, 2.0) .contentShape(Rectangle()) .rotationEffect(.degrees(item.isExpanded ? 90.0 : 0.0)) }) .buttonStyle(.plain) if item.visibleChildren.count == 0 { button.hidden() } else { button } SourceItemLink(selection: $selection, item: item) } if item.isExpanded { ForEach(item.visibleChildren) { childItem in SourceItemGroup<Item.Child>(item: childItem, selection: $selection) } .padding(.leading, 12.0) } } } struct SourceItemGroup_Previews: PreviewProvider { @State static var selection : UUID? static var state = SourceState(model: SimModel()) static var sampleItem = state.deviceStyleItems()[0] static var previews: some View { List { SourceItemGroup(item: sampleItem, selection: $selection) SourceItemGroup(item: sampleItem, selection: $selection) SourceItemGroup(item: sampleItem, selection: $selection) } } }
mit
ab6306c58eb67fb205e601ba3cac8334
29.819672
109
0.535106
4.870466
false
false
false
false
DeveloperLx/LxProjectTemplate
LxProjectTemplateDemo/Pods/PromiseKit/Categories/AssetsLibrary/ALAssetsLibrary+Promise.swift
3
1712
import AssetsLibrary import Foundation.NSData #if !COCOAPODS import PromiseKit #endif import UIKit.UIViewController /** To import this `UIViewController` extension: use_frameworks! pod "PromiseKit/AssetsLibrary" And then in your sources: import PromiseKit */ extension UIViewController { /** @return A promise that presents the provided UIImagePickerController and fulfills with the user selected media’s `NSData`. */ public func promiseViewController(vc: UIImagePickerController, animated: Bool = false, completion: (() -> Void)? = nil) -> Promise<NSData> { let proxy = UIImagePickerControllerProxy() vc.delegate = proxy presentViewController(vc, animated: animated, completion: completion) return proxy.promise.then(on: zalgo) { info -> Promise<NSData> in let url = info[UIImagePickerControllerReferenceURL] as! NSURL return Promise { fulfill, reject in ALAssetsLibrary().assetForURL(url, resultBlock: { asset in let N = Int(asset.defaultRepresentation().size()) let bytes = UnsafeMutablePointer<UInt8>.alloc(N) var error: NSError? asset.defaultRepresentation().getBytes(bytes, fromOffset: 0, length: N, error: &error) if let error = error { reject(error) } else { fulfill(NSData(bytesNoCopy: bytes, length: N)) } }, failureBlock: { reject($0) } ) } }.always { self.dismissViewControllerAnimated(animated, completion: nil) } } }
mit
1c21d58c6600fd0347e25cbf7fededc3
33.2
144
0.602339
5.310559
false
false
false
false
tavultesoft/keymanweb
ios/engine/KMEI/KeymanEngine/Classes/Resource Management/Migrations.swift
1
29684
// // Migrations.swift // KeymanEngine // // Created by Gabriel Wong on 2017-12-08. // Copyright © 2017 SIL International. All rights reserved. // import Foundation import Sentry private enum MigrationLevel { static let initial = 0 static let migratedUserDefaultsToStructs = 10 static let migratedForKMP = 20 } struct VersionResourceSet { var version: Version var resources: [AnyLanguageResourceFullID] // but how to handle deprecation? init(version: Version, resources: [AnyLanguageResourceFullID]) { self.version = version self.resources = resources } } public enum Migrations { static let resourceHistory: [VersionResourceSet] = { let font = Font(family: "LatinWeb", source: ["DejaVuSans.ttf"], size: nil) let european = FullKeyboardID(keyboardID: "european", languageID: "en") // Default keyboard in version 10.0 (and likely before) let european2 = FullKeyboardID(keyboardID: "european2", languageID: "en") let sil_euro_latin = FullKeyboardID(keyboardID: "sil_euro_latin", languageID: "en") let nrc_en_mtnt = FullLexicalModelID(lexicalModelID: "nrc.en.mtnt", languageID: "en") // Unknown transition point: european // Before v11: european2 // Before v12: sil_euro_latin 1.8.1 // At v12: sil_euro_latin 1.8.1 + nrc.en.mtnt (lex model) var timeline: [VersionResourceSet] = [] let legacy_resources = VersionResourceSet(version: Version.fallback, resources: [european]) let v10_resources = VersionResourceSet(version: Version("10.0")!, resources: [european2]) let v11_resources = VersionResourceSet(version: Version("11.0")!, resources: [sil_euro_latin]) let v12_resources = VersionResourceSet(version: Version("12.0")!, resources: [sil_euro_latin, nrc_en_mtnt]) timeline.append(legacy_resources) timeline.append(v10_resources) timeline.append(v11_resources) timeline.append(v12_resources) return timeline }() static func migrate(storage: Storage) { if storage.userDefaults.migrationLevel < MigrationLevel.migratedUserDefaultsToStructs { migrateUserDefaultsToStructs(storage: storage) storage.userDefaults.migrationLevel = MigrationLevel.migratedUserDefaultsToStructs } else { SentryManager.breadcrumbAndLog("UserDefaults migration to structs already performed. Skipping.", category: "migration") } if storage.userDefaults.migrationLevel < MigrationLevel.migratedForKMP { migrateForKMP(storage: storage) storage.userDefaults.migrationLevel = MigrationLevel.migratedForKMP } else { SentryManager.breadcrumbAndLog("KMP directory migration already performed. Skipping.", category: "migration") } // Version-based migrations if let version = engineVersion { if version < Version.fileBrowserImplemented { do { try migrateDocumentsFromPreBrowser() } catch { SentryManager.captureAndLog(error, message: "Could not migrate Documents directory contents: \(error)") } } else { SentryManager.breadcrumbAndLog("Documents directory structure compatible with \(Version.fileBrowserImplemented)") } if version < Version.packageBasedFileReorg { do { try migrateCloudResourcesToKMPFormat() } catch { let event = Sentry.Event(level: .error) event.message = SentryMessage(formatted: "Could not migrate pre-existing resources to KMP-style file organization") event.extra = [ "priorVersion": version ] SentryManager.captureAndLog(event) } } else { SentryManager.breadcrumbAndLog("Resource directories already migrated to package-based format; kmp.jsons already exist.", category: "migration") } } storage.userDefaults.synchronize() } static func detectLegacyKeymanVersion() -> [Version] { // While the 'key' used to track version info existed before v12, it was unused until then. SentryManager.breadcrumbAndLog("Prior engine version unknown; attepting to auto-detect.", category: "migration") // Detect possible version matches. let userResources = Storage.active.userDefaults.userResources ?? [] // If there are no pre-existing resources and we need to detect a version, this is a fresh install. if userResources.count == 0 { return [Version.freshInstall] } let possibleMatches: [Version] = resourceHistory.compactMap { set in if set.version < Version("12.0")! { // Are all of the version's default resources present? let match = set.resources.allSatisfy { res in return userResources.contains(where: { res2 in return res.id == res2.id && res.languageID == res2.languageID }) } // If so, report that we can match this version. if match { return set.version } else { // No match; don't consider this version. return nil } } else { // If it were at least version 12.0, the version would be specified and we wouldn't be guessing. return nil } } return possibleMatches } // The only part actually visible outside of KeymanEngine. public internal(set) static var engineVersion: Version? { get { return Storage.active.userDefaults.lastEngineVersion } set(value) { Storage.active.userDefaults.lastEngineVersion = value! } } static func updateResources(storage: Storage) { var lastVersion = engineVersion // Will always seek to update default resources on version upgrades, // even if only due to the build component of the version. // // This may make intentional downgrading of our default resources tedious, // as there's (currently) no way to detect if a user intentionally did so before // the app upgrade. if lastVersion != nil, lastVersion! > Version.currentTagged { // We've just been downgraded; no need to modify resources. // If it's a downgrade, it's near-certainly a testing environment return } // Legacy check - what was the old version? If it's older than 12.0, // we don't actually know. if (lastVersion ?? Version.fallback) < Version.firstTracked { let possibleMatches: [Version] = detectLegacyKeymanVersion() // Now we have a list of possible original versions of the Keyman app. if possibleMatches.count > 1 { // If more than one case matches, the user never cleaned out deprecated keyboards. // They're probably fine with it, so the easiest solution is to give them one more // and make it the updated default. // No de-installs here; just additional install later in the method. } else if possibleMatches.count == 1 { // Simplest case - remove old default material so that we can insert the updated // resources in a later part of the method. lastVersion = possibleMatches[0] } else { // if possibleMatches.count == 0 // The user has previously decided that they don't want our defaults and has already // significantly customized their resource selection. No need to 'update' anything. return } } var userKeyboards = Storage.active.userDefaults.userKeyboards ?? [] var userModels = Storage.active.userDefaults.userLexicalModels ?? [] var hasVersionDefaults = true var oldDefaultKbd: InstallableKeyboard? = nil var oldDefaultLex: InstallableLexicalModel? = nil // Only assigned a non-nil value if the old default's ID matches the current default's. // Used for version comparisons to ensure we don't unnecessarily downgrade. var currentDefaultKbdVersion: Version? = nil var currentDefaultLexVersion: Version? = nil if lastVersion != nil && lastVersion != Version.freshInstall { // Time to check on the old version's default resources. // The user may have updated them, and possibly even beyond the currently-packaged version. // First, find the most recent version with a listed history. let possibleHistories: [VersionResourceSet] = resourceHistory.compactMap { set in if set.version <= lastVersion! { return set } else { return nil } } // Assumes the history definition is in ascending Version order; takes the last in the list // as the correct "old version" resource set. This allows covering gaps, // such as for a 'plain' 13.0 prior install. let resources = possibleHistories[possibleHistories.count-1].resources resources.forEach { res in if let kbd = res as? FullKeyboardID { // Does not remove the deprecated keyboard's files - just the registration. if let match = userKeyboards.first(where: { $0.fullID == kbd }) { if match.fullID == Defaults.keyboard.fullID { currentDefaultKbdVersion = Version(match.version) } oldDefaultKbd = match } else { hasVersionDefaults = false } } else if let lex = res as? FullLexicalModelID { // Parallels the issue with deprecated files for keyboards. if let match = userModels.first(where: { $0.fullID == lex }) { if match.fullID == Defaults.lexicalModel.fullID { currentDefaultLexVersion = Version(match.version) } oldDefaultLex = match } else { hasVersionDefaults = false } } // else Not yet implemented } // The user has customized their default resources; Keyman will refrain from // changing the user's customizations. if !hasVersionDefaults { return } } // Now to install the new version's resources. let defaultsNeedBackup = (lastVersion ?? Version.fallback) < Version.defaultsNeedBackup // First the keyboard. If it needs an update: if currentDefaultKbdVersion ?? Version("0.0")! <= Version(Defaults.keyboard.version)! || defaultsNeedBackup { // Remove old installation. userKeyboards.removeAll(where: { $0.fullID == oldDefaultKbd?.fullID }) userKeyboards = [Defaults.keyboard] + userKeyboards // Make sure the default goes in the first slot! Storage.active.userDefaults.userKeyboards = userKeyboards do { try Storage.active.installDefaultKeyboard(from: Resources.bundle) } catch { SentryManager.captureAndLog(error, message: "Failed to copy default keyboard from bundle: \(error)") } } if currentDefaultLexVersion ?? Version("0.0")! < Version(Defaults.lexicalModel.version)! || defaultsNeedBackup { // Remove old installation userModels.removeAll(where: { $0.fullID == oldDefaultLex?.fullID} ) userModels = [Defaults.lexicalModel] + userModels Storage.active.userDefaults.userLexicalModels = userModels do { try Storage.active.installDefaultLexicalModel(from: Resources.bundle) } catch { SentryManager.captureAndLog(error, message: "Failed to copy default lexical model from bundle: \(error)") } } // Store the version we just upgraded to. storage.userDefaults.lastEngineVersion = Version.currentTagged } static func migrateUserDefaultsToStructs(storage: Storage) { guard let userKeyboardObject = storage.userDefaults.object(forKey: Key.userKeyboardsList), let currentKeyboardObject = storage.userDefaults.object(forKey: Key.userCurrentKeyboard) else { SentryManager.breadcrumbAndLog("User keyboard list or current keyboard missing. Skipping migration.", category: "migration") return } guard let oldUserKeyboards = userKeyboardObject as? [[String: String]], let oldCurrentKeyboard = currentKeyboardObject as? [String: String] else { SentryManager.captureAndLog("User keyboard list or current keyboard has an unexpected type") return } let userKeyboards = oldUserKeyboards.compactMap { installableKeyboard(from: $0) } let currentKeyboardID = fullKeyboardID(from: oldCurrentKeyboard) storage.userDefaults.userKeyboards = userKeyboards if userKeyboards.contains(where: { $0.fullID == currentKeyboardID }) { storage.userDefaults.currentKeyboardID = currentKeyboardID } else { storage.userDefaults.currentKeyboardID = nil } } private static func installableKeyboard(from kbDict: [String: String]) -> InstallableKeyboard? { SentryManager.breadcrumbAndLog("Migrating keyboard dictionary for '\(String(describing: kbDict["kbId"]))", category: "migration", sentryLevel: .debug) guard let id = kbDict["kbId"], let name = kbDict["kbName"], let languageID = kbDict["langId"], let languageName = kbDict["langName"], let version = kbDict["version"] else { SentryManager.captureAndLog("Missing required fields in keyboard dictionary: \(kbDict)") return nil } let rtl = kbDict["rtl"] == "Y" let isCustom = kbDict["CustomKeyboard"] == "Y" let displayFont = font(from: kbDict["font"]) let oskFont = font(from: kbDict["oskFont"]) let kb = InstallableKeyboard(id: id, name: name, languageID: languageID, languageName: languageName, version: version, isRTL: rtl, font: displayFont, oskFont: oskFont, isCustom: isCustom) SentryManager.breadcrumbAndLog("Migrated keyboard dictionary to keyboard \(kb.id)") log.debug(kb) return kb } private static func fullKeyboardID(from kbDict: [String: String]) -> FullKeyboardID? { guard let keyboardID = kbDict["kbId"], let languageID = kbDict["langId"] else { let event = Sentry.Event(level: .error) event.message = SentryMessage(formatted: "Missing required fields in keyboard dictionary for FullKeyboardID") event.extra = ["kbId": kbDict["kbId"] ?? "nil", "langId": kbDict["langId"] ?? "nil"] SentryManager.captureAndLog(event) return nil } let id = FullKeyboardID(keyboardID: keyboardID, languageID: languageID) SentryManager.breadcrumbAndLog("Migrated keyboard dictionary to \(id)", category: "migration") return id } private static func font(from jsonString: String?) -> Font? { guard let jsonString = jsonString else { return nil } guard let data = jsonString.data(using: .utf8) else { log.error("Failed to encode string: \(jsonString)") return nil } guard let fontDict = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else { log.error("Error parsing String as JSON: \(jsonString)") return nil } guard let family = fontDict["family"] as? String else { log.error("Missing 'family' String: \(fontDict)") return nil } let files: [String] if let filesString = fontDict["files"] as? String { files = [filesString] } else if let filesArray = fontDict["files"] as? [String] { files = filesArray } else { log.error("Missing 'files': \(fontDict)") return nil } return Font(family: family, source: files) } // OLD legacy migration. static func migrateForKMP(storage: Storage) { let languageDir = storage.baseDir.appendingPathComponent("languages") let fontDir = storage.baseDir.appendingPathComponent("fonts") SentryManager.breadcrumbAndLog("Migrating from base directory: \(storage.baseDir)", category: "migration") guard var userKeyboards = storage.userDefaults.userKeyboards else { SentryManager.breadcrumbAndLog("No user keyboards to migrate", category: "migration") return } var urlsForKeyboard: [String: Set<URL>] = [:] for i in userKeyboards.indices { let keyboard = userKeyboards[i] guard let version = latestKeyboardFileVersion(withID: keyboard.id, dirPath: languageDir.path) else { log.warning("Could not find JS file for keyboard \(keyboard.id) in \(languageDir.path)") continue } var urls = urlsForKeyboard[keyboard.id] ?? Set() urls.insert(languageDir.appendingPathComponent("\(keyboard.id)-\(version.plainString).js")) let fontFiles = (keyboard.font?.source ?? []) + (keyboard.oskFont?.source ?? []) for file in fontFiles { guard file.hasFontExtension else { log.info("Skipping copy of \(file) for keyboard \(keyboard.id) since it is not a font file.") continue } let url = fontDir.appendingPathComponent(file) guard FileManager.default.fileExists(atPath: url.path) else { log.warning("Font file \(url) for keyboard \(keyboard.id) does not exist") continue } urls.insert(url) } urlsForKeyboard[keyboard.id] = urls userKeyboards[i].version = version.plainString } var successfulKeyboards: [String] = [] // Copy files for (keyboardID, urls) in urlsForKeyboard { let keyboardDir = storage.legacyKeyboardDir(forID: keyboardID) do { try FileManager.default.createDirectory(at: keyboardDir, withIntermediateDirectories: true, attributes: nil) } catch { log.error("Failed to create keyboard directory at \(keyboardDir)") continue } var successful = true for srcURL in urls { let dstURL = keyboardDir.appendingPathComponent(srcURL.lastPathComponent) do { try FileManager.default.copyItem(at: srcURL, to: dstURL) } catch { log.error("Failed to copy from \(srcURL) to \(dstURL) for keyboard \(keyboardID)") successful = false } } if successful { successfulKeyboards.append(keyboardID) log.info("Succesfully copied keyboard files for keyboard \(keyboardID)") } } // Remove keyboards that were not copied successfully let filteredUserKeyboards = userKeyboards.filter { successfulKeyboards.contains($0.id) } storage.userDefaults.userKeyboards = filteredUserKeyboards // TODO: Remove old directory } private static func latestKeyboardFileVersion(withID keyboardID: String, dirPath: String) -> Version? { guard let dirContents = try? FileManager.default.contentsOfDirectory(atPath: dirPath) else { return nil } var latestVersion: Version? for filename in dirContents where filename.hasPrefix("\(keyboardID)-") && filename.hasJavaScriptExtension { let dashRange = filename.range(of: "-", options: .backwards)! let extensionRange = filename.range(of: ".js", options: .backwards)! guard let version = Version(String(filename[dashRange.upperBound..<extensionRange.lowerBound])) else { continue } if let previousMax = latestVersion { latestVersion = max(version, previousMax) } else { latestVersion = version } } return latestVersion } static func migrateDocumentsFromPreBrowser() throws { SentryManager.breadcrumbAndLog("Cleaning Documents folder due to 12.0 installation artifacts", category: "migration") // Actually DO it. let documentFolderURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] // The String-based version will break, at least in Simulator. let contents = try FileManager.default.contentsOfDirectory(at: documentFolderURL, includingPropertiesForKeys: nil, options: []) try contents.forEach { fileURL in // 12.0: extracts .kmp files by first putting them in Documents and giving // them this suffix. if fileURL.lastPathComponent.hasSuffix(".kmp.zip") { // Renames the .kmp.zip files back to their original .kmp filename. let destFile = fileURL.lastPathComponent.replacingOccurrences(of: ".kmp.zip", with: ".kmp") let destURL = fileURL.deletingLastPathComponent().appendingPathComponent(destFile) SentryManager.breadcrumbAndLog("\(fileURL) -> \(destURL)", category: "migration", sentryLevel: .debug) try FileManager.default.moveItem(at: fileURL, to: destURL) } else if fileURL.lastPathComponent == "temp" { // Removes the 'temp' installation directory; that shouldn't be visible to users. SentryManager.breadcrumbAndLog("Deleting directory: \(fileURL)", category: "migration", sentryLevel: .debug) try FileManager.default.removeItem(at: fileURL) } else if fileURL.lastPathComponent.hasSuffix(".kmp") { // Do nothing; this file is fine. } else { SentryManager.breadcrumbAndLog("Unexpected file found in documents folder during upgrade: \(fileURL)", category: "migration") } } } static func migrateCloudResourcesToKMPFormat() throws { let userDefaults = Storage.active.userDefaults if var userKeyboards = userDefaults.userKeyboards { userKeyboards = migrateToKMPFormat(userKeyboards) userDefaults.userKeyboards = userKeyboards } if var userLexicalModels = userDefaults.userLexicalModels { userLexicalModels = migrateToKMPFormat(userLexicalModels) userDefaults.userLexicalModels = userLexicalModels } } static func migrateToKMPFormat<Resource: KMPInitializableLanguageResource>( _ resources: [Resource]) -> [Resource] where Resource.Package: TypedKeymanPackage<Resource> { // Step 1 - drop version numbers from all filenames. KMP installations don't include them, and // the version numbered filenames will actually interfere with migration. resources.forEach { resource in let srcLocation = Storage.active.legacyResourceURL(for: resource)! let dstLocation = Storage.active.resourceURL(for: resource)! do { if FileManager.default.fileExists(atPath: srcLocation.path) { try FileManager.default.moveItem(at: srcLocation, to: dstLocation) } } catch { let event = Sentry.Event(level: .error) event.message = SentryMessage(formatted: "Could not remove version number from filename") event.extra = ["package" : resource.packageID ?? "<no package>", "id": resource.id, "location": srcLocation ] SentryManager.captureAndLog(event) } } // Step 2 - analyze all locally-cached KMPs for possible resource sources. var allLocalPackages: [(KeymanPackage, URL)] = [] do { let cachedKMPsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let files = try FileManager.default.contentsOfDirectory(atPath: cachedKMPsDirectory.path) let kmpFiles = files.filter { $0.suffix(4).lowercased() == ".kmp" } allLocalPackages = kmpFiles.compactMap { file in let filePath = cachedKMPsDirectory.appendingPathComponent(file) do { let tuple = try (ResourceFileManager.shared.prepareKMPInstall(from: filePath), filePath) return tuple } catch { SentryManager.captureAndLog("Could not load kmp.info for local package during migration: \(file)") return nil } } } catch { SentryManager.captureAndLog("Could not check contents of Documents directory for resource-migration assist") } // Filters out Packages that don't contain the matching resource type. let localPackages: [(Resource.Package, URL)] = allLocalPackages.compactMap { tuple in if let package = tuple.0 as? Resource.Package { return (package, tuple.1) } else { return nil } } // Step 3 - determine which resources were installed from our locally-available KMPs, // then migrate by reinstalling the KMP. var matched: [Resource] = [] localPackages.forEach { (package, kmpFile) in let packageMatches: [Resource] = resources.compactMap { resource in if let possibleMatch = package.findResource(withID: resource.typedFullID) { if possibleMatch.version == resource.version { return resource } } // else, for either if-condition. return nil } // All resources within packageMatches were sourced from the current package. // Time to set migrate these. Overwrites any obstructing files with the // the decompressed KMP's contents. do { // We've already parsed the metadata, but now we need to have the files ready for install. try packageMatches.forEach { resource in try ResourceFileManager.shared.install(resourceWithID: resource.typedFullID, from: package) matched.append(package.findResource(withID: resource.typedFullID)!) } } catch { SentryManager.captureAndLog(error, message: "Could not install resource from locally-cached package: \(String(describing: error))") } } // Step 4 - anything unmatched is a cloud resource. Autogenerate a kmp.json for it // so that it becomes its own package. (Is already installed in own subdir.) let unmatched: [Resource] = resources.compactMap { resource in // Return the resource only if it isn't in the 'matched' array, return matched.contains(where: { $0.typedFullID == resource.typedFullID }) ? nil : resource } var wrapperPackages: [Resource.Package] = [] // The following block loads any already-migrated local resources; there's a chance we may // need to merge new resources into an autogenerated kmp.json. (Cloud JS workaround - data // loss prevention) // // In a manner, this re-migrates them harmlessly. Safe to eliminate the block below // once Cloud JS downloads are removed in favor of KMP downloads, at which point this // method will only ever be called a single time. wrapperPackages = ResourceFileManager.shared.installedPackages.compactMap { package in // We only consider appending resources to existing kmp.jsons if the kmp.jsons were // produced during resource migration. We don't alter Developer-compiled kmp.jsons. if package.metadata.isAutogeneratedWrapper { return package as? Resource.Package // also ensures it's the right package type. } else { return nil } } for resource in unmatched { // Did we already build a matching wrapper package? let packageMatches: [Resource.Package] = wrapperPackages.compactMap { package in let metadata: Resource.Metadata? = package.findMetadataMatchFor(resource: resource, ignoreLanguage: true, ignoreVersion: true) return (metadata != nil) ? package : nil } if packageMatches.count > 0 { // We did! Add this resource to the existing metadata object. var resourceMetadata: Resource.Metadata = packageMatches[0].findMetadataMatchFor(resource: resource, ignoreLanguage: true, ignoreVersion: true)! // Ensure we don't accidentally make a duplicate entry. // Of particular interest while the Cloud-download stop-gap measure is in place. if !resourceMetadata.languages.contains(where: { return $0.languageId == resource.languageID }) { resourceMetadata.languages.append(KMPLanguage(from: resource)!) // Update the installable resources listing! packageMatches[0].setInstallableResourceSets(for: [resourceMetadata]) } } else { // Time for a new wrapper package! let location = Storage.active.resourceDir(for: resource)! let migrationPackage = KeymanPackage.forMigration(of: resource, at: location)! wrapperPackages.append(migrationPackage as! Resource.Package) } } // Step 5 - write out the finalized metadata for the new 'wrapper' Packages for package in wrapperPackages { let folderURL = Storage.active.packageDir(for: package) let metadataFile = folderURL!.appendingPathComponent("kmp.json") let encoder = JSONEncoder() do { let metadataJSON = try encoder.encode(package.metadata) FileManager.default.createFile(atPath: metadataFile.path, contents: metadataJSON, attributes: .none) // write to location. } catch { let event = Sentry.Event(level: .error) event.message = SentryMessage(formatted: "Could not generate kmp.json for legacy resource!") event.extra = [ "resourceId": package.id, "type": package.resourceType()] SentryManager.captureAndLog(event) } } // Step 6 - return the Resources that map to the original argument. // Each wrapper package contains only a single resource. .installables[0] returns all // LanguageResource pairings for that script resource. let wrappedResources: [Resource] = wrapperPackages.flatMap { package in // Just in case the 'wrapping' process goes wrong, this will prevent a fatal error. package.installables.count > 0 ? package.installables[0] : [] } let mappedResources: [Resource] = wrappedResources.compactMap { resource in if resources.contains(where: { $0.typedFullID == resource.typedFullID}) { return resource } else { return nil } } return matched + mappedResources } internal static func resourceHasPackageMetadata<Resource: LanguageResource>(_ resource: Resource) -> Bool { var resourceDir = Storage.active.resourceDir(for: resource)! resourceDir.appendPathComponent("kmp.json") return FileManager.default.fileExists(atPath: resourceDir.path) } }
apache-2.0
b474623e0711a7eefc5e1f4c8e2d7ba7
41.525788
154
0.674157
4.765291
false
false
false
false
jpvasquez/Eureka
Source/Core/Form.swift
1
16065
// Form.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// The delegate of the Eureka form. public protocol FormDelegate : class { func sectionsHaveBeenAdded(_ sections: [Section], at: IndexSet) func sectionsHaveBeenRemoved(_ sections: [Section], at: IndexSet) func sectionsHaveBeenReplaced(oldSections: [Section], newSections: [Section], at: IndexSet) func rowsHaveBeenAdded(_ rows: [BaseRow], at: [IndexPath]) func rowsHaveBeenRemoved(_ rows: [BaseRow], at: [IndexPath]) func rowsHaveBeenReplaced(oldRows: [BaseRow], newRows: [BaseRow], at: [IndexPath]) func valueHasBeenChanged(for row: BaseRow, oldValue: Any?, newValue: Any?) } // MARK: Form /// The class representing the Eureka form. public final class Form { /// Defines the default options of the navigation accessory view. public static var defaultNavigationOptions = RowNavigationOptions.Enabled.union(.SkipCanNotBecomeFirstResponderRow) /// The default options that define when an inline row will be hidden. Applies only when `inlineRowHideOptions` is nil. public static var defaultInlineRowHideOptions = InlineRowHideOptions.FirstResponderChanges.union(.AnotherInlineRowIsShown) /// The options that define when an inline row will be hidden. If nil then `defaultInlineRowHideOptions` are used public var inlineRowHideOptions: InlineRowHideOptions? /// Which `UIReturnKeyType` should be used by default. Applies only when `keyboardReturnType` is nil. public static var defaultKeyboardReturnType = KeyboardReturnTypeConfiguration() /// Which `UIReturnKeyType` should be used in this form. If nil then `defaultKeyboardReturnType` is used public var keyboardReturnType: KeyboardReturnTypeConfiguration? /// This form's delegate public weak var delegate: FormDelegate? public init() {} /** Returns the row at the given indexPath */ public subscript(indexPath: IndexPath) -> BaseRow { return self[indexPath.section][indexPath.row] } /** Returns the row whose tag is passed as parameter. Uses a dictionary to get the row faster */ public func rowBy<T>(tag: String) -> RowOf<T>? where T: Equatable{ let row: BaseRow? = rowBy(tag: tag) return row as? RowOf<T> } /** Returns the row whose tag is passed as parameter. Uses a dictionary to get the row faster */ public func rowBy<Row>(tag: String) -> Row? where Row: RowType{ let row: BaseRow? = rowBy(tag: tag) return row as? Row } /** Returns the row whose tag is passed as parameter. Uses a dictionary to get the row faster */ public func rowBy(tag: String) -> BaseRow? { return rowsByTag[tag] } /** Returns the section whose tag is passed as parameter. */ public func sectionBy(tag: String) -> Section? { return kvoWrapper._allSections.filter({ $0.tag == tag }).first } /** Method used to get all the values of all the rows of the form. Only rows with tag are included. - parameter includeHidden: If the values of hidden rows should be included. - returns: A dictionary mapping the rows tag to its value. [tag: value] */ public func values(includeHidden: Bool = false) -> [String: Any?] { if includeHidden { return getValues(for: allRows.filter({ $0.tag != nil })) .merging(getValues(for: allSections.filter({ $0 is MultivaluedSection && $0.tag != nil }) as? [MultivaluedSection]), uniquingKeysWith: {(_, new) in new }) } return getValues(for: rows.filter({ $0.tag != nil })) .merging(getValues(for: allSections.filter({ $0 is MultivaluedSection && $0.tag != nil }) as? [MultivaluedSection]), uniquingKeysWith: {(_, new) in new }) } /** Set values to the rows of this form - parameter values: A dictionary mapping tag to value of the rows to be set. [tag: value] */ public func setValues(_ values: [String: Any?]) { for (key, value) in values { let row: BaseRow? = rowBy(tag: key) row?.baseValue = value } } /// The visible rows of this form public var rows: [BaseRow] { return flatMap { $0 } } /// All the rows of this form. Includes the hidden rows. public var allRows: [BaseRow] { return kvoWrapper._allSections.map({ $0.kvoWrapper._allRows }).flatMap { $0 } } /// All the sections of this form. Includes hidden sections. public var allSections: [Section] { return kvoWrapper._allSections } /** * Hides all the inline rows of this form. */ public func hideInlineRows() { for row in self.allRows { if let inlineRow = row as? BaseInlineRowType { inlineRow.collapseInlineRow() } } } // MARK: Private var rowObservers = [String: [ConditionType: [Taggable]]]() var rowsByTag = [String: BaseRow]() var tagToValues = [String: Any]() lazy var kvoWrapper: KVOWrapper = { [unowned self] in return KVOWrapper(form: self) }() } extension Form: Collection { public var startIndex: Int { return 0 } public var endIndex: Int { return kvoWrapper.sections.count } } extension Form: MutableCollection { // MARK: MutableCollectionType public subscript (_ position: Int) -> Section { get { return kvoWrapper.sections[position] as! Section } set { if position > kvoWrapper.sections.count { assertionFailure("Form: Index out of bounds") } if position < kvoWrapper.sections.count { let oldSection = kvoWrapper.sections[position] let oldSectionIndex = kvoWrapper._allSections.firstIndex(of: oldSection as! Section)! // Remove the previous section from the form kvoWrapper._allSections[oldSectionIndex].willBeRemovedFromForm() kvoWrapper._allSections[oldSectionIndex] = newValue } else { kvoWrapper._allSections.append(newValue) } kvoWrapper.sections[position] = newValue newValue.wasAddedTo(form: self) } } public func index(after i: Int) -> Int { return i+1 <= endIndex ? i+1 : endIndex } public func index(before i: Int) -> Int { return i > startIndex ? i-1 : startIndex } public var last: Section? { return reversed().first } } extension Form : RangeReplaceableCollection { // MARK: RangeReplaceableCollectionType public func append(_ formSection: Section) { kvoWrapper.sections.insert(formSection, at: kvoWrapper.sections.count) kvoWrapper._allSections.append(formSection) formSection.wasAddedTo(form: self) } public func append<S: Sequence>(contentsOf newElements: S) where S.Iterator.Element == Section { kvoWrapper.sections.addObjects(from: newElements.map { $0 }) kvoWrapper._allSections.append(contentsOf: newElements) for section in newElements { section.wasAddedTo(form: self) } } public func replaceSubrange<C: Collection>(_ subRange: Range<Int>, with newElements: C) where C.Iterator.Element == Section { for i in subRange.lowerBound..<subRange.upperBound { if let section = kvoWrapper.sections.object(at: i) as? Section { section.willBeRemovedFromForm() kvoWrapper._allSections.remove(at: kvoWrapper._allSections.firstIndex(of: section)!) } } kvoWrapper.sections.replaceObjects(in: NSRange(location: subRange.lowerBound, length: subRange.upperBound - subRange.lowerBound), withObjectsFrom: newElements.map { $0 }) kvoWrapper._allSections.insert(contentsOf: newElements, at: indexForInsertion(at: subRange.lowerBound)) for section in newElements { section.wasAddedTo(form: self) } } public func removeAll(keepingCapacity keepCapacity: Bool = false) { // not doing anything with capacity let sections = kvoWrapper._allSections kvoWrapper.removeAllSections() for section in sections { section.willBeRemovedFromForm() } } private func indexForInsertion(at index: Int) -> Int { guard index != 0 else { return 0 } let section = kvoWrapper.sections[index-1] if let i = kvoWrapper._allSections.firstIndex(of: section as! Section) { return i + 1 } return kvoWrapper._allSections.count } } extension Form { // MARK: Private Helpers class KVOWrapper: NSObject { @objc dynamic private var _sections = NSMutableArray() var sections: NSMutableArray { return mutableArrayValue(forKey: "_sections") } var _allSections = [Section]() private weak var form: Form? init(form: Form) { self.form = form super.init() addObserver(self, forKeyPath: "_sections", options: [.new, .old], context:nil) } deinit { removeObserver(self, forKeyPath: "_sections") _sections.removeAllObjects() _allSections.removeAll() } func removeAllSections() { _sections = [] _allSections.removeAll() } public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { let newSections = change?[NSKeyValueChangeKey.newKey] as? [Section] ?? [] let oldSections = change?[NSKeyValueChangeKey.oldKey] as? [Section] ?? [] guard let delegateValue = form?.delegate, let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey] else { return } guard keyPathValue == "_sections" else { return } switch (changeType as! NSNumber).uintValue { case NSKeyValueChange.setting.rawValue: if newSections.count == 0 { let indexSet = IndexSet(integersIn: 0..<oldSections.count) delegateValue.sectionsHaveBeenRemoved(oldSections, at: indexSet) } else { let indexSet = change![NSKeyValueChangeKey.indexesKey] as? IndexSet ?? IndexSet(integersIn: 0..<newSections.count) delegateValue.sectionsHaveBeenAdded(newSections, at: indexSet) } case NSKeyValueChange.insertion.rawValue: let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet delegateValue.sectionsHaveBeenAdded(newSections, at: indexSet) case NSKeyValueChange.removal.rawValue: let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet delegateValue.sectionsHaveBeenRemoved(oldSections, at: indexSet) case NSKeyValueChange.replacement.rawValue: let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet delegateValue.sectionsHaveBeenReplaced(oldSections: oldSections, newSections: newSections, at: indexSet) default: assertionFailure() } } } func dictionaryValuesToEvaluatePredicate() -> [String: Any] { return tagToValues } func addRowObservers(to taggable: Taggable, rowTags: [String], type: ConditionType) { for rowTag in rowTags { if rowObservers[rowTag] == nil { rowObservers[rowTag] = Dictionary() } if let _ = rowObservers[rowTag]?[type] { if !rowObservers[rowTag]![type]!.contains(where: { $0 === taggable }) { rowObservers[rowTag]?[type]!.append(taggable) } } else { rowObservers[rowTag]?[type] = [taggable] } } } func removeRowObservers(from taggable: Taggable, rowTags: [String], type: ConditionType) { for rowTag in rowTags { guard let arr = rowObservers[rowTag]?[type], let index = arr.firstIndex(where: { $0 === taggable }) else { continue } rowObservers[rowTag]?[type]?.remove(at: index) if rowObservers[rowTag]?[type]?.isEmpty == true { rowObservers[rowTag] = nil } } } func nextRow(for row: BaseRow) -> BaseRow? { let allRows = rows guard let index = allRows.firstIndex(of: row) else { return nil } guard index < allRows.count - 1 else { return nil } return allRows[index + 1] } func previousRow(for row: BaseRow) -> BaseRow? { let allRows = rows guard let index = allRows.firstIndex(of: row) else { return nil } guard index > 0 else { return nil } return allRows[index - 1] } func hideSection(_ section: Section) { kvoWrapper.sections.remove(section) } func showSection(_ section: Section) { guard !kvoWrapper.sections.contains(section) else { return } guard var index = kvoWrapper._allSections.firstIndex(of: section) else { return } var formIndex = NSNotFound while formIndex == NSNotFound && index > 0 { index = index - 1 let previous = kvoWrapper._allSections[index] formIndex = kvoWrapper.sections.index(of: previous) } kvoWrapper.sections.insert(section, at: formIndex == NSNotFound ? 0 : formIndex + 1 ) } var containsMultivaluedSection: Bool { return kvoWrapper._allSections.contains { $0 is MultivaluedSection } } func getValues(for rows: [BaseRow]) -> [String: Any?] { return rows.reduce([String: Any?]()) { var result = $0 result[$1.tag!] = $1.baseValue return result } } func getValues(for multivaluedSections: [MultivaluedSection]?) -> [String: [Any?]] { return multivaluedSections?.reduce([String: [Any?]]()) { var result = $0 result[$1.tag!] = $1.values() return result } ?? [:] } } extension Form { @discardableResult public func validate(includeHidden: Bool = false, includeDisabled: Bool = true, quietly: Bool = false) -> [ValidationError] { let rowsWithHiddenFilter = includeHidden ? allRows : rows let rowsWithDisabledFilter = includeDisabled ? rowsWithHiddenFilter : rowsWithHiddenFilter.filter { $0.isDisabled != true } return rowsWithDisabledFilter.reduce([ValidationError]()) { res, row in var res = res res.append(contentsOf: row.validate(quietly: quietly)) return res } } // Reset rows validation public func cleanValidationErrors(){ allRows.forEach { $0.cleanValidationErrors() } } }
mit
a1a7191b9dabf290011c5c301f30fb12
37.992718
170
0.636913
4.834487
false
false
false
false
marinehero/ExSwift
ExSwiftTests/RangeExtensionsTests.swift
25
887
// // RangeExtensionsTests.swift // ExSwift // // Created by pNre on 04/06/14. // Copyright (c) 2014 pNre. All rights reserved. // import Quick import Nimble class RangeExtensionsSpec: QuickSpec { override func spec() { /** * Range.times */ it("times") { var count: Int = 0 (2..<4).times { count++ } expect(count) == 2 count = 0 (2...4).times { count++ } expect(count) == 3 } /** * Range.each */ it("each") { var items = [Int]() (0..<2).each(items.append) expect(items) == [0, 1] (0..<0).each { (current: Int) in fail() } } } }
bsd-2-clause
3a74bd0a82b9f579cc50020b9284e85a
16.057692
49
0.361894
4.391089
false
false
false
false
diwip/inspector-ios
Inspector/ViewControllers/Caches/CachesViewModel.swift
1
1696
// // CachesViewModel.swift // Inspector // // Created by Kevin Hury on 11/4/15. // Copyright © 2015 diwip. All rights reserved. // import Cocoa import RxSwift import SwiftyJSON enum CacheError: ErrorType { case FetchCacheError } class CachesViewModel { lazy var cacheData: Observable<[String:[String]]> = { return Observable.create { observer in let networkHandler = (NSApplication.sharedApplication().delegate as! AppDelegate).networkHandler dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { guard let json = networkHandler.getResourcesCache() else { return observer.onError(CacheError.FetchCacheError) } let frames = json["frames"].arrayValue.map { $0.stringValue }.sort() let textures = json["textures"].arrayValue .map { (json: JSON) -> Dictionary<String, Any> in let dict = json.dictionaryValue return ["name": dict.keys.first!, "size": NSPointFromString(dict.values.first!.dictionaryValue["size"]!.stringValue)] }.sort { let pointA = $0["size"] as! NSPoint let pointB = $1["size"] as! NSPoint return pointA.x * pointA.y > pointB.x * pointB.y } .map { $0["name"] as! String } observer.onNext(["frames": frames, "textures": textures]) observer.onCompleted() } return AnonymousDisposable {} } }() }
mit
eec3cd6396d2b02af528f8b5daf387ab
35.085106
141
0.539233
5.014793
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/Plans/PurchaseButton.swift
2
2821
import UIKit import MRProgress class PurchaseButton: RoundedButton { var animatesWhenSelected: Bool = true fileprivate var collapseConstraint: NSLayoutConstraint! fileprivate lazy var activityIndicatorView: MRActivityIndicatorView = { let activityView = MRActivityIndicatorView(frame: self.bounds) activityView.tintColor = self.tintColor activityView.lineWidth = 1.0 self.addSubview(activityView) activityView.translatesAutoresizingMaskIntoConstraints = false self.pinSubviewAtCenter(activityView) activityView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true activityView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true activityView.widthAnchor.constraint(equalTo: activityView.heightAnchor).isActive = true return activityView }() override func awakeFromNib() { super.awakeFromNib() collapseConstraint = widthAnchor.constraint(equalTo: heightAnchor) } fileprivate var _cornerRadius: CGFloat = 0 override var isSelected: Bool { didSet { if oldValue == isSelected { return } if isSelected { collapseConstraint.isActive = true UIView.animate(withDuration: 0.3, animations: { // Save the corner radius so we can restore it later self._cornerRadius = self.cornerRadius self.cornerRadius = self.bounds.height / 2 self.titleLabel?.alpha = 0 // Ask the superview to layout if necessary, because the // button has changed size. This is required otherwise // we were seeing an animation glitch where the superview's // constraints weren't animating correctly to contain the // button as it changed size. // See https://github.com/wordpress-mobile/WordPress-iOS/pull/5361 // for more info. self.superview?.layoutIfNeeded() }, completion: { finished in self.activityIndicatorView.startAnimating() self.borderWidth = 0 }) } else { collapseConstraint.isActive = false self.activityIndicatorView.stopAnimating() UIView.animate(withDuration: 0.3, animations: { self.cornerRadius = self._cornerRadius self.borderWidth = 1 // See comment above self.superview?.layoutIfNeeded() }, completion: { finished in self.titleLabel?.alpha = 1 }) } } } }
gpl-2.0
543b4907fddf2702a56960378ff9d38b
37.643836
95
0.589507
6.186404
false
false
false
false
ccwuzhou/WWZSwift
Source/Extensions/UISwitch+WWZ.swift
1
773
// // UIControl-WWZ.swift // webo_swift // // Created by wwz on 17/2/25. // Copyright © 2017年 tijio. All rights reserved. // import UIKit public extension UISwitch { public convenience init(onTintColor: UIColor?, tintColor: UIColor?, thumbTintColor: UIColor?) { self.init() if let onTintColor = onTintColor { self.onTintColor = onTintColor } if let tintColor = tintColor { self.tintColor = tintColor } if let thumbTintColor = thumbTintColor { self.thumbTintColor = thumbTintColor } } public func wwz_setTarget(target: Any?, action: Selector) { self.addTarget(target, action: action, for: .valueChanged) } }
mit
edde453905a96e22b45837c352474dc4
20.388889
99
0.588312
4.638554
false
false
false
false
mgireesh05/leetcode
LeetCodeSwiftPlayground.playground/Sources/delete-node-in-a-bst.swift
1
1530
/** * Solution to the problem: https://leetcode.com/problems/delete-node-in-a-bst/ */ //Note: The number here denotes the problem id in leetcode. This is to avoid name conflict with other solution classes in the Swift playground. public class Solution450 { public init(){ } public func deleteNode(_ root: TreeNode?, _ key: Int) -> TreeNode? { if(root == nil){ return nil } if(key < (root?.val)!){ //Key smaller than the the current root, so find it in the left subtree root?.left = deleteNode(root?.left, key) }else if (key > (root?.val)!){ //Key larger than the the current root, so find it in the right subtree root?.right = deleteNode(root?.right, key) } else { if(root?.left == nil){ //Key is in the current root and left branch is empty, delete the root and return the right as the new root return root?.right }else if(root?.right == nil) { //Key is in the current root and right branch is empty, delete the root and return the left as the new root return root?.left }else{ //Key is in the current root and left and right are not empty. Find the min in the right subtree, copy the min to the root, and recursively delete that value from the right subtree let node: TreeNode? = minNode(root?.right) root?.val = (node?.val)! root?.right = deleteNode(root?.right, (node?.val)!) } } return root } func minNode(_ root: TreeNode?) -> TreeNode { var node = root while(node?.left != nil){ node = node?.left } return node! } }
mit
f1dd9944681ef3010d32e896cd0b43d8
30.22449
184
0.662745
3.422819
false
false
false
false
huangboju/Moots
Examples/SwiftUI/Mac/RedditOS-master/RedditOs/Features/Subreddit/SubredditViewModel.swift
1
2541
// // SubredditViewModel.swift // RedditOs // // Created by Thomas Ricouard on 09/07/2020. // import Foundation import SwiftUI import Combine import Backend class SubredditViewModel: ObservableObject { enum SortOrder: String, CaseIterable { case hot, new, top, rising } let name: String private var subredditCancellable: AnyCancellable? private var listingCancellable: AnyCancellable? private var subscribeCancellable: AnyCancellable? @Published var subreddit: Subreddit? @Published var listings: [SubredditPost]? @AppStorage(SettingsKey.subreddit_defaut_sort_order) var sortOrder = SortOrder.hot { didSet { listings = nil fetchListings() } } @Published var errorLoadingAbout = false init(name: String) { self.name = name } func fetchAbout() { subredditCancellable = Subreddit.fetchAbout(name: name) .receive(on: DispatchQueue.main) .sink { [weak self] holder in self?.errorLoadingAbout = holder == nil self?.subreddit = holder?.data } } func fetchListings() { listingCancellable = SubredditPost.fetch(subreddit: name, sort: sortOrder.rawValue, after: listings?.last) .receive(on: DispatchQueue.main) .map{ $0.data?.children.map{ $0.data }} .sink{ [weak self] listings in if self?.listings?.last != nil, let listings = listings { self?.listings?.append(contentsOf: listings) } else if self?.listings == nil { self?.listings = listings } } } func toggleSubscribe() { if subreddit?.userIsSubscriber == true { subscribeCancellable = subreddit?.unSubscribe() .receive(on: DispatchQueue.main) .sink { [weak self] response in if response.error != nil { self?.subreddit?.userIsSubscriber = true } } } else { subscribeCancellable = subreddit?.subscribe() .receive(on: DispatchQueue.main) .sink { [weak self] response in if response.error != nil { self?.subreddit?.userIsSubscriber = false } } } } }
mit
f95c52c43474df20ba86ad740817d0e3
30.37037
88
0.534042
5.217659
false
false
false
false
huangboju/Moots
Examples/SwiftUI/PokeMaster/PokeMaster/View/Utils/BlurView.swift
1
1022
// // BlurView.swift // PokeMaster // // Created by 黄伯驹 on 2021/11/20. // import SwiftUI struct BlurView: UIViewRepresentable { let style: UIBlurEffect.Style func makeUIView(context: Context) -> some UIView { let view = UIView(frame: .zero) view.backgroundColor = .clear let blurEffect = UIBlurEffect(style: style) let blurView = UIVisualEffectView(effect: blurEffect) blurView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(blurView) NSLayoutConstraint.activate([ blurView.heightAnchor .constraint(equalTo: view.heightAnchor), blurView.widthAnchor .constraint(equalTo: view.widthAnchor) ]) return view } func updateUIView(_ uiView: UIViewType, context: Context) { } } extension View { func blurBackground(style: UIBlurEffect.Style) -> some View { ZStack { BlurView(style: style) self } } }
mit
f55e7be0b51ba58947fd5f8a168664da
23.190476
66
0.621063
4.932039
false
false
false
false
HongxiangShe/DYZB
DY/DY/Class/Main/View/PageTitleView.swift
1
6411
// // PageTitleView.swift // DY // // Created by 佘红响 on 16/12/7. // Copyright © 2016年 佘红响. All rights reserved. // import UIKit // MARK: - PageTitleViewDelegate protocol PageTitleViewDelegate: class { func pageTitleViewClickWithButton(titleView: PageTitleView, button: UIButton) } fileprivate let kScrollLineH: CGFloat = 3 fileprivate let kNormarlColor: (CGFloat, CGFloat, CGFloat) = (40, 40, 40) fileprivate let kSelectorColor: (CGFloat, CGFloat, CGFloat) = (255, 128, 0) fileprivate let btnSelectorColor = UIColor(r: kSelectorColor.0, g: kSelectorColor.1, b: kSelectorColor.2) fileprivate let btnNormalColor = UIColor(r: kNormarlColor.0, g: kNormarlColor.1, b: kNormarlColor.2) class PageTitleView: UIView { // MARK: - 自定义属性 fileprivate var titles: [String]? fileprivate var selectedBtn: UIButton? weak var delegate: PageTitleViewDelegate? // MARK: - 懒加载 fileprivate lazy var titleButtons: [UIButton] = [UIButton]() fileprivate lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() fileprivate lazy var lineView: UIView = { let lineView = UIView() lineView.backgroundColor = UIColor.orange return lineView }() init(frame: CGRect, titles: [String]) { self.titles = titles super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 设置UI界面 fileprivate extension PageTitleView { /// 初始化方法 fileprivate func setupUI() { addSubview(scrollView) scrollView.frame = self.bounds setupButtons() setupScrollLine() } /// 初始化Buttons fileprivate func setupButtons() { guard let titleArr = titles , titleArr.count > 0 else { return } let width = self.bounds.size.width / CGFloat(titleArr.count) let height = self.bounds.size.height let btnY: CGFloat = 0 var btnX: CGFloat = 0 for (index, title) in titleArr.enumerated() { let btn = UIButton(type:.custom) btn.tag = index btnX = CGFloat(index) * width btn.setTitle(title, for: .normal) btn.setTitleColor(btnNormalColor, for: .normal) btn.titleLabel?.font = UIFont.systemFont(ofSize: 15) btn.frame = CGRect(x: btnX, y: btnY, width: width, height: height) btn.addTarget(self, action: #selector(btnClick(button:)), for: .touchUpInside) scrollView.addSubview(btn) titleButtons.append(btn) if (index == 0) { selectedBtn = btn btn.setTitleColor(btnSelectorColor, for: .normal) } } } /// 初始化底线 fileprivate func setupScrollLine() { scrollView.insertSubview(lineView, at: 10) guard let firstBtn = titleButtons.first else { return } // 取出button中titleLabel的宽度 guard let titleLabel = firstBtn.titleLabel else { return } titleLabel.sizeToFit() let lineViewWidth: CGFloat = titleLabel.frame.size.width; lineView.frame = CGRect(x: 0, y: frame.size.height - kScrollLineH , width: lineViewWidth + 8, height: kScrollLineH) lineView.center = CGPoint(x: firstBtn.center.x, y: lineView.center.y) } } // MARK: - title按钮的点击方法 fileprivate extension PageTitleView { /// 按钮的点击方法 @objc fileprivate func btnClick(button: UIButton) { guard button != selectedBtn else { return } button.setTitleColor(btnSelectorColor, for: .normal) selectedBtn?.setTitleColor(btnNormalColor, for: .normal) selectedBtn = button delegate?.pageTitleViewClickWithButton(titleView: self, button: button) } } // MARK: - 暴露给外面的方法 extension PageTitleView { func titleViewWithProgress(progress: CGFloat, sourceIndex: Int, targetIndex: Int) { // 获取按钮 let sourceButton = titleButtons[sourceIndex] let targetButton = titleButtons[targetIndex] // 处理指示器的逻辑 let moveTotalX = targetButton.frame.origin.x - sourceButton.frame.origin.x let moveX = moveTotalX * progress lineView.center.x = sourceButton.center.x + moveX // 处理颜色转换以及按钮的选中效果 let colorDelta: (CGFloat, CGFloat, CGFloat) = ((kSelectorColor.0-kNormarlColor.0)*progress, (kSelectorColor.1-kNormarlColor.1)*progress, (kSelectorColor.2-kNormarlColor.2)*progress) let sourceColor = UIColor(r: kSelectorColor.0 - colorDelta.0, g: kSelectorColor.1 - colorDelta.1, b: kSelectorColor.2 - colorDelta.2) let targetColor = UIColor(r: kNormarlColor.0 + colorDelta.0, g: kNormarlColor.1 + colorDelta.1, b: kNormarlColor.2 + colorDelta.2) if (sourceButton != targetButton) { sourceButton.setTitleColor(sourceColor, for: .normal) targetButton.setTitleColor(targetColor, for: .normal) } else { selectedBtn = sourceButton } } // func setCenterXWithOffsetX(offsetX: CGFloat, totalWidth: CGFloat) { // // guard offsetX >= 0 && offsetX <= (totalWidth - kScreenWidth) else { // return // } // // let centerX = kScreenWidth / totalWidth * offsetX + (titleButtons.first?.center.x)!; // UIView.animate(withDuration: 0.25) { // self.lineView.center = CGPoint(x: centerX, y: self.lineView.center.y) // } // } // // func selectTitleButton(offsetX: CGFloat) { // // let index = Int(offsetX / kScreenWidth) // let button = titleButtons[index] // guard button != selectedBtn else { // return // } // // button.isSelected = true // selectedBtn?.isSelected = false // selectedBtn = button // // } }
mit
8f47b818e7ae199168f7bbb261aec008
31.14433
189
0.608724
4.541879
false
false
false
false
jmgc/swift
test/Concurrency/Runtime/async_taskgroup_throw_recover.swift
1
2112
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency) | %FileCheck %s --dump-input always // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: OS=macosx // REQUIRES: CPU=x86_64 import Dispatch struct Boom: Error { } struct IgnoredBoom: Error { } func one() async -> Int { 1 } func boom() async throws -> Int { throw Boom() } func test_taskGroup_throws() async { do { let got = await try Task.withGroup(resultType: Int.self) { group async throws -> Int in await group.add { await one() } await group.add { await try boom() } do { while let r = await try group.next() { print("next: \(r)") } } catch { print("error caught in group: \(error)") await group.add { () async -> Int in print("task 3 (cancelled: \(await Task.isCancelled()))") return 3 } guard let got = await try! group.next() else { print("task group failed to get 3 (:\(#line))") return 0 } print("task group next: \(got)") if got == 1 { // the previous 1 completed before the 3 we just submitted, // we still want to see that three so let's await for it guard let third = await try! group.next() else { print("task group failed to get 3 (:\(#line))") return got } print("task group returning normally: \(third)") return third } else { print("task group returning normally: \(got)") return got } } fatalError("Should have thrown and handled inside the catch block") } // Optionally, we may get the first result back before the failure: // COM: next: 1 // CHECK: error caught in group: Boom() // CHECK: task 3 (cancelled: false) // CHECK: task group returning normally: 3 // CHECK: got: 3 print("got: \(got)") } catch { print("rethrown: \(error)") fatalError("Expected recovered result, but got error: \(error)") } } runAsyncAndBlock(test_taskGroup_throws)
apache-2.0
1466e095b8c043771d220e0dcfc23029
23.55814
113
0.574337
4.07722
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/CommonCrypto/Sources/CommonCryptoKit/Extensions/Data+Extensions.swift
1
855
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation extension NSData { public var hexValue: String { (self as Data).hexValue } } extension Data { public var hexValue: String { map { String(format: "%02x", $0) }.reduce("", +) } public init(hexValue hex: String) { let len = hex.count / 2 var data = Data(capacity: len) for i in 0..<len { let j = hex.index(hex.startIndex, offsetBy: i * 2) let k = hex.index(j, offsetBy: 2) let bytes = hex[j..<k] if var num = UInt8(bytes, radix: 16) { data.append(&num, count: 1) } else { self = Data() return } } self = data } public var bytes: [UInt8] { Array(self) } }
lgpl-3.0
2e7e8b477bb63c9570f5fd7cb0128352
22.722222
62
0.495316
3.917431
false
false
false
false
tjw/swift
test/SourceKit/InterfaceGen/gen_clang_module.swift
2
5094
import Foo var x: FooClassBase // REQUIRES: objc_interop // FIXME: the test output we're comparing to is specific to macOS. // REQUIRES-ANY: OS=macosx // RUN: %empty-directory(%t.overlays) // RUN: %empty-directory(%t) // RUN: %build-clang-importer-objc-overlays // // RUN: %target-swift-frontend -emit-module -o %t.overlays -F %S/../Inputs/libIDE-mock-sdk %S/Inputs/Foo.swift // // RUN: %sourcekitd-test -req=interface-gen -module Foo -- -I %t.overlays -F %S/../Inputs/libIDE-mock-sdk \ // RUN: %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t > %t.response // RUN: diff -u %s.response %t.response // RUN: %sourcekitd-test -req=interface-gen -module Foo.FooSub -- -I %t.overlays -F %S/../Inputs/libIDE-mock-sdk \ // RUN: %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t > %t.sub.response // RUN: diff -u %s.sub.response %t.sub.response // RUN: %sourcekitd-test -req=interface-gen -module FooHelper -- -I %t.overlays -F %S/../Inputs/libIDE-mock-sdk \ // RUN: %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t > %t.helper.response // RUN: diff -u %s.helper.response %t.helper.response // RUN: %sourcekitd-test -req=interface-gen -module FooHelper.FooHelperExplicit -- -I %t.overlays \ // RUN: -F %S/../Inputs/libIDE-mock-sdk %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t > %t.helper.explicit.response // RUN: diff -u %s.helper.explicit.response %t.helper.explicit.response // RUN: %sourcekitd-test -req=interface-gen-open -module Foo -- -I %t.overlays -F %S/../Inputs/libIDE-mock-sdk \ // RUN: %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t \ // RUN: == -req=cursor -pos=205:67 | %FileCheck -check-prefix=CHECK1 %s // The cursor points to 'FooClassBase' inside the list of base classes, see 'gen_clang_module.swift.response' // RUN: %sourcekitd-test -req=interface-gen-open -module Foo -- -I %t.overlays -F %S/../Inputs/libIDE-mock-sdk \ // RUN: %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t \ // RUN: == -req=cursor -pos=3:11 %s -- %s -I %t.overlays -F %S/../Inputs/libIDE-mock-sdk \ // RUN: %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK1 %s // CHECK1: source.lang.swift.ref.class ({{.*}}Foo.framework/Headers/Foo.h:147:12-147:24) // CHECK1: FooClassBase // CHECK1: c:objc(cs)FooClassBase // CHECK1: Foo{{$}} // CHECK1-NEXT: /<interface-gen> // RUN: %sourcekitd-test -req=interface-gen-open -module Foo -- -I %t.overlays -F %S/../Inputs/libIDE-mock-sdk \ // RUN: %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t \ // RUN: == -req=cursor -pos=232:20 | %FileCheck -check-prefix=CHECK2 %s // The cursor points inside the interface, see 'gen_clang_module.swift.response' // CHECK2: source.lang.swift.decl.function.method.instance ({{.*}}Foo.framework/Headers/Foo.h:170:10-170:27) // CHECK2: fooInstanceFunc0 // CHECK2: c:objc(cs)FooClassDerived(im)fooInstanceFunc0 // CHECK2: Foo{{$}} // CHECK2-NEXT: /<interface-gen> // RUN: %sourcekitd-test -req=interface-gen-open -module Foo -- -I %t.overlays -F %S/../Inputs/libIDE-mock-sdk \ // RUN: %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t \ // RUN: == -req=find-usr -usr "c:objc(cs)FooClassDerived(im)fooInstanceFunc0" | %FileCheck -check-prefix=CHECK-USR %s // The returned line:col points inside the interface, see 'gen_clang_module.swift.response' // CHECK-USR: (232:15-232:33) // RUN: %sourcekitd-test -req=interface-gen-open -module Foo -- -I %t.overlays -F %S/../Inputs/libIDE-mock-sdk \ // RUN: %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t \ // RUN: == -req=find-interface -module Foo -- %s -I %t.overlays -F %S/../Inputs/libIDE-mock-sdk \ // RUN: %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-IFACE %s // CHECK-IFACE: DOC: (/<interface-gen>) // CHECK-IFACE: ARGS: [-target x86_64-{{.*}} -sdk {{.*}} -F {{.*}}/libIDE-mock-sdk -I {{.*}}.overlays {{.*}} -module-cache-path {{.*}} ] // RUN: %sourcekitd-test -req=interface-gen-open -module Foo -- -I %t.overlays -F %S/../Inputs/libIDE-mock-sdk \ // RUN: %mcp_opt -target %target-triple %clang-importer-sdk-nosource -I %t \ // RUN: == -req=cursor -pos=1:8 == -req=cursor -pos=1:12 \ // RUN: == -req=cursor -pos=2:10 \ // RUN: == -req=cursor -pos=3:10 | %FileCheck -check-prefix=CHECK-IMPORT %s // The cursors point to module names inside the imports, see 'gen_clang_module.swift.response' // CHECK-IMPORT: source.lang.swift.ref.module () // CHECK-IMPORT-NEXT: Foo{{$}} // CHECK-IMPORT-NEXT: Foo{{$}} // CHECK-IMPORT: source.lang.swift.ref.module () // CHECK-IMPORT-NEXT: FooSub{{$}} // CHECK-IMPORT-NEXT: Foo.FooSub{{$}} // CHECK-IMPORT: source.lang.swift.ref.module () // CHECK-IMPORT-NEXT: Foo{{$}} // CHECK-IMPORT-NEXT: Foo{{$}} // CHECK-IMPORT: source.lang.swift.ref.module () // CHECK-IMPORT-NEXT: FooHelper{{$}} // CHECK-IMPORT-NEXT: FooHelper{{$}}
apache-2.0
95a5845ccb3df0a1fb57844a8c97c8fc
54.369565
145
0.660188
2.978947
false
true
false
false
Pluto-Y/SwiftyEcharts
SwiftyEchartsTest_iOS/FunctionOrOthersSpec.swift
1
2858
// // FunctionOrOthersSpec.swift // SwiftyEcharts // // Created by Pluto Y on 20/06/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import Quick import Nimble @testable import SwiftyEcharts class FunctionOrOthersSpec: QuickSpec { override func spec() { let errorJsonString = "null" let function: Function = "function (idx) {return idx * 0.65;}" let floatValue: Float = 3.1415 let integerValue: Int = 10 beforeEach { JsCache.removeAll() } describe("For FunctionOrFloat") { it(" needs to check the jsonString ") { let floatCase = FunctionOrFloat.value(floatValue) expect(floatCase.jsonString).to(equal(floatValue.jsonString)) let functionCase = FunctionOrFloat.function(function) expect(functionCase.jsonString).to(equal(function.jsonString)) } it(" needs to check the literal convertible ") { let floatLiteralCase: FunctionOrFloat = 3.1415 let integerLieteralCase: FunctionOrFloat = 10 expect(floatLiteralCase.jsonString).to(equal(floatValue.jsonString)) expect(integerLieteralCase.jsonString).to(equal(Float(integerValue).jsonString)) } } describe("For FunctionOrFloatOrPair") { let arrayLiteralValue: Point = [floatValue, 100%] it(" needs to check the jsonString ") { let floatCase = FunctionOrFloatOrPair.value(floatValue) expect(floatCase.jsonString).to(equal(floatValue.jsonString)) let functionCase = FunctionOrFloatOrPair.function(function) expect(functionCase.jsonString).to(equal(function.jsonString)) let pointCase = FunctionOrFloatOrPair.point(arrayLiteralValue) expect(pointCase.jsonString).to(equal(arrayLiteralValue.jsonString)) } it(" need to check the literal convertible ") { let floatLiteralCase: FunctionOrFloatOrPair = 3.1415 let integerLieteralCase: FunctionOrFloatOrPair = 10 let errorArrayLiteralCase: FunctionOrFloatOrPair = [1] let arrayLiteralCase: FunctionOrFloatOrPair = [floatValue, 100%] expect(floatLiteralCase.jsonString).to(equal(floatValue.jsonString)) expect(integerLieteralCase.jsonString).to(equal(Float(integerValue).jsonString)) expect(arrayLiteralCase.jsonString).to(equal(arrayLiteralValue.jsonString)) expect(errorArrayLiteralCase.jsonString).to(equal(errorJsonString)) } } } }
mit
30c9a303e5bc49509d67f396056054d6
39.239437
96
0.59993
5.390566
false
false
false
false
tjw/swift
test/TBD/protocol.swift
2
3527
// RUN: %target-swift-frontend -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s // RUN: %target-swift-frontend -enable-resilience -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s public protocol Public { func publicMethod() associatedtype PublicAT var publicVarGet: Int { get } var publicVarGetSet: Int { get set } } protocol Internal { func internalMethod() associatedtype InternalAT var internalVarGet: Int { get } var internalVarGetSet: Int { get set } } private protocol Private { func privateMethod() associatedtype PrivateAT var privateVarGet: Int { get } var privateVarGetSet: Int { get set } } // Naming scheme: type access, protocol access, witness access, type kind public struct PublicPublicPublicStruct: Public { public func publicMethod() {} public typealias PublicAT = Int public let publicVarGet: Int = 0 public var publicVarGetSet: Int = 0 } public struct PublicInternalPublicStruct: Internal { public func internalMethod() {} public typealias InternalAT = Int public let internalVarGet: Int = 0 public var internalVarGetSet: Int = 0 } public struct PublicPrivatePublicStruct: Private { public func privateMethod() {} public typealias PrivateAT = Int public let privateVarGet: Int = 0 public var privateVarGetSet: Int = 0 } public struct PublicInternalInternalStruct: Internal { func internalMethod() {} typealias InternalAT = Int let internalVarGet: Int = 0 var internalVarGetSet: Int = 0 } public struct PublicPrivateInternalStruct: Private { func privateMethod() {} typealias PrivateAT = Int let privateVarGet: Int = 0 var privateVarGetSet: Int = 0 } public struct PublicPrivateFileprivateStruct: Private { fileprivate func privateMethod() {} fileprivate typealias PrivateAT = Int fileprivate let privateVarGet: Int = 0 fileprivate var privateVarGetSet: Int = 0 } struct InternalPublicInternalStruct: Public { func publicMethod() {} typealias PublicAT = Int let publicVarGet: Int = 0 var publicVarGetSet: Int = 0 } struct InternalInternalInternalStruct: Internal { func internalMethod() {} typealias InternalAT = Int let internalVarGet: Int = 0 var internalVarGetSet: Int = 0 } struct InternalPrivateInternalStruct: Private { func privateMethod() {} typealias PrivateAT = Int let privateVarGet: Int = 0 var privateVarGetSet: Int = 0 } struct InternalPrivateFileprivateStruct: Private { fileprivate func privateMethod() {} fileprivate typealias PrivateAT = Int fileprivate let privateVarGet: Int = 0 fileprivate var privateVarGetSet: Int = 0 } private struct PrivatePublicInternalStruct: Public { func publicMethod() {} typealias PublicAT = Int let publicVarGet: Int = 0 var publicVarGetSet: Int = 0 } private struct PrivateInternalInternalStruct: Internal { func internalMethod() {} typealias InternalAT = Int let internalVarGet: Int = 0 var internalVarGetSet: Int = 0 } private struct PrivatePrivateInternalStruct: Private { func privateMethod() {} typealias PrivateAT = Int let privateVarGet: Int = 0 var privateVarGetSet: Int = 0 } private struct PrivatePrivateFileprivateStruct: Private { fileprivate func privateMethod() {} fileprivate typealias PrivateAT = Int fileprivate let privateVarGet: Int = 0 fileprivate var privateVarGetSet: Int = 0 }
apache-2.0
ac1b25cdef38e2145b5e283a7101f20a
28.638655
134
0.724128
4.898611
false
false
false
false
austinzheng/swift
test/Profiler/coverage_smoke.swift
5
5840
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -profile-generate -profile-coverage-mapping -Xfrontend -disable-incremental-llvm-codegen -o %t/main // This unusual use of 'sh' allows the path of the profraw file to be // substituted by %target-run. // RUN: %target-run sh -c 'env LLVM_PROFILE_FILE=$1 $2' -- %t/default.profraw %t/main // RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata // RUN: %llvm-profdata show %t/default.profdata -function=f_internal | %FileCheck %s --check-prefix=CHECK-INTERNAL // RUN: %llvm-profdata show %t/default.profdata -function=f_private | %FileCheck %s --check-prefix=CHECK-PRIVATE // RUN: %llvm-profdata show %t/default.profdata -function=f_public | %FileCheck %s --check-prefix=CHECK-PUBLIC // RUN: %llvm-profdata show %t/default.profdata -function=main | %FileCheck %s --check-prefix=CHECK-MAIN // RUN: %llvm-cov show %t/main -instr-profile=%t/default.profdata | %FileCheck %s --check-prefix=CHECK-COV // RUN: %llvm-cov report %t/main -instr-profile=%t/default.profdata -show-functions %s | %FileCheck %s --check-prefix=CHECK-REPORT // RUN: rm -rf %t // REQUIRES: profile_runtime // REQUIRES: executable_test // REQUIRES: OS=macosx // CHECK-INTERNAL: Functions shown: 1 // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}func f_internal internal func f_internal() {} // CHECK-PRIVATE: Functions shown: 1 // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}func f_private private func f_private() { f_internal() } // CHECK-PUBLIC: Functions shown: 1 // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}func f_public public func f_public() { f_private() } class Class1 { var Field1 = 0 // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}init init() {} // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}deinit deinit {} } // CHECK-MAIN: Maximum function count: 4 func main() { // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}f_public f_public() // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}if (true) if (true) {} var x : Int32 = 0 while (x < 10) { // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}10{{.*}}x += 1 x += 1 } // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}Class1 let _ = Class1() } // rdar://problem/22761498 - enum declaration suppresses coverage func foo() { var x : Int32 = 0 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 enum ETy { case A } // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 repeat { // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 x += 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } while x == 0 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 x += 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } // rdar://problem/27874041 - top level code decls get no coverage var g1 : Int32 = 0 // CHECK-COV: {{ *}}[[@LINE]]| repeat { // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 g1 += 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } while g1 == 0 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 func call_closure() { // CHECK-COV: {{ *}}[[@LINE]]| var x : Int32 = 0 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 ({ () -> () in // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 x += 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 })() // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } func call_auto_closure() { func use_auto_closure(_ x: @autoclosure () -> Bool) -> Bool { return x() && // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 x() && // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 x() // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } let _ = use_auto_closure(true) // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}3 } class Class2 { var field: Int init(field: Int) { if field > 0 { self.field = 0 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } else { self.field = 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}3 } } } extension Class2 { convenience init() { self.init(field: 0) // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } } class SubClass1: Class2 { override init(field: Int) { super.init(field: field) // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } } struct Struct1 { var field: Int init(field: Int) { if field > 0 { self.field = 0 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } else { self.field = 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } } } extension Struct1 { init() { self.init(field: 0) // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } } var g2: Int = 0 class Class3 { var m1 = g2 == 0 ? "false" // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 : "true"; // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } // rdar://34244637: Wrong coverage for do/catch sequence enum CustomError : Error { case Err } func throwError(_ b: Bool) throws { if b { throw CustomError.Err } } func catchError(_ b: Bool) -> Int { do { try throwError(b) // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}2 } catch { // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}2 return 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 let _ = 1 + 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 return 0 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } let _ = catchError(true) let _ = catchError(false) func catchError2(_ b: Bool) -> Int { do { throw CustomError.Err // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}2 } catch { if b { // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}2 return 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } } return 0 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } let _ = catchError2(true) let _ = catchError2(false) main() // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 foo() // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 call_closure() call_auto_closure() let _ = Class2(field: 0) let _ = Class2(field: 1) let _ = Class2() let _ = SubClass1(field: 0) let _ = Class3() g2 = 1 let _ = Class3() let _ = Struct1(field: 1) let _ = Struct1() // CHECK-REPORT: TOTAL {{.*}} 100.00% {{.*}} 100.00%
apache-2.0
28979a3e2c2def1f57dc6a7ebabc7998
29.416667
130
0.500685
3.187773
false
false
false
false
pkrawat1/TravelApp-ios
TravelApp/Reducers/TripReducer.swift
1
1332
// // TripReducer.swift // TravelApp // // Created by Pankaj Rawat on 01/02/17. // Copyright © 2017 Pankaj Rawat. All rights reserved. // import ReSwift func tripReducer(state: TripState?, action: Action) -> TripState { var state = state ?? initialTripState() switch action { case _ as ReSwiftInit: break case let action as SetFeedTrips: state.pushTrips(tripType: .feedTrips, trips: action.trips) break case let action as SetTrendingTrips: state.pushTrips(tripType: .trendingTrips, trips: action.trips) break case let action as UpdateTrips: action.trips.forEach({ (trip) in state.entities[trip.id!] = trip }) break case let action as SelectTrip: state.selectedTripId = action.tripId break case let action as UpdateTripUser: let user = action.user state.entities.forEach({ (key: NSNumber, trip: Trip) in if trip.user_id == user.id { trip.user = user state.entities[key] = trip } }) break default: break } return state } func initialTripState() -> TripState { return TripState(feedTripIds: [], trendingTripIds: [], entities: [:], selectedTripId: nil, searchTerms: nil) }
mit
095a76f985822f41f1becb6a9500ece2
25.62
112
0.600301
4.033333
false
false
false
false
dfreniche/SpriteKit-Playground
Spritekit-playgorund.playground/Pages/SKSpriteNodes.xcplaygroundpage/Contents.swift
1
558
//: [Previous](@previous) import SpriteKit let view = setupView() let scene = setupScene() // shows this scene on the SKView view.presentScene(scene) let myPlane = SKSpriteNode(imageNamed: "Spaceship") myPlane.position = CGPoint(x: scene.size.width/2, y: scene.size.height/2) scene.addChild(myPlane) let fadeIn = SKAction.fadeAlpha(to: 1.0, duration: 2.0) let fadeOut = SKAction.fadeAlpha(to: 0.0, duration: 2.0) let seq01 = SKAction.sequence([fadeOut, fadeIn]) let repeater = SKAction.repeat(seq01, count: 3) myPlane.run(repeater) //: [Next](@next)
mit
1627d287cf5951de19cfd0321d85934d
23.26087
73
0.729391
3.170455
false
false
false
false
grimcoder/tetriz
tetriz/tetriz/PlayGrid.swift
1
1206
import UIKit @IBDesignable class PlayGrid: UIView { @IBInspectable var fillColor: UIColor = UIColor.blackColor() var matrix = Matrix() static var unit : Int = 18 static let width : Int = 10 static let height: Int = 20 override func drawRect(rect: CGRect) { for x in 0...PlayGrid.width - 1{ for y in 0...PlayGrid.height-1{ if (matrix.array[x][y] > 0) { let path = UIBezierPath() path.moveToPoint(CGPoint(x:x*PlayGrid.unit+0,y:y*PlayGrid.unit+0)) path.addLineToPoint(CGPoint(x:x*PlayGrid.unit+0, y:y*PlayGrid.unit+PlayGrid.unit)) path.addLineToPoint(CGPoint(x:x*PlayGrid.unit+PlayGrid.unit, y:y*PlayGrid.unit+PlayGrid.unit)) path.addLineToPoint(CGPoint(x:x*PlayGrid.unit+PlayGrid.unit, y:y*PlayGrid.unit+0)) path.closePath() GetColor(matrix.array[x][y]).setFill() path.fill() } } } } }
mit
ffc1526f84f7c15d362c321ede48ecf7
30.736842
114
0.481758
4.62069
false
false
false
false
jvesala/teknappi
teknappi/Pods/RxSwift/RxSwift/Observables/Implementations/Producer.swift
26
1458
// // Producer.swift // Rx // // Created by Krunoslav Zaher on 2/20/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation public class _Producer<Element> : Producer<Element> { public override init() { super.init() } } public class Producer<Element> : Observable<Element> { override init() { super.init() } public override func subscribe<O : ObserverType where O.E == Element>(observer: O) -> Disposable { let sink = SingleAssignmentDisposable() let subscription = SingleAssignmentDisposable() let d = BinaryDisposable(sink, subscription) let setSink: (Disposable) -> Void = { d in sink.disposable = d } if !CurrentThreadScheduler.isScheduleRequired { let disposable = run(observer, cancel: subscription, setSink: setSink) subscription.disposable = disposable } else { CurrentThreadScheduler.instance.schedule(sink) { sink in let disposable = self.run(observer, cancel: subscription, setSink: setSink) subscription.disposable = disposable return NopDisposable.instance } } return d } public func run<O : ObserverType where O.E == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { return abstractMethod() } }
gpl-3.0
8a7fd44939338b8ddb0409b78a4bf0bb
28.77551
138
0.608368
4.942373
false
false
false
false
dokun1/Lumina
Sources/Lumina/Camera/Extensions/Delegates/FileRecordingExtension.swift
1
2025
// // LuminaCamera+FileOutputRecordingDelegate.swift // Lumina // // Created by David Okun on 11/20/17. // Copyright © 2017 David Okun. All rights reserved. // import Foundation import AVFoundation extension LuminaCamera: AVCaptureFileOutputRecordingDelegate { func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) { DispatchQueue.main.async { if error == nil, let delegate = self.delegate { delegate.videoRecordingCaptured(camera: self, videoURL: outputFileURL) } } } func photoOutput(_ output: AVCapturePhotoOutput, willBeginCaptureFor resolvedSettings: AVCaptureResolvedPhotoSettings) { if self.captureLivePhotos { LuminaLogger.notice(message: "beginning live photo capture") self.delegate?.cameraBeganTakingLivePhoto(camera: self) } } func photoOutput(_ output: AVCapturePhotoOutput, didFinishRecordingLivePhotoMovieForEventualFileAt outputFileURL: URL, resolvedSettings: AVCaptureResolvedPhotoSettings) { if self.captureLivePhotos { LuminaLogger.notice(message: "finishing live photo capture") self.delegate?.cameraFinishedTakingLivePhoto(camera: self) } } //swiftlint:disable function_parameter_count func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingLivePhotoToMovieFileAt outputFileURL: URL, duration: CMTime, photoDisplayTime: CMTime, resolvedSettings: AVCaptureResolvedPhotoSettings, error: Error?) { photoCollectionQueue.sync { if self.currentPhotoCollection == nil { var collection = LuminaPhotoCapture() collection.camera = self collection.livePhotoURL = outputFileURL self.currentPhotoCollection = collection } else { guard var collection = self.currentPhotoCollection else { return } collection.camera = self collection.livePhotoURL = outputFileURL self.currentPhotoCollection = collection } } } }
mit
2955573475d9545ecd70a49515ae5004
37.188679
223
0.740119
5.243523
false
false
false
false
theMatys/myWatch
myWatch/Source/UI/Core/MWTintedImageView.swift
1
5924
// // MWTintedImageView.swift // myWatch // // Created by Máté on 2017. 04. 10.. // Copyright © 2017. theMatys. All rights reserved. // import UIKit @IBDesignable class MWTintedImageView: UIImageView { //MARK: Inspectable variables @IBInspectable private var tintingColor: UIColor = MWDefaults.Colors.defaultTintColor { didSet { MWUtil.execute(ifNotNil: self.image, execution: { self.tintedImage = self.setupTinting(self.image!, self.gradientTinted) self.image = self.tintedImage }, elseExecution: {}) MWUtil.execute(ifNotNil: self.animationImages, execution: { self.tintedAnimationImages = self.setupTinting(self.animationImages!, self.gradientTinted) self.animationImages = self.tintedAnimationImages }, elseExecution: {}) } } @IBInspectable private var gradientTinted: Bool = false { didSet { MWUtil.execute(ifNotNil: self.image, execution: { self.tintedImage = self.setupTinting(self.image!, self.gradientTinted) self.image = self.tintedImage }, elseExecution: {}) MWUtil.execute(ifNotNil: self.animationImages, execution: { self.tintedAnimationImages = self.setupTinting(self.animationImages!, self.gradientTinted) self.animationImages = self.tintedAnimationImages }, elseExecution: {}) } } private var tintingGradient: MWGradient = MWDefaults.Gradients.defaultGradient private var tintedImage: UIImage? private var tintedAnimationImages: [UIImage]? override var image: UIImage? { willSet(newValue) { MWUtil.execute(ifNotNil: newValue, execution: { MWUtil.execute(ifNil: self.tintedImage, execution: { self.tintedImage = self.setupTinting(newValue!, self.gradientTinted) }, elseExecution: { self.tintedImage = nil }) }, elseExecution: {}) } didSet { MWUtil.execute(ifNotNil: tintedImage, execution: { self.image = self.tintedImage }, elseExecution: {}) } } override var animationImages: [UIImage]? { willSet(newValue) { MWUtil.execute(ifNotNil: newValue, execution: { MWUtil.execute(ifNil: self.tintedAnimationImages, execution: { self.tintedAnimationImages = self.setupTinting(newValue!, self.gradientTinted) }, elseExecution: { self.tintedAnimationImages = nil }) }, elseExecution: {}) } didSet { MWUtil.execute(ifNotNil: tintedAnimationImages, execution: { self.animationImages = self.tintedAnimationImages }, elseExecution: {}) } } //MARK: - Instance functions func setTintingColor(_ tintingColor: UIColor) { self.tintingColor = tintingColor } func getTintingColor() -> UIColor { return self.tintingColor } func setTintingGradient(_ tintingGradient: MWGradient) { self.tintingGradient = tintingGradient } func getTintingGradient() -> MWGradient { return self.tintingGradient } func setGradientTinted(_ gradientTinted: Bool) { self.gradientTinted = gradientTinted } func isGradientTinted() -> Bool { return self.gradientTinted } //MARK: Inherited functions from: UIImageView override init(frame: CGRect) { super.init(frame: frame) MWUtil.execute(ifNotNil: self.image) { self.tintedImage = self.setupTinting(self.image!, self.gradientTinted) self.image = self.tintedImage } } override init(image: UIImage?) { super.init(image: image) MWUtil.execute(ifNotNil: self.image) { self.tintedImage = self.setupTinting(self.image!, self.gradientTinted) self.image = self.tintedImage } } override init(image: UIImage?, highlightedImage: UIImage?) { super.init(image: image) MWUtil.execute(ifNotNil: self.image) { self.tintedImage = self.setupTinting(self.image!, self.gradientTinted) self.image = self.tintedImage } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) MWUtil.execute(ifNotNil: self.image) { self.tintedImage = self.setupTinting(self.image!, self.gradientTinted) self.image = self.tintedImage } } //MARK: Private functions private func setupTinting(_ image: UIImage, _ isGradientTinted: Bool) -> UIImage { var ret: UIImage = UIImage() if(isGradientTinted) { MWUtil.execute(ifNotNil: image) { ret = image.gradientTinted(gradient: self.tintingGradient) } } else { MWUtil.execute(ifNotNil: image) { ret = image.tinted(color: self.tintingColor) } } return ret } private func setupTinting(_ imageArray: [UIImage], _ isGradientTinted: Bool) -> [UIImage] { var ret: [UIImage] = [UIImage]() for image in imageArray { if(isGradientTinted) { ret.append(image.gradientTinted(gradient: tintingGradient)) } else { ret.append(image.tinted(color: tintingColor)) } } return ret } }
gpl-3.0
a2ef9af55b56008c347e019be8da5b71
28.02451
106
0.561729
5.21674
false
false
false
false