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
shmidt/ContactsPro
ContactsPro/ContactEditVC.swift
1
17029
// // ContactEditVC.swift // ContactsPro // // Created by Dmitry Shmidt on 17/04/15. // Copyright (c) 2015 Dmitry Shmidt. All rights reserved. // import UIKit import RealmSwift class ContactEditVC: UITableViewController { var person: Person! private lazy var dateFormatter: NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .MediumStyle dateFormatter.timeStyle = .NoStyle return dateFormatter }() override func viewDidLoad() { super.viewDidLoad() tableView.accessibilityLabel = "Edit Contact" tableView.accessibilityValue = person.fullName tableView.isAccessibilityElement = true tableView.tableFooterView = UIView() editing = true title = person.fullName setupTableViewUI() registerFormCells() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "closeVC") } func closeVC(){ dismissViewControllerAnimated(true, completion: nil) } func setupTableViewUI(){ tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension tableView.allowsSelectionDuringEditing = true tableView.keyboardDismissMode = .Interactive } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sectionNames.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let section = indexPath.section switch section{ case Section.Notes: if indexPath.row < person.notes.count{ let note = person.notes[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.EditLongTextCellID, forIndexPath: indexPath) as! EditLongTextTableViewCell cell.label = dateFormatter.stringFromDate(note.date) cell.longText = note.text cell.pick({ (longText) -> Void in if !note.invalidated{ let realm = Realm() realm.beginWrite() note.text = longText realm.commitWrite() } }) return cell }else{ let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.AddButtonCellID, forIndexPath: indexPath) as! AddButtonTableViewCell cell.label.text = "add note" cell.accessibilityLabel = "add note cell" return cell } case Section.WeakPoints: if indexPath.row < person.weakPoints.count{ let note = person.weakPoints[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.EditLongTextCellID, forIndexPath: indexPath) as! EditLongTextTableViewCell cell.longText = note.text cell.label = dateFormatter.stringFromDate(note.date) cell.pick({ (longText) -> Void in if !note.invalidated{ let realm = Realm() realm.beginWrite() note.text = longText realm.commitWrite() } }) return cell }else{ let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.AddButtonCellID, forIndexPath: indexPath) as! AddButtonTableViewCell cell.label.text = "add weak point" cell.accessibilityLabel = "add weak point cell" return cell } case Section.StrongPoints: if indexPath.row < person.strongPoints.count{ let note = person.strongPoints[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.EditLongTextCellID, forIndexPath: indexPath) as! EditLongTextTableViewCell cell.longText = note.text cell.label = dateFormatter.stringFromDate(note.date) cell.pick({ (longText) -> Void in if !note.invalidated{ let realm = Realm() realm.beginWrite() note.text = longText realm.commitWrite() } }) return cell }else{ let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.AddButtonCellID, forIndexPath: indexPath) as! AddButtonTableViewCell cell.label.text = "add strong point" cell.accessibilityLabel = "add strong point cell" return cell } case Section.ToDo: if indexPath.row < person.todos.count{ let todo = person.todos[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.ListItemCell, forIndexPath: indexPath) as! ListItemCell cell.textValue = todo.text cell.isComplete = todo.isComplete cell.pickText({ [unowned self] (text) -> Void in let realm = Realm() realm.beginWrite() if !text.isEmpty{ todo.text = text }else{ //TODO: Delete todo realm.delete(todo) } realm.commitWrite() }) return cell }else{ let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.EditTextCellID, forIndexPath: indexPath) as! EditTextTableViewCell cell.label = "add to do item" cell.accessibilityLabel = "add todo cell" cell.pickText({ [unowned self] (text) -> Void in if !text.isEmpty{ self.addToDo(text: text) } }) return cell } default:() } let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.DefaultCellID, forIndexPath: indexPath) as! UITableViewCell return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var rows = 0 switch section{ case Section.WeakPoints: rows = person.weakPoints.count case Section.StrongPoints: rows = person.strongPoints.count case Section.Notes: rows = person.notes.count case Section.ToDo: rows = person.todos.count default: rows = 0 } return ++rows } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { let section = indexPath.section switch section { case Section.Notes: if editingStyle == .Delete{ let note = person.notes[indexPath.row] // person.notes.removeAtIndex(indexPath.row) let realm = Realm() realm.write({ () -> Void in realm.delete(note) }) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) }else if editingStyle == .Insert{ addNote() } case Section.WeakPoints: if editingStyle == .Delete{ let note = person.weakPoints[indexPath.row] let realm = Realm() realm.write({ () -> Void in realm.delete(note) }) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) }else if editingStyle == .Insert{ addWeakPoint() } case Section.StrongPoints: if editingStyle == .Delete{ let note = person.strongPoints[indexPath.row] let realm = Realm() realm.write({ () -> Void in realm.delete(note) }) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) }else if editingStyle == .Insert{ addStrongPoint() } case Section.ToDo: if editingStyle == .Delete{ let todo = person.todos[indexPath.row] let realm = Realm() realm.write({ () -> Void in realm.delete(todo) }) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) }else if editingStyle == .Insert{ let cell = tableView.cellForRowAtIndexPath(indexPath) as! EditTextTableViewCell addToDo(text: cell.textValue) } default: return } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { println("didSelectRowAtIndexPath") let section = indexPath.section switch section{ case Section.Notes: tableView.deselectRowAtIndexPath(indexPath, animated: false) if editing && indexPath.row == person.notes.count{ addNote() } case Section.StrongPoints: tableView.deselectRowAtIndexPath(indexPath, animated: false) if editing && indexPath.row == person.strongPoints.count{ addStrongPoint() } case Section.WeakPoints: tableView.deselectRowAtIndexPath(indexPath, animated: false) if editing && indexPath.row == person.weakPoints.count{ addWeakPoint() }else{ } default:() } } override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { let section = indexPath.section if editing{ switch section{ case Section.Notes: return indexPath.row < person.notes.count ? .Delete : .Insert case Section.WeakPoints: return indexPath.row < person.weakPoints.count ? .Delete : .Insert case Section.StrongPoints: return indexPath.row < person.strongPoints.count ? .Delete : .Insert case Section.ToDo: return indexPath.row < person.todos.count ? .Delete : .Insert default: return .None } }else { return .None } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if !editing{ switch section{ case Section.Notes: if person.notes.count == 0{ return nil } case Section.StrongPoints: if person.strongPoints.count == 0{ return nil } case Section.WeakPoints: if person.weakPoints.count == 0{ return nil } default: return sectionNames[section] } } return sectionNames[section] } //MARK: - Helpers func addNote(){ let realm = Realm() let note = Note() tableView.beginUpdates() realm.write {[unowned self] () -> Void in realm.add(note) self.person.notes.append(note) } let ip = NSIndexPath(forRow: (person.notes.count - 1), inSection: Section.Notes) tableView.insertRowsAtIndexPaths([ip], withRowAnimation: .Top) tableView.endUpdates() tableView.scrollToRowAtIndexPath(ip, atScrollPosition: .Bottom, animated: true) if let insertedCell = tableView.cellForRowAtIndexPath(ip) as? EditLongTextTableViewCell{ insertedCell.textView.becomeFirstResponder() } } func addStrongPoint(){ let realm = Realm() let note = SimpleNote() tableView.beginUpdates() realm.write {[unowned self] () -> Void in realm.add(note) self.person.strongPoints.append(note) } let ip = NSIndexPath(forRow: (person.strongPoints.count - 1), inSection: Section.StrongPoints) tableView.insertRowsAtIndexPaths([ip], withRowAnimation: .Top) tableView.endUpdates() tableView.scrollToRowAtIndexPath(ip, atScrollPosition: .Bottom, animated: true) let insertedCell = tableView.cellForRowAtIndexPath(ip) as! EditLongTextTableViewCell insertedCell.textView.becomeFirstResponder() } func addWeakPoint(){ let realm = Realm() let note = SimpleNote() tableView.beginUpdates() realm.write {[unowned self] () -> Void in realm.add(note) self.person.weakPoints.append(note) } let ip = NSIndexPath(forRow: (person.weakPoints.count - 1), inSection: Section.WeakPoints) tableView.insertRowsAtIndexPaths([ip], withRowAnimation: .Top) tableView.endUpdates() let newIp = NSIndexPath(forRow: person.weakPoints.count, inSection: Section.WeakPoints) tableView.scrollToRowAtIndexPath(newIp, atScrollPosition: .Bottom, animated: true) let insertedCell = tableView.cellForRowAtIndexPath(ip) as! EditLongTextTableViewCell insertedCell.textView.becomeFirstResponder() } func addToDo(#text:String){ let realm = Realm() let todo = ToDo() tableView.beginUpdates() realm.write {[unowned self] () -> Void in todo.text = text realm.add(todo) self.person.todos.append(todo) } let ip = NSIndexPath(forRow: (person.todos.count - 1), inSection: Section.ToDo) tableView.insertRowsAtIndexPaths([ip], withRowAnimation: .Top) tableView.endUpdates() let newIp = NSIndexPath(forRow: person.todos.count, inSection: Section.ToDo) tableView.scrollToRowAtIndexPath(newIp, atScrollPosition: .Bottom, animated: true) let insertedCell = tableView.cellForRowAtIndexPath(ip) as! ListItemCell } // MARK: - Utilities func registerFormCells(){ //Cells tableView.registerNib(UINib(nibName: Constants.TableViewCell.EditTextCellID, bundle: nil), forCellReuseIdentifier: Constants.TableViewCell.EditTextCellID) tableView.registerNib(UINib(nibName: Constants.TableViewCell.ButtonCellID, bundle: nil), forCellReuseIdentifier: Constants.TableViewCell.ButtonCellID) tableView.registerNib(UINib(nibName: Constants.TableViewCell.LabelTextTableViewCellID, bundle: nil), forCellReuseIdentifier: Constants.TableViewCell.LabelTextTableViewCellID) tableView.registerNib(UINib(nibName: Constants.TableViewCell.EditLongTextCellID, bundle: nil), forCellReuseIdentifier: Constants.TableViewCell.EditLongTextCellID) tableView.registerNib(UINib(nibName: Constants.TableViewCell.AddButtonCellID, bundle: nil), forCellReuseIdentifier: Constants.TableViewCell.AddButtonCellID) tableView.registerNib(UINib(nibName: Constants.TableViewCell.ListCellID, bundle: nil), forCellReuseIdentifier: Constants.TableViewCell.ListCellID) tableView.registerNib(UINib(nibName: Constants.TableViewCell.ListItemCell, bundle: nil), forCellReuseIdentifier: Constants.TableViewCell.ListItemCell) tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: Constants.TableViewCell.DefaultCellID) } func indexPathForView(view: UIView) -> NSIndexPath? { let viewOrigin = view.bounds.origin let viewLocation = tableView.convertPoint(viewOrigin, fromView: view) return tableView.indexPathForRowAtPoint(viewLocation) } }
mit
23e6a3ccd15aba35f8ad0faaa0b1a4e1
37.181614
182
0.576076
5.804022
false
false
false
false
huang1988519/WechatArticles
WechatArticles/WechatArticles/AppDelegate.swift
1
1793
// // AppDelegate.swift // WechatArticles // // Created by hwh on 15/12/6. // Copyright © 2015年 hwh. All rights reserved. // import UIKit //import AVOSCloud import Fabric import Crashlytics var log = Loggerithm() @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { config(launchOptions) return true } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { if MonkeyKing.handleOpenURL(url) { return true } return false } //MARK: -- func config(launchOption: [NSObject: AnyObject]?) { //配置log log.showFunctionName = true log.showDateTime = false log.verboseColor = UIColor.darkGrayColor() //配置 崩溃 日志 Fabric.with([Crashlytics.self]) //配置 leanCloud // AVOSCloud.setApplicationId("qfrsSEumQvfkvyR7gMSXErKg", clientKey: "nTSTQrCGKDFm9zQoexAJHhGW") //配置缓存 ImageCache.defaultCache.calculateDiskCacheSizeWithCompletionHandler { (size) -> () in log.debug("图片缓存 %d M", args: size/1024/1024) } //注册通知 let types : UIUserNotificationType = [.Alert,.Sound,.Badge] UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: types, categories: nil)) //配置 腾讯 bugly CrashReporter.sharedInstance().enableLog(true) CrashReporter.sharedInstance().installWithAppId("900014291") ReportManager.Synchronous() } }
apache-2.0
265c7bfb60457b127a08f63889c4eb63
30.6
136
0.666858
4.411168
false
false
false
false
Chakery/CGYPay
CGYPay/Classes/UPPaySDK/CGYPayUPService.swift
1
1511
// // CGYPayUPService.swift // CGYPay // // Created by Chakery on 16/3/28. // Copyright © 2016年 Chakery. All rights reserved. // // 银联支付 import Foundation public class CGYPayUPService: BaseCGYPay { private var payCallBack: CGYPayCompletedBlock? private static let _sharedInstance = CGYPayUPService() override public class var sharedInstance: CGYPayUPService { return _sharedInstance } override public func sendPay(channel: CGYPayChannel, callBack: CGYPayCompletedBlock) { payCallBack = callBack if case .upPay(let order) = channel { UPPaymentControl.defaultControl().startPay(order.tn, fromScheme: order.appScheme, mode: order.mode, viewController: order.viewController) } } override public func handleOpenURL(url: NSURL) { guard "uppayresult" == url.host else { return } UPPaymentControl.defaultControl().handlePaymentResult(url) { [unowned self] stringCode, resultDic in switch stringCode { case "success": self.payCallBack?(CGYPayStatusCode.PaySuccess(wxPayResult: nil, aliPayResult: nil, upPayResult: resultDic as! [String:AnyObject]?)) case "cancel": self.payCallBack?(CGYPayStatusCode.PayErrCodeUserCancel) case "fail": self.payCallBack?(CGYPayStatusCode.PayErrPayFail) default: self.payCallBack?(CGYPayStatusCode.PayErrUnKnown) } } } }
mit
5a70ee9ff4073f458264b95d7ac16cf9
34.738095
149
0.658
4.054054
false
false
false
false
duliodenis/slappydroid
Slappy Droid/Slappy Droid/GameScene.swift
1
10000
// // GameScene.swift // Slappy Droid // // Created by Dulio Denis on 1/4/16. // Copyright (c) 2016 Dulio Denis. All rights reserved. // import SpriteKit import AVFoundation class GameScene: SKScene, SKPhysicsContactDelegate { // MARK: Scenery Variable & Constants let ASP_PIECES = 15 let SIDEWALK_PIECES = 24 let GROUND_X_RESET: CGFloat = -150 var asphaltPieces = [SKSpriteNode]() var sidewalkPieces = [SKSpriteNode]() var buildings = [SKSpriteNode]() var obstacles = [SKSpriteNode]() // Background Arrays for parallaxing var farBackground = [SKSpriteNode]() var midBackground = [SKSpriteNode]() var nearBackground = [SKSpriteNode]() var backgroundActions = [SKAction]() let BACKGROUND_X_RESET: CGFloat = -912.0 var moveGroundAction: SKAction! var moveGroundActionForever: SKAction! var player: Player! // Audio Player var musicPlayer: AVAudioPlayer! // MARK: Scene Lifecycle override func didMoveToView(view: SKView) { setupBackground() setupGround() setupSidewalk() setupBuildings() setupPlayer() setupGestures() setupDroid() setupWorld() playLevelMusic() } override func update(currentTime: CFTimeInterval) { groundMovement() sidewalkMovement() backgroundMovement() updateChildren() } // call the update function of each child func updateChildren() { for child in children { child.update() } } // MARK: UI Set-up Functions func setupBackground() { for i in 0..<3 { addBackground("bg1", index: i, imageWidth: 400, zPosition: 3, velocity: -2.0) addBackground("bg2", index: i, imageWidth: 450, zPosition: 2, velocity: -1.0) addBackground("bg3", index: i, imageWidth: 500, zPosition: 1, velocity: -0.5) } } func addBackground(imageName: String!, index: Int, imageWidth: CGFloat, zPosition: CGFloat, velocity: CGFloat) { let background = SKSpriteNode(imageNamed: imageName) background.position = CGPointMake(CGFloat(index) * background.size.width, imageWidth) background.zPosition = zPosition let action: SKAction = SKAction.repeatActionForever(SKAction.moveByX(velocity, y: 0, duration: 0.02)) background.runAction(action) backgroundActions.append(action) addChild(background) if imageName == "bg1" { nearBackground.append(background) } if imageName == "bg2" { midBackground.append(background) } if imageName == "bg3" { farBackground.append(background) } } func setupGround() { moveGroundAction = SKAction.moveByX(GameManager.sharedInstance.MOVEMENT_SPEED, y: 0, duration: 0.02) moveGroundActionForever = SKAction.repeatActionForever(moveGroundAction) for x in 0..<ASP_PIECES { let asp = SKSpriteNode(imageNamed: "asphalt") // Add a static physics body as a ground collider let groundCollider = SKPhysicsBody(rectangleOfSize: CGSizeMake(asp.size.width, 5), center: CGPointMake(0, -20)) groundCollider.dynamic = false asp.physicsBody = groundCollider asphaltPieces.append(asp) if x == 0 { // if its the first one then start at the bottom left let start = CGPointMake(0, 144) asp.position = start } else { // otherwise, position it appropriately asp.position = CGPointMake(asp.size.width + asphaltPieces[x - 1].position.x, asphaltPieces[x - 1].position.y) } asp.runAction(moveGroundActionForever) addChild(asp) } } func setupSidewalk() { for x in 0..<SIDEWALK_PIECES { let piece = SKSpriteNode(imageNamed: "sidewalk") sidewalkPieces.append(piece) if x == 0 { // if its the first one then start at the bottom left let start = CGPointMake(0, 190) piece.position = start } else { // otherwise, position it appropriately piece.position = CGPointMake(piece.size.width + sidewalkPieces[x - 1].position.x, sidewalkPieces[x - 1].position.y) } piece.zPosition = 4 piece.runAction(moveGroundActionForever) addChild(piece) } } func setupBuildings() { for i in 0..<3 { let wait = SKAction.waitForDuration(2.0 * Double(i)) runAction(wait, completion: { () -> Void in let building = Building() self.buildings.append(building) self.addChild(building) building.startMoving() }) } } func setupPlayer() { player = Player() addChild(player) } func setupDroid() { let droid = Droid() let droidTop = DroidTop() // Add a top to the Droid so we can land on it and jump off of it droidTop.position = CGPointMake(droid.position.x, droid.position.y + 40) droid.startMoving() droidTop.startMoving() addChild(droid) addChild(droidTop) obstacles.append(droid) obstacles.append(droidTop) } // do any world environmental variable setting func setupWorld() { physicsWorld.gravity = CGVectorMake(0, -10) physicsWorld.contactDelegate = self } // MARK: Ground Function func groundMovement() { for x in 0..<ASP_PIECES { if asphaltPieces[x].position.x <= GROUND_X_RESET { var index: Int! if x == 0 { index = asphaltPieces.count - 1 } else { index = x - 1 } let newPosition = CGPointMake(asphaltPieces[index].position.x + asphaltPieces[x].size.width, asphaltPieces[x].position.y) asphaltPieces[x].position = newPosition } } } func sidewalkMovement() { for x in 0..<SIDEWALK_PIECES { if sidewalkPieces[x].position.x <= GROUND_X_RESET { var index: Int! if x == 0 { index = sidewalkPieces.count - 1 } else { index = x - 1 } let newPosition = CGPointMake(sidewalkPieces[index].position.x + sidewalkPieces[x].size.width, sidewalkPieces[x].position.y) sidewalkPieces[x].position = newPosition } } } func backgroundMovement() { for i in 0..<3 { setPosition(farBackground, index: i, resetValue: BACKGROUND_X_RESET) setPosition(midBackground, index: i, resetValue: BACKGROUND_X_RESET) setPosition(nearBackground, index: i, resetValue: BACKGROUND_X_RESET) } } func setPosition(imageArray: [SKSpriteNode], index: Int, resetValue: CGFloat) { if imageArray[index].position.x <= resetValue { var i: Int! if index == 0 { i = imageArray.count - 1 } else { i = index - 1 } let newPosition = CGPointMake(imageArray[i].position.x + imageArray[index].size.width, imageArray[index].position.y) imageArray[index].position = newPosition } } // MARK: Gesture Recognizer Functions func setupGestures() { let tap = UITapGestureRecognizer(target: self, action: "tapped:") tap.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)] view?.addGestureRecognizer(tap) } func tapped(gesture: UIGestureRecognizer) { player.jump() } // MARK: Collision Handling func didBeginContact(contact: SKPhysicsContact) { if contact.bodyA.categoryBitMask == GameManager.sharedInstance.COLLIDER_OBSTACLE || contact.bodyB.categoryBitMask == GameManager.sharedInstance.COLLIDER_OBSTACLE { removeAllActions() // Crash Animation player.playCrashAnimation() // Stop the music musicPlayer.stop() // Play the Crash Sound runAction(SKAction.playSoundFileNamed("gameover.wav", waitForCompletion: false)) // Stop the moving ground for node in asphaltPieces { node.removeAllActions() } for node in sidewalkPieces { node.removeAllActions() } // Stop the moving backgrounds for i in 0..<3 { farBackground[i].removeAllActions() midBackground[i].removeAllActions() nearBackground[i].removeAllActions() } // Stop the obstacles for obstacle in obstacles { obstacle.removeAllActions() } // Stop the Moving Buildings for building in buildings { building.removeAllActions() } } } // MARK: Audio Function func playLevelMusic() { let levelMusicURL = NSBundle.mainBundle().URLForResource("level", withExtension: "wav")! do { musicPlayer = try AVAudioPlayer(contentsOfURL: levelMusicURL) musicPlayer.numberOfLoops = -1 // infinite play musicPlayer.prepareToPlay() musicPlayer.play() } catch { } } }
mit
16804cbc326026eebb42c01c89322700
30.545741
140
0.5546
4.935834
false
false
false
false
silan-liu/SLSwitchAnimation
SLSwitchAnimation/Source/SLSwitchView.swift
1
7899
// // SLSwitchView.swift // SLSwitchAnimation // // Created by silan on 16/5/28. // Copyright © 2016年 summer-liu. All rights reserved. // import Foundation import UIKit class SLSwitchView: UIButton { var faceLayer: SLFaceLayer! var faceBgLayer: CALayer! var isAnimating: Bool = false let margin: CGFloat = 5 var isOn: Bool = false let onColor = UIColor(red: 73/255.0, green: 182/255.0, blue: 235/255.0, alpha: 1) let offColor = UIColor(red: 211/255.0, green: 207/255.0, blue: 207/255.0, alpha: 1) override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { self.clipsToBounds = true self.backgroundColor = offColor self.layer.cornerRadius = self.frame.size.height / 2 self.addTarget(self, action: #selector(SLSwitchView.switchStatus), forControlEvents: .TouchUpInside) initFaceBgLayer() initFaceView() } private func initFaceBgLayer() { let width = self.frame.size.height - 2 * margin faceBgLayer = CALayer() faceBgLayer.frame = CGRectMake(margin, margin, width, width) faceBgLayer.cornerRadius = width / 2 faceBgLayer.masksToBounds = true faceBgLayer.backgroundColor = UIColor.whiteColor().CGColor layer.addSublayer(faceBgLayer) } private func initFaceView() { faceLayer = SLFaceLayer() faceLayer.frame = faceBgLayer.bounds faceLayer.onColor = onColor faceLayer.offColor = offColor faceLayer.isOn = isOn faceLayer.mouthOffset = faceBgLayer.bounds.size.width / 2 faceBgLayer.addSublayer(faceLayer) faceLayer.setNeedsDisplay() } private func positionOfFaceView(on: Bool) -> CGPoint { let width = self.frame.size.height - 2 * margin if on { return CGPointMake(self.frame.size.width - margin - width + width / 2, margin + width / 2) } else { return CGPointMake(margin + width / 2, margin + width / 2) } } func switchStatus() { guard isAnimating == false else { return } isAnimating = true if isOn { moveLeftAnimation() } else { moveRightAnimation() } faceBgLayerAnimation() backgroundAnimation() } // MARK: animations func faceBgLayerAnimation() { let positionAnimation = CABasicAnimation(keyPath: "position.x") positionAnimation.duration = 0.5 positionAnimation.fromValue = positionOfFaceView(isOn).x positionAnimation.toValue = positionOfFaceView(!isOn).x positionAnimation.delegate = self positionAnimation.setValue("faceBgLayerAnimation", forKey: "animation") positionAnimation.removedOnCompletion = false positionAnimation.fillMode = kCAFillModeForwards; faceBgLayer.addAnimation(positionAnimation, forKey: "positionAnimation") } // bgColor func backgroundAnimation() { let backgroundAnimation = CABasicAnimation(keyPath: "backgroundColor") backgroundAnimation.duration = 0.5 backgroundAnimation.fromValue = isOn ? onColor.CGColor : offColor.CGColor backgroundAnimation.toValue = isOn ? offColor.CGColor : onColor.CGColor backgroundAnimation.delegate = self backgroundAnimation.setValue("backgroundAnimation", forKey: "animation") backgroundAnimation.removedOnCompletion = false backgroundAnimation.fillMode = kCAFillModeForwards; self.layer.addAnimation(backgroundAnimation, forKey: "background") } func moveRightAnimation() { let positionAnimation = CABasicAnimation(keyPath: "position.x") positionAnimation.duration = 0.3 positionAnimation.fromValue = faceLayer.position.x positionAnimation.toValue = faceLayer.position.x + faceLayer.frame.size.width positionAnimation.delegate = self positionAnimation.setValue("moveAnimation", forKey: "animation") positionAnimation.removedOnCompletion = false positionAnimation.fillMode = kCAFillModeForwards; faceLayer.addAnimation(positionAnimation, forKey: "positionAnimation") } func moveLeftAnimation() { let positionAnimation = CABasicAnimation(keyPath: "position.x") positionAnimation.duration = 0.3 positionAnimation.fromValue = faceLayer.position.x positionAnimation.toValue = faceLayer.position.x - faceLayer.frame.size.width positionAnimation.delegate = self positionAnimation.setValue("moveAnimation", forKey: "animation") positionAnimation.removedOnCompletion = false positionAnimation.fillMode = kCAFillModeForwards; faceLayer.addAnimation(positionAnimation, forKey: "positionAnimation") } func moveRightBackAnimation() { let animation = CAKeyframeAnimation(keyPath: "position.x") animation.duration = 0.5 animation.values = [faceLayer.position.x - faceLayer.frame.size.width, faceLayer.position.x + faceLayer.frame.size.width / 6, faceLayer.position.x] animation.delegate = self animation.setValue("moveBackAnimation", forKey: "animation") faceLayer.addAnimation(animation, forKey: "positionAnimation") } func moveLeftBackAnimation() { let animation = CAKeyframeAnimation(keyPath: "position.x") animation.duration = 0.5 animation.values = [faceLayer.position.x + faceLayer.frame.size.width, faceLayer.position.x - faceLayer.frame.size.width / 6, faceLayer.position.x] animation.delegate = self animation.setValue("moveBackAnimation", forKey: "animation") faceLayer.addAnimation(animation, forKey: "positionAnimation") } func mouthAnimation(on: Bool, offset: CGFloat) { let animation1 = CABasicAnimation(keyPath: "mouthOffset") animation1.duration = 0.5 animation1.fromValue = on ? offset : 0 animation1.toValue = on ? 0 : offset faceLayer.addAnimation(animation1, forKey: "mouthAnimation") } override func animationDidStop(anim: CAAnimation, finished flag: Bool) { if flag { if let type = anim.valueForKey("animation") as? String { // 脸盘移动到端点 if type == "faceBgLayerAnimation" { faceBgLayer.removeAllAnimations() faceBgLayer.position = positionOfFaceView(!isOn) faceLayer.isOn = !isOn faceLayer.mouthOffset = !isOn ? faceLayer.bounds.size.width / 2 : 0 faceLayer.setNeedsDisplay() if (!isOn) { mouthAnimation(isOn, offset: faceLayer.bounds.size.width / 2) moveRightBackAnimation() } else { moveLeftBackAnimation() } } else if type == "backgroundAnimation" { self.backgroundColor = isOn ? onColor : offColor } else if type == "moveBackAnimation" { faceLayer.removeAllAnimations() isOn = !isOn isAnimating = false } } } } }
mit
783ecacdc9da2ec0f4489961e038ae5d
32.688034
155
0.602893
5.158377
false
false
false
false
Acumen004/MovieTime
Movies/DetailedImageViewVC.swift
1
1434
// // FavouritesVC.swift // Movies // // Created by Appinventiv on 17/02/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit import AlamofireImage class DetailedImageViewVC: UIViewController { //MARK: variables var url: URL! var nextPoint = CGPoint(x: 0, y: 0) //MARK: outlets @IBOutlet weak var detailedImage: UIImageView! @IBOutlet weak var imageLabel: UILabel! //MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() detailedImage.af_setImage(withURL: url) let pan = UIPanGestureRecognizer(target: self, action: #selector(translateImage)) self.detailedImage.addGestureRecognizer(pan) //detailedImage.isUserInteractionEnabled = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } //translate image on pan func translateImage(gesture: UIPanGestureRecognizer){ nextPoint = gesture.translation(in: detailedImage) switch gesture.state { case .began: print("gesture begins") case .changed: detailedImage.transform = CGAffineTransform(translationX: nextPoint.x, y: nextPoint.y) case .ended: print("gesture ended") default: print("default") } } }
mit
afb20c9124917eea9c67c21b1ac14e04
24.140351
109
0.612701
4.993031
false
false
false
false
osorioabel/my-location-app
My Locations/My Locations/Controllers/LocationsViewController.swift
1
7302
// // LocationsViewController.swift // My Locations // // Created by Abel Osorio on 2/17/16. // Copyright © 2016 Abel Osorio. All rights reserved. // import UIKit import CoreData import CoreLocation class LocationsViewController: UITableViewController { var managedObjectContext: NSManagedObjectContext! lazy var fetchedResultsController: NSFetchedResultsController = { let fetchRequest = NSFetchRequest() let entity = NSEntityDescription.entityForName("Location", inManagedObjectContext: self.managedObjectContext) fetchRequest.entity = entity let sortDescriptor1 = NSSortDescriptor(key: "category", ascending: true) let sortDescriptor2 = NSSortDescriptor(key: "date", ascending: true) fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2] fetchRequest.fetchBatchSize = 20 let fetchedResultsController = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: "category", cacheName: "Locations") fetchedResultsController.delegate = self return fetchedResultsController }() deinit { fetchedResultsController.delegate = nil } override func viewDidLoad() { super.viewDidLoad() performFetch() navigationItem.rightBarButtonItem = editButtonItem() tableView.backgroundColor = UIColor.blackColor() tableView.separatorColor = UIColor(white: 1.0, alpha: 0.2) tableView.indicatorStyle = .White } func performFetch() { do { try fetchedResultsController.performFetch() } catch { fatalCoreDataError(error) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "EditLocation" { let navigationController = segue.destinationViewController as! UINavigationController let controller = navigationController.topViewController as! LocationDetailsViewController controller.managedObjectContext = managedObjectContext if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell) { let location = fetchedResultsController.objectAtIndexPath(indexPath) as! Location controller.locationToEdit = location } } } // MARK: - UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return fetchedResultsController.sections!.count } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let sectionInfo = fetchedResultsController.sections![section] return sectionInfo.name.uppercaseString } override func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int { let sectionInfo = fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("LocationCell", forIndexPath: indexPath) as! LocationCell let location = fetchedResultsController.objectAtIndexPath(indexPath) as! Location cell.configureForLocation(location) return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let location = fetchedResultsController.objectAtIndexPath(indexPath) as! Location location.removePhotoFile() managedObjectContext.deleteObject(location) do { try managedObjectContext.save() } catch { fatalCoreDataError(error) } } } // MARK: - UITableViewDelegate override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let labelRect = CGRect(x: 15, y: tableView.sectionHeaderHeight - 14, width: 300, height: 14) let label = UILabel(frame: labelRect) label.font = UIFont.boldSystemFontOfSize(11) label.text = tableView.dataSource!.tableView!(tableView, titleForHeaderInSection: section) label.textColor = UIColor(white: 1.0, alpha: 0.4) label.backgroundColor = UIColor.clearColor() let separatorRect = CGRect(x: 15, y: tableView.sectionHeaderHeight - 0.5, width: tableView.bounds.size.width - 15, height: 0.5) let separator = UIView(frame: separatorRect) separator.backgroundColor = tableView.separatorColor let viewRect = CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.sectionHeaderHeight) let view = UIView(frame: viewRect) view.backgroundColor = UIColor(white: 0, alpha: 0.85) view.addSubview(label) view.addSubview(separator) return view } } extension LocationsViewController: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(controller: NSFetchedResultsController) { tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: if let cell = tableView.cellForRowAtIndexPath(indexPath!) as? LocationCell { let location = controller.objectAtIndexPath(indexPath!) as! Location cell.configureForLocation(location) } case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) } } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Update: print("*** NSFetchedResultsChangeUpdate (section)") case .Move: print("*** NSFetchedResultsChangeMove (section)") } } func controllerDidChangeContent(controller: NSFetchedResultsController) { tableView.endUpdates() } }
mit
100019a0ec7f7e6e92ab918a976f9e31
38.042781
211
0.664293
6.283133
false
false
false
false
dasdom/Jupp
PostToADN/RequestFactory.swift
1
4111
// // RequestFactory.swift // Jupp // // Created by dasdom on 10.08.14. // Copyright (c) 2014 Dominik Hauser. All rights reserved. // import UIKit public class RequestFactory { public init() { } public class func postRequestFromPostText(postText: String, linksArray: [[String:String]], accessToken:String, imageDict: [String:AnyObject]? = nil, replyTo: Int? = nil) -> NSURLRequest { let urlString = "https://api.app.net/posts?include_post_annotations=1" let url = NSURL(string: urlString) let postRequest = NSMutableURLRequest(URL: url!) let authorizationString = "Bearer " + accessToken; postRequest.addValue(authorizationString, forHTTPHeaderField: "Authorization") postRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") postRequest.HTTPMethod = "POST" //TODO: Add case when posting links and image. (see hAppy) var postDictionary = Dictionary<String, AnyObject>() var alteredPostTest = postText if let imageDict = imageDict { alteredPostTest += "\n" alteredPostTest += "photos.app.net/{post_id}/1" let imageAnnotationDict: [String:String] = ["file_id": imageDict["id"] as! String, "file_token": imageDict["file_token"] as! String, "format": "oembed"] let annotationValueDict: [String:AnyObject] = ["+net.app.core.file": imageAnnotationDict] let annotationDict: [String:AnyObject] = ["type": "net.app.core.oembed", "value" : annotationValueDict] postDictionary["annotations"] = [annotationDict] } postDictionary["text"] = alteredPostTest if replyTo != nil { postDictionary["reply_to"] = replyTo } postDictionary["entities"] = ["links": linksArray, "parse_links": true] print("postDictionary \(postDictionary)") var error: NSError? = nil let postData: NSData? do { postData = try NSJSONSerialization.dataWithJSONObject(postDictionary, options: []) } catch let error1 as NSError { error = error1 postData = nil } print(error) postRequest.HTTPBody = postData return postRequest } public class func imageUploadRequest(image: UIImage, accessToken: String) -> NSURLRequest { let imageData = UIImageJPEGRepresentation(image, 0.3) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy_MM_dd'T'HH_mm_ss'Z'" let imageName = "\(dateFormatter.stringFromDate(NSDate()))" let imageUploadRequest = NSMutableURLRequest(URL: NSURL(string: "https://alpha-api.app.net/stream/0/files")!) let authorizationString = "Bearer " + accessToken; imageUploadRequest.addValue(authorizationString, forHTTPHeaderField: "Authorization") imageUploadRequest.HTTPMethod = "POST" let boundary = "82481319dca6" let contentType = "multipart/form-data; boundary=\(boundary)" imageUploadRequest.addValue(contentType, forHTTPHeaderField: "Content-Type") let postBody = NSMutableData() postBody.appendData("\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) postBody.appendData("Content-Disposition: form-data; name=\"content\"; filename=\"\(imageName).jpg\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) postBody.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) postBody.appendData(imageData!) postBody.appendData("\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) postBody.appendData("Content-Disposition: form-data; name=\"type\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) postBody.appendData("de.dasdom.jupp.photo".dataUsingEncoding(NSUTF8StringEncoding)!) imageUploadRequest.HTTPBody = postBody return imageUploadRequest } }
mit
61e3d5e125acc8ef2b7c47dc56b122ad
40.959184
191
0.640477
4.687571
false
false
false
false
bencochran/SpringExperiment
Bouncy/TupleArithmetic.swift
1
3294
// // TupleArithmetic.swift // Bouncy // // Created by Ben Cochran on 9/12/15. // Copyright © 2015 Ben Cochran. All rights reserved. // import Foundation /// A “private” protocol that allows for conversion of values into a two-value tuple. /// This is used so standard types (`CGPoint`, `CGRect`, etc) can conform to `SpringArithmeticType` /// using some protocol extensions to reduce the need for duplicate code. public protocol _TwoTupleable { typealias First: SpringArithmeticType typealias Second: SpringArithmeticType var twoTuple: _TwoTuple<First, Second> { get } init(twoTuple: _TwoTuple<First, Second>) } extension _TwoTupleable { /// Combine the tuple with another tuple, applying the `firstTransform` /// and `secondTransform` to their first and second values, respectively. /// /// Essentially: `(First,Second) + (First,Second) -> (A,B)` where `+` /// represents the application of two functions `(First, First) -> A` /// and `(Second, Second) -> B`. /// private func combineWith<Other: _TwoTupleable, A, B, Result: _TwoTupleable where Other.First == Self.First, Other.Second == Self.Second, Result.First == A, Result.Second == B> (other: Other, firstTransform: (Self.First, Self.First) -> A, secondTransform: (Self.Second, Self.Second) -> B) -> Result { let tuple = self.twoTuple let otherTuple = other.twoTuple let newTuple = tuple.combineWith(otherTuple, firstTransform: firstTransform, secondTransform: secondTransform) return Result(twoTuple: newTuple) } } public struct _TwoTuple<First,Second> { var first: First var second: Second internal init(_ first: First, _ second: Second) { self.first = first self.second = second } private func combineWith<A,B>( other: _TwoTuple<First, Second>, firstTransform: (First, First) -> A, secondTransform: (Second, Second) -> B) -> _TwoTuple<A,B> { let first = firstTransform(self.first, other.first) let second = secondTransform(self.second, other.second) return _TwoTuple<A,B>(first, second) } } public func *<T: _TwoTupleable>(lhs: T, rhs: T) -> T { return lhs.combineWith(rhs, firstTransform: *, secondTransform: *) } public func /<T: _TwoTupleable>(lhs: T, rhs: T) -> T { return lhs.combineWith(rhs, firstTransform: /, secondTransform: /) } public func +<T: _TwoTupleable>(lhs: T, rhs: T) -> T { return lhs.combineWith(rhs, firstTransform: +, secondTransform: +) } public func -<T: _TwoTupleable>(lhs: T, rhs: T) -> T { return lhs.combineWith(rhs, firstTransform: -, secondTransform: -) } public func <<T: _TwoTupleable>(lhs: T, rhs: T) -> Bool { let leftTuple = lhs.twoTuple let rightTuple = rhs.twoTuple let newTuple = leftTuple.combineWith(rightTuple, firstTransform: <, secondTransform: <) return newTuple.first && newTuple.second } extension _TwoTupleable { public static func abs(value: Self) -> Self { var tuple = value.twoTuple tuple.first = Self.First.abs(tuple.first) tuple.second = Self.Second.abs(tuple.second) return Self(twoTuple: tuple) } }
bsd-3-clause
fc4fbf33b5a8ae5d4345ad216f0c6188
34.365591
118
0.643661
3.71219
false
false
false
false
tise/SwipeableViewController
SwipeableViewController/ExampleViewController.swift
1
2308
// // ExampleViewController.swift // SwipingViewController // // Created by Oscar Apeland on 12.10.2017. // Copyright © 2017 Tise. All rights reserved. // import UIKit class ExampleViewController: UIViewController { lazy var collectionView: UICollectionView = { $0.backgroundColor = .white $0.alwaysBounceVertical = true $0.delegate = self $0.dataSource = self $0.autoresizingMask = [.flexibleHeight, .flexibleWidth] ($0.collectionViewLayout as? UICollectionViewFlowLayout)?.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0) return $0 }(UICollectionView(frame: view.bounds, collectionViewLayout: UICollectionViewFlowLayout())) let cellColor = UIColor.random override func viewDidLoad() { super.viewDidLoad() view.addSubview(collectionView) if #available(iOS 11.0, *) { collectionView.contentInsetAdjustmentBehavior = .always } } } extension ExampleViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 100 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell") let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) cell.backgroundColor = cellColor return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let vc = UICollectionViewController(collectionViewLayout: UICollectionViewFlowLayout()) vc.collectionView?.backgroundColor = .white vc.collectionView?.dataSource = self vc.collectionView?.delegate = self navigationController?.pushViewController(vc, animated: true) } } extension UIColor { class var random: UIColor { func random() -> CGFloat { return CGFloat(arc4random()) / CGFloat(UInt32.max) } return UIColor(red: random(), green: random(), blue: random(), alpha: 1.0) } }
mit
fecfc4049141554e292f430955402f9a
33.954545
132
0.678804
5.47981
false
false
false
false
JohnSundell/SwiftKit
Source/Shared/CGPoint+SwiftKit.swift
1
2078
import CoreGraphics /// SwiftKit extensions to CGPoint public extension CGPoint { /// Return the distance (in form of a vector) between this point and another public func distanceToPoint(point: CGPoint) -> CGVector { return CGVector(dx: point.x - self.x, dy: point.y - self.y) } /// Return a new point by offsetting this point by a x and y value public func pointOffsetByX(x: CGFloat, y: CGFloat) -> CGPoint { return CGPoint(x: self.x + x, y: self.y + y) } /// Return a new point by offsetting this point with a vector public func pointOffsetBy(vector: CGVector) -> CGPoint { return CGPoint(x: self.x + vector.dx, y: self.y + vector.dy) } /// Return a new point by multiplying this point's x and y values by a factor public func pointMultipliedByX(x: CGFloat, y: CGFloat) -> CGPoint { return CGPoint(x: self.x * x, y: self.y * y) } /// Return a new point that is the result of moving this point a certain distance in a direction public func pointAtDistance<T: DirectionType>(distance: CGFloat, inDirection direction: T, coordinateSystem: CoordinateSystem, integral: Bool = true) -> CGPoint { var verticalDistance = distance * cos(direction.radianValue) if coordinateSystem.incrementalVerticalDirection == .Down { verticalDistance = -verticalDistance } let decimalCount = UInt(integral ? 0 : 3) return CGPoint( x: (self.x + distance * sin(direction.radianValue)).roundedValueWithDecimalCount(decimalCount), y: (self.y + verticalDistance).roundedValueWithDecimalCount(decimalCount) ) } /// Return a new point by finding the closest point in a grid given a certain tile size, assuming a {0, 0} origo public func closestPointInGridWithTileSize(tileSize: CGSize) -> CGPoint { return CGPoint( x: round(self.x / tileSize.width) * tileSize.width, y: round(self.y / tileSize.height) * tileSize.height ) } }
mit
f885ed984399373200816abda3e8d8ab
42.3125
166
0.650626
4.311203
false
false
false
false
Szaq/Grower
Grower/Simulator.swift
1
8871
// // Simulator.swift // Grower // // Created by Lukasz Kwoska on 10/12/14. // Copyright (c) 2014 Spinal Development. All rights reserved. // import Foundation import SwiftCL import OpenCL func time2str(time:CFTimeInterval) -> String { let hours = Int(time) / 3600 let minutes = (Int(time) / 60) % 60 let seconds = Int(time) % 60 return [(hours, "h"), (minutes, "m"), (seconds, "s")].reduce("", combine: { previous, current in current.0 > 0 ? "\(previous)\(current.0)\(current.1)" : previous }) } class Simulator { let queue: CommandQueue! let renderKernel: Kernel! let tonemapKernel: Kernel! let positions: Buffer<Float>! let materials: Memory! let outputBuffer: Buffer<Float>! let pixels: Buffer<UInt8>! let width: cl_int let height: cl_int var samples: cl_int = 0 var samplesInLastReport: cl_int = 0 let simulationStatTime: CFTimeInterval var statsHandler:((String)->Void)? init?(width:Int, height:Int) { self.width = cl_int(width) self.height = cl_int(height) self.simulationStatTime = CACurrentMediaTime() if let context = Context( fromType: CL_DEVICE_TYPE_GPU, properties: nil, errorHandler: errorHandler("Context")) { if let queue = CommandQueue( context: context, device: nil, properties: 0, errorHandler: errorHandler("CommandQueue")) { self.queue = queue let headers = ["prng.cl", "intersections.h", "shading.h", "common.h", "ray.h"]; let headerPrograms = toDictionary(headers) { name -> (String, Program)? in if let program = Program( context: context, loadFromMainBundle: name, compilationType: .None, errorHandler: self.errorHandler("Header load")) { return (name, program) } return nil } if let program = Program( context: context, loadFromMainBundle: "pathtrace.cl", compilationType: .None, errorHandler: errorHandler("Program")) { if program.compile( devices: nil, options: nil, headers: headerPrograms, errorHandler: errorHandler("Compile")) { let buildInfo = program.getBuildInfo(context.getInfo().deviceIDs[0]) if let program = linkPrograms(context, [program], options: nil, devices: nil, errorHandler: errorHandler("Link")) { let buildInfo = program.getBuildInfo(context.getInfo().deviceIDs[0]) if let kernel = Kernel(program: program, name: "render", errorHandler: errorHandler("Kernel")) { self.renderKernel = kernel } if let kernel = Kernel(program: program, name: "tonemap", errorHandler: errorHandler("Kernel")) { self.tonemapKernel = kernel } } } } if let buffer = Buffer<UInt8>( context: context, count: Int(width * height * 4), readOnly: false, errorHandler: errorHandler("Pixels buffer")) { pixels = buffer } if let buffer = Buffer<Float>( context: context, copyFrom: [cl_float](count:Int(width * height * 4), repeatedValue:0.0), readOnly: false, errorHandler: errorHandler("Output buffer")) { outputBuffer = buffer } if let buffer = Buffer<Float>( context: context, copyFrom: [ -1000020, 0, 0, 1000000, 0, -1000010, 0, 1000000, 0, 0, -1000001, 1000000, 1000020, 0, 0, 1000000, 0, 0, 1000040, 1000000, 0,1,30,3, 0,-6,30,4, 10,-2,30,5, -1,-4,20,4, 0, 1000015, 0, 1000000, 0,12,30,2, ], readOnly: true, errorHandler: errorHandler("Positions buffer")) { positions = buffer } if let materials = serializeToMemory([ Material(color: (0.75, 0, 0, 1), type: .Diffuse, IOR: 1.2, roughness:0, dummy: 0), Material(color: (0.75, 0.75, 0.75, 1), type: .Diffuse, IOR: 1.2, roughness:0, dummy: 0), Material(color: (0.75, 0.75, 0.75, 1), type: .Diffuse, IOR: 1.2, roughness:0, dummy: 0), Material(color: (0, 0.75, 0, 1), type: .Diffuse, IOR: 1.2, roughness:0, dummy: 0), Material(color: (0.75, 0.75, 0.75, 1), type: .Diffuse, IOR: 1.2, roughness:0, dummy: 0), Material(color: (0, 0.5, 0.75, 1), type: .Diffuse, IOR: 1.2, roughness:0, dummy: 0), Material(color: (0.75, 0.75, 0.75, 1), type: .Diffuse, IOR: 0.1, roughness:0.3, dummy: 0), Material(color: (2.0, 2.0, 2.0, 1), type: .Glossy, IOR: 10, roughness:0.1, dummy: 0), Material(color: (1, 0.75, 0.2, 1), type: .Transparent, IOR: 1.5, roughness:0, dummy: 0), Material(color: (0.75, 0.75, 0.75, 1), type: .Emitter, IOR: 1.2, roughness:0, dummy: 0), Material(color: (1, 1, 1, 1), type: .Diffuse, IOR: 0.0, roughness:0, dummy: 0) ], context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, errorHandler: errorHandler("Materials buffer")) { self.materials = materials } if (renderKernel != nil && positions != nil && pixels != nil && outputBuffer != nil && materials != nil) { return } } } return nil } func step() -> Bool { for i in 0..<10 { let randSeed = samples + i if let kernel = renderKernel.setArgs(width, height, randSeed, outputBuffer, cl_int(positions.objects.count / 4), positions, materials, errorHandler: errorHandler("Prepare kernel")) { let result = queue.enqueue(kernel, globalWorkSize: [UInt(width), UInt(height)]) if result != CL_SUCCESS { errorHandler("Kernel enqueue")(result: result) return false } } } samples += 10 return true } func currentImage() -> NSImage? { let samplesCount = max(samples, 1) if let kernel = tonemapKernel.setArgs(width, height, samplesCount, pixels, outputBuffer, errorHandler: errorHandler("Tonemap")) { if queue.enqueue(kernel, globalWorkSize: [UInt(width), UInt(height)]) != CL_SUCCESS { return nil } if queue.enqueueRead(pixels) != CL_SUCCESS { return nil } } if let bitmap = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(width), pixelsHigh: Int(height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bitmapFormat: NSBitmapFormat.NSAlphaNonpremultipliedBitmapFormat, bytesPerRow:Int(4 * width), bitsPerPixel: 32) { memcpy(bitmap.bitmapData, pixels.data, UInt(width * height * 4)); let image = NSImage() image.addRepresentation(bitmap) return image } return nil } func reportStats() { let timeStart = CACurrentMediaTime() dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1000000000), dispatch_get_main_queue()) { let timePassed = CACurrentMediaTime() - timeStart; let samplesSinceLastReport = self.samples - self.samplesInLastReport self.samplesInLastReport = self.samples let msamplesPerSec = Float(samplesSinceLastReport * self.width * self.height) / Float(timePassed * 1000000) let samplesPerPixel = Float(self.samples) let time = time2str(CACurrentMediaTime() - self.simulationStatTime) let stats = "[\(time)]\t \(msamplesPerSec) MS/sec\t\(samplesPerPixel) S/px" println(stats) if let statsHandler = self.statsHandler { statsHandler(stats) } self.reportStats(); } } func errorHandler(label:String)(param:Int32, result:cl_int) { println("\(label) error for param \(param): \(result)") } func errorHandler(label:String)(result:cl_int) { println("\(label) error: \(result)") } func errorHandler(label:String)(result: cl_int, desc: String) { println("\(label) error: \(result): \(desc)") } }
mit
96c704e4b87b7b7589ecf252053c6cc8
36.277311
148
0.539285
4.190364
false
false
false
false
MartinOSix/DemoKit
dOC/JavaScriptCoreDemo/JavaScriptCoreDemo/ViewController.swift
1
4492
// // ViewController.swift // JavaScriptCoreDemo // // Created by runo on 17/7/10. // Copyright © 2017年 com.runo. All rights reserved. // import UIKit import JavaScriptCore import ExternalAccessory let kScreenBounds = UIScreen.main.bounds let kScreenWidth = UIScreen.main.bounds.size.width let kScreenHeight = UIScreen.main.bounds.size.height class ViewController: UIViewController { let eaManager = EAAccessoryManager.shared() let label = UILabel() override func viewDidLoad() { super.viewDidLoad() label.frame = kScreenBounds self.view.addSubview(label) eaManager.registerForLocalNotifications() //EAAccessoryDidConnect DispatchQueue.global().async { let connectAcc = self.eaManager.connectedAccessories; var infoStr = "info: " for ea in connectAcc { for pro in ea.protocolStrings{ infoStr.append("protocolStr=\(pro)\n") } infoStr.append("manufacturer=\(ea.manufacturer)") infoStr.append("name=\(ea.name)") infoStr.append("modelNumber=\(ea.modelNumber)") infoStr.append("serialNumber=\(ea.serialNumber)") infoStr.append("firmwareRevision=\(ea.firmwareRevision)") infoStr.append("hardwareRevision=\(ea.hardwareRevision)") infoStr.append("dockType=\(ea.dockType)") } print(infoStr) DispatchQueue.main.async { self.label.text = infoStr } } NotificationCenter.default.addObserver(self, selector: #selector(getConnect), name: NSNotification.Name.init("EAAccessoryDidConnect"), object: nil) } func getConnect() { DispatchQueue.global().async { let connectAcc = self.eaManager.connectedAccessories; var infoStr = "info: " for ea in connectAcc { for pro in ea.protocolStrings{ infoStr.append("protocolStr=\(pro)\n") } infoStr.append("manufacturer=\(ea.manufacturer)") infoStr.append("name=\(ea.name)") infoStr.append("modelNumber=\(ea.modelNumber)") infoStr.append("serialNumber=\(ea.serialNumber)") infoStr.append("firmwareRevision=\(ea.firmwareRevision)") infoStr.append("hardwareRevision=\(ea.hardwareRevision)") infoStr.append("dockType=\(ea.dockType)") } print(infoStr) DispatchQueue.main.async { self.label.text = infoStr } } self.view.backgroundColor = UIColor.red; } func test() { //self.swiftUseJSFun() //self.swiftUseJS() //self.jsCallBlock() //安全性理解 let person: [String: String] = ["name":"haha"] print(type(of: person["name"])) let users:[String] = ["haha","haha1","haha2"] print(type(of: users[2])) } func swiftUseJSFun() { let jsCode = "function hello(say){ return say+\"abc\"; }" let jsContext = JSContext.init() _ = jsContext?.evaluateScript(jsCode) let jsFun = jsContext?.objectForKeyedSubscript("hello") let jsvalue = jsFun?.call(withArguments: ["1234"]) print(jsvalue) } func swiftUseJS() { let jsCode = "var num = \"this is js code\"" let jsContext = JSContext() _ = jsContext?.evaluateScript(jsCode) let jsValue = jsContext?.objectForKeyedSubscript("num") print(jsValue) } func jsCallBlock() { let jsCtx = JSContext() let swiftClosure:(@convention(block) (String) -> Void)? = { (abc: String)->Void in { print("这是\(abc) 写的方法") }() } let swiftAnyObject = unsafeBitCast(swiftClosure, to: AnyObject.self) //将swift闭包转换成js jsCtx?.setObject(swiftAnyObject, forKeyedSubscript: "eat" as (NSCopying & NSObjectProtocol)!) //使用js的方式调用闭包方法 let jsvalue = jsCtx?.objectForKeyedSubscript("eat") _ = jsvalue?.call(withArguments: ["嘎嘎嘎"]) } }
apache-2.0
25cf3a5281c417adeb6a8e11954f8b11
30.621429
155
0.551163
4.71459
false
false
false
false
stripe/stripe-ios
StripeCardScan/StripeCardScan/Source/CardScan/MLRuntime/NMS.swift
1
2304
// // NMS.swift // CardScan // // Created by Zain on 8/6/19. // import CoreGraphics import Foundation import os.log struct NMS { static func hardNMS( subsetBoxes: [[Float]], probs: [Float], iouThreshold: Float, topK: Int, candidateSize: Int ) -> [Int] { /// * I highly recommend checkout SOFT NMS Implementation of Facebook Detectron Framework /// * /// * Args: /// * subsetBoxes (N, 4): boxes in corner-form and probabilities. /// * iouThreshold: intersection over union threshold. /// * topK: keep topK results. If k <= 0, keep all the results. /// * candidateSize: only consider the candidates with the highest scores. /// * /// * Returns: /// * pickedIndices: a list of indexes of the kept boxes let sorted = probs.enumerated().sorted(by: { $0.element > $1.element }) var indices = sorted.map { $0.offset } var current: Int = 0 var currentBox = [Float]() var pickedIndices = [Int]() if indices.count > 200 { // TODO Fix This indices = Array(indices[0..<200]) os_log("Exceptional Situation more than 200 candiates found", type: .error) } while indices.count > 0 { current = indices.remove(at: 0) pickedIndices.append(current) if topK > 0 && topK == pickedIndices.count { break } currentBox = subsetBoxes[current] let currentBoxRect = CGRect( x: Double(currentBox[0]), y: Double(currentBox[1]), width: Double(currentBox[2] - currentBox[0]), height: Double(currentBox[3] - currentBox[1]) ) indices.removeAll(where: { currentBoxRect.iou( nextBox: CGRect( x: Double(subsetBoxes[$0][0]), y: Double(subsetBoxes[$0][1]), width: Double(subsetBoxes[$0][2] - subsetBoxes[$0][0]), height: Double(subsetBoxes[$0][3] - subsetBoxes[$0][1]) ) ) >= iouThreshold }) } return pickedIndices } }
mit
744e4a90fb11807c8321f3398faf1d37
29.72
97
0.509115
4.25878
false
false
false
false
luzefeng/MLSwiftBasic
MLSwiftBasic/Classes/Base/MBNavigationBarView.swift
2
7727
// github: https://github.com/MakeZL/MLSwiftBasic // author: @email <[email protected]> // // MBNavigationBarView.swift // MakeBolo // // Created by 张磊 on 15/6/22. // Copyright (c) 2015年 MakeZL. All rights reserved. // import UIKit protocol MBNavigationBarViewDelegate:NSObjectProtocol{ func goBack() } class MBNavigationBarView: UIView { var titleImage,leftImage,rightImage:String! var rightTitleBtns:NSMutableArray = NSMutableArray() var delegate:MBNavigationBarViewDelegate! var rightItemWidth:CGFloat{ set{ if (self.rightTitleBtns.count > 0 || self.rightImgs.count > 0) { var count = self.rightTitleBtns.count ?? self.rightImgs.count for (var i = 0; i < count; i++){ if var button = self.rightTitleBtns[i] as? UIButton ?? self.rightImgs[i] as? UIButton { button.frame.size.width = newValue var x = self.frame.size.width - newValue * CGFloat(i) - newValue button.frame = CGRectMake(x, NAV_BAR_Y, newValue, NAV_BAR_HEIGHT) ; } } }else { self.rightButton.frame.size.width = newValue self.rightButton.frame.origin.x = self.frame.size.width - newValue } } get{ return self.rightItemWidth } } var leftItemWidth:CGFloat { set{ } get{ return self.leftItemWidth } } var title:String{ set { self.titleButton.setTitle(newValue, forState: .Normal) } get { if (self.titleButton.currentTitle != nil) { return self.titleButton.currentTitle! }else{ return "" } } } var leftStr:String{ set { self.leftButton.setTitle(newValue, forState: .Normal) } get { if (self.leftButton.currentTitle != nil) { return self.leftButton.currentTitle! }else{ return "" } } } var rightImgs:NSArray{ set{ var allImgs = newValue.reverseObjectEnumerator().allObjects for (var i = 0; i < allImgs.count; i++){ var rightButton = UIButton.buttonWithType(.Custom) as! UIButton rightButton.tag = i rightButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal) var x = self.frame.size.width - CGFloat(NAV_ITEM_RIGHT_W) * CGFloat(i) - NAV_ITEM_LEFT_W rightButton.setImage(UIImage(named: allImgs[i] as! String), forState: .Normal) rightButton.frame = CGRectMake(x, NAV_BAR_Y, NAV_ITEM_RIGHT_W, NAV_BAR_HEIGHT) ; rightButton.titleLabel?.font = NAV_ITEM_FONT self.addSubview(rightButton) rightTitleBtns.addObject(rightButton) } if (newValue.count > 1){ self.titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_RIGHT_W * CGFloat((2 + newValue.count)) } } get{ return ( rightTitleBtns != false && rightTitleBtns.count > 0) ? rightTitleBtns: [] } } var rightTitles:NSArray{ set{ for (var i = 0; i < newValue.count; i++){ var rightButton = UIButton.buttonWithType(.Custom) as! UIButton rightButton.tag = i rightButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal) var x = self.frame.size.width - CGFloat(NAV_ITEM_LEFT_W) * CGFloat(i) - NAV_ITEM_RIGHT_W rightButton.setTitle(newValue[i] as! NSString as String, forState: .Normal) rightButton.frame = CGRectMake(x, NAV_BAR_Y, NAV_ITEM_RIGHT_W, NAV_BAR_HEIGHT) ; rightButton.titleLabel?.font = NAV_ITEM_FONT self.addSubview(rightButton) self.rightTitleBtns.addObject(rightButton) } if (newValue.count > 1){ self.titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_RIGHT_W * CGFloat((2 + newValue.count)) } } get{ return ( rightTitleBtns != false && rightTitleBtns.count > 0) ? rightTitleBtns: [] } } var rightStr:String{ set { self.rightButton.setTitle(newValue, forState: .Normal) } get { if (self.rightButton.currentTitle != nil) { return self.rightButton.currentTitle! }else{ return "" } } } var titleButton:UIButton{ get{ var titleButton = UIButton.buttonWithType(.Custom) as! UIButton titleButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal) titleButton.frame = CGRectMake(NAV_ITEM_LEFT_W, NAV_BAR_Y, self.frame.size.width - NAV_ITEM_RIGHT_W - NAV_ITEM_LEFT_W, NAV_BAR_HEIGHT); if (self.rightTitles.count > 1){ titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_RIGHT_W * CGFloat((2 + self.rightTitles.count)) titleButton.frame.origin.x = CGFloat(self.frame.size.width - titleButton.frame.size.width) * 0.5 } titleButton.titleLabel?.font = NAV_TITLE_FONT self.addSubview(titleButton) return titleButton } } var leftButton:UIButton{ get{ var leftButton = UIButton.buttonWithType(.Custom) as! UIButton leftButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal) leftButton.frame = CGRectMake(0, NAV_BAR_Y, NAV_ITEM_LEFT_W, NAV_BAR_HEIGHT); leftButton.titleLabel?.font = NAV_ITEM_FONT self.addSubview(leftButton) return leftButton } } lazy var rightButton:UIButton = { var rightButton = UIButton.buttonWithType(.Custom) as! UIButton rightButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal) rightButton.frame = CGRectMake(self.frame.size.width - NAV_ITEM_RIGHT_W, NAV_BAR_Y, NAV_ITEM_RIGHT_W, NAV_BAR_HEIGHT) ; rightButton.titleLabel?.font = NAV_ITEM_FONT self.addSubview(rightButton) return rightButton }() var back:Bool{ set{ if (newValue && (count(self.leftStr) <= 0 && self.leftStr.isEmpty)) { var backBtn = UIButton.buttonWithType(.Custom) as! UIButton backBtn.setTitleColor(NAV_TEXT_COLOR, forState: .Normal) backBtn.setImage(UIImage(named: BACK_NAME), forState: .Normal) backBtn.titleLabel!.textAlignment = .Left backBtn.frame = CGRectMake(0, NAV_BAR_Y, NAV_ITEM_LEFT_W, NAV_BAR_HEIGHT); backBtn.addTarget(self, action:"goBack", forControlEvents: .TouchUpInside) self.addSubview(backBtn) } } get{ return self.back } } func goBack(){ if self.delegate.respondsToSelector(Selector("goBack")) { self.delegate.goBack() } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } required override init(frame: CGRect) { super.init(frame: frame) self.setup() } func setup(){ } }
mit
95f3e50dc486e2ec99d3de61302e8444
32.720524
147
0.540863
4.520492
false
false
false
false
VernonVan/SmartClass
SmartClass/AppDelegate.swift
1
13018
// // AppDelegate.swift // SmartClass // // Created by Vernon on 16/2/28. // Copyright © 2016年 Vernon. All rights reserved. // import UIKit import RealmSwift import GCDWebServer import IQKeyboardManager @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let webUploader = GCDWebUploader(uploadDirectory: ConvenientFileManager.uploadURL.path) var webUploaderURL: URL? { return self.webUploader?.serverURL } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { ConvenientFileManager.createInitDirectory() print(ConvenientFileManager.documentURL().path) initUI() UIApplication.shared.isIdleTimerDisabled = true addHandlerForWebUploader() webUploader?.start() return true } func initUI() { UITextView.appearance().tintColor = ThemeGreenColor UITextField.appearance().tintColor = ThemeGreenColor IQKeyboardManager.shared().isEnabled = true } func addHandlerForWebUploader() { // 发送试卷列表给Web端 webUploader?.addHandler(forMethod: "GET", path: "/getPaperList", request: GCDWebServerRequest.self) { (request, completionBlock) in DispatchQueue.global(qos: .default).async(execute: { let issuingPapers = self.getIssuingPaperList() let response = GCDWebServerDataResponse(data: issuingPapers, contentType: "") completionBlock!(response) }) } // 接收确认学生的请求并返回是否是我的学生的确认信息给Web端 webUploader?.addHandler(forMethod: "POST", path: "/confirmID", request: GCDWebServerDataRequest.self) { (request, completionBlock) in DispatchQueue.global(qos: .default).async(execute: { if let dataRequest = request as? GCDWebServerDataRequest { var stuentInformationDict: NSDictionary? do { stuentInformationDict = try JSONSerialization.jsonObject(with: dataRequest.data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary } catch let error as NSError { print("AppDelegate confirmID error: \(error)") } guard let _ = stuentInformationDict, let studentName = stuentInformationDict!["student_name"] as? String, let studentNumber = stuentInformationDict!["student_number"] as? String else { completionBlock!(GCDWebServerDataResponse(statusCode: 204)) return } let isMyStudent = self.confirmStudentName(studentName, number: studentNumber) do { let responseData = try JSONSerialization.data(withJSONObject: ["isMyStudent": isMyStudent], options: JSONSerialization.WritingOptions.prettyPrinted) completionBlock!(GCDWebServerDataResponse(data: responseData, contentType: "")) } catch let error as NSError { print("AppDelegate confirmID error: \(error)") } } else { completionBlock!(GCDWebServerDataResponse(statusCode: 204)) } }) } // 接收某份试卷的请求并返回该试卷的json数据给Web端 webUploader?.addHandler(forMethod: "POST", path: "/TestPage/HTML/requestPaper", request: GCDWebServerDataRequest.self) { (request, completionBlock) in if let dataRequest = request as? GCDWebServerDataRequest { var paperNameDict: NSDictionary? do { paperNameDict = try JSONSerialization.jsonObject(with: dataRequest.data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary } catch let error as NSError { print("AppDelegate requestPaper error: \(error)") } guard let _ = paperNameDict, let paperName = paperNameDict!["name"] as? String else { completionBlock!(GCDWebServerDataResponse(statusCode: 204)) return } let paperData = self.getPaperJsonWithName(paperName) completionBlock!(GCDWebServerDataResponse(data: paperData, contentType: "")) } else { completionBlock!(GCDWebServerDataResponse(statusCode: 204)) } } // 接收学生考试的答题情况 webUploader?.addHandler(forMethod: "POST", path: "/TestPage/HTML/resultData", request: GCDWebServerDataRequest.self) { (request, completionBlock) in if let dataRequest = request as? GCDWebServerDataRequest { do { if let paperResultDict = try JSONSerialization.jsonObject(with: dataRequest.data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary { self.addPaperResultForDict(paperResultDict) } } catch let error as NSError { print("AppDelegate addHandlerForWebUploader error: \(error)") } completionBlock!(GCDWebServerDataResponse(statusCode: 200)) } else { completionBlock!(GCDWebServerDataResponse(statusCode: 204)) } } // 接收学生提问 webUploader?.addHandler(forMethod: "POST", path: "/haveQuestion", request: GCDWebServerDataRequest.self) { (request, completionBlock) in if let dataRequest = request as? GCDWebServerDataRequest { do { if let questionDict = try JSONSerialization.jsonObject(with: dataRequest.data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary { print("接收到学生提问: \(questionDict)") let realm = try! Realm() try! realm.write { let quiz = Quiz(value: ["content": questionDict["question"], "name": questionDict["name"], "date": NSDate()]) realm.add(quiz) } } } catch let error as NSError { print("AppDelegate addHandlerForWebUploader error: \(error)") } completionBlock!(GCDWebServerDataResponse(statusCode: 200)) } else { completionBlock!(GCDWebServerDataResponse(statusCode: 204)) } } // 导入学生名单 webUploader?.addHandler(forMethod: "POST", path: "/studentList", request: GCDWebServerDataRequest.self) { (request, completionBlock) in if let dataRequest = request as? GCDWebServerDataRequest { do { if let studentListDict = try JSONSerialization.jsonObject(with: dataRequest.data, options: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary { print("接收到学生名单: \(studentListDict)") self.importStudentList(studentListDict: studentListDict) } } catch let error as NSError { print("AppDelegate addHandlerForWebUploader error: \(error)") } completionBlock!(GCDWebServerDataResponse(statusCode: 200)) } else { completionBlock!(GCDWebServerDataResponse(statusCode: 204)) } } // 发送直播网址给网页 webUploader?.addHandler(forMethod: "GET", path: "/getLiveAddress", request: GCDWebServerRequest.self) { (request, completionBlock) in DispatchQueue.global(qos: .default).async(execute: { let liveAddress = "http://w.gdou.com/?ppt_\(self.getTodaysDate())" let data = try! JSONSerialization.data(withJSONObject: ["isLiving": false, "address": liveAddress], options: JSONSerialization.WritingOptions.prettyPrinted) let response = GCDWebServerDataResponse(data: data, contentType: "") completionBlock!(response) }) } } func getTodaysDate() -> String { let date = Date() let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd" return formatter.string(from: date) } // 将所有发布中的试卷组织成NSData func getIssuingPaperList() -> Data { let paperArray = NSMutableArray() let realm = try! Realm() let issuingPapers = realm.objects(Paper.self).filter("state == 1") for paper in issuingPapers { paperArray.add(["name": paper.name, "blurb": paper.blurb]) } var paperData: Data! do { paperData = try JSONSerialization.data(withJSONObject: ["papers": paperArray], options: JSONSerialization.WritingOptions.prettyPrinted) } catch let error as NSError { print("AppDelegate getIssuingPaperList error: \(error)") } return paperData } // 确定该学生是否是我的学生 func confirmStudentName(_ name: String, number: String) -> Bool { let realm = try! Realm() if let _ = realm.objects(Student.self).filter("name = '\(name)' AND number = '\(number)'").first { return true } return false } // 将试卷的信息封装为NSData func getPaperJsonWithName(_ name: String) -> Data { let paperUrl = ConvenientFileManager.paperURL.appendingPathComponent(name) return (try! Data(contentsOf: paperUrl)) } // 添加学生的考试结果 func addPaperResultForDict(_ paperResultDict: NSDictionary) { print("学生成绩: \(paperResultDict)") guard let paperName = paperResultDict["paper_name"] as? String, let studentName = paperResultDict["student_name"] as? String, let studentNumber = paperResultDict["student_number"] as? String, let score = paperResultDict["score"] as? Int, let correctQuestions = paperResultDict["result"] as? NSArray else { print("解析失败") return } let realm = try! Realm() guard let paper = realm.objects(Paper.self).filter("name == '\(paperName)'").first else { return } if paper.state == 1 { let result = paper.results.filter("number == '\(studentNumber)'").first if result?.name == studentName { print("学号: \(studentNumber)姓名: \(studentName)的学生已经提交过试卷了,不能重复提交") return } try! realm.write { let result = Result(value: ["name": studentName, "number": studentNumber, "score": score]) for i in 0..<correctQuestions.count-2 { let questionNumber = QuestionNumber(value: ["number": correctQuestions[i]]) result.correctQuestionNumbers.append(questionNumber) } print("Result: \(result)") paper.results.append(result) } } } // 导入学生名单 func importStudentList(studentListDict: NSDictionary) { guard let table = studentListDict["table"] as? NSArray else { fatalError("导入学生名单失败") } var newStudents = [Student]() for tempStudent in table { guard let studentDict = tempStudent as? NSDictionary, let number = studentDict["学号"] as? String, let name = studentDict["姓名"] as? String, let school = studentDict["学校"] as? String, let major = studentDict["专业"] as? String else { fatalError("导入学生名单失败") } // print("学号: \(number)\t姓名: \(name)\t学校: \(school)\t专业: \(major)") if newStudents.filter({ $0.number == number }).count == 0 { let student = Student(value: ["number": number, "name": name, "major": major, "school": school]) newStudents.append(student) } } let realm = try! Realm() try! realm.write({ // 删除所有已有的学生 let oldStudents = realm.objects(Student.self) realm.delete(oldStudents) // 添加新的学生 for student in newStudents { realm.add(student) } }) print("导入学生名单成功,共导入\(newStudents.count)名学生") } }
mit
d6b1f6212bf2a53d656ce55b33e2eda7
42.224138
204
0.581252
5.143619
false
false
false
false
samsymons/Photon
Photon/Parsing/OBJParser.swift
1
3056
// OBJParser.swift // Copyright (c) 2017 Sam Symons // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public enum OBJParserError: Error { case emptyFile case malformedFile } private enum OBJLineType: String { case vertex = "v" case textureCoordinate = "vt" case normal = "vn" case faceElement = "f" } public final class OBJParser { // MARK: - Initialization public init() {} // MARK: - Parser public func load(file: URL, material: Material) throws -> Mesh { return Mesh(triangles: []) } public func parse(string: String) throws -> Mesh { guard !string.isEmpty else { throw OBJParserError.emptyFile } let scanner = Scanner(string: string) var stringResult: NSString? var vertices: [Vector3D] = [] var normals: [Vector3D] = [] var textureCoordinates: [Vector3D] = [] var triangles: [Triangle] = [] while scanner.scanUpToCharacters(from: CharacterSet.newlines, into: &stringResult) { guard let unwrappedResult = stringResult else { continue } let components = unwrappedResult.components(separatedBy: .whitespaces).filter { !$0.isEmpty } guard let firstComponent = components.first, let lineType = OBJLineType(rawValue: firstComponent) else { continue } let tailComponents = components.dropFirst() switch lineType { case .vertex: let floatValues = tailComponents.map { Float($0)! } vertices.append(Vector3D(floatValues)) case .normal: let floatValues = tailComponents.map { Float($0)! } normals.append(Vector3D(floatValues)) case .textureCoordinate: let floatValues = tailComponents.map { Float($0)! } textureCoordinates.append(Vector3D(floatValues)) case .faceElement: let indices = tailComponents.map { Int($0)! } let mappedVertices = indices.map { vertices[$0 - 1] } triangles.append(Triangle(material: Material.redMaterial, vertices: mappedVertices)) } } return Mesh(triangles: triangles) } }
mit
b08c7c828722f565b644a931f0e7657c
35.380952
121
0.706479
4.334752
false
false
false
false
KoheiHayakawa/KHATableViewWithSeamlessScrollingHeaderView
KHATableViewWithSeamlessScrollingHeaderViewDemo/KHATableViewWithSeamlessScrollingHeaderViewDemo/MusicBlackViewController.swift
1
3091
// // MusicBlackViewController.swift // KHATableViewWithSeamlessScrollingHeaderViewDemo // // Created by Kohei Hayakawa on 12/25/15. // Copyright © 2015 Kohei Hayakawa. All rights reserved. // import UIKit import KHATableViewWithSeamlessScrollingHeaderView class MusicCustomColorViewController: KHATableViewWithSeamlessScrollingHeaderViewController { private let songs: NSArray = [ "1. 20th Century Fox Fanfare", "2. Main Title/Rebel Blockade Runner", "3. Imperial Attack", "4. The Dune Sea of Tatooine/Jawa Sandcrawler", "5. The Moisture Farm", "6. The Hologram/Binary Sunset", "7. Landspeeder Search/Attack Of The Sand People", "8. Tales of a Jedi Knight/Learn About the Force", "9. Burning Homestead", "10. Mos Eisley Spaceport", "11. Cantina Band", "12. Cantina Band #2", "13. Archival Bonus Track: Binary Sunset (Alternate)", "1. Princess Leia's Theme", "2. The Millennium Falcon/Imperial Cruiser Pursuit", "3. Destruction of Alderaan", "4. The Death Star/The Stormtroopers", "5. Wookie Prisoner/Detention Block Ambush", "6. Shootout in the Cell Bay/Dianoga", "7. The Trash Compactor", "8. The Tractor Beam/Chasm Crossfire", "9. Ben Kenobi's Death/Tie Fighter Attack", "10. The Battle of Yavin", "11. The Throne Room/End Title"] override func viewDidLoad() { super.viewDidLoad() title = "Star Wars IV: A New Hope" navigationController?.navigationBar.tintColor = UIColor.whiteColor() navigationBarTitleColor = UIColor.whiteColor() navigationBarBackgroundColor = UIColor.blackColor() navigationBarShadowColor = UIColor.lightGrayColor() tableView.backgroundColor = UIColor.blackColor() tableView.indicatorStyle = .White statusBarStyle = .LightContent navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "addTapped") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func headerViewInView(view: KHATableViewWithSeamlessScrollingHeaderViewController) -> UIView { return UINib(nibName: "MusicBlackHeaderView", bundle: nil).instantiateWithOwner(self, options: nil)[0] as! UIView } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.songs.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("id", forIndexPath: indexPath) cell.textLabel?.text = "\(self.songs[indexPath.row])" cell.textLabel?.font = UIFont(name: "HelveticaNeue-Light", size: 16.0) cell.textLabel?.textColor = UIColor.whiteColor() cell.backgroundColor = UIColor.blackColor() return cell } }
mit
aa8336c33bbed3bf21d3646395204575
38.628205
124
0.667638
4.426934
false
false
false
false
tlax/looper
looper/Model/Camera/Compress/MCameraCompressItemMax.swift
1
880
import UIKit class MCameraCompressItemMax:MCameraCompressItem { private let kResize:CGFloat = 0.6 private let kQuality:CGFloat = 0.1 private let kPercent:Int = 10 private let kRemoveInterval:Int = 3 init() { let title:String = NSLocalizedString("MCameraCompressItemMax_title", comment:"") let color:UIColor = UIColor(red:0.9, green:0, blue:0, alpha:1) super.init(title:title, percent:kPercent, color:color) } override func compress(record:MCameraRecord) -> MCameraRecord? { let removeRecord:MCameraRecord = removeInterItems( record:record, intervalRemove:kRemoveInterval) let lowerQuality:MCameraRecord = lowerImageQuality( record:removeRecord, quality:kQuality, resize:kResize) return lowerQuality } }
mit
dd105d09a240ee2abfc44206e1ce8504
28.333333
88
0.642045
4.251208
false
false
false
false
xu6148152/binea_project_for_ios
Bouncer Settings/Bouncer/ViewController.swift
1
1745
// // ViewController.swift // Bouncer // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: - Animation Behavior Setup let bouncer = BouncerBehavior() lazy var animator: UIDynamicAnimator = { UIDynamicAnimator(referenceView: self.view) }() override func viewDidLoad() { super.viewDidLoad() animator.addBehavior(bouncer) } // MARK: - View Controller Lifecycle override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if redBlock == nil { redBlock = addBlock() redBlock?.backgroundColor = UIColor.redColor() bouncer.addBlock(redBlock!) } let motionManager = AppDelegate.Motion.Manager if motionManager.accelerometerAvailable { motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) { (data, error) -> Void in self.bouncer.gravity.gravityDirection = CGVector(dx: data.acceleration.x, dy: -data.acceleration.y) } } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) AppDelegate.Motion.Manager.stopAccelerometerUpdates() } // MARK: - Blocks var redBlock: UIView? func addBlock() -> UIView { let block = UIView(frame: CGRect(origin: CGPoint.zeroPoint, size: Constants.BlockSize)) block.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY) view.addSubview(block) return block } struct Constants { static let BlockSize = CGSize(width: 40, height: 40) } }
mit
cbe6848e88f60fc27d1bf29229faa383
28.083333
115
0.641261
4.754768
false
false
false
false
Draveness/Kernel
Kernel/AppDelegate.swift
1
2568
// // AppDelegate.swift // Kernel // // Created by Draveness on 15/8/8. // Copyright (c) 2015年 Draveness. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Override point for customization after application launch. self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() let vc = UIViewController() self.window?.rootViewController = vc let aView = UIView(frame: CGRect(width: 10, height: 10)) aView.backgroundColor = UIColor.blackColor() vc.view.addSubview(aView) aView.top = 200 return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
dd27e0a16c1e30693d3c0b294640fb52
44.017544
285
0.735386
5.390756
false
false
false
false
jakub-tucek/fit-checker-2.0
fit-checker/networking/EduxValidators.swift
1
3831
// // EduxValidators.swift // fit-checker // // Created by Josef Dolezal on 20/01/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import Foundation import Alamofire struct EduxValidators { /// Shared validator constants struct Constants { /// If verifier is contained in HTML response, user is logged in static let loginHTMLVerifier = tr(.htmlLogoutVerifier) /// If verifier is contained in JSON response, user is logged in static let loginJSONVerifier = tr(.jsonLogoutVerifier) } /// Possible edux validation errors /// /// - generalError: Unrecognized error during request processing /// - badCredentials: Given user credentials are not valid (thrown at login) /// - unauthorized: User is not logged in enum ValidationError: Error { case generalError case badCredentials case unauthorized } /// Validates if login request was successfull. It uses authorizedHTML /// validator under the hood but returns different error. /// Usualy used only to check if cookies was obtained successfully. /// /// - Parameters: /// - request: Original request /// - response: Server response /// - data: Response body /// - Returns: Failure if request did not contained valid credentials static func validCredentials(request: URLRequest?, response: HTTPURLResponse, data: Data?) -> Request.ValidationResult { let result = authorizedHTML(request: request, response: response, data: data) switch result { case .success: return result case .failure: return .failure(ValidationError.badCredentials) } } /// Checks whether user is logged in (for HTML requests only). /// Used for common HTML requests, not user authorization. /// If you use it during authorization, you could make /// infinite requests calling. Use this validator if you want /// your request to be retriable. /// /// - Parameters: /// - request: Original URL request /// - response: Server response /// - data: Response data /// - Returns: Failure if login was not successfull, success otherwise static func authorizedHTML(request: URLRequest?, response: HTTPURLResponse, data: Data?) -> Request.ValidationResult { return dataContainsVerifier(data: data, verifier: Constants.loginHTMLVerifier) } /// Checks whether user is logged in (for JSON requests only) /// /// - Parameters: /// - request: Original URL request /// - response: Server response /// - data: Response data /// - Returns: Failure if login was not successfull, success otherwise static func authorizedJSON(request: URLRequest?, response: HTTPURLResponse, data: Data?) -> Request.ValidationResult { return dataContainsVerifier(data: data, verifier: Constants.loginJSONVerifier) } /// Checks if response containts verifier /// /// - Parameters: /// - data: Response body /// - verifier: Verifier which should be in body /// - Returns: .success if validator is presented, .failure otherwise private static func dataContainsVerifier(data: Data?, verifier: String) -> Request.ValidationResult { guard // This is legit since both JSON and HTML // response should have body and the body // should be representable by string let data = data, let html = String(data: data, encoding: .utf8) else { return .failure(ValidationError.generalError) } return html.contains(verifier) ? .success : .failure(ValidationError.badCredentials) } }
mit
17297d52ed0a928c7139d522169c1874
33.504505
80
0.642298
5.006536
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RxSwift/RxSwift/Deprecated.swift
14
29746
// // Deprecated.swift // RxSwift // // Created by Krunoslav Zaher on 3/5/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import Foundation extension Observable { /** Converts a optional to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter optional: Optional element in the resulting observable sequence. - returns: An observable sequence containing the wrapped value or not from given optional. */ @available(*, deprecated, message: "Implicit conversions from any type to optional type are allowed and that is causing issues with `from` operator overloading.", renamed: "from(optional:)") public static func from(_ optional: Element?) -> Observable<Element> { return Observable.from(optional: optional) } /** Converts a optional to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter optional: Optional element in the resulting observable sequence. - parameter scheduler: Scheduler to send the optional element on. - returns: An observable sequence containing the wrapped value or not from given optional. */ @available(*, deprecated, message: "Implicit conversions from any type to optional type are allowed and that is causing issues with `from` operator overloading.", renamed: "from(optional:scheduler:)") public static func from(_ optional: Element?, scheduler: ImmediateSchedulerType) -> Observable<Element> { return Observable.from(optional: optional, scheduler: scheduler) } } extension ObservableType { /** Projects each element of an observable sequence into a new form by incorporating the element's index. - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) - parameter selector: A transform function to apply to each source element; the second parameter of the function represents the index of the source element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. */ @available(*, deprecated, message: "Please use enumerated().map()") public func mapWithIndex<Result>(_ selector: @escaping (Element, Int) throws -> Result) -> Observable<Result> { return self.enumerated().map { try selector($0.element, $0.index) } } /** Projects each element of an observable sequence to an observable sequence by incorporating the element's index and merges the resulting observable sequences into one observable sequence. - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) - parameter selector: A transform function to apply to each element; the second parameter of the function represents the index of the source element. - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. */ @available(*, deprecated, message: "Please use enumerated().flatMap()") public func flatMapWithIndex<Source: ObservableConvertibleType>(_ selector: @escaping (Element, Int) throws -> Source) -> Observable<Source.Element> { return self.enumerated().flatMap { try selector($0.element, $0.index) } } /** Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. The element's index is used in the logic of the predicate function. - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) - parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element. - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ @available(*, deprecated, message: "Please use enumerated().skipWhile().map()") public func skipWhileWithIndex(_ predicate: @escaping (Element, Int) throws -> Bool) -> Observable<Element> { return self.enumerated().skipWhile { try predicate($0.element, $0.index) }.map { $0.element } } /** Returns elements from an observable sequence as long as a specified condition is true. The element's index is used in the logic of the predicate function. - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) - parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element. - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ @available(*, deprecated, message: "Please use enumerated().takeWhile().map()") public func takeWhileWithIndex(_ predicate: @escaping (Element, Int) throws -> Bool) -> Observable<Element> { return self.enumerated().takeWhile { try predicate($0.element, $0.index) }.map { $0.element } } } extension Disposable { /// Deprecated in favor of `disposed(by:)` /// /// /// Adds `self` to `bag`. /// /// - parameter bag: `DisposeBag` to add `self` to. @available(*, deprecated, message: "use disposed(by:) instead", renamed: "disposed(by:)") public func addDisposableTo(_ bag: DisposeBag) { self.disposed(by: bag) } } extension ObservableType { /** Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays latest element in buffer. This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ @available(*, deprecated, message: "use share(replay: 1) instead", renamed: "share(replay:)") public func shareReplayLatestWhileConnected() -> Observable<Element> { return self.share(replay: 1, scope: .whileConnected) } } extension ObservableType { /** Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays maximum number of elements in buffer. This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - parameter bufferSize: Maximum element count of the replay buffer. - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ @available(*, deprecated, message: "Suggested replacement is `share(replay: 1)`. In case old 3.x behavior of `shareReplay` is required please use `share(replay: 1, scope: .forever)` instead.", renamed: "share(replay:)") public func shareReplay(_ bufferSize: Int) -> Observable<Element> { return self.share(replay: bufferSize, scope: .forever) } } /// Variable is a wrapper for `BehaviorSubject`. /// /// Unlike `BehaviorSubject` it can't terminate with error, and when variable is deallocated /// it will complete its observable sequence (`asObservable`). /// /// **This concept will be deprecated from RxSwift but offical migration path hasn't been decided yet.** /// https://github.com/ReactiveX/RxSwift/issues/1501 /// /// Current recommended replacement for this API is `RxCocoa.BehaviorRelay` because: /// * `Variable` isn't a standard cross platform concept, hence it's out of place in RxSwift target. /// * It doesn't have a counterpart for handling events (`PublishRelay`). It models state only. /// * It doesn't have a consistent naming with *Relay or other Rx concepts. /// * It has an inconsistent memory management model compared to other parts of RxSwift (completes on `deinit`). /// /// Once plans are finalized, official availability attribute will be added in one of upcoming versions. @available(*, deprecated, message: "Variable is deprecated. Please use `BehaviorRelay` as a replacement.") public final class Variable<Element> { private let _subject: BehaviorSubject<Element> private var _lock = SpinLock() // state private var _value: Element #if DEBUG fileprivate let _synchronizationTracker = SynchronizationTracker() #endif /// Gets or sets current value of variable. /// /// Whenever a new value is set, all the observers are notified of the change. /// /// Even if the newly set value is same as the old value, observers are still notified for change. public var value: Element { get { self._lock.lock(); defer { self._lock.unlock() } return self._value } set(newValue) { #if DEBUG self._synchronizationTracker.register(synchronizationErrorMessage: .variable) defer { self._synchronizationTracker.unregister() } #endif self._lock.lock() self._value = newValue self._lock.unlock() self._subject.on(.next(newValue)) } } /// Initializes variable with initial value. /// /// - parameter value: Initial variable value. public init(_ value: Element) { self._value = value self._subject = BehaviorSubject(value: value) } /// - returns: Canonical interface for push style sequence public func asObservable() -> Observable<Element> { return self._subject } deinit { self._subject.on(.completed) } } extension ObservableType { /** Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed. - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) - parameter dueTime: Relative time shift of the source by. - parameter scheduler: Scheduler to run the subscription delay timer on. - returns: the source Observable shifted in time by the specified delay. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "delay(_:scheduler:)") public func delay(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType) -> Observable<Element> { return self.delay(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler) } } extension ObservableType { /** Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer. - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) - parameter dueTime: Maximum duration between values before a timeout occurs. - parameter scheduler: Scheduler to run the timeout timer on. - returns: An observable sequence with a `RxError.timeout` in case of a timeout. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timeout(_:scheduler:)") public func timeout(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType) -> Observable<Element> { return timeout(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler) } /** Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on. - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) - parameter dueTime: Maximum duration between values before a timeout occurs. - parameter other: Sequence to return in case of a timeout. - parameter scheduler: Scheduler to run the timeout timer on. - returns: The source sequence switching to the other sequence in case of a timeout. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timeout(_:other:scheduler:)") public func timeout<OtherSource: ObservableConvertibleType>(_ dueTime: Foundation.TimeInterval, other: OtherSource, scheduler: SchedulerType) -> Observable<Element> where Element == OtherSource.Element { return timeout(.milliseconds(Int(dueTime * 1000.0)), other: other, scheduler: scheduler) } } extension ObservableType { /** Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) - parameter duration: Duration for skipping elements from the start of the sequence. - parameter scheduler: Scheduler to run the timer on. - returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "skip(_:scheduler:)") public func skip(_ duration: Foundation.TimeInterval, scheduler: SchedulerType) -> Observable<Element> { return skip(.milliseconds(Int(duration * 1000.0)), scheduler: scheduler) } } extension ObservableType where Element : RxAbstractInteger { /** Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) - parameter period: Period for producing the values in the resulting sequence. - parameter scheduler: Scheduler to run the timer on. - returns: An observable sequence that produces a value after each period. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "interval(_:scheduler:)") public static func interval(_ period: Foundation.TimeInterval, scheduler: SchedulerType) -> Observable<Element> { return interval(.milliseconds(Int(period * 1000.0)), scheduler: scheduler) } } extension ObservableType where Element: RxAbstractInteger { /** Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) - parameter dueTime: Relative time at which to produce the first value. - parameter period: Period to produce subsequent values. - parameter scheduler: Scheduler to run timers on. - returns: An observable sequence that produces a value after due time has elapsed and then each period. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timer(_:period:scheduler:)") public static func timer(_ dueTime: Foundation.TimeInterval, period: Foundation.TimeInterval? = nil, scheduler: SchedulerType) -> Observable<Element> { return timer(.milliseconds(Int(dueTime * 1000.0)), period: period.map { .milliseconds(Int($0 * 1000.0)) }, scheduler: scheduler) } } extension ObservableType { /** Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. This operator makes sure that no two elements are emitted in less then dueTime. - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) - parameter dueTime: Throttling duration for each element. - parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted. - parameter scheduler: Scheduler to run the throttle timers on. - returns: The throttled sequence. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "throttle(_:latest:scheduler:)") public func throttle(_ dueTime: Foundation.TimeInterval, latest: Bool = true, scheduler: SchedulerType) -> Observable<Element> { return throttle(.milliseconds(Int(dueTime * 1000.0)), latest: latest, scheduler: scheduler) } } extension ObservableType { /** Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) - parameter duration: Duration for taking elements from the start of the sequence. - parameter scheduler: Scheduler to run the timer on. - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "take(_:scheduler:)") public func take(_ duration: Foundation.TimeInterval, scheduler: SchedulerType) -> Observable<Element> { return take(.milliseconds(Int(duration * 1000.0)), scheduler: scheduler) } } extension ObservableType { /** Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) - parameter dueTime: Relative time shift of the subscription. - parameter scheduler: Scheduler to run the subscription delay timer on. - returns: Time-shifted sequence. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "delaySubscription(_:scheduler:)") public func delaySubscription(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType) -> Observable<Element> { return delaySubscription(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler) } } extension ObservableType { /** Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed. - seealso: [window operator on reactivex.io](http://reactivex.io/documentation/operators/window.html) - parameter timeSpan: Maximum time length of a window. - parameter count: Maximum element count of a window. - parameter scheduler: Scheduler to run windowing timers on. - returns: An observable sequence of windows (instances of `Observable`). */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "window(_:)") public func window(timeSpan: Foundation.TimeInterval, count: Int, scheduler: SchedulerType) -> Observable<Observable<Element>> { return window(timeSpan: .milliseconds(Int(timeSpan * 1000.0)), count: count, scheduler: scheduler) } } extension PrimitiveSequence { /** Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed. - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) - parameter dueTime: Relative time shift of the source by. - parameter scheduler: Scheduler to run the subscription delay timer on. - returns: the source Observable shifted in time by the specified delay. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "delay(_:scheduler:)") public func delay(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType) -> PrimitiveSequence<Trait, Element> { return delay(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler) } /** Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) - parameter dueTime: Relative time shift of the subscription. - parameter scheduler: Scheduler to run the subscription delay timer on. - returns: Time-shifted sequence. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "delaySubscription(_:scheduler:)") public func delaySubscription(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType) -> PrimitiveSequence<Trait, Element> { return delaySubscription(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler) } /** Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer. - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) - parameter dueTime: Maximum duration between values before a timeout occurs. - parameter scheduler: Scheduler to run the timeout timer on. - returns: An observable sequence with a `RxError.timeout` in case of a timeout. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timeout(_:scheduler:)") public func timeout(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType) -> PrimitiveSequence<Trait, Element> { return timeout(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler) } /** Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on. - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) - parameter dueTime: Maximum duration between values before a timeout occurs. - parameter other: Sequence to return in case of a timeout. - parameter scheduler: Scheduler to run the timeout timer on. - returns: The source sequence switching to the other sequence in case of a timeout. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timeout(_:other:scheduler:)") public func timeout(_ dueTime: Foundation.TimeInterval, other: PrimitiveSequence<Trait, Element>, scheduler: SchedulerType) -> PrimitiveSequence<Trait, Element> { return timeout(.milliseconds(Int(dueTime * 1000.0)), other: other, scheduler: scheduler) } } extension PrimitiveSequenceType where Trait == SingleTrait { /** Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. - returns: The source sequence with the side-effecting behavior applied. */ @available(*, deprecated, renamed: "do(onSuccess:onError:onSubscribe:onSubscribed:onDispose:)") public func `do`(onNext: ((Element) throws -> Void)?, onError: ((Swift.Error) throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) -> Single<Element> { return self.`do`( onSuccess: onNext, onError: onError, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose ) } } extension ObservableType { /** Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers. A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first. - seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html) - parameter timeSpan: Maximum time length of a buffer. - parameter count: Maximum element count of a buffer. - parameter scheduler: Scheduler to run buffering timers on. - returns: An observable sequence of buffers. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "buffer(timeSpan:count:scheduler:)") public func buffer(timeSpan: Foundation.TimeInterval, count: Int, scheduler: SchedulerType) -> Observable<[Element]> { return buffer(timeSpan: .milliseconds(Int(timeSpan * 1000.0)), count: count, scheduler: scheduler) } } extension PrimitiveSequenceType where Element: RxAbstractInteger { /** Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) - parameter dueTime: Relative time at which to produce the first value. - parameter scheduler: Scheduler to run timers on. - returns: An observable sequence that produces a value after due time has elapsed and then each period. */ @available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timer(_:scheduler:)") public static func timer(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType) -> PrimitiveSequence<Trait, Element> { return timer(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler) } } extension Completable { /** Merges the completion of all Completables from a collection into a single Completable. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - parameter sources: Collection of Completables to merge. - returns: A Completable that merges the completion of all Completables. */ @available(*, deprecated, message: "Use Completable.zip instead.", renamed: "zip") public static func merge<Collection: Swift.Collection>(_ sources: Collection) -> Completable where Collection.Element == Completable { return zip(sources) } /** Merges the completion of all Completables from an array into a single Completable. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - parameter sources: Array of observable sequences to merge. - returns: A Completable that merges the completion of all Completables. */ @available(*, deprecated, message: "Use Completable.zip instead.", renamed: "zip") public static func merge(_ sources: [Completable]) -> Completable { return zip(sources) } /** Merges the completion of all Completables into a single Completable. - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) - parameter sources: Collection of observable sequences to merge. - returns: The observable sequence that merges the elements of the observable sequences. */ @available(*, deprecated, message: "Use Completable.zip instead.", renamed: "zip") public static func merge(_ sources: Completable...) -> Completable { return zip(sources) } }
mit
5368cbec8722b6918f3b5c98a3b462c9
50.192771
316
0.712672
5.065225
false
false
false
false
mortorqrobotics/morscout-ios
MorScout/Models/NumberBox.swift
1
1227
// // NumberBox.swift // MorScout // // Created by Farbod Rafezy on 3/1/16. // Copyright © 2016 MorTorq. All rights reserved. // import Foundation import SwiftyJSON class NumberBox: DataPoint { let name: String let start: Int let min: Int let max: Int init(json: JSON) { name = json["name"].stringValue start = json["start"].intValue min = json["min"].intValue max = json["max"].intValue } init(name: String, start: Int, min: Int, max: Int){ self.name = name self.start = start self.min = min self.max = max } required convenience init(coder aDecoder: NSCoder) { let name = aDecoder.decodeObject(forKey: "name") as! String let start = aDecoder.decodeInteger(forKey: "start") let min = aDecoder.decodeInteger(forKey: "min") let max = aDecoder.decodeInteger(forKey: "max") self.init(name: name, start: start, min: min, max: max) } func encodeWithCoder(_ aCoder: NSCoder) { aCoder.encode(name, forKey: "name") aCoder.encode(start, forKey: "start") aCoder.encode(min, forKey: "min") aCoder.encode(max, forKey: "max") }}
mit
390fcad96c586b737df007f9cc879ffe
26.244444
67
0.593801
3.83125
false
false
false
false
lorentey/swift
test/ModuleInterface/inlinable-function.swift
5
9017
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -o %t/Test.swiftmodule -emit-module-interface-path %t/Test.swiftinterface -module-name Test %s // RUN: %FileCheck %s --check-prefix FROMSOURCE --check-prefix CHECK < %t/Test.swiftinterface // RUN: %target-swift-frontend -emit-module -o /dev/null -merge-modules %t/Test.swiftmodule -disable-objc-attr-requires-foundation-module -emit-module-interface-path %t/TestFromModule.swiftinterface -module-name Test // RUN: %FileCheck %s --check-prefix FROMMODULE --check-prefix CHECK < %t/TestFromModule.swiftinterface // FIXME: These shouldn't be different, or we'll get different output from // WMO and non-WMO builds. // CHECK-LABEL: public struct Foo : Swift.Hashable { public struct Foo: Hashable { // CHECK: public var inlinableGetPublicSet: Swift.Int { public var inlinableGetPublicSet: Int { // FROMSOURCE: @inlinable get { // FROMMODULE: @inlinable get{{$}} // FROMSOURCE-NEXT: return 3 // FROMSOURCE-NEXT: } @inlinable get { return 3 } // CHECK-NEXT: set[[NEWVALUE:(\(newValue\))?]]{{$}} set { print("I am set to \(newValue)") } // CHECK-NEXT: {{^}} } } // CHECK: public var noAccessors: Swift.Int{{$}} public var noAccessors: Int // CHECK: public var hasDidSet: Swift.Int { public var hasDidSet: Int { // CHECK-NEXT: @_transparent get{{$}} // CHECK-NEXT: set{{(\(value\))?}}{{$}} // CHECK-NOT: didSet didSet { print("b set to \(hasDidSet)") } // CHECK-NEXT: {{^}} } } // CHECK: @_transparent public var transparent: Swift.Int { // FROMMODULE-NEXT: get{{$}} // FROMSOURCE-NEXT: get { // FROMSOURCE-NEXT: return 34 // FROMSOURCE-NEXT: } // CHECK-NEXT: } @_transparent public var transparent: Int { return 34 } // CHECK: public var transparentSet: Swift.Int { public var transparentSet: Int { // CHECK-NEXT: get{{$}} get { return 34 } // FROMMODULE-NEXT: @_transparent set[[NEWVALUE]]{{$}} // FROMSOURCE-NEXT: @_transparent set[[NEWVALUE]] { // FROMSOURCE-NOT: #if false // FROMSOURCE-NOT: print("I should not appear") // FROMSOURCE-NOT: #else // FROMSOURCE-NOT: #if false // FROMSOURCE-NOT: print("I also should not") // FROMSOURCE-NOT: #else // FROMSOURCE: print("I am set to \(newValue)") // FROMSOURCE-NOT: #endif // FROMSOURCE-NOT: #endif // FROMSOURCE-NEXT: } @_transparent set { #if false print("I should not appear") #else #if false print("I also should not") #else print("I am set to \(newValue)") #endif #endif } } // CHECK: @inlinable public var inlinableProperty: Swift.Int { @inlinable public var inlinableProperty: Int { // FROMMODULE: get{{$}} // FROMSOURCE: get { // FROMSOURCE-NEXT: return 32 // FROMSOURCE-NEXT: } get { return 32 } // FROMMODULE: set[[NEWVALUE]]{{$}} // FROMSOURCE: set[[NEWVALUE]] { // FROMSOURCE-NOT: #if true // FROMSOURCE: print("I am set to \(newValue)") // FROMSOURCE-NOT: #else // FROMSOURCE-NOT: print("I should not appear") // FROMSOURCE-NOT #endif // FROMSOURCE: } set { #if true print("I am set to \(newValue)") #else print("I should not appear") #endif } // CHECK-NEXT: } } // CHECK: @inlinable public var inlinableReadAndModify: Swift.Int { @inlinable public var inlinableReadAndModify: Int { // FROMMODULE: _read{{$}} // FROMSOURCE: _read { // FROMSOURCE-NEXT: yield 0 // FROMSOURCE-NEXT: } _read { yield 0 } // FROMMODULE: _modify{{$}} // FROMSOURCE: _modify { // FROMSOURCE-NEXT: var x = 0 // FROMSOURCE-NEXT: yield &x // FROMSOURCE-NEXT: } _modify { var x = 0 yield &x } // CHECK-NEXT: } } // CHECK: public var inlinableReadNormalModify: Swift.Int { public var inlinableReadNormalModify: Int { // FROMMODULE: @inlinable _read{{$}} // FROMSOURCE: @inlinable _read { // FROMSOURCE-NEXT: yield 0 // FROMSOURCE-NEXT: } @inlinable _read { yield 0 } // CHECK: _modify{{$}} // CHECK-NOT: var x = 0 // CHECK-NOT: yield &x // CHECK-NOT: } _modify { var x = 0 yield &x } // CHECK-NEXT: } } // CHECK: public var normalReadInlinableModify: Swift.Int { public var normalReadInlinableModify: Int { // CHECK: _read{{$}} // CHECK-NOT: yield 0 // CHECK-NOT: } _read { yield 0 } // FROMMODULE: @inlinable _modify{{$}} // FROMSOURCE: @inlinable _modify { // FROMSOURCE-NEXT: var x = 0 // FROMSOURCE-NEXT: yield &x // FROMSOURCE-NEXT: } @inlinable _modify { var x = 0 yield &x } // CHECK-NEXT: } } // CHECK: public var normalReadAndModify: Swift.Int { public var normalReadAndModify: Int { // CHECK-NEXT: _read{{$}} _read { yield 0 } // CHECK-NEXT: _modify{{$}} _modify { var x = 0 yield &x } // CHECK-NEXT: } } // FROMMODULE: @inlinable public func inlinableMethod(){{$}} // FROMSOURCE: @inlinable public func inlinableMethod() { // FROMSOURCE-NOT: #if NO // FROMSOURCE-NOT: print("Hello, world!") // FROMSOURCE-NOT: #endif // FROMSOURCE: print("Goodbye, world!") // FROMSOURCE-NEXT: } @inlinable public func inlinableMethod() { #if NO print("Hello, world!") #endif print("Goodbye, world!") } // FROMMODULE: @_transparent [[ATTRS:(mutating public|public mutating)]] func transparentMethod(){{$}} // FROMSOURCE: @_transparent [[ATTRS:(mutating public|public mutating)]] func transparentMethod() { // FROMSOURCE-NEXT: inlinableProperty = 4 // FROMSOURCE-NEXT: } @_transparent mutating public func transparentMethod() { inlinableProperty = 4 } // CHECK: public func nonInlinableMethod(){{$}} // CHECK-NOT: print("Not inlinable") public func nonInlinableMethod() { print("Not inlinable") } // CHECK: public subscript(i: Swift.Int) -> Swift.Int { // CHECK-NEXT: get{{$}} // FROMSOURCE-NEXT: @inlinable set[[NEWVALUE]] { print("set") } // FROMMODULE-NEXT: @inlinable set[[NEWVALUE]]{{$}} // CHECK-NEXT: } public subscript(i: Int) -> Int { get { return 0 } @inlinable set { print("set") } } // CHECK: public subscript(j: Swift.Int, k: Swift.Int) -> Swift.Int { // FROMMODULE-NEXT: @inlinable get{{$}} // FROMSOURCE-NEXT: @inlinable get { return 0 } // CHECK-NEXT: set[[NEWVALUE]]{{$}} // CHECK-NEXT: } public subscript(j: Int, k: Int) -> Int { @inlinable get { return 0 } set { print("set") } } // CHECK: @inlinable public subscript(l: Swift.Int, m: Swift.Int, n: Swift.Int) -> Swift.Int { // FROMMODULE-NEXT: get{{$}} // FROMSOURCE-NEXT: get { return 0 } // FROMMODULE-NEXT: set[[NEWVALUE]]{{$}} // FROMSOURCE-NEXT: set[[NEWVALUE]] { print("set") } // CHECK-NEXT: } @inlinable public subscript(l: Int, m: Int, n: Int) -> Int { get { return 0 } set { print("set") } } // FROMMODULE: @inlinable public init(value: Swift.Int){{$}} // FROMSOURCE: @inlinable public init(value: Swift.Int) { // FROMSOURCE-NEXT: topLevelUsableFromInline() // FROMSOURCE-NEXT: noAccessors = value // FROMSOURCE-NEXT: hasDidSet = value // FROMSOURCE-NEXT: } @inlinable public init(value: Int) { topLevelUsableFromInline() noAccessors = value hasDidSet = value } // CHECK: public init(){{$}} // CHECK-NOT: noAccessors = 0 // CHECK-NOT: hasDidSet = 0 public init() { noAccessors = 0 hasDidSet = 0 } // CHECK: {{^}}} } // CHECK-NOT: private func topLevelPrivate() private func topLevelPrivate() { print("Ssshhhhh") } // CHECK: internal func topLevelUsableFromInline(){{$}} @usableFromInline internal func topLevelUsableFromInline() { topLevelPrivate() } // FROMMODULE: @inlinable public func topLevelInlinable(){{$}} // FROMSOURCE: @inlinable public func topLevelInlinable() { // FROMSOURCE-NEXT: topLevelUsableFromInline() // FROMSOURCE-NEXT: } @inlinable public func topLevelInlinable() { topLevelUsableFromInline() } // CHECK: public class HasInlinableDeinit { public class HasInlinableDeinit { // CHECK: public init(){{$}} public init() {} // FROMMODULE: [[OBJC:(@objc )?]]@inlinable deinit{{$}} // FROMSOURCE: [[OBJC:(@objc )?]]@inlinable deinit { // FROMSOURCE-NEXT: print("goodbye") // FROMSOURCE-NEXT: } @inlinable deinit { print("goodbye") } // CHECK-NEXT: } } // CHECK: public class HasStandardDeinit { public class HasStandardDeinit { // CHECK: public init(){{$}} public init() {} // CHECK: [[OBJC]]deinit{{$}} deinit { print("goodbye") } // CHECK-NEXT: } } // CHECK: public class HasDefaultDeinit { public class HasDefaultDeinit { // CHECK: public init(){{$}} public init() {} // CHECK: [[OBJC]]deinit{{$}} // CHECK-NEXT: } }
apache-2.0
c3fb8be4b2ba8bda0a4f0861e3512545
26.241692
216
0.604303
3.817528
false
false
false
false
hackiftekhar/IQKeyboardManager
Demo/Swift_Demo/ViewController/SettingsViewController.swift
1
21936
// // SettingsViewController.swift // Demo // // Created by Iftekhar on 26/08/15. // Copyright (c) 2015 Iftekhar. All rights reserved. // import UIKit import IQKeyboardManagerSwift class SettingsViewController: UITableViewController { let sectionTitles = ["UIKeyboard handling", "IQToolbar handling", "UIKeyboard appearance overriding", "Resign first responder handling", "UISound handling", "IQKeyboardManager Debug"] let keyboardManagerProperties = [["Enable", "Keyboard Distance From TextField"], ["Enable AutoToolbar", "Toolbar Manage Behaviour", "Should Toolbar Uses TextField TintColor", "Should Show TextField Placeholder", "Placeholder Font", "Toolbar Tint Color", "Toolbar Done BarButtonItem Image", "Toolbar Done Button Text"], ["Override Keyboard Appearance", "UIKeyboard Appearance"], ["Should Resign On Touch Outside"], ["Should Play Input Clicks"], ["Debugging logs in Console"]] let keyboardManagerPropertyDetails = [["Enable/Disable IQKeyboardManager", "Set keyboard distance from textField"], ["Automatic add the IQToolbar on UIKeyboard", "AutoToolbar previous/next button managing behaviour", "Uses textField's tintColor property for IQToolbar", "Add the textField's placeholder text on IQToolbar", "UIFont for IQToolbar placeholder text", "Override toolbar tintColor property", "Replace toolbar done button text with provided image", "Override toolbar done button text"], ["Override the keyboardAppearance for all UITextField/UITextView", "All the UITextField keyboardAppearance is set using this property"], ["Resigns Keyboard on touching outside of UITextField/View"], ["Plays inputClick sound on next/previous/done click"], ["Setting enableDebugging to YES/No to turn on/off debugging mode"]] var selectedIndexPathForOptions: IndexPath? @IBAction func doneAction (_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } /** UIKeyboard Handling */ @objc func enableAction (_ sender: UISwitch) { IQKeyboardManager.shared.enable = sender.isOn self.tableView.reloadSections(IndexSet(integer: 0), with: .fade) } @objc func keyboardDistanceFromTextFieldAction (_ sender: UIStepper) { IQKeyboardManager.shared.keyboardDistanceFromTextField = CGFloat(sender.value) self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .none) } /** IQToolbar handling */ @objc func enableAutoToolbarAction (_ sender: UISwitch) { IQKeyboardManager.shared.enableAutoToolbar = sender.isOn self.tableView.reloadSections(IndexSet(integer: 1), with: .fade) } @objc func shouldToolbarUsesTextFieldTintColorAction (_ sender: UISwitch) { IQKeyboardManager.shared.shouldToolbarUsesTextFieldTintColor = sender.isOn } @objc func shouldShowToolbarPlaceholder (_ sender: UISwitch) { IQKeyboardManager.shared.shouldShowToolbarPlaceholder = sender.isOn self.tableView.reloadSections(IndexSet(integer: 1), with: .fade) } @objc func toolbarDoneBarButtonItemImage (_ sender: UISwitch) { if sender.isOn { IQKeyboardManager.shared.toolbarDoneBarButtonItemImage = UIImage(named: "IQButtonBarArrowDown") } else { IQKeyboardManager.shared.toolbarDoneBarButtonItemImage = nil } self.tableView.reloadSections(IndexSet(integer: 1), with: .fade) } /** "Keyboard appearance overriding */ @objc func overrideKeyboardAppearanceAction (_ sender: UISwitch) { IQKeyboardManager.shared.overrideKeyboardAppearance = sender.isOn self.tableView.reloadSections(IndexSet(integer: 2), with: .fade) } /** Resign first responder handling */ @objc func shouldResignOnTouchOutsideAction (_ sender: UISwitch) { IQKeyboardManager.shared.shouldResignOnTouchOutside = sender.isOn } /** Sound handling */ @objc func shouldPlayInputClicksAction (_ sender: UISwitch) { IQKeyboardManager.shared.shouldPlayInputClicks = sender.isOn } /** Debugging */ @objc func enableDebugging (_ sender: UISwitch) { IQKeyboardManager.shared.enableDebugging = sender.isOn } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } override func numberOfSections(in tableView: UITableView) -> Int { return sectionTitles.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: if IQKeyboardManager.shared.enable == true { let properties = keyboardManagerProperties[section] return properties.count } else { return 1 } case 1: if IQKeyboardManager.shared.enableAutoToolbar == false { return 1 } else if IQKeyboardManager.shared.shouldShowToolbarPlaceholder == false { return 4 } else { let properties = keyboardManagerProperties[section] return properties.count } case 2: if IQKeyboardManager.shared.overrideKeyboardAppearance == true { let properties = keyboardManagerProperties[section] return properties.count } else { return 1 } case 3, 4, 5: let properties = keyboardManagerProperties[section] return properties.count default: return 0 } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionTitles[section] } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: switch indexPath.row { case 0: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else { fatalError("Can't dequeue cell") } cell.switchEnable.isEnabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.isOn = IQKeyboardManager.shared.enable cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents) cell.switchEnable.addTarget(self, action: #selector(self.enableAction(_:)), for: .valueChanged) return cell case 1: guard let cell = tableView.dequeueReusableCell(withIdentifier: "StepperTableViewCell", for: indexPath) as? StepperTableViewCell else { fatalError("Can't dequeue cell") } cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.stepper.value = Double(IQKeyboardManager.shared.keyboardDistanceFromTextField) cell.labelStepperValue.text = NSString(format: "%.0f", IQKeyboardManager.shared.keyboardDistanceFromTextField) as String cell.stepper.removeTarget(nil, action: nil, for: .allEvents) cell.stepper.addTarget(self, action: #selector(self.keyboardDistanceFromTextFieldAction(_:)), for: .valueChanged) return cell default: break } case 1: switch indexPath.row { case 0: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else { fatalError("Can't dequeue cell") } cell.switchEnable.isEnabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.isOn = IQKeyboardManager.shared.enableAutoToolbar cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents) cell.switchEnable.addTarget(self, action: #selector(self.enableAutoToolbarAction(_:)), for: .valueChanged) return cell case 1: guard let cell = tableView.dequeueReusableCell(withIdentifier: "NavigationTableViewCell", for: indexPath) as? NavigationTableViewCell else { fatalError("Can't dequeue cell") } cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] return cell case 2: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else { fatalError("Can't dequeue cell") } cell.switchEnable.isEnabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.isOn = IQKeyboardManager.shared.shouldToolbarUsesTextFieldTintColor cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents) cell.switchEnable.addTarget(self, action: #selector(self.shouldToolbarUsesTextFieldTintColorAction(_:)), for: .valueChanged) return cell case 3: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else { fatalError("Can't dequeue cell") } cell.switchEnable.isEnabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.isOn = IQKeyboardManager.shared.shouldShowToolbarPlaceholder cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents) cell.switchEnable.addTarget(self, action: #selector(self.shouldShowToolbarPlaceholder(_:)), for: .valueChanged) return cell case 4: guard let cell = tableView.dequeueReusableCell(withIdentifier: "NavigationTableViewCell", for: indexPath) as? NavigationTableViewCell else { fatalError("Can't dequeue cell") } cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] return cell case 5: guard let cell = tableView.dequeueReusableCell(withIdentifier: "ColorTableViewCell", for: indexPath) as? ColorTableViewCell else { fatalError("Can't dequeue cell") } cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.colorPickerTextField.selectedColor = IQKeyboardManager.shared.toolbarTintColor cell.colorPickerTextField.tag = 15 cell.colorPickerTextField.delegate = self return cell case 6: guard let cell = tableView.dequeueReusableCell(withIdentifier: "ImageSwitchTableViewCell", for: indexPath) as? ImageSwitchTableViewCell else { fatalError("Can't dequeue cell") } cell.switchEnable.isEnabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.arrowImageView.image = IQKeyboardManager.shared.toolbarDoneBarButtonItemImage cell.switchEnable.isOn = IQKeyboardManager.shared.toolbarDoneBarButtonItemImage != nil cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents) cell.switchEnable.addTarget(self, action: #selector(self.toolbarDoneBarButtonItemImage(_:)), for: .valueChanged) return cell case 7: guard let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldTableViewCell", for: indexPath) as? TextFieldTableViewCell else { fatalError("Can't dequeue cell") } cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.textField.text = IQKeyboardManager.shared.toolbarDoneBarButtonItemText cell.textField.tag = 17 cell.textField.delegate = self return cell default: break } case 2: switch indexPath.row { case 0: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else { fatalError("Can't dequeue cell") } cell.switchEnable.isEnabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.isOn = IQKeyboardManager.shared.overrideKeyboardAppearance cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents) cell.switchEnable.addTarget(self, action: #selector(self.overrideKeyboardAppearanceAction(_:)), for: .valueChanged) return cell case 1: guard let cell = tableView.dequeueReusableCell(withIdentifier: "NavigationTableViewCell", for: indexPath) as? NavigationTableViewCell else { fatalError("Can't dequeue cell") } cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] return cell default: break } case 3: switch indexPath.row { case 0: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else { fatalError("Can't dequeue cell") } cell.switchEnable.isEnabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.isOn = IQKeyboardManager.shared.shouldResignOnTouchOutside cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents) cell.switchEnable.addTarget(self, action: #selector(self.shouldResignOnTouchOutsideAction(_:)), for: .valueChanged) return cell default: break } case 4: switch indexPath.row { case 0: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else { fatalError("Can't dequeue cell") } cell.switchEnable.isEnabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.isOn = IQKeyboardManager.shared.shouldPlayInputClicks cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents) cell.switchEnable.addTarget(self, action: #selector(self.shouldPlayInputClicksAction(_:)), for: .valueChanged) return cell default: break } case 5: switch indexPath.row { case 0: guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else { fatalError("Can't dequeue cell") } cell.switchEnable.isEnabled = true cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row] cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row] cell.switchEnable.isOn = IQKeyboardManager.shared.enableDebugging cell.switchEnable.removeTarget(nil, action: nil, for: .allEvents) cell.switchEnable.addTarget(self, action: #selector(self.enableDebugging(_:)), for: .valueChanged) return cell default: break } default: break } return UITableViewCell() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let identifier = segue.identifier else { return } if identifier.elementsEqual("OptionsViewController"), let controller = segue.destination as? OptionsViewController, let cell = sender as? UITableViewCell { controller.delegate = self selectedIndexPathForOptions = self.tableView.indexPath(for: cell) guard let selectedIndexPath = selectedIndexPathForOptions else { return } if selectedIndexPath.section == 1 && selectedIndexPath.row == 1 { controller.title = "Toolbar Manage Behaviour" controller.options = ["IQAutoToolbar By Subviews", "IQAutoToolbar By Tag", "IQAutoToolbar By Position"] controller.selectedIndex = IQKeyboardManager.shared.toolbarManageBehaviour.hashValue } else if selectedIndexPath.section == 1 && selectedIndexPath.row == 4 { controller.title = "Fonts" controller.options = ["Bold System Font", "Italic system font", "Regular"] controller.selectedIndex = IQKeyboardManager.shared.toolbarManageBehaviour.hashValue let fonts = [UIFont.boldSystemFont(ofSize: 12), UIFont.italicSystemFont(ofSize: 12), UIFont.systemFont(ofSize: 12)] if let placeholderFont = IQKeyboardManager.shared.placeholderFont { if let index = fonts.firstIndex(of: placeholderFont) { controller.selectedIndex = index } } } else if selectedIndexPath.section == 2 && selectedIndexPath.row == 1 { controller.title = "Keyboard Appearance" controller.options = ["UIKeyboardAppearance Default", "UIKeyboardAppearance Dark", "UIKeyboardAppearance Light"] controller.selectedIndex = IQKeyboardManager.shared.keyboardAppearance.hashValue } } } } extension SettingsViewController: ColorPickerTextFieldDelegate { func colorPickerTextField(_ textField: ColorPickerTextField, selectedColorAttributes colorAttributes: [String: Any] = [:]) { if textField.tag == 15, let color = colorAttributes["color"] as? UIColor { if color.isEqual(UIColor.clear) { IQKeyboardManager.shared.toolbarTintColor = nil } else { IQKeyboardManager.shared.toolbarTintColor = color } } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } func textFieldDidEndEditing(_ textField: UITextField) { if textField.tag == 17 { IQKeyboardManager.shared.toolbarDoneBarButtonItemText = textField.text?.isEmpty == false ? textField.text : nil } } } extension SettingsViewController: OptionsViewControllerDelegate { func optionsViewController(_ controller: OptionsViewController, index: NSInteger) { guard let selectedIndexPath = selectedIndexPathForOptions else { return } if selectedIndexPath.section == 1 && selectedIndexPath.row == 1 { IQKeyboardManager.shared.toolbarManageBehaviour = IQAutoToolbarManageBehaviour(rawValue: index)! } else if selectedIndexPath.section == 1 && selectedIndexPath.row == 4 { let fonts = [UIFont.boldSystemFont(ofSize: 12), UIFont.italicSystemFont(ofSize: 12), UIFont.systemFont(ofSize: 12)] IQKeyboardManager.shared.placeholderFont = fonts[index] } else if selectedIndexPath.section == 2 && selectedIndexPath.row == 1 { IQKeyboardManager.shared.keyboardAppearance = UIKeyboardAppearance(rawValue: index)! } } }
mit
46426a098b403182024c6a372ec84f2a
46.072961
384
0.649161
5.995081
false
false
false
false
xmartlabs/XLPagerTabStrip
Sources/PagerTabStripViewController.swift
2
16621
// PagerTabStripViewController.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 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 // MARK: Protocols public protocol IndicatorInfoProvider { func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo } public protocol PagerTabStripDelegate: class { func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) } public protocol PagerTabStripIsProgressiveDelegate: PagerTabStripDelegate { func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) } public protocol PagerTabStripDataSource: class { func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] } // MARK: PagerTabStripViewController open class PagerTabStripViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak public var containerView: UIScrollView! open weak var delegate: PagerTabStripDelegate? open weak var datasource: PagerTabStripDataSource? open var pagerBehaviour = PagerTabStripBehaviour.progressive(skipIntermediateViewControllers: true, elasticIndicatorLimit: true) open private(set) var viewControllers = [UIViewController]() open private(set) var currentIndex = 0 open private(set) var preCurrentIndex = 0 // used *only* to store the index to which move when the pager becomes visible open var pageWidth: CGFloat { return containerView.bounds.width } open var scrollPercentage: CGFloat { if swipeDirection != .right { let module = fmod(containerView.contentOffset.x, pageWidth) return module == 0.0 ? 1.0 : module / pageWidth } return 1 - fmod(containerView.contentOffset.x >= 0 ? containerView.contentOffset.x : pageWidth + containerView.contentOffset.x, pageWidth) / pageWidth } open var swipeDirection: SwipeDirection { if containerView.contentOffset.x > lastContentOffset { return .left } else if containerView.contentOffset.x < lastContentOffset { return .right } return .none } override open func viewDidLoad() { super.viewDidLoad() let conteinerViewAux = containerView ?? { let containerView = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)) containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight] return containerView }() containerView = conteinerViewAux if containerView.superview == nil { view.addSubview(containerView) } containerView.bounces = true containerView.alwaysBounceHorizontal = true containerView.alwaysBounceVertical = false containerView.scrollsToTop = false containerView.delegate = self containerView.showsVerticalScrollIndicator = false containerView.showsHorizontalScrollIndicator = false containerView.isPagingEnabled = true reloadViewControllers() let childController = viewControllers[currentIndex] addChild(childController) childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] containerView.addSubview(childController.view) childController.didMove(toParent: self) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) isViewAppearing = true children.forEach { $0.beginAppearanceTransition(true, animated: animated) } } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) lastSize = containerView.bounds.size updateIfNeeded() let needToUpdateCurrentChild = preCurrentIndex != currentIndex if needToUpdateCurrentChild { moveToViewController(at: preCurrentIndex) } isViewAppearing = false children.forEach { $0.endAppearanceTransition() } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) children.forEach { $0.beginAppearanceTransition(false, animated: animated) } } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) children.forEach { $0.endAppearanceTransition() } } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateIfNeeded() } open override var shouldAutomaticallyForwardAppearanceMethods: Bool { return false } open func moveToViewController(at index: Int, animated: Bool = true) { guard isViewLoaded && view.window != nil && currentIndex != index else { preCurrentIndex = index return } if animated && pagerBehaviour.skipIntermediateViewControllers && abs(currentIndex - index) > 1 { var tmpViewControllers = viewControllers let currentChildVC = viewControllers[currentIndex] let fromIndex = currentIndex < index ? index - 1 : index + 1 let fromChildVC = viewControllers[fromIndex] tmpViewControllers[currentIndex] = fromChildVC tmpViewControllers[fromIndex] = currentChildVC pagerTabStripChildViewControllersForScrolling = tmpViewControllers containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: fromIndex), y: 0), animated: false) (navigationController?.view ?? view).isUserInteractionEnabled = !animated containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: 0), animated: true) } else { (navigationController?.view ?? view).isUserInteractionEnabled = !animated containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: 0), animated: animated) } } open func moveTo(viewController: UIViewController, animated: Bool = true) { moveToViewController(at: viewControllers.firstIndex(of: viewController)!, animated: animated) } // MARK: - PagerTabStripDataSource open func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] { assertionFailure("Sub-class must implement the PagerTabStripDataSource viewControllers(for:) method") return [] } // MARK: - Helpers open func updateIfNeeded() { if isViewLoaded && !lastSize.equalTo(containerView.bounds.size) { updateContent() } } open func canMoveTo(index: Int) -> Bool { return currentIndex != index && viewControllers.count > index } open func pageOffsetForChild(at index: Int) -> CGFloat { return CGFloat(index) * containerView.bounds.width } open func offsetForChild(at index: Int) -> CGFloat { return (CGFloat(index) * containerView.bounds.width) + ((containerView.bounds.width - view.bounds.width) * 0.5) } open func offsetForChild(viewController: UIViewController) throws -> CGFloat { guard let index = viewControllers.firstIndex(of: viewController) else { throw PagerTabStripError.viewControllerOutOfBounds } return offsetForChild(at: index) } open func pageFor(contentOffset: CGFloat) -> Int { let result = virtualPageFor(contentOffset: contentOffset) return pageFor(virtualPage: result) } open func virtualPageFor(contentOffset: CGFloat) -> Int { return Int((contentOffset + 1.5 * pageWidth) / pageWidth) - 1 } open func pageFor(virtualPage: Int) -> Int { if virtualPage < 0 { return 0 } if virtualPage > viewControllers.count - 1 { return viewControllers.count - 1 } return virtualPage } open func updateContent() { if lastSize.width != containerView.bounds.size.width { lastSize = containerView.bounds.size containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0) } lastSize = containerView.bounds.size let pagerViewControllers = pagerTabStripChildViewControllersForScrolling ?? viewControllers containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(pagerViewControllers.count), height: containerView.contentSize.height) for (index, childController) in pagerViewControllers.enumerated() { let pageOffsetForChild = self.pageOffsetForChild(at: index) if abs(containerView.contentOffset.x - pageOffsetForChild) < containerView.bounds.width { if childController.parent != nil { childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height) childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] } else { childController.beginAppearanceTransition(true, animated: false) addChild(childController) childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height) childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] containerView.addSubview(childController.view) childController.didMove(toParent: self) childController.endAppearanceTransition() } } else { if childController.parent != nil { childController.beginAppearanceTransition(false, animated: false) childController.willMove(toParent: nil) childController.view.removeFromSuperview() childController.removeFromParent() childController.endAppearanceTransition() } } } let oldCurrentIndex = currentIndex let virtualPage = virtualPageFor(contentOffset: containerView.contentOffset.x) let newCurrentIndex = pageFor(virtualPage: virtualPage) currentIndex = newCurrentIndex preCurrentIndex = currentIndex let changeCurrentIndex = newCurrentIndex != oldCurrentIndex if let progressiveDelegate = self as? PagerTabStripIsProgressiveDelegate, pagerBehaviour.isProgressiveIndicator { let (fromIndex, toIndex, scrollPercentage) = progressiveIndicatorData(virtualPage) progressiveDelegate.updateIndicator(for: self, fromIndex: fromIndex, toIndex: toIndex, withProgressPercentage: scrollPercentage, indexWasChanged: changeCurrentIndex) } else { delegate?.updateIndicator(for: self, fromIndex: min(oldCurrentIndex, pagerViewControllers.count - 1), toIndex: newCurrentIndex) } } open func reloadPagerTabStripView() { guard isViewLoaded else { return } for childController in viewControllers where childController.parent != nil { childController.beginAppearanceTransition(false, animated: false) childController.willMove(toParent: nil) childController.view.removeFromSuperview() childController.removeFromParent() childController.endAppearanceTransition() } reloadViewControllers() containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(viewControllers.count), height: containerView.contentSize.height) if currentIndex >= viewControllers.count { currentIndex = viewControllers.count - 1 } preCurrentIndex = currentIndex containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0) updateContent() } // MARK: - UIScrollViewDelegate open func scrollViewDidScroll(_ scrollView: UIScrollView) { if containerView == scrollView { updateContent() lastContentOffset = scrollView.contentOffset.x } } open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if containerView == scrollView { lastPageNumber = pageFor(contentOffset: scrollView.contentOffset.x) } } open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { if containerView == scrollView { pagerTabStripChildViewControllersForScrolling = nil (navigationController?.view ?? view).isUserInteractionEnabled = true updateContent() } } // MARK: - Orientation open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) isViewRotating = true pageBeforeRotate = currentIndex coordinator.animate(alongsideTransition: nil) { [weak self] _ in guard let me = self else { return } me.isViewRotating = false me.currentIndex = me.pageBeforeRotate me.preCurrentIndex = me.currentIndex me.updateIfNeeded() } } // MARK: Private private func progressiveIndicatorData(_ virtualPage: Int) -> (Int, Int, CGFloat) { let count = viewControllers.count var fromIndex = currentIndex var toIndex = currentIndex let direction = swipeDirection if direction == .left { if virtualPage > count - 1 { fromIndex = count - 1 toIndex = count } else { if self.scrollPercentage >= 0.5 { fromIndex = max(toIndex - 1, 0) } else { toIndex = fromIndex + 1 } } } else if direction == .right { if virtualPage < 0 { fromIndex = 0 toIndex = -1 } else { if self.scrollPercentage > 0.5 { fromIndex = min(toIndex + 1, count - 1) } else { toIndex = fromIndex - 1 } } } let scrollPercentage = pagerBehaviour.isElasticIndicatorLimit ? self.scrollPercentage : ((toIndex < 0 || toIndex >= count) ? 0.0 : self.scrollPercentage) return (fromIndex, toIndex, scrollPercentage) } private func reloadViewControllers() { guard let dataSource = datasource else { fatalError("dataSource must not be nil") } viewControllers = dataSource.viewControllers(for: self) // viewControllers guard !viewControllers.isEmpty else { fatalError("viewControllers(for:) should provide at least one child view controller") } viewControllers.forEach { if !($0 is IndicatorInfoProvider) { fatalError("Every view controller provided by PagerTabStripDataSource's viewControllers(for:) method must conform to IndicatorInfoProvider") }} } private var pagerTabStripChildViewControllersForScrolling: [UIViewController]? private var lastPageNumber = 0 private var lastContentOffset: CGFloat = 0.0 private var pageBeforeRotate = 0 private var lastSize = CGSize(width: 0, height: 0) internal var isViewRotating = false internal var isViewAppearing = false }
mit
e90c371d22cdd8e6ac79a8e06e929c66
40.972222
213
0.673064
5.544029
false
false
false
false
gzios/swift
SwiftBase/Swift数组.playground/Contents.swift
1
786
//: Playground - noun: a place where people can play import UIKit //泛型集合 //1.定义数组 let arr = ["1","2","3"] //不可变数组 let array:Array<String> = ["1","2","3"] //let arrayM = Array<String>() var arrayM = [String]() //2.可变数组的基本操作 //2.1添加元素 arrayM.append("whx") arrayM.append("why") arrayM.append("whz") arrayM.append("whw") //2.2删除元素 arrayM.remove(at: 0) arrayM //2.3修改元素 arrayM[0] = "w" arrayM //2.4取出元素 arrayM[2] //3.遍历数组 //3.1根据下标值 for i in 0..<arr.count{ print(arr[i]) } for name in arr { print(name) } for i in 0..<2 { print(arr[i]) } for name in arr[0..<2] { print(name) } //4.合并数组 let resu = arr + arrayM; //注意相同类型的数组才可以合并
apache-2.0
535c5e44f5681b2357f386114d61a986
10.714286
52
0.605183
2.293706
false
false
false
false
mshhmzh/firefox-ios
Client/Frontend/Browser/TabScrollController.swift
1
8606
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit private let ToolbarBaseAnimationDuration: CGFloat = 0.2 class TabScrollingController: NSObject { enum ScrollDirection { case Up case Down } enum ToolbarState { case Collapsed case Visible case Animating } weak var tab: Tab? { willSet { self.scrollView?.delegate = nil self.scrollView?.removeGestureRecognizer(panGesture) } didSet { self.scrollView?.addGestureRecognizer(panGesture) scrollView?.delegate = self } } weak var header: UIView? weak var footer: UIView? weak var urlBar: URLBarView? weak var snackBars: UIView? var footerBottomConstraint: Constraint? var headerTopConstraint: Constraint? var toolbarsShowing: Bool { return headerTopOffset == 0 } private var headerTopOffset: CGFloat = 0 { didSet { headerTopConstraint?.updateOffset(headerTopOffset) header?.superview?.setNeedsLayout() } } private var footerBottomOffset: CGFloat = 0 { didSet { footerBottomConstraint?.updateOffset(footerBottomOffset) footer?.superview?.setNeedsLayout() } } private lazy var panGesture: UIPanGestureRecognizer = { let panGesture = UIPanGestureRecognizer(target: self, action: #selector(TabScrollingController.handlePan(_:))) panGesture.maximumNumberOfTouches = 1 panGesture.delegate = self return panGesture }() private var scrollView: UIScrollView? { return tab?.webView?.scrollView } private var contentOffset: CGPoint { return scrollView?.contentOffset ?? CGPointZero } private var contentSize: CGSize { return scrollView?.contentSize ?? CGSizeZero } private var scrollViewHeight: CGFloat { return scrollView?.frame.height ?? 0 } private var topScrollHeight: CGFloat { return header?.frame.height ?? 0 } private var bottomScrollHeight: CGFloat { return urlBar?.frame.height ?? 0 } private var snackBarsFrame: CGRect { return snackBars?.frame ?? CGRectZero } private var lastContentOffset: CGFloat = 0 private var scrollDirection: ScrollDirection = .Down private var toolbarState: ToolbarState = .Visible override init() { super.init() } func showToolbars(animated animated: Bool, completion: ((finished: Bool) -> Void)? = nil) { if toolbarState == .Visible { completion?(finished: true) return } toolbarState = .Visible let durationRatio = abs(headerTopOffset / topScrollHeight) let actualDuration = NSTimeInterval(ToolbarBaseAnimationDuration * durationRatio) self.animateToolbarsWithOffsets( animated: animated, duration: actualDuration, headerOffset: 0, footerOffset: 0, alpha: 1, completion: completion) } func hideToolbars(animated animated: Bool, completion: ((finished: Bool) -> Void)? = nil) { if toolbarState == .Collapsed { completion?(finished: true) return } toolbarState = .Collapsed let durationRatio = abs((topScrollHeight + headerTopOffset) / topScrollHeight) let actualDuration = NSTimeInterval(ToolbarBaseAnimationDuration * durationRatio) self.animateToolbarsWithOffsets( animated: animated, duration: actualDuration, headerOffset: -topScrollHeight, footerOffset: bottomScrollHeight, alpha: 0, completion: completion) } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "contentSize" { if !checkScrollHeightIsLargeEnoughForScrolling() && !toolbarsShowing { showToolbars(animated: true, completion: nil) } } } } private extension TabScrollingController { func tabIsLoading() -> Bool { return tab?.loading ?? true } @objc func handlePan(gesture: UIPanGestureRecognizer) { if tabIsLoading() { return } if let containerView = scrollView?.superview { let translation = gesture.translationInView(containerView) let delta = lastContentOffset - translation.y if delta > 0 { scrollDirection = .Down } else if delta < 0 { scrollDirection = .Up } lastContentOffset = translation.y if checkRubberbandingForDelta(delta) && checkScrollHeightIsLargeEnoughForScrolling() { if toolbarState != .Collapsed || contentOffset.y <= 0 { scrollWithDelta(delta) } if headerTopOffset == -topScrollHeight { toolbarState = .Collapsed } else if headerTopOffset == 0 { toolbarState = .Visible } else { toolbarState = .Animating } } if gesture.state == .Ended || gesture.state == .Cancelled { lastContentOffset = 0 } } } func checkRubberbandingForDelta(delta: CGFloat) -> Bool { return !((delta < 0 && contentOffset.y + scrollViewHeight > contentSize.height && scrollViewHeight < contentSize.height) || contentOffset.y < delta) } func scrollWithDelta(delta: CGFloat) { if scrollViewHeight >= contentSize.height { return } var updatedOffset = headerTopOffset - delta headerTopOffset = clamp(updatedOffset, min: -topScrollHeight, max: 0) if isHeaderDisplayedForGivenOffset(updatedOffset) { scrollView?.contentOffset = CGPoint(x: contentOffset.x, y: contentOffset.y - delta) } updatedOffset = footerBottomOffset + delta footerBottomOffset = clamp(updatedOffset, min: 0, max: bottomScrollHeight) let alpha = 1 - abs(headerTopOffset / topScrollHeight) urlBar?.updateAlphaForSubviews(alpha) } func isHeaderDisplayedForGivenOffset(offset: CGFloat) -> Bool { return offset > -topScrollHeight && offset < 0 } func clamp(y: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat { if y >= max { return max } else if y <= min { return min } return y } func animateToolbarsWithOffsets(animated animated: Bool, duration: NSTimeInterval, headerOffset: CGFloat, footerOffset: CGFloat, alpha: CGFloat, completion: ((finished: Bool) -> Void)?) { let animation: () -> Void = { self.headerTopOffset = headerOffset self.footerBottomOffset = footerOffset self.urlBar?.updateAlphaForSubviews(alpha) self.header?.superview?.layoutIfNeeded() } if animated { UIView.animateWithDuration(duration, animations: animation, completion: completion) } else { animation() completion?(finished: true) } } func checkScrollHeightIsLargeEnoughForScrolling() -> Bool { return (UIScreen.mainScreen().bounds.size.height + 2 * UIConstants.ToolbarHeight) < scrollView?.contentSize.height } } extension TabScrollingController: UIGestureRecognizerDelegate { func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } extension TabScrollingController: UIScrollViewDelegate { func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if tabIsLoading() { return } if (decelerate || (toolbarState == .Animating && !decelerate)) && checkScrollHeightIsLargeEnoughForScrolling() { if scrollDirection == .Up { showToolbars(animated: true) } else if scrollDirection == .Down { hideToolbars(animated: true) } } } func scrollViewShouldScrollToTop(scrollView: UIScrollView) -> Bool { showToolbars(animated: true) return true } }
mpl-2.0
088c731900fdd9def83ae5b6cc0d55fe
33.424
157
0.624797
5.520205
false
false
false
false
hyperoslo/Sync
iOSDemo/iOS/Source/ItemsController.swift
1
1650
import UIKit import Sync class ItemsController: UITableViewController { var fetcher: Fetcher var users = [User]() init(style: UITableViewStyle = .plain, fetcher: Fetcher) { self.fetcher = fetcher super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.tableView.dataSource = self self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: String(describing: UITableViewCell.self)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Refresh", style: .done, target: self, action: #selector(refresh)) self.users = self.fetcher.fetchLocalUsers() self.refresh() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UITableViewCell.self), for: indexPath) let user = self.users[indexPath.row] cell.textLabel?.text = user.name return cell } @objc func refresh() { self.fetcher.syncUsingNetworking { result in switch result { case .success: self.users = self.fetcher.fetchLocalUsers() self.tableView.reloadData() case .failure(let error): print(error) } } } }
mit
fb172af5c7afb19c593158dc0974487d
30.132075
138
0.644848
4.94012
false
false
false
false
fedtuck/Spine
Spine/SerializeOperation.swift
1
6817
// // SerializeOperation.swift // Spine // // Created by Ward van Teijlingen on 30-12-14. // Copyright (c) 2014 Ward van Teijlingen. All rights reserved. // import Foundation import SwiftyJSON /** A SerializeOperation is responsible for serializing resource into a multidimensional dictionary/array structure. The resouces are converted to their serialized form using a layered process. This process is the inverse of that of the DeserializeOperation. */ class SerializeOperation: NSOperation { private let resources: [ResourceProtocol] var transformers = TransformerDirectory() var options = SerializationOptions() var result: NSData? // MARK: Initializers init(resources: [ResourceProtocol]) { self.resources = resources } // MARK: NSOperation override func main() { if resources.count == 1 { let serializedData = serializeResource(resources.first!) result = NSJSONSerialization.dataWithJSONObject(["data": serializedData], options: NSJSONWritingOptions(0), error: nil) } else { var data = resources.map { resource in self.serializeResource(resource) } result = NSJSONSerialization.dataWithJSONObject(["data": data], options: NSJSONWritingOptions(0), error: nil) } } // MARK: Serializing private func serializeResource(resource: ResourceProtocol) -> [String: AnyObject] { Spine.logDebug(.Serializing, "Serializing resource \(resource) of type '\(resource.type)' with id '\(resource.id)'") var serializedData: [String: AnyObject] = [:] // Serialize ID if options.includeID { if let ID = resource.id { serializedData["id"] = ID } } // Serialize type serializedData["type"] = resource.type // Serialize fields addAttributes(&serializedData, resource: resource) addRelationships(&serializedData, resource: resource) return serializedData } // MARK: Attributes /** Adds the attributes of the the given resource to the passed serialized data. This method loops over all the attributes in the passed resource, maps the attribute name to the key for the serialized form and formats the value of the attribute. It then passes the key and value to the addAttribute method. :param: serializedData The data to add the attributes to. :param: resource The resource whose attributes to add. */ private func addAttributes(inout serializedData: [String: AnyObject], resource: ResourceProtocol) { var attributes = [String: AnyObject](); enumerateFields(resource, Attribute.self) { attribute in let key = attribute.serializedName Spine.logDebug(.Serializing, "Serializing attribute \(attribute) with name '\(attribute.name) as '\(key)'") //TODO: Dirty checking if let unformattedValue: AnyObject = resource.valueForField(attribute.name) { self.addAttribute(&attributes, key: key, value: self.transformers.serialize(unformattedValue, forAttribute: attribute)) } else { self.addAttribute(&attributes, key: key, value: NSNull()) } } serializedData["attributes"] = attributes } /** Adds the given key/value pair to the passed serialized data. :param: serializedData The data to add the key/value pair to. :param: key The key to add to the serialized data. :param: value The value to add to the serialized data. */ private func addAttribute(inout serializedData: [String: AnyObject], key: String, value: AnyObject) { serializedData[key] = value } // MARK: Relationships /** Adds the relationships of the the given resource to the passed serialized data. This method loops over all the relationships in the passed resource, maps the attribute name to the key for the serialized form and gets the related attributes. It then passes the key and related resources to either the addToOneRelationship or addToManyRelationship method. :param: serializedData The data to add the relationships to. :param: resource The resource whose relationships to add. */ private func addRelationships(inout serializedData: [String: AnyObject], resource: ResourceProtocol) { enumerateFields(resource, Relationship.self) { field in let key = field.serializedName Spine.logDebug(.Serializing, "Serializing relationship \(field) with name '\(field.name) as '\(key)'") switch field { case let toOne as ToOneRelationship: if self.options.includeToOne { self.addToOneRelationship(&serializedData, key: key, type: toOne.linkedType, linkedResource: resource.valueForField(field.name) as? ResourceProtocol) } case let toMany as ToManyRelationship: if self.options.includeToMany { self.addToManyRelationship(&serializedData, key: key, type: toMany.linkedType, linkedResources: resource.valueForField(field.name) as? ResourceCollection) } default: () } } } /** Adds the given resource as a to to-one relationship to the serialized data. :param: serializedData The data to add the related resource to. :param: key The key to add to the serialized data. :param: relatedResource The related resource to add to the serialized data. */ private func addToOneRelationship(inout serializedData: [String: AnyObject], key: String, type: ResourceType, linkedResource: ResourceProtocol?) { let serializedRelationship = [ "data": [ "type": type, "id": linkedResource?.id ?? NSNull() ] ] if serializedData["relationships"] == nil { serializedData["relationships"] = [key: serializedRelationship] } else { var relationships = serializedData["relationships"] as! [String: AnyObject] relationships[key] = serializedRelationship serializedData["relationships"] = relationships } } /** Adds the given resources as a to to-many relationship to the serialized data. :param: serializedData The data to add the related resources to. :param: key The key to add to the serialized data. :param: relatedResources The related resources to add to the serialized data. */ private func addToManyRelationship(inout serializedData: [String: AnyObject], key: String, type: ResourceType, linkedResources: ResourceCollection?) { var resourceIdentifiers: [ResourceIdentifier] = [] if let resources = linkedResources?.resources { resourceIdentifiers = resources.filter { $0.id != nil }.map { resource in return ResourceIdentifier(type: resource.type, id: resource.id!) } } let serializedRelationship = [ "data": resourceIdentifiers.map { $0.toDictionary() } ] if serializedData["relationships"] == nil { serializedData["relationships"] = [key: serializedRelationship] } else { var relationships = serializedData["relationships"] as! [String: AnyObject] relationships[key] = serializedRelationship serializedData["relationships"] = relationships } } }
mit
07400a982b647e3fea285954fea2e9eb
32.586207
159
0.727739
4.144073
false
false
false
false
frootloops/swift
test/SILGen/generic_property_base_lifetime.swift
1
6986
// RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s protocol ProtocolA: class { var intProp: Int { get set } } protocol ProtocolB { var intProp: Int { get } } @objc protocol ProtocolO: class { var intProp: Int { get set } } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolA_pF : $@convention(thin) (@owned ProtocolA) -> Int { // CHECK: bb0([[ARG:%.*]] : @owned $ProtocolA): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[BORROWED_PROJECTION_COPY:%.*]] = begin_borrow [[PROJECTION_COPY]] // CHECK: [[WITNESS_METHOD:%.*]] = witness_method $@opened({{.*}}) ProtocolA, #ProtocolA.intProp!getter.1 : {{.*}}, [[PROJECTION]] // CHECK: [[RESULT:%.*]] = apply [[WITNESS_METHOD]]<@opened{{.*}}>([[BORROWED_PROJECTION_COPY]]) // CHECK: end_borrow [[BORROWED_PROJECTION_COPY]] from [[PROJECTION_COPY]] // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolA_pF' func getIntPropExistential(_ a: ProtocolA) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolA_pF : $@convention(thin) (@owned ProtocolA) -> () { // CHECK: bb0([[ARG:%.*]] : @owned $ProtocolA): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[BORROWED_PROJECTION_COPY:%.*]] = begin_borrow [[PROJECTION_COPY]] // CHECK: [[WITNESS_METHOD:%.*]] = witness_method $@opened({{.*}}) ProtocolA, #ProtocolA.intProp!setter.1 : {{.*}}, [[PROJECTION]] // CHECK: apply [[WITNESS_METHOD]]<@opened{{.*}}>({{%.*}}, [[BORROWED_PROJECTION_COPY]]) // CHECK: end_borrow [[BORROWED_PROJECTION_COPY]] from [[PROJECTION_COPY]] // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolA_pF' func setIntPropExistential(_ a: ProtocolA) { a.intProp = 0 } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17getIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @owned $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>([[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func getIntPropGeneric<T: ProtocolA>(_ a: T) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17setIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @owned $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>({{%.*}}, [[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func setIntPropGeneric<T: ProtocolA>(_ a: T) { a.intProp = 0 } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolB_pF // CHECK: [[PROJECTION:%.*]] = open_existential_addr immutable_access %0 // CHECK: [[STACK:%[0-9]+]] = alloc_stack $@opened({{".*"}}) ProtocolB // CHECK: copy_addr [[PROJECTION]] to [initialization] [[STACK]] // CHECK: apply {{%.*}}([[STACK]]) // CHECK: destroy_addr [[STACK]] // CHECK: dealloc_stack [[STACK]] // CHECK: destroy_addr %0 func getIntPropExistential(_ a: ProtocolB) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17getIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] // CHECK: apply {{%.*}}<T>([[STACK]]) // CHECK: destroy_addr [[STACK]] // CHECK: dealloc_stack [[STACK]] // CHECK: destroy_addr %0 func getIntPropGeneric<T: ProtocolB>(_ a: T) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolO_pF : $@convention(thin) (@owned ProtocolO) -> Int { // CHECK: bb0([[ARG:%.*]] : @owned $ProtocolO): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[METHOD:%.*]] = objc_method [[PROJECTION_COPY]] : $@opened({{.*}}) ProtocolO, #ProtocolO.intProp!getter.1.foreign : {{.*}} // CHECK: apply [[METHOD]]<@opened{{.*}}>([[PROJECTION_COPY]]) // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolO_pF' func getIntPropExistential(_ a: ProtocolO) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolO_pF : $@convention(thin) (@owned ProtocolO) -> () { // CHECK: bb0([[ARG:%.*]] : @owned $ProtocolO): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[METHOD:%.*]] = objc_method [[PROJECTION_COPY]] : $@opened({{.*}}) ProtocolO, #ProtocolO.intProp!setter.1.foreign : {{.*}} // CHECK: apply [[METHOD]]<@opened{{.*}}>({{.*}}, [[PROJECTION_COPY]]) // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolO_pF' func setIntPropExistential(_ a: ProtocolO) { a.intProp = 0 } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17getIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @owned $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>([[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func getIntPropGeneric<T: ProtocolO>(_ a: T) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17setIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @owned $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>({{%.*}}, [[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func setIntPropGeneric<T: ProtocolO>(_ a: T) { a.intProp = 0 }
apache-2.0
425955e96fa51d04178c7962443d7b6a
48.197183
152
0.633123
3.318765
false
false
false
false
yrchen/edx-app-ios
Source/DataManager.swift
1
760
// // DataManager.swift // edX // // Created by Akiva Leffert on 5/6/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation public class DataManager : NSObject { let courseDataManager : CourseDataManager let interface : OEXInterface? let pushSettings : OEXPushSettingsManager let userProfileManager : UserProfileManager public init(courseDataManager : CourseDataManager, interface : OEXInterface? = nil, pushSettings : OEXPushSettingsManager = OEXPushSettingsManager(), userProfileManager : UserProfileManager) { self.courseDataManager = courseDataManager self.pushSettings = pushSettings self.interface = interface self.userProfileManager = userProfileManager } }
apache-2.0
b915f02e2725e9859b68f19b81e4f7f5
29.4
196
0.725
4.871795
false
false
false
false
magnetsystems/message-samples-ios
SmartShopper/Pods/Argo/Argo/Operators/Operators.swift
6
1716
infix operator <| { associativity left precedence 150 } infix operator <|? { associativity left precedence 150 } infix operator <|| { associativity left precedence 150 } infix operator <||? { associativity left precedence 150 } // MARK: Values // Pull value from JSON public func <| <A where A: Decodable, A == A.DecodedType>(json: JSON, key: String) -> Decoded<A> { return json <| [key] } // Pull optional value from JSON public func <|? <A where A: Decodable, A == A.DecodedType>(json: JSON, key: String) -> Decoded<A?> { return .optional(json <| [key]) } // Pull embedded value from JSON public func <| <A where A: Decodable, A == A.DecodedType>(json: JSON, keys: [String]) -> Decoded<A> { return flatReduce(keys, initial: json, combine: decodedJSON) >>- A.decode } // Pull embedded optional value from JSON public func <|? <A where A: Decodable, A == A.DecodedType>(json: JSON, keys: [String]) -> Decoded<A?> { return .optional(json <| keys) } // MARK: Arrays // Pull array from JSON public func <|| <A where A: Decodable, A == A.DecodedType>(json: JSON, key: String) -> Decoded<[A]> { return json <|| [key] } // Pull optional array from JSON public func <||? <A where A: Decodable, A == A.DecodedType>(json: JSON, key: String) -> Decoded<[A]?> { return .optional(json <|| [key]) } // Pull embedded array from JSON public func <|| <A where A: Decodable, A == A.DecodedType>(json: JSON, keys: [String]) -> Decoded<[A]> { return flatReduce(keys, initial: json, combine: decodedJSON) >>- Array<A>.decode } // Pull embedded optional array from JSON public func <||? <A where A: Decodable, A == A.DecodedType>(json: JSON, keys: [String]) -> Decoded<[A]?> { return .optional(json <|| keys) }
apache-2.0
5f4df7ad921873a291f77751f16ee467
34.75
106
0.662587
3.567568
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/PeerInfoHeadItem.swift
1
51581
// // PeerInfoHeadItem.swift // Telegram // // Created by Mikhail Filimonov on 01/04/2020. // Copyright © 2020 Telegram. All rights reserved. // import Cocoa import TGUIKit import Postbox import SwiftSignalKit import TelegramCore import ColorPalette fileprivate final class ActionButton : Control { fileprivate let imageView: ImageView = ImageView() fileprivate let textView: TextView = TextView() required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(imageView) addSubview(textView) self.imageView.animates = true imageView.isEventLess = true textView.isEventLess = true textView.userInteractionEnabled = false textView.isSelectable = false set(handler: { control in control.change(opacity: 0.8, animated: true) }, for: .Highlight) set(handler: { control in control.change(opacity: 1.0, animated: true) }, for: .Normal) set(handler: { control in control.change(opacity: 1.0, animated: true) }, for: .Hover) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateAndLayout(item: ActionItem, theme: PresentationTheme) { self.imageView.image = item.image self.imageView.sizeToFit() self.textView.update(item.textLayout) self.backgroundColor = theme.colors.background self.layer?.cornerRadius = 10 self.removeAllHandlers() if let subItems = item.subItems, !subItems.isEmpty { self.contextMenu = { let menu = ContextMenu() for sub in subItems { let item = ContextMenuItem(sub.text, handler: sub.action, itemMode: sub.destruct ? .destruct : .normal, itemImage: sub.animation.value) if sub.destruct { menu.addItem(ContextSeparatorItem()) } menu.addItem(item) } return menu } } else { self.contextMenu = nil self.set(handler: { [weak item] _ in item?.action() }, for: .Click) } needsLayout = true } override func layout() { super.layout() imageView.centerX(y: 5) textView.centerX(y: frame.height - textView.frame.height - 11) } } extension TelegramPeerPhoto : Equatable { public static func ==(lhs: TelegramPeerPhoto, rhs: TelegramPeerPhoto) -> Bool { if lhs.date != rhs.date { return false } if !lhs.image.isEqual(to: rhs.image) { return false } if lhs.index != rhs.index { return false } if lhs.messageId != rhs.messageId { return false } if lhs.reference != rhs.reference { return false } if lhs.totalCount != rhs.totalCount { return false } return true } } fileprivate let actionItemWidth: CGFloat = 135 fileprivate let actionItemInsetWidth: CGFloat = 19 private struct SubActionItem { let text: String let destruct: Bool let action:()->Void let animation: LocalAnimatedSticker init(text: String, animation: LocalAnimatedSticker, destruct: Bool = false, action:@escaping()->Void) { self.text = text self.animation = animation self.action = action self.destruct = destruct } } private final class ActionItem { let text: String let destruct: Bool let image: CGImage let action:()->Void let animation: LocalAnimatedSticker let subItems:[SubActionItem]? let textLayout: TextViewLayout let size: NSSize init(text: String, image: CGImage, animation: LocalAnimatedSticker, destruct: Bool = false, action: @escaping()->Void, subItems:[SubActionItem]? = nil) { self.text = text self.image = image self.action = action self.animation = animation self.subItems = subItems self.destruct = destruct self.textLayout = TextViewLayout(.initialize(string: text, color: theme.colors.accent, font: .normal(.text)), alignment: .center) self.textLayout.measure(width: actionItemWidth) self.size = NSMakeSize(actionItemWidth, image.backingSize.height + textLayout.layoutSize.height + 10) } } private func actionItems(item: PeerInfoHeadItem, width: CGFloat, theme: TelegramPresentationTheme) -> [ActionItem] { var items:[ActionItem] = [] var rowItemsCount: Int = 1 while width - (actionItemWidth + actionItemInsetWidth) > ((actionItemWidth * CGFloat(rowItemsCount)) + (CGFloat(rowItemsCount - 1) * actionItemInsetWidth)) { rowItemsCount += 1 } rowItemsCount = min(rowItemsCount, 4) if let peer = item.peer as? TelegramUser, let arguments = item.arguments as? UserInfoArguments { if !(item.peerView.peers[item.peerView.peerId] is TelegramSecretChat) { items.append(ActionItem(text: strings().peerInfoActionMessage, image: theme.icons.profile_message, animation: .menu_show_message, action: arguments.sendMessage)) } if peer.canCall && peer.id != item.context.peerId, !isServicePeer(peer) && !peer.rawDisplayTitle.isEmpty { if let cachedData = item.peerView.cachedData as? CachedUserData, cachedData.voiceCallsAvailable { items.append(ActionItem(text: strings().peerInfoActionCall, image: theme.icons.profile_call, animation: .menu_call, action: { arguments.call(false) })) } } let videoConfiguration: VideoCallsConfiguration = VideoCallsConfiguration(appConfiguration: item.context.appConfiguration) let isVideoPossible: Bool switch videoConfiguration.videoCallsSupport { case .disabled: isVideoPossible = false case .full: isVideoPossible = true case .onlyVideo: isVideoPossible = true } if peer.canCall && peer.id != item.context.peerId, !isServicePeer(peer) && !peer.rawDisplayTitle.isEmpty, isVideoPossible { if let cachedData = item.peerView.cachedData as? CachedUserData, cachedData.videoCallsAvailable { items.append(ActionItem(text: strings().peerInfoActionVideoCall, image: theme.icons.profile_video_call, animation: .menu_video_call, action: { arguments.call(true) })) } } let value = item.peerView.notificationSettings?.isRemovedFromTotalUnreadCount(default: false) ?? false items.append(ActionItem(text: value ? strings().peerInfoActionUnmute : strings().peerInfoActionMute, image: value ? theme.icons.profile_unmute : theme.icons.profile_mute, animation: .menu_mute, action: { arguments.toggleNotifications(value) })) if !peer.isBot { if !(item.peerView.peers[item.peerView.peerId] is TelegramSecretChat), arguments.context.peerId != peer.id, !isServicePeer(peer) && !peer.rawDisplayTitle.isEmpty { items.append(ActionItem(text: strings().peerInfoActionSecretChat, image: theme.icons.profile_secret_chat, animation: .menu_lock, action: arguments.startSecretChat)) } if peer.id != item.context.peerId, item.peerView.peerIsContact, peer.phone != nil { items.append(ActionItem(text: strings().peerInfoActionShare, image: theme.icons.profile_share, animation: .menu_forward, action: arguments.shareContact)) } if peer.id != item.context.peerId, !peer.isPremium { if let cachedData = item.peerView.cachedData as? CachedUserData { if !cachedData.premiumGiftOptions.isEmpty { items.append(ActionItem(text: strings().peerInfoActionGiftPremium, image: theme.icons.profile_share, animation: .menu_gift, action: { arguments.giftPremium(cachedData.premiumGiftOptions) })) } } } if peer.id != item.context.peerId, let cachedData = item.peerView.cachedData as? CachedUserData, item.peerView.peerIsContact { items.append(ActionItem(text: (!cachedData.isBlocked ? strings().peerInfoBlockUser : strings().peerInfoUnblockUser), image: !cachedData.isBlocked ? theme.icons.profile_block : theme.icons.profile_unblock, animation: cachedData.isBlocked ? .menu_unblock : .menu_restrict, destruct: true, action: { arguments.updateBlocked(peer: peer, !cachedData.isBlocked, false) })) } } else if let botInfo = peer.botInfo { if let address = peer.addressName, !address.isEmpty { items.append(ActionItem(text: strings().peerInfoBotShare, image: theme.icons.profile_share, animation: .menu_forward, action: { arguments.botShare(address) })) } if botInfo.flags.contains(.worksWithGroups) { items.append(ActionItem(text: strings().peerInfoBotAddToGroup, image: theme.icons.profile_more, animation: .menu_plus, action: arguments.botAddToGroup)) } if let cachedData = item.peerView.cachedData as? CachedUserData, let botInfo = cachedData.botInfo { for command in botInfo.commands { if command.text == "settings" { items.append(ActionItem(text: strings().peerInfoBotSettings, image: theme.icons.profile_more, animation: .menu_plus, action: arguments.botSettings)) } if command.text == "help" { items.append(ActionItem(text: strings().peerInfoBotHelp, image: theme.icons.profile_more, animation: .menu_plus, action: arguments.botHelp)) } if command.text == "privacy" { items.append(ActionItem(text: strings().peerInfoBotPrivacy, image: theme.icons.profile_more, animation: .menu_plus, action: arguments.botPrivacy)) } } items.append(ActionItem(text: !cachedData.isBlocked ? strings().peerInfoStopBot : strings().peerInfoRestartBot, image: theme.icons.profile_more, animation: .menu_restrict, destruct: true, action: { arguments.updateBlocked(peer: peer, !cachedData.isBlocked, true) })) } } } else if let peer = item.peer, peer.isSupergroup || peer.isGroup, let arguments = item.arguments as? GroupInfoArguments { let access = peer.groupAccess if access.canAddMembers { items.append(ActionItem(text: strings().peerInfoActionAddMembers, image: theme.icons.profile_add_member, animation: .menu_plus, action: { arguments.addMember(access.canCreateInviteLink) })) } if let value = item.peerView.notificationSettings?.isRemovedFromTotalUnreadCount(default: false) { items.append(ActionItem(text: value ? strings().peerInfoActionUnmute : strings().peerInfoActionMute, image: value ? theme.icons.profile_unmute : theme.icons.profile_mute, animation: value ? .menu_unmuted : .menu_mute, action: { arguments.toggleNotifications(value) })) } if let cachedData = item.peerView.cachedData as? CachedChannelData, let peer = peer as? TelegramChannel { if peer.groupAccess.canMakeVoiceChat { let isLiveStream = peer.isChannel || peer.flags.contains(.isGigagroup) items.append(ActionItem(text: isLiveStream ? strings().peerInfoActionLiveStream : strings().peerInfoActionVoiceChat, image: theme.icons.profile_voice_chat, animation: .menu_video_chat, action: { arguments.makeVoiceChat(cachedData.activeCall, callJoinPeerId: cachedData.callJoinPeerId) })) } } else if let cachedData = item.peerView.cachedData as? CachedGroupData { if peer.groupAccess.canMakeVoiceChat { items.append(ActionItem(text: strings().peerInfoActionVoiceChat, image: theme.icons.profile_voice_chat, animation: .menu_call, action: { arguments.makeVoiceChat(cachedData.activeCall, callJoinPeerId: cachedData.callJoinPeerId) })) } } if let cachedData = item.peerView.cachedData as? CachedChannelData { if cachedData.statsDatacenterId > 0, cachedData.flags.contains(.canViewStats) { items.append(ActionItem(text: strings().peerInfoActionStatistics, image: theme.icons.profile_stats, animation: .menu_statistics, action: { arguments.stats(cachedData.statsDatacenterId) })) } } if access.canReport { items.append(ActionItem(text: strings().peerInfoActionReport, image: theme.icons.profile_report, animation: .menu_report, destruct: false, action: arguments.report)) } if let group = peer as? TelegramGroup { if case .Member = group.membership { items.append(ActionItem(text: strings().peerInfoActionLeave, image: theme.icons.profile_leave, animation: .menu_leave, destruct: true, action: arguments.delete)) } } else if let group = peer as? TelegramChannel { if case .member = group.participationStatus { items.append(ActionItem(text: strings().peerInfoActionLeave, image: theme.icons.profile_leave, animation: .menu_delete, destruct: true, action: arguments.delete)) } } } else if let peer = item.peer as? TelegramChannel, peer.isChannel, let arguments = item.arguments as? ChannelInfoArguments { if let value = item.peerView.notificationSettings?.isRemovedFromTotalUnreadCount(default: false) { items.append(ActionItem(text: value ? strings().peerInfoActionUnmute : strings().peerInfoActionMute, image: value ? theme.icons.profile_unmute : theme.icons.profile_mute, animation: value ? .menu_unmuted : .menu_mute, action: { arguments.toggleNotifications(value) })) } if let cachedData = item.peerView.cachedData as? CachedChannelData { switch cachedData.linkedDiscussionPeerId { case let .known(peerId): if let peerId = peerId { items.append(ActionItem(text: strings().peerInfoActionDiscussion, image: theme.icons.profile_message, animation: .menu_show_message, action: { [weak arguments] in arguments?.peerChat(peerId) })) } default: break } if cachedData.statsDatacenterId > 0, cachedData.flags.contains(.canViewStats) { items.append(ActionItem(text: strings().peerInfoActionStatistics, image: theme.icons.profile_stats, animation: .menu_statistics, action: { arguments.stats(cachedData.statsDatacenterId) })) } } if let cachedData = item.peerView.cachedData as? CachedChannelData { if peer.groupAccess.canMakeVoiceChat { items.append(ActionItem(text: strings().peerInfoActionVoiceChat, image: theme.icons.profile_voice_chat, animation: .menu_call, action: { arguments.makeVoiceChat(cachedData.activeCall, callJoinPeerId: cachedData.callJoinPeerId) })) } } if let address = peer.addressName, !address.isEmpty { items.append(ActionItem(text: strings().peerInfoActionShare, image: theme.icons.profile_share, animation: .menu_share, action: arguments.share)) } if peer.groupAccess.canReport { items.append(ActionItem(text: strings().peerInfoActionReport, image: theme.icons.profile_report, animation: .menu_report, action: arguments.report)) } switch peer.participationStatus { case .member: items.append(ActionItem(text: strings().peerInfoActionLeave, image: theme.icons.profile_leave, animation: .menu_leave, destruct: true, action: arguments.delete)) default: break } } else if let arguments = item.arguments as? TopicInfoArguments, let data = arguments.threadData { let value = data.notificationSettings.isMuted items.append(ActionItem(text: value ? strings().peerInfoActionUnmute : strings().peerInfoActionMute, image: value ? theme.icons.profile_unmute : theme.icons.profile_mute, animation: .menu_mute, action: { arguments.toggleNotifications(value) })) items.append(ActionItem(text: strings().peerInfoActionShare, image: theme.icons.profile_share, animation: .menu_share, action: arguments.share)) } if items.count > rowItemsCount { var subItems:[SubActionItem] = [] while items.count > rowItemsCount - 1 { let item = items.removeLast() subItems.insert(SubActionItem(text: item.text, animation: item.animation, destruct: item.destruct, action: item.action), at: 0) } if !subItems.isEmpty { items.append(ActionItem(text: strings().peerInfoActionMore, image: theme.icons.profile_more, animation: .menu_plus, action: { }, subItems: subItems)) } } return items } class PeerInfoHeadItem: GeneralRowItem { override var height: CGFloat { let insets = self.viewType.innerInset var height: CGFloat = 0 if !editing { height = photoDimension + insets.top + insets.bottom + nameLayout.layoutSize.height + statusLayout.layoutSize.height + insets.bottom if !items.isEmpty { let maxActionSize: NSSize = items.max(by: { $0.size.height < $1.size.height })!.size height += maxActionSize.height + insets.top } } else { height = photoDimension + insets.top + insets.bottom } return height } fileprivate var photoDimension:CGFloat { return self.threadData != nil ? 60 : 120 } fileprivate var statusLayout: TextViewLayout fileprivate var nameLayout: TextViewLayout let context: AccountContext let peer:Peer? let isVerified: Bool let isPremium: Bool let isScam: Bool let isFake: Bool let isMuted: Bool let peerView:PeerView var result:PeerStatusStringResult { didSet { nameLayout = TextViewLayout(result.title, maximumNumberOfLines: 1) nameLayout.interactions = globalLinkExecutor statusLayout = TextViewLayout(result.status, maximumNumberOfLines: 1, alwaysStaticItems: true) } } private(set) fileprivate var items: [ActionItem] = [] private let fetchPeerAvatar = DisposableSet() private let onlineMemberCountDisposable = MetaDisposable() fileprivate let editing: Bool fileprivate let updatingPhotoState:PeerInfoUpdatingPhotoState? fileprivate let updatePhoto:(NSImage?, Control?)->Void fileprivate let arguments: PeerInfoArguments fileprivate let threadData: MessageHistoryThreadData? let canEditPhoto: Bool let peerPhotosDisposable = MetaDisposable() var photos: [TelegramPeerPhoto] = [] init(_ initialSize:NSSize, stableId:AnyHashable, context: AccountContext, arguments: PeerInfoArguments, peerView:PeerView, threadData: MessageHistoryThreadData?, viewType: GeneralViewType, editing: Bool, updatingPhotoState:PeerInfoUpdatingPhotoState? = nil, updatePhoto:@escaping(NSImage?, Control?)->Void = { _, _ in }) { let peer = peerViewMainPeer(peerView) self.peer = peer self.threadData = threadData self.peerView = peerView self.context = context self.editing = editing self.arguments = arguments self.isVerified = peer?.isVerified ?? false self.isPremium = peer?.isPremium ?? false self.isScam = peer?.isScam ?? false self.isFake = peer?.isFake ?? false self.isMuted = peerView.notificationSettings?.isRemovedFromTotalUnreadCount(default: false) ?? false self.updatingPhotoState = updatingPhotoState self.updatePhoto = updatePhoto let canEditPhoto: Bool if let _ = peer as? TelegramUser { canEditPhoto = false } else if let _ = peer as? TelegramSecretChat { canEditPhoto = false } else if let peer = peer as? TelegramGroup { canEditPhoto = peer.groupAccess.canEditGroupInfo } else if let peer = peer as? TelegramChannel { canEditPhoto = peer.groupAccess.canEditGroupInfo } else { canEditPhoto = false } self.canEditPhoto = canEditPhoto && editing if let peer = peer, threadData == nil { if let peerReference = PeerReference(peer) { if let largeProfileImage = peer.largeProfileImage { fetchPeerAvatar.add(fetchedMediaResource(mediaBox: context.account.postbox.mediaBox, reference: .avatar(peer: peerReference, resource: largeProfileImage.resource)).start()) } if let smallProfileImage = peer.smallProfileImage { fetchPeerAvatar.add(fetchedMediaResource(mediaBox: context.account.postbox.mediaBox, reference: .avatar(peer: peerReference, resource: smallProfileImage.resource)).start()) } } } var result = stringStatus(for: peerView, context: context, theme: PeerStatusStringTheme(titleFont: .medium(.huge), highlightIfActivity: false), expanded: true) if let threadData = threadData { result = result .withUpdatedTitle(threadData.info.title) .withUpdatedStatus(strings().peerInfoTopicStatusIn(peer?.displayTitle ?? "")) } self.result = result nameLayout = TextViewLayout(result.title, maximumNumberOfLines: 1) statusLayout = TextViewLayout(result.status, maximumNumberOfLines: 1, alwaysStaticItems: true) super.init(initialSize, stableId: stableId, viewType: viewType) if let cachedData = peerView.cachedData as? CachedChannelData, threadData == nil { let onlineMemberCount:Signal<Int32?, NoError> if (cachedData.participantsSummary.memberCount ?? 0) > 200 { onlineMemberCount = context.peerChannelMemberCategoriesContextsManager.recentOnline(peerId: peerView.peerId) |> map(Optional.init) |> deliverOnMainQueue } else { onlineMemberCount = context.peerChannelMemberCategoriesContextsManager.recentOnlineSmall(peerId: peerView.peerId) |> map(Optional.init) |> deliverOnMainQueue } self.onlineMemberCountDisposable.set(onlineMemberCount.start(next: { [weak self] count in guard let `self` = self else { return } var result = stringStatus(for: peerView, context: context, theme: PeerStatusStringTheme(titleFont: .medium(.huge)), onlineMemberCount: count) if let threadData = threadData { result = result.withUpdatedTitle(threadData.info.title) result = result.withUpdatedStatus(strings().peerInfoTopicStatusIn(peer?.displayTitle ?? "")) } if result != self.result { self.result = result _ = self.makeSize(self.width, oldWidth: 0) self.redraw(animated: true, options: .effectFade) } })) } _ = self.makeSize(initialSize.width, oldWidth: 0) if let peer = peer, threadData == nil, peer.hasVideo { self.photos = syncPeerPhotos(peerId: peer.id) let signal = peerPhotos(context: context, peerId: peer.id) |> deliverOnMainQueue var first: Bool = true peerPhotosDisposable.set(signal.start(next: { [weak self] photos in if self?.photos != photos { self?.photos = photos if !first { self?.redraw(animated: true, options: .effectFade) } first = false } })) } } var isForum: Bool { return self.peer?.isForum == true } var isTopic: Bool { return self.isForum && threadData != nil } deinit { fetchPeerAvatar.dispose() onlineMemberCountDisposable.dispose() } override func viewClass() -> AnyClass { return PeerInfoHeadView.self } override func makeSize(_ width: CGFloat, oldWidth:CGFloat) -> Bool { let success = super.makeSize(width, oldWidth: oldWidth) self.items = editing ? [] : actionItems(item: self, width: blockWidth, theme: theme) var textWidth = blockWidth - viewType.innerInset.right - viewType.innerInset.left - 10 if let peer = peer, let controlSize = PremiumStatusControl.controlSize(peer, true) { textWidth -= (controlSize.width + 5) } nameLayout.measure(width: textWidth) statusLayout.measure(width: textWidth) return success } var stateText: String? { if isScam { return strings().peerInfoScamWarning } else if isFake { return strings().peerInfoFakeWarning } else if isVerified { return strings().peerInfoVerifiedTooltip } else if isPremium { return strings().peerInfoPremiumTooltip } return nil } fileprivate var nameSize: NSSize { var stateHeight: CGFloat = 0 if let peer = peer, let size = PremiumStatusControl.controlSize(peer, true) { stateHeight = max(size.height + 4, nameLayout.layoutSize.height) } else { stateHeight = nameLayout.layoutSize.height } var width = nameLayout.layoutSize.width if let peer = peer, let size = PremiumStatusControl.controlSize(peer, true) { width += size.width + 5 } return NSMakeSize(width, stateHeight) } } private final class PeerInfoPhotoEditableView : Control { private let backgroundView = View() private let camera: ImageView = ImageView() private var progressView:RadialProgressContainerView? private var updatingPhotoState: PeerInfoUpdatingPhotoState? private var tempImageView: ImageView? var setup: ((NSImage?, Control?)->Void)? required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(backgroundView) addSubview(camera) camera.image = theme.icons.profile_edit_photo camera.sizeToFit() camera.center() camera.isEventLess = true backgroundView.isEventLess = true set(handler: { [weak self] _ in if self?.updatingPhotoState == nil { self?.backgroundView.change(opacity: 0.8, animated: true) self?.camera.change(opacity: 0.8, animated: true) } }, for: .Highlight) set(handler: { [weak self] _ in if self?.updatingPhotoState == nil { self?.backgroundView.change(opacity: 1.0, animated: true) self?.camera.change(opacity: 1.0, animated: true) } }, for: .Normal) set(handler: { [weak self] _ in if self?.updatingPhotoState == nil { self?.backgroundView.change(opacity: 1.0, animated: true) self?.camera.change(opacity: 1.0, animated: true) } }, for: .Hover) backgroundView.backgroundColor = .blackTransparent backgroundView.frame = bounds set(handler: { [weak self] control in if self?.updatingPhotoState == nil { self?.setup?(nil, control) } }, for: .Click) } func updateState(_ updatingPhotoState: PeerInfoUpdatingPhotoState?, animated: Bool) { self.updatingPhotoState = updatingPhotoState userInteractionEnabled = updatingPhotoState == nil self.camera.change(opacity: updatingPhotoState == nil ? 1.0 : 0.0, animated: true) if let uploadState = updatingPhotoState { if self.progressView == nil { self.progressView = RadialProgressContainerView(theme: RadialProgressTheme(backgroundColor: .clear, foregroundColor: .white, icon: nil)) self.progressView!.frame = bounds progressView?.proggressBackground.backgroundColor = .clear self.addSubview(progressView!) } progressView?.progress.fetchControls = FetchControls(fetch: { updatingPhotoState?.cancel() }) progressView?.progress.state = .Fetching(progress: uploadState.progress, force: false) if let _ = uploadState.image, self.tempImageView == nil { self.tempImageView = ImageView() self.tempImageView?.contentGravity = .resizeAspect self.tempImageView!.frame = bounds self.addSubview(tempImageView!, positioned: .below, relativeTo: backgroundView) if animated { self.tempImageView?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } } self.tempImageView?.image = uploadState.image } else { if let progressView = self.progressView { self.progressView = nil if animated { progressView.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak progressView] _ in progressView?.removeFromSuperview() }) } else { progressView.removeFromSuperview() } } if let tempImageView = self.tempImageView { self.tempImageView = nil if animated { tempImageView.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak tempImageView] _ in tempImageView?.removeFromSuperview() }) } else { tempImageView.removeFromSuperview() } } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private final class NameContainer : View { let nameView = TextView() var statusControl: PremiumStatusControl? required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(nameView) } func update(_ item: PeerInfoHeadItem, animated: Bool) { self.nameView.update(item.nameLayout) let context = item.context if let peer = item.peer { let control = PremiumStatusControl.control(peer, account: item.context.account, inlinePacksContext: item.context.inlinePacksContext, isSelected: false, isBig: true, cached: self.statusControl, animated: animated) if let control = control { self.statusControl = control self.addSubview(control) } else if let view = self.statusControl { performSubviewRemoval(view, animated: animated) self.statusControl = nil } } else if let view = self.statusControl { performSubviewRemoval(view, animated: animated) self.statusControl = nil } if let stateText = item.stateText, let control = statusControl, let peerId = item.peer?.id { control.userInteractionEnabled = true control.scaleOnClick = true control.set(handler: { control in if item.peer?.emojiStatus != nil { showModal(with: PremiumBoardingController(context: context, source: .profile(peerId)), for: context.window) } else { let attr = parseMarkdownIntoAttributedString(stateText, attributes: MarkdownAttributes(body: MarkdownAttributeSet(font: .normal(.text), textColor: .white), bold: MarkdownAttributeSet(font: .bold(.text), textColor: .white), link: MarkdownAttributeSet(font: .normal(.text), textColor: nightAccentPalette.link), linkAttribute: { contents in return (NSAttributedString.Key.link.rawValue, contents) })) if !context.premiumIsBlocked { let interactions = TextViewInteractions(processURL: { content in if let content = content as? String { if content == "premium" { showModal(with: PremiumBoardingController(context: context, source: .profile(peerId)), for: context.window) } } }) tooltip(for: control, text: "", attributedText: attr, interactions: interactions) } } }, for: .Click) } else { statusControl?.scaleOnClick = false statusControl?.userInteractionEnabled = false } needsLayout = true } override func layout() { super.layout() nameView.centerY(x: 0) if let control = statusControl { control.centerY(x: nameView.frame.maxX + 5, addition: -1) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private final class PeerInfoHeadView : GeneralContainableRowView { private let photoView: AvatarControl = AvatarControl(font: .avatar(30)) private var photoVideoView: MediaPlayerView? private var photoVideoPlayer: MediaPlayer? private let nameView = NameContainer(frame: .zero) private let statusView = TextView() private let actionsView = View() private var photoEditableView: PeerInfoPhotoEditableView? private var activeDragging: Bool = false { didSet { self.item?.redraw(animated: true) } } override var backdorColor: NSColor { guard let item = item as? PeerInfoHeadItem else { return super.backdorColor } return item.editing ? super.backdorColor : .clear } required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(photoView) addSubview(nameView) addSubview(statusView) addSubview(actionsView) photoView.set(handler: { [weak self] _ in if let item = self?.item as? PeerInfoHeadItem, let peer = item.peer, let _ = peer.largeProfileImage { showPhotosGallery(context: item.context, peerId: peer.id, firstStableId: item.stableId, item.table, nil) } }, for: .Click) registerForDraggedTypes([.tiff, .string, .kUrl, .kFileUrl]) } override public func performDragOperation(_ sender: NSDraggingInfo) -> Bool { if activeDragging { activeDragging = false if let item = item as? PeerInfoHeadItem { if let tiff = sender.draggingPasteboard.data(forType: .tiff), let image = NSImage(data: tiff) { item.updatePhoto(image, self.photoEditableView) return true } else { let list = sender.draggingPasteboard.propertyList(forType: .kFilenames) as? [String] if let list = list { if let first = list.first, let image = NSImage(contentsOfFile: first) { item.updatePhoto(image, self.photoEditableView) return true } } } } } return false } override public func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { if let item = item as? PeerInfoHeadItem, !item.editing, let peer = item.peer, peer.groupAccess.canEditGroupInfo { if let tiff = sender.draggingPasteboard.data(forType: .tiff), let _ = NSImage(data: tiff) { activeDragging = true } else { let list = sender.draggingPasteboard.propertyList(forType: .kFilenames) as? [String] if let list = list { let list = list.filter { path -> Bool in if let size = fs(path) { return size <= 5 * 1024 * 1024 } return false } activeDragging = list.count == 1 && NSImage(contentsOfFile: list[0]) != nil } else { activeDragging = false } } } else { activeDragging = false } return .generic } override public func draggingExited(_ sender: NSDraggingInfo?) { activeDragging = false } public override func draggingEnded(_ sender: NSDraggingInfo) { activeDragging = false } @objc func updatePlayerIfNeeded() { let accept = window != nil && window!.isKeyWindow && !NSIsEmptyRect(visibleRect) && !isDynamicContentLocked if let photoVideoPlayer = photoVideoPlayer { if accept { photoVideoPlayer.play() } else { photoVideoPlayer.pause() } } } override func addAccesoryOnCopiedView(innerId: AnyHashable, view: NSView) { photoVideoPlayer?.seek(timestamp: 0) } override func viewDidUpdatedDynamicContent() { super.viewDidUpdatedDynamicContent() updatePlayerIfNeeded() } override func viewDidMoveToWindow() { super.viewDidMoveToWindow() updateListeners() updatePlayerIfNeeded() updateAnimatableContent() } override func viewDidMoveToSuperview() { super.viewDidMoveToSuperview() updateListeners() updatePlayerIfNeeded() updateAnimatableContent() } func updateListeners() { if let window = window { NotificationCenter.default.removeObserver(self) NotificationCenter.default.addObserver(self, selector: #selector(updatePlayerIfNeeded), name: NSWindow.didBecomeKeyNotification, object: window) NotificationCenter.default.addObserver(self, selector: #selector(updatePlayerIfNeeded), name: NSWindow.didResignKeyNotification, object: window) NotificationCenter.default.addObserver(self, selector: #selector(updatePlayerIfNeeded), name: NSView.boundsDidChangeNotification, object: item?.table?.clipView) NotificationCenter.default.addObserver(self, selector: #selector(updatePlayerIfNeeded), name: NSView.boundsDidChangeNotification, object: self) NotificationCenter.default.addObserver(self, selector: #selector(updatePlayerIfNeeded), name: NSView.frameDidChangeNotification, object: item?.table?.view) } else { removeNotificationListeners() } } func removeNotificationListeners() { NotificationCenter.default.removeObserver(self) } deinit { removeNotificationListeners() } override func layout() { super.layout() guard let item = item as? PeerInfoHeadItem else { return } photoView.centerX(y: item.viewType.innerInset.top) nameView.centerX(y: photoView.frame.maxY + item.viewType.innerInset.top) statusView.centerX(y: nameView.frame.maxY + 4) actionsView.centerX(y: containerView.frame.height - actionsView.frame.height) photoEditableView?.centerX(y: item.viewType.innerInset.top) photoVideoView?.frame = photoView.frame if let photo = self.inlineTopicPhotoLayer { photo.frame = NSMakeRect(floorToScreenPixels(backingScaleFactor, containerView.frame.width - item.photoDimension) / 2, item.viewType.innerInset.top, item.photoDimension, item.photoDimension) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func layoutActionItems(_ items: [ActionItem], animated: Bool) { if !items.isEmpty { let maxActionSize: NSSize = items.max(by: { $0.size.height < $1.size.height })!.size while actionsView.subviews.count > items.count { actionsView.subviews.removeLast() } while actionsView.subviews.count < items.count { actionsView.addSubview(ActionButton(frame: .zero)) } let inset: CGFloat = 0 actionsView.change(size: NSMakeSize(actionItemWidth * CGFloat(items.count) + CGFloat(items.count - 1) * actionItemInsetWidth, maxActionSize.height), animated: animated) var x: CGFloat = inset for (i, item) in items.enumerated() { let view = actionsView.subviews[i] as! ActionButton view.updateAndLayout(item: item, theme: theme) view.setFrameSize(NSMakeSize(item.size.width, maxActionSize.height)) view.change(pos: NSMakePoint(x, 0), animated: false) x += maxActionSize.width + actionItemInsetWidth } } else { actionsView.removeAllSubviews() } } private var videoRepresentation: TelegramMediaImage.VideoRepresentation? override func set(item: TableRowItem, animated: Bool = false) { super.set(item: item, animated: animated) guard let item = item as? PeerInfoHeadItem else { return } photoView.setFrameSize(NSMakeSize(item.photoDimension, item.photoDimension)) photoView.setPeer(account: item.context.account, peer: item.peer) updatePhoto(item, animated: animated) photoView.isHidden = item.isTopic if !item.photos.isEmpty { if let first = item.photos.first, let video = first.image.videoRepresentations.last, item.updatingPhotoState == nil { let equal = videoRepresentation?.resource.id == video.resource.id if !equal { self.photoVideoView?.removeFromSuperview() self.photoVideoView = nil self.photoVideoView = MediaPlayerView(backgroundThread: true) if let photoEditableView = self.photoEditableView { self.addSubview(self.photoVideoView!, positioned: .below, relativeTo: photoEditableView) } else { self.addSubview(self.photoVideoView!) } self.photoVideoView!.isEventLess = true self.photoVideoView!.frame = self.photoView.frame let file = TelegramMediaFile(fileId: MediaId(namespace: 0, id: 0), partialReference: nil, resource: video.resource, previewRepresentations: first.image.representations, videoThumbnails: [], immediateThumbnailData: nil, mimeType: "video/mp4", size: video.resource.size, attributes: []) let reference: MediaResourceReference if let peer = item.peer, let peerReference = PeerReference(peer) { reference = MediaResourceReference.avatar(peer: peerReference, resource: file.resource) } else { reference = MediaResourceReference.standalone(resource: file.resource) } let mediaPlayer = MediaPlayer(postbox: item.context.account.postbox, reference: reference, streamable: true, video: true, preferSoftwareDecoding: false, enableSound: false, fetchAutomatically: true) mediaPlayer.actionAtEnd = .loop(nil) self.photoVideoPlayer = mediaPlayer if let seekTo = video.startTimestamp { mediaPlayer.seek(timestamp: seekTo) } mediaPlayer.attachPlayerView(self.photoVideoView!) self.videoRepresentation = video updatePlayerIfNeeded() } } else { self.photoVideoPlayer = nil self.photoVideoView?.removeFromSuperview() self.photoVideoView = nil self.videoRepresentation = nil } } else { self.photoVideoPlayer = nil self.photoVideoView?.removeFromSuperview() self.photoVideoView = nil self.videoRepresentation = nil } self.photoVideoView?.layer?.cornerRadius = item.isForum ? self.photoView.frame.height / 3 : self.photoView.frame.height / 2 nameView.change(size: item.nameSize, animated: animated) nameView.update(item, animated: animated) nameView.change(pos: NSMakePoint(containerView.focus(item.nameSize).minX, nameView.frame.minY), animated: animated) statusView.update(item.statusLayout) layoutActionItems(item.items, animated: animated) photoView.userInteractionEnabled = !item.editing let containerRect: NSRect switch item.viewType { case .legacy: containerRect = self.bounds case .modern: containerRect = NSMakeRect(floorToScreenPixels(backingScaleFactor, (frame.width - item.blockWidth) / 2), item.inset.top, item.blockWidth, item.height - item.inset.bottom - item.inset.top) } if item.canEditPhoto || self.activeDragging || item.updatingPhotoState != nil { if photoEditableView == nil { photoEditableView = .init(frame: NSMakeRect(0, 0, item.photoDimension, item.photoDimension)) addSubview(photoEditableView!) if animated { photoEditableView?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } } photoEditableView?.layer?.cornerRadius = item.isForum ? item.photoDimension / 3 : item.photoDimension / 2 photoEditableView?.updateState(item.updatingPhotoState, animated: animated) photoEditableView?.setup = item.updatePhoto } else { if let photoEditableView = self.photoEditableView { self.photoEditableView = nil if animated { photoEditableView.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak photoEditableView] _ in photoEditableView?.removeFromSuperview() }) } else { photoEditableView.removeFromSuperview() } } } containerView.change(size: containerRect.size, animated: animated) containerView.change(pos: containerRect.origin, animated: animated) containerView.setCorners(item.viewType.corners, animated: animated) borderView._change(opacity: item.viewType.hasBorder ? 1.0 : 0.0, animated: animated) needsLayout = true updateListeners() } override func interactionContentView(for innerId: AnyHashable, animateIn: Bool ) -> NSView { return photoView } override func copy() -> Any { return photoView.copy() } private var inlineTopicPhotoLayer: InlineStickerItemLayer? private func updatePhoto(_ item: PeerInfoHeadItem, animated: Bool) { let context = item.context if let threadData = item.threadData { let size = NSMakeSize(item.photoDimension, item.photoDimension) let current: InlineStickerItemLayer if let layer = self.inlineTopicPhotoLayer, layer.file?.fileId.id == threadData.info.icon { current = layer } else { if let layer = inlineTopicPhotoLayer { performSublayerRemoval(layer, animated: animated) self.inlineTopicPhotoLayer = nil } let info = threadData.info if let fileId = info.icon { current = .init(account: context.account, inlinePacksContext: context.inlinePacksContext, emoji: .init(fileId: fileId, file: nil, emoji: ""), size: size, playPolicy: .loop) } else { let file = ForumUI.makeIconFile(title: info.title, iconColor: info.iconColor) current = .init(account: context.account, file: file, size: size, playPolicy: .loop) } current.superview = containerView self.containerView.layer?.addSublayer(current) self.inlineTopicPhotoLayer = current } } else { if let layer = inlineTopicPhotoLayer { performSublayerRemoval(layer, animated: animated) self.inlineTopicPhotoLayer = nil } } self.updateAnimatableContent() } override func updateAnimatableContent() -> Void { let checkValue:(InlineStickerItemLayer)->Void = { value in if let superview = value.superview { var isKeyWindow: Bool = false if let window = superview.window { if !window.canBecomeKey { isKeyWindow = true } else { isKeyWindow = window.isKeyWindow } } value.isPlayable = superview.visibleRect != .zero && isKeyWindow } } if let value = inlineTopicPhotoLayer { checkValue(value) } } }
gpl-2.0
361ffd37c1d0e7801f14b0a48ee69c96
41.557756
357
0.595483
5.066798
false
false
false
false
Johennes/firefox-ios
Client/Frontend/Home/ActivityStreamPanel.swift
1
20938
/* 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 Shared import UIKit import Deferred import Storage import WebImage import XCGLogger import OnyxClient private let log = Logger.browserLogger private let DefaultSuggestedSitesKey = "topSites.deletedSuggestedSites" // MARK: - Lifecycle struct ASPanelUX { static let backgroundColor = UIColor(white: 1.0, alpha: 0.5) static let topSitesCacheSize = 12 static let historySize = 10 // These ratios repersent how much space the topsites require. // They are calculated from the iphone 5 which requires 220px of vertical height on a 320px width screen. // 320/220 = 1.4545. static let TopSiteDoubleRowRatio: CGFloat = 1.4545 static let TopSiteSingleRowRatio: CGFloat = 4.7333 static let PageControlOffsetSize: CGFloat = 20 } class ActivityStreamPanel: UITableViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? = nil private let profile: Profile private var onyxSession: OnyxSession? private let topSitesManager = ASHorizontalScrollCellManager() lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(ActivityStreamPanel.longPress(_:))) }() var highlights: [Site] = [] init(profile: Profile) { self.profile = profile super.init(style: .Grouped) view.addGestureRecognizer(longPressRecognizer) self.profile.history.setTopSitesCacheSize(Int32(ASPanelUX.topSitesCacheSize)) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TopSitesPanel.notificationReceived(_:)), name: NotificationFirefoxAccountChanged, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TopSitesPanel.notificationReceived(_:)), name: NotificationProfileDidFinishSyncing, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TopSitesPanel.notificationReceived(_:)), name: NotificationPrivateDataClearedHistory, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TopSitesPanel.notificationReceived(_:)), name: NotificationDynamicFontChanged, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationPrivateDataClearedHistory, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationDynamicFontChanged, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.registerClass(AlternateSimpleHighlightCell.self, forCellReuseIdentifier: "HistoryCell") tableView.registerClass(ASHorizontalScrollCell.self, forCellReuseIdentifier: "TopSiteCell") tableView.backgroundColor = ASPanelUX.backgroundColor tableView.separatorStyle = .None tableView.delegate = self tableView.dataSource = self tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorInset = UIEdgeInsetsZero tableView.estimatedRowHeight = 65 tableView.estimatedSectionHeaderHeight = 15 tableView.sectionFooterHeight = 0 tableView.sectionHeaderHeight = UITableViewAutomaticDimension reloadTopSites() reloadHighlights() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.onyxSession = OnyxTelemetry.sharedClient.beginSession() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) if let session = onyxSession { session.ping = ASOnyxPing.buildSessionPing(nil, loadReason: .newTab, unloadReason: .navigation, loadLatency: nil, page: .newTab) OnyxTelemetry.sharedClient.endSession(session, sendToEndpoint: .activityStream) } } override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) self.topSitesManager.currentTraits = self.traitCollection dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } } // MARK: - Section management extension ActivityStreamPanel { enum Section: Int { case TopSites case Highlights static let count = 2 var title: String? { switch self { case .Highlights: return Strings.ASHighlightsTitle case .TopSites: return nil } } var headerHeight: CGFloat { switch self { case .Highlights: return 40 case .TopSites: return 0 } } func cellHeight(traits: UITraitCollection, width: CGFloat) -> CGFloat { switch self { case .Highlights: return UITableViewAutomaticDimension case .TopSites: if traits.horizontalSizeClass == .Compact && traits.verticalSizeClass == .Regular { return CGFloat(Int(width / ASPanelUX.TopSiteDoubleRowRatio)) + ASPanelUX.PageControlOffsetSize } else { return CGFloat(Int(width / ASPanelUX.TopSiteSingleRowRatio)) + ASPanelUX.PageControlOffsetSize } } } var headerView: UIView? { switch self { case .Highlights: let view = ASHeaderView() view.title = title return view case .TopSites: return nil } } var cellIdentifier: String { switch self { case .TopSites: return "TopSiteCell" case .Highlights: return "HistoryCell" } } init(at indexPath: NSIndexPath) { self.init(rawValue: indexPath.section)! } init(_ section: Int) { self.init(rawValue: section)! } } } // MARK: - Tableview Delegate extension ActivityStreamPanel { override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return Section(section).headerHeight } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return Section(section).headerView } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return Section(indexPath.section).cellHeight(self.traitCollection, width: self.view.frame.width) } private func showSiteWithURLHandler(url: NSURL) { let visitType = VisitType.Bookmark homePanelDelegate?.homePanel(self, didSelectURL: url, visitType: visitType) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch Section(indexPath.section) { case .Highlights: let event = ASInfo(actionPosition: indexPath.item, source: .highlights) ASOnyxPing.reportTapEvent(event) let site = self.highlights[indexPath.row] showSiteWithURLHandler(NSURL(string:site.url)!) case .TopSites: return } } } // MARK: - Tableview Data Source extension ActivityStreamPanel { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return Section.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Section(section) { case .TopSites: return topSitesManager.content.isEmpty ? 0 : 1 case .Highlights: return self.highlights.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = Section(indexPath.section).cellIdentifier let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) switch Section(indexPath.section) { case .TopSites: return configureTopSitesCell(cell, forIndexPath: indexPath) case .Highlights: return configureHistoryItemCell(cell, forIndexPath: indexPath) } } func configureTopSitesCell(cell: UITableViewCell, forIndexPath indexPath: NSIndexPath) -> UITableViewCell { let topSiteCell = cell as! ASHorizontalScrollCell topSiteCell.delegate = self.topSitesManager return cell } func configureHistoryItemCell(cell: UITableViewCell, forIndexPath indexPath: NSIndexPath) -> UITableViewCell { let site = highlights[indexPath.row] let simpleHighlightCell = cell as! AlternateSimpleHighlightCell simpleHighlightCell.configureWithSite(site) return simpleHighlightCell } } // MARK: - Data Management extension ActivityStreamPanel { func notificationReceived(notification: NSNotification) { switch notification.name { case NotificationProfileDidFinishSyncing, NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged: self.reloadTopSites() default: log.warning("Received unexpected notification \(notification.name)") } } private func reloadHighlights() { fetchHighlights().uponQueue(dispatch_get_main_queue()) { result in self.highlights = result.successValue?.asArray() ?? self.highlights self.tableView.reloadSections(NSIndexSet(index: Section.Highlights.rawValue), withRowAnimation: .Automatic) } } private func fetchHighlights() -> Deferred<Maybe<Cursor<Site>>> { return self.profile.recommendations.getHighlights() } private func reloadTopSites() { invalidateTopSites().uponQueue(dispatch_get_main_queue()) { result in let defaultSites = self.defaultTopSites() let mySites = (result.successValue ?? []) // Merge default topsites with a user's topsites. let mergedSites = mySites.union(defaultSites, f: { (site) -> String in return NSURL(string: site.url)?.extractDomainName() ?? "" }) // Favour topsites from defaultSites as they have better favicons. let newSites = mergedSites.map { site -> Site in let domain = NSURL(string: site.url)?.extractDomainName() ?? "" return defaultSites.find { $0.title.lowercaseString == domain } ?? site } self.topSitesManager.currentTraits = self.view.traitCollection self.topSitesManager.content = newSites.count > ASPanelUX.topSitesCacheSize ? Array(newSites[0..<ASPanelUX.topSitesCacheSize]) : newSites self.topSitesManager.urlPressedHandler = { [unowned self] url, indexPath in let event = ASInfo(actionPosition: indexPath.item, source: .topSites) ASOnyxPing.reportTapEvent(event) self.showSiteWithURLHandler(url) } self.tableView.reloadSections(NSIndexSet(index: Section.TopSites.rawValue), withRowAnimation: .Automatic) } } private func invalidateTopSites() -> Deferred<Maybe<[Site]>> { let frecencyLimit = ASPanelUX.topSitesCacheSize return self.profile.history.updateTopSitesCacheIfInvalidated() >>== { dirty in return self.profile.history.getTopSitesWithLimit(frecencyLimit) >>== { topSites in return deferMaybe(topSites.asArray()) } } } func hideURLFromTopSites(siteURL: NSURL) { guard let host = siteURL.normalizedHost(), let url = siteURL.absoluteString else { return } // if the default top sites contains the siteurl. also wipe it from default suggested sites. if defaultTopSites().filter({$0.url == url}).isEmpty == false { deleteTileForSuggestedSite(url) } profile.history.removeHostFromTopSites(host).uponQueue(dispatch_get_main_queue()) { result in guard result.isSuccess else { return } self.reloadTopSites() } } func hideFromHighlights(site: Site) { profile.recommendations.removeHighlightForURL(site.url).uponQueue(dispatch_get_main_queue()) { result in guard result.isSuccess else { return } self.reloadHighlights() } } private func deleteTileForSuggestedSite(siteURL: String) { var deletedSuggestedSites = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? [] deletedSuggestedSites.append(siteURL) profile.prefs.setObject(deletedSuggestedSites, forKey: DefaultSuggestedSitesKey) } func defaultTopSites() -> [Site] { let suggested = SuggestedSites.asArray() let deleted = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? [] return suggested.filter({deleted.indexOf($0.url) == .None}) } @objc private func longPress(longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == UIGestureRecognizerState.Began else { return } let touchPoint = longPressGestureRecognizer.locationInView(self.view) guard let indexPath = tableView.indexPathForRowAtPoint(touchPoint) else { return } switch Section(indexPath.section) { case .Highlights: contextMenuForHighlightCellWithIndexPath(indexPath) case .TopSites: let topSiteCell = self.tableView.cellForRowAtIndexPath(indexPath) as! ASHorizontalScrollCell let pointInTopSite = longPressGestureRecognizer.locationInView(topSiteCell.collectionView) guard let topSiteIndexPath = topSiteCell.collectionView.indexPathForItemAtPoint(pointInTopSite) else { return } contextMenuForTopSiteCellWithIndexPath(topSiteIndexPath) } } private func contextMenuForTopSiteCellWithIndexPath(indexPath: NSIndexPath) { let topsiteIndex = NSIndexPath(forRow: 0, inSection: Section.TopSites.rawValue) guard let topSiteCell = self.tableView.cellForRowAtIndexPath(topsiteIndex) as? ASHorizontalScrollCell else { return } guard let topSiteItemCell = topSiteCell.collectionView.cellForItemAtIndexPath(indexPath) as? TopSiteItemCell else { return } let siteImage = topSiteItemCell.imageView.image let siteBGColor = topSiteItemCell.contentView.backgroundColor let site = self.topSitesManager.content[indexPath.item] let eventSource = ASInfo(actionPosition: indexPath.item, source: .topSites) presentContextMenu(site, eventInfo: eventSource, siteImage: siteImage, siteBGColor: siteBGColor) } private func contextMenuForHighlightCellWithIndexPath(indexPath: NSIndexPath) { guard let highlightCell = tableView.cellForRowAtIndexPath(indexPath) as? AlternateSimpleHighlightCell else { return } let siteImage = highlightCell.siteImageView.image let siteBGColor = highlightCell.siteImageView.backgroundColor let site = highlights[indexPath.row] let event = ASInfo(actionPosition: indexPath.row, source: .highlights) presentContextMenu(site, eventInfo: event, siteImage: siteImage, siteBGColor: siteBGColor) } private func presentContextMenu(site: Site, eventInfo: ASInfo, siteImage: UIImage?, siteBGColor: UIColor?) { guard let siteURL = NSURL(string: site.url) else { return } let openInNewTabAction = ActionOverlayTableViewAction(title: Strings.OpenInNewTabContextMenuTitle, iconString: "action_new_tab") { action in self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false) } let openInNewPrivateTabAction = ActionOverlayTableViewAction(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "action_new_private_tab") { action in self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true) } let bookmarkAction = ActionOverlayTableViewAction(title: Strings.BookmarkContextMenuTitle, iconString: "action_bookmark", handler: { action in let shareItem = ShareItem(url: site.url, title: site.title, favicon: site.icon) self.profile.bookmarks.shareItem(shareItem) var userData = [QuickActions.TabURLKey: shareItem.url] if let title = shareItem.title { userData[QuickActions.TabTitleKey] = title } QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.OpenLastBookmark, withUserData: userData, toApplication: UIApplication.sharedApplication()) }) let deleteFromHistoryAction = ActionOverlayTableViewAction(title: Strings.DeleteFromHistoryContextMenuTitle, iconString: "action_delete", handler: { action in ASOnyxPing.reportDeleteItemEvent(eventInfo) self.profile.history.removeHistoryForURL(site.url) }) let shareAction = ActionOverlayTableViewAction(title: Strings.ShareContextMenuTitle, iconString: "action_share", handler: { action in let helper = ShareExtensionHelper(url: siteURL, tab: nil, activities: []) let controller = helper.createActivityViewController { completed, activityType in ASOnyxPing.reportShareEvent(eventInfo, shareProvider: activityType) } self.presentViewController(controller, animated: true, completion: nil) }) let removeTopSiteAction = ActionOverlayTableViewAction(title: Strings.RemoveFromASContextMenuTitle, iconString: "action_close", handler: { action in ASOnyxPing.reportDeleteItemEvent(eventInfo) self.hideURLFromTopSites(site.tileURL) }) let dismissHighlightAction = ActionOverlayTableViewAction(title: Strings.RemoveFromASContextMenuTitle, iconString: "action_close", handler: { action in ASOnyxPing.reportDeleteItemEvent(eventInfo) self.hideFromHighlights(site) }) var actions = [openInNewTabAction, openInNewPrivateTabAction, bookmarkAction, shareAction] switch eventInfo.source { case .highlights: actions.appendContentsOf([dismissHighlightAction, deleteFromHistoryAction]) case .topSites: actions.append(removeTopSiteAction) default: break } let contextMenu = ActionOverlayTableViewController(site: site, actions: actions, siteImage: siteImage, siteBGColor: siteBGColor) contextMenu.modalPresentationStyle = .OverFullScreen contextMenu.modalTransitionStyle = .CrossDissolve self.presentViewController(contextMenu, animated: true, completion: nil) } } // MARK: - Section Header View struct ASHeaderViewUX { static let SeperatorColor = UIColor(rgb: 0xedecea) static let TextFont = DynamicFontHelper.defaultHelper.DefaultSmallFontBold static let SeperatorHeight = 1 static let Insets: CGFloat = 20 static let TitleTopInset: CGFloat = 5 } class ASHeaderView: UIView { lazy private var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.text = self.title titleLabel.textColor = UIColor.grayColor() titleLabel.font = ASHeaderViewUX.TextFont return titleLabel }() var title: String? { willSet(newTitle) { titleLabel.text = newTitle } } override init(frame: CGRect) { super.init(frame: frame) addSubview(titleLabel) titleLabel.snp_makeConstraints { make in make.edges.equalTo(self).offset(UIEdgeInsets(top: ASHeaderViewUX.TitleTopInset, left: ASHeaderViewUX.Insets, bottom: 0, right: -ASHeaderViewUX.Insets)) } let seperatorLine = UIView() seperatorLine.backgroundColor = ASHeaderViewUX.SeperatorColor addSubview(seperatorLine) seperatorLine.snp_makeConstraints { make in make.height.equalTo(ASHeaderViewUX.SeperatorHeight) make.leading.equalTo(self.snp_leading) make.trailing.equalTo(self.snp_trailing) make.top.equalTo(self.snp_top) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
8a6cd0367504bd79b53606c3271c7c79
41.905738
181
0.689225
5.276714
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Commons/Extensions/UIImage+CropWhiteSpace.swift
1
6139
// // UIImage+CropWhiteSpace.swift // NearbyWeather // // Created by Erik Maximilian Martens on 01.04.22. // Original Author: https://gist.github.com/chriszielinski/aec9a2f2ba54745dc715dd55f5718177 // Edit by: https://gist.github.com/msnazarow/a4cc6e8a0a7f1e075a25039ec3e32aca // Copyright © 2022 Erik Maximilian Martens. All rights reserved. // #if canImport(UIKit) import UIKit #else import AppKit #endif #if canImport(UIKit) typealias Image = UIImage #else typealias Image = NSImage #endif extension Image { /// Crops the insets of transparency around the image. /// /// - Parameters: /// - maximumAlphaChannel: The maximum alpha channel value to consider _transparent_ and thus crop. Any alpha value /// strictly greater than `maximumAlphaChannel` will be considered opaque. func trimmingTransparentPixels(maximumAlphaChannel: UInt8 = 0) -> Image? { guard size.height > 1 && size.width > 1 else { return self } #if canImport(UIKit) guard let cgImage = cgImage?.trimmingTransparentPixels(maximumAlphaChannel: maximumAlphaChannel) else { return nil } return UIImage(cgImage: cgImage, scale: scale, orientation: imageOrientation) #else guard let cgImage = cgImage(forProposedRect: nil, context: nil, hints: nil)? .trimmingTransparentPixels(maximumAlphaChannel: maximumAlphaChannel) else { return nil } let scale = recommendedLayerContentsScale(0) let scaledSize = CGSize(width: CGFloat(cgImage.width) / scale, height: CGFloat(cgImage.height) / scale) let image = NSImage(cgImage: cgImage, size: scaledSize) image.isTemplate = isTemplate return image #endif } } extension CGImage { /// Crops the insets of transparency around the image. /// /// - Parameters: /// - maximumAlphaChannel: The maximum alpha channel value to consider _transparent_ and thus crop. Any alpha value /// strictly greater than `maximumAlphaChannel` will be considered opaque. func trimmingTransparentPixels(maximumAlphaChannel: UInt8 = 0) -> CGImage? { let trimmer = _CGImageTransparencyTrimmer(image: self, maximumAlphaChannel: maximumAlphaChannel) let image = trimmer?.trim() free(trimmer?.zeroByteBlock) return image } } private struct _CGImageTransparencyTrimmer { let image: CGImage let maximumAlphaChannel: UInt8 let cgContext: CGContext let zeroByteBlock: UnsafeMutableRawPointer let pixelRowRange: Range<Int> let pixelColumnRange: Range<Int> init?(image: CGImage, maximumAlphaChannel: UInt8) { guard let cgContext = CGContext(data: nil, width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue), cgContext.data != nil else { return nil } cgContext.draw(image, in: CGRect(origin: .zero, size: CGSize(width: image.width, height: image.height))) guard let zeroByteBlock = calloc(image.width, MemoryLayout<UInt8>.size) else { return nil } self.image = image self.maximumAlphaChannel = maximumAlphaChannel self.cgContext = cgContext self.zeroByteBlock = zeroByteBlock pixelRowRange = 0..<image.height pixelColumnRange = 0..<image.width } func trim() -> CGImage? { guard let topInset = firstOpaquePixelRow(in: pixelRowRange), let bottomOpaqueRow = firstOpaquePixelRow(in: pixelRowRange.reversed()), let leftInset = firstOpaquePixelColumn(in: pixelColumnRange), let rightOpaqueColumn = firstOpaquePixelColumn(in: pixelColumnRange.reversed()) else { return nil } let bottomInset = (image.height - 1) - bottomOpaqueRow let rightInset = (image.width - 1) - rightOpaqueColumn guard !(topInset == 0 && bottomInset == 0 && leftInset == 0 && rightInset == 0) else { return image } return image.cropping(to: CGRect(origin: CGPoint(x: leftInset, y: topInset), size: CGSize(width: image.width - (leftInset + rightInset), height: image.height - (topInset + bottomInset)))) } @inlinable func isPixelOpaque(column: Int, row: Int) -> Bool { // Sanity check: It is safe to get the data pointer in iOS 4.0+ and macOS 10.6+ only. assert(cgContext.data != nil) return cgContext.data!.load(fromByteOffset: (row * cgContext.bytesPerRow) + column, as: UInt8.self) > maximumAlphaChannel } @inlinable func isPixelRowTransparent(_ row: Int) -> Bool { assert(cgContext.data != nil) // `memcmp` will efficiently check if the entire pixel row has zero alpha values return memcmp(cgContext.data! + (row * cgContext.bytesPerRow), zeroByteBlock, image.width) == 0 // When the entire row is NOT zeroed, we proceed to check each pixel's alpha // value individually until we locate the first "opaque" pixel (very ~not~ efficient). || !pixelColumnRange.contains(where: { isPixelOpaque(column: $0, row: row) }) } @inlinable func firstOpaquePixelRow<T: Sequence>(in rowRange: T) -> Int? where T.Element == Int { return rowRange.first(where: { !isPixelRowTransparent($0) }) } @inlinable func firstOpaquePixelColumn<T: Sequence>(in columnRange: T) -> Int? where T.Element == Int { return columnRange.first(where: { column in pixelRowRange.contains(where: { isPixelOpaque(column: column, row: $0) }) }) } }
mit
ec310199ce11328cec0a2eb6c8cec52d
38.346154
122
0.619583
4.519882
false
false
false
false
bermudadigitalstudio/Redshot
Sources/RedShot/RedisSocket.swift
1
6256
// // This source file is part of the RedShot open source project // // Copyright (c) 2017 Bermuda Digital Studio // Licensed under MIT // // See https://github.com/bermudadigitalstudio/Redshot/blob/master/LICENSE for license information // // Created by Laurent Gaches on 12/06/2017. // import Foundation #if os(Linux) import Glibc #else import Darwin #endif class RedisSocket { private let socketDescriptor: Int32 private let bufferSize: Int init(hostname: String, port: Int, bufferSize: Int) throws { self.bufferSize = bufferSize var hints = addrinfo() hints.ai_family = AF_UNSPEC hints.ai_protocol = Int32(IPPROTO_TCP) hints.ai_flags = AI_PASSIVE #if os(Linux) hints.ai_socktype = Int32(SOCK_STREAM.rawValue) #else hints.ai_socktype = SOCK_STREAM #endif var serverinfo: UnsafeMutablePointer<addrinfo>? = nil defer { if serverinfo != nil { freeaddrinfo(serverinfo) } } let status = getaddrinfo(hostname, port.description, &hints, &serverinfo) do { try RedisSocket.decodeAddrInfoStatus(status: status) } catch { freeaddrinfo(serverinfo) throw error } guard let addrInfo = serverinfo else { throw RedisError.connection("hostname or port not reachable") } // Create the socket descriptor socketDescriptor = socket(addrInfo.pointee.ai_family, addrInfo.pointee.ai_socktype, addrInfo.pointee.ai_protocol) guard socketDescriptor >= 0 else { throw RedisError.connection("Cannot Connect") } // set socket options var optval = 1 #if os(Linux) let statusSocketOpt = setsockopt(socketDescriptor, SOL_SOCKET, SO_REUSEADDR, &optval, socklen_t(MemoryLayout<Int>.stride)) #else let statusSocketOpt = setsockopt(socketDescriptor, SOL_SOCKET, SO_NOSIGPIPE, &optval, socklen_t(MemoryLayout<Int>.stride)) #endif do { try RedisSocket.decodeSetSockOptStatus(status: statusSocketOpt) } catch { #if os(Linux) _ = Glibc.close(self.socketDescriptor) #else _ = Darwin.close(self.socketDescriptor) #endif throw error } // Connect #if os(Linux) let connStatus = Glibc.connect(socketDescriptor, addrInfo.pointee.ai_addr, addrInfo.pointee.ai_addrlen) try RedisSocket.decodeConnectStatus(connStatus: connStatus) #else let connStatus = Darwin.connect(socketDescriptor, addrInfo.pointee.ai_addr, addrInfo.pointee.ai_addrlen) try RedisSocket.decodeConnectStatus(connStatus: connStatus) #endif } func read() -> Data { var data = Data() let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize) var readFlags: Int32 = 0 buffer.initialize(to: 0x0) var read = 0 #if os(Linux) read = Glibc.recv(self.socketDescriptor, buffer, Int(UInt16.max), readFlags) #else read = Darwin.recv(self.socketDescriptor, buffer, Int(UInt16.max), readFlags) #endif if read > 0 { data.append(buffer, count: read) } defer { buffer.deallocate(capacity: 4096) } return data } @discardableResult func send(buffer: UnsafeRawPointer, bufferSize: Int) -> Int { var sent = 0 var sendFlags: Int32 = 0 while sent < bufferSize { var s = 0 #if os(Linux) s = Glibc.send(self.socketDescriptor, buffer.advanced(by: sent), Int(bufferSize - sent), sendFlags) #else s = Darwin.send(self.socketDescriptor, buffer.advanced(by: sent), Int(bufferSize - sent), sendFlags) #endif sent += s } return sent } @discardableResult func send(data: Data) throws -> Int { guard !data.isEmpty else { return 0} return try data.withUnsafeBytes { [unowned self](buffer: UnsafePointer<UInt8>) throws -> Int in return self.send(buffer: buffer, bufferSize: data.count) } } @discardableResult func send(string: String) -> Int { return string.utf8CString.withUnsafeBufferPointer { return self.send(buffer: $0.baseAddress!, bufferSize: $0.count - 1) } } func close() { #if os(Linux) _ = Glibc.close(self.socketDescriptor) #else _ = Darwin.close(self.socketDescriptor) #endif } var isConnected: Bool { var error = 0 var len: socklen_t = 4 getsockopt(self.socketDescriptor, SOL_SOCKET, SO_ERROR, &error, &len) guard error == 0 else { return false } return true } deinit { close() } static func decodeAddrInfoStatus(status: Int32) throws { if status != 0 { var strError: String if status == EAI_SYSTEM { strError = String(validatingUTF8: strerror(errno)) ?? "Unknown error code" } else { strError = String(validatingUTF8: gai_strerror(status)) ?? "Unknown error code" } throw RedisError.connection(strError) } } static func decodeSetSockOptStatus(status: Int32) throws { if status == -1 { let strError = String(utf8String: strerror(errno)) ?? "Unknown error code" let message = "Setsockopt error \(errno) \(strError)" throw RedisError.connection(message) } } static func decodeConnectStatus(connStatus: Int32) throws { if connStatus != 0 { let strError = String(utf8String: strerror(errno)) ?? "Unknown error code" let message = "Setsockopt error \(errno) \(strError)" throw RedisError.connection("can't connect : \(connStatus) message : \(message)") } } }
mit
871831898d1be4e461f28f417e8dfc90
29.222222
116
0.577526
4.430595
false
false
false
false
ResearchSuite/ResearchSuiteAppFramework-iOS
Source/Core/Classes/RSAFReduxManager.swift
1
1661
// // RSAFReduxManager.swift // Pods // // Created by James Kizer on 3/23/17. // // import UIKit import ReSwift import ResearchKit open class RSAFReduxManager: NSObject { let store: Store<RSAFCombinedState> public init(initialState: RSAFCombinedState?, reducer: RSAFCombinedReducer) { let loggingMiddleware: Middleware = { dispatch, getState in return { next in return { action in // perform middleware logic let oldState: RSAFCombinedState? = getState() as? RSAFCombinedState let retVal = next(action) let newState: RSAFCombinedState? = getState() as? RSAFCombinedState print("\n") print("*******************************************************") if let oldState = oldState { print("oldState: \(oldState)") } print("action: \(action)") if let newState = newState { print("newState: \(newState)") } print("*******************************************************\n") // call next middleware return retVal } } } self.store = Store<RSAFCombinedState>( reducer: reducer, state: initialState, middleware: [loggingMiddleware] ) super.init() } deinit { debugPrint("\(self) deiniting") } }
apache-2.0
983603841f094fdc9c83f7fecb414bc6
27.637931
87
0.433474
5.953405
false
false
false
false
ALmanCoder/SwiftyGuesturesView
SwiftyGuesturesView/Classes/GH_Util.swift
1
1883
// // GH_Util.swift // SwiftyGuesturesView // // Created by wuguanghui on 2017/8/23. // Copyright © 2017年 wuguanghui. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public class GH_Util: NSObject { // MARK: - 视图抖动效果 public class func shakerView(_ ashakerView:UIView) { let kfanimation = CAKeyframeAnimation(keyPath: "transform.translation.x") let cTx = ashakerView.transform.tx kfanimation.duration = 0.4 kfanimation.values = [cTx, cTx+10, cTx-8, cTx+8, cTx-5, cTx+5, cTx] kfanimation.keyTimes = [(0), (0.225), (0.425), (0.525), (0.750), (0.875), (1)] kfanimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) ashakerView.layer.add(kfanimation, forKey: "kShakerAnimationKey") } }
mit
7ee4473dab9e032bdc8654030ad4daf9
45.7
101
0.721627
3.899791
false
false
false
false
ualch9/onebusaway-iphone
Carthage/Checkouts/CocoaLumberjack/Sources/CocoaLumberjackSwift/DDLog+Combine.swift
2
4025
// Software License Agreement (BSD License) // // Copyright (c) 2010-2020, Deusty, LLC // All rights reserved. // // Redistribution and use of this software in source and binary forms, // with or without modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Neither the name of Deusty nor the names of its contributors may be used // to endorse or promote products derived from this software without specific // prior written permission of Deusty, LLC. #if canImport(Combine) import Combine #if SWIFT_PACKAGE import CocoaLumberjack import CocoaLumberjackSwiftSupport #endif @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension DDLog { /** * Creates a message publisher. * * The publisher will add and remove loggers as subscriptions are added and removed. * * The level that you provide here is a preemptive filter (for performance). * That is, the level specified here will be used to filter out logMessages so that * the logger is never even invoked for the messages. * * More information: * See -[DDLog addLogger:with:] * * - Parameter logLevel: preemptive filter of the message returned by the publisher. All levels are sent by default * - Returns: A MessagePublisher that emits LogMessages filtered by the specified logLevel **/ public func messagePublisher(with logLevel: DDLogLevel = .all) -> MessagePublisher { return MessagePublisher(log: self, with: logLevel) } // MARK: - MessagePublisher @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) public struct MessagePublisher: Combine.Publisher { public typealias Output = DDLogMessage public typealias Failure = Never private let log: DDLog private let logLevel: DDLogLevel public init(log: DDLog, with logLevel: DDLogLevel) { self.log = log self.logLevel = logLevel } public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Failure, S.Input == Output { let subscription = Subscription(log: self.log, with: logLevel, subscriber: subscriber) subscriber.receive(subscription: subscription) } } // MARK: - Subscription private final class Subscription<S: Subscriber>: NSObject, DDLogger, Combine.Subscription where S.Input == DDLogMessage { private var subscriber: S? private weak var log: DDLog? //Not used but DDLogger requires it. The preferred way to achieve this is to use the `map()` Combine operator of the publisher. //ie: // DDLog.sharedInstance.messagePublisher() // .map { [format log message] } // .sink(receiveValue: { [process log message] }) // var logFormatter: DDLogFormatter? = nil let combineIdentifier = CombineIdentifier() init(log: DDLog, with logLevel: DDLogLevel, subscriber: S) { self.subscriber = subscriber self.log = log super.init() log.add(self, with: logLevel) } func request(_ demand: Subscribers.Demand) { //The log messages are endless until canceled, so we won't do any demand management. //Combine operators can be used to deal with it as needed. } func cancel() { self.log?.remove(self) self.subscriber = nil } func log(message logMessage: DDLogMessage) { _ = self.subscriber?.receive(logMessage) } } } @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension Publisher where Output == DDLogMessage { public func formatted(with formatter: DDLogFormatter) -> Publishers.CompactMap<Self, String> { return compactMap { formatter.format(message: $0) } } } #endif
apache-2.0
d0081886866f653367ddfe7da5844820
31.991803
135
0.654161
4.568672
false
false
false
false
austinzheng/swift
test/SILGen/super.swift
4
10751
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule %S/../Inputs/resilient_class.swift // Note: we build fixed_layout_class without -enable-resilience, since with // -enable-resilience even @_fixed_layout classes have resilient metadata, and // we want to test the fragile access pattern here. // RUN: %target-swift-frontend -emit-module -I %t -o %t %S/../Inputs/fixed_layout_class.swift // RUN: %target-swift-emit-silgen -module-name super -parse-as-library -I %t %s | %FileCheck %s import resilient_class import fixed_layout_class public class Parent { public final var finalProperty: String { return "Parent.finalProperty" } public var property: String { return "Parent.property" } public final class var finalClassProperty: String { return "Parent.finalProperty" } public class var classProperty: String { return "Parent.property" } public func methodOnlyInParent() {} public final func finalMethodOnlyInParent() {} public func method() {} public final class func finalClassMethodOnlyInParent() {} public class func classMethod() {} } public class Child : Parent { // CHECK-LABEL: sil [ossa] @$s5super5ChildC8propertySSvg : $@convention(method) (@guaranteed Child) -> @owned String { // CHECK: bb0([[SELF:%.*]] : @guaranteed $Child): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[CAST_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $Child to $Parent // CHECK: [[CAST_SELF_BORROW:%[0-9]+]] = begin_borrow [[CAST_SELF_COPY]] // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$s5super6ParentC8propertySSvg : $@convention(method) (@guaranteed Parent) -> @owned String // CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CAST_SELF_BORROW]]) // CHECK: end_borrow [[CAST_SELF_BORROW]] // CHECK: destroy_value [[CAST_SELF_COPY]] // CHECK: return [[RESULT]] public override var property: String { return super.property } // CHECK-LABEL: sil [ossa] @$s5super5ChildC13otherPropertySSvg : $@convention(method) (@guaranteed Child) -> @owned String { // CHECK: bb0([[SELF:%.*]] : @guaranteed $Child): // CHECK: [[COPIED_SELF:%.*]] = copy_value [[SELF]] // CHECK: [[CAST_SELF_COPY:%[0-9]+]] = upcast [[COPIED_SELF]] : $Child to $Parent // CHECK: [[CAST_SELF_BORROW:%[0-9]+]] = begin_borrow [[CAST_SELF_COPY]] // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$s5super6ParentC13finalPropertySSvg // CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CAST_SELF_BORROW]]) // CHECK: end_borrow [[CAST_SELF_BORROW]] // CHECK: destroy_value [[CAST_SELF_COPY]] // CHECK: return [[RESULT]] public var otherProperty: String { return super.finalProperty } } public class Grandchild : Child { // CHECK-LABEL: sil [ossa] @$s5super10GrandchildC06onlyInB0yyF public func onlyInGrandchild() { // CHECK: function_ref @$s5super6ParentC012methodOnlyInB0yyF : $@convention(method) (@guaranteed Parent) -> () super.methodOnlyInParent() // CHECK: function_ref @$s5super6ParentC017finalMethodOnlyInB0yyF super.finalMethodOnlyInParent() } // CHECK-LABEL: sil [ossa] @$s5super10GrandchildC6methodyyF public override func method() { // CHECK: function_ref @$s5super6ParentC6methodyyF : $@convention(method) (@guaranteed Parent) -> () super.method() } } public class GreatGrandchild : Grandchild { // CHECK-LABEL: sil [ossa] @$s5super15GreatGrandchildC6methodyyF public override func method() { // CHECK: function_ref @$s5super10GrandchildC6methodyyF : $@convention(method) (@guaranteed Grandchild) -> () super.method() } } public class ChildToResilientParent : ResilientOutsideParent { // CHECK-LABEL: sil [ossa] @$s5super22ChildToResilientParentC6methodyyF : $@convention(method) (@guaranteed ChildToResilientParent) -> () public override func method() { // CHECK: bb0([[SELF:%.*]] : @guaranteed $ChildToResilientParent): // CHECK: [[COPY_SELF:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF:%.*]] = upcast [[COPY_SELF]] // CHECK: [[BORROW_UPCAST_SELF:%.*]] = begin_borrow [[UPCAST_SELF]] // CHECK: [[CAST_BORROW_BACK_TO_BASE:%.*]] = unchecked_ref_cast [[BORROW_UPCAST_SELF]] // CHECK: [[FUNC:%.*]] = super_method [[CAST_BORROW_BACK_TO_BASE]] : $ChildToResilientParent, #ResilientOutsideParent.method!1 : (ResilientOutsideParent) -> () -> (), $@convention(method) (@guaranteed ResilientOutsideParent) -> () // CHECK: end_borrow [[BORROW_UPCAST_SELF]] // CHECK: apply [[FUNC]]([[UPCAST_SELF]]) super.method() } // CHECK: } // end sil function '$s5super22ChildToResilientParentC6methodyyF' // CHECK-LABEL: sil [ossa] @$s5super22ChildToResilientParentC11classMethodyyFZ : $@convention(method) (@thick ChildToResilientParent.Type) -> () public override class func classMethod() { // CHECK: bb0([[METASELF:%.*]] : $@thick ChildToResilientParent.Type): // CHECK: [[UPCAST_METASELF:%.*]] = upcast [[METASELF]] // CHECK: [[FUNC:%.*]] = super_method [[SELF]] : $@thick ChildToResilientParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> (), $@convention(method) (@thick ResilientOutsideParent.Type) -> () // CHECK: apply [[FUNC]]([[UPCAST_METASELF]]) super.classMethod() } // CHECK: } // end sil function '$s5super22ChildToResilientParentC11classMethodyyFZ' // CHECK-LABEL: sil [ossa] @$s5super22ChildToResilientParentC11returnsSelfACXDyFZ : $@convention(method) (@thick ChildToResilientParent.Type) -> @owned ChildToResilientParent public class func returnsSelf() -> Self { // CHECK: bb0([[METASELF:%.*]] : $@thick ChildToResilientParent.Type): // CHECK: [[CAST_METASELF:%.*]] = unchecked_trivial_bit_cast [[METASELF]] : $@thick ChildToResilientParent.Type to $@thick @dynamic_self ChildToResilientParent.Type // CHECK: [[UPCAST_CAST_METASELF:%.*]] = upcast [[CAST_METASELF]] : $@thick @dynamic_self ChildToResilientParent.Type to $@thick ResilientOutsideParent.Type // CHECK: [[FUNC:%.*]] = super_method [[METASELF]] : $@thick ChildToResilientParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> () // CHECK: apply [[FUNC]]([[UPCAST_CAST_METASELF]]) // CHECK: unreachable super.classMethod() } // CHECK: } // end sil function '$s5super22ChildToResilientParentC11returnsSelfACXDyFZ' } public class ChildToFixedParent : OutsideParent { // CHECK-LABEL: sil [ossa] @$s5super18ChildToFixedParentC6methodyyF : $@convention(method) (@guaranteed ChildToFixedParent) -> () public override func method() { // CHECK: bb0([[SELF:%.*]] : @guaranteed $ChildToFixedParent): // CHECK: [[COPY_SELF:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_COPY_SELF:%.*]] = upcast [[COPY_SELF]] // CHECK: [[BORROWED_UPCAST_COPY_SELF:%.*]] = begin_borrow [[UPCAST_COPY_SELF]] // CHECK: [[DOWNCAST_BORROWED_UPCAST_COPY_SELF:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_COPY_SELF]] : $OutsideParent to $ChildToFixedParent // CHECK: [[FUNC:%.*]] = super_method [[DOWNCAST_BORROWED_UPCAST_COPY_SELF]] : $ChildToFixedParent, #OutsideParent.method!1 : (OutsideParent) -> () -> (), $@convention(method) (@guaranteed OutsideParent) -> () // CHECK: end_borrow [[BORROWED_UPCAST_COPY_SELF]] // CHECK: apply [[FUNC]]([[UPCAST_COPY_SELF]]) super.method() } // CHECK: } // end sil function '$s5super18ChildToFixedParentC6methodyyF' // CHECK-LABEL: sil [ossa] @$s5super18ChildToFixedParentC11classMethodyyFZ : $@convention(method) (@thick ChildToFixedParent.Type) -> () public override class func classMethod() { // CHECK: bb0([[SELF:%.*]] : $@thick ChildToFixedParent.Type): // CHECK: [[UPCAST_SELF:%.*]] = upcast [[SELF]] // CHECK: [[FUNC:%.*]] = super_method [[SELF]] : $@thick ChildToFixedParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> (), $@convention(method) (@thick OutsideParent.Type) -> () // CHECK: apply [[FUNC]]([[UPCAST_SELF]]) super.classMethod() } // CHECK: } // end sil function '$s5super18ChildToFixedParentC11classMethodyyFZ' // CHECK-LABEL: sil [ossa] @$s5super18ChildToFixedParentC11returnsSelfACXDyFZ : $@convention(method) (@thick ChildToFixedParent.Type) -> @owned ChildToFixedParent public class func returnsSelf() -> Self { // CHECK: bb0([[SELF:%.*]] : $@thick ChildToFixedParent.Type): // CHECK: [[FIRST_CAST:%.*]] = unchecked_trivial_bit_cast [[SELF]] // CHECK: [[SECOND_CAST:%.*]] = upcast [[FIRST_CAST]] // CHECK: [[FUNC:%.*]] = super_method [[SELF]] : $@thick ChildToFixedParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> () // CHECK: apply [[FUNC]]([[SECOND_CAST]]) // CHECK: unreachable super.classMethod() } // CHECK: } // end sil function '$s5super18ChildToFixedParentC11returnsSelfACXDyFZ' } public extension ResilientOutsideChild { public func callSuperMethod() { super.method() } public class func callSuperClassMethod() { super.classMethod() } } public class GenericBase<T> { public func method() {} } public class GenericDerived<T> : GenericBase<T> { public override func method() { // CHECK-LABEL: sil private [ossa] @$s5super14GenericDerivedC6methodyyFyyXEfU_ : $@convention(thin) <T> (@guaranteed GenericDerived<T>) -> () // CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T> // CHECK: return { super.method() }() // CHECK: } // end sil function '$s5super14GenericDerivedC6methodyyFyyXEfU_' // CHECK-LABEL: sil private [ossa] @$s5super14GenericDerivedC6methodyyF13localFunctionL_yylF : $@convention(thin) <T> (@guaranteed GenericDerived<T>) -> () // CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T> // CHECK: return // CHECK: } // end sil function '$s5super14GenericDerivedC6methodyyF13localFunctionL_yylF' func localFunction() { super.method() } localFunction() // CHECK-LABEL: sil private [ossa] @$s5super14GenericDerivedC6methodyyF15genericFunctionL_yyqd__r__lF : $@convention(thin) <T><U> (@in_guaranteed U, @guaranteed GenericDerived<T>) -> () // CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T> // CHECK: return func genericFunction<U>(_: U) { super.method() } // CHECK: } // end sil function '$s5super14GenericDerivedC6methodyyF15genericFunctionL_yyqd__r__lF' genericFunction(0) } }
apache-2.0
e1bbf64912ea41e24dba0fbf740436d3
49.238318
238
0.663566
3.730396
false
false
false
false
loudnate/Loop
WatchApp Extension/Managers/ComplicationChartManager.swift
1
6067
// // ComplicationChartManager.swift // WatchApp Extension // // Created by Michael Pangburn on 10/17/18. // Copyright © 2018 LoopKit Authors. All rights reserved. // import Foundation import UIKit import HealthKit import WatchKit private let textInsets = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2) extension CGSize { fileprivate static let glucosePoint = CGSize(width: 2, height: 2) } extension NSAttributedString { fileprivate class func forGlucoseLabel(string: String) -> NSAttributedString { return NSAttributedString(string: string, attributes: [ .font: UIFont(name: "HelveticaNeue", size: 10)!, .foregroundColor: UIColor.chartLabel ]) } } extension CGFloat { fileprivate static let predictionDashPhase: CGFloat = 11 } private let predictionDashLengths: [CGFloat] = [5, 3] final class ComplicationChartManager { private enum GlucoseLabelPosition { case high case low } var data: GlucoseChartData? private var lastRenderDate: Date? private var renderedChartImage: UIImage? private var visibleInterval: TimeInterval = .hours(4) private var unit: HKUnit { return data?.unit ?? .milligramsPerDeciliter } func renderChartImage(size: CGSize, scale: CGFloat) -> UIImage? { guard let data = data else { renderedChartImage = nil return nil } UIGraphicsBeginImageContextWithOptions(size, false, 0.0) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext() else { return nil } drawChart(in: context, data: data, size: size) guard let cgImage = context.makeImage() else { renderedChartImage = nil return nil } let image = UIImage(cgImage: cgImage, scale: scale, orientation: .up) renderedChartImage = image return image } private func drawChart(in context: CGContext, data: GlucoseChartData, size: CGSize) { let now = Date() lastRenderDate = now let spannedInterval = DateInterval(start: now - visibleInterval / 2, duration: visibleInterval) let glucoseRange = data.chartableGlucoseRange(from: spannedInterval) let scaler = GlucoseChartScaler(size: size, dateInterval: spannedInterval, glucoseRange: glucoseRange, unit: unit) let drawingSteps = [drawTargetRange, drawOverridesIfNeeded, drawHistoricalGlucose, drawPredictedGlucose, drawGlucoseLabels] drawingSteps.forEach { drawIn in drawIn(context, scaler) } } private func drawGlucoseLabels(in context: CGContext, using scaler: GlucoseChartScaler) { let formatter = NumberFormatter.glucoseFormatter(for: unit) drawGlucoseLabelText(formatter.string(from: scaler.glucoseMax)!, position: .high, scaler: scaler) drawGlucoseLabelText(formatter.string(from: scaler.glucoseMin)!, position: .low, scaler: scaler) } private func drawGlucoseLabelText(_ text: String, position: GlucoseLabelPosition, scaler: GlucoseChartScaler) { let attributedText = NSAttributedString.forGlucoseLabel(string: text) let size = attributedText.size() let x = scaler.xCoordinate(for: scaler.dates.end) - size.width - textInsets.right let y: CGFloat = { switch position { case .high: return scaler.yCoordinate(for: scaler.glucoseMax) + textInsets.top case .low: return scaler.yCoordinate(for: scaler.glucoseMin) - size.height - textInsets.bottom } }() let rect = CGRect(origin: CGPoint(x: x, y: y), size: size).alignedToScreenScale(WKInterfaceDevice.current().screenScale) attributedText.draw(with: rect, options: .usesLineFragmentOrigin, context: nil) } private func drawTargetRange(in context: CGContext, using scaler: GlucoseChartScaler) { let activeOverride = data?.activeScheduleOverride let targetRangeAlpha: CGFloat = activeOverride != nil ? 0.2 : 0.3 context.setFillColor(UIColor.glucose.withAlphaComponent(targetRangeAlpha).cgColor) data?.correctionRange?.quantityBetween(start: scaler.dates.start, end: scaler.dates.end).forEach { range in let rangeRect = scaler.rect(for: range, unit: unit) context.fill(rangeRect) } } private func drawOverridesIfNeeded(in context: CGContext, using scaler: GlucoseChartScaler) { guard let override = data?.activeScheduleOverride, let overrideHashable = TemporaryScheduleOverrideHashable(override) else { return } context.setFillColor(UIColor.glucose.withAlphaComponent(0.4).cgColor) let overrideRect = scaler.rect(for: overrideHashable, unit: unit) context.fill(overrideRect) } private func drawHistoricalGlucose(in context: CGContext, using scaler: GlucoseChartScaler) { context.setFillColor(UIColor.glucose.cgColor) data?.historicalGlucose?.lazy.filter { scaler.dates.contains($0.startDate) }.forEach { glucose in let origin = scaler.point(for: glucose, unit: unit) let glucoseRect = CGRect(origin: origin, size: .glucosePoint).alignedToScreenScale(WKInterfaceDevice.current().screenScale) context.fill(glucoseRect) } } private func drawPredictedGlucose(in context: CGContext, using scaler: GlucoseChartScaler) { guard let predictedGlucose = data?.predictedGlucose, predictedGlucose.count > 2 else { return } let predictedPath = CGMutablePath() let glucosePoints = predictedGlucose.map { scaler.point(for: $0, unit: unit) } predictedPath.addLines(between: glucosePoints) let dashedPath = predictedPath.copy(dashingWithPhase: .predictionDashPhase, lengths: predictionDashLengths) context.setStrokeColor(UIColor.white.cgColor) context.addPath(dashedPath) context.strokePath() } }
apache-2.0
7a8a72e585791a2d5995868e4529ea9a
38.38961
135
0.681174
4.560902
false
false
false
false
Flinesoft/HandySwift
Sources/HandySwift/Structs/Unowned.swift
1
1703
// Copyright © 2018 Flinesoft. All rights reserved. import Foundation /// A wrapper for storing unowned references to a `Wrapped` instance. public struct Unowned<Wrapped> where Wrapped: AnyObject { /// The value of `Wrapped` stored as unowned reference public unowned var value: Wrapped /// Creates an instance that stores the given value. public init(_ value: Wrapped) { self.value = value } } extension Unowned: CustomDebugStringConvertible where Wrapped: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { value.debugDescription } } extension Unowned: Decodable where Wrapped: Decodable { /// Creates a new instance by decoding from the given decoder. /// /// This initializer throws an error if reading from the decoder fails, or /// if the data read is corrupted or otherwise invalid. /// /// - Parameter decoder: The decoder to read data from. public init(from decoder: Decoder) throws { self.value = try Wrapped(from: decoder) } } extension Unowned: Equatable where Wrapped: Equatable { /// Returns a Boolean value indicating whether two instances are equal. /// /// - Parameters: /// - lhs: An optional value to compare. /// - rhs: Another optional value to compare. public static func == (lhs: Unowned<Wrapped>, rhs: Unowned<Wrapped>) -> Bool { lhs.value == rhs.value } } extension Unowned: Encodable where Wrapped: Encodable { /// Encodes this value into the given encoder. /// /// - Parameter encoder: The encoder to write data to. public func encode(to encoder: Encoder) throws { try value.encode(to: encoder) } }
mit
ceaedd0e15164284692f3852cf3506e6
31.113208
93
0.712691
4.502646
false
false
false
false
fgulan/letter-ml
project/LetterML/Frameworks/framework/Source/Operations/WhiteBalance.swift
9
491
public class WhiteBalance: BasicOperation { public var temperature:Float = 5000.0 { didSet { uniformSettings["temperature"] = temperature < 5000.0 ? 0.0004 * (temperature - 5000.0) : 0.00006 * (temperature - 5000.0) } } public var tint:Float = 0.0 { didSet { uniformSettings["tint"] = tint / 100.0 } } public init() { super.init(fragmentShader:WhiteBalanceFragmentShader, numberOfInputs:1) ({temperature = 5000.0})() ({tint = 0.0})() } }
mit
520929917ef672019f32983f3102a73c
43.727273
179
0.625255
3.99187
false
false
false
false
windirt/WeatherMap
WeatherAroundUs/WeatherAroundUs/ImageCache.swift
9
1258
// // ImageCache.swift // WeatherAroundUs // // Created by Kedan Li on 15/4/20. // Copyright (c) 2015年 Kedan Li. All rights reserved. // import UIKit import Haneke @objc protocol ImageCacheDelegate: class { optional func gotImageFromCache(image: UIImage, cityID: String) optional func gotSmallImageFromCache(image: UIImage, cityID: String) } class ImageCache: NSObject { static var smallImagesUrl = [String: String]() static var imagesUrl = [String: String]() var delegate: ImageCacheDelegate! func getSmallImageFromCache(url: String, cityID: String){ // get the image from cache let cache = Shared.dataCache var img = UIImage() cache.fetch(URL: NSURL(string: url)!).onSuccess { image in img = UIImage(data: image)! self.delegate?.gotSmallImageFromCache!(img, cityID: cityID) } } func getImageFromCache(url: String, cityID: String){ // get the image from cache let cache = Shared.dataCache var img = UIImage() cache.fetch(URL: NSURL(string: url)!).onSuccess { image in img = UIImage(data: image)! self.delegate?.gotImageFromCache!(img, cityID: cityID) } } }
apache-2.0
18ff91790a3f723e8f247e0740ac1f8c
26.304348
72
0.633758
4.228956
false
false
false
false
moonrailgun/OpenCode
OpenCode/Classes/MarkdownReader/Controller/MarkdownReaderController.swift
1
1382
// // MarkdownReaderController.swift // OpenCode // // Created by 陈亮 on 16/6/14. // Copyright © 2016年 moonrailgun. All rights reserved. // import UIKit import TSMarkdownParser class MarkdownReaderController: UIViewController { lazy var textView:UITextView = UITextView(frame: self.view.bounds, textContainer: nil) var string:NSAttributedString? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. initView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func initView(){ if(string != nil){ textView.attributedText = string! } self.view.addSubview(textView) } func setMarkdownStr(markdown:String){ let string = TSMarkdownParser.standardParser().attributedStringFromMarkdown(markdown) self.string = string } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
85bd994314720560284ca99f2dc8e698
26.5
106
0.670545
4.893238
false
false
false
false
Frgallah/MasterTransitions
Sources/MTInteractiveTransitioning/AnimatedInteractiveTransitioning.swift
1
9319
// // MTAnimatedInteractiveTransitioning.swift // Pods // // Created by Frgallah on 4/11/17. // // Copyright (c) 2017 Mohammed Frgallah. All rights reserved. // // Licensed under the MIT license, can be found at: https://github.com/Frgallah/MasterTransitions/blob/master/LICENSE or https://opensource.org/licenses/MIT // // For last updated version of this code check the github page at https://github.com/Frgallah/MasterTransitions // // import UIKit enum GestureDirection: Int { case LeftToRight case RightToLeft case TopToBottom case BottomToTop case none } class AnimatedInteractiveTransitioning: NSObject { fileprivate var initiallyInteractive = false private let transitionType: TransitionType private let transitionSubType: TransitionSubType fileprivate var duration: TimeInterval = 0 var panGestureRecognizer: UIPanGestureRecognizer? { didSet { panGestureRecognizer?.addTarget(self, action: #selector(updateInteractionFor(gesture:))) initiallyInteractive = true } } var transitionBackgroundColor: UIColor = UIColor.black { willSet { transition.backgroundColor = newValue } } var gestureDirection: GestureDirection? fileprivate var context: UIViewControllerContextTransitioning? var transition: TransitionAnimator! fileprivate var initialTranslation = CGPoint.zero private var lastPercentage: CGFloat = 0 init(transitionType: TransitionType, transitionSubType:TransitionSubType, duration:TimeInterval, panGestureRecognizer:UIPanGestureRecognizer?, gestureDirection:GestureDirection?, backgroundColor: UIColor?) { self.transitionType = transitionType self.transitionSubType = transitionSubType self.gestureDirection = gestureDirection; if let color = backgroundColor { self.transitionBackgroundColor = color } super.init() transition = TransitionLoader.transitionForType(transitionType: transitionType, transitionSubType: transitionSubType) transition.duration = duration > 0 ? duration : transition.defaultDuration self.duration = transition.duration if let gesture = panGestureRecognizer { gesture.addTarget(self, action: #selector(updateInteractionFor(gesture:))) self.panGestureRecognizer = gesture self.initiallyInteractive = true } } deinit { NSLog(" AnimatedInteractiveTransitioning has been deinit ") } @objc func updateInteractionFor(gesture: UIPanGestureRecognizer) { switch gesture.state { case .began: break case .changed: let percentage = percentFor(gesture: gesture) if percentage < 0.0 { context?.cancelInteractiveTransition() panGestureRecognizer?.removeTarget(self, action: #selector(updateInteractionFor(gesture:))) } else { transition.fractionComplete = percentage context?.updateInteractiveTransition(percentage) } case .ended: lastPercentage = 0 endInteraction() default: context?.cancelInteractiveTransition() } } private func percentFor(gesture: UIPanGestureRecognizer) -> CGFloat { guard let containerView = context?.containerView else { return lastPercentage } let translation: CGPoint = gesture.translation(in: containerView) var percentage:CGFloat = 0.0 if gestureDirection == .LeftToRight && translation.x > 0.0 { if initialTranslation.x < 0.0 { percentage = -1.0 } else { percentage = translation.x/(containerView.bounds.width) } } else if gestureDirection == .RightToLeft && translation.x < 0.0 { if initialTranslation.x > 0.0 { percentage = -1.0 } else { percentage = -1.0 * (translation.x/(containerView.bounds.width)) } } else if gestureDirection == .TopToBottom && translation.y > 0.0 { if initialTranslation.y < 0.0 { percentage = -1.0 } else { percentage = translation.y/(containerView.bounds.height) } } else if gestureDirection == .BottomToTop && translation.y < 0.0 { if initialTranslation.y > 0.0 { percentage = -1.0 } else { percentage = -1.0 * (translation.y/(containerView.bounds.height)) } } lastPercentage = percentage return percentage } private func completionPosition() -> UIViewAnimatingPosition { if transition.fractionComplete < transition.midDuration { return .start; } else { return .end; } } private func endInteraction() { guard let transitiContext = context , transitiContext.isInteractive else { return } let position = completionPosition() if position == .end { transitiContext.finishInteractiveTransition() } else { transitiContext.cancelInteractiveTransition() } transition.animateTo(position: position, isResume: true) } fileprivate func transitionAnimator() -> TransitionAnimator { if transition == nil { return TransitionLoader.transitionForType(transitionType: transitionType, transitionSubType: transitionSubType) } else { return transition } } } extension AnimatedInteractiveTransitioning : UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { transition.setupTranisition(transitionContext: transitionContext, transitionCompletion: { (completed) in transitionContext.completeTransition(completed) }) transition.animateTo(position: .end, isResume: false) } func animationEnded(_ transitionCompleted: Bool) { transition = nil } func interruptibleAnimator(using transitionContext: UIViewControllerContextTransitioning) -> UIViewImplicitlyAnimating { if transition.propertyAnimator != nil { return transition.propertyAnimator! } else { return interruptibleAnimator(using: transitionContext, transitionCompletion: { (completed) in transitionContext.completeTransition(completed) }) } } func interruptibleAnimator(using transitionContext: UIViewControllerContextTransitioning, transitionCompletion: @escaping (Bool) -> ()) -> UIViewImplicitlyAnimating { let fromViewController = transitionContext.viewController(forKey: .from) let toViewController = transitionContext.viewController(forKey: .to) let containerView = transitionContext.containerView var fromView: UIView! var toView: UIView! if transitionContext.responds(to:#selector(transitionContext.view(forKey:))) { fromView = transitionContext.view(forKey: .from) toView = transitionContext.view(forKey: .to) } else { fromView = fromViewController?.view toView = toViewController?.view } let fromViewFrame = transitionContext.initialFrame(for: fromViewController!) let toViewFrame = transitionContext.finalFrame(for: toViewController!) fromView.frame = fromViewFrame toView.frame = toViewFrame containerView.addSubview(toView) toView.alpha = 0 let animator: UIViewPropertyAnimator = UIViewPropertyAnimator.init(duration: duration, curve: .linear, animations: { fromView.alpha = 0 toView.alpha = 1 }) animator.addCompletion({ (position) in let completed = position == .end transitionCompletion(completed) }) animator.isUserInteractionEnabled = false return animator } } extension AnimatedInteractiveTransitioning : UIViewControllerInteractiveTransitioning { func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) { context = transitionContext initialTranslation = (panGestureRecognizer?.translation(in: transitionContext.containerView))! transition.isInteractive = true transition.setupTranisition(transitionContext: transitionContext, transitionCompletion: { (completed) in transitionContext.completeTransition(completed) }) } var wantsInteractiveStart: Bool { return initiallyInteractive } }
mit
2c917f16cec8f2059278eb473d37a2fa
33.135531
212
0.631613
5.928117
false
false
false
false
slavapestov/swift
stdlib/public/SDK/Foundation/NSValue.swift
1
1135
//===--- NSValue.swift - Bridging things in NSValue -----------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension NSRange : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public static func _getObjectiveCType() -> Any.Type { return NSValue.self } public func _bridgeToObjectiveC() -> NSValue { return NSValue(range: self) } public static func _forceBridgeFromObjectiveC( x: NSValue, inout result: NSRange? ) { result = x.rangeValue } public static func _conditionallyBridgeFromObjectiveC( x: NSValue, inout result: NSRange? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } }
apache-2.0
5872b577bedd34ef2d6c6262c646c385
27.375
80
0.629956
4.850427
false
false
false
false
radioboo/ListKitDemo
ListKitDemo/Cells/EmbeddedCollectionViewCell.swift
1
1330
// // EmbeddedCollectionViewCell.swift // ListKitDemo // // Created by 酒井篤 on 2016/12/10. // Copyright © 2016年 Atsushi Sakai. All rights reserved. // import UIKit import IGListKit class EmbeddedCollectionViewCell: UICollectionViewCell { lazy var collectionView: IGListCollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal let view = IGListCollectionView(frame: .zero, collectionViewLayout: layout) view.backgroundColor = .clear view.alwaysBounceVertical = false view.alwaysBounceHorizontal = true self.contentView.addSubview(view) return view }() override func layoutSubviews() { super.layoutSubviews() collectionView.frame = contentView.frame let bounds = contentView.bounds let height: CGFloat = 0.5 let left = UIEdgeInsets(top: 8, left: 15, bottom: 8, right: 15).left separator.frame = CGRect(x: left, y: bounds.height - height, width: bounds.width, height: height) } lazy var separator: CALayer = { let layer = CALayer() layer.backgroundColor = UIColor(red: 200/255.0, green: 199/255.0, blue: 204/255.0, alpha: 1).cgColor self.contentView.layer.addSublayer(layer) return layer }() }
mit
31313fc449da11ae2ecb5cd8af89f253
31.219512
108
0.663134
4.539519
false
false
false
false
sishenyihuba/Weibo
Weibo/00-Main(主要)/OAuth/UserAccount.swift
1
1785
// // UserAccount.swift // Weibo // // Created by daixianglong on 2017/1/12. // Copyright © 2017年 Dale. All rights reserved. // import UIKit class UserAccount: NSObject,NSCoding { //MARK: - 属性 var access_token:String? var expires_in:NSTimeInterval = 0.0 { didSet { expires_date = NSDate(timeIntervalSinceNow: expires_in) } } var uid:String? var expires_date:NSDate? var avatar_large:String? var screen_name:String? //MARK: - 构造方法 init(dict:[String:AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } //MARK: - description override var description: String { return dictionaryWithValuesForKeys(["access_token","expires_date","uid","avatar_large","screen_name"]).description } //MARK: - nsCoding required init?(coder aDecoder: NSCoder) { access_token = aDecoder.decodeObjectForKey("access_token") as? String expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate uid = aDecoder.decodeObjectForKey("uid") as? String avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String screen_name = aDecoder.decodeObjectForKey("screen_name") as? String } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(access_token, forKey: "access_token") aCoder.encodeObject(uid, forKey: "uid") aCoder.encodeObject(expires_date, forKey: "expires_date") aCoder.encodeObject(avatar_large, forKey: "avatar_large") aCoder.encodeObject(screen_name, forKey: "screen_name") } }
mit
d36b73f68d640bf43e9ec5ba9293f473
26.65625
122
0.633333
4.381188
false
false
false
false
joelconnects/FlipTheBlinds
FlipTheBlinds/TabBarRootThreeViewController.swift
1
1106
// // TabBarRootThreeViewController.swift // FlipTheBlinds // // Created by Joel Bell on 1/2/17. // Copyright © 2017 Joel Bell. All rights reserved. // import UIKit // MARK: Main class TabBarRootThreeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() configImageView() } } // MARK: Configure View extension TabBarRootThreeViewController { private func configImageView() { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.image = #imageLiteral(resourceName: "blueImage") view.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true imageView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true imageView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true } }
mit
4281a81bb39c9a6eaaf4964726ad6d62
25.95122
87
0.688688
5.045662
false
true
false
false
colemancda/HTTP-Server
Mustache/Rendering/CoreFunctions.swift
3
31391
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ============================================================================= // MARK: - KeyedSubscriptFunction /** `KeyedSubscriptFunction` is used by the Mustache rendering engine whenever it has to resolve identifiers in expressions such as `{{ name }}` or `{{ user.name }}`. Subscript functions turn those identifiers into `MustacheBox`, the type that wraps rendered values. All types that expose keys to Mustache templates provide such a subscript function by conforming to the `MustacheBoxable` protocol. This is the case of built-in types such as NSObject, that uses `valueForKey:` in order to expose its properties; String, which exposes its "length"; collections, which expose keys like "count", "first", etc. etc. var box = Box("string") box = box["length"] // Evaluates the KeyedSubscriptFunction box.value // 6 box = Box(["a", "b", "c"]) box = box["first"] // Evaluates the KeyedSubscriptFunction box.value // "a" Your can build boxes that hold a custom subscript function. This is a rather advanced usage, only supported with the low-level function `func Box(boolValue:value:keyedSubscript:filter:render:willRender:didRender:) -> MustacheBox`. // A KeyedSubscriptFunction that turns "key" into "KEY": let keyedSubscript: KeyedSubscriptFunction = { (key: String) -> MustacheBox in return Box(key.uppercaseString) } // Render "FOO & BAR" let template = try! Template(string: "{{foo}} & {{bar}}") let box = Box(keyedSubscript: keyedSubscript) try! template.render(box) ### Missing keys vs. missing values. `KeyedSubscriptFunction` returns a non-optional `MustacheBox`. In order to express "missing key", and have Mustache rendering engine dig deeper in the context stack in order to resolve a key, return the empty box `Box()`. In order to express "missing value", and prevent the rendering engine from digging deeper, return `Box(NSNull())`. */ public typealias KeyedSubscriptFunction = (key: String) -> MustacheBox // ============================================================================= // MARK: - FilterFunction /** `FilterFunction` is the core type that lets GRMustache evaluate filtered expressions such as `{{ uppercase(string) }}`. To build a filter, you use the `Filter()` function. It takes a function as an argument. For example: let increment = Filter { (x: Int?) in return Box(x! + 1) } To let a template use a filter, register it: let template = try! Template(string: "{{increment(x)}}") template.registerInBaseContext("increment", Box(increment)) // "2" try! template.render(Box(["x": 1])) `Filter()` can take several types of functions, depending on the type of filter you want to build. The example above processes `Int` values. There are three types of filters: - Values filters: - `(MustacheBox) throws -> MustacheBox` - `(T?) throws -> MustacheBox` (Generic) - `([MustacheBox]) throws -> MustacheBox` (Multiple arguments) - Post-rendering filters: - `(Rendering) throws -> Rendering` - Custom rendering filters: - `(MustacheBox, RenderingInfo) throws -> Rendering` - `(T?, RenderingInfo) throws -> Rendering` (Generic) See the documentation of the `Filter()` functions. */ public typealias FilterFunction = (box: MustacheBox, partialApplication: Bool) throws -> MustacheBox // ----------------------------------------------------------------------------- // MARK: - Values Filters /** Builds a filter that takes a single argument. For example, here is the trivial `identity` filter: let identity = Filter { (box: MustacheBox) in return box } let template = try! Template(string: "{{identity(a)}}, {{identity(b)}}") template.registerInBaseContext("identity", Box(identity)) // "foo, 1" try! template.render(Box(["a": "foo", "b": 1])) If the template provides more than one argument, the filter returns an error of domain `GRMustacheErrorDomain` and code `GRMustacheErrorCodeRenderingError`. - parameter filter: A function `(MustacheBox) throws -> MustacheBox`. - returns: A FilterFunction. */ public func Filter(filter: (MustacheBox) throws -> MustacheBox) -> FilterFunction { return { (box: MustacheBox, partialApplication: Bool) in guard !partialApplication else { // This is a single-argument filter: we do not wait for another one. throw MustacheError.Render("Too many arguments") } return try filter(box) } } /** Builds a filter that takes a single argument of type `T?`. For example: let increment = Filter { (x: Int?) in return Box(x! + 1) } let template = try! Template(string: "{{increment(x)}}") template.registerInBaseContext("increment", Box(increment)) // "2" try! template.render(Box(["x": 1])) The argument is converted to `T` using the built-in `as?` operator before being given to the filter. If the template provides more than one argument, the filter returns an error of domain `GRMustacheErrorDomain` and code `GRMustacheErrorCodeRenderingError`. - parameter filter: A function `(T?) throws -> MustacheBox`. - returns: A FilterFunction. */ public func Filter<T>(filter: (T?) throws -> MustacheBox) -> FilterFunction { return { (box: MustacheBox, partialApplication: Bool) in guard !partialApplication else { // This is a single-argument filter: we do not wait for another one. throw MustacheError.Render("Too many arguments") } return try filter(box.value as? T) } } /** Returns a filter than accepts any number of arguments. For example: // `sum(x, ...)` evaluates to the sum of provided integers let sum = VariadicFilter { (boxes: [MustacheBox]) in // Extract integers out of input boxes, assuming zero for non numeric values let integers = boxes.map { (box) in (box.value as? Int) ?? 0 } let sum = integers.reduce(0, combine: +) return Box(sum) } let template = try! Template(string: "{{ sum(a,b,c) }}") template.registerInBaseContext("sum", Box(sum)) // Renders "6" try! template.render(Box(["a": 1, "b": 2, "c": 3])) - parameter filter: A function `([MustacheBox]) throws -> MustacheBox`. - returns: A FilterFunction. */ public func VariadicFilter(filter: ([MustacheBox]) throws -> MustacheBox) -> FilterFunction { // f(a,b,c) is implemented as f(a)(b)(c). // // f(a) returns another filter, which returns another filter, which // eventually computes the final result. // // It is the partialApplication flag the tells when it's time to return the // final result. func partialFilter(filter: ([MustacheBox]) throws -> MustacheBox, arguments: [MustacheBox]) -> FilterFunction { return { (nextArgument: MustacheBox, partialApplication: Bool) in let arguments = arguments + [nextArgument] if partialApplication { // Wait for another argument return Box(filter: partialFilter(filter, arguments: arguments)) } else { // No more argument: compute final value return try filter(arguments) } } } return partialFilter(filter, arguments: []) } // ----------------------------------------------------------------------------- // MARK: - Post-Rendering Filters /** Builds a filter that performs post rendering. `Rendering` is a type that wraps a rendered String, and its content type (HTML or Text). This filter turns a rendering in another one: // twice filter renders its argument twice: let twice = Filter { (rendering: Rendering) in return Rendering(rendering.string + rendering.string, rendering.contentType) } let template = try! Template(string: "{{ twice(x) }}") template.registerInBaseContext("twice", Box(twice)) // Renders "foofoo", "123123" try! template.render(Box(["x": "foo"])) try! template.render(Box(["x": 123])) When this filter is executed, eventual HTML-escaping performed by the rendering engine has not happened yet: the rendering argument may contain raw text. This allows you to chain post-rendering filters without mangling HTML entities. - parameter filter: A function `(Rendering) throws -> Rendering`. - returns: A FilterFunction. */ public func Filter(filter: (Rendering) throws -> Rendering) -> FilterFunction { return { (box: MustacheBox, partialApplication: Bool) in guard !partialApplication else { // This is a single-argument filter: we do not wait for another one. throw MustacheError.Render("Too many arguments") } // Box a RenderFunction return Box { (info: RenderingInfo) in let rendering = try box.render(info: info) return try filter(rendering) } } } // ----------------------------------------------------------------------------- // MARK: - Custom Rendering Filters /** Builds a filter that takes a single argument and performs custom rendering. See the documentation of the `RenderFunction` type for a detailed discussion of the `RenderingInfo` and `Rendering` types. For an example of such a filter, see the documentation of `func Filter<T>(filter: (T?, RenderingInfo) throws -> Rendering) -> FilterFunction`. This example processes `T?` instead of `MustacheBox`, but the idea is the same. - parameter filter: A function `(MustacheBox, RenderingInfo) throws -> Rendering`. - returns: A FilterFunction. */ public func Filter(filter: (MustacheBox, RenderingInfo) throws -> Rendering) -> FilterFunction { return Filter { (box: MustacheBox) in // Box a RenderFunction return Box { (info: RenderingInfo) in return try filter(box, info) } } } /** Builds a filter that takes a single argument of type `T?` and performs custom rendering. For example: // {{# pluralize(count) }}...{{/ }} renders the plural form of the section // content if the `count` argument is greater than 1. let pluralize = Filter { (count: Int?, info: RenderingInfo) in // Pluralize the inner content of the section tag: var string = info.tag.innerTemplateString if count > 1 { string += "s" // naive pluralization } return Rendering(string) } let template = try! Template(string: "I have {{ cats.count }} {{# pluralize(cats.count) }}cat{{/ }}.") template.registerInBaseContext("pluralize", Box(pluralize)) // Renders "I have 3 cats." let data = ["cats": ["Kitty", "Pussy", "Melba"]] try! template.render(Box(data)) The argument is converted to `T` using the built-in `as?` operator before being given to the filter. If the template provides more than one argument, the filter returns an error of domain `GRMustacheErrorDomain` and code `GRMustacheErrorCodeRenderingError`. See the documentation of the `RenderFunction` type for a detailed discussion of the `RenderingInfo` and `Rendering` types. - parameter filter: A function `(T?, RenderingInfo) throws -> Rendering`. - returns: A FilterFunction. */ public func Filter<T>(filter: (T?, RenderingInfo) throws -> Rendering) -> FilterFunction { return Filter { (t: T?) in // Box a RenderFunction return Box { (info: RenderingInfo) in return try filter(t, info) } } } // ============================================================================= // MARK: - RenderFunction /** `RenderFunction` is used by the Mustache rendering engine when it renders a variable tag (`{{name}}` or `{{{body}}}`) or a section tag (`{{#name}}...{{/name}}`). ### Output: `Rendering` The return type of `RenderFunction` is `Rendering`, a type that wraps a rendered String, and its ContentType (HTML or Text). Text renderings are HTML-escaped, except for `{{{triple}}}` mustache tags, and Text templates (see `Configuration.contentType` for a full discussion of the content type of templates). For example: let HTML: RenderFunction = { (_) in return Rendering("<HTML>", .HTML) } let text: RenderFunction = { (_) in return Rendering("<text>") // default content type is text } // Renders "<HTML>, &lt;text&gt;" let template = try! Template(string: "{{HTML}}, {{text}}") let data = ["HTML": Box(HTML), "text": Box(text)] let rendering = try! template.render(Box(data)) ### Input: `RenderingInfo` The `info` argument contains a `RenderingInfo` which provides information about the requested rendering: - `info.context: Context` is the context stack which contains the rendered data. - `info.tag: Tag` is the tag to render. - `info.tag.type: TagType` is the type of the tag (variable or section). You can use this type to have a different rendering for variable and section tags. - `info.tag.innerTemplateString: String` is the inner content of the tag, unrendered. For the section tag `{{# person }}Hello {{ name }}!{{/ person }}`, it is `Hello {{ name }}!`. - `info.tag.render: (Context) throws -> Rendering` is a function that renders the inner content of the tag, given a context stack. For example, the section tag `{{# person }}Hello {{ name }}!{{/ person }}` would render `Hello Arthur!`, assuming the provided context stack provides "Arthur" for the key "name". ### Example As an example, let's write a `RenderFunction` which performs the default rendering of a value: - `{{ value }}` and `{{{ value }}}` renders the built-in Swift String Interpolation of the value: our render function will return a `Rendering` with content type Text when the rendered tag is a variable tag. The Text content type makes sure that the returned string will be HTML-escaped if needed. - `{{# value }}...{{/ value }}` pushes the value on the top of the context stack, and renders the inner content of section tags. The default rendering thus reads: let value = ... // Some value let renderValue: RenderFunction = { (info: RenderingInfo) throws in // Default rendering depends on the tag type: switch info.tag.type { case .Variable: // {{ value }} and {{{ value }}} // Return the built-in Swift String Interpolation of the value: return Rendering("\(value)", .Text) case .Section: // {{# value }}...{{/ value }} // Push the value on the top of the context stack: let context = info.context.extendedContext(Box(value)) // Renders the inner content of the section tag: return try info.tag.render(context) } } let template = try! Template(string: "{{value}}") let rendering = try! template.render(Box(["value": Box(renderValue)])) - parameter info: A RenderingInfo. - parameter error: If there is a problem in the rendering, throws an error that describes the problem. - returns: A Rendering. */ public typealias RenderFunction = (info: RenderingInfo) throws -> Rendering // ----------------------------------------------------------------------------- // MARK: - Mustache lambdas /** Builds a `RenderFunction` which conforms to the "lambda" defined by the Mustache specification (see https://github.com/mustache/spec/blob/v1.1.2/specs/%7Elambdas.yml). The `lambda` parameter is a function which takes the unrendered context of a section, and returns a String. The returned `RenderFunction` renders this string against the current delimiters. For example: let template = try! Template(string: "{{#bold}}{{name}} has a Mustache!{{/bold}}") let bold = Lambda { (string) in "<b>\(string)</b>" } let data = [ "name": Box("Clark Gable"), "bold": Box(bold)] // Renders "<b>Clark Gable has a Mustache.</b>" let rendering = try! template.render(Box(data)) **Warning**: the returned String is *parsed* each time the lambda is executed. In the example above, this is inefficient because the inner content of the bolded section has already been parsed with its template. You may prefer the raw `RenderFunction` type, capable of an equivalent and faster implementation: TODO: rewrite example below in Swift 2 let bold: RenderFunction = { (info: RenderingInfo) in let rendering = try info.tag.render(info.context) return Rendering("<b>\(rendering.string)</b>", rendering.contentType) } let data = [ "name": Box("Clark Gable"), "bold": Box(bold)] // Renders "<b>Lionel Richie has a Mustache.</b>" let rendering = try! template.render(Box(data)) - parameter lambda: A `String -> String` function. - returns: A RenderFunction. */ public func Lambda(lambda: String -> String) -> RenderFunction { return { (info: RenderingInfo) in switch info.tag.type { case .Variable: // {{ lambda }} return Rendering("(Lambda)") case .Section: // {{# lambda }}...{{/ lambda }} // // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L117 // > Lambdas used for sections should parse with the current delimiters let templateRepository = TemplateRepository() templateRepository.configuration.tagDelimiterPair = info.tag.tagDelimiterPair let templateString = lambda(info.tag.innerTemplateString) let template = try templateRepository.template(string: templateString) return try template.render(info.context) // IMPLEMENTATION NOTE // // This lambda implementation is unable to process partial tags // correctly: it uses a TemplateRepository that does not know how // to load partials. // // This problem is a tricky one to solve. The `{{>partial}}` tag // loads the "partial" template which is sibling of the currently // rendered template. // // Imagine the following template hierarchy: // // - /a.mustache: {{#lambda}}...{{/lambda}}...{{>dir/b}} // - /x.mustache: ... // - /dir/b.mustache: {{#lambda}}...{{/lambda}} // - /dir/x.mustache: ... // // If the lambda returns `{{>x}}` then rendering the `a.mustache` // template should trigger the inclusion of both `/x.mustache` and // `/dir/x.mustache`. // // Given the current state of GRMustache types, achieving this // feature would require: // // - a template repository // - a TemplateID // - a method `TemplateRepository.template(string:tagDelimiterPair:baseTemplateID:)` // // Code would read something like: // // let templateString = lambda(info.tag.innerTemplateString) // let templateRepository = info.tag.templateRepository // let templateID = info.tag.templateID // let template = try templateRepository.template( // string: templateString, // tagDelimiterPair: info.tag.tagDelimiterPair, // baseTemplateID: templateID) // return try template.render(info.context) // // Should we ever implement this, beware the retain cycle between // tags and template repositories (which own tags through their // cached templateASTs). } } } /** Builds a `RenderFunction` which conforms to the "lambda" defined by the Mustache specification (see https://github.com/mustache/spec/blob/v1.1.2/specs/%7Elambdas.yml). The `lambda` parameter is a function without any argument that returns a String. The returned `RenderFunction` renders this string against the default `{{` and `}}` delimiters. For example: let template = try! Template(string: "{{fullName}} has a Mustache.") let fullName = Lambda { "{{firstName}} {{lastName}}" } let data = [ "firstName": Box("Lionel"), "lastName": Box("Richie"), "fullName": Box(fullName)] // Renders "Lionel Richie has a Mustache." let rendering = try! template.render(Box(data)) **Warning**: the returned String is *parsed* each time the lambda is executed. In the example above, this is inefficient because the same `"{{firstName}} {{lastName}}"` would be parsed several times. You may prefer using a Template instead of a lambda (see the documentation of `Template.mustacheBox` for more information): let fullName = try! Template(string:"{{firstName}} {{lastName}}") let data = [ "firstName": Box("Lionel"), "lastName": Box("Richie"), "fullName": Box(fullName)] // Renders "Lionel Richie has a Mustache." let rendering = try! template.render(Box(data)) - parameter lambda: A `() -> String` function. - returns: A RenderFunction. */ public func Lambda(lambda: () -> String) -> RenderFunction { return { (info: RenderingInfo) in switch info.tag.type { case .Variable: // {{ lambda }} // // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L73 // > Lambda results should be appropriately escaped // // Let's render a text template: let templateRepository = TemplateRepository() templateRepository.configuration.contentType = .Text let templateString = lambda() let template = try templateRepository.template(string: templateString) return try template.render(info.context) // IMPLEMENTATION NOTE // // This lambda implementation is unable to process partial tags // correctly: it uses a TemplateRepository that does not know how // to load partials. // // This problem is a tricky one to solve. The `{{>partial}}` tag // loads the "partial" template which is sibling of the currently // rendered template. // // Imagine the following template hierarchy: // // - /a.mustache: {{lambda}}...{{>dir/b}} // - /x.mustache: ... // - /dir/b.mustache: {{lambda}} // - /dir/x.mustache: ... // // If the lambda returns `{{>x}}` then rendering the `a.mustache` // template should trigger the inclusion of both `/x.mustache` and // `/dir/x.mustache`. // // Given the current state of GRMustache types, achieving this // feature would require: // // - a template repository // - a TemplateID // - a method `TemplateRepository.template(string:contentType:tagDelimiterPair:baseTemplateID:)` // // Code would read something like: // // let templateString = lambda(info.tag.innerTemplateString) // let templateRepository = info.tag.templateRepository // let templateID = info.tag.templateID // let template = try templateRepository.template( // string: templateString, // contentType: .Text, // tagDelimiterPair: ("{{", "}}), // baseTemplateID: templateID) // return try template.render(info.context) // // Should we ever implement this, beware the retain cycle between // tags and template repositories (which own tags through their // cached templateASTs). case .Section: // {{# lambda }}...{{/ lambda }} // // Behave as a true object, and render the section. let context = info.context.extendedContext(box: Box(render: Lambda(lambda))) return try info.tag.render(context) } } } /** `Rendering` is a type that wraps a rendered String, and its content type (HTML or Text). See `RenderFunction` and `FilterFunction` for more information. */ public struct Rendering { /// The rendered string public let string: String /// The content type of the rendering public let contentType: ContentType /** Builds a Rendering with a String and a ContentType. Rendering("foo") // Defaults to Text Rendering("foo", .Text) Rendering("foo", .HTML) - parameter string: A string. - parameter contentType: A content type. - returns: A Rendering. */ public init(_ string: String, _ contentType: ContentType = .Text) { self.string = string self.contentType = contentType } } extension Rendering : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { var string = self.string.replaceOccurrencesOfString("\n", withString: "\\n") string = string.replaceOccurrencesOfString("\t", withString: "\\t") var contentTypeString: String switch contentType { case .HTML: contentTypeString = "HTML" case .Text: contentTypeString = "Text" } return "Rendering(\(contentTypeString):\"\(string)\")" } } /** `RenderingInfo` provides information about a rendering. See `RenderFunction` for more information. */ public struct RenderingInfo { /// The currently rendered tag. public let tag: Tag /// The current context stack. public var context: Context // If true, the rendering is part of an enumeration. Some values don't // render the same whenever they render as an enumeration item, or alone: // {{# values }}...{{/ values }} vs. {{# value }}...{{/ value }}. // // This is the case of Int, UInt, Double, Bool: they enter the context // stack when used in an iteration, and do not enter the context stack when // used as a boolean (see https://github.com/groue/GRMustache/issues/83). // // This is also the case of collections: they enter the context stack when // used as an item of a collection, and enumerate their items when used as // a collection. var enumerationItem: Bool } // ============================================================================= // MARK: - WillRenderFunction /** Once a `WillRenderFunction` has entered the context stack, it is called just before tags are about to render, and has the opportunity to replace the value they are about to render. let logTags: WillRenderFunction = { (tag: Tag, box: MustacheBox) in print("\(tag) will render \(box.value!)") return box } // By entering the base context of the template, the logTags function // will be notified of all tags. let template = try! Template(string: "{{# user }}{{ firstName }} {{ lastName }}{{/ user }}") template.extendBaseContext(Box(logTags)) // Prints: // {{# user }} at line 1 will render { firstName = Errol; lastName = Flynn; } // {{ firstName }} at line 1 will render Errol // {{ lastName }} at line 1 will render Flynn let data = ["user": ["firstName": "Errol", "lastName": "Flynn"]] try! template.render(Box(data)) `WillRenderFunction` don't have to enter the base context of a template to perform: they can enter the context stack just like any other value, by being attached to a section. In this case, they are only notified of tags inside that section. let template = try! Template(string: "{{# user }}{{ firstName }} {{# spy }}{{ lastName }}{{/ spy }}{{/ user }}") // Prints: // {{ lastName }} at line 1 will render Flynn let data = [ "user": Box(["firstName": "Errol", "lastName": "Flynn"]), "spy": Box(logTags) ] try! template.render(Box(data)) */ public typealias WillRenderFunction = (tag: Tag, box: MustacheBox) -> MustacheBox // ============================================================================= // MARK: - DidRenderFunction /** Once a DidRenderFunction has entered the context stack, it is called just after tags have been rendered. let logRenderings: DidRenderFunction = { (tag: Tag, box: MustacheBox, string: String?) in println("\(tag) did render \(box.value!) as `\(string!)`") } // By entering the base context of the template, the logRenderings function // will be notified of all tags. let template = try! Template(string: "{{# user }}{{ firstName }} {{ lastName }}{{/ user }}") template.extendBaseContext(Box(logRenderings)) // Renders "Errol Flynn" // // Prints: // {{ firstName }} at line 1 did render Errol as `Errol` // {{ lastName }} at line 1 did render Flynn as `Flynn` // {{# user }} at line 1 did render { firstName = Errol; lastName = Flynn; } as `Errol Flynn` let data = ["user": ["firstName": "Errol", "lastName": "Flynn"]] try! template.render(Box(data)) DidRender functions don't have to enter the base context of a template to perform: they can enter the context stack just like any other value, by being attached to a section. In this case, they are only notified of tags inside that section. let template = try! Template(string: "{{# user }}{{ firstName }} {{# spy }}{{ lastName }}{{/ spy }}{{/ user }}") // Renders "Errol Flynn" // // Prints: // {{ lastName }} at line 1 did render Flynn as `Flynn` let data = [ "user": Box(["firstName": "Errol", "lastName": "Flynn"]), "spy": Box(logRenderings) ] try! template.render(Box(data)) The string argument of DidRenderFunction is optional: it is nil if and only if the tag could not render because of a rendering error. See also: - WillRenderFunction */ public typealias DidRenderFunction = (tag: Tag, box: MustacheBox, string: String?) -> Void
mit
79571ba27379137748b26b56a16f1168
34.428894
119
0.627206
4.478528
false
false
false
false
rudedogg/TiledSpriteKit
Sources/SKTilemapCamera.swift
1
12336
/* SKTilemap SKTilemapCamera.swift Created by Thomas Linthwaite on 07/04/2016. GitHub: https://github.com/TomLinthwaite/SKTilemap Website (Guide): http://tomlinthwaite.com/ Wiki: https://github.com/TomLinthwaite/SKTilemap/wiki YouTube: https://www.youtube.com/channel/UCAlJgYx9-Ub_dKD48wz6vMw Twitter: https://twitter.com/Mr_Tomoso ----------------------------------------------------------------------------------------------------------------------- MIT License Copyright (c) 2016 Tom Linthwaite Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------------------------------------------------- */ import SpriteKit #if os(iOS) import UIKit #endif protocol SKTilemapCameraDelegate : class { func didUpdatePosition(position: CGPoint, scale: CGFloat, bounds: CGRect) func didUpdateZoomScale(position: CGPoint, scale: CGFloat, bounds: CGRect) func didUpdateBounds(position: CGPoint, scale: CGFloat, bounds: CGRect) } // MARK: Camera public class SKTilemapCamera : SKCameraNode { // MARK: Properties /** The node the camera intereacts with. Anything you want to be effected by the camera should be a child of this node. */ let worldNode: SKNode /** Bounds the camera constrains the worldNode to. Default value is the size of the view but this can be changed. */ fileprivate var bounds: CGRect /** The current zoom scale of the camera. */ fileprivate var zoomScale: CGFloat /** Min/Max scale the camera can zoom in/out. */ var zoomRange: (min: CGFloat, max: CGFloat) /** Enable/Disable the ability to zoom the camera. */ var allowZoom: Bool fileprivate var isEnabled: Bool /** Enable/Disable the camera. */ var enabled: Bool { get { return isEnabled } set { isEnabled = newValue #if os(iOS) longPressGestureRecognizer.isEnabled = newValue pinchGestureRecognizer.isEnabled = newValue #endif } } /** Enable/Disable clamping of the worldNode */ var enableClamping: Bool /** Delegates are informed when the camera repositions or performs some other action. */ fileprivate var delegates: [SKTilemapCameraDelegate] = [] /** Previous touch/mouse location the last time the position was updated. */ fileprivate var previousLocation: CGPoint! // MARK: Initialization /** Initialize a basic camera. */ init(scene: SKScene, view: SKView, worldNode: SKNode) { self.worldNode = worldNode bounds = view.bounds zoomScale = 1.0 zoomRange = (0.05, 4.0) allowZoom = true isEnabled = true enableClamping = true super.init() #if os(iOS) pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(self.updateScale(_:))) view.addGestureRecognizer(pinchGestureRecognizer) longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.updatePosition(_:))) longPressGestureRecognizer.numberOfTouchesRequired = 1 longPressGestureRecognizer.numberOfTapsRequired = 0 longPressGestureRecognizer.allowableMovement = 0 longPressGestureRecognizer.minimumPressDuration = 0 view.addGestureRecognizer(longPressGestureRecognizer) #endif } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** Adds a delegate to camera. Will not allow duplicate delegates to be added. */ func addDelegate(_ delegate: SKTilemapCameraDelegate) { if let _ = delegates.index(where: { $0 === delegate }) { return } delegates.append(delegate) } /** Removes a delegate from the camera. */ func removeDelegate(_ delegate: SKTilemapCameraDelegate) { if let index = delegates.index( where: { $0 === delegate } ) { delegates.remove(at: index) } } // MARK: Input - iOS #if os(iOS) /** Used for zooming/scaling the camera. */ var pinchGestureRecognizer: UIPinchGestureRecognizer! var longPressGestureRecognizer: UILongPressGestureRecognizer! /** Used to determine the intial touch location when the user performs a pinch gesture. */ fileprivate var initialTouchLocation = CGPoint.zero /** Will move the camera based on the direction of a touch from the longPressGestureRecognizer. Any delegates of the camera will be informed that the camera moved. */ func updatePosition(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == .began { previousLocation = recognizer.location(in: recognizer.view) } if recognizer.state == .changed { if previousLocation == nil { return } let location = recognizer.location(in: recognizer.view) let difference = CGPoint(x: location.x - previousLocation.x, y: location.y - previousLocation.y) centerOnPosition(CGPoint(x: Int(position.x - difference.x), y: Int(position.y - -difference.y))) previousLocation = location } } /** Scales the worldNode using input from a pinch gesture recogniser. Any delegates of the camera will be informed that the camera changed scale. */ func updateScale(_ recognizer: UIPinchGestureRecognizer) { guard let scene = self.scene else { return } if recognizer.state == .began { initialTouchLocation = scene.convertPoint(fromView: recognizer.location(in: recognizer.view)) } if recognizer.state == .changed && enabled && allowZoom { zoomScale *= recognizer.scale applyZoomScale(zoomScale) recognizer.scale = 1 centerOnPosition(CGPoint(x: initialTouchLocation.x * zoomScale, y: initialTouchLocation.y * zoomScale)) } if recognizer.state == .ended { } } #endif // MARK: Input - OSX #if os(OSX) /** Updates the camera position based on mouse movement. Any delegates of the camera will be informed that the camera moved. */ func updatePosition(event: NSEvent) { if scene == nil || !enabled { return } if previousLocation == nil { previousLocation = event.location(in: self) } let location = event.location(in: self) let difference = CGPoint(x: location.x - previousLocation.x, y: location.y - previousLocation.y) centerOnPosition(CGPoint(x: Int(position.x - difference.x), y: Int(position.y - difference.y))) previousLocation = location } /** Call this on mouseUp so the camera can reset the previous position. Without this the update position function will assume the mouse was in the last place as before an cause undesired "jump" effect. */ func finishedInput() { previousLocation = nil } #endif // MARK: Positioning /** Moves the camera so it centers on a certain position within the scene. Easing can be applied by setting a timing interval. Otherwise the position is changed instantly. */ func centerOnPosition(_ scenePosition: CGPoint, easingDuration: TimeInterval = 0) { if easingDuration == 0 { position = scenePosition clampWorldNode() for delegate in delegates { delegate.didUpdatePosition(position: position, scale: zoomScale, bounds: self.bounds) } } else { let moveAction = SKAction.move(to: scenePosition, duration: easingDuration) moveAction.timingMode = .easeOut let blockAction = SKAction.run({ self.clampWorldNode() for delegate in self.delegates { delegate.didUpdatePosition(position: self.position, scale: self.zoomScale, bounds: self.bounds) } }) run(SKAction.group([moveAction, blockAction])) } } func centerOnNode(node: SKNode?, easingDuration: TimeInterval = 0) { guard let theNode = node , theNode.parent != nil else { return } let position = scene!.convert(theNode.position, from: theNode.parent!) centerOnPosition(position, easingDuration: easingDuration) } // MARK: Scaling and Zoom /** Applies a scale to the worldNode. Ensures that the scale stays within its range and that the worldNode is clamped within its bounds. */ func applyZoomScale(_ scale: CGFloat) { var zoomScale = scale if zoomScale < zoomRange.min { zoomScale = zoomRange.min } else if zoomScale > zoomRange.max { zoomScale = zoomRange.max } self.zoomScale = zoomScale worldNode.setScale(zoomScale) for delegate in delegates { delegate.didUpdateZoomScale(position: position, scale: zoomScale, bounds: self.bounds) } } /** Returns the minimum zoom scale possible for the size of the worldNode. Useful when you don't want the worldNode to be displayed smaller than the current bounds. */ func minimumZoomScale() -> CGFloat { let frame = worldNode.calculateAccumulatedFrame() if bounds == CGRect.zero || frame == CGRect.zero { return 0 } let xScale = (bounds.width * zoomScale) / frame.width let yScale = (bounds.height * zoomScale) / frame.height return min(xScale, yScale) } // MARK: Bounds /** Keeps the worldNode clamped between a specific bounds. If the worldNode is smaller than these bounds it will stop it from moving outside of those bounds. */ fileprivate func clampWorldNode() { if !enableClamping { return } let frame = worldNode.calculateAccumulatedFrame() var minX = frame.minX + (bounds.size.width / 2) var maxX = frame.maxX - (bounds.size.width / 2) var minY = frame.minY + (bounds.size.height / 2) var maxY = frame.maxY - (bounds.size.height / 2) if frame.width < bounds.width { swap(&minX, &maxX) } if frame.height < bounds.height { swap(&minY, &maxY) } if position.x < minX { position.x = CGFloat(Int(minX)) } else if position.x > maxX { position.x = CGFloat(Int(maxX)) } if position.y < minY { position.y = CGFloat(Int(minY)) } else if position.y > maxY { position.y = CGFloat(Int(maxY)) } } /** Returns the current bounds the camera is using. */ func getBounds() -> CGRect { return bounds } /** Updates the bounds for the worldNode to be constrained to. Will inform all delegates this change occured. */ func updateBounds(_ bounds: CGRect) { self.bounds = bounds for delegate in delegates { delegate.didUpdateBounds(position: position, scale: zoomScale, bounds: self.bounds) } } }
mit
2e1829a8648e302f445dfa6d02036311
36.609756
146
0.630512
4.9344
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
the-blue-alliance-ios/View Elements/Base/ReverseSubtitleTableViewCell.swift
1
966
import Foundation import UIKit class ReverseSubtitleTableViewCell: UITableViewCell, Reusable { // MARK: - Init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) selectionStyle = .none } // MARK: - Reusable static var nib: UINib? { return UINib(nibName: String(describing: self), bundle: nil) } // MARK: - Interface Builder @IBOutlet public var titleLabel: UILabel! { didSet { titleLabel.font = UIFont.preferredFont(forTextStyle: .subheadline) titleLabel.adjustsFontForContentSizeCategory = true titleLabel.textColor = UIColor.secondaryLabel } } @IBOutlet public var subtitleLabel: UILabel! { didSet { subtitleLabel.font = UIFont.preferredFont(forTextStyle: .body) subtitleLabel.adjustsFontForContentSizeCategory = true subtitleLabel.textColor = UIColor.label } } }
mit
d6d0e365b8cf09b7c6da10c634064e20
25.108108
78
0.642857
5.366667
false
false
false
false
liuche/FirefoxAccounts-ios
Shared/RollingFileLogger.swift
14
4160
/* 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 XCGLogger //// A rolling file logger that saves to a different log file based on given timestamp. open class RollingFileLogger: XCGLogger { fileprivate static let TwoMBsInBytes: Int64 = 2 * 100000 fileprivate let sizeLimit: Int64 fileprivate let logDirectoryPath: String? let fileLogIdentifierPrefix = "com.mozilla.firefox.filelogger." fileprivate static let DateFormatter: DateFormatter = { let formatter = Foundation.DateFormatter() formatter.dateFormat = "yyyyMMdd'T'HHmmssZ" return formatter }() let root: String public init(filenameRoot: String, logDirectoryPath: String?, sizeLimit: Int64 = TwoMBsInBytes) { root = filenameRoot self.sizeLimit = sizeLimit self.logDirectoryPath = logDirectoryPath super.init() } /** Create a new log file with the given timestamp to log events into :param: date Date for with to start and mark the new log file */ open func newLogWithDate(_ date: Date) { // Don't start a log if we don't have a valid log directory path if logDirectoryPath == nil { return } if let filename = filenameWithRoot(root, withDate: date) { remove(destinationWithIdentifier: fileLogIdentifierWithRoot(root)) add(destination: FileDestination(owner: self, writeToFile: filename, identifier: fileLogIdentifierWithRoot(root))) info("Created file destination for logger with root: \(self.root) and timestamp: \(date)") } else { error("Failed to create a new log with root name: \(self.root) and timestamp: \(date)") } } open func deleteOldLogsDownToSizeLimit() { // Check to see we haven't hit our size limit and if we did, clear out some logs to make room. while sizeOfAllLogFilesWithPrefix(self.root, exceedsSizeInBytes: sizeLimit) { deleteOldestLogWithPrefix(self.root) } } open func logFilenamesAndURLs() throws -> [(String, URL)] { guard let logPath = logDirectoryPath else { return [] } let files = try FileManager.default.contentsOfDirectoryAtPath(logPath, withFilenamePrefix: root) return files.flatMap { filename in if let url = URL(string: "\(logPath)/\(filename)") { return (filename, url) } return nil } } fileprivate func deleteOldestLogWithPrefix(_ prefix: String) { if logDirectoryPath == nil { return } do { let logFiles = try FileManager.default.contentsOfDirectoryAtPath(logDirectoryPath!, withFilenamePrefix: prefix) if let oldestLogFilename = logFiles.first { try FileManager.default.removeItem(atPath: "\(logDirectoryPath!)/\(oldestLogFilename)") } } catch _ as NSError { error("Shouldn't get here") return } } fileprivate func sizeOfAllLogFilesWithPrefix(_ prefix: String, exceedsSizeInBytes threshold: Int64) -> Bool { guard let path = logDirectoryPath else { return false } let logDirURL = URL(fileURLWithPath: path) do { return try FileManager.default.allocatedSizeOfDirectoryAtURL(logDirURL, forFilesPrefixedWith: prefix, isLargerThanBytes: threshold) } catch let errorValue as NSError { error("Error determining log directory size: \(errorValue)") } return false } fileprivate func filenameWithRoot(_ root: String, withDate date: Date) -> String? { if let dir = logDirectoryPath { return "\(dir)/\(root).\(RollingFileLogger.DateFormatter.string(from: date)).log" } return nil } fileprivate func fileLogIdentifierWithRoot(_ root: String) -> String { return "\(fileLogIdentifierPrefix).\(root)" } }
mpl-2.0
ce96302ecc5c92efc81ee2f8fbc02d11
35.173913
143
0.64375
4.946492
false
false
false
false
cxa/MenuItemKit
AutoPopupMenuControllerDemo/AutoPopupMenuControllerDemo/ViewController.swift
1
1604
// // ViewController.swift // AutoPopupMenuControllerDemo // // Created by CHEN Xian-an on 25/02/2018. // Copyright © 2018 Neo Xian-an CHEN. All rights reserved. // import UIKit import MenuItemKit class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! var showsColorItem = false override func viewDidLoad() { super.viewDidLoad() let controller = UIMenuController.shared let textItem = UIMenuItem(title: "Toggle Color Item") { [weak self] _ in self?.showAlertWithTitle("Toggle item tapped") self?.showsColorItem = !(self?.showsColorItem ?? true) } let image = UIImage(named: "Image") let imageItem = UIMenuItem(title: "Image", image: image) { [weak self] _ in self?.showAlertWithTitle("image item tapped") } let colorImage = UIImage(named: "ColorImage") let colorImageItem = UIMenuItem(title: "ColorImage", image: colorImage) { [weak self] _ in self?.showAlertWithTitle("color image item tapped") } controller.menuItems = [textItem, imageItem, colorImageItem] UIMenuController.installTo(responder: textView) { action, `default` in if action == colorImageItem.action { return self.showsColorItem } return UIMenuItem.isMenuItemKitSelector(action) } textView.becomeFirstResponder() } func showAlertWithTitle(_ title: String) { let alertVC = UIAlertController(title: title, message: nil, preferredStyle: .alert) alertVC.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { _ in })) present(alertVC, animated: true, completion: nil) } }
mit
1f6125c2fc243b64272824b672222bc6
31.714286
94
0.702433
4.240741
false
false
false
false
WhisperSystems/Signal-iOS
Signal/src/ViewControllers/ConversationView/Cells/TypingIndicatorCell.swift
1
5449
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation @objc(OWSTypingIndicatorCell) public class TypingIndicatorCell: ConversationViewCell { @objc public static let cellReuseIdentifier = "TypingIndicatorCell" @available(*, unavailable, message:"use other constructor instead.") @objc public required init(coder aDecoder: NSCoder) { notImplemented() } private let kAvatarSize: CGFloat = 36 private let kAvatarHSpacing: CGFloat = 8 private let avatarView = AvatarImageView() private let bubbleView = OWSBubbleView() private let typingIndicatorView = TypingIndicatorView() private var viewConstraints = [NSLayoutConstraint]() override init(frame: CGRect) { super.init(frame: frame) commonInit() } private func commonInit() { self.layoutMargins = .zero self.contentView.layoutMargins = .zero bubbleView.layoutMargins = .zero bubbleView.addSubview(typingIndicatorView) contentView.addSubview(bubbleView) avatarView.autoSetDimension(.width, toSize: kAvatarSize) avatarView.autoSetDimension(.height, toSize: kAvatarSize) } @objc public override func loadForDisplay() { guard let conversationStyle = self.conversationStyle else { owsFailDebug("Missing conversationStyle") return } bubbleView.fillColor = conversationStyle.bubbleColor(isIncoming: true) typingIndicatorView.startAnimation() viewConstraints.append(contentsOf: [ bubbleView.autoPinEdge(toSuperviewEdge: .leading, withInset: conversationStyle.gutterLeading), bubbleView.autoPinEdge(toSuperviewEdge: .trailing, withInset: conversationStyle.gutterTrailing, relation: .greaterThanOrEqual), bubbleView.autoPinTopToSuperviewMargin(withInset: 0), bubbleView.autoPinBottomToSuperviewMargin(withInset: 0), typingIndicatorView.autoPinEdge(toSuperviewEdge: .leading, withInset: conversationStyle.textInsetHorizontal), typingIndicatorView.autoPinEdge(toSuperviewEdge: .trailing, withInset: conversationStyle.textInsetHorizontal), typingIndicatorView.autoPinTopToSuperviewMargin(withInset: conversationStyle.textInsetTop), typingIndicatorView.autoPinBottomToSuperviewMargin(withInset: conversationStyle.textInsetBottom) ]) if let avatarView = configureAvatarView() { contentView.addSubview(avatarView) viewConstraints.append(contentsOf: [ bubbleView.autoPinLeading(toTrailingEdgeOf: avatarView, offset: kAvatarHSpacing), bubbleView.autoAlignAxis(.horizontal, toSameAxisOf: avatarView) ]) } else { avatarView.removeFromSuperview() } } private func configureAvatarView() -> UIView? { guard let viewItem = self.viewItem else { owsFailDebug("Missing viewItem") return nil } guard let typingIndicators = viewItem.interaction as? TypingIndicatorInteraction else { owsFailDebug("Missing typingIndicators") return nil } guard shouldShowAvatar() else { return nil } guard let colorName = viewItem.authorConversationColorName else { owsFailDebug("Missing authorConversationColorName") return nil } guard let authorAvatarImage = OWSContactAvatarBuilder(address: typingIndicators.address, colorName: ConversationColorName(rawValue: colorName), diameter: UInt(kAvatarSize)).build() else { owsFailDebug("Could build avatar image") return nil } avatarView.image = authorAvatarImage return avatarView } private func shouldShowAvatar() -> Bool { guard let viewItem = self.viewItem else { owsFailDebug("Missing viewItem") return false } return viewItem.isGroupThread } @objc public override func cellSize() -> CGSize { guard let conversationStyle = self.conversationStyle else { owsFailDebug("Missing conversationStyle") return .zero } let insetsSize = CGSize(width: conversationStyle.textInsetHorizontal * 2, height: conversationStyle.textInsetTop + conversationStyle.textInsetBottom) let typingIndicatorSize = typingIndicatorView.sizeThatFits(.zero) let bubbleSize = CGSizeAdd(insetsSize, typingIndicatorSize) if shouldShowAvatar() { return CGSizeCeil(CGSize(width: kAvatarSize + kAvatarHSpacing + bubbleSize.width, height: max(kAvatarSize, bubbleSize.height))) } else { return CGSizeCeil(CGSize(width: bubbleSize.width, height: max(kAvatarSize, bubbleSize.height))) } } @objc public override func prepareForReuse() { super.prepareForReuse() NSLayoutConstraint.deactivate(viewConstraints) viewConstraints = [NSLayoutConstraint]() avatarView.image = nil avatarView.removeFromSuperview() typingIndicatorView.stopAnimation() } }
gpl-3.0
9fed9027c5a87bb0364ac8300742ad1d
35.817568
139
0.650028
5.723739
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Browser/Views/BrowserErrorView.swift
1
2309
// Copyright DApps Platform Inc. All rights reserved. import UIKit protocol BrowserErrorViewDelegate: class { func didTapReload(_ sender: Button) } final class BrowserErrorView: UIView { weak var delegate: BrowserErrorViewDelegate? private let topMargin: CGFloat = 120 private let leftMargin: CGFloat = 40 private let buttonTopMargin: CGFloat = 6 lazy var textLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.textColor = Colors.gray label.font = UIFont.systemFont(ofSize: 18) label.translatesAutoresizingMaskIntoConstraints = false return label }() lazy var reloadButton: Button = { let button = Button(size: .normal, style: .borderless) button.addTarget(self, action: #selector(reloadTapped), for: .touchUpInside) button.setTitle(NSLocalizedString("browser.reload.button.title", value: "Reload", comment: ""), for: .normal) button.translatesAutoresizingMaskIntoConstraints = false button.sizeToFit() return button }() init() { super.init(frame: CGRect.zero) finishInit() } override init(frame: CGRect) { super.init(frame: frame) finishInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func show(error: Error) { self.isHidden = false textLabel.text = error.localizedDescription textLabel.textAlignment = .center textLabel.setNeedsLayout() } @objc func reloadTapped() { delegate?.didTapReload(reloadButton) } private func finishInit() { self.backgroundColor = .white addSubview(textLabel) addSubview(reloadButton) NSLayoutConstraint.activate([ textLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: leftMargin), textLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -leftMargin), textLabel.topAnchor.constraint(equalTo: topAnchor, constant: topMargin), reloadButton.centerXAnchor.constraint(equalTo: textLabel.centerXAnchor), reloadButton.topAnchor.constraint(equalTo: textLabel.bottomAnchor, constant: buttonTopMargin), ]) } }
gpl-3.0
73799a6737dab0b5c5029e6c51a9ffde
30.630137
117
0.667822
5.085903
false
false
false
false
LuckyResistor/FontToBytes
FontToBytes/WelcomeView.swift
1
7125
// // Lucky Resistor's Font to Byte // --------------------------------------------------------------------------- // (c)2015 by Lucky Resistor. See LICENSE for details. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // import Cocoa /// The view for the welcome screen where the user can drop PNG files. /// This view also displays the progress indicator until the result is ready. /// class WelcomeView: NSView { /// A closure which is called if a URL is dropped on the welcome screen. /// var onURLDropped: ((url: NSURL)->())? = nil /// The main layer of this view /// private var mainLayer = CALayer() /// The displayed drop border. /// private var borderLayer = CAShapeLayer() /// The text inside of the drop border. /// private var textLayer = CATextLayer() /// The background color in normal state. /// private let backgroundColorNormal = StyleKit.lRWhite /// The foreground color in normal state. /// private let foregroundColorNormal = StyleKit.lRGray1 /// The background color in drag state. /// private let backgroundColorDrag = StyleKit.lRBlue /// The foreground color in drag state. /// private let foregroundColorDrag = StyleKit.lRWhite /// If a file was successfully dropped. /// private var successFullDrop: Bool = false override init(frame frameRect: NSRect) { super.init(frame: frameRect) initializeLayers() registerForDraggedTypes([NSFilenamesPboardType]) } required init?(coder: NSCoder) { super.init(coder: coder) initializeLayers() registerForDraggedTypes([NSFilenamesPboardType]) } /// Initialize all layers /// func initializeLayers() { // setup the main layer self.layer = mainLayer self.wantsLayer = true mainLayer.layoutManager = CAConstraintLayoutManager() mainLayer.backgroundColor = backgroundColorNormal.CGColor // Setup the border mainLayer.addSublayer(borderLayer) borderLayer.addConstraint(CAConstraint(attribute: .MidX, relativeTo: "superlayer", attribute: .MidX)) borderLayer.addConstraint(CAConstraint(attribute: .MidY, relativeTo: "superlayer", attribute: .MidY)) borderLayer.frame = CGRect(x: 0.0, y: 0.0, width: 380.0, height: 280.0) let borderRadius: CGFloat = 40.0 let borderLineWidth: CGFloat = 20.0 let innerRect = CGRectInset(borderLayer.bounds, borderLineWidth+2.0, borderLineWidth+2.0) let path = NSBezierPath(roundedRect: innerRect, xRadius: borderRadius, yRadius: borderRadius) borderLayer.path = path.newCGPath() borderLayer.fillColor = nil borderLayer.lineWidth = 10.0 borderLayer.lineDashPhase = 20.0 borderLayer.lineDashPattern = [20.0, 10.0] borderLayer.strokeColor = foregroundColorNormal.CGColor borderLayer.actions = ["position": NSNull(), "bounds": NSNull()] // Setup the text mainLayer.addSublayer(textLayer) textLayer.addConstraint(CAConstraint(attribute: .MidX, relativeTo: "superlayer", attribute: .MidX)) textLayer.addConstraint(CAConstraint(attribute: .MidY, relativeTo: "superlayer", attribute: .MidY)) textLayer.string = NSLocalizedString("Drop your\nPNG file here!", comment: "Message to drop PNG files.") textLayer.alignmentMode = kCAAlignmentCenter textLayer.actions = ["position": NSNull(), "bounds": NSNull()] textLayer.font = NSFont.boldSystemFontOfSize(50.0) textLayer.foregroundColor = foregroundColorNormal.CGColor } /// Switch the colors to visualize the two drop states. /// func setDropState(cursorInside: Bool) { let newForegroundColor: NSColor let newBackgroundColor: NSColor if cursorInside { newForegroundColor = foregroundColorDrag newBackgroundColor = backgroundColorDrag } else { newForegroundColor = foregroundColorNormal newBackgroundColor = backgroundColorNormal } borderLayer.strokeColor = newForegroundColor.CGColor textLayer.foregroundColor = newForegroundColor.CGColor mainLayer.backgroundColor = newBackgroundColor.CGColor } override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation { let pasteBoard = sender.draggingPasteboard() if let types = pasteBoard.types { if (types.contains(NSFilenamesPboardType)) { let options: [String: AnyObject] = [NSPasteboardURLReadingFileURLsOnlyKey: true, NSPasteboardURLReadingContentsConformToTypesKey:["public.png"]] let classes: [AnyClass] = [NSURL.self] if let fileURLs = pasteBoard.readObjectsForClasses(classes, options: options) { if fileURLs.count == 1 { setDropState(true) return .Copy } } } } return .None } override func draggingEnded(sender: NSDraggingInfo?) { if !successFullDrop { setDropState(false) } } override func performDragOperation(sender: NSDraggingInfo) -> Bool { let pasteBoard = sender.draggingPasteboard() if let types = pasteBoard.types { if (types.contains(NSFilenamesPboardType)) { let options: [String: AnyObject] = [NSPasteboardURLReadingFileURLsOnlyKey: true, NSPasteboardURLReadingContentsConformToTypesKey:["public.png"]] let classes: [AnyClass] = [NSURL.self] let fileURLs = pasteBoard.readObjectsForClasses(classes, options: options) self.onURLDropped!(url: fileURLs![0] as! NSURL) self.successFullDrop = true goIntoDroppedState() } } return true } func goIntoDroppedState() { // background for progress indicator self.mainLayer.backgroundColor = StyleKit.lRWhite.CGColor self.borderLayer.hidden = true self.textLayer.hidden = true } override func draggingExited(sender: NSDraggingInfo?) { if !successFullDrop { setDropState(false) } } }
gpl-2.0
0df6dc5a1916019adbef183a093e5396
35.538462
112
0.637474
5.159305
false
false
false
false
candyan/RepairMan
RepairMan/controllers/LoginViewController.swift
1
5415
// // LoginViewController.swift // RepairMan // // Created by cherry on 15/8/23. // Copyright (c) 2015年 ABRS. All rights reserved. // import UIKit @objc protocol LoginViewControllerDelegate: NSObjectProtocol { optional func loginViewController(loginVC: LoginViewController, didFinishLoginWithInfo info: [String: AnyObject!]) } class LoginViewController: UIViewController { weak var delegate: LoginViewControllerDelegate? var nextButton: UIButton? var nameTextField: UITextField? var passwordTextField: UITextField? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupNavigator() self.edgesForExtendedLayout = UIRectEdge.None self.view.backgroundColor = UIColor.whiteColor() self.loadSubviews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension LoginViewController { private func loadSubviews() { nameTextField = UITextField.loginTextField("手机号") self.view.addSubview(nameTextField!) nameTextField!.delegate = self nameTextField!.mas_makeConstraints({ (maker) -> Void in maker.width.mas_equalTo()(200) maker.centerX.equalTo()(self.view) maker.height.mas_equalTo()(50) maker.top.equalTo()(self.view).offset()(40) }) passwordTextField = UITextField.loginTextField("密码") self.view.addSubview(passwordTextField!) passwordTextField!.delegate = self passwordTextField!.secureTextEntry = true passwordTextField!.mas_makeConstraints { (maker) -> Void in maker.width.equalTo()(self.nameTextField!) maker.centerX.equalTo()(self.nameTextField!) maker.height.equalTo()(self.nameTextField!) maker.top.equalTo()(self.nameTextField!.mas_bottom) } nextButton = UIButton(frame: CGRectZero) self.view.addSubview(nextButton!) nextButton!.mas_makeConstraints { (maker) -> Void in maker.width.equalTo()(200) maker.height.equalTo()(44) maker.top.equalTo()(self.passwordTextField!.mas_bottom).offset()(20); maker.centerX.equalTo()(self.view) } nextButton!.layer.cornerRadius = 22 nextButton!.backgroundColor = UIColor(hex: 0x4A90E2) nextButton!.setTitle("登录", forState: .Normal) nextButton!.titleLabel?.font = UIFont(name: "Helvetica", size: 17) nextButton!.setTitleColor(UIColor.whiteColor(), forState: .Normal) nextButton!.addTarget(self, action: "nextButtonTouchUpInsideHandler:", forControlEvents: .TouchUpInside) } private func setupNavigator() { self.title = "登录" weak var weakSelf = self let closeBarButtonItems = UIBarButtonItem.barButtonItemsWithImage(UIImage(named: "NaviClose"), actionBlock: { () -> Void in weakSelf?.dismissViewControllerAnimated(true, completion: nil) }) self.navigationItem.leftBarButtonItems = closeBarButtonItems as? [UIBarButtonItem] } } extension LoginViewController : UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } extension LoginViewController { internal func nextButtonTouchUpInsideHandler(sender: UIButton?) { weak var weakSelf = self if self.nameTextField?.text.isEmpty == false && self.passwordTextField?.text.isEmpty == false { MBProgressHUD.showProgressHUDWithText("登录中...") AVUser.logInWithMobilePhoneNumberInBackground(self.nameTextField?.text, password: self.passwordTextField?.text, block: { (user, error) -> Void in if error == nil && user != nil { MBProgressHUD.hideHUDForView(UIApplication.sharedApplication().keyboardWindow(), animated: false) AVUser.changeCurrentUser(user, save: true) weakSelf?.delegate?.loginViewController!(weakSelf!, didFinishLoginWithInfo: ["LoginUser": user]) } else { MBProgressHUD.showHUDWithText("登录失败", complete: nil) } }) } } } extension UITextField { private static func loginTextField(placeholder: String) -> UITextField! { let textField = UITextField(frame: CGRectZero) textField.placeholder = placeholder textField.font = UIFont(name: "helvetica", size: 13) textField.textColor = UIColor(hex: 0x333333) textField.returnKeyType = .Done let bottomSL = YASeparatorLine(frame: CGRectZero, lineColor: UIColor(hex: 0x000000, alpha: 0.2), lineWidth: 1) textField.addSubview(bottomSL) bottomSL.mas_makeConstraints { (maker) -> Void in maker.leading.equalTo()(textField) maker.trailing.equalTo()(textField) maker.height.mas_equalTo()(0.5) maker.bottom.equalTo()(textField) } return textField } }
mit
3b21c85904c44238bffa420d93ea08fb
34.635762
121
0.628694
5.249756
false
false
false
false
wwu-pi/md2-framework
de.wwu.md2.framework/res/resources/ios/lib/controller/eventhandler/MD2OnConnectionRegainedHandler.swift
1
1540
// // MD2OnConnectionRegainedHandler.swift // md2-ios-library // // Created by Christoph Rieger on 05.08.15. // Copyright (c) 2015 Christoph Rieger. All rights reserved. // /// Event handler for connection regains. class MD2OnConnectionRegainedHandler: MD2GlobalEventHandler { /// The singleton instance. static let instance: MD2OnConnectionRegainedHandler = MD2OnConnectionRegainedHandler() /// The list of registered actions. var actions: Dictionary<String, MD2Action> = [:] /// Singleton initializer. private init() { // Nothing to initialize } /** Register an action. :param: action The action to execute in case of an event. */ func registerAction(action: MD2Action) { actions[action.actionSignature] = action } /** Unregister an action. :param: action The action to remove. */ func unregisterAction(action: MD2Action) { for (key, value) in actions { if key == action.actionSignature { actions[key] = nil break } } } /** Method that is called to fire an event. *Notice* Visible to Objective-C runtime to receive events. */ @objc func fire() { //println("Event fired to OnClickHandler: " + String(sender.tag) + "=" + WidgetMapping.fromRawValue(sender.tag).description) for (_, action) in actions { action.execute() } } }
apache-2.0
4cf797451a06b833c5660eecd8ab1f67
24.683333
132
0.58961
4.4
false
false
false
false
austinfitzpatrick/SwiftVG
SwiftVG/SwiftSVG/Views/SVGView.swift
1
2247
// // SVGView.swift // SVGPlayground // // Created by Austin Fitzpatrick on 3/18/15. // Copyright (c) 2015 Seedling. All rights reserved. // import UIKit /// An SVGView provides a way to display SVGVectorImages to the screen respecting the contentMode property. @IBDesignable class SVGView: UIView { @IBInspectable var svgName:String? // The name of the SVG - mostly for interface builder { didSet { svgNameChanged() } } var vectorImage:SVGVectorImage? // The vector image to draw to the screen { didSet { setNeedsDisplay() } } convenience init(vectorImage:SVGVectorImage?){ self.init(frame:CGRect(x: 0, y: 0, width: vectorImage?.size.width ?? 0, height: vectorImage?.size.height ?? 0)) self.vectorImage = vectorImage } //MARK: Lifecycle override func awakeFromNib() { super.awakeFromNib() if let svgName = svgName { svgNameChanged() } } /// When the SVG's name changes we'll reparse the new file func svgNameChanged() { #if !TARGET_INTERFACE_BUILDER let bundle = NSBundle.mainBundle() #else let bundle = NSBundle(forClass: self.dynamicType) #endif if let path = bundle.pathForResource(svgName, ofType: "svg") { let parser = SVGParser(path: path) vectorImage = parser.parse() } else { vectorImage = nil } } /// Draw the SVGVectorImage to the screen - respecting the contentMode property override func drawRect(rect: CGRect) { super.drawRect(rect) if let svg = self.vectorImage { let context = UIGraphicsGetCurrentContext() let translation = svg.translationWithTargetSize(rect.size, contentMode: contentMode) let scale = svg.scaleWithTargetSize(rect.size, contentMode: contentMode) CGContextScaleCTM(context, scale.width, scale.height) CGContextTranslateCTM(context, translation.x / scale.width, translation.y / scale.height) svg.draw() } } /// Interface builder drawing code override func prepareForInterfaceBuilder() { svgNameChanged() setNeedsDisplay() } }
mit
38c3620fff96952cda934f47d3832913
33.045455
119
0.631954
4.567073
false
false
false
false
SwiftAndroid/swift
stdlib/public/core/Unmanaged.swift
1
6774
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type for propagating an unmanaged object reference. /// /// When you use this type, you become partially responsible for /// keeping the object alive. @_fixed_layout public struct Unmanaged<Instance : AnyObject> { internal unowned(unsafe) var _value: Instance @_versioned @_transparent internal init(_private: Instance) { _value = _private } /// Unsafely turn an opaque C pointer into an unmanaged /// class reference. /// /// This operation does not change reference counts. /// /// let str: CFString = Unmanaged.fromOpaque(ptr).takeUnretainedValue() @_transparent @warn_unused_result public static func fromOpaque(_ value: OpaquePointer) -> Unmanaged { return Unmanaged(_private: unsafeBitCast(value, to: Instance.self)) } /// Create an unmanaged reference with an unbalanced retain. /// The object will leak if nothing eventually balances the retain. /// /// This is useful when passing an object to an API which Swift /// does not know the ownership rules for, but you know that the /// API expects you to pass the object at +1. @_transparent @warn_unused_result public static func passRetained(_ value: Instance) -> Unmanaged { return Unmanaged(_private: value).retain() } /// Create an unmanaged reference without performing an unbalanced /// retain. /// /// This is useful when passing a reference to an API which Swift /// does not know the ownership rules for, but you know that the /// API expects you to pass the object at +0. /// /// CFArraySetValueAtIndex(.passUnretained(array), i, /// .passUnretained(object)) @_transparent @warn_unused_result public static func passUnretained(_ value: Instance) -> Unmanaged { return Unmanaged(_private: value) } /// Get the value of this unmanaged reference as a managed /// reference without consuming an unbalanced retain of it. /// /// This is useful when a function returns an unmanaged reference /// and you know that you're not responsible for releasing the result. @warn_unused_result public func takeUnretainedValue() -> Instance { return _value } /// Get the value of this unmanaged reference as a managed /// reference and consume an unbalanced retain of it. /// /// This is useful when a function returns an unmanaged reference /// and you know that you're responsible for releasing the result. @warn_unused_result public func takeRetainedValue() -> Instance { let result = _value release() return result } /// Get the value of the unmanaged referenced as a managed reference without /// consuming an unbalanced retain of it and pass it to the closure. Asserts /// that there is some other reference ('the owning reference') to the /// instance referenced by the unmanaged reference that guarantees the /// lifetime of the instance for the duration of the /// '_withUnsafeGuaranteedRef' call. /// /// NOTE: You are responsible for ensuring this by making the owning /// reference's lifetime fixed for the duration of the /// '_withUnsafeGuaranteedRef' call. /// /// Violation of this will incur undefined behavior. /// /// A lifetime of a reference 'the instance' is fixed over a point in the /// programm if: /// /// * There exists a global variable that references 'the instance'. /// /// import Foundation /// var globalReference = Instance() /// func aFunction() { /// point() /// } /// /// Or if: /// /// * There is another managed reference to 'the instance' whose life time is /// fixed over the point in the program by means of 'withExtendedLifetime' /// dynamically closing over this point. /// /// var owningReference = Instance() /// ... /// withExtendedLifetime(owningReference) { /// point($0) /// } /// /// Or if: /// /// * There is a class, or struct instance ('owner') whose lifetime is fixed /// at the point and which has a stored property that references /// 'the instance' for the duration of the fixed lifetime of the 'owner'. /// /// class Owned { /// } /// /// class Owner { /// final var owned : Owned /// /// func foo() { /// withExtendedLifetime(self) { /// doSomething(...) /// } // Assuming: No stores to owned occur for the dynamic lifetime of /// // the withExtendedLifetime invocation. /// } /// /// func doSomething() { /// // both 'self' and 'owned''s lifetime is fixed over this point. /// point(self, owned) /// } /// } /// /// The last rule applies transitively through a chains of stored references /// and nested structs. /// /// Examples: /// /// var owningReference = Instance() /// ... /// withExtendedLifetime(owningReference) { /// let u = Unmanaged.passUnretained(owningReference) /// for i in 0 ..< 100 { /// u._withUnsafeGuaranteedRef { /// $0.doSomething() /// } /// } /// } /// /// class Owner { /// final var owned : Owned /// /// func foo() { /// withExtendedLifetime(self) { /// doSomething(Unmanaged.passUnretained(owned)) /// } /// } /// /// func doSomething(_ u : Unmanaged<Owned>) { /// u._withUnsafeGuaranteedRef { /// $0.doSomething() /// } /// } /// } public func _withUnsafeGuaranteedRef<Result>( @noescape _ closure: (Instance) throws -> Result ) rethrows -> Result { let instance = _value let (guaranteedInstance, token) = Builtin.unsafeGuaranteed(instance) let result = try closure(guaranteedInstance) Builtin.unsafeGuaranteedEnd(token) return result } /// Perform an unbalanced retain of the object. @_transparent public func retain() -> Unmanaged { Builtin.retain(_value) return self } /// Perform an unbalanced release of the object. @_transparent public func release() { Builtin.release(_value) } #if _runtime(_ObjC) /// Perform an unbalanced autorelease of the object. @_transparent public func autorelease() -> Unmanaged { Builtin.autorelease(_value) return self } #endif }
apache-2.0
57bb7dbca97ab4def2771dd35b8aba71
31.411483
80
0.627694
4.598778
false
false
false
false
tensorflow/swift-apis
Sources/TensorFlow/Core/TensorGroup.swift
1
13871
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import CTensorFlow /// A protocol representing types that can be mapped to `Array<CTensorHandle>`. /// /// This protocol is defined separately from `TensorGroup` in order for the number of tensors to be /// determined at runtime. For example, `[Tensor<Float>]` may have an unknown number of elements at /// compile time. /// /// This protocol can be derived automatically for structs whose stored properties all conform to /// the `TensorGroup` protocol. It cannot be derived automatically for structs whose properties all /// conform to `TensorArrayProtocol` due to the constructor requirement (i.e., in such cases it /// would be impossible to know how to break down `count` among the stored properties). public protocol TensorArrayProtocol { /// Writes the tensor handles to `address`, which must be allocated with enough capacity to hold /// `_tensorHandleCount` handles. The tensor handles written to `address` are borrowed: this /// container still owns them. func _unpackTensorHandles(into address: UnsafeMutablePointer<CTensorHandle>?) var _tensorHandleCount: Int32 { get } var _typeList: [TensorDataType] { get } var _tensorHandles: [_AnyTensorHandle] { get } init(_owning tensorHandles: UnsafePointer<CTensorHandle>?, count: Int) init<C: RandomAccessCollection>(_handles: C) where C.Element: _AnyTensorHandle } extension TensorArrayProtocol { public init<C: RandomAccessCollection>(_handles: C) where C.Element: _AnyTensorHandle { let status = TF_NewStatus() defer { TF_DeleteStatus(status) } let buffer = UnsafeMutableBufferPointer<CTensorHandle>.allocate(capacity: _handles.count) defer { buffer.deallocate() } for (i, handle) in _handles.enumerated() { // Increment the reference count in TF. let handleCopy = TFE_TensorHandleCopySharingTensor(handle._cTensorHandle, status) checkOk(status) buffer[i] = handleCopy! } let baseAddress = UnsafeMutablePointer<OpaquePointer>(buffer.baseAddress) self.init(_owning: baseAddress, count: _handles.count) } public var _tensorHandles: [_AnyTensorHandle] { let status = TF_NewStatus() defer { TF_DeleteStatus(status) } let count = Int(_tensorHandleCount) let buffer = UnsafeMutableBufferPointer<CTensorHandle>.allocate(capacity: count) defer { buffer.deallocate() } self._unpackTensorHandles(into: buffer.baseAddress) let result: [TFETensorHandle] = (0..<count).map { let cTensorHandle = buffer[$0] // Increment the reference count in TF. let handleCopy = TFE_TensorHandleCopySharingTensor(cTensorHandle, status) checkOk(status) return TFETensorHandle(_owning: handleCopy!) } return result } } /// A protocol representing types that can be mapped to and from `Array<CTensorHandle>`. /// /// When a `TensorGroup` is used as an argument to a tensor operation, it is passed as an argument /// list whose elements are the tensor fields of the type. /// /// When a `TensorGroup` is returned as a result of a tensor operation, it is initialized with its /// tensor fields set to the tensor operation's tensor results. public protocol TensorGroup: TensorArrayProtocol { /// The types of the tensor stored properties in this type. static var _typeList: [TensorDataType] { get } /// Initializes a value of this type, taking ownership of the `_tensorHandleCount` tensors /// starting at address `tensorHandles`. init(_owning tensorHandles: UnsafePointer<CTensorHandle>?) } extension TensorGroup { /// The number of tensor fields in this type. public static var _tensorHandleCount: Int32 { return Int32(Self._typeList.count) } /// An array of `nil`s with the same number of elements as `_outputTypeList`. The `nil` /// represents unknown shape. public static var _unknownShapeList: [TensorShape?] { return Array(repeating: nil, count: _typeList.count) } // The following instance properties are from `TensorArrayProtocol`. public var _tensorHandleCount: Int32 { return Int32(Self._typeList.count) } public var _typeList: [TensorDataType] { return Self._typeList } public init(_owning tensorHandles: UnsafePointer<CTensorHandle>?, count: Int) { precondition(count == Self._typeList.count) self.init(_owning: tensorHandles) } } //===------------------------------------------------------------------------------------------===// // TensorGroup Conformances //===------------------------------------------------------------------------------------------===// extension TensorHandle: TensorGroup { @inlinable public static var _unknownShapeList: [TensorShape?] { return [nil] } @inlinable public static var _typeList: [TensorDataType] { return [Scalar.tensorFlowDataType] } public var _tensorHandles: [_AnyTensorHandle] { [self.handle] } public func _unpackTensorHandles(into address: UnsafeMutablePointer<CTensorHandle>?) { address!.initialize(to: _cTensorHandle) } public init(_owning tensorHandles: UnsafePointer<CTensorHandle>?) { self.init(_owning: tensorHandles!.pointee) } public init<C: RandomAccessCollection>( _handles: C ) where C.Element: _AnyTensorHandle { precondition(_handles.count == 1) self.init(handle: _handles[_handles.startIndex]) } } extension ResourceHandle: TensorGroup { @inlinable public static var _unknownShapeList: [TensorShape?] { return [nil] } @inlinable public static var _typeList: [TensorDataType] { return [TensorDataType(TF_RESOURCE)] } public var _tensorHandles: [_AnyTensorHandle] { [self.handle] } public func _unpackTensorHandles(into address: UnsafeMutablePointer<CTensorHandle>?) { address!.initialize(to: _cTensorHandle) } public init(_owning tensorHandles: UnsafePointer<CTensorHandle>?) { self.init(owning: tensorHandles!.pointee) } public init<C: RandomAccessCollection>( _handles: C ) where C.Element: _AnyTensorHandle { precondition(_handles.count == 1) self.init(handle: _handles[_handles.startIndex]) } } extension VariantHandle: TensorGroup { @inlinable public static var _unknownShapeList: [TensorShape?] { return [nil] } @inlinable public static var _typeList: [TensorDataType] { return [TensorDataType(TF_VARIANT)] } public var _tensorHandles: [_AnyTensorHandle] { [self.handle] } public func _unpackTensorHandles(into address: UnsafeMutablePointer<CTensorHandle>?) { address!.initialize(to: _cTensorHandle) } public init(_owning tensorHandles: UnsafePointer<CTensorHandle>?) { self.init(owning: tensorHandles!.pointee) } public init<C: RandomAccessCollection>( _handles: C ) where C.Element: _AnyTensorHandle { precondition(_handles.count == 1) self.init(handle: _handles[_handles.startIndex]) } } extension Tensor: TensorGroup { @inlinable public static var _unknownShapeList: [TensorShape?] { return [nil] } @inlinable public static var _typeList: [TensorDataType] { return [Scalar.tensorFlowDataType] } public func _unpackTensorHandles(into address: UnsafeMutablePointer<CTensorHandle>?) { address!.initialize(to: handle._cTensorHandle) } public var _tensorHandles: [_AnyTensorHandle] { [self.handle.handle] } public init(_owning tensorHandles: UnsafePointer<CTensorHandle>?) { self.init(handle: TensorHandle(_owning: tensorHandles!.pointee)) } public init<C: RandomAccessCollection>( _handles: C ) where C.Element: _AnyTensorHandle { precondition(_handles.count == 1) self.init(handle: TensorHandle(handle: _handles[_handles.startIndex])) } } extension _TensorElementLiteral: TensorGroup { @inlinable public static var _unknownShapeList: [TensorShape?] { return [nil] } @inlinable public static var _typeList: [TensorDataType] { return [Scalar.tensorFlowDataType] } public var _tensorHandles: [_AnyTensorHandle] { tensor._tensorHandles } public func _unpackTensorHandles(into address: UnsafeMutablePointer<CTensorHandle>?) { tensor._unpackTensorHandles(into: address) } public init(_owning tensorHandles: UnsafePointer<CTensorHandle>?) { tensor = Tensor(_owning: tensorHandles) } public init<C: RandomAccessCollection>( _handles: C ) where C.Element: _AnyTensorHandle { tensor = Tensor(_handles: _handles) } } extension StringTensor: TensorGroup { @inlinable public static var _unknownShapeList: [TensorShape?] { return [nil] } @inlinable public static var _typeList: [TensorDataType] { return [String.tensorFlowDataType] } public func _unpackTensorHandles(into address: UnsafeMutablePointer<CTensorHandle>?) { address!.initialize(to: handle._cTensorHandle) } public var _tensorHandles: [_AnyTensorHandle] { [self.handle.handle] } public init(_owning tensorHandles: UnsafePointer<CTensorHandle>?) { self.init(handle: TensorHandle(_owning: tensorHandles!.pointee)) } public init<C: RandomAccessCollection>( _handles: C ) where C.Element: _AnyTensorHandle { precondition(_handles.count == 1) self.init(handle: TensorHandle(handle: _handles[_handles.startIndex])) } } extension Array: TensorArrayProtocol where Element: TensorGroup { public func _unpackTensorHandles(into address: UnsafeMutablePointer<CTensorHandle>?) { var ptr = address for elem in self { elem._unpackTensorHandles(into: ptr) ptr = ptr!.advanced(by: Int(elem._tensorHandleCount)) } } public var _tensorHandleCount: Int32 { return Element._tensorHandleCount * Int32(count) } public var _typeList: [TensorDataType] { return [TensorDataType]( [[TensorDataType]]( repeating: Element._typeList, count: Int(count) ).joined()) } public var _tensorHandles: ([_AnyTensorHandle]) { var result: [_AnyTensorHandle] = [] result.reserveCapacity(Int(self._tensorHandleCount)) for elem in self { result += elem._tensorHandles } return result } public init(_owning tensorHandles: UnsafePointer<CTensorHandle>?, count: Int) { let size = count / Int(Element._tensorHandleCount) self = Array( (0..<size).map { Element.init( _owning: tensorHandles?.advanced(by: $0 * Int(Element._tensorHandleCount))) }) } public init<C: RandomAccessCollection>( _handles: C ) where C.Element: _AnyTensorHandle { let size = _handles.count / Int(Element._tensorHandleCount) self = (0..<size).map { let start = _handles.index( _handles.startIndex, offsetBy: $0 * Int(Element._tensorHandleCount)) let end = _handles.index( start, offsetBy: Int(Element._tensorHandleCount)) return Element.init(_handles: _handles[start..<end]) } } } #if TENSORFLOW_USE_STANDARD_TOOLCHAIN @_spi(Reflection) import Swift func reflectionInit<T>(type: T.Type, body: (inout T, PartialKeyPath<T>) -> Void) -> T { guard #available(macOS 9999, *) else { fatalError("\(#function) is unavailable") } let x = UnsafeMutablePointer<T>.allocate(capacity: 1) defer { x.deallocate() } if !_forEachFieldWithKeyPath(of: type, body: { name, kp in body(&x.pointee, kp) return true }) { fatalError("Cannot initialize \(T.self) because of unknown fields.") } return x.move() } extension TensorGroup { public static var _typeList: [TensorDataType] { guard #available(macOS 9999, *) else { fatalError("\(#function) is unavailable") } var out = [TensorDataType]() if !(_forEachFieldWithKeyPath(of: Self.self) { name, kp in guard let valueType = type(of: kp).valueType as? TensorGroup.Type else { return false } out += valueType._typeList return true }) { fatalError("\(Self.self) does not have children that conform to TensorGroup.") } return out } public static func initialize<Root>( _ base: inout Root, _ kp: PartialKeyPath<Root>, _owning tensorHandles: UnsafePointer<CTensorHandle>? ) { guard let kp = kp as? WritableKeyPath<Root, Self> else { fatalError("\(kp) is not \(WritableKeyPath<Root, Self>.self)") } withUnsafeMutablePointer(to: &base[keyPath: kp]) { v in v.initialize(to: .init(_owning: tensorHandles)) } } public init(_owning tensorHandles: UnsafePointer<CTensorHandle>?) { var i = 0 self = reflectionInit(type: Self.self) { base, kp in guard let valueType = type(of: kp).valueType as? TensorGroup.Type else { fatalError("\(type(of: kp).valueType) does not conform to TensorGroup") } valueType.initialize(&base, kp, _owning: tensorHandles?.advanced(by: i)) i += Int(valueType._tensorHandleCount) } } public func _unpackTensorHandles(into address: UnsafeMutablePointer<CTensorHandle>?) { guard #available(macOS 9999, *) else { fatalError("\(#function) is unavailable") } var i = 0 if !_forEachFieldWithKeyPath(of: Self.self, body: { name, kp in guard let x = self[keyPath: kp] as? TensorGroup else { return false } x._unpackTensorHandles(into: address?.advanced(by: i)) i += Int(type(of: x)._tensorHandleCount) return true }) { fatalError("Cannot unpack \(Self.self) because of non-TensorGroup fields.") } } } #endif
apache-2.0
f4074a84a4d1f17e1ba7ef77c2821b8e
32.105012
100
0.694182
4.209712
false
false
false
false
fumitoito/yak
Pod/Classes/UIImage+toBase64.swift
1
2363
// // UIImage+toBase64.swift // Pods // // Created by 伊藤史 on 2016/02/04. // // import Foundation import UIKit extension UIImage { /** Translate this UIImage object to base64 encoded string. If failed to translate to JPEG, it will return nil value. If it returns nil, image has no CGImageRef or invalid bitmap format. - parameter compressionRatio: compression ratio for this UIImage - returns: base64 encoded string as JPEG */ public func yak_toBase64EncodedStringAsJPEG(compressionRatio: CGFloat = 1.0) -> String? { if let data = UIImageJPEGRepresentation(self, compressionRatio) { return (data.base64EncodedStringWithOptions(.EncodingEndLineWithLineFeed)) } return nil } /** Translate this UIImage object to base64 encoded URI. If failed to translate to JPEG, it will return nil value. If it returns nil, image has no CGImageRef or invalid bitmap format. - parameter compressionRatio: compression ratio for this UIImage - returns: base64 encoded URI as JPEG */ public func yak_toBase64EncodedURIAsJPEG(compressionRatio: CGFloat = 1.0) -> NSURL? { if let encodedString = yak_toBase64EncodedStringAsJPEG(compressionRatio) { return NSURL(string: "data:image/jpeg;base64,\(encodedString)") } return nil } /** Translate this UIImage object to base64 encoded string. If failed to translate to PNG, it will return nil value. If it returns nil, image has no CGImageRef or invalid bitmap format. - returns: base64 encoded string as PNG */ public func yak_toBase64EncodedStringAsPNG() -> String? { if let data = UIImagePNGRepresentation(self) { return (data.base64EncodedStringWithOptions(.EncodingEndLineWithLineFeed)) } return nil } /** Translate this UIImage object to base64 encoded URI. If failed to translate to PNG, it will return nil value. If it returns nil, image has no CGImageRef or invalid bitmap format. - returns: base64 encoded URI as PNG */ public func yak_toBase64EncodedURIAsPNG() -> NSURL? { if let encodedString = yak_toBase64EncodedStringAsPNG() { return NSURL(string: "data:image/png;base64,\(encodedString)") } return nil } }
mit
5fbe905c0dc33175e170b697aed1cb6a
30.851351
93
0.675435
4.585603
false
false
false
false
boyvanamstel/Picsojags-iOS
Picsojags/Models/Photo.swift
1
535
// // Photo.swift // Picsojags // // Created by Boy van Amstel on 19/02/2017. // Copyright © 2017 Danger Cove. All rights reserved. // import UIKit /// Photo model. struct Photo: Equatable { /// Squared photo URL to be used in a grid. fileprivate(set) var squaredPhotoURL: URL /// Larger size image URL to be used fullscreen. fileprivate(set) var fullPhotoURL: URL } func ==(lhs: Photo, rhs: Photo) -> Bool { return lhs.squaredPhotoURL == rhs.squaredPhotoURL && lhs.fullPhotoURL == rhs.fullPhotoURL }
mit
3e42e0e956c058c65bfac6c8bb95fa30
22.217391
93
0.674157
3.536424
false
false
false
false
RCacheaux/BitbucketKit
Carthage/Checkouts/Swinject/Tests/ContainerSpec.Arguments.swift
2
3830
// // ContainerSpec.Arguments.swift // Swinject // // Created by Yoichi Tagaya on 8/3/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import Quick import Nimble @testable import Swinject class ContainerSpec_Arguments: QuickSpec { override func spec() { var container: Container! beforeEach { container = Container() } it("accepts 1 argument.") { container.register(AnimalType.self) { _, arg1 in Cat(name: arg1) } let animal = container.resolve( AnimalType.self, argument: "1")! expect(animal.name) == "1" } it("accepts 2 arguments.") { container.register(AnimalType.self) { _, arg1, arg2 in Cat(name: arg1 + arg2) } let animal = container.resolve( AnimalType.self, arguments: ("1", "2"))! expect(animal.name) == "12" } it("accepts 3 arguments.") { container.register(AnimalType.self) { _, arg1, arg2, arg3 in Cat(name: arg1 + arg2 + arg3) } let animal = container.resolve( AnimalType.self, arguments: ("1", "2", "3"))! expect(animal.name) == "123" } it("accepts 4 arguments.") { container.register(AnimalType.self) { _, arg1, arg2, arg3, arg4 in Cat(name: arg1 + arg2 + arg3 + arg4) } let animal = container.resolve( AnimalType.self, arguments: ("1", "2", "3", "4"))! expect(animal.name) == "1234" } it("accepts 5 arguments.") { container.register(AnimalType.self) { _, arg1, arg2, arg3, arg4, arg5 in Cat(name: arg1 + arg2 + arg3 + arg4 + arg5) } let animal = container.resolve( AnimalType.self, arguments: ("1", "2", "3", "4", "5"))! expect(animal.name) == "12345" } it("accepts 6 arguments.") { container.register(AnimalType.self) { _, arg1, arg2, arg3, arg4, arg5, arg6 in Cat(name: arg1 + arg2 + arg3 + arg4 + arg5 + arg6) } let animal = container.resolve( AnimalType.self, arguments: ("1", "2", "3", "4", "5", "6"))! expect(animal.name) == "123456" } it("accepts 7 arguments.") { container.register(AnimalType.self) { _, arg1, arg2, arg3, arg4, arg5, arg6, arg7 in Cat(name: arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7) } let animal = container.resolve( AnimalType.self, arguments: ("1", "2", "3", "4", "5", "6", "7"))! expect(animal.name) == "1234567" } it("accepts 8 arguments.") { container.register(AnimalType.self) { _, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 in Cat(name: arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8) } let animal = container.resolve( AnimalType.self, arguments: ("1", "2", "3", "4", "5", "6", "7", "8"))! expect(animal.name) == "12345678" } it("accepts 9 arguments.") { container.register(AnimalType.self) { _, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 in Cat(name: arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9) } let animal = container.resolve( AnimalType.self, arguments: ("1", "2", "3", "4", "5", "6", "7", "8", "9"))! expect(animal.name) == "123456789" } } }
apache-2.0
fb26e6d39d7b92f4174da2db7645a059
36.539216
108
0.473492
3.817547
false
false
false
false
DSanzh/GuideMe-iOS
Pods/PageMenu/Classes/CAPSPageMenuConfiguration.swift
7
1591
// // CAPSPageMenuConfiguration.swift // PageMenuConfigurationDemo // // Created by Matthew York on 3/5/17. // Copyright © 2017 Aeron. All rights reserved. // import UIKit public class CAPSPageMenuConfiguration { open var menuHeight : CGFloat = 34.0 open var menuMargin : CGFloat = 15.0 open var menuItemWidth : CGFloat = 111.0 open var selectionIndicatorHeight : CGFloat = 3.0 open var scrollAnimationDurationOnMenuItemTap : Int = 500 // Millisecons open var selectionIndicatorColor : UIColor = UIColor.white open var selectedMenuItemLabelColor : UIColor = UIColor.white open var unselectedMenuItemLabelColor : UIColor = UIColor.lightGray open var scrollMenuBackgroundColor : UIColor = UIColor.black open var viewBackgroundColor : UIColor = UIColor.white open var bottomMenuHairlineColor : UIColor = UIColor.white open var menuItemSeparatorColor : UIColor = UIColor.lightGray open var menuItemFont : UIFont = UIFont.systemFont(ofSize: 15.0) open var menuItemSeparatorPercentageHeight : CGFloat = 0.2 open var menuItemSeparatorWidth : CGFloat = 0.5 open var menuItemSeparatorRoundEdges : Bool = false open var addBottomMenuHairline : Bool = true open var menuItemWidthBasedOnTitleTextWidth : Bool = false open var titleTextSizeBasedOnMenuItemWidth : Bool = false open var useMenuLikeSegmentedControl : Bool = false open var centerMenuItems : Bool = false open var enableHorizontalBounce : Bool = true open var hideTopMenuBar : Bool = false public init() { } }
mit
70b1a330d5d7cba2c7cdb786cfb55cfe
37.780488
76
0.735849
5.196078
false
true
false
false
prolificinteractive/Marker
Marker/Marker/Marker.swift
1
6200
// // Marker.swift // Marker // // Created by Htin Linn on 5/15/17. // Copyright © 2017 Prolific Interactive. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #elseif os(macOS) || os(OSX) import AppKit #endif /// Parses Markdown text and eturns formatted text as an attributed string with custom markup attributes applied. /// If the parsing failed, specified Markdown tags are ignored. Yet, the rest of the style information is still applied. /// /// - Parameters: /// - text: Text. /// - textStyle: Text style object containing style information. /// - markups: Markup information. /// - Returns: Formatted text. public func attributedMarkdownString(from markdownText: String, using textStyle: TextStyle) -> NSAttributedString { do { return try parsedMarkdownString(from: markdownText, using: textStyle) } catch { return NSAttributedString(string: markdownText, textStyle: textStyle) } } /// Parses custom mark up information and returns formatted text as an attributed string with custom markup attributes applied. /// If the parsing failed, custom markup attributes are ignored. Yet, style information from `textStyle` parameter is still applied. /// /// - Parameters: /// - text: Text. /// - textStyle: Text style object containing style information. /// - markups: Markup information. /// - Returns: Formatted text. public func attributedMarkupString(from text: String, using textStyle: TextStyle, customMarkup markups: Markup) -> NSAttributedString { do { return try parsedMarkupString(from: text, using: textStyle, customMarkup: markups) } catch { return NSAttributedString(string: text, textStyle: textStyle) } } /// Returns formatted Markdown text as an attributed string. /// /// - Parameters: /// - markdownText: String with Markdown tags. /// - textStyle: Text style object containing style information. /// - Returns: Formatted Markdown text. /// - Throws: Parser error. public func parsedMarkdownString(from markdownText: String, using textStyle: TextStyle) throws -> NSAttributedString { let (parsedString, elements) = try MarkdownParser.parse(markdownText) let attributedString = NSMutableAttributedString(string: textStyle.textTransform.applied(to: parsedString)) attributedString.addAttributes(textStyle.attributes, range: NSRange(location: 0, length: parsedString.count)) elements.forEach { (element) in var font: Font? = nil switch element { case .em: font = textStyle.emFont case .strong: font = textStyle.strongFont case .strikethrough(let range): if let strikethroughStyle = textStyle.strikethroughStyle { attributedString.addAttributes([AttributedStringKey.strikethroughStyle: strikethroughStyle.rawValue], range: NSRange(range, in: parsedString)) } if let strikethroughColor = textStyle.strikethroughColor { attributedString.addAttributes([AttributedStringKey.strikethroughColor: strikethroughColor], range: NSRange(range, in: parsedString)) } case .underline(let range): if let underlineStyle = textStyle.underlineStyle { attributedString.addAttributes([AttributedStringKey.underlineStyle: underlineStyle.rawValue], range: NSRange(range, in: parsedString)) } if let underlineColor = textStyle.underlineColor { attributedString.addAttributes([AttributedStringKey.underlineColor: underlineColor], range: NSRange(range, in: parsedString)) } case .link(let range, let urlString): attributedString.addAttribute(AttributedStringKey.link, value: urlString, range: NSRange(range, in: parsedString)) if let linkFont = textStyle.linkFont { attributedString.addAttribute(AttributedStringKey.font, value: linkFont, range: NSRange(range, in: parsedString)) } } if let font = font { attributedString.addAttributes([AttributedStringKey.font: font], range: NSRange(element.range, in: parsedString)) } } return attributedString } /// Returns formatted text as an attributed string with custom markup attributes applied. /// /// - Parameters: /// - text: Text. /// - textStyle: Text style object containing style information. /// - markups: Markup information. /// - Returns: Formatted text. /// - Throws: Parser error. public func parsedMarkupString(from text: String, using textStyle: TextStyle, customMarkup markups: Markup) throws -> NSAttributedString { guard markups.count > 0 else { return NSAttributedString(string: text, textStyle: textStyle) } let markupRules = Dictionary( uniqueKeysWithValues: markups.map { (key, value) in return (Rule(symbol: Symbol(character: key)), value) } ) let (parsedString, elements) = try ElementParser.parse(text, using: Array(markupRules.keys)) let attributedString = NSMutableAttributedString(string: textStyle.textTransform.applied(to: parsedString)) attributedString.addAttributes(textStyle.attributes, range: NSRange(location: 0, length: parsedString.count)) elements.forEach { (element) in if let markup = markupRules[element.rule] { attributedString.addAttributes(markup.attributes, range: NSRange(element.range, in: parsedString)) } } return attributedString }
mit
e90a96b31c115eee7420ff9c6d7e1227
41.458904
132
0.621068
5.423447
false
false
false
false
icylydia/PlayWithLeetCode
28. Implement strStr()/solution.swift
1
528
class Solution { func strStr(haystack: String, _ needle: String) -> Int { let lenHaystack = haystack.characters.count let lenNeedle = needle.characters.count if lenHaystack < lenNeedle { return -1 } for i in 0...(lenHaystack - lenNeedle) { let sub = haystack.substringWithRange( haystack.startIndex.advancedBy(i)..<haystack.startIndex.advancedBy(i+lenNeedle)) if sub == needle { return i } } return -1 } }
mit
7ce90a3660ad482cf09bb5701f57a6fe
30.117647
90
0.57197
4.258065
false
false
false
false
macc704/iKF
iKF/AppDelegate.swift
1
7653
// // AppDelegate.swift // iKF // // Created by Yoshiaki Matsuzawa on 2014-06-05. // Copyright (c) 2014 Yoshiaki Matsuzawa. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func getRootNavigationViewController() -> UINavigationController{ return window!.rootViewController as UINavigationController; } func getCurrentViewController() -> UIViewController{ return (window!.rootViewController as UINavigationController).visibleViewController; } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { let nav = UINavigationController(); nav.setNavigationBarHidden(true, animated: false); window!.rootViewController = nav; let loginController = KFLoginViewController(nibName: "KFLoginViewController", bundle: nil); self.getRootNavigationViewController().pushViewController(loginController, animated: false); return true; } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } func saveContext () { var error: NSError? = nil let managedObjectContext = self.managedObjectContext //if (managedObjectContext != nil) { if managedObjectContext.hasChanges && !managedObjectContext.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //println("Unresolved error \(error), \(error.userInfo)") abort() } //} } // #pragma mark - Core Data stack // Returns the managed object context for the application. // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application. var managedObjectContext: NSManagedObjectContext { if (_managedObjectContext != nil) { let coordinator = self.persistentStoreCoordinator //if (coordinator != nil) { _managedObjectContext = NSManagedObjectContext() _managedObjectContext!.persistentStoreCoordinator = coordinator //} } return _managedObjectContext! } var _managedObjectContext: NSManagedObjectContext? = nil // Returns the managed object model for the application. // If the model doesn't already exist, it is created from the application's model. var managedObjectModel: NSManagedObjectModel { if (_managedObjectModel != nil){ let modelURL = NSBundle.mainBundle().URLForResource("iKF", withExtension: "momd") _managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL!) } return _managedObjectModel! } var _managedObjectModel: NSManagedObjectModel? = nil // Returns the persistent store coordinator for the application. // If the coordinator doesn't already exist, it is created and the application's store added to it. var persistentStoreCoordinator: NSPersistentStoreCoordinator { if (_persistentStoreCoordinator != nil){ let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("iKF.sqlite") var error: NSError? = nil _persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. Typical reasons for an error here include: * The persistent store is not accessible; * The schema for the persistent store is incompatible with current managed object model. Check the error message to determine what the actual problem was. If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. If you encounter schema incompatibility errors during development, you can reduce their frequency by: * Simply deleting the existing store: NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil) * Performing automatic lightweight migration by passing the following dictionary as the options parameter: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true} Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. */ //println("Unresolved error \(error), \(error.userInfo)") abort() } } return _persistentStoreCoordinator! } var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil // #pragma mark - Application's Documents directory // Returns the URL to the application's Documents directory. var applicationDocumentsDirectory: NSURL { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.endIndex-1] as NSURL } }
gpl-2.0
e8f023d455a91d0a452e5c131cf1344a
50.362416
285
0.702992
6.132212
false
false
false
false
michaelrice/furry-octo-happiness
furry-octo-happiness/GameViewController.swift
1
2159
// // GameViewController.swift // furry-octo-happiness // // Created by Michael Rice on 7/1/15. // Copyright (c) 2015 Michael Rice. All rights reserved. // import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : NSString) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)! var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // Configure the view. let skView = self.view as SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
apache-2.0
b0d1bdfac46cd419cab2809c1f428700
30.289855
104
0.625753
5.535897
false
false
false
false
leo-lp/LPIM
LPIM/Common/Base/LPBaseNavigationController.swift
1
6264
// // LPBaseNavigationController.swift // LPIM // // Created by lipeng on 2017/6/16. // Copyright © 2017年 lipeng. All rights reserved. // import UIKit class LPBaseNavigationController: UINavigationController { fileprivate var panGestureRecognizer: UIPanGestureRecognizer? fileprivate var useClearBar = false override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //self.setNeedsStatusBarAppearanceUpdate() if useClearBar { navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() } else { navigationBar.setBackgroundImage(nil, for: .default) navigationBar.shadowImage = nil } } init(rootViewController: UIViewController, clearBar: Bool = false) { super.init(nibName: nil, bundle: nil) self.viewControllers = [rootViewController] useClearBar = clearBar } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { log.warning("release memory.") } override func viewDidLoad() { super.viewDidLoad() //// let barSize = self.navigationBar.frame.size //// var image = UIImage(named: "discoveer_top_title_bar") //// image = image?.reSizeImage(CGSize(width: barSize.width, height: barSize.height + 20)) //// self.navigationBar.barTintColor = UIColor(patternImage: image!) // // navigationBar.barTintColor = UIColor(hex6: kBackgroundColor, alpha: 1) // navigationBar.tintColor = UIColor.white // navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] // //UINavigationBar.appearance().tintColor = UIColor.white // //UINavigationBar.appearance().barTintColor = UIColor(hex6: kBackgroundColor) // //下面两句是去掉UINavigationBar的下边距黑线 // UINavigationBar.appearance().setBackgroundImage(UIImage(), for: UIBarMetrics.default) // UINavigationBar.appearance().shadowImage = UIImage() // navigationBar.isTranslucent = false // // /// 这个方法有2个弊端:1.如果上一个界面的title太长会把下一个界面的title挤到右边去;2.当app从后台进入页面会闪屏 // //let backButtonImage = UIImage(named: "btn_back_ico")?.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 30, 0, 0)) // //UIBarButtonItem.appearance().setBackButtonBackgroundImage(backButtonImage, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default) // //UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(CGFloat(NSInteger.min), CGFloat(NSInteger.min)), forBarMetrics: UIBarMetrics.Default) // 设置滑动返回手势 setupPanGestureRecognizer() } // override func preferredStatusBarStyle() -> UIStatusBarStyle { // return UIStatusBarStyle.LightContent // } override func pushViewController(_ viewController: UIViewController, animated: Bool) { // 这时push进来的控制器viewController,不是第一个子控制器(不是根控制器) if viewControllers.count > 0 { // 自动显示和隐藏tabbar viewController.hidesBottomBarWhenPushed = true /// 设置导航栏上面的内容 // 设置左边的返回按钮 let menItem = UIBarButtonItem(image: UIImage(named: "back_nav_gray"), style: UIBarButtonItemStyle.done, target: self, action: #selector(back)) // 使用弹簧控件缩小菜单按钮和边缘距离 let spaceItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: self, action: nil) spaceItem.width = -5 viewController.navigationItem.leftBarButtonItems = [spaceItem, menItem] } super.pushViewController(viewController, animated: animated) } func back() { /// 因为self本来就是一个导航控制器,self.navigationController这里是nil的 popViewController(animated: true) } func enabledGestureRecognizer(_ enable: Bool) { panGestureRecognizer?.isEnabled = enable } } // MARK: - Private extension LPBaseNavigationController { fileprivate func setupPanGestureRecognizer() { // 获取系统自带滑动手势的target对象 if let target = interactivePopGestureRecognizer?.delegate { let action = NSSelectorFromString("handleNavigationTransition:") // 创建全屏滑动手势,调用系统自带滑动手势的target的action方法 let pan = UIPanGestureRecognizer(target: target, action: action) // 设置手势代理,拦截手势触发 pan.delegate = self // 给导航控制器的view添加全屏滑动手势 view.addGestureRecognizer(pan) // 禁止使用系统自带的滑动手势 interactivePopGestureRecognizer?.isEnabled = false panGestureRecognizer = pan } } } // MARK: - Delegate extension LPBaseNavigationController: UIGestureRecognizerDelegate { /// 什么时候调用:每次触发手势之前都会询问下代理,是否触发。 /// 作用:拦截手势触发 /// /// - Parameter gestureRecognizer: 手势识别器 /// - Returns: 标志是否禁用了当前手势识别器 func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { // 注意:只有非根控制器才有滑动返回功能,根控制器没有。 // 判断导航控制器是否只有一个子控制器,如果只有一个子控制器,肯定是根控制器 if childViewControllers.count == 1 { return false // 表示用户在根控制器界面,就不需要触发滑动手势, } if let pan = gestureRecognizer as? UIPanGestureRecognizer { let translationX = pan.translation(in: view).x return translationX > 0 } return true } }
mit
3f53876d104446a3b919c3f6b133698c
34.850649
176
0.649339
4.767703
false
false
false
false
RajatDhasmana/rajat_appinventiv
ProfileViewAgain/ProfileViewAgain/ProfileVC.swift
1
3779
// // ProfileVC.swift // ProfileViewAgain // // Created by Mohd Sultan on 08/02/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit class ProfileVC: UIViewController { @IBOutlet weak var profileTableView: UITableView! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! let data = [ ["titlename":"Full Name" , "titledetail":"Rajat Dhasmana"], ["titlename":"E-mail" , "titledetail":"[email protected]"], ["titlename":"Password" , "titledetail":"rajat1234"], ["titlename":"Height" , "titledetail":"5'10"], ["titlename":"Weight" , "titledetail":"68"], ["titlename":"Date Of Birth" , "titledetail":"5th june, 1995"] ] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.profileTableView.dataSource = self self.profileTableView.delegate = self let cellNib1 = UINib(nibName: "ButtonCell", bundle: nil) profileTableView.register(cellNib1, forCellReuseIdentifier: "ButtonCellID") let cellNib2 = UINib(nibName: "ProfileDetailCellTableViewCell", bundle: nil) profileTableView.register(cellNib2, forCellReuseIdentifier:"ProfileDetailCellID" ) let cellNib3 = UINib(nibName: "UpperCell", bundle: nil) profileTableView.register(cellNib3, forCellReuseIdentifier: "UpperCellID") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(forName: .UIKeyboardDidShow, object: nil, queue: OperationQueue.main, using: {(Notification) -> Void in guard let userinfo = Notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else{ return } let keyboardHeight = userinfo.cgRectValue.height self.bottomConstraint.constant = keyboardHeight }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ProfileVC : UITableViewDataSource , UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count + 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.row { case 0: let uppercell = tableView.dequeueReusableCell(withIdentifier: "UpperCellID") as! UpperCell return uppercell case 7: let buttoncell = tableView.dequeueReusableCell(withIdentifier: "ButtonCellID") as! ButtonCell return buttoncell default : let profiledetailcell = tableView.dequeueReusableCell(withIdentifier: "ProfileDetailCellID") as! ProfileDetailCellTableViewCell profiledetailcell.configureCell( data[indexPath.row - 1]) return profiledetailcell } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.row { case 0 : return 272 case 7 : return 160 default : return 100 } } }
mit
2db94578cc4b436e155d41edf90edd70
28.984127
150
0.575966
5.681203
false
false
false
false
claesjacobsson/ColorPinAnnotationView
ColorPinAnnotationView.swift
1
2190
// // ColorPinAnnotationView.swift // ColorPinAnnotationView // // Created by Daniel Saidi on 2015-08-18. // Copyright (c) 2015 Daniel Saidi. All rights reserved. // /* If you use this view instead of the MKPinAnnotationView class, you can set any UIColor as the pinColor, instead of the three MKPinAnnotationViewColor values. Other than that, this class looks a little different if compared to the default MKPinAnnotationView. It lacks a shadow and has a cleaner pin hole. */ import UIKit import MapKit import CoreGraphics public class ColorPinAnnotationView: MKAnnotationView { public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) update() } public override init(frame: CGRect) { super.init(frame: frame) update() } public override init!(annotation: MKAnnotation!, reuseIdentifier: String!) { super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) update() } public var pinColor = UIColor.redColor() { didSet { update() } } public var animatesDrop = true func animateDropWithDuration(duration: Double) { let viewFrame = frame frame = CGRectOffset(viewFrame, 0, -500) UIView.animateWithDuration(duration, animations: { self.frame = viewFrame }) } private func update() { canShowCallout = true for view in subviews { view.removeFromSuperview() } let bundle = NSBundle(forClass: object_getClass(ColorPinAnnotationView)) let body = UIImage(named: "ColorPinBody", inBundle: bundle, compatibleWithTraitCollection: nil) let head = UIImage(named: "ColorPinHead", inBundle: bundle, compatibleWithTraitCollection: nil) let coloredHead = head!.imageByTintingWithColor(pinColor, andBlendMode: kCGBlendModeScreen) let offset = 0.5 * body!.size.height - 2 centerOffset = CGPoint(x: 0, y: -offset) image = body let headView = UIImageView(image: coloredHead) addSubview(headView) } }
mit
f510edae15852e481c74c9a9c813a589
27.076923
103
0.645205
4.910314
false
false
false
false
kNeerajPro/EcommerceApp
ECommerceApp/Entities/Cart.swift
1
1832
// // Cart.swift // ECommerceApp // // Created by Neeraj Kumar on 19/12/14. // Copyright (c) 2014 Neeraj Kumar. All rights reserved. // // TODO:Timer in Cart. import UIKit private let _sharedInstance = Cart() class Cart: NSObject { var products:ProductCollection = ProductCollection() var cartTimer:Timer? class var sharedInstance : Cart { return _sharedInstance } func addProduct(product:Product) { Cart.sharedInstance.products.insert(product) // If a product is added then invalidate previous cart timer and create a new one. let isTimerValid:Bool? = self.cartTimer?.isValidTimer() if let uwIsTimerValid = isTimerValid { self.cartTimer?.invalidate() } self.cartTimer = Timer(timerInterval: 120.0, repeat:false) } func deleteProduct(product:Product) { Cart.sharedInstance.products.removeProduct(product) if (Cart.sharedInstance.products.productCount() == 0) { self.cartTimer?.invalidate() } } func deleteProductAtIndex(index:Int) { Cart.sharedInstance.products.removeAtIndex(index) if (Cart.sharedInstance.products.productCount() == 0) { self.cartTimer?.invalidate() } } func productAtIndex(index:Int) ->Product? { return self.products.productAtIndex(index) } func totalPrice() -> Double { var totalPrice:Double = 0.0 for product in Cart.sharedInstance.products { totalPrice += product.price } return totalPrice } func productsCount() -> Int { return Cart.sharedInstance.products.productCount() } } extension Cart:Printable { override var description: String { return "products:\(self.products)" } }
mit
b78554ec3ffa78ec2d88289c9fbcbe97
25.171429
90
0.629367
4.361905
false
false
false
false
artursDerkintis/Starfly
Starfly/SFTab.swift
1
10985
// // SFTab.swift // Starfly // // Created by Arturs Derkintis on 9/14/15. // Copyright © 2015 Starfly. All rights reserved. // import UIKit class SFTab: SFView { var label : UILabel? var icon : UIImageView? var closeTabButton : UIButton? var overLayer : CALayer? var loadingIndicator : CALayer? var id : Double = 0 var controllerDelegate : SFTabsControllerDelegate? var webViewController : SFWebController?{ didSet{ self.setUpObservers() } } let replicatorLayer = CAReplicatorLayer() override init(frame: CGRect) { super.init(frame: frame) layer.cornerRadius = frame.height * 0.5 layer.shadowColor = UIColor.blackColor().colorWithAlphaComponent(0.5).CGColor layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowRadius = 2 layer.borderColor = UIColor.lightGrayColor().CGColor layer.shadowOpacity = 1.0 layer.rasterizationScale = UIScreen.mainScreen().scale layer.shouldRasterize = true overLayer = CALayer() overLayer?.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.1).CGColor layer.addSublayer(overLayer!) icon = UIImageView(frame: .zero) icon?.layer.cornerRadius = 15 * 0.5 icon?.center = CGPoint(x: icon!.frame.height * 1.05, y: frame.height * 0.5) icon?.backgroundColor = lighterColorForColor(currentColor!, index: -0.2) icon?.image = UIImage(named: "g") icon?.layer.masksToBounds = true addSubviewSafe(icon) icon?.snp_makeConstraints(closure: {(make) -> Void in make.left.equalTo(10) make.centerY.equalTo(snp_centerY) make.width.height.equalTo(15) }) label = UILabel(frame: .zero) label!.text = "Loading..." label?.font = UIFont.systemFontOfSize(13, weight: UIFontWeightMedium) label?.textColor = UIColor.whiteColor() label!.layer.shadowColor = UIColor.blackColor().colorWithAlphaComponent(0.5).CGColor label!.layer.shadowOffset = CGSize(width: 0, height: lineWidth()) label!.layer.shadowRadius = 0 label!.layer.shadowOpacity = 1.0 label!.layer.rasterizationScale = UIScreen.mainScreen().scale label!.layer.shouldRasterize = true addSubviewSafe(label) closeTabButton = UIButton(type: UIButtonType.Custom) closeTabButton?.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin closeTabButton?.setImage(UIImage(named: Images.closeTab), forState: UIControlState.Normal) closeTabButton?.setImage(UIImage(named: Images.closeTab)?.imageWithColor(UIColor.lightGrayColor()), forState: UIControlState.Highlighted) closeTabButton?.imageView?.snp_makeConstraints(closure: {(make) -> Void in make.height.width.equalTo(13) make.center.equalTo(closeTabButton!) }) closeTabButton?.addTarget(self, action: "closeTab", forControlEvents: UIControlEvents.TouchDown) addSubviewSafe(closeTabButton) closeTabButton?.snp_makeConstraints(closure: {(make) -> Void in make.right.equalTo(0) make.height.width.equalTo(self.snp_height) make.centerY.equalTo(snp_centerY) }) createLoadingIndicator() showIndicator(on : true) let tap = UITapGestureRecognizer(target: self, action: "selectThisTab") self.addGestureRecognizer(tap) let doubleTap = UITapGestureRecognizer(target: self, action: "closeTab") doubleTap.numberOfTapsRequired = 2 self.addGestureRecognizer(doubleTap) label?.snp_makeConstraints(closure: {(make) -> Void in make.top.bottom.equalTo(0) make.left.equalTo(30) make.right.equalTo(closeTabButton!.snp_left).offset(10) }) } //Observers func setUpObservers() { if let web = webViewController?.webView { web.addObserver(self, forKeyPath: "title", options: NSKeyValueObservingOptions.New, context: nil) web.addObserver(self, forKeyPath: "loading", options: NSKeyValueObservingOptions.New, context: nil) webViewController?.addObserver(self, forKeyPath: "favicon", options: NSKeyValueObservingOptions.New, context: nil) } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "title" { label?.text = webViewController?.webView?.title } if keyPath == "loading" { showIndicator(on: webViewController?.webView?.loading) } if keyPath == "favicon" { icon?.image = webViewController?.favicon } } deinit { if let web = webViewController?.webView { web.removeObserver(self, forKeyPath: "title") web.removeObserver(self, forKeyPath: "loading") webViewController?.removeObserver(self, forKeyPath: "favicon") } } override func layoutSubviews() { super.layoutSubviews() overLayer?.frame = layer.bounds overLayer?.cornerRadius = frame.height * 0.5 layer.cornerRadius = frame.height * 0.5 replicatorLayer.frame.size = CGSize(width: 15, height: 15) replicatorLayer.position = CGPoint(x: 17.5, y: frame.height * 0.5) } func selectThisTab() { controllerDelegate?.selectTab(self.id) } //Closes this tab func closeTab() { controllerDelegate?.removeTabWithId(self.id) } //Incrase Touch area override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { if CGRectContainsPoint(CGRectInset(self.bounds, -10, -5), point) { return true } return false } //Selection and Unselection Animations var selected : Bool = false { didSet { if selected != oldValue { if selected == false { let basicAnim0 = CABasicAnimation(keyPath: "backgroundColor") basicAnim0.fromValue = UIColor.clearColor().CGColor basicAnim0.toValue = UIColor.lightGrayColor().colorWithAlphaComponent(0.4).CGColor basicAnim0.duration = 0.2 basicAnim0.fillMode = kCAFillModeForwards basicAnim0.removedOnCompletion = false overLayer!.addAnimation(basicAnim0, forKey: "shadow24") let basicAnim = CABasicAnimation(keyPath: "shadowRadius") basicAnim.fromValue = 2 basicAnim.toValue = 0.5 basicAnim.duration = 0.2 basicAnim.fillMode = kCAFillModeForwards basicAnim.removedOnCompletion = false layer.addAnimation(basicAnim, forKey: "shadow") let basicAnim2 = CABasicAnimation(keyPath: "borderWidth") basicAnim2.fromValue = 0 basicAnim2.toValue = lineWidth() basicAnim2.duration = 0.2 basicAnim2.fillMode = kCAFillModeForwards basicAnim2.removedOnCompletion = false layer.addAnimation(basicAnim2, forKey: "shadows") let basicAnim1 = CABasicAnimation(keyPath: "shadowColor") basicAnim1.fromValue = UIColor.blackColor().colorWithAlphaComponent(0.5).CGColor basicAnim1.toValue = UIColor.blackColor().colorWithAlphaComponent(0.0).CGColor basicAnim1.duration = 0.2 basicAnim1.fillMode = kCAFillModeForwards basicAnim1.removedOnCompletion = false layer.addAnimation(basicAnim1, forKey: "shadow2") } else { let basicAnim0 = CABasicAnimation(keyPath: "backgroundColor") basicAnim0.fromValue = UIColor.lightGrayColor().colorWithAlphaComponent(0.4).CGColor basicAnim0.toValue = UIColor.clearColor().CGColor basicAnim0.duration = 0.2 basicAnim0.fillMode = kCAFillModeForwards basicAnim0.removedOnCompletion = false overLayer!.addAnimation(basicAnim0, forKey: "shadow24") let basicAnim2 = CABasicAnimation(keyPath: "borderWidth") basicAnim2.fromValue = lineWidth() basicAnim2.toValue = 0 basicAnim2.duration = 0.2 basicAnim2.fillMode = kCAFillModeForwards basicAnim2.removedOnCompletion = false layer.addAnimation(basicAnim2, forKey: "shadows") let basicAnim = CABasicAnimation(keyPath: "shadowRadius") basicAnim.fromValue = 0.5 basicAnim.toValue = 2 basicAnim.duration = 0.2 basicAnim.fillMode = kCAFillModeForwards basicAnim.removedOnCompletion = false layer.addAnimation(basicAnim, forKey: "shadow") let basicAnim1 = CABasicAnimation(keyPath: "shadowColor") basicAnim1.fromValue = UIColor.blackColor().colorWithAlphaComponent(0.1).CGColor basicAnim1.toValue = UIColor.blackColor().colorWithAlphaComponent(0.5).CGColor basicAnim1.duration = 0.2 basicAnim1.fillMode = kCAFillModeForwards basicAnim1.removedOnCompletion = false layer.addAnimation(basicAnim1, forKey: "shadow2") }} } } //Show/Hide Spinner Loading indicator func showIndicator(on on : Bool?) { if let on = on { let basicAnim = CABasicAnimation(keyPath: "opacity") basicAnim.fromValue = on ? 0.0 : 1.0 basicAnim.toValue = on ? 1.0 : 0.0 basicAnim.duration = 0.6 basicAnim.fillMode = kCAFillModeForwards basicAnim.removedOnCompletion = false self.loadingIndicator?.addAnimation(basicAnim, forKey: "animate") } } func createLoadingIndicator() { replicatorLayer.frame = CGRectInset(icon!.frame, -1, -1) replicatorLayer.instanceCount = 15 replicatorLayer.instanceDelay = CFTimeInterval(1 / 15.0) replicatorLayer.preservesDepth = true replicatorLayer.instanceColor = UIColor.whiteColor().CGColor replicatorLayer.instanceRedOffset = 0.0 replicatorLayer.instanceGreenOffset = 0.0 replicatorLayer.instanceBlueOffset = 0.0 replicatorLayer.instanceAlphaOffset = 0.0 let angle = Float(M_PI * 2.0) / 15 replicatorLayer.instanceTransform = CATransform3DMakeRotation(CGFloat(angle), 0.0, 0.0, 1.0) layer.addSublayer(replicatorLayer) loadingIndicator = replicatorLayer loadingIndicator?.opacity = 0.0 let rotAtStart : Float? = loadingIndicator?.valueForKey("transform.rotation") as? Float let rotTrans = CATransform3DRotate(loadingIndicator!.transform, -CGFloat(M_PI * 2), 0.0, 0.0, 1.0) loadingIndicator?.transform = rotTrans let rotation = CABasicAnimation(keyPath: "transform.rotation") rotation.duration = 15.0 rotation.fromValue = rotAtStart rotation.toValue = -Float(M_PI * 2) rotation.repeatCount = Float.infinity loadingIndicator?.addAnimation(rotation, forKey: "e") let instanceLayer = CALayer() let layerWidth: CGFloat = 2.0 instanceLayer.cornerRadius = 1.0 let midX = CGRectGetMidX(icon!.frame) - layerWidth / 2.0 instanceLayer.frame = CGRect(x: midX, y: 0.0, width: layerWidth, height: layerWidth * 3.0) instanceLayer.backgroundColor = UIColor.whiteColor().CGColor replicatorLayer.addSublayer(instanceLayer) let fadeAnimation = CABasicAnimation(keyPath: "opacity") fadeAnimation.fromValue = 1.0 fadeAnimation.toValue = 0.0 fadeAnimation.duration = 1 fadeAnimation.repeatCount = Float(Int.max) instanceLayer.opacity = 0.0 instanceLayer.addAnimation(fadeAnimation, forKey: "FadeAnimation") instanceLayer.rasterizationScale = UIScreen.mainScreen().scale instanceLayer.shouldRasterize = true } func destroy() { UIView.animateWithDuration(0.3, animations: {() -> Void in self.center = CGPoint(x: self.center.x, y: self.center.y - 50) }) {(fin) -> Void in self.removeFromSuperview() self.webViewController?.view.removeFromSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
0d9fcb2bc36ebea46cd62efac259e171
33.869841
154
0.731336
3.885391
false
false
false
false
jwfriese/FrequentFlyer
FrequentFlyerTests/Builds/ModelBuilder/BuildBuilder.swift
1
2016
@testable import FrequentFlyer class BuildBuilder { private var nextId = 1 private var nextName = "name" private var nextTeamName = "teamName" private var nextJobName = "jobName" private var nextStatus = BuildStatus.pending private var nextPipelineName = "pipelineName" private var nextStartTime: UInt? = UInt(50) private var nextEndTime: UInt? = UInt(100) private func reset() { nextId = 1 nextName = "name" nextTeamName = "teamName" nextJobName = "jobName" nextStatus = BuildStatus.pending nextPipelineName = "pipelineName" nextStartTime = UInt(50) nextEndTime = UInt(100) } init() { reset() } func build() -> Build { let build = Build( id: nextId, name: nextName, teamName: nextTeamName, jobName: nextJobName, status: nextStatus, pipelineName: nextPipelineName, startTime: nextStartTime, endTime: nextEndTime ) reset() return build } func withId(_ id: Int) -> BuildBuilder { nextId = id return self } func withName(_ name: String) -> BuildBuilder { nextName = name return self } func withTeamName(_ teamName: String) -> BuildBuilder { nextTeamName = teamName return self } func withJobName(_ jobName: String) -> BuildBuilder { nextJobName = jobName return self } func withStatus(_ status: BuildStatus) -> BuildBuilder { nextStatus = status return self } func withPipelineName(_ pipelineName: String) -> BuildBuilder { nextPipelineName = pipelineName return self } func withStartTime(_ startTime: UInt?) -> BuildBuilder { nextStartTime = startTime return self } func withEndTime(_ endTime: UInt?) -> BuildBuilder { nextEndTime = endTime return self } }
apache-2.0
d7b6b3f0517bab2dc1a2f7bfc1a4da74
23.289157
67
0.585317
4.788599
false
false
false
false
Jamol/Nutil
Sources/http/v2/H2ConnectionMgr.swift
1
2240
// // H2ConnectionMgr.swift // Nutil // // Created by Jamol Bao on 12/25/16. // Copyright © 2016 Jamol Bao. All rights reserved. // Contact: [email protected] // import Foundation final class H2ConnectionMgr { fileprivate var connMap: [String : H2Connection] = [:] private init() { } func addConnection(_ key: String, _ conn: H2Connection) { objc_sync_enter(self) defer { objc_sync_exit(self) } connMap[key] = conn } func getConnection(_ key: String) -> H2Connection? { objc_sync_enter(self) defer { objc_sync_exit(self) } return connMap[key] } func getConnection(_ host: String, _ port: Int, _ sslFlags: UInt32) -> H2Connection? { var ss_addr = sockaddr_storage() var hints = addrinfo( ai_flags: AI_ADDRCONFIG, ai_family: AF_UNSPEC, ai_socktype: SOCK_STREAM, ai_protocol: 0, ai_addrlen: 0, ai_canonname: nil, ai_addr: nil, ai_next: nil) if getAddrInfo(host, port, &hints, &ss_addr) != 0 { errTrace("getConnection, failed to get addr info, host=\(host)") return nil } let info = getNameInfo(&ss_addr) let connKey = "\(info.addr):\(info.port)" objc_sync_enter(self) defer { objc_sync_exit(self) } var conn = connMap[connKey] if conn != nil { return conn } conn = H2Connection() conn!.setConnectionKey(connKey) conn!.setSslFlags(sslFlags) if conn!.connect(host, port) != .noError { return nil } connMap[connKey] = conn! return conn } func removeConnection(_ key: String) { objc_sync_enter(self) defer { objc_sync_exit(self) } connMap.removeValue(forKey: key) } class func getRequestConnMgr(_ secure: Bool) -> H2ConnectionMgr { if secure { return sharedSecure } else { return sharedNormal } } static let sharedNormal: H2ConnectionMgr = H2ConnectionMgr() static let sharedSecure: H2ConnectionMgr = H2ConnectionMgr() }
mit
18b05b3f927664a903b2bdb359d590b6
26.641975
90
0.552032
3.873702
false
false
false
false
Fenrikur/ef-app_ios
Domain Model/EurofurenceModel/Public/System Services/Network/URLSessionBasedJSONSession.swift
1
2283
import Foundation public struct URLSessionBasedJSONSession: JSONSession { public static let shared = URLSessionBasedJSONSession() private let session: URLSession private static let userAgent: String? = { return Bundle.main.infoDictionary.let { (info) -> String in let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" let osNameVersion: String = { let version = ProcessInfo.processInfo.operatingSystemVersion let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" return "iOS \(versionString)" }() return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion))" } }() public init(session: URLSession = .shared) { self.session = session } public func get(_ request: JSONRequest, completionHandler: @escaping (Data?, Error?) -> Void) { perform(request, method: "GET", completionHandler: completionHandler) } public func post(_ request: JSONRequest, completionHandler: @escaping (Data?, Error?) -> Void) { perform(request, method: "POST", completionHandler: completionHandler) } private func perform(_ request: JSONRequest, method: String, completionHandler: @escaping (Data?, Error?) -> Void) { guard let actualURL = URL(string: request.url) else { return } var urlRequest = URLRequest(url: actualURL) urlRequest.setValue(type(of: self).userAgent, forHTTPHeaderField: "User-Agent") urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") urlRequest.httpMethod = method urlRequest.httpBody = request.body urlRequest.allHTTPHeaderFields = request.headers session.dataTask(with: urlRequest, completionHandler: { (data, _, error) in DispatchQueue.main.async { completionHandler(data, error) } }).resume() } }
mit
091cc8c3071eb4df620269d8f75365f9
39.767857
120
0.650898
5.200456
false
false
false
false
rocketmade/rockauth-ios
RockauthiOS/Providers/GoogleProvider.swift
1
1796
// // GoogleProvider.swift // Pods // // Created by Daniel Gubler on 11/3/15. // // import UIKit public protocol ConnectWithGoogleDelegate { func googleButtonClicked() } public class GoogleProvider: SocialProvider { public static var sharedProvider: SocialProvider? = GoogleProvider() public var token: String? public var name: String = "google_plus" public var secret: String? = nil public var userName: String? = nil public var email: String? = nil public var firstName: String? = nil public var lastName: String? = nil public var iconName: String? = "googleicon" public var color = UIColor(colorLiteralRed: 220/255.0, green: 78/255.0, blue: 65/255.0, alpha: 1.0) public var prettyName: String = "Google" public var delegate: ConnectWithGoogleDelegate? public init() { } //WARNING: This doesn't make sense becus the success block will never be called public func login(fromViewController viewController: UIViewController, success: loginSuccess, failure: loginFailure) { if let delegate = self.delegate { delegate.googleButtonClicked() } else { let e = RockauthError(title: "Connect With Google Delegate not found", message: "You must set the ConnectWithGoogleDelegate") failure(error: e) } } public func connect(fromViewController viewController: UIViewController, success: loginSuccess, failure: loginFailure) { if let sharedClient = RockauthClient.sharedClient { sharedClient.login(self, success: success, failure: failure) } } public func logout() { // This is how to logout. Must be done in app for now, since Google is a static framework // GIDSignIn.sharedInstance().signOut() } }
mit
6b095f200650b8f4d0123989b2db228e
32.90566
137
0.680958
4.423645
false
false
false
false
Drusy/auvergne-webcams-ios
AuvergneWebcams/AnalyticsManager.swift
1
4960
// // AnalyticsManager.swift // AuvergneWebcams // // Created by Drusy on 21/02/2017. // // import UIKit import FirebaseAnalytics import SwiftyUserDefaults import Crashlytics class AnalyticsManager { // MARK: - Private fileprivate static func logEvent(withName name: String, parameters: [String: NSObject]?) { #if !DEBUG Analytics.logEvent(name, parameters: parameters) Answers.logContentView(withName: name, contentType: parameters?[AnalyticsParameterContentType] as? String, contentId: parameters?[AnalyticsParameterItemID] as? String, customAttributes: nil) #endif } fileprivate static func logShare(withName name: String, forType type: String) { #if !DEBUG Answers.logShare(withMethod: type, contentName: name, contentType: nil, contentId: nil, customAttributes: nil) let parameters = [ AnalyticsParameterItemID: name as NSObject, AnalyticsParameterContentType: type as NSObject ] Analytics.logEvent(AnalyticsEventShare, parameters: parameters) #endif } fileprivate static func logSearch(withText text: String) { #if !DEBUG Answers.logSearch(withQuery: text, customAttributes: nil) let parameters = [ AnalyticsParameterSearchTerm: text as NSObject ] Analytics.logEvent(AnalyticsEventSearch, parameters: parameters) #endif } // MARK: - Events static func logEvent(shareName name: String, forType type: String) { AnalyticsManager.logShare(withName: name, forType: type) } static func logEvent(searchText text: String) { AnalyticsManager.logSearch(withText: text) } static func logEvent(showSection section: WebcamSection) { guard let sectionName = section.title else { return } let parameters = [ AnalyticsParameterItemCategory: sectionName as NSObject ] AnalyticsManager.logEvent(withName: AnalyticsEventViewItemList, parameters: parameters) } static func logEvent(showWebcam webcam: Webcam) { guard let webcamName = webcam.title else { return } let parameters = [ AnalyticsParameterContentType: "webcam" as NSObject, AnalyticsParameterItemID: webcamName as NSObject ] AnalyticsManager.logEvent(withName: AnalyticsEventSelectContent, parameters: parameters) } static func logEvent(screenName screen: String) { let parameters = [ AnalyticsParameterContentType: "screen" as NSObject, AnalyticsParameterItemID: screen as NSObject ] AnalyticsManager.logEvent(withName: AnalyticsEventSelectContent, parameters: parameters) } static func logEvent(set webcam: Webcam, asFavorite favorite: Bool) { guard let webcamName = webcam.title else { return } let contentType = favorite ? "favorite" : "unfavorite" let parameters = [ AnalyticsParameterContentType: contentType as NSObject, AnalyticsParameterItemID: webcamName as NSObject ] AnalyticsManager.logEvent(withName: "favorite", parameters: parameters) } static func logEvent(button: String) { let parameters = [ AnalyticsParameterContentType: "button" as NSObject, AnalyticsParameterItemID: button as NSObject ] AnalyticsManager.logEvent(withName: AnalyticsEventSelectContent, parameters: parameters) } static func logEventAppOpen() { AnalyticsManager.logEvent(withName: AnalyticsEventAppOpen, parameters: nil) } // MARK: - User Properties static func logUserProperties() { #if !DEBUG let refresh = Defaults[.shouldAutorefresh] ? "true" : "false" let refreshInterval = String(format: "%d", Defaults[.autorefreshInterval]) let quality = Defaults[.prefersHighQuality] ? "high" : "low" Analytics.setUserProperty(refresh, forName: Analytics.refreshUserProperty) Analytics.setUserProperty(refreshInterval, forName: Analytics.refreshIntervalUserProperty) Analytics.setUserProperty(quality, forName: Analytics.webcamQualityUserProperty) #endif } }
apache-2.0
529a1f0add6d7a79959441a5da439697
34.942029
102
0.585282
5.807963
false
false
false
false
alexktchen/ExchangeRate
Core/Services/LoadCountryDataService.swift
1
2238
// // loadCountryData.swift // ExchangeRate // // Created by Alex Chen on 2015/10/3. // Copyright © 2015 AlexChen. All rights reserved. // import Foundation public class LoadCountryDataService: NSData { public class var sharedInstance: LoadCountryDataService { struct Singleton { static let instance = LoadCountryDataService() } return Singleton.instance } public var allCurrencys: Array<Currency> = Array<Currency>() override init() { super.init() if let items = UserDefaultDataService.sharedInstance.getMainCurrencysData() { allCurrencys = items } else { loadCountry() } } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } public func saveMainCountry() { UserDefaultDataService.sharedInstance.removeMainCurrencysData() UserDefaultDataService.sharedInstance.setMainCurrencysData(self.allCurrencys) } func loadCountry() { for country in CurrencyMap.country { let isoCode = country.0 let countryName = country.1 let imageName = ("\(isoCode)_\(countryName)") let currency = Currency() let largeImageName = "\(imageName)_large" currency.flagImageName = imageName currency.largeFlagImageName = largeImageName currency.flagImage = UIImage(named: imageName)! currency.largeFlagImage = UIImage(named: largeImageName)! if let symbol = NSLocale.localesCurrencySymbol(country.0) { currency.symbol = symbol } if let currencyCode = NSLocale.localesCurrencyCode(country.0) { currency.currencyCode = currencyCode } if let displayName = NSLocale.locales(country.0) { currency.displayName = displayName } if isoCode == "TW" { currency.isMajor = true } else { currency.isMajor = false } allCurrencys.append(currency) } allCurrencys.sortInPlace({ $0.displayName < $1.displayName }) saveMainCountry() } }
mit
d8a2c43271ab065e1e841a6be579e507
26.9625
85
0.600805
5.038288
false
false
false
false
tdquang/CarlWrite
CVCalendar/CVCalendarMenuView.swift
1
3459
// // CVCalendarMenuView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit class CVCalendarMenuView: UIView { var symbols = [String]() var symbolViews: [UILabel]? var firstWeekday: Weekday { get { if let delegate = delegate { return delegate.firstWeekday() } else { return .Sunday } } } @IBOutlet weak var menuViewDelegate: AnyObject? { set { if let delegate = newValue as? MenuViewDelegate { self.delegate = delegate } } get { return delegate as? AnyObject } } var delegate: MenuViewDelegate? { didSet { setupWeekdaySymbols() createDaySymbols() } } init() { super.init(frame: CGRectZero) } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setupWeekdaySymbols() { let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)! calendar.components([NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: NSDate()) calendar.firstWeekday = firstWeekday.rawValue symbols = calendar.weekdaySymbols } func createDaySymbols() { // Change symbols with their places if needed. let dateFormatter = NSDateFormatter() var weekdays = dateFormatter.shortWeekdaySymbols as NSArray let firstWeekdayIndex = firstWeekday.rawValue - 1 if (firstWeekdayIndex > 0) { let copy = weekdays weekdays = (weekdays.subarrayWithRange(NSMakeRange(firstWeekdayIndex, 7 - firstWeekdayIndex))) weekdays = weekdays.arrayByAddingObjectsFromArray(copy.subarrayWithRange(NSMakeRange(0, firstWeekdayIndex))) } self.symbols = weekdays as! [String] // Add symbols. self.symbolViews = [UILabel]() let space = 0 as CGFloat let width = self.frame.width / 7 - space let height = self.frame.height var x: CGFloat = 0 let y: CGFloat = 0 for i in 0..<7 { x = CGFloat(i) * width + space let symbol = UILabel(frame: CGRectMake(x, y, width, height)) symbol.textAlignment = .Center symbol.text = (self.symbols[i]).uppercaseString symbol.font = UIFont.boldSystemFontOfSize(10) // may be provided as a delegate property symbol.textColor = UIColor.darkGrayColor() self.symbolViews?.append(symbol) self.addSubview(symbol) } } func commitMenuViewUpdate() { if let delegate = delegate { let space = 0 as CGFloat let width = self.frame.width / 7 - space let height = self.frame.height var x: CGFloat = 0 let y: CGFloat = 0 for i in 0..<self.symbolViews!.count { x = CGFloat(i) * width + space let frame = CGRectMake(x, y, width, height) let symbol = self.symbolViews![i] symbol.frame = frame } } } }
mit
ee3cf48359bb48537a74296ad8e5de54
28.067227
120
0.54669
5.064422
false
false
false
false
CodeDrunkard/ARViewer
ARViewer/Camera/CameraCapture.swift
1
5132
// // CameraSession.swift // CameraKit // // Created by JT Ma on 14/04/2017. // Copyright © 2017 Apple, Inc. All rights reserved. // import AVFoundation public enum CameraSessionSetupStatus { case success case notAuthorized case configurationFailed } public class CameraCapture { public let session = AVCaptureSession() public var configStatus: CameraSessionSetupStatus = .success public var devicePosition: AVCaptureDevicePosition = .back public var flashMode: AVCaptureFlashMode = .off { didSet { guard flashMode != oldValue, configStatus == .success, let device = videoDeviceInput?.device else { return } configFlash(flashMode, device: device) } } public var torchMode: AVCaptureTorchMode = .off { didSet { guard torchMode != oldValue, configStatus == .success, let device = videoDeviceInput?.device else { return } configTorch(torchMode, device: device) } } public var focusMode: AVCaptureFocusMode = .autoFocus { didSet { guard focusMode != oldValue, configStatus == .success, let device = videoDeviceInput?.device else { return } configFocus(focusMode, device: device) } } fileprivate var videoDeviceInput: AVCaptureDeviceInput? fileprivate let sessionQueue = DispatchQueue(label: "com.jt.camera.sessionQueue") fileprivate var sessionPreset: String = AVCaptureSessionPresetHigh fileprivate var isRunning = false public init() { prepare() } } public extension CameraCapture { func start() { sessionQueue.async { guard self.configStatus == .success else { return } self.session.startRunning() self.isRunning = self.session.isRunning } } func stop() { sessionQueue.async { guard self.configStatus == .success else { return } self.session.stopRunning() self.isRunning = self.session.isRunning } } } fileprivate extension CameraCapture { func prepare() { authorization() sessionQueue.async { [unowned self] in self.configSession() } } func authorization() { switch AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) { case .authorized: break case .notDetermined: sessionQueue.suspend() AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { [unowned self] granted in if !granted { self.configStatus = .notAuthorized } self.sessionQueue.resume() }) default: configStatus = .notAuthorized } } func configSession() { guard configStatus == .success else { return } session.beginConfiguration() session.sessionPreset = sessionPreset do { var defaultVideoDevice: AVCaptureDevice? if let dualCameraDevice = AVCaptureDevice.defaultDevice(withDeviceType: .builtInDuoCamera, mediaType: AVMediaTypeVideo, position: devicePosition) { defaultVideoDevice = dualCameraDevice } else if let backCameraDevice = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: devicePosition) { defaultVideoDevice = backCameraDevice } let videoDeviceInput = try AVCaptureDeviceInput(device: defaultVideoDevice) if session.canAddInput(videoDeviceInput) { session.addInput(videoDeviceInput) self.videoDeviceInput = videoDeviceInput } else { print("Could not add video device input to the session") configStatus = .configurationFailed session.commitConfiguration() return } } catch { print("Could not create video device input: \(error)") configStatus = .configurationFailed session.commitConfiguration() return } session.commitConfiguration() } } fileprivate extension CameraCapture { func configFocus(_ mode: AVCaptureFocusMode, device: AVCaptureDevice) { } func configFlash(_ mode: AVCaptureFlashMode, device: AVCaptureDevice) { } func configTorch(_ mode: AVCaptureTorchMode, device: AVCaptureDevice) { } func changeCamera() { } }
mit
a1af533cffb25e6f802b0b9a2a660155
30.478528
115
0.557786
6.167067
false
true
false
false
ontouchstart/swift3-playground
Shapes.playgroundbook/Contents/Chapters/Shapes.playgroundchapter/Pages/Animate.playgroundpage/Contents.swift
1
1279
//#-code-completion(module, hide, Swift) //#-code-completion(identifier, hide, _setup()) //#-code-completion(identifier, hide, AbstractDrawable) //#-hidden-code _setup() //#-end-hidden-code //#-editable-code Tap to enter code // create a line. let line = Line(start: Point(x: -10, y: 0), end: Point(x: 10, y: 0)) line.color = .blue line.center.y += 6 // create a Text object that, when tapped, will kick off the clockwise rotation animation. let rotateClockwiseText = Text(string: "Rotate Line Clockwise", fontSize: 21.0) rotateClockwiseText.color = .blue rotateClockwiseText.center.y -= 7 // create a Text object that, when tapped, will kick off the counter-clockwise rotation animation. let rotateCounterClockwiseText = Text(string: "Rotate Line Counter Clockwise", fontSize: 21.0) rotateCounterClockwiseText.color = .blue rotateCounterClockwiseText.center.y -= 12 // roate the line clockwise with animation when the "Rotate Line Clockwise" text is tapped. rotateClockwiseText.onTouchUp { animate { line.rotation += 3.14159/4 } } // roate the line counter clockwise with animation when the "Rotate Line Counter Clockwise" text is tapped. rotateCounterClockwiseText.onTouchUp { animate { line.rotation -= 3.14159/4 } } //#-end-editable-code
mit
b808eb7d25ebc1b4196d553d6feef45e
33.567568
107
0.73104
3.772861
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Controllers/Threads/ThreadsViewController.swift
1
9185
// // ThreadsViewController.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 22/04/19. // Copyright © 2019 Rocket.Chat. All rights reserved. // import Foundation import DifferenceKit import RocketChatViewController import FLAnimatedImage private typealias NibCellIndentifier = (nib: UINib, cellIdentifier: String) final class ThreadsViewController: RocketChatViewController, MessagesListProtocol { let viewModel = ThreadsViewModel() let viewSizingModel = MessagesSizingManager() lazy var screenSize = view.frame.size var isInLandscape: Bool { return screenSize.width / screenSize.height > 1 && UIDevice.current.userInterfaceIdiom == .phone } // We want to remove the composer for this controller public override var inputAccessoryView: UIView? { return nil } override func viewDidLoad() { super.viewDidLoad() title = viewModel.title isInverted = false ThemeManager.addObserver(self) registerCells() loadMoreData() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { let visibleIndexPaths = collectionView.indexPathsForVisibleItems let topIndexPath = visibleIndexPaths.sorted().last screenSize = size coordinator.animate(alongsideTransition: { [weak self] _ in self?.viewSizingModel.clearCache() self?.collectionView.reloadData() }, completion: { [weak self] _ in guard let self = self else { return } if let indexPath = topIndexPath { self.collectionView.scrollToItem(at: indexPath, at: .bottom, animated: false) } }) } private func registerCells() { let collectionViewCells: [NibCellIndentifier] = [ (nib: BasicMessageCell.nib, cellIdentifier: BasicMessageCell.identifier), (nib: SequentialMessageCell.nib, cellIdentifier: SequentialMessageCell.identifier), (nib: LoaderCell.nib, cellIdentifier: LoaderCell.identifier), (nib: DateSeparatorCell.nib, cellIdentifier: DateSeparatorCell.identifier), (nib: UnreadMarkerCell.nib, cellIdentifier: UnreadMarkerCell.identifier), (nib: AudioCell.nib, cellIdentifier: AudioCell.identifier), (nib: AudioMessageCell.nib, cellIdentifier: AudioMessageCell.identifier), (nib: VideoCell.nib, cellIdentifier: VideoCell.identifier), (nib: VideoMessageCell.nib, cellIdentifier: VideoMessageCell.identifier), (nib: ReactionsCell.nib, cellIdentifier: ReactionsCell.identifier), (nib: FileCell.nib, cellIdentifier: FileCell.identifier), (nib: FileMessageCell.nib, cellIdentifier: FileMessageCell.identifier), (nib: TextAttachmentCell.nib, cellIdentifier: TextAttachmentCell.identifier), (nib: TextAttachmentMessageCell.nib, cellIdentifier: TextAttachmentMessageCell.identifier), (nib: ImageCell.nib, cellIdentifier: ImageCell.identifier), (nib: ImageMessageCell.nib, cellIdentifier: ImageMessageCell.identifier), (nib: QuoteCell.nib, cellIdentifier: QuoteCell.identifier), (nib: QuoteMessageCell.nib, cellIdentifier: QuoteMessageCell.identifier), (nib: MessageURLCell.nib, cellIdentifier: MessageURLCell.identifier), (nib: MessageActionsCell.nib, cellIdentifier: MessageActionsCell.identifier), (nib: MessageVideoCallCell.nib, cellIdentifier: MessageVideoCallCell.identifier), (nib: MessageDiscussionCell.nib, cellIdentifier: MessageDiscussionCell.identifier), (nib: MessageMainThreadCell.nib, cellIdentifier: MessageMainThreadCell.identifier), (nib: ThreadReplyCollapsedCell.nib, cellIdentifier: ThreadReplyCollapsedCell.identifier), (nib: HeaderCell.nib, cellIdentifier: HeaderCell.identifier) ] collectionViewCells.forEach { collectionView?.register($0.nib, forCellWithReuseIdentifier: $0.cellIdentifier) } } // MARK: Data Management func loadMoreData() { let activity = UIActivityIndicatorView(style: .gray) let buttonActivity = UIBarButtonItem(customView: activity) activity.startAnimating() navigationItem.rightBarButtonItem = buttonActivity viewModel.controllerContext = self viewModel.loadMoreObjects { [weak self] in guard let self = self else { return } self.navigationItem.rightBarButtonItem = nil self.updateData(with: self.viewModel.dataNormalized) } } // MARK: Sizing func messageWidth() -> CGFloat { var horizontalMargins: CGFloat if isInLandscape { horizontalMargins = collectionView.adjustedContentInset.top + collectionView.adjustedContentInset.bottom } else { horizontalMargins = 0 } return screenSize.width - horizontalMargins } } extension ThreadsViewController: ChatDataUpdateDelegate { func didUpdateChatData(newData: [AnyChatSection], updatedItems: [AnyHashable]) { updatedItems.forEach { viewSizingModel.invalidateLayout(for: $0) } viewModel.data = newData viewModel.normalizeData() } } extension ThreadsViewController { override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.section == viewModel.numberOfObjects - viewModel.pageSize / 2 { loadMoreData() } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return .zero } override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { guard let item = viewModel.item(for: indexPath) else { return .zero } if let size = viewSizingModel.size(for: item.differenceIdentifier) { return size } else { let identifier = item.relatedReuseIdentifier var sizingCell: Any? if let cachedSizingCell = viewSizingModel.view(for: identifier) as? SizingCell { sizingCell = cachedSizingCell } else { sizingCell = UINib(nibName: identifier, bundle: nil).instantiate() as? SizingCell if let sizingCell = sizingCell { viewSizingModel.set(view: sizingCell, for: identifier) } } guard let cell = sizingCell as? SizingCell else { fatalError(""" Failed to reference sizing cell instance. Please, check the relatedReuseIdentifier and make sure all the chat components conform to SizingCell protocol """) } let cellWidth = messageWidth() var size = type(of: cell).size(for: item, with: cellWidth) size = CGSize(width: cellWidth, height: size.height) viewSizingModel.set(size: size, for: item.differenceIdentifier) return size } } } extension ThreadsViewController: ChatMessageCellProtocol { func openThread(identifier: String) { guard let controller = UIStoryboard.controller(from: "Chat", identifier: "Chat") as? MessagesViewController else { return } controller.threadIdentifier = identifier navigationController?.pushViewController(controller, animated: true) } func openURL(url: URL) { } func handleLongPressMessageCell(_ message: Message, view: UIView, recognizer: UIGestureRecognizer) { } func handleUsernameTapMessageCell(_ message: Message, view: UIView, recognizer: UIGestureRecognizer) { } func handleLongPress(reactionListView: ReactionListView, reactionView: ReactionView) { } func handleReadReceiptPress(_ message: Message, source: (UIView, CGRect)) { } func handleReviewRequest() { } func openURLFromCell(url: String) { } func openVideoFromCell(attachment: UnmanagedAttachment) { } func openImageFromCell(attachment: UnmanagedAttachment, thumbnail: FLAnimatedImageView) { } func openImageFromCell(url: URL, thumbnail: FLAnimatedImageView) { } func viewDidCollapseChange(viewModel: AnyChatItem) { } func openFileFromCell(attachment: UnmanagedAttachment) { } func openReplyMessage(message: UnmanagedMessage) { } }
mit
b320e7ef192072cb68334a6e5f78e9dd
33.920152
175
0.676285
5.389671
false
false
false
false
nineteen-apps/swift
lessons-01/lesson2/Sources/cpf.swift
1
2316
// -*-swift-*- // The MIT License (MIT) // // Copyright (c) 2017 - Nineteen // // 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. // // Created: 2017-06-20 by Ronaldo Faria Lima // // This file purpose: Classe que realiza o cálculo do dígito verificador do CPF // para verificação de sua validade. import Foundation struct CPF { let cpf: String init(cpf: String) { self.cpf = cpf } func cpfIsValid() -> Bool { let ckDigits = checkDigit(weight: 10) * 10 + checkDigit(weight: 11) return ckDigits == getCurrCheckDigits() } private func checkDigit(weight: Int) -> Int { var ckDigit = 0 var i = 0 let strLen = cpf.characters.count var currWeight = weight while i < strLen && currWeight > 1 { let index = cpf.index(cpf.startIndex, offsetBy: i) let digit = String(cpf[index]) ckDigit += Int(digit)! * currWeight i += 1 currWeight -= 1 } let remainder = ckDigit % 11 ckDigit = remainder < 2 ? 0 : 11 - remainder return ckDigit } private func getCurrCheckDigits() -> Int { let lastDigits = Int(cpf.substring(from: cpf.index(cpf.endIndex, offsetBy: -2))) return lastDigits! } }
mit
fb984ca69602d20d181e2384a1014ad1
35.125
88
0.665657
4.180832
false
false
false
false
ozpopolam/TrivialAsia
TrivialAsia/TriviaTableViewCell.swift
1
3356
// // TriviaTableViewCell.swift // TrivialAsia // // Created by Anastasia Stepanova-Kolupakhina on 27.05.17. // Copyright © 2017 Anastasia Kolupakhina. All rights reserved. // import UIKit protocol TriviaTableViewCellDelegate: class { func isAnswer(_ answer: String, correctForTriviaWithId triviaId: Int) -> Bool func cellDidFinishWIthTrivia(withId triviaId: Int) } final class TriviaTableViewCell: UITableViewCell { static let identifier = "TriviaTableViewCell" static let cornerRadius: CGFloat = 4.0 private var trivia: TriviaViewAdapted? private weak var delegate: TriviaTableViewCellDelegate? @IBOutlet private weak var difficultyLabel: UILabel! @IBOutlet private weak var questionLabel: UILabel! @IBOutlet private weak var answersView: UIView! { didSet { isFolded = true } } var isFolded: Bool = true { didSet { answersView.isHidden = isFolded } } @IBOutlet weak var answersStackView: UIStackView! private var answerButtons = [UIButton]() override func awakeFromNib() { super.awakeFromNib() selectionStyle = .none difficultyLabel.layer.cornerRadius = TriviaTableViewCell.cornerRadius difficultyLabel.layer.masksToBounds = true difficultyLabel.backgroundColor = TriviaColor.pink difficultyLabel.textColor = .white } func configure(with trivia: TriviaViewAdapted, delegate: TriviaTableViewCellDelegate?, isFolded: Bool, isEven: Bool) { self.trivia = trivia self.delegate = delegate backgroundColor = isEven ? UIColor.white : TriviaColor.whiteSmoke difficultyLabel.text = " " + trivia.difficulty + " " // imitate UIEdgeInsets xD questionLabel.text = trivia.question self.isFolded = isFolded add(answers: trivia.answers) } private func add(answers: [String]) { answerButtons.forEach { $0.removeFromSuperview() } for (id, answer) in answers.enumerated() { let answerButton = UIButton() answerButton.tag = id if id % 2 == 0 { answerButton.backgroundColor = TriviaColor.tealBlue } else { answerButton.backgroundColor = TriviaColor.blue } answerButton.layer.cornerRadius = TriviaTableViewCell.cornerRadius answerButton.layer.masksToBounds = true answerButton.setTitle(answer, for: .normal) answerButton.titleLabel?.font = UIFont.systemFont(ofSize: 15.0) answerButton.addTarget(self, action: #selector(touch(_:)), for: .touchUpInside) answerButtons.append(answerButton) answersStackView.addArrangedSubview(answerButton) } } @objc private func touch(_ button: UIButton) { guard let trivia = trivia else { return } guard let answerIsCorrect = delegate?.isAnswer(trivia.answers[button.tag], correctForTriviaWithId: trivia.id) else { return } answerButtons.forEach { $0.isUserInteractionEnabled = false } if answerIsCorrect { button.backgroundColor = TriviaColor.green } else { button.backgroundColor = TriviaColor.red } delegate?.cellDidFinishWIthTrivia(withId: trivia.id) } }
mit
25227505f59972e05c160441a96f4c7f
29.5
133
0.65693
4.869376
false
false
false
false
cpmpercussion/microjam
chirpey/TouchRecord.swift
1
3098
// // TouchRecord.swift // microjam // // Created by Charles Martin on 6/8/17. // Copyright © 2017 Charles Martin. All rights reserved. // import UIKit /** Contains the data from a single touch in the interaction square. - time: time since the start of the recording in seconds. - x: location in square in [0,1] - y: location in square in [0,1] - z: pressure/size of touch in [0,1] (so far unused) - moving: whether the touch was moving when recorded (Bool represented as 0 or 1). Includes functions to output a single CSV line representing the touch. Must be a class so that TouchRecords can be encoded as NSCoders. */ class TouchRecord: NSObject, NSCoding { /// Time since the start of the recording in seconds var time : Double /// location in square in [0,1] var x : Double /// location in square in [0,1] var y : Double /// pressure/size of touch in [0,1] (so far unused) var z : Double /// whether the touch was moving when recorded var moving : Bool /// Keys for NSCoder encoded contents. struct PropertyKey { static let time = "time" static let x = "x" static let y = "y" static let z = "z" static let moving = "moving" } init(time: Double, x: Double, y: Double, z: Double, moving: Bool) { self.time = time self.x = x self.y = y self.z = z self.moving = moving super.init() } /// Initialises a touchRecord from a single line of a CSV file convenience init?(fromCSVLine line : String) { let components = line.replacingOccurrences(of: " ", with: "").components(separatedBy: ",") guard let time = Double(components[0]), let x = Double(components[1]), let y = Double(components[2]), let z = Double(components[3]), let mov = Double(components[4]) else { return nil } let moving = (mov == 1) self.init(time: time, x: x, y: y, z: z, moving: moving) } /// CSV version of the touchRecord for output to file func csv() -> String { return String(format:"%f, %f, %f, %f, %d\n", time, x, y, z, moving ? 1 : 0) } /// Initialise a TouchRecord from an NSCoder. required convenience init?(coder aDecoder: NSCoder) { let time = aDecoder.decodeDouble(forKey: PropertyKey.time) let x = aDecoder.decodeDouble(forKey: PropertyKey.x) let y = aDecoder.decodeDouble(forKey: PropertyKey.y) let z = aDecoder.decodeDouble(forKey: PropertyKey.z) let moving = aDecoder.decodeBool(forKey: PropertyKey.moving) self.init(time: time, x: x, y: y, z: z, moving: moving) } /// Encode a TouchRecord as an NSCoder. func encode(with aCoder: NSCoder) { aCoder.encode(time, forKey: PropertyKey.time) aCoder.encode(x, forKey: PropertyKey.x) aCoder.encode(y, forKey: PropertyKey.y) aCoder.encode(z, forKey: PropertyKey.z) aCoder.encode(moving, forKey: PropertyKey.moving) } }
mit
73f6a53341d47c3d8a4899b41e3017a1
33.032967
98
0.609622
3.925222
false
false
false
false
khizkhiz/swift
test/DebugInfo/bbentry-location.swift
2
1064
// REQUIRES: OS=ios // REQUIRES: objc_interop // RUN: %target-swift-frontend -emit-ir -g %s -o - | FileCheck %s import UIKit @available(iOS, introduced=8.0) class ActionViewController { var imageView: UIImageView! func viewDidLoad(inputItems: [AnyObject]) { for item: AnyObject in inputItems { let inputItem = item as! NSExtensionItem for provider: AnyObject in inputItem.attachments! { let itemProvider = provider as! NSItemProvider // CHECK: load {{.*}}selector // CHECK:; <label>{{.*}} ; preds = %{{[0-9]+}} // CHECK: @rt_swift_allocObject({{.*}}, !dbg ![[DBG:[0-9]+]] // Test that the location is reset at the entry of a new basic block. // CHECK: ![[DBG]] = {{.*}}line: 0 if itemProvider.hasItemConforming(toTypeIdentifier: "") { weak var weakImageView = self.imageView itemProvider.loadItem(forTypeIdentifier: "", options: nil, completionHandler: { (image, error) in if let imageView = weakImageView { } }) } } } } }
apache-2.0
128ffe8a6586e4e37e1258153d3f730a
33.322581
77
0.606203
4.256
false
false
false
false
aschwaighofer/swift
test/SILGen/objc_bridging_array.swift
2
2400
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) %s | %FileCheck %s // REQUIRES: objc_interop import Foundation class Child : NSObject {} @objc protocol Parent { var children: [Child] { get set } } func setChildren(p: Parent, c: Child) { p.children = [c] } // CHECK-LABEL: sil hidden [ossa] @$s19objc_bridging_array11setChildren1p1cyAA6Parent_p_AA5ChildCtF : $@convention(thin) (@guaranteed Parent, @guaranteed Child) -> () { // CHECK: [[OPENED:%.*]] = open_existential_ref %0 : $Parent to $[[OPENED_TYPE:.* Parent]] // CHECK: [[COPIED:%.*]] = copy_value [[OPENED]] : $[[OPENED_TYPE]] // CHECK: [[LENGTH:%.*]] = integer_literal $Builtin.Word, 1 // CHECK: [[FN:%.*]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: [[ARRAY_AND_BUFFER:%.*]] = apply [[FN]]<Child>([[LENGTH]]) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: ([[ARRAY:%.*]], [[BUFFER_PTR:%.*]]) = destructure_tuple [[ARRAY_AND_BUFFER]] : $(Array<Child>, Builtin.RawPointer) // CHECK: [[BUFFER:%.*]] = pointer_to_address [[BUFFER_PTR]] : $Builtin.RawPointer to [strict] $*Child // CHECK: [[CHILD:%.*]] = copy_value %1 : $Child // CHECK: store [[CHILD]] to [init] [[BUFFER]] : $*Child // CHECK: [[FN:%.*]] = function_ref @$sSa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF : $@convention(method) <τ_0_0> (@guaranteed Array<τ_0_0>) -> @owned NSArray // CHECK: [[BORROW_ARRAY:%.*]] = begin_borrow [[ARRAY]] : $Array<Child> // CHECK: [[BRIDGED_ARRAY:%.*]] = apply [[FN]]<Child>([[BORROW_ARRAY]]) : $@convention(method) <τ_0_0> (@guaranteed Array<τ_0_0>) -> @owned NSArray // CHECK: end_borrow [[BORROW_ARRAY]] : $Array<Child> // CHECK: destroy_value [[ARRAY]] : $Array<Child> // CHECK: [[FN:%.*]] = objc_method [[COPIED]] : $[[OPENED_TYPE]], #Parent.children!setter.foreign : <Self where Self : Parent> (Self) -> ([Child]) -> (), $@convention(objc_method) <τ_0_0 where τ_0_0 : Parent> (NSArray, τ_0_0) -> () // CHECK: apply [[FN]]<[[OPENED_TYPE]]>([[BRIDGED_ARRAY]], [[COPIED]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : Parent> (NSArray, τ_0_0) -> () // CHECK: destroy_value [[BRIDGED_ARRAY]] : $NSArray // CHECK: destroy_value [[COPIED]] : $[[OPENED_TYPE]] // CHECK: [[RESULT:%.*]] = tuple () // CHECK: return [[RESULT]] : $()
apache-2.0
153b445c78e6cb3822d8f7688f932a1d
61.789474
231
0.626153
3.198391
false
false
false
false
paperboy1109/Capstone
Capstone/StandardNormalVC.swift
1
13311
// // StandardNormalVC.swift // Capstone // // Created by Daniel J Janiak on 9/5/16. // Copyright © 2016 Daniel J Janiak. All rights reserved. // import UIKit import Charts import NumberMorphView class StandardNormalVC: UIViewController { // MARK: - Properties let plotBackgroundColor = UIColor.whiteColor() let defaultStartingPoint = -3.0 let defaultEndingPoint = 3.0 let defaultStepsPerLine = 99 let defaultDecimalPlacesToShow = 3 let numberFormatter = NSNumberFormatter() let pValNumberFormatter = NSNumberFormatter() var zScore: Double! // MARK: - Outlets @IBOutlet var plusMinusLabel: UILabel! @IBOutlet var leadingDigit: NumberMorphView! @IBOutlet var decimal1: NumberMorphView! @IBOutlet var decimal2: NumberMorphView! @IBOutlet var decimal3: NumberMorphView! @IBOutlet var stepper: UIStepper! @IBOutlet var pValTitleLabel: UILabel! @IBOutlet var pValueLabel: UILabel! @IBOutlet var plotView: LineChartView! @IBOutlet var slider: UISlider! @IBOutlet var maskView: UIView! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() configurePlotView() numberFormatter.maximumFractionDigits = defaultDecimalPlacesToShow numberFormatter.minimumFractionDigits = defaultDecimalPlacesToShow slider.minimumValue = -3.0 slider.maximumValue = 3.0 stepper.stepValue = 0.001 stepper.minimumValue = Double(slider.minimumValue) stepper.maximumValue = Double(slider.maximumValue) leadingDigit.currentDigit = 0 decimal1.currentDigit = 0 zScore = 0.0 pValTitleLabel.text = "p-value:" maskView.hidden = false } // MARK: - Actions @IBAction func plotTapped(sender: UIButton) { maskView.hidden = true plotView.data = nil plotView.setNeedsLayout() let xValues = SequenceGenerator.createSequenceWithStartingPoint(defaultStartingPoint, end: defaultEndingPoint, numberOfSteps: defaultStepsPerLine) let yValues = xValues.map() { StatisticsFunctions.swift_dorm($0, mean: 0, standardDev: 1)} switch sender.tag { case 0: let maskFillValues = lineDataForMaskingFill(xValues, targetValue: zScore, maskingValue: yValues.maxElement()!, leftTail: true) pNormWithFill(xValues, dataCollections: [yValues, maskFillValues]) /* Display the p-value */ if zScore > 0 { pValueLabel.text = roundPValue(1.0 - StatisticsFunctions.swift_pnormFewestSteps(zScore, mean: 0, standardDev: 1, n: 500)) } else { pValueLabel.text = roundPValue(StatisticsFunctions.swift_pnormFewestSteps(zScore, mean: 0, standardDev: 1, n: 500)) } case 1: let maskFillValues = lineDataForMaskingFill(xValues, targetValue: zScore, maskingValue: yValues.maxElement()!, leftTail: false) pNormWithFill(xValues, dataCollections: [yValues, maskFillValues]) /* Display the p-value */ if zScore < 0 { pValueLabel.text = roundPValue(1.0 - StatisticsFunctions.swift_pnormFewestSteps(zScore, mean: 0, standardDev: 1, n: 500)) } else { pValueLabel.text = roundPValue(StatisticsFunctions.swift_pnormFewestSteps(zScore, mean: 0, standardDev: 1, n: 500)) } default: let maskFillValues = lineDataForMaskingFill(xValues, targetValue: 3.0, maskingValue: yValues.maxElement()!, leftTail: false) pNormWithFill(xValues, dataCollections: [yValues, maskFillValues]) } let plotVerticalLimit = yValues.maxElement()! * 1.1 plotView.xAxis.setLabelsToSkip(10) plotView.leftAxis.axisMaxValue = plotVerticalLimit plotView.rightAxis.axisMaxValue = plotVerticalLimit plotView.setNeedsLayout() plotView.animate(xAxisDuration: 2.0, easingOption: .EaseInOutQuad) //plotView.animate(yAxisDuration: 1.5, easingOption: .EaseInOutQuart) } @IBAction func doneTapped(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func sliderMoved(sender: UISlider) { /* Synchronize with the stepper value */ stepper.value = Double(slider.value) if sender.value < 0 { plusMinusLabel.text = "-" } else { plusMinusLabel.text = "" } setMorphNumbers(sender.value) } @IBAction func stepperTapped(sender: UIStepper) { if sender.value < 0 { plusMinusLabel.text = "-" } else { plusMinusLabel.text = "" } slider.value = Float(stepper.value) setMorphNumbers(slider.value) } // MARK: - Helpers func updateZScore(leadingDigit: Int, firstDecimal: Int, secondDecimal: Int, thirdDecimal: Int) { let zScoreText = "\(leadingDigit)" + "." + "\(firstDecimal)\(secondDecimal)\(thirdDecimal)" zScore = Double(zScoreText) if plusMinusLabel.text == "-" { zScore = (-1.0) * zScore } } func setMorphNumbers(newValue: Float) { guard var numberText = numberFormatter.stringFromNumber(abs(newValue)) else { return } guard !numberText.isEmpty else { return } /* Add a leading zero */ if numberText[numberText.startIndex] == "." { numberText = "0" + numberText } if numberText.characters.count == 5 { let leadingDigitAsString = String(numberText[numberText.startIndex]) let firstDecimalAsString = String(numberText[numberText.startIndex.advancedBy(2)]) let secondDecimalAsString = String(numberText[numberText.startIndex.advancedBy(3)]) let thirdDecimalAsString = String(numberText[numberText.startIndex.advancedBy(4)]) guard let newLeadingDigit = Int(leadingDigitAsString), newFirstDecimal = Int(firstDecimalAsString), newSecondDecimal = Int(secondDecimalAsString), newThirdDecimal = Int(thirdDecimalAsString) else { return } leadingDigit.nextDigit = newLeadingDigit decimal1.nextDigit = newFirstDecimal decimal2.nextDigit = newSecondDecimal decimal3.nextDigit = newThirdDecimal /* The zScore and displayed value must be an exact match */ updateZScore(newLeadingDigit, firstDecimal: newFirstDecimal, secondDecimal: newSecondDecimal, thirdDecimal: newThirdDecimal) } } func roundPValue(fullNumber: Double) -> String { pValNumberFormatter.minimumFractionDigits = 4 pValNumberFormatter.maximumFractionDigits = 4 if let roundedNumberAsString = pValNumberFormatter.stringFromNumber(fullNumber) { return roundedNumberAsString } else { return "" } } } extension StandardNormalVC { func configurePlotView() { /* Remove the grid */ plotView.xAxis.drawGridLinesEnabled = false plotView.drawGridBackgroundEnabled = false plotView.backgroundColor = plotBackgroundColor /* Set up the axes */ plotView.leftAxis.drawGridLinesEnabled = false plotView.leftAxis.enabled = false plotView.leftAxis.axisMinValue = 0.0 plotView.rightAxis.drawGridLinesEnabled = false plotView.rightAxis.enabled = false plotView.rightAxis.axisMinValue = 0.0 plotView.xAxis.setLabelsToSkip(0) /* Remove the legend */ plotView.legend.enabled = false /* Remove the description */ plotView.descriptionText = "" /* Disable user interaction (tapping would otherwise collapse the plot */ plotView.userInteractionEnabled = false } func lineDataForMaskingFill(xValues: [Double], targetValue: Double, maskingValue: Double, leftTail: Bool) -> [Double] { var errorArray: [Double] = [] // xValues.map() {abs(targetValue - $0)} var offset = 0 /* Most practical use cases fit one of the statements below */ // (1) if leftTail && targetValue < 0 { errorArray = xValues[0...xValues.count/2].map() {abs(targetValue - $0)} } // (2) else if !leftTail && targetValue > 0 { errorArray = xValues[(xValues.count-1)/2...(xValues.count-1)].map() {abs(targetValue - $0)} offset = ((xValues.count-1)/2) } /* Not practical, but students will want the flexibility */ // (3) else { errorArray = xValues.map() {abs(targetValue - $0)} } guard errorArray.count > 0 else { return [Double](count: xValues.count, repeatedValue: 0.0) } // let maskingValue = yValues.maxElement()! let availableTarget = xValues[offset + errorArray.indexOf(errorArray.minElement()!)!] let maskingArray = xValues.map() { (xValue) -> Double in if leftTail { return xValue < availableTarget ? 0 : maskingValue } else { return xValue < availableTarget ? maskingValue : 0 } } return maskingArray } func pNormWithFill(xValues: [Double], dataCollections: [[Double]]) { let xValuesAsStrings = xValues.map { String(format: "%.2f", $0) } let bezierIntensity:CGFloat = 0.1 var completeDataEntriesCollection: [[ChartDataEntry]] = [[]] for item in dataCollections { var newDataCollection: [ChartDataEntry] = [] for i in 0..<xValues.count { let dataEntry = ChartDataEntry(value: item[i], xIndex: i) newDataCollection.append(dataEntry) } completeDataEntriesCollection.append(newDataCollection) } completeDataEntriesCollection.removeFirst() let lineChartDataSet_Layer1 = LineChartDataSet(yVals: completeDataEntriesCollection[0], label: "Line 1") let lineChartDataSet_Layer2 = LineChartDataSet(yVals: completeDataEntriesCollection[1], label: "Line 2") let lineChartDataSet_Layer3 = LineChartDataSet(yVals: completeDataEntriesCollection[0], label: "Line 3") /* Customize the appearance of line 1 (bottom layer) */ lineChartDataSet_Layer1.fillColor = UIColor.redColor() lineChartDataSet_Layer1.drawFilledEnabled = true lineChartDataSet_Layer1.drawCirclesEnabled = false lineChartDataSet_Layer1.mode = .CubicBezier lineChartDataSet_Layer1.cubicIntensity = bezierIntensity lineChartDataSet_Layer1.setColor(UIColor.darkGrayColor()) /* Customize the appearance of line 2 (middle layer) */ lineChartDataSet_Layer2.setColor(plotBackgroundColor) lineChartDataSet_Layer2.fillColor = plotBackgroundColor lineChartDataSet_Layer2.drawFilledEnabled = true lineChartDataSet_Layer2.fillAlpha = 1.0 lineChartDataSet_Layer2.mode = .Stepped lineChartDataSet_Layer2.drawCirclesEnabled = false /* Customize the appearance of line 3 (top layer)*/ lineChartDataSet_Layer3.drawCirclesEnabled = false lineChartDataSet_Layer3.mode = .CubicBezier lineChartDataSet_Layer3.cubicIntensity = bezierIntensity lineChartDataSet_Layer3.setColor(UIColor.darkGrayColor()) let linesToPlot = [lineChartDataSet_Layer1, lineChartDataSet_Layer2, lineChartDataSet_Layer3] let lineChartData = LineChartData(xVals: xValuesAsStrings, dataSets: linesToPlot) /* Set the data to be included in the plot */ plotView.data = lineChartData /* Remove labels from the data points */ plotView.data?.setValueTextColor(UIColor.clearColor()) // plotView.xAxis.axisMinValue plotView.leftAxis.axisMinValue = dataCollections[0].minElement()! plotView.rightAxis.axisMinValue = dataCollections[0].minElement()! } } extension StandardNormalVC { override func prefersStatusBarHidden() -> Bool { return true } /* Disable landscape mode for this scene */ override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait } }
mit
16bbeec1089f42b459ca164426338743
33.571429
154
0.604808
5.105485
false
false
false
false
yysskk/SwipeMenuViewController
Sources/Classes/TabView.swift
1
22618
import UIKit // MARK: - TabViewDelegate public protocol TabViewDelegate: class { /// Called before selecting the tab. func tabView(_ tabView: TabView, willSelectTabAt index: Int) /// Called after selecting the tab. func tabView(_ tabView: TabView, didSelectTabAt index: Int) } extension TabViewDelegate { public func tabView(_ tabView: TabView, willSelectTabAt index: Int) {} public func tabView(_ tabView: TabView, didSelectTabAt index: Int) {} } // MARK: - TabViewDataSource public protocol TabViewDataSource: class { /// Return the number of Items in `TabView`. func numberOfItems(in tabView: TabView) -> Int /// Return strings to be displayed at the tab in `TabView`. func tabView(_ tabView: TabView, titleForItemAt index: Int) -> String? } open class TabView: UIScrollView { open weak var tabViewDelegate: TabViewDelegate? open weak var dataSource: TabViewDataSource? var itemViews: [TabItemView] = [] fileprivate let containerView: UIStackView = UIStackView() fileprivate var additionView: UIView = .init() fileprivate var currentIndex: Int = 0 fileprivate(set) var options: SwipeMenuViewOptions.TabView = SwipeMenuViewOptions.TabView() private var leftMarginConstraint: NSLayoutConstraint = .init() private var widthConstraint: NSLayoutConstraint = .init() public init(frame: CGRect, options: SwipeMenuViewOptions.TabView? = nil) { super.init(frame: frame) if let options = options { self.options = options } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func didMoveToSuperview() { reloadData() } open override func layoutSubviews() { super.layoutSubviews() resetAdditionViewPosition(index: currentIndex) } @available(iOS 11.0, *) open override func safeAreaInsetsDidChange() { super.safeAreaInsetsDidChange() leftMarginConstraint.constant = options.margin + safeAreaInsets.left if options.style == .segmented { widthConstraint.constant = options.margin * -2 - safeAreaInsets.left - safeAreaInsets.right } layoutIfNeeded() } fileprivate func focus(on target: UIView, animated: Bool = true) { if options.style == .segmented { return } let offset: CGFloat let contentWidth: CGFloat if #available(iOS 11.0, *), options.isSafeAreaEnabled { offset = target.center.x + options.margin + safeAreaInsets.left - self.frame.width / 2 contentWidth = containerView.frame.width + options.margin * 2 + safeAreaInsets.left + safeAreaInsets.right } else { offset = target.center.x + options.margin - self.frame.width / 2 contentWidth = containerView.frame.width + options.margin * 2 } if offset < 0 || self.frame.width > contentWidth { self.setContentOffset(CGPoint(x: 0, y: 0), animated: animated) } else if contentWidth - self.frame.width < offset { self.setContentOffset(CGPoint(x: contentWidth - self.frame.width, y: 0), animated: animated) } else { self.setContentOffset(CGPoint(x: offset, y: 0), animated: animated) } } // MARK: - Setup /// Reloads all `TabView` item views with the dataSource and refreshes the display. public func reloadData(options: SwipeMenuViewOptions.TabView? = nil, default defaultIndex: Int? = nil, animated: Bool = true) { if let options = options { self.options = options } reset() guard let dataSource = dataSource, dataSource.numberOfItems(in: self) > 0 else { return } setupScrollView() setupContainerView(dataSource: dataSource) setupTabItemViews(dataSource: dataSource) setupAdditionView() if let defaultIndex = defaultIndex { moveTabItem(index: defaultIndex, animated: animated) } } func reset() { currentIndex = 0 itemViews.forEach { $0.removeFromSuperview() } additionView.removeFromSuperview() containerView.removeFromSuperview() itemViews = [] } func update(_ index: Int) { if currentIndex == index { return } currentIndex = index updateSelectedItem(by: currentIndex) } fileprivate func setupScrollView() { backgroundColor = options.backgroundColor showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false isScrollEnabled = true isDirectionalLockEnabled = true alwaysBounceHorizontal = false scrollsToTop = false bouncesZoom = false translatesAutoresizingMaskIntoConstraints = false } fileprivate func setupContainerView(dataSource: TabViewDataSource) { containerView.alignment = .leading switch options.style { case .flexible: containerView.distribution = .fill case .segmented: containerView.distribution = .fillEqually } let itemCount = dataSource.numberOfItems(in: self) var containerHeight: CGFloat = 0.0 switch options.addition { case .underline: containerHeight = frame.height - options.additionView.underline.height - options.additionView.padding.bottom case .none, .circle: containerHeight = frame.height } switch options.style { case .flexible: let containerWidth = options.itemView.width * CGFloat(itemCount) if #available(iOS 11.0, *), options.isSafeAreaEnabled { contentSize = CGSize(width: containerWidth + options.margin * 2 + safeAreaInsets.left + safeAreaInsets.right, height: options.height) containerView.frame = CGRect(x: 0, y: options.margin + safeAreaInsets.left, width: containerWidth, height: containerHeight) } else { contentSize = CGSize(width: containerWidth + options.margin * 2, height: options.height) containerView.frame = CGRect(x: 0, y: options.margin, width: containerWidth, height: containerHeight) } case .segmented: if #available(iOS 11.0, *), options.isSafeAreaEnabled { contentSize = CGSize(width: frame.width, height: options.height) containerView .frame = CGRect(x: 0, y: options.margin + safeAreaInsets.left, width: frame.width - options.margin * 2 - safeAreaInsets.left - safeAreaInsets.right, height: containerHeight) } else { contentSize = CGSize(width: frame.width, height: options.height) containerView .frame = CGRect(x: 0, y: options.margin, width: frame.width - options.margin * 2, height: containerHeight) } } containerView.backgroundColor = .clear addSubview(containerView) } fileprivate func setupTabItemViews(dataSource: TabViewDataSource) { itemViews = [] let itemCount = dataSource.numberOfItems(in: self) var xPosition: CGFloat = 0 for index in 0..<itemCount { let tabItemView = TabItemView(frame: CGRect(x: xPosition, y: 0, width: options.itemView.width, height: containerView.frame.size.height)) tabItemView.translatesAutoresizingMaskIntoConstraints = false tabItemView.clipsToBounds = options.clipsToBounds if let title = dataSource.tabView(self, titleForItemAt: index) { tabItemView.titleLabel.text = title tabItemView.titleLabel.font = options.itemView.font tabItemView.textColor = options.itemView.textColor tabItemView.selectedTextColor = options.itemView.selectedTextColor } tabItemView.isSelected = index == currentIndex switch options.style { case .flexible: if options.needsAdjustItemViewWidth { var adjustCellSize = tabItemView.frame.size adjustCellSize.width = tabItemView.titleLabel.sizeThatFits(containerView.frame.size).width + options.itemView.margin * 2 tabItemView.frame.size = adjustCellSize containerView.addArrangedSubview(tabItemView) NSLayoutConstraint.activate([ tabItemView.widthAnchor.constraint(equalToConstant: adjustCellSize.width) ]) } else { containerView.addArrangedSubview(tabItemView) NSLayoutConstraint.activate([ tabItemView.widthAnchor.constraint(equalToConstant: options.itemView.width) ]) } case .segmented: let adjustCellSize: CGSize if #available(iOS 11.0, *), options.isSafeAreaEnabled { adjustCellSize = CGSize(width: (frame.width - options.margin * 2 - safeAreaInsets.left - safeAreaInsets.right) / CGFloat(itemCount), height: tabItemView.frame.size.height) } else { adjustCellSize = CGSize(width: (frame.width - options.margin * 2) / CGFloat(itemCount), height: tabItemView.frame.size.height) } tabItemView.frame.size = adjustCellSize containerView.addArrangedSubview(tabItemView) } itemViews.append(tabItemView) NSLayoutConstraint.activate([ tabItemView.topAnchor.constraint(equalTo: containerView.topAnchor), tabItemView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor) ]) xPosition += tabItemView.frame.size.width } layout(containerView: containerView, containerWidth: xPosition) addTabItemGestures() animateAdditionView(index: currentIndex, animated: false) } private func layout(containerView: UIView, containerWidth: CGFloat) { containerView.frame.size.width = containerWidth containerView.translatesAutoresizingMaskIntoConstraints = false let heightConstraint: NSLayoutConstraint switch options.addition { case .underline: heightConstraint = containerView.heightAnchor.constraint(equalToConstant: options.height - options.additionView.underline.height - options.additionView.padding.bottom) case .circle, .none: heightConstraint = containerView.heightAnchor.constraint(equalToConstant: options.height) } switch options.style { case .flexible: if #available(iOS 11.0, *), options.isSafeAreaEnabled { leftMarginConstraint = containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: options.margin + safeAreaInsets.left) NSLayoutConstraint.activate([ containerView.topAnchor.constraint(equalTo: self.topAnchor), leftMarginConstraint, containerView.widthAnchor.constraint(equalToConstant: containerWidth), heightConstraint ]) contentSize.width = containerWidth + options.margin * 2 + safeAreaInsets.left - safeAreaInsets.right } else { leftMarginConstraint = containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: options.margin) NSLayoutConstraint.activate([ containerView.topAnchor.constraint(equalTo: self.topAnchor), leftMarginConstraint, containerView.widthAnchor.constraint(equalToConstant: containerWidth), heightConstraint ]) contentSize.width = containerWidth + options.margin * 2 } case .segmented: if #available(iOS 11.0, *), options.isSafeAreaEnabled { leftMarginConstraint = containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: options.margin + safeAreaInsets.left) widthConstraint = containerView.widthAnchor.constraint(equalTo: self.widthAnchor, constant: options.margin * -2 - safeAreaInsets.left - safeAreaInsets.right) NSLayoutConstraint.activate([ containerView.topAnchor.constraint(equalTo: self.topAnchor), leftMarginConstraint, widthConstraint, heightConstraint ]) } else { leftMarginConstraint = containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: options.margin) widthConstraint = containerView.widthAnchor.constraint(equalTo: self.widthAnchor, constant: options.margin * -2) NSLayoutConstraint.activate([ containerView.topAnchor.constraint(equalTo: self.topAnchor), leftMarginConstraint, widthConstraint, heightConstraint ]) } contentSize = .zero } } private func updateSelectedItem(by newIndex: Int) { for (i, itemView) in itemViews.enumerated() { itemView.isSelected = i == newIndex } } } // MARK: - AdditionView extension TabView { public enum Direction { case forward case reverse } fileprivate func setupAdditionView() { if itemViews.isEmpty { return } switch options.addition { case .underline: let itemView = itemViews[currentIndex] additionView = UIView(frame: CGRect(x: itemView.frame.origin.x + options.additionView.padding.left, y: itemView.frame.height - options.additionView.padding.vertical, width: itemView.frame.width - options.additionView.padding.horizontal, height: options.additionView.underline.height)) additionView.backgroundColor = options.additionView.backgroundColor containerView.addSubview(additionView) case .circle: let itemView = itemViews[currentIndex] let height = itemView.bounds.height - options.additionView.padding.vertical additionView = UIView(frame: CGRect(x: itemView.frame.origin.x + options.additionView.padding.left, y: 0, width: itemView.frame.width - options.additionView.padding.horizontal, height: height)) additionView.layer.position.y = itemView.layer.position.y additionView.layer.cornerRadius = options.additionView.circle.cornerRadius ?? additionView.frame.height / 2 additionView.backgroundColor = options.additionView.backgroundColor if #available(iOS 11.0, *) { if let m = options.additionView.circle.maskedCorners { additionView.layer.maskedCorners = m } } else { var cornerMask = UIRectCorner() if let maskedCorners = options.additionView.circle.maskedCorners { if(maskedCorners.contains(.layerMinXMinYCorner)){ cornerMask.insert(.topLeft) } if(maskedCorners.contains(.layerMaxXMinYCorner)){ cornerMask.insert(.topRight) } if(maskedCorners.contains(.layerMinXMaxYCorner)){ cornerMask.insert(.bottomLeft) } if(maskedCorners.contains(.layerMaxXMaxYCorner)){ cornerMask.insert(.bottomRight) } let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: cornerMask, cornerRadii: CGSize(width: options.additionView.circle.cornerRadius ?? additionView.frame.height / 2, height: options.additionView.circle.cornerRadius ?? additionView.frame.height / 2)) let mask = CAShapeLayer() mask.path = path.cgPath additionView.layer.mask = mask } } containerView.addSubview(additionView) containerView.sendSubviewToBack(additionView) case .none: additionView.backgroundColor = .clear } jump(to: currentIndex) } private func updateAdditionViewPosition(index: Int) { guard let target = currentItem else { return } additionView.frame.origin.x = target.frame.origin.x + options.additionView.padding.left if options.needsAdjustItemViewWidth { let cellWidth = itemViews[index].frame.width additionView.frame.size.width = cellWidth - options.additionView.padding.horizontal } focus(on: target) } fileprivate func resetAdditionViewPosition(index: Int) { guard options.style == .segmented, let dataSource = dataSource, dataSource.numberOfItems(in: self) > 0 else { return } let adjustCellWidth: CGFloat if #available(iOS 11.0, *), options.isSafeAreaEnabled && safeAreaInsets != .zero { adjustCellWidth = (frame.width - options.margin * 2 - safeAreaInsets.left - safeAreaInsets.right) / CGFloat(dataSource.numberOfItems(in: self)) - options.additionView.padding.horizontal } else { adjustCellWidth = (frame.width - options.margin * 2) / CGFloat(dataSource.numberOfItems(in: self)) - options.additionView.padding.horizontal } additionView.frame.origin.x = adjustCellWidth * CGFloat(index) - options.additionView.padding.left additionView.frame.size.width = adjustCellWidth } fileprivate func animateAdditionView(index: Int, animated: Bool, completion: ((Bool) -> Swift.Void)? = nil) { update(index) if animated { UIView.animate(withDuration: options.additionView.animationDuration, animations: { self.updateAdditionViewPosition(index: index) }, completion: completion) } else { updateAdditionViewPosition(index: index) } } func moveAdditionView(index: Int, ratio: CGFloat, direction: Direction) { update(index) guard let currentItem = currentItem else { return } if options.additionView.isAnimationOnSwipeEnable { switch direction { case .forward: additionView.frame.origin.x = currentItem.frame.origin.x + (nextItem.frame.origin.x - currentItem.frame.origin.x) * ratio + options.additionView.padding.left additionView.frame.size.width = currentItem.frame.size.width + (nextItem.frame.size.width - currentItem.frame.size.width) * ratio - options.additionView.padding.horizontal if options.needsConvertTextColorRatio { nextItem.titleLabel.textColor = options.itemView.textColor.convert(to: options.itemView.selectedTextColor, multiplier: ratio) currentItem.titleLabel.textColor = options.itemView.selectedTextColor.convert(to: options.itemView.textColor, multiplier: ratio) } case .reverse: additionView.frame.origin.x = previousItem.frame.origin.x + (currentItem.frame.origin.x - previousItem.frame.origin.x) * ratio + options.additionView.padding.left additionView.frame.size.width = previousItem.frame.size.width + (currentItem.frame.size.width - previousItem.frame.size.width) * ratio - options.additionView.padding.horizontal if options.needsConvertTextColorRatio { previousItem.titleLabel.textColor = options.itemView.selectedTextColor.convert(to: options.itemView.textColor, multiplier: ratio) currentItem.titleLabel.textColor = options.itemView.textColor.convert(to: options.itemView.selectedTextColor, multiplier: ratio) } } } else { moveTabItem(index: index, animated: true) } if options.itemView.selectedTextColor.convert(to: options.itemView.textColor, multiplier: ratio) == nil { updateSelectedItem(by: currentIndex) } focus(on: additionView, animated: false) } } extension TabView { var currentItem: TabItemView? { return currentIndex < itemViews.count ? itemViews[currentIndex] : nil } var nextItem: TabItemView { if currentIndex < itemViews.count - 1 { return itemViews[currentIndex + 1] } return itemViews[currentIndex] } var previousItem: TabItemView { if currentIndex > 0 { return itemViews[currentIndex - 1] } return itemViews[currentIndex] } func jump(to index: Int) { update(index) guard let currentItem = currentItem else { return } if options.addition == .underline { additionView.frame.origin.x = currentItem.frame.origin.x + options.additionView.padding.left additionView.frame.size.width = currentItem.frame.size.width - options.additionView.padding.horizontal } focus(on: currentItem, animated: false) } } // MARK: - GestureRecognizer extension TabView { fileprivate var tapGestureRecognizer: UITapGestureRecognizer { let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapItemView(_:))) gestureRecognizer.numberOfTapsRequired = 1 gestureRecognizer.cancelsTouchesInView = false return gestureRecognizer } fileprivate func addTabItemGestures() { itemViews.forEach { $0.addGestureRecognizer(tapGestureRecognizer) } } @objc func tapItemView(_ recognizer: UITapGestureRecognizer) { guard let itemView = recognizer.view as? TabItemView, let index: Int = itemViews.firstIndex(of: itemView), currentIndex != index else { return } tabViewDelegate?.tabView(self, willSelectTabAt: index) moveTabItem(index: index, animated: true) update(index) tabViewDelegate?.tabView(self, didSelectTabAt: index) } private func moveTabItem(index: Int, animated: Bool) { switch options.addition { case .underline, .circle: animateAdditionView(index: index, animated: animated, completion: nil) case .none: update(index) } } }
mit
dc0cc8df9a6d64b19c221b2ddb868f1b
40.273723
296
0.6356
5.284579
false
false
false
false
iOSDevLog/InkChat
InkChat/InkChat/Login/Controller/StyleViewController.swift
1
3634
// // StyleViewController.swift // InkChat // // Created by iOS Dev Log on 2017/5/26. // Copyright © 2017年 iOSDevLog. All rights reserved. // import UIKit class StyleViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var flowLayout: UICollectionViewFlowLayout! @IBOutlet weak var rightButtonItem: UIBarButtonItem! class Style { var name: String var isSelected: Bool init(name: String, isSelected: Bool) { self.name = name self.isSelected = isSelected } } var results = [ Style(name: "新传统", isSelected: false), Style(name: "奇卡诺", isSelected: true), Style(name: "old school", isSelected: false), Style(name: "new school", isSelected: true), Style(name: "老传统", isSelected: false), Style(name: "小清新", isSelected: false), Style(name: "写实", isSelected: false), Style(name: "3D风格", isSelected: false), Style(name: "肖像风格", isSelected: false), Style(name: "写实风格", isSelected: true), Style(name: "几何", isSelected: false), ] override func viewDidLoad() { super.viewDidLoad() self.collectionView.dataSource = self self.collectionView.delegate = self self.flowLayout.estimatedItemSize = CGSize(width: 30, height: 100) if ad.user?.type == "artist" { rightButtonItem.title = "Next" } else { rightButtonItem.title = "Done" } } @IBAction func rightButtonClicked(_ sender: UIBarButtonItem) { if ad.user?.type == "artist" { performSegue(withIdentifier: "PriceViewControllerSegue", sender: nil) } else { self.dismiss(animated: true, completion: nil) } } @IBAction func selectAllStyles(_ sender: UIButton) { for style in self.results { style.isSelected = true } self.collectionView.reloadData() } } // MARK: - UICollectionViewDataSource extension StyleViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return results.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as StyleCollectionViewCell let style = results[indexPath.row] cell.styleLabel.text = " \(style.name) " cell.styleLabel.borderWidth = 1 cell.styleLabel.borderColor = UIColor.white cell.styleLabel.clipsToBounds = true if (style.isSelected) { cell.styleLabel.fillColor = UIColor.white cell.styleLabel.textColor = UIColor.black } else { cell.styleLabel.fillColor = UIColor.clear cell.styleLabel.textColor = UIColor.white } return cell } } // MAKR: - UICollectionViewDelegate extension StyleViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) var style = results[indexPath.row] style.isSelected = !style.isSelected self.collectionView.reloadData() } }
apache-2.0
596b2b6899d2b08dadb47ab30cad4ac7
30.955357
121
0.630902
4.797587
false
false
false
false
asm-products/giraff-ios
Fun/MenuViewController.swift
1
1564
import UIKit class MenuViewController: UIViewController, FBLoginViewDelegate { @IBOutlet weak var fbLoginView: FBLoginView! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var userProfileImageView: UIImageView! @IBOutlet weak var logoutButton: UIButton! override func viewDidLoad() { super.viewDidLoad() if let facebookName = User.currentUser.facebookName { usernameLabel.text = facebookName.uppercaseString } if User.currentUser.didLoginWithFacebook { User.currentUser.getFacebookProfilePicture { image in if let facebookProfilePicture = image { self.userProfileImageView.image = facebookProfilePicture } } fbLoginView.delegate = self logoutButton.hidden = true } else { if let email = User.currentUser.email { usernameLabel.text = email } fbLoginView.hidden = true } } func loginViewShowingLoggedOutUser(loginView: FBLoginView!) { NSLog("Facebook logged out") self.logoutUser() revealViewController().dismissViewControllerAnimated(true, completion: nil) } @IBAction func logoutButtonDidPress(button: UIButton) { self.logoutUser() revealViewController().dismissViewControllerAnimated(true, completion: nil) } func logoutUser() { User.removeCache() FunSession.sharedSession.deletePersistedAuthenticationToken() } }
agpl-3.0
5ce56bb7b4d3941190c7903e6448e88c
32.276596
83
0.642583
5.771218
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Services/Service.Battery.swift
1
1094
import Foundation extension Service { open class Battery: Service { public init(characteristics: [AnyCharacteristic] = []) { var unwrapped = characteristics.map { $0.wrapped } statusLowBattery = getOrCreateAppend( type: .statusLowBattery, characteristics: &unwrapped, generator: { PredefinedCharacteristic.statusLowBattery() }) batteryLevel = get(type: .batteryLevel, characteristics: unwrapped) chargingState = get(type: .chargingState, characteristics: unwrapped) name = get(type: .name, characteristics: unwrapped) super.init(type: .battery, characteristics: unwrapped) } // MARK: - Required Characteristics public let statusLowBattery: GenericCharacteristic<Enums.StatusLowBattery> // MARK: - Optional Characteristics public let batteryLevel: GenericCharacteristic<UInt8>? public let chargingState: GenericCharacteristic<Enums.ChargingState>? public let name: GenericCharacteristic<String>? } }
mit
c3d1c2f692f389f2770b8829b2bde65c
42.76
82
0.662706
5.610256
false
false
false
false
Bouke/HAP
Sources/HAPInspector/main.swift
1
1451
import Foundation var sourceURL: URL if CommandLine.argc > 1 { let arg = CommandLine.arguments[1] sourceURL = URL(fileURLWithPath: arg) } else { let path = "/System/Library/PrivateFrameworks/HomeKitDaemon.framework" guard let framework = Bundle(path: path) else { print("No HomeKitDaemon private framework found") exit(1) } guard let plistUrl = framework.url(forResource: "plain-metadata", withExtension: "config") else { print("Resource plain-metadata.config not found in HomeKitDaemon.framework") exit(1) } sourceURL = plistUrl } do { print("Generating from \(sourceURL)") let base = "Sources/HAP/Base" if !FileManager.default.directoryExists(atPath: base) { print("Expected existing directory at `\(base)`") exit(1) } let target = "\(base)/Predefined" if FileManager.default.directoryExists(atPath: target) { try FileManager.default.removeItem(atPath: target) } try FileManager.default.createDirectory(atPath: target, withIntermediateDirectories: false, attributes: nil) try inspect(source: sourceURL, target: target) } catch { print("Couldn't update: \(error)") } extension FileManager { func directoryExists(atPath path: String) -> Bool { var isDirectory: ObjCBool = false let exists = fileExists(atPath: path, isDirectory: &isDirectory) return exists && isDirectory.boolValue } }
mit
3c7ad9bd1bc6b5046f561ac8879d3a88
31.244444
112
0.68091
4.344311
false
false
false
false
hsavit1/PowerUpYourAnimations
PowerUpYourAnimations/MAViewController.swift
5
1910
// // ViewController.swift // MarchingAnts // // Created by Marin Todorov on 6/10/15. // Copyright (c) 2015 Underplot ltd. All rights reserved. // import UIKit class MAViewController: UIViewController { let selection = CAShapeLayer() override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // configure the appearance of the selection selection.fillColor = UIColor.clearColor().CGColor selection.strokeColor = UIColor.whiteColor().CGColor selection.lineWidth = 3.0 selection.shadowOpacity = 0.25 selection.shadowOffset = CGSize(width: 1, height: 1) selection.shadowRadius = 0.1 view.layer.addSublayer(selection) //configure the dash pattern selection.lineDashPattern = [5, 3] } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { super.touchesMoved(touches, withEvent: event) // make the selection frame rect let location = (touches.first as! UITouch).locationInView(view) let selectionRect = CGRect( x: view.center.x - abs(location.x - view.center.x), y: view.center.y - abs(location.y - view.center.y), width: 2 * abs(location.x - view.center.x), height: 2 * abs(location.y - view.center.y) ) selection.path = UIBezierPath(rect: selectionRect).CGPath //let the ants march! UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveLinear | .Repeat, animations: { self.selection.lineDashPhase = 8.0 }, completion: nil) } } /* selection.lineDashPattern = [5, 3] // marching ants! UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveLinear | .Repeat, animations: { self.selection.lineDashPhase = 8.0 }, completion: nil) */
mit
35a2cf07f706c36a18472f0e0039fb58
27.954545
98
0.624607
4.272931
false
false
false
false