repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
rambler-ios/RamblerConferences
Carthage/Checkouts/rides-ios-sdk/source/UberRides/OAuth/KeychainWrapper.swift
1
4951
// // KeychainWrapper.swift // UberRides // // Copyright © 2016 Uber Technologies, Inc. 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. /// Wraps saving and retrieving objects from keychain. class KeychainWrapper: NSObject { private static let serviceName = "com.uber.rides-ios-sdk" private var accessGroup = "" private let Class = kSecClass as String private let AttrAccount = kSecAttrAccount as String private let AttrService = kSecAttrService as String private let AttrAccessGroup = kSecAttrAccessGroup as String private let AttrGeneric = kSecAttrGeneric as String private let AttrAccessible = kSecAttrAccessible as String private let ReturnData = kSecReturnData as String private let ValueData = kSecValueData as String private let MatchLimit = kSecMatchLimit as String /** Set the access group for keychain to use. - parameter group: String representing name of keychain access group. */ func setAccessGroup(accessGroup: String) { self.accessGroup = accessGroup } /** Save an object to keychain. - parameter object: object conforming to NSCoding to save to keychain. - parameter key: key for the object. - returns: true if object was successfully added to keychain. */ func setObject(object: NSCoding, key: String) -> Bool { var keychainItemData = getKeychainItemData(key) let value = NSKeyedArchiver.archivedDataWithRootObject(object) keychainItemData[AttrAccessible] = kSecAttrAccessibleWhenUnlocked keychainItemData[ValueData] = value var result: OSStatus = SecItemAdd(keychainItemData, nil) if result == errSecDuplicateItem { result = SecItemUpdate(keychainItemData, [ValueData: value]) } return result == errSecSuccess } /** Get an object from the keychain. - parameter key: the key associated to the object to retrieve. - returns: the object in keychain or nil if none exists for the given key. */ func getObjectForKey(key: String) -> NSCoding? { var keychainItemData = getKeychainItemData(key) keychainItemData[MatchLimit] = kSecMatchLimitOne keychainItemData[ReturnData] = kCFBooleanTrue var data: AnyObject? let result = withUnsafeMutablePointer(&data) { SecItemCopyMatching(keychainItemData, UnsafeMutablePointer($0)) } var object: AnyObject? if let data = data as? NSData { object = NSKeyedUnarchiver.unarchiveObjectWithData(data) } return result == noErr ? object as? NSCoding : nil } /** Remove an object from keychain - parameter key: key for object to remove. - returns: true if object was successfully deleted. */ func deleteObjectForKey(key: String) -> Bool { let keychainItemData = getKeychainItemData(key) let result = SecItemDelete(keychainItemData) return result == noErr } /** Helper method to build keychain query dictionary. - returns: dictionary of base attributes for keychain query. */ private func getKeychainItemData(key: String) -> [String: AnyObject] { var keychainItemData = [String: AnyObject]() let identifier = key.dataUsingEncoding(NSUTF8StringEncoding) keychainItemData[AttrGeneric] = identifier keychainItemData[AttrAccount] = identifier keychainItemData[AttrService] = self.dynamicType.serviceName keychainItemData[Class] = kSecClassGenericPassword if !accessGroup.isEmpty { keychainItemData[AttrAccessGroup] = accessGroup } return keychainItemData } }
mit
42abe55d86b14fe63551ef7ba0fcae44
35.666667
81
0.677576
5.288462
false
false
false
false
rocketmade/rockauth-ios
RockauthiOS/UI/FlatRoundedButton.swift
1
1975
// // FlatRoundedButton.swift // Pods // // Created by Brayden Morris on 11/4/15. // // import UIKit public class FlatRoundedButton: UIButton { init(title: String?, fontSize: CGFloat, color: UIColor?) { super.init(frame: CGRectZero) if let color = color { commonInit(title: title, fontSize: fontSize, color: color) } } init(title: String?, fontSize: CGFloat, color: UIColor?, frame: CGRect) { super.init(frame: frame) commonInit(title: title, fontSize: fontSize, color: color) } override init(frame: CGRect) { super.init(frame: frame) commonInit(title: nil, fontSize: nil, color: nil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit(title: nil, fontSize: nil, color: nil) } func commonInit(title title: String?, fontSize: CGFloat?, color: UIColor?) { self.translatesAutoresizingMaskIntoConstraints = false self.setTitle(title, forState: UIControlState.Normal) self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) self.clipsToBounds = true self.layer.cornerRadius = 3 if let fontSize = fontSize { self.titleLabel?.font = UIFont.systemFontOfSize(fontSize, weight: UIFontWeightSemibold) } else { self.titleLabel?.font = UIFont.systemFontOfSize(18, weight: UIFontWeightSemibold) } if let color = color { self.setBackgroundImage(color.resizeableImageFromColor(), forState: UIControlState.Normal) } else { self.setBackgroundImage(UIColor.blackColor().resizeableImageFromColor(), forState: UIControlState.Normal) } } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
mit
32d04139470058025d4c87eef27cdf8d
31.377049
117
0.650633
4.582367
false
false
false
false
Coderian/SwiftedGPX
SwiftedGPX/Elements/Keywords.swift
1
1576
// // Keywords.swift // SwiftedGPX // // Created by 佐々木 均 on 2016/02/16. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// GPX Keywords /// /// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd) /// /// <xsd:element name="keywords" type="xsd:string" minOccurs="0"> /// <xsd:annotation> /// <xsd:documentation> /// Keywords associated with the file. Search engines or databases can use this information to classify the data. /// </xsd:documentation> /// </xsd:annotation> /// </xsd:element> public class Keywords : SPXMLElement, HasXMLElementValue, HasXMLElementSimpleValue { public static var elementName: String = "keywords" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as Metadata: v.value.keywords = self default: break } } } } public var value: [String] = [String]() public var originalValue:String! public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{ // TODO: self.originalValue = contents // self.value = contents self.parent = parent return parent } public required init(attributes:[String:String]){ super.init(attributes: attributes) } }
mit
a079799b0ca941d1e80cfe29a1e20209
30.666667
124
0.603687
3.986877
false
false
false
false
tokyovigilante/CesiumKit
CesiumKit/Scene/ScreenSpaceCameraController.swift
1
69570
// // ScreenSpaceCameraController.swift // CesiumKit // // Created by Ryan Walklin on 15/08/14. // Copyright (c) 2014 Test Toast. All rights reserved. // import Foundation /** * Modifies the camera position and orientation based on mouse input to a canvas. * @alias ScreenSpaceCameraController * @constructor * * @param {Scene} scene The scene. */ open class ScreenSpaceCameraController { /** * If true, inputs are allowed conditionally with the flags enableTranslate, enableZoom, * enableRotate, enableTilt, and enableLook. If false, all inputs are disabled. * * NOTE: This setting is for temporary use cases, such as camera flights and * drag-selection of regions (see Picking demo). It is typically set to false at the * start of such events, and set true on completion. To keep inputs disabled * past the end of camera flights, you must use the other booleans (enableTranslate, * enableZoom, enableRotate, enableTilt, and enableLook). * @type {Boolean} * @default true */ var enableInputs = true /** * If true, allows the user to pan around the map. If false, the camera stays locked at the current position. * This flag only applies in 2D and Columbus view modes. * @type {Boolean} * @default true */ var enableTranslate = true /** * If true, allows the user to zoom in and out. If false, the camera is locked to the current distance from the ellipsoid. * @type {Boolean} * @default true */ var enableZoom = true /** * If true, allows the user to rotate the camera. If false, the camera is locked to the current heading. * This flag only applies in 2D and 3D. * @type {Boolean} * @default true */ var enableRotate = true /** * If true, allows the user to tilt the camera. If false, the camera is locked to the current heading. * This flag only applies in 3D and Columbus view. * @type {Boolean} * @default true */ var enableTilt = true /** * If true, allows the user to use free-look. If false, the camera view direction can only be changed through translating * or rotating. This flag only applies in 3D and Columbus view modes. * @type {Boolean} * @default true */ var enableLook = true /** * A parameter in the range <code>[0, 1)</code> used to determine how long * the camera will continue to spin because of inertia. * With value of zero, the camera will have no inertia. * @type {Number} * @default 0.9 */ var inertiaSpin = 0.9 /** * A parameter in the range <code>[0, 1)</code> used to determine how long * the camera will continue to translate because of inertia. * With value of zero, the camera will have no inertia. * @type {Number} * @default 0.9 */ var inertiaTranslate = 0.9 /** * A parameter in the range <code>[0, 1)</code> used to determine how long * the camera will continue to zoom because of inertia. * With value of zero, the camera will have no inertia. * @type {Number} * @default 0.8 */ var inertiaZoom = 0.8 /** * A parameter in the range <code>[0, 1)</code> used to limit the range * of various user inputs to a percentage of the window width/height per animation frame. * This helps keep the camera under control in low-frame-rate situations. * @type {Number} * @default 0.1 */ var maximumMovementRatio = 0.1 /** * Sets the duration, in seconds, of the bounce back animations in 2D and Columbus view. * @type {Number} * @default 3.0 */ var bounceAnimationTime = 3.0 /** * The minimum magnitude, in meters, of the camera position when zooming. Defaults to 20.0. * @type {Number} * @default 20.0 */ var minimumZoomDistance = 1.0 /** * The maximum magnitude, in meters, of the camera position when zooming. Defaults to positive infinity. * @type {Number} * @default {@link Number.POSITIVE_INFINITY} */ var maximumZoomDistance = Double.infinity /** * The input that allows the user to pan around the map. This only applies in 2D and Columbus view modes. * <p> * The type came be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code> * and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier}, * or an array of any of the preceding. * </p> * @type {CameraEventType|Array|undefined} * @default {@link CameraEventType.LEFT_DRAG} */ var translateEventTypes = CameraEventType.leftDrag /** * The input that allows the user to zoom in/out. * <p> * The type came be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code> * and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier}, * or an array of any of the preceding. * </p> * @type {CameraEventType|Array|undefined} * @default [{@link CameraEventType.RIGHT_DRAG}, {@link CameraEventType.WHEEL}, {@link CameraEventType.PINCH}] */ var zoomEventTypes: [CameraEvent] = [ CameraEvent(type: .rightDrag, modifier: nil), CameraEvent(type: .wheel, modifier: nil), CameraEvent(type: .pinch, modifier: nil)] /** * The input that allows the user to rotate around the globe or another object. This only applies in 3D and Columbus view modes. * <p> * The type came be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code> * and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier}, * or an array of any of the preceding. * </p> * @type {CameraEventType|Array|undefined} * @default {@link CameraEventType.LEFT_DRAG} */ var rotateEventTypes: [CameraEvent] = [CameraEvent(type: .leftDrag, modifier: nil)] /** * The input that allows the user to tilt in 3D and Columbus view or twist in 2D. * <p> * The type came be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code> * and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier}, * or an array of any of the preceding. * </p> * @type {CameraEventType|Array|undefined} * @default [{@link CameraEventType.MIDDLE_DRAG}, {@link CameraEventType.PINCH}, { * eventType : {@link CameraEventType.LEFT_DRAG}, * modifier : {@link KeyboardEventModifier.CTRL} * }, { * eventType : {@link CameraEventType.RIGHT_DRAG}, * modifier : {@link KeyboardEventModifier.CTRL} * }] * }] */ var tiltEventTypes: [CameraEvent] = [ //FIXME: middleDrag //CameraEvent(type: .middleDrag, modifier: nil), CameraEvent(type: .pinch, modifier: nil), CameraEvent(type: .leftDrag, modifier: .ctrl), CameraEvent(type: .rightDrag, modifier: .ctrl) ] /** * The input that allows the user to change the direction the camera is viewing. This only applies in 3D and Columbus view modes. * <p> * The type came be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code> * and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier}, * or an array of any of the preceding. * </p> * @type {CameraEventType|Array|undefined} * @default { eventType : {@link CameraEventType.LEFT_DRAG}, modifier : {@link KeyboardEventModifier.SHIFT} } */ var lookEventTypes: [CameraEvent] = [ CameraEvent(type: .leftDrag, modifier: .shift) ] /** * The minimum height the camera must be before picking the terrain instead of the ellipsoid. * @type {Number} * @default 150000.0 */ var minimumPickingTerrainHeight = 150000.0 /** * The minimum height the camera must be before testing for collision with terrain. * @type {Number} * @default 15000.0 */ var minimumCollisionTerrainHeight = 15000.0 /** * The minimum height the camera must be before switching from rotating a track ball to * free look when clicks originate on the sky on in space. * @type {Number} * @default 7500000.0 */ var minimumTrackBallHeight = 7500000.0 /** * Enables or disables camera collision detection with terrain. * @type {Boolean} * @default true */ var enableCollisionDetection = true weak fileprivate var _scene: Scene! weak fileprivate var _globe: Globe? = nil fileprivate var _ellipsoid: Ellipsoid! let _aggregator: CameraEventAggregator class MovementState: StartEndPosition { var startPosition = Cartesian2() var endPosition = Cartesian2() var motion = Cartesian2() var active = false } fileprivate var _intertiaMovementStates = [String: MovementState]() /* this._tweens = new TweenCollection(); this._tween = undefined; */ fileprivate var _horizontalRotationAxis: Cartesian3? = nil fileprivate var _tiltCenterMousePosition = Cartesian2(x: -1.0, y: -1.0) fileprivate var _tiltCenter = Cartesian3() fileprivate var _rotateMousePosition = Cartesian2(x: -1.0, y: -1.0) fileprivate var _rotateStartPosition = Cartesian3() fileprivate var _strafeStartPosition = Cartesian3() fileprivate var _zoomMouseStart = Cartesian2() fileprivate var _zoomWorldPosition = Cartesian3() fileprivate var _tiltCVOffMap = false fileprivate var _tiltOnEllipsoid = false fileprivate var _looking = false fileprivate var _rotating = false fileprivate var _strafing = false fileprivate var _zoomingOnVector = false fileprivate var _rotatingZoom = false var projection: MapProjection { return _scene.mapProjection } fileprivate var _maxCoord: Cartesian3 // Constants, Make any of these public?*/ fileprivate var _zoomFactor = 5.0 fileprivate var _rotateFactor = 0.0 fileprivate var _rotateRateRangeAdjustment = 0.0 fileprivate var _maximumRotateRate = 1.77 fileprivate var _minimumRotateRate = 1.0 / 5000.0 fileprivate var _minimumZoomRate = 20.0 fileprivate var _maximumZoomRate = 5906376272000.0 // distance from the Sun to Pluto in meters. init(scene: Scene) { _scene = scene _maxCoord = _scene.mapProjection.project(Cartographic(longitude: .pi, latitude: .pi/2)) _aggregator = CameraEventAggregator(/*layer: _scene.context.layer*/) } func decay(_ time: Double, coefficient: Double) -> Double { if (time < 0) { return 0.0 } let tau = (1.0 - coefficient) * 25.0 return exp(-tau * time) } func sameMousePosition(_ movement: StartEndPosition) -> Bool { return movement.startPosition.equalsEpsilon(movement.endPosition, relativeEpsilon: Math.Epsilon14) } // If the time between mouse down and mouse up is not between // these thresholds, the camera will not move with inertia. // This value is probably dependent on the browser and/or the // hardware. Should be investigated further. var inertiaMaxClickTimeThreshold = 0.4 func maintainInertia(_ type: CameraEventType, modifier: KeyboardEventModifier? = nil, decayCoef: Double, action: (_ startPosition: Cartesian2, _ movement: MouseMovement) -> (), lastMovementName: String) { var state = _intertiaMovementStates[lastMovementName] if state == nil { state = MovementState() _intertiaMovementStates[lastMovementName] = state! } let movementState = state! let ts = _aggregator.getButtonPressTime(type, modifier: modifier) let tr = _aggregator.getButtonReleaseTime(type, modifier: modifier) if let ts = ts, let tr = tr { let threshold = tr.timeIntervalSinceReferenceDate - ts.timeIntervalSinceReferenceDate let now = Date() let fromNow = now.timeIntervalSinceReferenceDate - tr.timeIntervalSinceReferenceDate if threshold < inertiaMaxClickTimeThreshold { let d = decay(fromNow, coefficient: decayCoef) if !movementState.active { let lastMovement = _aggregator.getLastMovement(type, modifier: modifier) if lastMovement == nil || sameMousePosition(lastMovement!) { return } movementState.motion.x = (lastMovement!.endPosition.x - lastMovement!.startPosition.x) * 0.5 movementState.motion.y = (lastMovement!.endPosition.y - lastMovement!.startPosition.y) * 0.5 movementState.startPosition = lastMovement!.startPosition movementState.endPosition = movementState.startPosition.add(movementState.motion.multiplyBy(scalar: d)) movementState.active = true } else { movementState.startPosition = movementState.endPosition movementState.endPosition = movementState.startPosition.add(movementState.motion.multiplyBy(scalar: d)) movementState.motion = Cartesian2.zero } // If value from the decreasing exponential function is close to zero, // the end coordinates may be NaN. if (movementState.endPosition.x == Double.nan || movementState.endPosition.y == Double.nan) || sameMousePosition(movementState) { movementState.active = false return } if !_aggregator.isButtonDown(type, modifier: modifier) { let startPosition = _aggregator.getStartMousePosition(type, modifier: modifier) action( startPosition, MouseMovement( startPosition: movementState.startPosition, endPosition: movementState.endPosition, angleStartPosition: Cartesian2(), angleEndPosition: Cartesian2(), prevAngle: 0.0, valid: true ) ) } } } else { movementState.active = false } } func reactToInput(_ enabled: Bool, eventTypes: [CameraEvent], action: (_ startPosition: Cartesian2, _ movement: MouseMovement) -> (), inertiaConstant: Double, inertiaStateName: String? = nil) { var movement: MouseMovement? = nil for eventType in eventTypes { let type = eventType.type let modifier = eventType.modifier if _aggregator.isMoving(type, modifier: modifier) { movement = _aggregator.getMovement(type, modifier: modifier) } let startPosition = _aggregator.getStartMousePosition(type, modifier: modifier) if enableInputs && enabled { if movement != nil { action(startPosition, movement!) } else if inertiaConstant < 1.0 && inertiaStateName != nil { maintainInertia(type, modifier: modifier, decayCoef: inertiaConstant, action: action, lastMovementName: inertiaStateName!) } } } } /*var scratchZoomPickRay = new Ray(); var scratchPickCartesian = new Cartesian3(); var scratchZoomOffset = new Cartesian2(); var scratchZoomDirection = new Cartesian3(); var scratchCenterPixel = new Cartesian2(); var scratchCenterPosition = new Cartesian3(); var scratchPositionNormal = new Cartesian3(); var scratchPickNormal = new Cartesian3(); var scratchZoomAxis = new Cartesian3(); var scratchCameraPositionNormal = new Cartesian3();*/ func handleZoom(_ startPosition: Cartesian2, movement: MouseMovement, zoomFactor: Double, distanceMeasure: Double, unitPositionDotDirection: Double? = nil) { var percentage = 1.0 if let unitPositionDotDirection = unitPositionDotDirection { percentage = Math.clamp(abs(unitPositionDotDirection), min: 0.25, max: 1.0) } // distanceMeasure should be the height above the ellipsoid. // The zoomRate slows as it approaches the surface and stops minimumZoomDistance above it. let minHeight = minimumZoomDistance * percentage let maxHeight = maximumZoomDistance let minDistance = distanceMeasure - minHeight let zoomRate = Math.clamp(zoomFactor * minDistance, min: _minimumZoomRate, max: _maximumZoomRate) let diff = movement.endPosition.y - movement.startPosition.y let rangeWindowRatio = min(diff / Double(_scene.drawableHeight), maximumMovementRatio) var distance = zoomRate * rangeWindowRatio if distance > 0.0 && abs(distanceMeasure - minHeight) < 1.0 { return } if distance < 0.0 && abs(distanceMeasure - maxHeight) < 1.0 { return } if distanceMeasure - distance < minHeight { distance = distanceMeasure - minHeight - 1.0 } else if distanceMeasure - distance > maxHeight { distance = distanceMeasure - maxHeight } let camera = _scene.camera let mode = _scene.mode let pickedPosition: Cartesian3? if _globe != nil { pickedPosition = mode != .scene2D ? pickGlobe(startPosition) : camera.getPickRay(startPosition).origin } else { pickedPosition = nil } if pickedPosition == nil { camera.zoomIn(distance) return } let sameStartPosition = startPosition == _zoomMouseStart var zoomingOnVector = _zoomingOnVector var rotatingZoom = _rotatingZoom if !sameStartPosition { _zoomMouseStart = startPosition _zoomWorldPosition = pickedPosition! zoomingOnVector = _zoomingOnVector == false rotatingZoom = _rotatingZoom == false } var zoomOnVector = mode == .columbusView if !sameStartPosition || rotatingZoom { if mode == SceneMode.scene2D { let worldPosition = _zoomWorldPosition let endPosition = camera.position // FIXME: Object if !(worldPosition == endPosition) /*&& camera.positionCartographic.height < object._maxCoord.x * 2.0*/ { let direction = worldPosition.subtract(endPosition).normalize() let d = worldPosition.distance(endPosition) * distance / (camera.getMagnitude() * 0.5) camera.move(direction, amount: d * 0.5) // FIXME: savedX /*if (camera.position.x < 0.0 && savedX > 0.0) || (camera.position.x > 0.0 && savedX < 0.0) { pickedPosition = camera.getPickRay(startPosition, scratchZoomPickRay).origin; object._zoomWorldPosition = Cartesian3.clone(pickedPosition, object._zoomWorldPosition); }*/ } } else if mode == .scene3D { let cameraPositionNormal = camera.position.normalize() if camera.positionCartographic.height < 3000.0 && abs(camera.direction.dot(cameraPositionNormal)) < 0.6 { zoomOnVector = true } else { let centerPixel = Cartesian2(x: Double(_scene.drawableWidth) / 2.0, y: Double(_scene.drawableHeight) / 2.0) let centerPosition = pickGlobe(centerPixel) if centerPosition != nil { let positionNormal = centerPosition!.normalize() let pickedNormal = _zoomWorldPosition.normalize() let dotProduct = pickedNormal.dot(positionNormal) if dotProduct > 0.0 { let angle = Math.acosClamped(dotProduct) let axis = pickedNormal.cross(positionNormal) let denom = abs(angle) > Math.toRadians(20.0) ? camera.positionCartographic.height * 0.75 : camera.positionCartographic.height - distance let scalar = distance / denom; camera.rotate(axis, angle: angle * scalar) } } else { zoomOnVector = true } } } _rotatingZoom = !zoomOnVector } if (!sameStartPosition && zoomOnVector) || zoomingOnVector { let zoomMouseStart = SceneTransforms.wgs84ToWindowCoordinates(_scene, position: _zoomWorldPosition) let ray: Ray if mode != .columbusView && startPosition == _zoomMouseStart && zoomMouseStart != nil { ray = camera.getPickRay(zoomMouseStart!) } else { ray = camera.getPickRay(startPosition) } var rayDirection = ray.direction if mode == .columbusView { rayDirection = Cartesian3(x: rayDirection.y, y: rayDirection.z, z: rayDirection.x) } camera.move(rayDirection, amount: distance) _zoomingOnVector = true } else { camera.zoomIn(distance) } } /* var translate2DStart = new Ray(); var translate2DEnd = new Ray(); var scratchTranslateP0 = new Cartesian3(); var scratchTranslateP1 = new Cartesian3(); function translate2D(controller, startPosition, movement) { var scene = controller._scene; var camera = scene.camera; var start = camera.getPickRay(movement.startPosition, translate2DStart).origin; var end = camera.getPickRay(movement.endPosition, translate2DEnd).origin; var direction = Cartesian3.subtract(start, end, scratchTranslateP0); var distance = Cartesian3.magnitude(direction); if (distance > 0.0) { Cartesian3.normalize(direction, direction); camera.move(direction, distance); } } function zoom2D(controller, startPosition, movement) { if (defined(movement.distance)) { movement = movement.distance; } var scene = controller._scene; var camera = scene.camera; handleZoom(controller, startPosition, movement, controller._zoomFactor, camera.getMagnitude()); } */ func update2D() { /* + if (!Matrix4.equals(Matrix4.IDENTITY, controller._scene.camera.transform)) { + reactToInput(controller, controller.enableZoom, controller.zoomEventTypes, zoom2D, controller.inertiaZoom, '_lastInertiaZoomMovement'); + } else { + reactToInput(controller, controller.enableTranslate, controller.translateEventTypes, translate2D, controller.inertiaTranslate, '_lastInertiaTranslateMovement'); + reactToInput(controller, controller.enableZoom, controller.zoomEventTypes, zoom2D, controller.inertiaZoom, '_lastInertiaZoomMovement'); } tweens.update();*/ } func pickGlobe(_ mousePosition: Cartesian2) -> Cartesian3? { let camera = _scene.camera if _globe == nil { return nil } var depthIntersection: Cartesian3? if _scene.pickPositionSupported { depthIntersection = _scene.pickPosition(mousePosition) } let ray = camera.getPickRay(mousePosition) let rayIntersection = _globe!.pick(ray, scene: _scene) let pickDistance = depthIntersection?.distance(camera.positionWC) ?? Double.infinity let rayDistance = rayIntersection?.distance(camera.positionWC) ?? Double.infinity if pickDistance < rayDistance { return depthIntersection } return rayIntersection } /* var translateCVStartRay = new Ray(); var translateCVEndRay = new Ray(); var translateCVStartPos = new Cartesian3(); var translateCVEndPos = new Cartesian3(); var translatCVDifference = new Cartesian3(); var translateCVOrigin = new Cartesian3(); var translateCVPlane = new Plane(Cartesian3.ZERO, 0.0); var translateCVStartMouse = new Cartesian2(); var translateCVEndMouse = new Cartesian2(); if (!Cartesian3.equals(startPosition, controller._translateMousePosition)) { controller._looking = false; } if (!Cartesian3.equals(startPosition, controller._strafeMousePosition)) { controller._strafing = false; } if (controller._looking) { look3D(controller, startPosition, movement); return; } if (controller._strafing) { strafe(controller, startPosition, movement); return; } var scene = controller._scene; var camera = scene.camera; var startMouse = Cartesian2.clone(movement.startPosition, translateCVStartMouse); var endMouse = Cartesian2.clone(movement.endPosition, translateCVEndMouse); var startRay = camera.getPickRay(startMouse, translateCVStartRay); var origin = Cartesian3.clone(Cartesian3.ZERO, translateCVOrigin); var normal = Cartesian3.UNIT_X; var globePos; if (camera.position.z < controller.minimumPickingTerrainHeight) { globePos = pickGlobe(controller, startMouse, translateCVStartPos); if (defined(globePos)) { origin.x = globePos.x; } } if (origin.x > camera.position.z && defined(globePos)) { Cartesian3.clone(globePos, controller._strafeStartPosition); controller._strafing = true; strafe(controller, startPosition, movement); controller._strafeMousePosition = Cartesian2.clone(startPosition, controller._strafeMousePosition); return; } var plane = Plane.fromPointNormal(origin, normal, translateCVPlane); startRay = camera.getPickRay(startMouse, translateCVStartRay); var startPlanePos = IntersectionTests.rayPlane(startRay, plane, translateCVStartPos); var endRay = camera.getPickRay(endMouse, translateCVEndRay); var endPlanePos = IntersectionTests.rayPlane(endRay, plane, translateCVEndPos); if (!defined(startPlanePos) || !defined(endPlanePos)) { controller._looking = true; look3D(controller, startPosition, movement); Cartesian2.clone(startPosition, controller._translateMousePosition); return; } var diff = Cartesian3.subtract(startPlanePos, endPlanePos, translatCVDifference); var temp = diff.x; diff.x = diff.y; diff.y = diff.z; diff.z = temp; var mag = Cartesian3.magnitude(diff); if (mag > CesiumMath.EPSILON6) { Cartesian3.normalize(diff, diff); camera.move(diff, mag); } var rotateCVWindowPos = new Cartesian2(); var rotateCVWindowRay = new Ray(); var rotateCVCenter = new Cartesian3(); var rotateCVVerticalCenter = new Cartesian3(); var rotateCVTransform = new Matrix4(); var rotateCVVerticalTransform = new Matrix4(); var rotateCVOrigin = new Cartesian3(); var rotateCVPlane = new Plane(Cartesian3.ZERO, 0.0); var rotateCVCartesian3 = new Cartesian3(); var rotateCVCart = new Cartographic(); var rotateCVOldTransform = new Matrix4(); var rotateCVQuaternion = new Quaternion(); var rotateCVMatrix = new Matrix3(); function rotateCV(controller, startPosition, movement) { if (defined(movement.angleAndHeight)) { movement = movement.angleAndHeight; } if (!Cartesian2.equals(startPosition, controller._tiltCenterMousePosition)) { controller._tiltCVOffMap = false; controller._looking = false; } if (controller._looking) { look3D(controller, startPosition, movement); return; } var scene = controller._scene; var camera = scene.camera; var maxCoord = controller._maxCoord; var onMap = Math.abs(camera.position.x) - maxCoord.x < 0 && Math.abs(camera.position.y) - maxCoord.y < 0; if (controller._tiltCVOffMap || !onMap || camera.position.z > controller.minimumPickingTerrainHeight) { controller._tiltCVOffMap = true; rotateCVOnPlane(controller, startPosition, movement); } else { rotateCVOnTerrain(controller, startPosition, movement); } } function rotateCVOnPlane(controller, startPosition, movement) { var scene = controller._scene; var camera = scene.camera; var canvas = scene.canvas; var windowPosition = rotateCVWindowPos; windowPosition.x = canvas.clientWidth / 2; windowPosition.y = canvas.clientHeight / 2; var ray = camera.getPickRay(windowPosition, rotateCVWindowRay); var normal = Cartesian3.UNIT_X; var position = ray.origin; var direction = ray.direction; var scalar; var normalDotDirection = Cartesian3.dot(normal, direction); if (Math.abs(normalDotDirection) > CesiumMath.EPSILON6) { scalar = -Cartesian3.dot(normal, position) / normalDotDirection; } if (!defined(scalar) || scalar <= 0.0) { controller._looking = true; look3D(controller, startPosition, movement); Cartesian2.clone(startPosition, controller._tiltCenterMousePosition); return; } var center = Cartesian3.multiplyBy(scalar: direction, scalar, rotateCVCenter); Cartesian3.add(position, center, center); var projection = scene.mapProjection; var ellipsoid = projection.ellipsoid; Cartesian3.fromElements(center.y, center.z, center.x, center); var cart = projection.unproject(center, rotateCVCart); ellipsoid.cartographicToCartesian(cart, center); var transform = Transforms.eastNorthUpToFixedFrame(center, ellipsoid, rotateCVTransform); var oldGlobe = controller._globe; var oldEllipsoid = controller._ellipsoid; controller._globe = undefined; controller._ellipsoid = Ellipsoid.UNIT_SPHERE; controller._rotateFactor = 1.0; controller._rotateRateRangeAdjustment = 1.0; var oldTransform = Matrix4.clone(camera.transform, rotateCVOldTransform); camera._setTransform(transform); rotate3D(controller, startPosition, movement, Cartesian3.UNIT_Z); camera._setTransform(oldTransform); controller._globe = oldGlobe; controller._ellipsoid = oldEllipsoid; var radius = oldEllipsoid.maximumRadius; controller._rotateFactor = 1.0 / radius; controller._rotateRateRangeAdjustment = radius; } function rotateCVOnTerrain(controller, startPosition, movement) { var ellipsoid = controller._ellipsoid; var scene = controller._scene; var camera = scene.camera; var center; var ray; var normal = Cartesian3.UNIT_X; if (Cartesian2.equals(startPosition, controller._tiltCenterMousePosition)) { center = Cartesian3.clone(controller._tiltCenter, rotateCVCenter); } else { if (camera.position.z < controller.minimumPickingTerrainHeight) { center = pickGlobe(controller, startPosition, rotateCVCenter); } if (!defined(center)) { ray = camera.getPickRay(startPosition, rotateCVWindowRay); var position = ray.origin; var direction = ray.direction; var scalar; var normalDotDirection = Cartesian3.dot(normal, direction); if (Math.abs(normalDotDirection) > CesiumMath.EPSILON6) { scalar = -Cartesian3.dot(normal, position) / normalDotDirection; } if (!defined(scalar) || scalar <= 0.0) { controller._looking = true; look3D(controller, startPosition, movement); Cartesian2.clone(startPosition, controller._tiltCenterMousePosition); return; } center = Cartesian3.multiplyBy(scalar: direction, scalar, rotateCVCenter); Cartesian3.add(position, center, center); } Cartesian2.clone(startPosition, controller._tiltCenterMousePosition); Cartesian3.clone(center, controller._tiltCenter); } var canvas = scene.canvas; var windowPosition = rotateCVWindowPos; windowPosition.x = canvas.clientWidth / 2; windowPosition.y = controller._tiltCenterMousePosition.y; ray = camera.getPickRay(windowPosition, rotateCVWindowRay); var origin = Cartesian3.clone(Cartesian3.ZERO, rotateCVOrigin); origin.x = center.x; var plane = Plane.fromPointNormal(origin, normal, rotateCVPlane); var verticalCenter = IntersectionTests.rayPlane(ray, plane, rotateCVVerticalCenter); var projection = camera._projection; ellipsoid = projection.ellipsoid; Cartesian3.fromElements(center.y, center.z, center.x, center); var cart = projection.unproject(center, rotateCVCart); ellipsoid.cartographicToCartesian(cart, center); var transform = Transforms.eastNorthUpToFixedFrame(center, ellipsoid, rotateCVTransform); var verticalTransform; if (defined(verticalCenter)) { Cartesian3.fromElements(verticalCenter.y, verticalCenter.z, verticalCenter.x, verticalCenter); cart = projection.unproject(verticalCenter, rotateCVCart); ellipsoid.cartographicToCartesian(cart, verticalCenter); verticalTransform = Transforms.eastNorthUpToFixedFrame(verticalCenter, ellipsoid, rotateCVVerticalTransform); } else { verticalTransform = transform; } var oldGlobe = controller._globe; var oldEllipsoid = controller._ellipsoid; controller._globe = undefined; controller._ellipsoid = Ellipsoid.UNIT_SPHERE; controller._rotateFactor = 1.0; controller._rotateRateRangeAdjustment = 1.0; var constrainedAxis = Cartesian3.UNIT_Z; var oldTransform = Matrix4.clone(camera.transform, rotateCVOldTransform); camera._setTransform(transform); var tangent = Cartesian3.cross(Cartesian3.UNIT_Z, Cartesian3.normalize(camera.position, rotateCVCartesian3), rotateCVCartesian3); var dot = Cartesian3.dot(camera.right, tangent); rotate3D(controller, startPosition, movement, constrainedAxis, false, true); camera._setTransform(verticalTransform); if (dot < 0.0) { if (movement.startPosition.y > movement.endPosition.y) { constrainedAxis = undefined; } var oldConstrainedAxis = camera.constrainedAxis; camera.constrainedAxis = undefined; rotate3D(controller, startPosition, movement, constrainedAxis, true, false); camera.constrainedAxis = oldConstrainedAxis; } else { rotate3D(controller, startPosition, movement, constrainedAxis, true, false); } if (defined(camera.constrainedAxis)) { var right = Cartesian3.cross(camera.direction, camera.constrainedAxis, tilt3DCartesian3); if (!Cartesian3.equalsEpsilon(right, Cartesian3.ZERO, CesiumMath.EPSILON6)) { if (Cartesian3.dot(right, camera.right) < 0.0) { Cartesian3.negate(right, right); } Cartesian3.cross(right, camera.direction, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.up, camera.up); Cartesian3.normalize(camera.right, camera.right); } } camera.setTransform(oldTransform); controller._globe = oldGlobe; controller._ellipsoid = oldEllipsoid; var radius = oldEllipsoid.maximumRadius; controller._rotateFactor = 1.0 / radius; controller._rotateRateRangeAdjustment = radius; var originalPosition = Cartesian3.clone(camera.positionWC, rotateCVCartesian3); adjustHeightForTerrain(controller); if (!Cartesian3.equals(camera.positionWC, originalPosition)) { camera._setTransform(verticalTransform); camera.worldToCameraCoordinatesPoint(originalPosition, originalPosition); var magSqrd = Cartesian3.magnitudeSquared(originalPosition); if (Cartesian3.magnitudeSquared(camera.position) > magSqrd) { Cartesian3.normalize(camera.position, camera.position); Cartesian3.multiplyBy(scalar: camera.position, Math.sqrt(magSqrd), camera.position); } var angle = Cartesian3.angleBetween(originalPosition, camera.position); var axis = Cartesian3.cross(originalPosition, camera.position, originalPosition); Cartesian3.normalize(axis, axis); var quaternion = Quaternion.fromAxisAngle(axis, angle, rotateCVQuaternion); var rotation = Matrix3.fromQuaternion(quaternion, rotateCVMatrix); Matrix3.multiplyByVector(rotation, camera.direction, camera.direction); Matrix3.multiplyByVector(rotation, camera.up, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.cross(camera.right, camera.direction, camera.up); camera._setTransform(oldTransform); } } var zoomCVWindowPos = new Cartesian2(); var zoomCVWindowRay = new Ray(); var zoomCVIntersection = new Cartesian3(); function zoomCV(controller, startPosition, movement) { if (defined(movement.distance)) { movement = movement.distance; } var scene = controller._scene; var camera = scene.camera; var canvas = scene.canvas; var windowPosition = zoomCVWindowPos; windowPosition.x = canvas.clientWidth / 2; windowPosition.y = canvas.clientHeight / 2; var ray = camera.getPickRay(windowPosition, zoomCVWindowRay); var intersection; if (camera.position.z < controller.minimumPickingTerrainHeight) { intersection = pickGlobe(controller, windowPosition, zoomCVIntersection); } var distance; if (defined(intersection)) { distance = Cartesian3.distance(ray.origin, intersection); } else { var normal = Cartesian3.UNIT_X; var position = ray.origin; var direction = ray.direction; distance = -Cartesian3.dot(normal, position) / Cartesian3.dot(normal, direction); } handleZoom(controller, startPosition, movement, controller._zoomFactor, distance); } */ func updateCV() { /*var scene = controller._scene; var camera = scene.camera; if (!Matrix4.equals(Matrix4.IDENTITY, camera.transform)) { reactToInput(controller, controller.enableRotate, controller.rotateEventTypes, rotate3D, controller.inertiaSpin, '_lastInertiaSpinMovement'); reactToInput(controller, controller.enableZoom, controller.zoomEventTypes, zoom3D, controller.inertiaZoom, '_lastInertiaZoomMovement'); } else { var tweens = controller._tweens; if (controller._aggregator.anyButtonDown) { tweens.removeAll(); } reactToInput(controller, controller.enableTilt, controller.tiltEventTypes, rotateCV, controller.inertiaSpin, '_lastInertiaTiltMovement'); reactToInput(controller, controller.enableTranslate, controller.translateEventTypes, translateCV, controller.inertiaTranslate, '_lastInertiaTranslateMovement'); reactToInput(controller, controller.enableZoom, controller.zoomEventTypes, zoomCV, controller.inertiaZoom, '_lastInertiaZoomMovement'); reactToInput(controller, controller.enableLook, controller.lookEventTypes, look3D); if (!controller._aggregator.anyButtonDown && (!defined(controller._lastInertiaZoomMovement) || !controller._lastInertiaZoomMovement.active) && (!defined(controller._lastInertiaTranslateMovement) || !controller._lastInertiaTranslateMovement.active) && !tweens.contains(controller._tween)) { var tween = camera.createCorrectPositionTween(controller.bounceAnimationTime); if (defined(tween)) { controller._tween = tweens.add(tween); } } tweens.update(); }*/ } /* var scratchStrafeRay = new Ray(); var scratchStrafePlane = new Plane(Cartesian3.ZERO, 0.0); var scratchStrafeIntersection = new Cartesian3(); var scratchStrafeDirection = new Cartesian3(); */ func strafe (_ startPosition: Cartesian2, movement: MouseMovement) { let camera = _scene.camera guard let mouseStartPosition = pickGlobe(movement.startPosition) else { return } let mousePosition = movement.endPosition let ray = camera.getPickRay(mousePosition) var direction = camera.direction if _scene.mode == .columbusView { direction = Cartesian3(x: direction.z, y: direction.x, z: direction.y) } let plane = Plane(fromPoint: mouseStartPosition, normal: direction) guard let intersection = IntersectionTests.rayPlane(ray, plane: plane) else { return } direction = mouseStartPosition.subtract(intersection) if _scene.mode == SceneMode.columbusView { direction = Cartesian3(x: direction.y, y: direction.z, z: direction.x) } camera.position = camera.position.add(direction) } func spin3D(_ startPosition: Cartesian2, movement: MouseMovement) { let camera = _scene.camera if camera.transform != Matrix4.identity { rotate3D(startPosition, movement: movement) return } var magnitude: Double = 0.0 let up = _ellipsoid.geodeticSurfaceNormal(camera.position) guard let height = _ellipsoid.cartesianToCartographic(camera.positionWC)?.height else { return } var mousePos: Cartesian3? = nil var tangentPick = false if _globe != nil && height < minimumPickingTerrainHeight { mousePos = pickGlobe(movement.startPosition) if let mousePos = mousePos { let ray = camera.getPickRay(movement.startPosition) let normal = _ellipsoid.geodeticSurfaceNormal(mousePos) tangentPick = abs(ray.direction.dot(normal)) < 0.05 if tangentPick && !_looking { _rotating = false _strafing = true } } } if startPosition == _rotateMousePosition { if _looking { look3D(startPosition, movement: movement, rotationAxis: up) } else if _rotating { rotate3D(startPosition, movement: movement) } else if _strafing { _strafeStartPosition = mousePos! strafe(startPosition, movement: movement) } else { magnitude = _rotateStartPosition.magnitude let ellipsoid = Ellipsoid(x: magnitude, y: magnitude, z: magnitude) pan3D(startPosition, movement: movement, ellipsoid: ellipsoid) } return } else { _looking = false _rotating = false _strafing = false } if _globe != nil && height < minimumPickingTerrainHeight { if mousePos != nil { if camera.position.magnitude < mousePos!.magnitude { _strafeStartPosition = mousePos! _strafing = true strafe(startPosition, movement: movement) } else { magnitude = mousePos!.magnitude let radii = Cartesian3(x: magnitude, y: magnitude, z: magnitude) let ellipsoid = Ellipsoid(radii: radii) pan3D(startPosition, movement: movement, ellipsoid: ellipsoid) _rotateStartPosition = mousePos! } } else { _looking = true look3D(startPosition, movement: movement, rotationAxis: up) } } else if let spin3DPick = camera.pickEllipsoid(movement.startPosition, ellipsoid: _ellipsoid) { pan3D(startPosition, movement: movement, ellipsoid: _ellipsoid) _rotateStartPosition = spin3DPick } else if height > minimumTrackBallHeight { _rotating = true rotate3D(startPosition, movement: movement) } else { _looking = true look3D(startPosition, movement: movement, rotationAxis: up) } _rotateMousePosition = startPosition } func rotate3D(_ startPosition: Cartesian2, movement: MouseMovement, constrainedAxis: Cartesian3? = nil, rotateOnlyVertical: Bool = false, rotateOnlyHorizontal: Bool = false) { let camera = _scene.camera let oldAxis = camera.constrainedAxis if constrainedAxis != nil { camera.constrainedAxis = constrainedAxis } let rho = camera.position.magnitude var rotateRate = _rotateFactor * (rho - _rotateRateRangeAdjustment) if rotateRate > _maximumRotateRate { rotateRate = _maximumRotateRate } if rotateRate < _minimumRotateRate { rotateRate = _minimumRotateRate } var phiWindowRatio = (movement.startPosition.x - movement.endPosition.x) / Double(_scene.context.width) var thetaWindowRatio = (movement.startPosition.y - movement.endPosition.y) / Double(_scene.context.width) phiWindowRatio = min(phiWindowRatio, maximumMovementRatio) thetaWindowRatio = min(thetaWindowRatio, maximumMovementRatio) let deltaPhi = rotateRate * phiWindowRatio * .pi * 2.0 let deltaTheta = rotateRate * thetaWindowRatio * .pi if !rotateOnlyVertical { camera.rotateRight(deltaPhi) } if !rotateOnlyHorizontal { camera.rotateUp(deltaTheta) } camera.constrainedAxis = oldAxis } func pan3D(_ startPosition: Cartesian2, movement: MouseMovement, ellipsoid: Ellipsoid) { let camera = _scene.camera let startMousePosition = movement.startPosition let endMousePosition = movement.endPosition var p0: Cartesian3! = camera.pickEllipsoid(startMousePosition, ellipsoid: ellipsoid) var p1: Cartesian3! = camera.pickEllipsoid(endMousePosition, ellipsoid: ellipsoid) if p0 == nil || p1 == nil { _rotating = true rotate3D(startPosition, movement: movement) return } let c0 = camera.worldToCameraCoordinates(Cartesian4(x: p0.x, y: p0.y, z: p0.z, w: 1.0)) //var pan3DP0 = Cartesian4.clone(Cartesian4.UNIT_W); let c1 = camera.worldToCameraCoordinates(Cartesian4(x: p1.x, y: p1.y, z: p1.z, w: 1.0)) //var pan3DP1 = Cartesian4.clone(Cartesian4.UNIT_W); p0 = Cartesian3(cartesian4: c0) p1 = Cartesian3(cartesian4: c1) if camera.constrainedAxis == nil { p0 = p0.normalize() p1 = p1.normalize() let dot = p0.dot(p1) let axis = p0.cross(p1) if dot < 1.0 && !axis.equalsEpsilon(Cartesian3.zero, relativeEpsilon: Math.Epsilon14) { // dot is in [0, 1] let angle = acos(dot) camera.rotate(axis, angle: angle) } } else { let basis0 = camera.constrainedAxis! let basis1 = basis0.mostOrthogonalAxis().cross(basis0).normalize() let basis2 = basis0.cross(basis1) let startRho = p0.magnitude let startDot = basis0.dot(p0) let startTheta = acos(startDot / startRho) let startRej = p0.subtract(basis0.multiplyBy(scalar: startDot)).normalize() let endRho = p1.magnitude let endDot = basis0.dot(p1) let endTheta = acos(endDot / endRho) let endRej = p1.subtract(basis0.multiplyBy(scalar: endDot)).normalize() var startPhi = acos(startRej.dot(basis1)) if startRej.dot(basis2) < 0 { startPhi = Math.TwoPi - startPhi } var endPhi = acos(endRej.dot(basis1)) if endRej.dot(basis2) < 0 { endPhi = Math.TwoPi - endPhi } let deltaPhi = startPhi - endPhi let east: Cartesian3 if basis0.equalsEpsilon(camera.position, relativeEpsilon: Math.Epsilon2) { east = camera.right } else { east = basis0.cross(camera.position) } let planeNormal = basis0.cross(east) let side0 = planeNormal.dot(p0.subtract(basis0)) let side1 = planeNormal.dot(p1.subtract(basis0)) let deltaTheta: Double if side0 > 0 && side1 > 0 { deltaTheta = endTheta - startTheta } else if side0 > 0 && side1 <= 0 { if camera.position.dot(basis0) > 0 { deltaTheta = -startTheta - endTheta } else { deltaTheta = startTheta + endTheta } } else { deltaTheta = startTheta - endTheta; } camera.rotateRight(deltaPhi) camera.rotateUp(deltaTheta) } } func zoom3D(_ startPosition: Cartesian2, movement: MouseMovement) { //FIXME: movement.distance /*if (defined(movement.distance)) { movement = movement.distance; }*/ let camera = _scene.camera let windowPosition = Cartesian2( x: Double(_scene.drawableWidth) / 2.0, y: Double(_scene.drawableHeight) / 2.0 ) let ray = _scene.camera.getPickRay(windowPosition) guard let height = _ellipsoid.cartesianToCartographic(camera.position)?.height else { return } var intersection: Cartesian3? = nil if _globe != nil && height < minimumPickingTerrainHeight { intersection = pickGlobe(windowPosition) } let distance: Double if intersection != nil { distance = ray.origin.distance(intersection!) } else { distance = height } let unitPosition = camera.position.normalize() handleZoom(startPosition, movement: movement, zoomFactor: _zoomFactor, distanceMeasure: distance, unitPositionDotDirection: unitPosition.dot(camera.direction)) } /* var tilt3DWindowPos = new Cartesian2(); var tilt3DRay = new Ray(); var tilt3DCenter = new Cartesian3(); var tilt3DVerticalCenter = new Cartesian3(); var tilt3DTransform = new Matrix4(); var tilt3DVerticalTransform = new Matrix4(); var tilt3DCartesian3 = new Cartesian3(); var tilt3DOldTransform = new Matrix4(); var tilt3DQuaternion = new Quaternion(); var tilt3DMatrix = new Matrix3(); var tilt3DCart = new Cartographic(); var tilt3DLookUp = new Cartesian3(); */ func tilt3D(_ startPosition: Cartesian2, movement: MouseMovement) { let camera = _scene.camera if camera.transform != Matrix4.identity { return } /*if (defined(movement.angleAndHeight)) { movement = movement.angleAndHeight; }*/ if startPosition != _tiltCenterMousePosition { _tiltOnEllipsoid = false _looking = false } if _looking { let up = _ellipsoid.geodeticSurfaceNormal(camera.position) look3D(startPosition, movement: movement, rotationAxis: up) return } guard let cartographic = _ellipsoid.cartesianToCartographic(camera.position) else { return } if _tiltOnEllipsoid || cartographic.height > minimumCollisionTerrainHeight { _tiltOnEllipsoid = true tilt3DOnEllipsoid(startPosition, movement: movement) } else { tilt3DOnTerrain(startPosition, movement: movement) } } func tilt3DOnEllipsoid(_ startPosition: Cartesian2, movement: MouseMovement) { /*let camera = _scene.camera let minHeight = minimumZoomDistance * 0.25 let height = _ellipsoid.cartesianToCartographic(camera.positionWC)!.height if height - minHeight - 1.0 < Math.Epsilon3 && movement.endPosition.y - movement.startPosition.y < 0 { return } let windowPosition = Cartesian2(x: Double(_scene.drawableWidth) / 2.0, y: Double(_scene.drawableHeight) / 2.0) let ray = camera.getPickRay(windowPosition) let center: Cartesian3 if let intersection = IntersectionTests.rayEllipsoid(ray, ellipsoid: _ellipsoid) { center = ray.getPoint(intersection.start) } else if height > minimumTrackBallHeight { guard let grazingAltitudeLocation = IntersectionTests.grazingAltitudeLocation(ray, _ellipsoid) else { return } let grazingAltitudeCart = ellipsoid.cartesianToCartographic(grazingAltitudeLocation) grazingAltitudeCart.height = 0.0 center = ellipsoid.cartographicToCartesian(grazingAltitudeCart) } else { controller._looking = true; var up = controller._ellipsoid.geodeticSurfaceNormal(camera.position, tilt3DLookUp); look3D(controller, startPosition, movement, up); Cartesian2.clone(startPosition, controller._tiltCenterMousePosition); return; } var transform = Transforms.eastNorthUpToFixedFrame(center, ellipsoid, tilt3DTransform); var oldGlobe = controller._globe; var oldEllipsoid = controller._ellipsoid; controller._globe = undefined; controller._ellipsoid = Ellipsoid.UNIT_SPHERE; controller._rotateFactor = 1.0; controller._rotateRateRangeAdjustment = 1.0; var oldTransform = Matrix4.clone(camera.transform, tilt3DOldTransform); camera._setTransform(transform); rotate3D(controller, startPosition, movement, Cartesian3.UNIT_Z); camera._setTransform(oldTransform); controller._globe = oldGlobe; controller._ellipsoid = oldEllipsoid; var radius = oldEllipsoid.maximumRadius; controller._rotateFactor = 1.0 / radius; controller._rotateRateRangeAdjustment = radius;*/ } func tilt3DOnTerrain(_ startPosition: Cartesian2, movement: MouseMovement) { /*var ellipsoid = controller._ellipsoid; var scene = controller._scene; var camera = scene.camera; var center; var ray; var intersection; if (Cartesian2.equals(startPosition, controller._tiltCenterMousePosition)) { center = Cartesian3.clone(controller._tiltCenter, tilt3DCenter); } else { center = pickGlobe(controller, startPosition, tilt3DCenter); if (!defined(center)) { ray = camera.getPickRay(startPosition, tilt3DRay); intersection = IntersectionTests.rayEllipsoid(ray, ellipsoid); if (!defined(intersection)) { var cartographic = ellipsoid.cartesianToCartographic(camera.position, tilt3DCart); if (cartographic.height <= controller.minimumTrackBallHeight) { controller._looking = true; var up = controller._ellipsoid.geodeticSurfaceNormal(camera.position, tilt3DLookUp); look3D(controller, startPosition, movement, up); Cartesian2.clone(startPosition, controller._tiltCenterMousePosition); } return; } center = Ray.getPoint(ray, intersection.start, tilt3DCenter); } Cartesian2.clone(startPosition, controller._tiltCenterMousePosition); Cartesian3.clone(center, controller._tiltCenter); } var canvas = scene.canvas; var windowPosition = tilt3DWindowPos; windowPosition.x = canvas.clientWidth / 2; windowPosition.y = controller._tiltCenterMousePosition.y; ray = camera.getPickRay(windowPosition, tilt3DRay); var mag = Cartesian3.magnitude(center); var radii = Cartesian3.fromElements(mag, mag, mag, scratchRadii); var newEllipsoid = Ellipsoid.fromCartesian3(radii, scratchEllipsoid); intersection = IntersectionTests.rayEllipsoid(ray, newEllipsoid); if (!defined(intersection)) { return; } var t = Cartesian3.magnitude(ray.origin) > mag ? intersection.start : intersection.stop; var verticalCenter = Ray.getPoint(ray, t, tilt3DVerticalCenter); var transform = Transforms.eastNorthUpToFixedFrame(center, ellipsoid, tilt3DTransform); var verticalTransform = Transforms.eastNorthUpToFixedFrame(verticalCenter, newEllipsoid, tilt3DVerticalTransform); var oldGlobe = controller._globe; var oldEllipsoid = controller._ellipsoid; controller._globe = undefined; controller._ellipsoid = Ellipsoid.UNIT_SPHERE; controller._rotateFactor = 1.0; controller._rotateRateRangeAdjustment = 1.0; var constrainedAxis = Cartesian3.UNIT_Z; var oldTransform = Matrix4.clone(camera.transform, tilt3DOldTransform); camera._setTransform(transform); var tangent = Cartesian3.cross(verticalCenter, camera.positionWC, tilt3DCartesian3); var dot = Cartesian3.dot(camera.rightWC, tangent); rotate3D(controller, startPosition, movement, constrainedAxis, false, true); camera._setTransform(verticalTransform); if (dot < 0.0) { if (movement.startPosition.y > movement.endPosition.y) { constrainedAxis = undefined; } var oldConstrainedAxis = camera.constrainedAxis; camera.constrainedAxis = undefined; rotate3D(controller, startPosition, movement, constrainedAxis, true, false); camera.constrainedAxis = oldConstrainedAxis; } else { rotate3D(controller, startPosition, movement, constrainedAxis, true, false); } if (defined(camera.constrainedAxis)) { var right = Cartesian3.cross(camera.direction, camera.constrainedAxis, tilt3DCartesian3); if (!Cartesian3.equalsEpsilon(right, Cartesian3.ZERO, CesiumMath.EPSILON6)) { if (Cartesian3.dot(right, camera.right) < 0.0) { Cartesian3.negate(right, right); } Cartesian3.cross(right, camera.direction, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.up, camera.up); Cartesian3.normalize(camera.right, camera.right); } } camera._setTransform(oldTransform); controller._globe = oldGlobe; controller._ellipsoid = oldEllipsoid; var radius = oldEllipsoid.maximumRadius; controller._rotateFactor = 1.0 / radius; controller._rotateRateRangeAdjustment = radius; var originalPosition = Cartesian3.clone(camera.positionWC, tilt3DCartesian3); adjustHeightForTerrain(controller); if (!Cartesian3.equals(camera.positionWC, originalPosition)) { camera._setTransform(verticalTransform); camera.worldToCameraCoordinatesPoint(originalPosition, originalPosition); var magSqrd = Cartesian3.magnitudeSquared(originalPosition); if (Cartesian3.magnitudeSquared(camera.position) > magSqrd) { Cartesian3.normalize(camera.position, camera.position); Cartesian3.multiplyBy(scalar: camera.position, Math.sqrt(magSqrd), camera.position); } var angle = Cartesian3.angleBetween(originalPosition, camera.position); var axis = Cartesian3.cross(originalPosition, camera.position, originalPosition); Cartesian3.normalize(axis, axis); var quaternion = Quaternion.fromAxisAngle(axis, angle, tilt3DQuaternion); var rotation = Matrix3.fromQuaternion(quaternion, tilt3DMatrix); Matrix3.multiplyByVector(rotation, camera.direction, camera.direction); Matrix3.multiplyByVector(rotation, camera.up, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.cross(camera.right, camera.direction, camera.up); camera._setTransform(oldTransform); }*/ } /* var look3DStartPos = new Cartesian2(); var look3DEndPos = new Cartesian2(); var look3DStartRay = new Ray(); var look3DEndRay = new Ray(); var look3DNegativeRot = new Cartesian3(); var look3DTan = new Cartesian3(); */ func look3D(_ startPosition: Cartesian2, movement: MouseMovement, rotationAxis: Cartesian3) { /*var scene = controller._scene; var camera = scene.camera; var startPos = look3DStartPos; startPos.x = movement.startPosition.x; startPos.y = 0.0; var endPos = look3DEndPos; endPos.x = movement.endPosition.x; endPos.y = 0.0; var start = camera.getPickRay(startPos, look3DStartRay).direction; var end = camera.getPickRay(endPos, look3DEndRay).direction; var angle = 0.0; var dot = Cartesian3.dot(start, end); if (dot < 1.0) { // dot is in [0, 1] angle = Math.acos(dot); } angle = (movement.startPosition.x > movement.endPosition.x) ? -angle : angle; var horizontalRotationAxis = controller._horizontalRotationAxis; if (defined(rotationAxis)) { camera.look(rotationAxis, -angle); } else if (defined(horizontalRotationAxis)) { camera.look(horizontalRotationAxis, -angle); } else { camera.lookLeft(angle); } startPos.x = 0.0; startPos.y = movement.startPosition.y; endPos.x = 0.0; endPos.y = movement.endPosition.y; start = camera.getPickRay(startPos, look3DStartRay).direction; end = camera.getPickRay(endPos, look3DEndRay).direction; angle = 0.0; dot = Cartesian3.dot(start, end); if (dot < 1.0) { // dot is in [0, 1] angle = Math.acos(dot); } angle = (movement.startPosition.y > movement.endPosition.y) ? -angle : angle; rotationAxis = defaultValue(rotationAxis, horizontalRotationAxis); if (defined(rotationAxis)) { var direction = camera.direction; var negativeRotationAxis = Cartesian3.negate(rotationAxis, look3DNegativeRot); var northParallel = Cartesian3.equalsEpsilon(direction, rotationAxis, CesiumMath.EPSILON2); var southParallel = Cartesian3.equalsEpsilon(direction, negativeRotationAxis, CesiumMath.EPSILON2); if ((!northParallel && !southParallel)) { dot = Cartesian3.dot(direction, rotationAxis); var angleToAxis = CesiumMath.acosClamped(dot); if (angle > 0 && angle > angleToAxis) { angle = angleToAxis - CesiumMath.EPSILON4; } dot = Cartesian3.dot(direction, negativeRotationAxis); angleToAxis = CesiumMath.acosClamped(dot); if (angle < 0 && -angle > angleToAxis) { angle = -angleToAxis + CesiumMath.EPSILON4; } var tangent = Cartesian3.cross(rotationAxis, direction, look3DTan); camera.look(tangent, angle); } else if ((northParallel && angle < 0) || (southParallel && angle > 0)) { camera.look(camera.right, -angle); } } else { camera.lookUp(angle); }*/ } func update3D() { reactToInput(enableRotate, eventTypes: rotateEventTypes, action: spin3D, inertiaConstant: inertiaSpin, inertiaStateName: "_lastInertiaSpinMovement") reactToInput(enableZoom, eventTypes: zoomEventTypes, action: zoom3D, inertiaConstant: inertiaZoom, inertiaStateName: "_lastInertiaZoomMovement") reactToInput(enableTilt, eventTypes: tiltEventTypes, action: tilt3D, inertiaConstant: inertiaSpin, inertiaStateName: "_lastInertiaTiltMovement") //reactToInput(enableLook, lookEventTypes, look3D) } func adjustHeightForTerrain() { if !enableCollisionDetection { return } let mode = _scene.mode if _globe == nil || mode == .scene2D || mode == .morphing { return } let camera = _scene.camera guard let ellipsoid = _ellipsoid else { return } let projection = _scene.mapProjection var transform: Matrix4? = nil var mag: Double = 0.0 if (camera.transform != Matrix4.identity) { transform = camera.transform mag = camera.position.magnitude camera._setTransform(Matrix4.identity) } var cartographic: Cartographic if mode == SceneMode.scene3D { cartographic = ellipsoid.cartesianToCartographic(camera.position)! } else { cartographic = projection.unproject(camera.position) } var heightUpdated = false if cartographic.height < minimumCollisionTerrainHeight { if let height = _globe!.getHeight(cartographic) { var height = height height += minimumZoomDistance if cartographic.height < height { cartographic.height = height if mode == .scene3D { camera.position = ellipsoid.cartographicToCartesian(cartographic) } else { camera.position = projection.project(cartographic) } heightUpdated = true } } } if transform != nil { camera._setTransform(transform!) if (heightUpdated) { camera.position = camera.position.normalize() camera.direction = camera.position.negate() camera.position = camera.position.multiplyBy(scalar: max(mag, minimumZoomDistance)) camera.direction = camera.direction.normalize() camera.right = camera.direction.cross(camera.up) camera.up = camera.right.cross(camera.direction) } } } /** * @private */ func update () { if _scene.camera.transform != Matrix4.identity { _globe = nil _ellipsoid = Ellipsoid.unitSphere } else { _globe = _scene.globe _ellipsoid = (_globe != nil ? _globe!.ellipsoid : _scene.mapProjection.ellipsoid) } let radius = _ellipsoid.maximumRadius _rotateFactor = 1.0 / radius _rotateRateRangeAdjustment = radius let mode = _scene.mode if mode == .scene2D { update2D() } else if mode == .columbusView { _horizontalRotationAxis = Cartesian3.unitZ updateCV() } else if mode == .scene3D { _horizontalRotationAxis = nil update3D() } adjustHeightForTerrain() _aggregator.reset() } /* /** * Returns true if this object was destroyed; otherwise, false. * <br /><br /> * If this object was destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. * * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>. * * @see ScreenSpaceCameraController#destroy */ ScreenSpaceCameraController.prototype.isDestroyed = function() { return false; }; /** * Removes mouse listeners held by this object. * <br /><br /> * Once an object is destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore, * assign the return value (<code>undefined</code>) to the object as done in the example. * * @returns {undefined} * * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called. * * @see ScreenSpaceCameraController#isDestroyed * * @example * controller = controller && controller.destroy(); */ ScreenSpaceCameraController.prototype.destroy = function() { this._tweens.removeAll(); this._pinchHandler = this._pinchHandler && this._pinchHandler.destroy(); return destroyObject(this); }; return ScreenSpaceCameraController; }); */ }
apache-2.0
82e5552ebb3bd5c25d8aa9d13cdfda64
38.550881
208
0.626879
4.470792
false
false
false
false
SoneeJohn/WWDC
WWDC/ChromeCastPlaybackProvider.swift
1
12042
// // ChromeCastPlaybackProvider.swift // WWDC // // Created by Guilherme Rambo on 03/06/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa import ChromeCastCore import PlayerUI import CoreMedia private struct ChromeCastConstants { static let defaultHost = "devstreaming-cdn.apple.com" static let chromeCastSupportedHost = "devstreaming.apple.com" static let placeholderImageURL = URL(string: "https://wwdc.io/images/placeholder.jpg")! } private extension URL { /// The default host returned by Apple's WWDC app has invalid headers for ChromeCast streaming, /// this rewrites the URL to use another host which returns a valid response for the ChromeCast device /// Calling this on a non-streaming URL doesn't change the URL var chromeCastSupportedURL: URL? { guard var components = URLComponents(url: self, resolvingAgainstBaseURL: false) else { return nil } if components.host == ChromeCastConstants.defaultHost { components.scheme = "http" components.host = ChromeCastConstants.chromeCastSupportedHost } return components.url } } final class ChromeCastPlaybackProvider: NSObject, PUIExternalPlaybackProvider { fileprivate weak var consumer: PUIExternalPlaybackConsumer? private lazy var scanner: CastDeviceScanner = CastDeviceScanner() /// Initializes the external playback provider to start playing the media at the specified URL /// /// - Parameter consumer: The consumer that's going to be using this provider init(consumer: PUIExternalPlaybackConsumer) { self.consumer = consumer status = PUIExternalPlaybackMediaStatus() super.init() NotificationCenter.default.addObserver(self, selector: #selector(deviceListDidChange), name: CastDeviceScanner.DeviceListDidChange, object: scanner) scanner.startScanning() } deinit { NotificationCenter.default.removeObserver(self) } /// Whether this provider only works with a remote URL or can be used with only the `AVPlayer` instance var requiresRemoteMediaUrl: Bool { return true } /// The name of the external playback system (ex: "AirPlay") static var name: String { return "ChromeCast" } /// An image to be used as the icon in the UI var icon: NSImage { return #imageLiteral(resourceName: "chromecast") } var image: NSImage { return #imageLiteral(resourceName: "chromecast-large") } var info: String { return "To control playback, use the Google Home app on your phone" } /// The current media status var status: PUIExternalPlaybackMediaStatus /// Return whether this playback system is available var isAvailable: Bool = false /// Tells the external playback provider to play func play() { } /// Tells the external playback provider to pause func pause() { } /// Tells the external playback provider to seek to the specified time (in seconds) func seek(to timestamp: Double) { } /// Tells the external playback provider to change the volume on the device /// /// - Parameter volume: The volume (value between 0 and 1) func setVolume(_ volume: Float) { } // MARK: - ChromeCast management fileprivate var client: CastClient? fileprivate var mediaPlayerApp: CastApp? fileprivate var currentSessionId: Int? fileprivate var mediaStatusRefreshTimer: Timer? @objc private func deviceListDidChange() { isAvailable = scanner.devices.count > 0 buildMenu() } private func buildMenu() { let menu = NSMenu() scanner.devices.forEach { device in let item = NSMenuItem(title: device.name, action: #selector(didSelectDeviceOnMenu), keyEquivalent: "") item.representedObject = device item.target = self if device.hostName == selectedDevice?.hostName { item.state = .on } menu.addItem(item) } // send menu to consumer consumer?.externalPlaybackProvider(self, deviceSelectionMenuDidChangeWith: menu) } private var selectedDevice: CastDevice? @objc private func didSelectDeviceOnMenu(_ sender: NSMenuItem) { guard let device = sender.representedObject as? CastDevice else { return } scanner.stopScanning() if let previousClient = client { if let app = mediaPlayerApp { client?.stop(app: app) } mediaStatusRefreshTimer?.invalidate() mediaStatusRefreshTimer = nil previousClient.disconnect() client = nil } if device.hostName == selectedDevice?.hostName { sender.state = .off consumer?.externalPlaybackProviderDidInvalidatePlaybackSession(self) } else { selectedDevice = device sender.state = .on client = CastClient(device: device) client?.delegate = self client?.connect() consumer?.externalPlaybackProviderDidBecomeCurrent(self) } } fileprivate var mediaForChromeCast: CastMedia? { guard let originalMediaURL = consumer?.remoteMediaUrl else { NSLog("Unable to play because the player view doesn't have a remote media URL associated with it") return nil } guard let mediaURL = originalMediaURL.chromeCastSupportedURL else { NSLog("Error generating ChromeCast-compatible media URL") return nil } #if DEBUG NSLog("Original media URL = \(originalMediaURL)") NSLog("ChromeCast-compatible media URL = \(mediaURL)") #endif let posterURL: URL if let poster = consumer?.mediaPosterUrl { posterURL = poster } else { posterURL = ChromeCastConstants.placeholderImageURL } let title: String if let playerTitle = consumer?.mediaTitle { title = playerTitle } else { title = "WWDC Video" } let streamType: CastMediaStreamType if let isLive = consumer?.mediaIsLiveStream { streamType = isLive ? .live : .buffered } else { streamType = .buffered } var currentTime: Double = 0 if let playerTime = consumer?.player?.currentTime() { currentTime = Double(CMTimeGetSeconds(playerTime)) } let media = CastMedia(title: title, url: mediaURL, poster: posterURL, contentType: "application/vnd.apple.mpegurl", streamType: streamType, autoplay: true, currentTime: currentTime) return media } fileprivate func loadMediaOnDevice() { guard let media = mediaForChromeCast else { return } guard let app = mediaPlayerApp else { return } guard let url = consumer?.remoteMediaUrl else { return } #if DEBUG NSLog("Load media \(url) with \(app.sessionId)") #endif var currentTime: Double = 0 if let playerTime = consumer?.player?.currentTime() { currentTime = Double(CMTimeGetSeconds(playerTime)) } #if DEBUG NSLog("Current time is \(currentTime)s") #endif client?.load(media: media, with: app) { [weak self] error, mediaStatus in guard let mediaStatus = mediaStatus, error == nil else { if let error = error { WWDCAlert.show(with: error) #if DEBUG NSLog("Error loading media: \(error)") #endif } return } self?.currentSessionId = mediaStatus.mediaSessionId #if DEBUG NSLog("Media loaded. SessionID: \(mediaStatus.mediaSessionId).") NSLog("MEDIA STATUS:\n\(mediaStatus)") #endif self?.startFetchingMediaStatusPeriodically() } } fileprivate func startFetchingMediaStatusPeriodically() { mediaStatusRefreshTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(requestMediaStatus), userInfo: nil, repeats: true) } @objc private func requestMediaStatus(_ sender: Any?) { do { try client?.requestStatus() } catch { #if DEBUG NSLog("Error requesting status from connected device: \(error)") #endif } } } extension ChromeCastPlaybackProvider: CastClientDelegate { public func castClient(_ client: CastClient, willConnectTo device: CastDevice) { #if DEBUG NSLog("Will connect to \(device.name) (\(device.id))") #endif } public func castClient(_ client: CastClient, didConnectTo device: CastDevice) { #if DEBUG NSLog("Did connect to \(device.name) (\(device.id))") #endif #if DEBUG NSLog("Launching app \(CastAppIdentifier.defaultMediaPlayer.rawValue)") #endif client.launch(appId: .defaultMediaPlayer) { [weak self] error, app in guard let app = app, error == nil else { if let error = error { #if DEBUG NSLog("Error launching app \(CastAppIdentifier.defaultMediaPlayer.rawValue): \(error)") #endif WWDCAlert.show(with: error) } return } #if DEBUG NSLog("App \(CastAppIdentifier.defaultMediaPlayer.rawValue) launched. Session: \(app.sessionId)") #endif self?.mediaPlayerApp = app self?.loadMediaOnDevice() } } public func castClient(_ client: CastClient, didDisconnectFrom device: CastDevice) { consumer?.externalPlaybackProviderDidInvalidatePlaybackSession(self) } public func castClient(_ client: CastClient, connectionTo device: CastDevice, didFailWith error: NSError) { WWDCAlert.show(with: error) consumer?.externalPlaybackProviderDidInvalidatePlaybackSession(self) } public func castClient(_ client: CastClient, deviceStatusDidChange status: CastStatus) { self.status.volume = Float(status.volume) consumer?.externalPlaybackProviderDidChangeMediaStatus(self) } public func castClient(_ client: CastClient, mediaStatusDidChange status: CastMediaStatus) { let rate: Float = status.playerState == .playing ? 1.0 : 0.0 let newStatus = PUIExternalPlaybackMediaStatus(rate: rate, volume: self.status.volume, currentTime: status.currentTime) self.status = newStatus #if DEBUG NSLog("# MEDIA STATUS #\n\(newStatus)\n---") #endif consumer?.externalPlaybackProviderDidChangeMediaStatus(self) } }
bsd-2-clause
fbcf0eb9294bba1926c34b627bb99ed0
31.720109
158
0.572461
5.453351
false
false
false
false
i-schuetz/clojushop_client_ios_swift
clojushop_client_ios/CartViewController.swift
1
9577
// // CartViewController.swift // // Created by ischuetz on 08/06/2014. // Copyright (c) 2014 ivanschuetz. All rights reserved. // import Foundation class CartViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate, SingleSelectionControllerDelegate { @IBOutlet var tableView: UITableView! @IBOutlet var emptyCartView: UIView! @IBOutlet var totalContainer: UIView! @IBOutlet var buyView: UIView! @IBOutlet var totalView: UILabel! var quantityPicker: SingleSelectionViewController! var quantityPickerPopover: UIPopoverController! var items: CartItem[] = [] var showingController: Bool! = false //quickfix to avoid reloading when coming back from quantity controller... needs correct implementation var currency: Currency! init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.tabBarItem.title = "Cart" } func clearCart() { self.items.removeAll(keepCapacity: false) self.tableView.reloadData() var a : String[] = [] a.removeAll(keepCapacity: false) } func onRetrievedItems(items: CartItem[]) { self.items = items if (items.count == 0) { self.showCartState(true) } else { self.showCartState(false) self.tableView.reloadData() self.onModifyLocalCartContent() } } func showCartState(empty: Bool) { emptyCartView.hidden = !empty } func onModifyLocalCartContent() { if (items.count == 0) { totalView.text = "0" //just for consistency self.showCartState(true) } else { //TODO server calculates this //TODO multiple currencies //for now we assume all the items have the same currency let currencyId = items[0].currency self.totalView.text = CurrencyManager.sharedCurrencyManager().getFormattedPrice(String(self.getTotalPrice(items)), currencyId: currencyId) self.showCartState(false) self.tableView.reloadData() } } func getTotalPrice(cartItems:CartItem[]) -> Double { //TODO reduce // ??? // why this doesn't compile "Could not find member 'price'", but it appears in autocompletion? // return cartItems.reduce(0, combine: {$0 + ($1.price * $1.quantity)}) // var total:Double = 0 for cartItem in cartItems { let price:Double = NSString(string: cartItem.price).doubleValue let quantity:Double = Double(cartItem.quantity) total = total + (price * quantity) } return total } override func viewDidLoad() { super.viewDidLoad() let nib = UINib(nibName: "CartItemCell", bundle: nil) self.tableView.registerNib(nib, forCellReuseIdentifier: "CartItemCell") self.emptyCartView.hidden = true } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if !self.showingController { self.requestItems() } self.showingController = false self.adjustLayout() } func requestItems() { self.setProgressHidden(false, transparent: false) DataStore.sharedDataStore().getCart( {(items:CartItem[]!) -> Void in self.setProgressHidden(true, transparent: false) self.onRetrievedItems(items) }, failureHandler: {(Int) -> Bool in self.setProgressHidden(true, transparent: false) self.emptyCartView.hidden = false return false }) } func adjustLayout() { self.navigationController.navigationBar.translucent = false; // self.navigationController.toolbar.translucent = NO; // self.tabBarController.tabBar.translucent = NO; // if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) // self.edgesForExtendedLayout = UIRectEdgeNone; let screenBounds: CGRect = UIScreen.mainScreen().bounds let h:Float = screenBounds.size.height - (CGRectGetHeight(self.tabBarController.tabBar.frame) + CGRectGetHeight(self.navigationController.navigationBar.frame) + CGRectGetHeight(self.buyView.frame)) self.tableView.frame = CGRectMake(0, CGRectGetHeight(self.buyView.frame), self.tableView.frame.size.width, h) ; // self.tableView.contentInset = UIEdgeInsetsMake(0., 0., CGRectGetHeight(self.navigationController.navigationBar.frame) + CGRectGetHeight(self.tabBarController.tabBar.frame) + CGRectGetHeight(self.buyView.frame), 0); } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell! { let cellIdentifier:String = "CartItemCell" let cell: CartItemCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as CartItemCell cell.selectionStyle = UITableViewCellSelectionStyle.None let item: CartItem = items[indexPath.row] cell.productName.text = item.name cell.productDescr.text = item.descr cell.productBrand.text = item.seller cell.productPrice.text = CurrencyManager.sharedCurrencyManager().getFormattedPrice(item.price, currencyId: item.currency) cell.quantityField.text = String(item.quantity) cell.controller = self cell.tableView = self.tableView cell.productImg.setImageWithURL(NSURL.URLWithString(item.imgList)) return cell } func tableView(tableView:UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> Double { return 133 } func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { if editingStyle == UITableViewCellEditingStyle.Delete { let item:CartItem = items[indexPath.row] DataStore.sharedDataStore().removeFromCart(item.id, successHandler: {() -> Void in self.items.removeAtIndex(indexPath.row) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) self.onModifyLocalCartContent() }, failureHandler: {(Int) -> Bool in return false}) } } func setQuantity(sender: AnyObject, atIndexPath ip:NSIndexPath) { let selectedCartItem:CartItem = items[ip.row] let quantities:Int[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] let cartItemsForQuantitiesDialog:CartQuantityItem[] = self.wrapQuantityItemsForDialog(quantities) let selectQuantityController:SingleSelectionViewController = SingleSelectionViewController(style: UITableViewStyle.Plain) //FIXME // println(cartItemsForQuantitiesDialog.count) //11 // var test:SingleSelectionItem[] = cartItemsForQuantitiesDialog as SingleSelectionItem[] // println(test.count) //this prints 318701632 selectQuantityController.items = cartItemsForQuantitiesDialog println(selectQuantityController.items.count) selectQuantityController.delegate = self selectQuantityController.baseObject = selectedCartItem self.showingController = true self.presentModalViewController(selectQuantityController, animated: true) } func wrapQuantityItemsForDialog(quantities: Int[]) -> CartQuantityItem[] { return quantities.map {(let q) -> CartQuantityItem in CartQuantityItem(quantity: q)} } @IBAction func onBuyPress(sender: UIButton) { let paymentViewController:PaymentViewController = PaymentViewController(nibName:"CSPaymentViewController", bundle:nil) paymentViewController.totalValue = self.getTotalPrice(items) // TODO // paymentViewController.currency = [CSCurrency alloc]initWithId:<#(int)#> format:<#(NSString *)#>; self.navigationController.pushViewController(paymentViewController, animated: true) } func selectedItem(item: SingleSelectionItem, baseObject:AnyObject) { var cartItem = baseObject as CartItem //TODO use generics let quantity:Int = item.getWrappedItem() as Int //TODO use generics self.setProgressHidden(false, transparent:true) DataStore.sharedDataStore().setCartQuantity(cartItem.id, quantity: quantity, {() -> Void in cartItem.quantity = quantity self.tableView.reloadData() self.onModifyLocalCartContent() self.setProgressHidden(true, transparent:true) }, failureHandler: {(Int) -> Bool in return false self.setProgressHidden(true, transparent: true) }) } }
apache-2.0
783d486ffa06c672c84a2df27fa502d8
34.474074
224
0.626814
5.276584
false
false
false
false
chess-cf/chess.cf-ios
Chess/GameViewController.swift
1
17988
// // GameViewController.swift // Chess // // Created by Alex Studnička on 25.10.14. // Copyright (c) 2014 Alex Studnička. All rights reserved. // import UIKit import QuartzCore import SceneKit class GameViewController: UIViewController { var game: GameInfo! var detailGame: DetailGameInfo! // var aiGame = true var ai: ChessAI! var waiting = false @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var overlayView: UIView! @IBOutlet weak var waitingView: UIView! @IBOutlet weak var resultView: UIView! @IBOutlet weak var scnView: SCNView! let piecesScene = SCNScene(named: "art.scnassets/chess_pieces.dae")! var board: SCNNode! var squares: SCNNode! var lightNode: SCNNode! var activePiece: (piece: BoardPiece, pos: Position)! var helpers = [(Position, MoveType)]() override func viewDidLoad() { super.viewDidLoad() self.title = "\(game.whitePlayer) × \(game.blackPlayer)" self.activityIndicator.alpha = 1 self.activityIndicator.startAnimating() if game.isAI { dispatch_after(0.1) { self.ai = ChessAI() var initialBoard = [[BoardPiece?]]() for initialRow in self.ai.board.board { var newRow = [BoardPiece?]() for piece in initialRow { newRow.append(piece.toBoardPiece()) } initialBoard.append(newRow) } var hints = [Move]() for hintMove in self.ai.board.genMoves() { if !self.ai.board.move(hintMove).inCheck(.k) { hints.append(hintMove) } } self.detailGame = DetailGameInfo(board: initialBoard, hints: hints) self.createScene() } } else { API.gameInfo(game.uid, completionHandler: { loadedGameInfo in self.detailGame = loadedGameInfo API.openChannel(self.game.uid, channelToken: self.detailGame.channelToken) self.createScene() }) } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) API.closeChannel() } // -------------------------------- // MARK: - Create scene func createScene() { let scene = SCNScene() let cameraSphere = SCNNode() let cameraNode = SCNNode() cameraNode.camera = SCNCamera() cameraNode.camera?.yFov = 20 cameraNode.position = SCNVector3(x: 0, y: 0, z: 45) cameraSphere.eulerAngles = SCNVector3(x: Float(M_PI/6), y: 0, z: 0) cameraSphere.addChildNode(cameraNode) scene.rootNode.addChildNode(cameraSphere) let lightSphere = SCNNode() lightNode = SCNNode() lightNode.light = SCNLight() lightNode.light!.type = SCNLightTypeSpot lightNode.position = SCNVector3(x: 0, y: 0, z: 16) lightSphere.eulerAngles = SCNVector3(x: Float(M_PI/8), y: 0, z: 0) lightSphere.addChildNode(lightNode) scene.rootNode.addChildNode(lightSphere) let ambientLightNode = SCNNode() ambientLightNode.light = SCNLight() ambientLightNode.light!.type = SCNLightTypeAmbient ambientLightNode.light!.color = UIColor.lightGrayColor() scene.rootNode.addChildNode(ambientLightNode) // -------------------------------- let boardMaterial = SCNMaterial() boardMaterial.diffuse.contents = UIImage(named: "art.scnassets/board.jpg") let woodMaterial = SCNMaterial() woodMaterial.diffuse.contents = UIImage(named: "art.scnassets/wood.jpg") woodMaterial.diffuse.wrapS = .Repeat woodMaterial.diffuse.wrapT = .Repeat let floor = SCNFloor() let floorNode = SCNNode(geometry: floor) floorNode.geometry?.firstMaterial = SCNMaterial() floorNode.geometry?.firstMaterial?.doubleSided = true floorNode.geometry?.firstMaterial?.diffuse.contents = UIColor(red: 229/255, green: 206/255, blue: 183/255, alpha: 1) floorNode.rotation = SCNVector4(x: 1, y: 0, z: 0, w: Float(M_PI_2)) scene.rootNode.addChildNode(floorNode) board = SCNNode(geometry: SCNBox(width: 8.5, height: 8.5, length: 0.5, chamferRadius: 0.05)) board.geometry?.materials = [boardMaterial, woodMaterial, woodMaterial, woodMaterial, woodMaterial, woodMaterial] scene.rootNode.addChildNode(board) // -------------------------------- squares = SCNNode() board.addChildNode(squares) for (var row = 0; row < 8; row++) { for (var col = 0; col < 8; col++) { let square = SCNNode(geometry: SCNBox(width: 1, height: 1, length: 0.1, chamferRadius: 0)) square.name = "Square-\(row)-\(col)" let position = getPositionForRow(row, col: col) square.position = SCNVector3(x: position.x, y: position.y, z: 0.25) square.geometry?.firstMaterial = SCNMaterial() square.geometry?.firstMaterial?.transparency = 0 square.geometry?.firstMaterial?.diffuse.contents = UIColor.blueColor() squares.addChildNode(square) } } // -------------------------------- scnView.scene = scene scnView.playing = true // scnView.loops = true // scnView.allowsCameraControl = true // scnView.showsStatistics = true scnView.backgroundColor = UIColor.darkGrayColor() scnView.antialiasingMode = .Multisampling4X let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:") var gestureRecognizers = scnView.gestureRecognizers ?? [] gestureRecognizers.append(tapGesture) scnView.gestureRecognizers = gestureRecognizers // -------------------------------- // board.runAction(SCNAction.repeatActionForever(SCNAction.rotateByAngle(CGFloat(M_PI), aroundAxis: SCNVector3(x: 0, y: 0, z: 1), duration: 10))) gameBoardArray = detailGame.board drawBoard() // -------------------------------- UIView.animateWithDuration(0.5, delay: 1, options: [], animations: { self.activityIndicator.alpha = 0 self.scnView.alpha = 1 if !self.detailGame.opponent_played { self.waiting = true self.overlayView.alpha = 1 self.move(Position(0, 0), user: true) } }) { completed in self.scnView.playing = false } } // -------------------------------- // MARK: - Tap func handleTap(gestureRecognize: UIGestureRecognizer) { let p = gestureRecognize.locationInView(scnView) if let hitResults = scnView.hitTest(p, options: nil) as NSArray! { // println("hitResults: \(hitResults)") var touchedSquare = false for result in hitResults { // println("result: \(result)") if result.node.name?.hasPrefix("Square") != true { continue } touchedSquare = true var row = -1, col = -1 let comps = result.node.name?.componentsSeparatedByString("-") if let comps = comps { if comps.count > 2 { row = Int(comps[1])! col = Int(comps[2])! } } let position = Position(row, col) var moved = false for move in helpers { if move.0 == position { self.move(position, user: true) moved = true break } } if !moved { if let piece = gameBoardArray[row][col] { if piece.color == game.color { resetHelperLights() // lightNode.runAction(SCNAction.moveTo(SCNVector3(x: result.node.position.x, y: result.node.position.y, z: 2), duration: 0.25)) activePiece = (piece, position) playSound(SOUND_CLICK) if let hints = detailGame.hints{ for hint in hints { if hint.from == position { if let _ = getPiece(hint.to) { addHelper(hint.to, type: .Take) } else { addHelper(hint.to, type: .Move) } } } } } else { resetMove() } } else { resetMove() } } } if !touchedSquare { resetMove() } } } // -------------------------------- // MARK: - Helpers func resetHelperLights() { // for light in helperLights.childNodes as [SCNNode] { //// light.runAction(SCNAction.sequence([SCNAction.fadeOutWithDuration(0.25), SCNAction.removeFromParentNode()])) // light.removeFromParentNode() // } SCNTransaction.begin() SCNTransaction.setAnimationDuration(0.25) for square in squares.childNodes { // square.geometry?.firstMaterial?.diffuse.contents = UIColor.clearColor() square.geometry?.firstMaterial?.transparency = 0 } SCNTransaction.commit() helpers = [(Position, MoveType)]() } func resetMove() { resetHelperLights() activePiece = nil // lightNode.runAction(SCNAction.moveTo(SCNVector3(x: 0, y: 0, z: 15), duration: 0.25)) } func addHelper(pos: Position, type: MoveType) { // let position = getPositionForRow(row, col: col) // let helperLightNode = SCNNode() // helperLightNode.light = SCNLight() // helperLightNode.light!.type = SCNLightTypeSpot // helperLightNode.light!.color = UIColor.blueColor() // helperLightNode.position = SCNVector3(x: position.x, y: position.y, z: 1) // helperLights.addChildNode(helperLightNode) let square = board.childNodeWithName("Square-\(pos.row)-\(pos.col)", recursively: true) switch type { case .Move: square?.geometry?.firstMaterial?.diffuse.contents = UIColor.blueColor() case .Take: square?.geometry?.firstMaterial?.diffuse.contents = UIColor.redColor() } SCNTransaction.begin() SCNTransaction.setAnimationDuration(0.25) // square?.geometry?.firstMaterial?.diffuse.contents = UIColor.blueColor() square?.geometry?.firstMaterial?.transparency = 0.5 SCNTransaction.commit() helpers.append(pos, type) } func getPositionForRow(row: Int, col: Int) -> (x: Float, y: Float) { return (-3.33 + Float(col)*0.95, -3.33 + Float(7-row)*0.95) } func getPosition(pos: Position) -> (x: Float, y: Float) { return getPositionForRow(pos.row, col: pos.col) } func modelForPieceType(pieceType: PieceType) -> SCNNode { var name: String var z: Float switch pieceType { case .Rook: name = "Rook" z = 0.7 case .Knight: name = "Knight" z = 0.75 case .Bishop: name = "Bishop" z = 0.8 case .Queen: name = "Queen" z = 1.1 case .King: name = "King" z = 1.1 case .Pawn: name = "Pawn" z = 0.6 } let node = piecesScene.rootNode.childNodeWithName(name, recursively: true)! var newNode: SCNNode if let geometry = node.geometry { newNode = SCNNode(geometry: geometry.copy() as? SCNGeometry) } else if pieceType == .Knight { let group = piecesScene.rootNode.childNodeWithName(name, recursively: true)! newNode = SCNNode() let part1 = group.childNodes[0].childNodes[0] newNode.addChildNode(SCNNode(geometry: part1.geometry?.copy() as? SCNGeometry)) let part2 = group.childNodes[0].childNodes[1] newNode.addChildNode(SCNNode(geometry: part2.geometry?.copy() as? SCNGeometry)) } else { newNode = SCNNode() } newNode.position = SCNVector3(x: 0, y: 0, z: z) newNode.scale = SCNVector3(x: 0.0033, y: 0.0033, z: 0.0033) newNode.rotation = SCNVector4(x: 1, y: 0, z: 0, w: Float(M_PI_2)) return newNode } func modelForPiece(piece: BoardPiece) -> SCNNode { var node: SCNNode switch piece.color { case .White: node = modelForPieceType(piece.type) // recolor let whitePiece = piecesScene.rootNode.childNodeWithName("White", recursively: true)! node.geometry?.firstMaterial = whitePiece.geometry?.firstMaterial // rotate node.eulerAngles = SCNVector3(x: Float(M_PI_2), y: 0, z: Float(M_PI)) case .Black: node = modelForPieceType(piece.type) } return node } func drawBoard() { //gameBoardArray let array = gameBoardArray for row in 0..<array.count { for col in 0..<array[row].count { if let piece = array[row][col] { let node = modelForPiece(piece) let position = getPositionForRow(row, col: col) node.position = SCNVector3(x: position.x, y: position.y, z: node.position.z) board.addChildNode(node) gameBoardArray[row][col] = BoardPiece(piece.color, piece.type, node) } } } } // -------------------------------- // MARK: - Move func move(pos: Position, user: Bool) { var originalPiece: BoardPiece? if !waiting { if activePiece == nil { print("NO_PIECE") return } let piece = activePiece.piece let activePos = activePiece.pos // Piece being taken originalPiece = getPiece(pos) // Castling var castlingMove: Move? if activePiece.piece.type == .King { if game.color == .Black { if piece.color == .Black && activePos == Position(7, 3) { if pos == Position(7, 1) { castlingMove = Move(from: Position(7, 0), to: Position(7, 2)) } else if pos == Position(7, 5) { castlingMove = Move(from: Position(7, 7), to: Position(7, 4)) } } else if piece.color == .White && activePos == Position(0, 3) { if pos == Position(0, 1) { castlingMove = Move(from: Position(0, 0), to: Position(0, 2)) } else if pos == Position(0, 5) { castlingMove = Move(from: Position(0, 7), to: Position(0, 4)) } } } else { if piece.color == .White && activePos == Position(7, 4) { if pos == Position(7, 2) { castlingMove = Move(from: Position(7, 0), to: Position(7, 3)) } else if pos == Position(7, 6) { castlingMove = Move(from: Position(7, 7), to: Position(7, 5)) } } else if piece.color == .Black && activePos == Position(0, 4) { if pos == Position(0, 2) { castlingMove = Move(from: Position(0, 0), to: Position(0, 3)) } else if pos == Position(0, 6) { castlingMove = Move(from: Position(0, 7), to: Position(0, 5)) } } } } if let move = castlingMove { let newRookPos = getPosition(move.to) let rookPiece = getPiece(move.from) let model = rookPiece!.model SCNTransaction.begin() SCNTransaction.setAnimationDuration(0.25) model.position = SCNVector3(x: newRookPos.x, y: newRookPos.y, z: model.position.z) SCNTransaction.commit() gameBoardArray[move.from.row][move.from.col] = nil gameBoardArray[move.to.row][move.to.col] = rookPiece } // En passant // var en_passant = false if piece.type == .Pawn && pos.col != activePos.col && originalPiece == nil { // en_passant = true let enPassantPos = Position(activePos.row, pos.col) if let piece = getPiece(enPassantPos) { piece.model.removeFromParentNode() } } // Promotion var promotion = false if piece.type == .Pawn { if game.color == .Black { if piece.color == .Black && pos.row == 0 { promotion = true } else if piece.color == .White && pos.row == 7 { promotion = true } } else { if piece.color == .White && pos.row == 0 { promotion = true } else if piece.color == .Black && pos.row == 7 { promotion = true } } } if (promotion) { // TODO: Promotion print("Promotion") // piece.type = .Queen } // Actual move let position = getPosition(pos) let model = activePiece.piece.model SCNTransaction.begin() SCNTransaction.setAnimationDuration(0.25) model.position = SCNVector3(x: position.x, y: position.y, z: model.position.z) SCNTransaction.commit() // Taking if let actualOriginalPiece = originalPiece { actualOriginalPiece.model.removeFromParentNode() } gameBoardArray[activePiece.pos.row][activePiece.pos.col] = nil gameBoardArray[pos.row][pos.col] = activePiece.piece resetHelperLights() waiting = false } if user { //var data: [String: AnyObject]! /*let handler = { (response: MoveResponse?) -> Void in if let response = response { self.waiting = !response.opponent_played if response.opponent_played { if let hints = response.hints { if hints.count > 0 { self.detailGame.hints = hints } else { self.detailGame.hints = nil } } else { self.detailGame.hints = nil } if response.move != nil && response.b_check! { playSound(SOUND_CHECK) } if let move = response.move { if let piece = getPiece(move.from) { self.activePiece = (piece, move.from) self.move(move.to, user: false) } else { println("piece error") } } if response.move == nil { playSound(SOUND_WIN) } else if self.detailGame.hints == nil { playSound(SOUND_LOSS) } if response.move == nil && self.detailGame.hints != nil && response.w_check! { playSound(SOUND_CHECK_2) } } else { dispatch_after(2) { self.move(pos, user: user) } } } else { println("move error") } if !self.waiting { UIView.animateWithDuration(0.25) { self.overlayView.alpha = 0 } } }*/ UIView.animateWithDuration(0.25) { self.overlayView.alpha = 1 } if !waiting { if originalPiece != nil { playSound(SOUND_CAPTURE) } else { playSound(SOUND_MOVE) } let move = Move(activePiece.pos, pos) if game.isAI { dispatch_after(0.25) { self.ai.board = self.ai.board.move(move) let result = self.ai.search(self.ai.board) if let aiMove: Move = result.0 { self.ai.board = self.ai.board.move(aiMove) let rotatedMove = aiMove.rotate() if let piece = getPiece(rotatedMove.from) { self.activePiece = (piece, rotatedMove.from) self.move(rotatedMove.to, user: false) } else { print("piece error") } } var hints = [Move]() for hintMove in self.ai.board.genMoves() { if !self.ai.board.move(hintMove).inCheck(.k) { hints.append(hintMove) } } self.detailGame.hints = hints UIView.animateWithDuration(0.25) { self.overlayView.alpha = 0 } } } else { API.gameMove(game.uid, move: move.description) } } } else { if originalPiece != nil { playSound(SOUND_CAPTURE_2) } else { playSound(SOUND_MOVE_2) } } } }
mit
02f1e75c351a0eb7f501f77bbec14afe
26.291351
146
0.618849
3.399811
false
false
false
false
Stamates/30-Days-of-Swift
src/Day 18 - Table View Details/Day 18 - Table View Details/ViewController.swift
2
982
// // ViewController.swift // Day 18 - Table View Details // // Created by Justin Mitchel on 11/23/14. // Copyright (c) 2014 Coding For Entrepreneurs. All rights reserved. // import UIKit class ViewController: UIViewController { var titleText: String? override func viewDidLoad() { super.viewDidLoad() let navBarHeight = self.navigationController!.navigationBar.frame.height let label = UILabel(frame: CGRectMake(10, navBarHeight + 20, self.view.frame.width - 20, 50)) label.text = self.titleText label.backgroundColor = UIColor.blackColor() label.textColor = UIColor.whiteColor() label.textAlignment = NSTextAlignment.Center self.view.addSubview(label) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
09b4fac50e4a6bc373d195d8cbcf8658
27.882353
101
0.679226
4.610329
false
false
false
false
nissivm/DemoShopPayPal
DemoShop-PayPal/Objects/Device.swift
2
1568
// // Device.swift // Demo Shop // // Created by Nissi Vieira Miranda on 1/13/16. // Copyright © 2016 Nissi Vieira Miranda. All rights reserved. // import Foundation class Device { static var IS_IPHONE: Bool { get { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return true } else { return false } } } static var IS_IPHONE_4: Bool { get { if IS_IPHONE && UIScreen.mainScreen().bounds.size.height == 480.0 { return true } else { return false } } } static var IS_IPHONE_5: Bool { get { if IS_IPHONE && UIScreen.mainScreen().bounds.size.height == 568.0 { return true } else { return false } } } static var IS_IPHONE_6: Bool { get { if IS_IPHONE && UIScreen.mainScreen().bounds.size.height == 667.0 { return true } else { return false } } } static var IS_IPHONE_6_PLUS: Bool { get { if IS_IPHONE && UIScreen.mainScreen().bounds.size.height == 736.0 { return true } else { return false } } } }
mit
bcd031b28a3da5bf01ba384d502beadf
19.363636
77
0.395022
4.912226
false
false
false
false
eoger/firefox-ios
Client/Helpers/TabEventHandler.swift
3
6293
/* 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 Storage /** * A handler can be a plain old swift object. It does not need to extend any * other object, but can. * * Handlers should register for tab events with the `registerFor` method, and * cleanup with the `unregister` method. * * ``` * class HandoffHandler { * var tabObservers: TabObservers! * * init() { * tabObservers = registerFor(.didLoadFavicon, .didLoadPageMetadata) * } * * deinit { * unregister(tabObservers) * } * } * ``` * * Handlers can implement any or all `TabEventHandler` methods. If you * implement a method, you should probably `registerFor` the event above. * * ``` * extension HandoffHandler: TabEventHandler { * func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) { * print("\(tab) has \(pageMetadata)") * } * * func tab(_ tab: Tab, didLoadFavicon favicon: Favicon) { * print("\(tab) has \(favicon)") * } * } * ``` * * Tab events should probably be only posted from one place, to avoid cycles. * * ``` * TabEvent.post(.didLoadPageMetadata(aPageMetadata), for: tab) * ``` * * In this manner, we are able to use the notification center and have type safety. * */ // As we want more events we add more here. // Each event needs: // 1. a method in the TabEventHandler. // 2. a default implementation of the method – so not everyone needs to implement it // 3. a TabEventLabel, which is needed for registration // 4. a TabEvent, with whatever parameters are needed. // i) a case to map the event to the event label (var label) // ii) a case to map the event to the event handler (func handle:with:) protocol TabEventHandler { func tab(_ tab: Tab, didChangeURL url: URL) func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) func tab(_ tab: Tab, didLoadFavicon favicon: Favicon?, with: Data?) func tabDidGainFocus(_ tab: Tab) func tabDidLoseFocus(_ tab: Tab) func tabDidClose(_ tab: Tab) func tabDidChangeContentBlockerStatus(_ tab: Tab) } // Provide default implmentations, because we don't want to litter the code with // empty methods, and `@objc optional` doesn't really work very well. extension TabEventHandler { func tab(_ tab: Tab, didChangeURL url: URL) {} func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) {} func tab(_ tab: Tab, didLoadFavicon favicon: Favicon?, with: Data?) {} func tabDidGainFocus(_ tab: Tab) {} func tabDidLoseFocus(_ tab: Tab) {} func tabDidClose(_ tab: Tab) {} func tabDidChangeContentBlockerStatus(_ tab: Tab) {} } enum TabEventLabel: String { case didChangeURL case didLoadPageMetadata case didLoadFavicon case didGainFocus case didLoseFocus case didClose case didChangeContentBlocking } enum TabEvent { case didChangeURL(URL) case didLoadPageMetadata(PageMetadata) case didLoadFavicon(Favicon?, with: Data?) case didGainFocus case didLoseFocus case didClose case didChangeContentBlocking var label: TabEventLabel { switch self { case .didChangeURL: return .didChangeURL case .didLoadPageMetadata: return .didLoadPageMetadata case .didLoadFavicon: return .didLoadFavicon case .didGainFocus: return .didGainFocus case .didLoseFocus: return .didLoseFocus case .didClose: return .didClose case .didChangeContentBlocking: return .didChangeContentBlocking } } func handle(_ tab: Tab, with handler: TabEventHandler) { switch self { case .didChangeURL(let url): handler.tab(tab, didChangeURL: url) case .didLoadPageMetadata(let metadata): handler.tab(tab, didLoadPageMetadata: metadata) case .didLoadFavicon(let favicon, let data): handler.tab(tab, didLoadFavicon: favicon, with: data) case .didGainFocus: handler.tabDidGainFocus(tab) case .didLoseFocus: handler.tabDidLoseFocus(tab) case .didClose: handler.tabDidClose(tab) case .didChangeContentBlocking: handler.tabDidChangeContentBlockerStatus(tab) } } } // Hide some of the machinery away from the boiler plate above. //////////////////////////////////////////////////////////////////////////////////////// extension TabEventLabel { var name: Notification.Name { return Notification.Name(self.rawValue) } } extension TabEvent { func notification(for tab: Any) -> Notification { return Notification(name: label.name, object: tab, userInfo: ["payload": self]) } /// Use this method to post notifications to any concerned listeners. static func post(_ event: TabEvent, for tab: Any) { center.post(event.notification(for: tab)) } } // These methods are used by TabEventHandler implementers. // Their usage remains consistent, even as we add more event types and handler methods. //////////////////////////////////////////////////////////////////////////////////////// private let center = NotificationCenter() typealias TabObservers = [NSObjectProtocol] extension TabEventHandler { /// Implementations of handles should use this method to register for events. /// `TabObservers` should be preserved for unregistering later. func registerFor(_ tabEvents: TabEventLabel..., queue: OperationQueue? = nil) -> TabObservers { return tabEvents.map { eventType in center.addObserver(forName: eventType.name, object: nil, queue: queue) { notification in guard let tab = notification.object as? Tab, let event = notification.userInfo?["payload"] as? TabEvent else { return } event.handle(tab, with: self) } } } func unregister(_ observers: TabObservers) { observers.forEach { observer in center.removeObserver(observer) } } }
mpl-2.0
5046bde03fc405bf296a7cf5471cd995
32.822581
100
0.639167
4.602048
false
false
false
false
dreamsxin/swift
stdlib/public/core/SwiftNativeNSArray.swift
4
9181
//===--- SwiftNativeNSArray.swift -----------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // _ContiguousArrayStorageBase supplies the implementation of the // _NSArrayCore API (and thus, NSArray the API) for our // _ContiguousArrayStorage<T>. We can't put this implementation // directly on _ContiguousArrayStorage because generic classes can't // override Objective-C selectors. // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims /// Returns `true` iff the given `index` is valid as a position, i.e. `0 /// ≤ index ≤ count`. @_transparent internal func _isValidArrayIndex(_ index: Int, count: Int) -> Bool { return (index >= 0) && (index <= count) } /// Returns `true` iff the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @_transparent internal func _isValidArraySubscript(_ index: Int, count: Int) -> Bool { return (index >= 0) && (index < count) } /// An `NSArray` with Swift-native reference counting and contiguous /// storage. internal class _SwiftNativeNSArrayWithContiguousStorage : _SwiftNativeNSArray { // Provides NSArray inheritance and native refcounting // Operate on our contiguous storage internal func withUnsafeBufferOfObjects<R>( _ body: @noescape (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R { _sanityCheckFailure( "Must override withUnsafeBufferOfObjects in derived classes") } } // Implement the APIs required by NSArray extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore { @objc internal var count: Int { return withUnsafeBufferOfObjects { $0.count } } @objc(objectAtIndex:) internal func objectAt(_ index: Int) -> AnyObject { return withUnsafeBufferOfObjects { objects in _precondition( _isValidArraySubscript(index, count: objects.count), "Array index out of range") return objects[index] } } @objc internal func getObjects( _ aBuffer: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange ) { return withUnsafeBufferOfObjects { objects in _precondition( _isValidArrayIndex(range.location, count: objects.count), "Array index out of range") _precondition( _isValidArrayIndex( range.location + range.length, count: objects.count), "Array index out of range") if objects.isEmpty { return } // These objects are "returned" at +0, so treat them as values to // avoid retains. UnsafeMutablePointer<Int>(aBuffer).initializeFrom( UnsafeMutablePointer(objects.baseAddress! + range.location), count: range.length) } } @objc(countByEnumeratingWithState:objects:count:) internal func countByEnumerating( with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>?, count: Int ) -> Int { var enumerationState = state.pointee if enumerationState.state != 0 { return 0 } return withUnsafeBufferOfObjects { objects in enumerationState.mutationsPtr = _fastEnumerationStorageMutationsPtr enumerationState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects.baseAddress) enumerationState.state = 1 state.pointee = enumerationState return objects.count } } @objc(copyWithZone:) internal func copy(with _: _SwiftNSZone?) -> AnyObject { return self } } /// An `NSArray` whose contiguous storage is created and filled, upon /// first access, by bridging the elements of a Swift `Array`. /// /// Ideally instances of this class would be allocated in-line in the /// buffers used for Array storage. @objc internal final class _SwiftDeferredNSArray : _SwiftNativeNSArrayWithContiguousStorage { // This stored property should be stored at offset zero. We perform atomic // operations on it. // // Do not access this property directly. internal var _heapBufferBridged_DoNotUse: AnyObject? = nil // When this class is allocated inline, this property can become a // computed one. internal let _nativeStorage: _ContiguousArrayStorageBase internal var _heapBufferBridgedPtr: UnsafeMutablePointer<AnyObject?> { return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) } internal typealias HeapBufferStorage = _HeapBufferStorage<Int, AnyObject> internal var _heapBufferBridged: HeapBufferStorage? { if let ref = _stdlib_atomicLoadARCRef(object: _heapBufferBridgedPtr) { return unsafeBitCast(ref, to: HeapBufferStorage.self) } return nil } internal init(_nativeStorage: _ContiguousArrayStorageBase) { self._nativeStorage = _nativeStorage } internal func _destroyBridgedStorage(_ hb: HeapBufferStorage?) { if let bridgedStorage = hb { let heapBuffer = _HeapBuffer(bridgedStorage) let count = heapBuffer.value heapBuffer.baseAddress.deinitialize(count: count) } } deinit { _destroyBridgedStorage(_heapBufferBridged) } internal override func withUnsafeBufferOfObjects<R>( _ body: @noescape (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R { repeat { var buffer: UnsafeBufferPointer<AnyObject> // If we've already got a buffer of bridged objects, just use it if let bridgedStorage = _heapBufferBridged { let heapBuffer = _HeapBuffer(bridgedStorage) buffer = UnsafeBufferPointer( start: heapBuffer.baseAddress, count: heapBuffer.value) } // If elements are bridged verbatim, the native buffer is all we // need, so return that. else if let buf = _nativeStorage._withVerbatimBridgedUnsafeBuffer( { $0 } ) { buffer = buf } else { // Create buffer of bridged objects. let objects = _nativeStorage._getNonVerbatimBridgedHeapBuffer() // Atomically store a reference to that buffer in self. if !_stdlib_atomicInitializeARCRef( object: _heapBufferBridgedPtr, desired: objects.storage!) { // Another thread won the race. Throw out our buffer. _destroyBridgedStorage( unsafeDowncast(objects.storage!, to: HeapBufferStorage.self)) } continue // Try again } defer { _fixLifetime(self) } return try body(buffer) } while true } /// Returns the number of elements in the array. /// /// This override allows the count to be read without triggering /// bridging of array elements. @objc internal override var count: Int { if let bridgedStorage = _heapBufferBridged { return _HeapBuffer(bridgedStorage).value } // Check if elements are bridged verbatim. return _nativeStorage._withVerbatimBridgedUnsafeBuffer { $0.count } ?? _nativeStorage._getNonVerbatimBridgedCount() } } #else // Empty shim version for non-objc platforms. class _SwiftNativeNSArrayWithContiguousStorage {} #endif /// Base class of the heap buffer backing arrays. internal class _ContiguousArrayStorageBase : _SwiftNativeNSArrayWithContiguousStorage { #if _runtime(_ObjC) internal override func withUnsafeBufferOfObjects<R>( _ body: @noescape (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R { if let result = try _withVerbatimBridgedUnsafeBuffer(body) { return result } _sanityCheckFailure( "Can't use a buffer of non-verbatim-bridged elements as an NSArray") } /// If the stored type is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements and return the result. /// Otherwise, return `nil`. internal func _withVerbatimBridgedUnsafeBuffer<R>( _ body: @noescape (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { _sanityCheckFailure( "Concrete subclasses must implement _withVerbatimBridgedUnsafeBuffer") } internal func _getNonVerbatimBridgedCount(_ dummy: Void) -> Int { _sanityCheckFailure( "Concrete subclasses must implement _getNonVerbatimBridgedCount") } internal func _getNonVerbatimBridgedHeapBuffer(_ dummy: Void) -> _HeapBuffer<Int, AnyObject> { _sanityCheckFailure( "Concrete subclasses must implement _getNonVerbatimBridgedHeapBuffer") } #endif func canStoreElements(ofDynamicType _: Any.Type) -> Bool { _sanityCheckFailure( "Concrete subclasses must implement canStoreElements(ofDynamicType:)") } /// A type that every element in the array is. var staticElementType: Any.Type { _sanityCheckFailure( "Concrete subclasses must implement staticElementType") } deinit { _sanityCheck( self !== _emptyArrayStorage, "Deallocating empty array storage?!") } }
apache-2.0
eb8880f4d7aa74f9ac119c81b227f750
31.535461
80
0.683815
5.145822
false
false
false
false
gokush/GKAddressKit
GKAddressKitExample/AddressEditCell.swift
1
2024
// // AddressEditCell.swift // bajibaji // // Created by 童小波 on 15/2/4. // Copyright (c) 2015年 bajibaji. All rights reserved. // import UIKit class AddressEditCell: UITableViewCell { @IBOutlet weak var keyLabel: UILabel! @IBOutlet weak var valueTextField: UITextField! @IBOutlet weak var valueLabel: UILabel! var delegate: AddressEditCellDelegate? var allowEdit: Bool = true{ didSet{ if allowEdit{ valueTextField.hidden = false valueLabel.hidden = true } else{ valueTextField.hidden = true valueLabel.hidden = false } } } override func awakeFromNib() { super.awakeFromNib() let tap = UITapGestureRecognizer(target: self, action: "didTap:") valueLabel.addGestureRecognizer(tap) valueLabel.userInteractionEnabled = true // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func didTap(sender: UITapGestureRecognizer){ self.delegate?.addressEditCellDidBeginEditing?(valueTextField, indexPath: indexPath()) } func indexPath() -> NSIndexPath{ let tableView = self.superview?.superview as UITableView return tableView.indexPathForCell(self)! } @IBAction func textFieldBeginEditing(sender: AnyObject) { self.delegate?.addressEditCellDidBeginEditing?(valueTextField, indexPath: indexPath()) } @IBAction func textFieldEndEditing(sender: AnyObject) { self.delegate?.addressEditCellDidEndEditing?(valueTextField.text, indexPath: indexPath()) } } @objc protocol AddressEditCellDelegate{ optional func addressEditCellDidEndEditing(text: String, indexPath: NSIndexPath) optional func addressEditCellDidBeginEditing(textField: UITextField, indexPath: NSIndexPath) }
mit
4a0c240c7be1062bbac9bf39ecf096aa
30.015385
97
0.668651
5.116751
false
false
false
false
ilyathewhite/Euler
EulerSketch/EulerSketch/Commands/Transformations/Sketch+Transformations.swift
1
9949
// // Sketch+Transformations.swift // EulerSketchOSX // // Created by Ilya Belenkiy on 7/25/16. // Copyright © 2016 Ilya Belenkiy. All rights reserved. // import Foundation extension Sketch { struct TransformationInfo { var name: String var f: (Point) -> HSPoint var usedFigures: [FigureType] } /// Adds a point that is transformed from another point. If the given point changes, the tranformed point is changed by reapplying the transform. @discardableResult func addTransformationPoint(_ toPointName: String, fromPoint fromPointName: String, transformInfo: TransformationInfo, style: DrawingStyle? = nil) -> FigureResult { do { let point: PointFigure = try getFigure(name: fromPointName) let figure = try PointFigure(name: toPointName, usedFigures: FigureSet(transformInfo.usedFigures + [point])) { return transformInfo.f(point) } return .success(try addFigure(figure, style: style)) } catch { return .failure(error) } } /// Adds a segment that is transformed from another segment. If the given segment changes, the tranformed segment is changed by reapplying the transform. @discardableResult func addTransformationSegment(_ toSegmentName: String, fromSegment fromSegmentName: String, transformInfo: TransformationInfo, style: DrawingStyle? = nil) -> FigureResult { do { let segment: SegmentFigure = try getFigure(name: fromSegmentName) let pointNames = try scanPointNames(toSegmentName, expected: .segment) guard pointNames.count == 2 else { throw SketchError.invalidFigureName(name: toSegmentName, kind: .segment) } addTransformationPoint(pointNames[0], fromPoint: (segment.vertex1 as! PointFigure).name, transformInfo: transformInfo) let A: PointFigure = try getFigure(name: pointNames[0]) addTransformationPoint(pointNames[1], fromPoint: (segment.vertex2 as! PointFigure).name, transformInfo: transformInfo) let B: PointFigure = try getFigure(name: pointNames[1]) let figure = try SegmentFigure(name: toSegmentName, point1: A, point2: B) try addFigure(figure, style: style) figure.dragUpdateFunc = nil return .success(figure.summary) } catch { return .failure(error) } } /// Adds a line that is transformed from another line. If the given line changes, the tranformed line is changed by reapplying the transform. @discardableResult func addTransformationLine(_ toLineName: String, fromLine fromLineName: String, transformInfo: TransformationInfo, style: DrawingStyle? = nil) -> FigureResult { do { let pointNames = try scanPointNames(fromLineName, expected: .line) let resPointNames = try scanPointNames(toLineName, expected: .line) let figure = try { () throws -> SimpleLineFigure in if resPointNames.count == 2 { guard pointNames.count == 2 else { throw SketchError.figureNotCreated(name: toLineName, kind: .line) } addTransformationPoint(resPointNames[0], fromPoint: pointNames[0], transformInfo: transformInfo) let A: PointFigure = try getFigure(name: resPointNames[0]) addTransformationPoint(resPointNames[1], fromPoint: pointNames[1], transformInfo: transformInfo) let B: PointFigure = try getFigure(name: resPointNames[1]) return try SimpleLineFigure(name: toLineName, point1: A, point2: B) } else { throw SketchError.figureNotCreated(name: toLineName, kind: .line) } }() try addFigure(figure, style: style) figure.dragUpdateFunc = nil return .success(figure.summary) } catch { return .failure(error) } } /// Adds a ray that is transformed from another ray. If the given ray changes, the tranformed ray is changed by reapplying the transform. @discardableResult func addTransformationRay(_ toRayName: String, fromRay fromRayName: String, transformInfo: TransformationInfo, style: DrawingStyle? = nil) -> FigureResult { do { let ray: RayFigure = try getFigure(name: fromRayName) let pointNames = try scanPointNames(fromRayName, expected: .ray) let resPointNames = try scanPointNames(toRayName, expected: .ray) let figure = try { () throws -> RayFigure in if resPointNames.count == 2 { guard pointNames.count == 2 else { throw SketchError.figureNotCreated(name: toRayName, kind: .ray) } addTransformationPoint(resPointNames[0], fromPoint: pointNames[0], transformInfo: transformInfo) let A: PointFigure = try getFigure(name: resPointNames[0]) addTransformationPoint(resPointNames[1], fromPoint: pointNames[1], transformInfo: transformInfo) let B: PointFigure = try getFigure(name: resPointNames[1]) return try RayFigure(name: toRayName, vertex: A, point: B) } else { return try RayFigure(name: toRayName, usedFigures: FigureSet(transformInfo.usedFigures + [ray])) { let vertex = transformInfo.f(ray.vertex) let handle = transformInfo.f(ray.handle) return HSSegment(vertex1: vertex, vertex2: handle)?.ray } } }() try addFigure(figure, style: style) figure.dragUpdateFunc = nil return .success(figure.summary) } catch { return .failure(error) } } /// Adds a cirlce that is transformed from another circle. If the given cirlce changes, the tranformed circle is changed by reapplying the transform. @discardableResult func addTransformationCircle(_ toCircleName: String, fromCircle fromCircleName: String, transformInfo: TransformationInfo, style: DrawingStyle? = nil) -> FigureResult { do { let circle: CircleFigure = try getFigure(name: fromCircleName) let figure = try CircleFigure(name: toCircleName, usedFigures: FigureSet(transformInfo.usedFigures + [circle])) { let center = transformInfo.f(circle.center) let handle = transformInfo.f(HSPoint(circle.center.x + circle.radius, circle.center.y)) let radius = center.distanceToPoint(handle) return HSCircle(center: center, radius: radius) } try addFigure(figure, style: style) figure.dragUpdateFunc = nil return .success(figure.summary) } catch { return .failure(error) } } } extension Sketch { /// Creates a translation tranformation from a given vector that is specified by the two points in the vector name. func makeTranslation(_ vectorName: String) throws -> TransformationInfo { let pointNames = try scanPointNames(vectorName, expected: .segment) guard pointNames.count == 2 else { throw SketchError.invalidFigureName(name: vectorName, kind: .vector) } let A: PointFigure = try getFigure(name: pointNames[0]) let B: PointFigure = try getFigure(name: pointNames[1]) return TransformationInfo(name: "translation", f: { $0.translate(by: vector(A, B)) }, usedFigures: [A, B] ) } /// Creates a translation transformation from a given vector. func makeTranslation(_ vector: Vector) -> TransformationInfo { return TransformationInfo(name: "translation", f: { $0.translate(by: vector) }, usedFigures: [] ) } /// Creates a rotation transformation from a given point and angle. func makeRotation(_ centerName: String, degAngle: Double) throws -> TransformationInfo { let angle = toRadians(degAngle) let O: PointFigure = try getFigure(name: centerName) return TransformationInfo(name: "rotation", f: { $0.rotateAroundPoint(O, angle: angle) }, usedFigures: [O]) } /// Creates a dilation transformation with a given center and scale. func makeDilation(_ centerName: String, scale: Double) throws -> TransformationInfo { let O: PointFigure = try getFigure(name: centerName) func dilation(_ point: Point) -> HSPoint { guard let segment = HSSegment(vertex1: O, vertex2: point) else { return O.value } let angle = scale > 0 ? segment.ray.angle : segment.ray.angle + .pi return HSRay(vertex: O, angle: angle).pointAtDistance(O.distanceToPoint(point) * abs(scale)) } return TransformationInfo(name: "dilation", f: dilation, usedFigures: [O]) } // Creates a reflection transformation from a given line as the mirror. func makeReflection(_ mirrorLineName: String) throws -> TransformationInfo { let line: LineFigure = try getFigure(name: mirrorLineName) func reflection(_ point: Point) -> HSPoint { let foot = line.footFromPoint(point) guard let ray = HSSegment(vertex1: point, vertex2: foot)?.ray else { return foot } return ray.pointAtDistance(2 * point.distanceToPoint(foot)) } return TransformationInfo(name: "reflection", f: reflection, usedFigures: [line]) } // Creates a reflection transformation from a given as the center. func makePointReflection(_ centerName: String) throws -> TransformationInfo { let O: PointFigure = try getFigure(name: centerName) func reflection(_ point: Point) -> HSPoint { guard let ray = HSSegment(vertex1: point, vertex2: O)?.ray else { return O.basicValue } return ray.pointAtDistance(2 * point.distanceToPoint(O)) } return TransformationInfo(name: "reflection", f: reflection, usedFigures: [O]) } }
mit
e6a8aa748a41260943468f78a06605f6
46.826923
194
0.652493
4.40177
false
false
false
false
creatubbles/ctb-api-swift
Pods/ObjectMapper/Sources/Operators.swift
4
11125
// // Operators.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-09. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Hearst // // 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. /** * This file defines a new operator which is used to create a mapping between an object and a JSON key value. * There is an overloaded operator definition for each type of object that is supported in ObjectMapper. * This provides a way to add custom logic to handle specific types of objects */ /// Operator used for defining mappings to and from JSON infix operator <- /// Operator used to define mappings to JSON infix operator >>> // MARK:- Objects with Basic types /// Object of Basic type public func <- <T>(left: inout T, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.basicType(&left, object: right.value()) case .toJSON: left >>> right default: () } } public func >>> <T>(left: T, right: Map) { if right.mappingType == .toJSON { ToJSON.basicType(left, map: right) } } /// Optional object of basic type public func <- <T>(left: inout T?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalBasicType(&left, object: right.value()) case .toJSON: left >>> right default: () } } public func >>> <T>(left: T?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalBasicType(left, map: right) } } // Code targeting the Swift 4.1 compiler and below. #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) /// Implicitly unwrapped optional object of basic type public func <- <T>(left: inout T!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalBasicType(&left, object: right.value()) case .toJSON: left >>> right default: () } } #endif // MARK:- Mappable Objects - <T: BaseMappable> /// Object conforming to Mappable public func <- <T: BaseMappable>(left: inout T, right: Map) { switch right.mappingType { case .fromJSON: FromJSON.object(&left, map: right) case .toJSON: left >>> right } } public func >>> <T: BaseMappable>(left: T, right: Map) { if right.mappingType == .toJSON { ToJSON.object(left, map: right) } } /// Optional Mappable objects public func <- <T: BaseMappable>(left: inout T?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObject(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: T?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalObject(left, map: right) } } // Code targeting the Swift 4.1 compiler and below. #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) /// Implicitly unwrapped optional Mappable objects public func <- <T: BaseMappable>(left: inout T!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObject(&left, map: right) case .toJSON: left >>> right default: () } } #endif // MARK:- Dictionary of Mappable objects - Dictionary<String, T: BaseMappable> /// Dictionary of Mappable objects <String, T: Mappable> public func <- <T: BaseMappable>(left: inout Dictionary<String, T>, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.objectDictionary(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Dictionary<String, T>, right: Map) { if right.mappingType == .toJSON { ToJSON.objectDictionary(left, map: right) } } /// Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: BaseMappable>(left: inout Dictionary<String, T>?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectDictionary(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Dictionary<String, T>?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalObjectDictionary(left, map: right) } } // Code targeting the Swift 4.1 compiler and below. #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) /// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: BaseMappable>(left: inout Dictionary<String, T>!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectDictionary(&left, map: right) case .toJSON: left >>> right default: () } } #endif /// Dictionary of Mappable objects <String, T: Mappable> public func <- <T: BaseMappable>(left: inout Dictionary<String, [T]>, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.objectDictionaryOfArrays(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Dictionary<String, [T]>, right: Map) { if right.mappingType == .toJSON { ToJSON.objectDictionaryOfArrays(left, map: right) } } /// Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: BaseMappable>(left: inout Dictionary<String, [T]>?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectDictionaryOfArrays(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Dictionary<String, [T]>?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalObjectDictionaryOfArrays(left, map: right) } } // Code targeting the Swift 4.1 compiler and below. #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) /// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: BaseMappable>(left: inout Dictionary<String, [T]>!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectDictionaryOfArrays(&left, map: right) case .toJSON: left >>> right default: () } } #endif // MARK:- Array of Mappable objects - Array<T: BaseMappable> /// Array of Mappable objects public func <- <T: BaseMappable>(left: inout Array<T>, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.objectArray(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Array<T>, right: Map) { if right.mappingType == .toJSON { ToJSON.objectArray(left, map: right) } } /// Optional array of Mappable objects public func <- <T: BaseMappable>(left: inout Array<T>?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectArray(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Array<T>?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalObjectArray(left, map: right) } } // Code targeting the Swift 4.1 compiler and below. #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) /// Implicitly unwrapped Optional array of Mappable objects public func <- <T: BaseMappable>(left: inout Array<T>!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectArray(&left, map: right) case .toJSON: left >>> right default: () } } #endif // MARK:- Array of Array of Mappable objects - Array<Array<T: BaseMappable>> /// Array of Array Mappable objects public func <- <T: BaseMappable>(left: inout Array<Array<T>>, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.twoDimensionalObjectArray(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Array<Array<T>>, right: Map) { if right.mappingType == .toJSON { ToJSON.twoDimensionalObjectArray(left, map: right) } } /// Optional array of Mappable objects public func <- <T: BaseMappable>(left:inout Array<Array<T>>?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalTwoDimensionalObjectArray(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Array<Array<T>>?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalTwoDimensionalObjectArray(left, map: right) } } // Code targeting the Swift 4.1 compiler and below. #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) /// Implicitly unwrapped Optional array of Mappable objects public func <- <T: BaseMappable>(left: inout Array<Array<T>>!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalTwoDimensionalObjectArray(&left, map: right) case .toJSON: left >>> right default: () } } #endif // MARK:- Set of Mappable objects - Set<T: BaseMappable> /// Set of Mappable objects public func <- <T: BaseMappable>(left: inout Set<T>, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.objectSet(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Set<T>, right: Map) { if right.mappingType == .toJSON { ToJSON.objectSet(left, map: right) } } /// Optional Set of Mappable objects public func <- <T: BaseMappable>(left: inout Set<T>?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectSet(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Set<T>?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalObjectSet(left, map: right) } } // Code targeting the Swift 4.1 compiler and below. #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) /// Implicitly unwrapped Optional Set of Mappable objects public func <- <T: BaseMappable>(left: inout Set<T>!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectSet(&left, map: right) case .toJSON: left >>> right default: () } } #endif
mit
32d00dc08a9befa4e0cc59922e4e2a23
26.952261
108
0.696449
3.508357
false
false
false
false
shadanan/mado
Antlr4Runtime/Sources/Antlr4/Token.swift
1
3229
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /** A token has properties: text, type, line, character position in the line * (so we can ignore tabs), token channel, index, and source from which * we obtained this token. */ public protocol Token: class, CustomStringConvertible { //let INVALID_TYPE : Int = 0; /** During lookahead operations, this "token" signifies we hit rule end ATN state * and did not follow it despite needing to. */ //let EPSILON : Int = -2; //let MIN_USER_TOKEN_TYPE : Int = 1; //let EOF : Int = IntStream.EOF; /** All tokens go to the parser (unless skip() is called in that rule) * on a particular "channel". The parser tunes to a particular channel * so that whitespace etc... can go to the parser on a "hidden" channel. */ //let DEFAULT_CHANNEL : Int = 0; /** Anything on different channel than DEFAULT_CHANNEL is not parsed * by parser. */ //let HIDDEN_CHANNEL : Int = 1; /** * This is the minimum constant value which can be assigned to a * user-defined token channel. * * <p> * The non-negative numbers less than {@link #MIN_USER_CHANNEL_VALUE} are * assigned to the predefined channels {@link #DEFAULT_CHANNEL} and * {@link #HIDDEN_CHANNEL}.</p> * * @see org.antlr.v4.runtime.Token#getChannel() */ //let MIN_USER_CHANNEL_VALUE : Int = 2; /** * Get the text of the token. */ func getText() -> String? /** Get the token type of the token */ func getType() -> Int /** The line number on which the 1st character of this token was matched, * line=1..n */ func getLine() -> Int /** The index of the first character of this token relative to the * beginning of the line at which it occurs, 0..n-1 */ func getCharPositionInLine() -> Int /** Return the channel this token. Each token can arrive at the parser * on a different channel, but the parser only "tunes" to a single channel. * The parser ignores everything not on DEFAULT_CHANNEL. */ func getChannel() -> Int /** An index from 0..n-1 of the token object in the input stream. * This must be valid in order to print token streams and * use TokenRewriteStream. * * Return -1 to indicate that this token was conjured up since * it doesn't have a valid index. */ func getTokenIndex() -> Int /** The starting character index of the token * This method is optional; return -1 if not implemented. */ func getStartIndex() -> Int /** The last character index of the token. * This method is optional; return -1 if not implemented. */ func getStopIndex() -> Int /** Gets the {@link org.antlr.v4.runtime.TokenSource} which created this token. */ func getTokenSource() -> TokenSource? /** * Gets the {@link org.antlr.v4.runtime.CharStream} from which this token was derived. */ func getInputStream() -> CharStream? var visited: Bool { get set } }
mit
9383516617a2a0fb161446d69a6d6ea3
30.656863
90
0.633323
4.021171
false
false
false
false
motylevm/skstylekit
Sources/SKStyleNavigationBar.swift
1
1892
// // Copyright (c) 2016 Mikhail Motylev https://twitter.com/mikhail_motylev // // 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 extension SKStyle { // MARK: - UITabBar - /** Applies style to a navigation bar - parameter navBar: Navigation bar to apply style to */ func apply(navBar: UINavigationBar) { if let tintColor = tintColor { navBar.tintColor = tintColor } if let barTintColor = barTintColor { navBar.barTintColor = barTintColor } if let isTranslucent = isTranslucent { navBar.isTranslucent = isTranslucent } if let textAttributes = textAttributes() { navBar.titleTextAttributes = textAttributes } } }
mit
09b737460ac15f211e3e64b8ecd356c6
37.612245
86
0.670719
4.965879
false
false
false
false
YangYouYong/SwiftLearnLog01
SongsPlayer/SongsPlayer/Classes/MasterViewController.swift
1
3573
// // MasterViewController.swift // SongsPlayer // // Created by yangyouyong on 15/8/7. // Copyright © 2015年 SongsPlayer. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { objects.insert(NSDate(), atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] as! NSDate let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] as! NSDate cell.textLabel!.text = object.description return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { objects.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
apache-2.0
e612423c8bc80bf0da378887622c61ce
36.978723
157
0.694118
5.721154
false
false
false
false
LYM-mg/MGOFO
MGOFO/MGOFO/Class/Extesion/UIBarButtonItem+Extension.swift
1
1188
// // UIBarButtonItem+Extension.swift // ProductionReport // // Created by i-Techsys.com on 2017/5/9. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit extension UIBarButtonItem { // UIBarButtonItem的封装 convenience init(image: UIImage, highImage: UIImage, norColor: UIColor, selColor: UIColor, title: String, target: Any, action: Selector) { let backBtn = UIButton(type: .custom) /// 1.设置照片 backBtn.setImage(image, for: .normal) // backBtn.setImage(highImage, for: .highlighted) /// 2.设置文字以及颜色 backBtn.setTitle(title, for: .normal) backBtn.setTitleColor(norColor, for: .normal) backBtn.setTitleColor(selColor, for: .highlighted) backBtn.sizeToFit() backBtn.addTarget(target, action: action, for: .touchUpInside) backBtn.contentHorizontalAlignment = .left backBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: -5, bottom: 0, right: 0) backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0) backBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -2, 0, 0) self.init(customView: backBtn) } }
mit
c35825a457c3b47d930cd459838bff17
35.09375
87
0.657143
4.010417
false
false
false
false
hoangdang1449/FontBlaster
FontBlaster.swift
1
6385
// // FontBlaster.swift // FontBlaster // // Created by Arthur Sabintsev on 5/5/15. // Copyright (c) 2015 Arthur Ariel Sabintsev. All rights reserved. // import Foundation import CoreGraphics import CoreText // MARK: Enumerations /** Limits the type of fonts that can be loaded into an application There are two options: - TrueTypeFont - OpenTypeFont */ private enum SupportedFontExtensions: String { case TrueTypeFont = ".ttf" case OpenTypeFont = ".otf" } // MARK: FontBlaster Class /** The FontBlaster Class. Only one class method can be accessed - blast(_:) Only one class variable can be accessed and modified - debugEnabled */ public class FontBlaster { // Typealiases to better handle of the different aspects of loading a font private typealias FontPath = String private typealias FontName = String private typealias FontExtension = String private typealias Font = (FontPath, FontName, FontExtension) /** Used to toggle debug println() statements */ public static var debugEnabled = false /** Load all fonts found in a specific bundle. If no value is entered, it defaults to NSBundle.mainBundle(). */ public class func blast(bundle: NSBundle = NSBundle.mainBundle()) { let path = bundle.bundlePath loadFontsForBundleWithPath(path) loadFontsFromBundlesFoundInBundle(path) } } // MARK: Helpers (Font Loading) private extension FontBlaster { /** Loads all fonts found in a bundle. - parameter path: The absolute path to the bundle. */ class func loadFontsForBundleWithPath(path: String) { do { let contents = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(path) let fonts = fontsFromPath(path: path, contents: contents) if !fonts.isEmpty { for font in fonts { loadFont(font) } } else { printStatus("No fonts were found in the bundle path: \(path).") } } catch let error as NSError { printStatus("There was an error loading fonts from the bundle. \nPath: \(path).\nError: \(error)") } } /** Loads all fonts found in a bundle that is loaded within another bundle. - parameter path: The absolute path to the bundle. */ class func loadFontsFromBundlesFoundInBundle(path: String) { do { let contents = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(path) for item in contents { if let url = NSURL(string: path) { if item.containsString(".bundle") { let urlPath = url.URLByAppendingPathComponent(item) loadFontsForBundleWithPath(urlPath.absoluteString) } } } } catch let error as NSError { printStatus("There was an error accessing bundle with path. \nPath: \(path).\nError: \(error)") } } /** Loads a specific font. - parameter font: The font to load. */ class func loadFont(font: Font) { let fontPath: FontPath = font.0 let fontName: FontPath = font.1 let fontExtension: FontPath = font.2 guard let fontFileURL = NSBundle(path: fontPath)?.URLForResource(fontName, withExtension: fontExtension) else { printStatus("Could not unwrap the file URL for the resource with name: \(fontName) and extension \(fontExtension)") return } var fontError: Unmanaged<CFError>? if CTFontManagerRegisterFontsForURL(fontFileURL, CTFontManagerScope.Process, &fontError) { printStatus("Successfully loaded font: '\(fontName)'.") } else { guard let fontError = fontError?.takeRetainedValue() else { printStatus("Failed to load font '\(fontName)'.") return } let errorDescription = CFErrorCopyDescription(fontError) printStatus("Failed to load font '\(fontName)': \(errorDescription)") } } } // MARK: Helpers (Miscellaneous) private extension FontBlaster { /** Parses a font into its name and extension components. - parameter path: The absolute path to the font file. - parameter contents: The contents of an NSBundle as an array of String objects. - returns: A tuple with the font's name and extension. */ class func fontsFromPath(path path: String, contents: [NSString]) -> [Font] { var fonts = [Font]() for fontName in contents { var parsedFont: (FontName, FontExtension)? if fontName.respondsToSelector(Selector("containsString:")) { // iOS 8+ if fontName.containsString(SupportedFontExtensions.TrueTypeFont.rawValue) || fontName.containsString(SupportedFontExtensions.OpenTypeFont.rawValue) { parsedFont = fontFromName(fontName as String) } } else { // iOS 7 if (fontName.rangeOfString(SupportedFontExtensions.TrueTypeFont.rawValue).location != NSNotFound) || (fontName.rangeOfString(SupportedFontExtensions.OpenTypeFont.rawValue).location != NSNotFound) { parsedFont = fontFromName(fontName as String) } } if let parsedFont = parsedFont { let font: Font = (path, parsedFont.0, parsedFont.1) fonts.append(font) } } return fonts } /** Parses a font into its name and extension components. - parameter The: name of the font. - returns: A tuple with the font's name and extension. */ class func fontFromName(name: String) -> (FontName, FontExtension) { let components = name.characters.split{$0 == "."}.map { String($0) } return (components[0], components[1]) } /** Prints debug messages to the console if debugEnabled is set to true. - parameter The: status to print to the console. */ class func printStatus(status: String) { if debugEnabled == true { print("[FontBlaster]: \(status)") } } }
mit
ab17d5d1ce657db8b6d5673d42fd2400
33.327957
213
0.607674
4.907763
false
false
false
false
SEMT2Group1/CASPER_IOS_Client
casper/LidarMapper.swift
1
2917
// // LidarMapper.swift // casper // // Created by Pontus Pohl on 24/04/16. // Copyright © 2016 Pontus Pohl. All rights reserved. // import Foundation import CocoaAsyncSocket class LidarMapper : NSObject, GCDAsyncUdpSocketDelegate{ let HOST:String = "devpi.smallwhitebird.org" let PORT:UInt16 = 9998 var outSocket:GCDAsyncUdpSocket! let userDefaults = NSUserDefaults.standardUserDefaults() var token:NSString = "" weak var delegate:LidarMapperDelegate? init(delegate: LidarMapperDelegate){ self.delegate = delegate super.init() } func setupConnection() -> Bool{ outSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue:dispatch_get_main_queue()) do { // try inSocket.bindToPort(PORT) // try inSocket.enableBroadcast(true) // try inSocket.joinMulticastGroup(HOST) // try inSocket.beginReceiving() try outSocket.enableBroadcast(true) try outSocket.connectToHost(HOST, onPort: PORT) try outSocket.beginReceiving() if(self.userDefaults.objectForKey("token") as? String != ""){ self.token = self.userDefaults.objectForKey("token") as! String print("token is"+(self.token as String)) self.sendStart() print("Starting idle message timer") return true } else{ if(self.token as String != "test"){ print("token is empty") return false } } } catch let error as NSError{ print(error.localizedDescription) print("Something went wrong!") return false } return false } func sendStart(){ print("sending start") var message = [UInt8](count: 0, repeatedValue: 0) // var token = "a71d1842e87c0aa2" let tokenData = self.token.dataUsingEncoding(NSUTF8StringEncoding) let count = tokenData!.length / sizeof(UInt8) // create array of appropriate length: var byteArray = [UInt8](count: count, repeatedValue: 0) // copy bytes into array tokenData!.getBytes(&byteArray, length:count * sizeof(UInt8)) message.append(0x4c) message.append(0x53) message.appendContentsOf(byteArray) let msgEnd : [UInt8] = [0x0d, 0x0a, 0x04] message.appendContentsOf(msgEnd) // let data = message.dataUsingEncoding(NSUTF8StringEncoding) outSocket.sendData(NSData(bytes: message,length:message.count), withTimeout: 2, tag: 0) } }
mit
27ea7f61d0699102d28c519a5d8aa29a
30.365591
95
0.550754
4.749186
false
false
false
false
tush4r/Edbinx
EdBinx/Pods/XLPagerTabStrip/Sources/ButtonBarPagerTabStripViewController.swift
1
18595
// ButtonBarPagerTabStripViewController.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public enum ButtonBarItemSpec<CellType: UICollectionViewCell> { case nibFile(nibName: String, bundle: Bundle?, width:((IndicatorInfo)-> CGFloat)) case cellClass(width:((IndicatorInfo)-> CGFloat)) public var weight: ((IndicatorInfo) -> CGFloat) { switch self { case .cellClass(let widthCallback): return widthCallback case .nibFile(_, _, let widthCallback): return widthCallback } } } public struct ButtonBarPagerTabStripSettings { public struct Style { public var buttonBarBackgroundColor: UIColor? @available(*, deprecated: 4.0.2) public var buttonBarMinimumInteritemSpacing: CGFloat? = 0 public var buttonBarMinimumLineSpacing: CGFloat? public var buttonBarLeftContentInset: CGFloat? public var buttonBarRightContentInset: CGFloat? public var selectedBarBackgroundColor = UIColor.black public var selectedBarHeight: CGFloat = 5 public var buttonBarItemBackgroundColor: UIColor? public var buttonBarItemFont = UIFont.systemFont(ofSize: 18) public var buttonBarItemLeftRightMargin: CGFloat = 8 public var buttonBarItemTitleColor: UIColor? public var buttonBarItemsShouldFillAvailiableWidth = true // only used if button bar is created programaticaly and not using storyboards or nib files public var buttonBarHeight: CGFloat? } public var style = Style() } open class ButtonBarPagerTabStripViewController: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate, UICollectionViewDelegate, UICollectionViewDataSource { open var settings = ButtonBarPagerTabStripSettings() lazy open var buttonBarItemSpec: ButtonBarItemSpec<ButtonBarViewCell> = .nibFile(nibName: "ButtonCell", bundle: Bundle(for: ButtonBarViewCell.self), width:{ [weak self] (childItemInfo) -> CGFloat in let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = self?.settings.style.buttonBarItemFont label.text = childItemInfo.title let labelSize = label.intrinsicContentSize return labelSize.width + (self?.settings.style.buttonBarItemLeftRightMargin ?? 8) * 2 }) open var changeCurrentIndex: ((_ oldCell: ButtonBarViewCell?, _ newCell: ButtonBarViewCell?, _ animated: Bool) -> Void)? open var changeCurrentIndexProgressive: ((_ oldCell: ButtonBarViewCell?, _ newCell: ButtonBarViewCell?, _ progressPercentage: CGFloat, _ changeCurrentIndex: Bool, _ animated: Bool) -> Void)? @IBOutlet open lazy var buttonBarView: ButtonBarView! = { [unowned self] in var flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = .horizontal let buttonBarHeight = self.settings.style.buttonBarHeight ?? 44 let buttonBar = ButtonBarView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: buttonBarHeight), collectionViewLayout: flowLayout) buttonBar.backgroundColor = .orange buttonBar.selectedBar.backgroundColor = .black buttonBar.autoresizingMask = .flexibleWidth var newContainerViewFrame = self.containerView.frame newContainerViewFrame.origin.y = buttonBarHeight newContainerViewFrame.size.height = self.containerView.frame.size.height - (buttonBarHeight - self.containerView.frame.origin.y) self.containerView.frame = newContainerViewFrame return buttonBar }() lazy fileprivate var cachedCellWidths: [CGFloat]? = { [unowned self] in return self.calculateWidths() }() override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) delegate = self datasource = self } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) delegate = self datasource = self } open override func viewDidLoad() { super.viewDidLoad() if buttonBarView.superview == nil { view.addSubview(buttonBarView) } if buttonBarView.delegate == nil { buttonBarView.delegate = self } if buttonBarView.dataSource == nil { buttonBarView.dataSource = self } buttonBarView.scrollsToTop = false let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout flowLayout.scrollDirection = .horizontal flowLayout.minimumInteritemSpacing = 0 flowLayout.minimumLineSpacing = settings.style.buttonBarMinimumLineSpacing ?? flowLayout.minimumLineSpacing let sectionInset = flowLayout.sectionInset flowLayout.sectionInset = UIEdgeInsetsMake(sectionInset.top, self.settings.style.buttonBarLeftContentInset ?? sectionInset.left, sectionInset.bottom, self.settings.style.buttonBarRightContentInset ?? sectionInset.right) buttonBarView.showsHorizontalScrollIndicator = false buttonBarView.backgroundColor = settings.style.buttonBarBackgroundColor ?? buttonBarView.backgroundColor buttonBarView.selectedBar.backgroundColor = settings.style.selectedBarBackgroundColor buttonBarView.selectedBarHeight = settings.style.selectedBarHeight ?? buttonBarView.selectedBarHeight // register button bar item cell switch buttonBarItemSpec { case .nibFile(let nibName, let bundle, _): buttonBarView.register(UINib(nibName: nibName, bundle: bundle), forCellWithReuseIdentifier:"Cell") case .cellClass: buttonBarView.register(ButtonBarViewCell.self, forCellWithReuseIdentifier:"Cell") } //- } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) buttonBarView.layoutIfNeeded() } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard isViewAppearing || isViewRotating else { return } // Force the UICollectionViewFlowLayout to get laid out again with the new size if // a) The view is appearing. This ensures that // collectionView:layout:sizeForItemAtIndexPath: is called for a second time // when the view is shown and when the view *frame(s)* are actually set // (we need the view frame's to have been set to work out the size's and on the // first call to collectionView:layout:sizeForItemAtIndexPath: the view frame(s) // aren't set correctly) // b) The view is rotating. This ensures that // collectionView:layout:sizeForItemAtIndexPath: is called again and can use the views // *new* frame so that the buttonBarView cell's actually get resized correctly cachedCellWidths = calculateWidths() buttonBarView.collectionViewLayout.invalidateLayout() // When the view first appears or is rotated we also need to ensure that the barButtonView's // selectedBar is resized and its contentOffset/scroll is set correctly (the selected // tab/cell may end up either skewed or off screen after a rotation otherwise) buttonBarView.moveToIndex(currentIndex, animated: false, swipeDirection: .none, pagerScroll: .scrollOnlyIfOutOfScreen) } // MARK: - Public Methods open override func reloadPagerTabStripView() { super.reloadPagerTabStripView() guard isViewLoaded else { return } buttonBarView.reloadData() cachedCellWidths = calculateWidths() buttonBarView.moveToIndex(currentIndex, animated: false, swipeDirection: .none, pagerScroll: .yes) } open func calculateStretchedCellWidths(_ minimumCellWidths: [CGFloat], suggestedStretchedCellWidth: CGFloat, previousNumberOfLargeCells: Int) -> CGFloat { var numberOfLargeCells = 0 var totalWidthOfLargeCells: CGFloat = 0 for minimumCellWidthValue in minimumCellWidths where minimumCellWidthValue > suggestedStretchedCellWidth { totalWidthOfLargeCells += minimumCellWidthValue numberOfLargeCells += 1 } guard numberOfLargeCells > previousNumberOfLargeCells else { return suggestedStretchedCellWidth } let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout let collectionViewAvailiableWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right let numberOfCells = minimumCellWidths.count let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing let numberOfSmallCells = numberOfCells - numberOfLargeCells let newSuggestedStretchedCellWidth = (collectionViewAvailiableWidth - totalWidthOfLargeCells - cellSpacingTotal) / CGFloat(numberOfSmallCells) return calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: newSuggestedStretchedCellWidth, previousNumberOfLargeCells: numberOfLargeCells) } open func pagerTabStripViewController(_ pagerTabStripViewController: PagerTabStripViewController, updateIndicatorFromIndex fromIndex: Int, toIndex: Int) { guard shouldUpdateButtonBarView else { return } buttonBarView.moveToIndex(toIndex, animated: true, swipeDirection: toIndex < fromIndex ? .right : .left, pagerScroll: .yes) if let changeCurrentIndex = changeCurrentIndex { let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarViewCell let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarViewCell changeCurrentIndex(oldCell, newCell, true) } } open func pagerTabStripViewController(_ pagerTabStripViewController: PagerTabStripViewController, updateIndicatorFromIndex fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) { guard shouldUpdateButtonBarView else { return } buttonBarView.moveFromIndex(fromIndex, toIndex: toIndex, progressPercentage: progressPercentage, pagerScroll: .yes) if let changeCurrentIndexProgressive = changeCurrentIndexProgressive { let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarViewCell let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarViewCell changeCurrentIndexProgressive(oldCell, newCell, progressPercentage, indexWasChanged, true) } } // MARK: - UICollectionViewDelegateFlowLayut open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { guard let cellWidthValue = cachedCellWidths?[(indexPath as NSIndexPath).row] else { fatalError("cachedCellWidths for \((indexPath as NSIndexPath).row) must not be nil") } return CGSize(width: cellWidthValue, height: collectionView.frame.size.height) } open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard (indexPath as NSIndexPath).item != currentIndex else { return } buttonBarView.moveToIndex((indexPath as NSIndexPath).item, animated: true, swipeDirection: .none, pagerScroll: .yes) shouldUpdateButtonBarView = false let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarViewCell let newCell = buttonBarView.cellForItem(at: IndexPath(item: (indexPath as NSIndexPath).item, section: 0)) as? ButtonBarViewCell if pagerBehaviour.isProgressiveIndicator { if let changeCurrentIndexProgressive = changeCurrentIndexProgressive { changeCurrentIndexProgressive(oldCell, newCell, 1, true, true) } } else { if let changeCurrentIndex = changeCurrentIndex { changeCurrentIndex(oldCell, newCell, true) } } moveToViewControllerAtIndex((indexPath as NSIndexPath).item) } // MARK: - UICollectionViewDataSource open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewControllers.count } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? ButtonBarViewCell else { fatalError("UICollectionViewCell should be or extend from ButtonBarViewCell") } let childController = viewControllers[(indexPath as NSIndexPath).item] as! IndicatorInfoProvider let indicatorInfo = childController.indicatorInfoForPagerTabStrip(self) cell.label.text = indicatorInfo.title cell.label.font = settings.style.buttonBarItemFont ?? cell.label.font cell.label.textColor = settings.style.buttonBarItemTitleColor ?? cell.label.textColor cell.contentView.backgroundColor = settings.style.buttonBarItemBackgroundColor ?? cell.contentView.backgroundColor cell.backgroundColor = settings.style.buttonBarItemBackgroundColor ?? cell.backgroundColor if let image = indicatorInfo.image { cell.imageView.image = image } if let highlightedImage = indicatorInfo.highlightedImage { cell.imageView.highlightedImage = highlightedImage } configureCell(cell, indicatorInfo: indicatorInfo) if pagerBehaviour.isProgressiveIndicator { if let changeCurrentIndexProgressive = changeCurrentIndexProgressive { changeCurrentIndexProgressive(currentIndex == (indexPath as NSIndexPath).item ? nil : cell, currentIndex == (indexPath as NSIndexPath).item ? cell : nil, 1, true, false) } } else { if let changeCurrentIndex = changeCurrentIndex { changeCurrentIndex(currentIndex == (indexPath as NSIndexPath).item ? nil : cell, currentIndex == (indexPath as NSIndexPath).item ? cell : nil, false) } } return cell } // MARK: - UIScrollViewDelegate open override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { super.scrollViewDidEndScrollingAnimation(scrollView) guard scrollView == containerView else { return } shouldUpdateButtonBarView = true } open func configureCell(_ cell: ButtonBarViewCell, indicatorInfo: IndicatorInfo){ } fileprivate func calculateWidths() -> [CGFloat] { let flowLayout = self.buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout let numberOfCells = self.viewControllers.count var minimumCellWidths = [CGFloat]() var collectionViewContentWidth: CGFloat = 0 for viewController in self.viewControllers { let childController = viewController as! IndicatorInfoProvider let indicatorInfo = childController.indicatorInfoForPagerTabStrip(self) switch buttonBarItemSpec { case .cellClass(let widthCallback): let width = widthCallback(indicatorInfo) minimumCellWidths.append(width) collectionViewContentWidth += width case .nibFile(_, _, let widthCallback): let width = widthCallback(indicatorInfo) minimumCellWidths.append(width) collectionViewContentWidth += width } } let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing collectionViewContentWidth += cellSpacingTotal let collectionViewAvailableVisibleWidth = self.buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right if !settings.style.buttonBarItemsShouldFillAvailiableWidth || collectionViewAvailableVisibleWidth < collectionViewContentWidth { return minimumCellWidths } else { let stretchedCellWidthIfAllEqual = (collectionViewAvailableVisibleWidth - cellSpacingTotal) / CGFloat(numberOfCells) let generalMinimumCellWidth = self.calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: stretchedCellWidthIfAllEqual, previousNumberOfLargeCells: 0) var stretchedCellWidths = [CGFloat]() for minimumCellWidthValue in minimumCellWidths { let cellWidth = (minimumCellWidthValue > generalMinimumCellWidth) ? minimumCellWidthValue : generalMinimumCellWidth stretchedCellWidths.append(cellWidth) } return stretchedCellWidths } } fileprivate var shouldUpdateButtonBarView = true }
mit
2857376c5e28d7a374e361442ab6cfee
50.941341
233
0.70761
5.975257
false
false
false
false
hawkfalcon/SpaceEvaders
SpaceEvaders/Rocket.swift
1
1392
import SpriteKit class Rocket: Sprite { var fireArray = Array<SKTexture>(); init(x: CGFloat, y: CGFloat) { super.init(named: "rocket", x: x, y: y) self.setScale(2.5) fire() } func fire() { for index in 0 ... 2 { fireArray.append(SKTexture(imageNamed: "fire\(index)")) } let fire = SKSpriteNode(texture: fireArray[0]); fire.anchorPoint = CGPoint(x: 0.5, y: 1.3) self.addChild(fire) let animateAction = SKAction.animate(with: self.fireArray, timePerFrame: 0.10); fire.run(SKAction.repeatForever(animateAction)) } func moveTo(x: CGFloat, y: CGFloat) { let speed: CGFloat = 12 var dx: CGFloat, dy: CGFloat // Compute vector components in direction of the touch dx = x - self.position.x dy = y - self.position.y + 50 self.zRotation = atan2(dy + 100, dx) - CGFloat(Double.pi / 2) //Do not move if tap is on sprite if (dx >= 1 || dx <= -1) && (dy >= 1 || dy <= 1) { let mag = sqrt(dx * dx + dy * dy) // Normalize and scale dx = dx / mag * speed dy = (dy + 50) / mag * speed self.position = CGPoint(x: self.position.x + dx, y: self.position.y + dy) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
5d17a3333b4d81fa49cc58b2e1ac70c9
31.372093
87
0.541667
3.68254
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Stats/Shared Views/GrowAudienceCell.swift
1
14253
import UIKit class GrowAudienceCell: UITableViewCell, NibLoadable { @IBOutlet weak var viewCountStackView: UIStackView! @IBOutlet weak var viewCountLabel: UILabel! @IBOutlet weak var viewCountDescriptionLabel: UILabel! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var detailsLabel: UILabel! @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var dismissButton: UIButton! @IBOutlet weak var actionButton: UIButton! private var hintType: HintType? private weak var insightsDelegate: SiteStatsInsightsDelegate? override func awakeFromNib() { super.awakeFromNib() applyStyles() } // MARK: - Configuration func configure(hintType: HintType, allTimeViewsCount: Int, isNudgeCompleted: Bool, insightsDelegate: SiteStatsInsightsDelegate?) { self.hintType = hintType self.insightsDelegate = insightsDelegate viewCountLabel.text = String(allTimeViewsCount) viewCountDescriptionLabel.text = Strings.getViewsCountDescription(viewsCount: allTimeViewsCount) iconView.image = hintType.image dismissButton.setTitle(Strings.dismissButtonTitle, for: .normal) updateView(isCompleted: isNudgeCompleted) prepareForVoiceOver(hintType: hintType, allTimeViewsCount: allTimeViewsCount, isNudgeCompleted: isNudgeCompleted) } // MARK: - A11y func prepareForVoiceOver(hintType: HintType, allTimeViewsCount: Int, isNudgeCompleted: Bool) { viewCountStackView.isAccessibilityElement = true viewCountStackView.accessibilityTraits = .staticText viewCountStackView.accessibilityLabel = Strings.getViewCountSummary(viewsCount: allTimeViewsCount) tipLabel.isAccessibilityElement = true tipLabel.accessibilityTraits = .staticText tipLabel.accessibilityLabel = hintType.getTipTitle((isNudgeCompleted)) detailsLabel.isAccessibilityElement = true detailsLabel.accessibilityTraits = .staticText detailsLabel.accessibilityLabel = hintType.getDetailsTitle(isNudgeCompleted) dismissButton.accessibilityLabel = Strings.dismissButtonTitle actionButton.accessibilityLabel = hintType.getActionButtonTitle(isNudgeCompleted) accessibilityElements = [ viewCountStackView, tipLabel, detailsLabel, dismissButton, actionButton ].compactMap { $0 } } // MARK: - Styling private func applyStyles() { selectionStyle = .none backgroundColor = .listForeground if FeatureFlag.statsNewAppearance.disabled { addBottomBorder(withColor: .divider) } viewCountLabel.font = WPStyleGuide.fontForTextStyle(.title1) viewCountLabel.textColor = .textSubtle viewCountDescriptionLabel.font = WPStyleGuide.fontForTextStyle(.body) viewCountDescriptionLabel.textColor = .textSubtle tipLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold) tipLabel.textColor = .text tipLabel.numberOfLines = 0 detailsLabel.font = WPStyleGuide.fontForTextStyle(.subheadline) detailsLabel.textColor = .text detailsLabel.numberOfLines = 0 dismissButton.titleLabel?.font = WPStyleGuide.fontForTextStyle(.body) actionButton.titleLabel?.font = WPStyleGuide.fontForTextStyle(.body, fontWeight: .medium) } private func updateView(isCompleted: Bool) { guard let hintType = hintType else { return } viewCountStackView.isHidden = isCompleted iconView.isHidden = isCompleted tipLabel.text = hintType.getTipTitle(isCompleted) detailsLabel.text = hintType.getDetailsTitle(isCompleted) actionButton.setTitle(hintType.getActionButtonTitle(isCompleted), for: .normal) layoutIfNeeded() } // MARK: - IBAction @IBAction private func dismissButtonTapped(_ sender: UIButton) { guard let hintType = hintType else { return } insightsDelegate?.growAudienceDismissButtonTapped?(hintType) } @IBAction private func actionButtonTapped(_ sender: UIButton) { guard let hintType = hintType else { return } switch hintType { case .social: insightsDelegate?.growAudienceEnablePostSharingButtonTapped?() case .bloggingReminders: insightsDelegate?.growAudienceBloggingRemindersButtonTapped?() case .readerDiscover: insightsDelegate?.growAudienceReaderDiscoverButtonTapped?() } } // MARK: - Localization private enum Strings { static let viewsCountDescriptionSingular = NSLocalizedString( "growAudienceCell.viewsCount.singular", value: "View to your site so far", comment: "Description for view count. Singular." ) static let viewsCountDescriptionPlural = NSLocalizedString( "growAudienceCell.viewsCount.plural", value: "Views to your site so far", comment: "Description for view count. Singular." ) static let tipTitle = NSLocalizedString( "growAudienceCell.tip", value: "A tip to grow your audience", comment: "A hint to users about growing the audience for their site, when their site doesn't have many views yet." ) static let dismissButtonTitle = NSLocalizedString( "growAudienceCell.dismiss", value: "Dismiss", comment: "Title for button that will dismiss the Grow Your Audience card." ) static func getViewsCountDescription(viewsCount: Int) -> String { return viewsCount == 1 ? viewsCountDescriptionSingular : viewsCountDescriptionPlural } static func getViewCountSummary(viewsCount: Int) -> String { let description = getViewsCountDescription(viewsCount: viewsCount) return "\(viewsCount) \(description)" } enum Social { static let detailsTitle = NSLocalizedString( "growAudienceCell.social.title", value: "Automatically share new posts to your social media to start bringing that audience over to your site.", comment: "A detailed message to users about growing the audience for their site through enabling post sharing." ) static let actionButtonTitle = NSLocalizedString( "growAudienceCell.social.actionButton", value: "Enable post sharing", comment: "Title for button that will open up the social media Sharing screen." ) static let completedTipTitle = NSLocalizedString( "growAudienceCell.social.completed.title", value: "Sharing is set up!", comment: "A hint to users that they've set up post sharing." ) static let completedDetailsTitle = NSLocalizedString( "growAudienceCell.social.completed.details", value: "When you publish your next post it will be automatically shared to your connected networks.", comment: "A detailed message to users indicating that they've set up post sharing." ) static let completedActionButtonTitle = NSLocalizedString( "growAudienceCell.social.completed.button", value: "Connect more networks", comment: "Title for button that will open up the social media Sharing screen." ) } enum BloggingReminders { static let detailsTitle = NSLocalizedString( "growAudienceCell.bloggingReminders.details", value: "Posting regularly can help build an audience. Reminders help keep you on track.", comment: "A detailed message to users about growing the audience for their site through blogging reminders." ) static let actionButtonTitle = NSLocalizedString( "growAudienceCell.bloggingReminders.actionButton", value: "Set up blogging reminders", comment: "Title for button that will open up the blogging reminders screen." ) static let completedTipTitle = NSLocalizedString( "growAudienceCell.bloggingReminders.completed.tip", value: "You set up blogging reminders", comment: "A hint to users that they've set up blogging reminders." ) static let completedDetailsTitle = NSLocalizedString( "growAudienceCell.bloggingReminders.completed.details", value: "Keep blogging and check back to see visitors arriving at your site.", comment: "A detailed message to users indicating that they've set up blogging reminders." ) static let completedActionButtonTitle = NSLocalizedString( "growAudienceCell.bloggingReminders.completed.actionButton", value: "Edit reminders", comment: "Title for button that will open up the blogging reminders screen." ) } enum ReaderDiscover { static let detailsTitle = NSLocalizedString( "growAudienceCell.readerDiscover.details", value: "Connect with other bloggers by following, liking and commenting on their posts.", comment: "A detailed message to users about growing the audience for their site through reader discover." ) static let actionButtonTitle = NSLocalizedString( "growAudienceCell.readerDiscover.actionButton", value: "Discover blogs to follow", comment: "Title for button that will open up the follow topics screen." ) static let completedTipTitle = NSLocalizedString( "growAudienceCell.readerDiscover.completed.tip", value: "You've connected with other blogs", comment: "A hint to users that they've set up reader discover." ) static let completedDetailsTitle = NSLocalizedString( "growAudienceCell.readerDiscover.completed.details", value: "Keep going! Liking and commenting is a good way to build a network. Go to Reader to find more posts.", comment: "A detailed message to users indicating that they've set up reader discover." ) static let completedActionButtonTitle = NSLocalizedString( "growAudienceCell.readerDiscover.completed.action", value: "Do it again", comment: "Title for button that will open up the follow topics screen." ) } } } extension GrowAudienceCell { @objc enum HintType: Int, SiteStatsPinnable { case social case bloggingReminders case readerDiscover func getTipTitle(_ isCompleted: Bool) -> String { return isCompleted ? completedTipTitle : Strings.tipTitle } func getDetailsTitle(_ isCompleted: Bool) -> String { return isCompleted ? completedDetailsTitle : detailsTitle } func getActionButtonTitle(_ isCompleted: Bool) -> String { return isCompleted ? completedActionButtonTitle : actionButtonTitle } var completedTipTitle: String { switch self { case .social: return Strings.Social.completedTipTitle case .bloggingReminders: return Strings.BloggingReminders.completedTipTitle case .readerDiscover: return Strings.ReaderDiscover.completedTipTitle } } var detailsTitle: String { switch self { case .social: return Strings.Social.detailsTitle case .bloggingReminders: return Strings.BloggingReminders.detailsTitle case .readerDiscover: return Strings.ReaderDiscover.detailsTitle } } var completedDetailsTitle: String { switch self { case .social: return Strings.Social.completedDetailsTitle case .bloggingReminders: return Strings.BloggingReminders.completedDetailsTitle case .readerDiscover: return Strings.ReaderDiscover.completedDetailsTitle } } var actionButtonTitle: String { switch self { case .social: return Strings.Social.actionButtonTitle case .bloggingReminders: return Strings.BloggingReminders.actionButtonTitle case .readerDiscover: return Strings.ReaderDiscover.actionButtonTitle } } var completedActionButtonTitle: String { switch self { case .social: return Strings.Social.completedActionButtonTitle case .bloggingReminders: return Strings.BloggingReminders.completedActionButtonTitle case .readerDiscover: return Strings.ReaderDiscover.completedActionButtonTitle } } var image: UIImage? { switch self { case .social: return UIImage(named: "grow-audience-illustration-social") case .bloggingReminders: return UIImage(named: "grow-audience-illustration-blogging-reminders") case .readerDiscover: return UIImage(named: "grow-audience-illustration-reader") } } var userDefaultsKey: String { switch self { case .social: return "social" case .bloggingReminders: return "bloggingReminders" case .readerDiscover: return "readerDiscover" } } } }
gpl-2.0
f9182f53821398f88b2b3eb2e6b6b4bd
37.008
127
0.629832
5.733307
false
false
false
false
JohnCoates/Aerial
Aerial/Source/Models/Sources/Source.swift
1
16246
// // Source.swift // Aerial // // Created by Guillaume Louel on 01/07/2020. // Copyright © 2020 Guillaume Louel. All rights reserved. // import Foundation // 10 has a different format // 11 is similar to 12+, but does not include pointsOfInterests // 12/13 share a same format, and we use that format for local videos too enum SourceType: Int, Codable { case local, tvOS10, tvOS11, tvOS12 } enum SourceScene: String, Codable { case nature = "Nature", city = "City", space = "Space", sea = "Sea", beach = "Beach", countryside = "Countryside" } // swiftlint:disable:next type_body_length struct Source: Codable { var name: String var description: String var manifestUrl: String var type: SourceType var scenes: [SourceScene] var isCachable: Bool var license: String var more: String func isEnabled() -> Bool { if PrefsVideos.enabledSources.keys.contains(name) { return PrefsVideos.enabledSources[name]! } // Unknown sources are enabled by default return true } func diskUsage() -> Double { let path = Cache.supportPath.appending("/" + name) return Cache.getDirectorySize(directory: path) } func wipeFromDisk() { let path = Cache.supportPath.appending("/" + name) if FileManager.default.fileExists(atPath: path) { try? FileManager.default.removeItem(atPath: path) } } func setEnabled(_ enabled: Bool) { PrefsVideos.enabledSources[name] = enabled VideoList.instance.reloadSources() } // Is the source already cached or not ? func isCached() -> Bool { let fileManager = FileManager.default return fileManager.fileExists(atPath: Cache.supportPath.appending("/" + name + "/entries.json")) } func lastUpdated() -> String { if isCached() { var date: Date? if !isCachable && type == .local { date = (try? FileManager.default.attributesOfItem(atPath: Cache.supportPath.appending("/" + name + "/entries.json")))?[.modificationDate] as? Date } else { date = (try? FileManager.default.attributesOfItem(atPath: Cache.supportPath.appending("/" + name + "/entries.json")))?[.creationDate] as? Date } if date != nil { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter.string(from: date!) } else { return "" } } return "" } func getUnprocessedVideos() -> [AerialVideo] { if isCached() { do { let cacheFileUrl = URL(fileURLWithPath: Cache.supportPath.appending("/" + name + "/entries.json")) let jsondata = try Data(contentsOf: cacheFileUrl) return readVideoManifest(jsondata) } catch { errorLog("\(name) could not be opened") return [] } } else { debugLog("\(name) is not cached") return [] } } func getVideos() -> [AerialVideo] { if isCached() { do { let cacheFileUrl = URL(fileURLWithPath: Cache.supportPath.appending("/" + name + "/entries.json")) let jsondata = try Data(contentsOf: cacheFileUrl) if name == "tvOS 10" { return parseOldVideoManifest(jsondata) } else if name.starts(with: "tvOS 13") { return parseVideoManifest(jsondata) + getMissingVideos() // Oh, Victoria Harbour 2... } else { return parseVideoManifest(jsondata) } } catch { errorLog("\(name) could not be opened") return [] } } else { debugLog("\(name) is not cached") return [] } } func localizePath(_ path: String?) -> String { if let tpath = path { if manifestUrl.starts(with: "file://") { return manifestUrl + tpath } return tpath } else { return "" } } // The things we do for one single missing video (for now) ;) func getMissingVideos() -> [AerialVideo] { // We also need to add the missing videos let bundlePath = Bundle(for: PanelWindowController.self).path(forResource: "missingvideos", ofType: "json")! do { let data = try Data(contentsOf: URL(fileURLWithPath: bundlePath), options: .mappedIfSafe) return parseVideoManifest(data) } catch { errorLog("missingvideos.json was not found in the bundle") } return [] } // MARK: - JSON processing func readOldJSONFromData(_ data: Data) -> [AerialVideo] { var processedVideos: [AerialVideo] = [] do { let poiStringProvider = PoiStringProvider.sharedInstance let options = JSONSerialization.ReadingOptions.allowFragments let batches = try JSONSerialization.jsonObject(with: data, options: options) as! [NSDictionary] for batch: NSDictionary in batches { let assets = batch["assets"] as! [NSDictionary] // rawCount = assets.count for item in assets { let url = item["url"] as! String let name = item["accessibilityLabel"] as! String let timeOfDay = item["timeOfDay"] as! String let id = item["id"] as! String let type = item["type"] as! String if type != "video" { continue } // We may have a secondary name var secondaryName = "" if let mergename = poiStringProvider.getCommunityName(id: id) { secondaryName = mergename } // We may have POIs to merge /*var poi: [String: String]? if let mergeId = SourceInfo.mergePOI[id] { let poiStringProvider = PoiStringProvider.sharedInstance poi = poiStringProvider.fetchExtraPoiForId(id: mergeId) }*/ let communityPoi = poiStringProvider.getCommunityPoi(id: id) // We may have dupes... let (isDupe, foundDupe) = SourceInfo.findDuplicate(id: id, url1080pH264: url) if isDupe { if foundDupe != nil { // foundDupe!.sources.append(manifest) if foundDupe?.urls[.v1080pH264] == "" { foundDupe?.urls[.v1080pH264] = url } } } else { var url1080pHEVC = "" var url1080pHDR = "" var url4KHEVC = "" var url4KHDR = "" // Check if we have some HEVC urls to merge if let val = SourceInfo.mergeInfo[id] { url1080pHEVC = val["url-1080-SDR"]! url1080pHDR = val["url-1080-HDR"]! url4KHEVC = val["url-4K-SDR"]! url4KHDR = val["url-4K-HDR"]! } let urls: [VideoFormat: String] = [.v1080pH264: url, .v1080pHEVC: url1080pHEVC, .v1080pHDR: url1080pHDR, .v4KHEVC: url4KHEVC, .v4KHDR: url4KHDR ] // Now we can finally add... let video = AerialVideo(id: id, // Must have name: name, // Must have secondaryName: secondaryName, type: type, // Not sure the point of this one ? timeOfDay: timeOfDay, scene: "landscape", urls: urls, source: self, poi: [:], communityPoi: communityPoi) processedVideos.append(video) } } } return processedVideos } catch { errorLog("Error retrieving content listing (old)") return [] } } func getSecondaryNameFor(_ asset: VideoAsset) -> String { let poiStringProvider = PoiStringProvider.sharedInstance if let mergename = poiStringProvider.getCommunityName(id: asset.id) { return mergename } else { return asset.title ?? "" } } func getSceneFor(_ asset: VideoAsset) -> String { if let updatedScene = SourceInfo.getSceneForVideo(id: asset.id) { return updatedScene.rawValue.lowercased() } else { return asset.scene ?? "landscape" } } func urlsFor(_ asset: VideoAsset) -> [VideoFormat: String] { return [.v1080pH264: localizePath(asset.url1080H264), .v1080pHEVC: localizePath(asset.url1080SDR), .v1080pHDR: localizePath(asset.url1080HDR), .v4KHEVC: localizePath(asset.url4KSDR), .v4KHDR: localizePath(asset.url4KHDR) ] } func oldUrlsFor(_ asset: VideoAsset) -> [VideoFormat: String] { var url1080pHEVC = "" var url1080pHDR = "" var url4KHEVC = "" var url4KHDR = "" // Check if we have some HEVC urls to merge if let val = SourceInfo.mergeInfo[asset.id] { url1080pHEVC = val["url-1080-SDR"]! url1080pHDR = val["url-1080-HDR"]! url4KHEVC = val["url-4K-SDR"]! url4KHDR = val["url-4K-HDR"]! } return [.v1080pH264: asset.url ?? "", .v1080pHEVC: url1080pHEVC, .v1080pHDR: url1080pHDR, .v4KHEVC: url4KHEVC, .v4KHDR: url4KHDR ] } func parseOldVideoManifest(_ data: Data) -> [AerialVideo] { do { let oldVideoManifest = try newJSONDecoder().decode(OldVideoManifest.self, from: data) var processedVideos: [AerialVideo] = [] for group in oldVideoManifest { for asset in group.assets { let (isDupe, foundDupe) = SourceInfo.findDuplicate(id: asset.id, url1080pH264: asset.url ?? "") if isDupe { if let dupe = foundDupe { if dupe.urls[.v1080pH264] == "" { dupe.urls[.v1080pH264] = asset.url } } } else { var poi: [String: String]? if let mergeId = SourceInfo.mergePOI[asset.id] { let poiStringProvider = PoiStringProvider.sharedInstance poi = poiStringProvider.fetchExtraPoiForId(id: mergeId) } let video = AerialVideo(id: asset.id, name: asset.accessibilityLabel, secondaryName: getSecondaryNameFor(asset), type: "video", timeOfDay: asset.timeOfDay ?? "day", scene: getSceneFor(asset), urls: oldUrlsFor(asset), source: self, poi: poi ?? [:], communityPoi: PoiStringProvider.sharedInstance.getCommunityPoi(id: asset.id)) processedVideos.append(video) } } } return processedVideos } catch let error { debugLog(error.localizedDescription) errorLog("### Could not parse manifest data") return [] } } func readVideoManifest(_ data: Data) -> [AerialVideo] { if let videoManifest = try? newJSONDecoder().decode(VideoManifest.self, from: data) { var processedVideos: [AerialVideo] = [] for asset in videoManifest.assets { let video = AerialVideo(id: asset.id, name: asset.accessibilityLabel, secondaryName: getSecondaryNameFor(asset), type: "video", timeOfDay: asset.timeOfDay ?? "day", scene: getSceneFor(asset), urls: urlsFor(asset), source: self, poi: asset.pointsOfInterest ?? [:], communityPoi: PoiStringProvider.sharedInstance.getCommunityPoi(id: asset.id)) processedVideos.append(video) } return processedVideos } errorLog("### Could not parse manifest data") return [] } func parseVideoManifest(_ data: Data) -> [AerialVideo] { if let videoManifest = try? newJSONDecoder().decode(VideoManifest.self, from: data) { // Let's save the manifest here // manifest = videoManifest var processedVideos: [AerialVideo] = [] for asset in videoManifest.assets { let (isDupe, _) = SourceInfo.findDuplicate(id: asset.id, url1080pH264: asset.url1080H264 ?? "") if !isDupe { let video = AerialVideo(id: asset.id, name: asset.accessibilityLabel, secondaryName: getSecondaryNameFor(asset), type: "video", timeOfDay: asset.timeOfDay ?? "day", scene: getSceneFor(asset), urls: urlsFor(asset), source: self, poi: asset.pointsOfInterest ?? [:], communityPoi: PoiStringProvider.sharedInstance.getCommunityPoi(id: asset.id)) processedVideos.append(video) } } return processedVideos } errorLog("### Could not parse manifest data") return [] } } // MARK: - VideoManifest /// The newer format used by all our other JSONs struct VideoManifest: Codable { let assets: [VideoAsset] let initialAssetCount, version: Int? } // MARK: - OldVideoManifestElement /// This is tvOS 10's manifest format struct OldVideoManifestElement: Codable { let id: String let assets: [VideoAsset] } typealias OldVideoManifest = [OldVideoManifestElement] // MARK: - VideoAsset /// Common Asset structure for all our JSONs /// /// I've added multiple extra fields that aren't in Apple's JSONs, including: /// - title: as in Los Angeles (accesibilityLabel) / Santa Monica Beach (title) /// - timeOfDay: only on tvOS 10, resurected for custom sources, can also be sunset or sunrise /// - scene: landscape, city, space, sea struct VideoAsset: Codable { let accessibilityLabel, id: String let title: String? let timeOfDay: String? let scene: String? let pointsOfInterest: [String: String]? let url4KHDR, url4KSDR, url1080H264, url1080HDR: String? let url1080SDR, url: String? let type: String? enum CodingKeys: String, CodingKey { case accessibilityLabel, id, pointsOfInterest case title, timeOfDay, scene case url4KHDR = "url-4K-HDR" case url4KSDR = "url-4K-SDR" case url1080H264 = "url-1080-H264" case url1080HDR = "url-1080-HDR" case url1080SDR = "url-1080-SDR" case url case type } }
mit
58710fe2474cead5bd70d0dc4dd4073e
35.342282
117
0.509018
4.945205
false
false
false
false
Kiandr/CrackingCodingInterview
Swift/Ch 4. Trees and Graphs/Ch 4. Trees and Graphs.playground/Pages/4.5 Validate BST.xcplaygroundpage/Contents.swift
1
2311
import Foundation /*: Implement a function to check if a binary tree is a binary search tree. */ extension Tree { func isBST() -> Bool { return isBST(min: nil, max: nil) } private func isBST(min: Element?, max: Element?) -> Bool { guard case .node = self else { return true } if let min = min, let element = element, min >= element { return false } if let max = max, let element = element, max < element { return false } let leftIsBST = left.isBST(min: min, max: element) if leftIsBST { return right.isBST(min: element, max: max) } return false } } let three = Tree.node(element: 3, left: .nil, right: .nil) let seven = Tree.node(element: 7, left: .nil, right: .nil) let eleven = Tree.node(element: 11, left: .nil, right: .nil) var tree = Tree.node(element: 7, left: three, right: .nil) assert(tree.isBST()) tree = .node(element: 7, left: .nil, right: three) assert(tree.isBST() == false) tree = .node(element: 7, left: three, right: eleven) assert(tree.isBST()) tree = .node(element: 7, left: eleven, right: three) assert(tree.isBST() == false) tree = .node(element: 7, left: eleven, right: eleven) assert(tree.isBST() == false) tree = .node(element: 7, left: three, right: three) assert(tree.isBST() == false) var treeDepth = 4 var numberOfElements = 2.pow(treeDepth) - 1 var nodeData = (0..<numberOfElements).map { $0 } tree = Tree(sortedIncreasing: nodeData)! assert(tree.isBST()) var left = tree.left var right = tree.right var lessThanNode = Tree.node(element: -1, left: left, right: left.right) tree = .node(element: 7, left: lessThanNode, right: tree.right) assert(tree.isBST() == false) lessThanNode = .node(element: 8, left: right.left, right: right) tree = .node(element: 7, left: left, right: lessThanNode) assert(tree.isBST() == false) tree = .node(element: 7, left: .nil, right: .nil) tree = tree.insert(3) tree = tree.insert(1) let leftLeft = tree.left.insert(8) tree = .node(element: 7, left: leftLeft, right: .nil) assert(tree.isBST() == false) lessThanNode = .node(element: 1, left: three, right: .nil) tree = .node(element: 7, left: lessThanNode, right: .nil) assert(tree.isBST() == false) print("\(tree.description)")
mit
dc3e1730c713b3344270230bae39aad8
26.511905
72
0.638685
3.131436
false
false
false
false
puyanLiu/LPYFramework
第三方框架改造/YHAlertView/YHAlertView/ClickTextView.swift
1
6016
// // ClickTextView.swift // YHAlertView // // Created by liupuyan on 2017/6/29. // Copyright © 2017年 samuelandkevin. All rights reserved. // import UIKit class ClickTextView: UITextView { private lazy var rectsArray: [[NSMutableDictionary]] = { let rectsArray = [[NSMutableDictionary]]() return rectsArray }() private let coverViewTag = 111 override func addGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) { gestureRecognizer.isEnabled = false super.addGestureRecognizer(gestureRecognizer) return } /// 设置textView的部分为下划线,并且使之可以点击 /// 将下划线对用的文字的frame,文字内容,点击效果背景颜色存储起来,以供点击的时候查询 /// /// - Parameters: /// - underlineTextRange: 需要下划线的文字范围,如果NSRange范围超出总的内容,将过滤掉 /// - underlineColor: 下划线的颜色,以及下划线上面文字的颜色 /// - coverColor: 是否有点击的背景,如果设置相关颜色的话,将会有点击效果,如果为nil将没有 /// - block: 点击文字的时候的回调 func setUnderlineText(underlineTextRange: NSRange, coverColor: UIColor?, block: OperationParamBlock?) { if self.text.characters.count < underlineTextRange.location + underlineTextRange.length { return } // 设置下划线的文字的点击事件 // self.selectedRange 影响 self.selectedTextRange selectedRange = underlineTextRange // 获取选中范围内的矩形框 let seleRects: [UITextSelectionRect] = selectionRects(for: selectedTextRange!) as! [UITextSelectionRect] // 清空选中范围 selectedRange = NSMakeRange(0, 0) // 可能会点击的范围的数组 var selectedArray = [NSMutableDictionary]() for seleRect in seleRects { let rect = seleRect.rect if (rect.size.width == 0 || rect.size.height == 0) { continue; } // 将有用的信息打包<存放到字典中>存储到数组中 let dic = NSMutableDictionary() // 存储文字对应的frame,一段文字可能会有两个甚至多个frame,考虑到文字换行问题 dic.setObject(rect, forKey: "rect" as NSCopying) // 存储下划线对应的文字 dic.setObject(text.substring(with: text.range(from: underlineTextRange)!), forKey: "content" as NSCopying) // 存储相应的回调的block dic.setObject(block!, forKey: "block" as NSCopying) // 存储对应的点击效果背景颜色 if let coverColor = coverColor { dic.setObject(coverColor, forKey: "coverColor" as NSCopying) } selectedArray.append(dic) } // 将可能点击的范围的数组存储到总的数组中 rectsArray.append(selectedArray) } private func touchingSpecial(point: CGPoint) -> [NSMutableDictionary]? { // 从所有的特殊的范围中找到点击的那个点 for selectedArray in rectsArray { for dict in selectedArray { let rect: CGRect = dict.object(forKey: "rect") as! CGRect if rect.contains(point) { return selectedArray } } } return nil } // 点击textView的touchesBegan方法 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // 获取触摸对象 let touch: UITouch = touches.first! // 触摸点 let point = touch.location(in: self) // 通过一个触摸点,查询点击的是不是在下划线对应的文字的frame if let selectedArray = touchingSpecial(point: point) { for dict in selectedArray { if (dict.object(forKey: "coverColor") != nil) { let cover = UIView() cover.backgroundColor = dict.object(forKey: "coverColor") as? UIColor cover.frame = dict.object(forKey: "rect") as! CGRect cover.layer.cornerRadius = 5 cover.tag = coverViewTag insertSubview(cover, at: 0) } } if selectedArray.count > 0 { // 如果说有点击效果的话,加个延时,展示下点击效果,如果没有点击效果的话,直接回调 let dict: NSDictionary = selectedArray.first! let block: OperationParamBlock = dict.object(forKey: "block") as! OperationParamBlock if (dict.object(forKey: "coverColor") != nil) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .microseconds(50)) { block(dict.object(forKey: "content")) } } else { block(dict.object(forKey: "content")) } } } } // 取消点击的时候,清除相关的阴影 override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for subView in subviews { if subView.tag == coverViewTag { subView.removeFromSuperview() } } } // 点击结束的时候 override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for subView in self.subviews { if subView.tag == self.coverViewTag { subView.removeFromSuperview() } } // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .microseconds(50)) { // for subView in self.subviews { // if subView.tag == self.coverViewTag { // subView.removeFromSuperview() // } // } // } } }
apache-2.0
1ff5ffcf4616fa0394e3445df30da1b1
35.598592
118
0.567443
4.422979
false
false
false
false
KyoheiG3/AttributedLabel
AttributedLabel/AttributedLabel.swift
1
7593
// // AttributedLabel.swift // AttributedLabel // // Created by Kyohei Ito on 2015/07/17. // Copyright © 2015年 Kyohei Ito. All rights reserved. // import UIKit @IBDesignable open class AttributedLabel: UIView { public enum ContentAlignment: Int { case center case top case bottom case left case right case topLeft case topRight case bottomLeft case bottomRight func alignOffset(viewSize: CGSize, containerSize: CGSize) -> CGPoint { let xMargin = viewSize.width - containerSize.width let yMargin = viewSize.height - containerSize.height switch self { case .center: return CGPoint(x: max(xMargin / 2, 0), y: max(yMargin / 2, 0)) case .top: return CGPoint(x: max(xMargin / 2, 0), y: 0) case .bottom: return CGPoint(x: max(xMargin / 2, 0), y: max(yMargin, 0)) case .left: return CGPoint(x: 0, y: max(yMargin / 2, 0)) case .right: return CGPoint(x: max(xMargin, 0), y: max(yMargin / 2, 0)) case .topLeft: return CGPoint(x: 0, y: 0) case .topRight: return CGPoint(x: max(xMargin, 0), y: 0) case .bottomLeft: return CGPoint(x: 0, y: max(yMargin, 0)) case .bottomRight: return CGPoint(x: max(xMargin, 0), y: max(yMargin, 0)) } } } /// default is `0`. @IBInspectable open var numberOfLines: Int { get { return container.maximumNumberOfLines } set { container.maximumNumberOfLines = newValue setNeedsDisplay() } } /// default is `Left`. open var contentAlignment: ContentAlignment = .left { didSet { setNeedsDisplay() } } /// `lineFragmentPadding` of `NSTextContainer`. default is `0`. @IBInspectable open var padding: CGFloat { get { return container.lineFragmentPadding } set { container.lineFragmentPadding = newValue setNeedsDisplay() } } /// default is system font 17 plain. open var font = UIFont.systemFont(ofSize: 17) { didSet { setNeedsDisplay() } } /// default is `ByTruncatingTail`. open var lineBreakMode: NSLineBreakMode { get { return container.lineBreakMode } set { container.lineBreakMode = newValue setNeedsDisplay() } } /// default is nil (text draws black). @IBInspectable open var textColor: UIColor? { didSet { setNeedsDisplay() } } /// default is nil. open var paragraphStyle: NSParagraphStyle? { didSet { setNeedsDisplay() } } /// default is nil. open var shadow: NSShadow? { didSet { setNeedsDisplay() } } /// default is nil. open var attributedText: NSAttributedString? { didSet { setNeedsDisplay() } } /// default is nil. @IBInspectable open var text: String? { get { return attributedText?.string } set { if let value = newValue { attributedText = NSAttributedString(string: value) } else { attributedText = nil } } } /// Support for constraint-based layout (auto layout) /// If nonzero, this is used when determining -intrinsicContentSize for multiline labels open var preferredMaxLayoutWidth: CGFloat = 0 /// If need to use intrinsicContentSize set true. /// Also should call invalidateIntrinsicContentSize when intrinsicContentSize is cached. When text was changed for example. public var usesIntrinsicContentSize = false var mergedAttributedText: NSAttributedString? { if let attributedText = attributedText { return mergeAttributes(attributedText) } return nil } let container = NSTextContainer() let layoutManager = NSLayoutManager() public override init(frame: CGRect) { super.init(frame: frame) isOpaque = false contentMode = .redraw lineBreakMode = .byTruncatingTail padding = 0 layoutManager.addTextContainer(container) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) isOpaque = false contentMode = .redraw lineBreakMode = .byTruncatingTail padding = 0 layoutManager.addTextContainer(container) } open override func setNeedsDisplay() { if Thread.isMainThread { super.setNeedsDisplay() } } open override var intrinsicContentSize: CGSize { if usesIntrinsicContentSize { let width = preferredMaxLayoutWidth == 0 ? bounds.width : preferredMaxLayoutWidth let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) return sizeThatFits(size) } else { return bounds.size } } open override func draw(_ rect: CGRect) { guard let attributedText = mergedAttributedText else { return } let storage = NSTextStorage(attributedString: attributedText) storage.addLayoutManager(layoutManager) container.size = rect.size let frame = layoutManager.usedRect(for: container) let point = contentAlignment.alignOffset(viewSize: rect.size, containerSize: frame.integral.size) let glyphRange = layoutManager.glyphRange(for: container) layoutManager.drawBackground(forGlyphRange: glyphRange, at: point) layoutManager.drawGlyphs(forGlyphRange: glyphRange, at: point) } open override func sizeThatFits(_ size: CGSize) -> CGSize { guard let attributedText = mergedAttributedText else { return .zero } let storage = NSTextStorage(attributedString: attributedText) storage.addLayoutManager(layoutManager) container.size = size let frame = layoutManager.usedRect(for: container) return frame.integral.size } open override func sizeToFit() { super.sizeToFit() let width = preferredMaxLayoutWidth == 0 ? CGFloat.greatestFiniteMagnitude : preferredMaxLayoutWidth let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) frame.size = sizeThatFits(size) } func mergeAttributes(_ attributedText: NSAttributedString) -> NSAttributedString { let attrString = NSMutableAttributedString(attributedString: attributedText) attrString.addAttribute(.font, attr: font) if let textColor = textColor { attrString.addAttribute(.foregroundColor, attr: textColor) } if let paragraphStyle = paragraphStyle { attrString.addAttribute(.paragraphStyle, attr: paragraphStyle) } if let shadow = shadow { attrString.addAttribute(.shadow, attr: shadow) } return attrString } } extension NSMutableAttributedString { @discardableResult func addAttribute(_ attrName: NSAttributedString.Key, attr: AnyObject, in range: NSRange? = nil) -> Self { let range = range ?? NSRange(location: 0, length: length) enumerateAttribute(attrName, in: range, options: .reverse) { object, range, pointer in if object == nil { addAttributes([attrName: attr], range: range) } } return self } }
mit
a7620898219035884d46bbf433db1915
30.234568
127
0.609223
5.209334
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/ImageCodec/Algorithm/TIFF/TIFFRawRepresentable.swift
1
15652
// // TIFFRawRepresentable.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. 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. // protocol TIFFRawRepresentable { func tiff_color_data(_ predictor: TIFFPrediction, _ isOpaque: Bool) -> MappedBuffer<UInt8> func tiff_opacity_data(_ predictor: TIFFPrediction) -> MappedBuffer<UInt8> } extension Image: TIFFRawRepresentable { func tiff_color_data(_ predictor: TIFFPrediction, _ isOpaque: Bool) -> MappedBuffer<UInt8> { let samplesPerPixel = isOpaque ? Pixel.Model.numberOfComponents : Pixel.Model.numberOfComponents + 1 let bytesPerSample = 2 var data = MappedBuffer<UInt8>(capacity: self.width * self.height * samplesPerPixel * bytesPerSample, fileBacked: true) self.withUnsafeBufferPointer { guard var source = $0.baseAddress else { return } switch predictor { case .none: let count = self.width * self.height if isOpaque { for _ in 0..<count { let color = source.pointee.color.normalized() for i in 0..<Pixel.Model.numberOfComponents { data.encode(UInt16((color[i] * 65535).clamped(to: 0...65535).rounded()).bigEndian) } source += 1 } } else { for _ in 0..<count { let pixel = source.pointee let color = pixel.color.normalized() for i in 0..<Pixel.Model.numberOfComponents { data.encode(UInt16((color[i] * 65535).clamped(to: 0...65535).rounded()).bigEndian) } data.encode(UInt16((pixel.opacity * 65535).clamped(to: 0...65535).rounded()).bigEndian) source += 1 } } case .subtract: var lhs: [UInt16] = Array(repeating: 0, count: samplesPerPixel) lhs.withUnsafeMutableBufferPointer { guard let lhs = $0.baseAddress else { return } if isOpaque { for _ in 0..<self.height { memset(lhs, 0, samplesPerPixel << 1) for _ in 0..<self.width { let color = source.pointee.color.normalized() for i in 0..<Pixel.Model.numberOfComponents { let c = UInt16((color[i] * 65535).clamped(to: 0...65535).rounded()) let s = c &- lhs[i] data.encode(s.bigEndian) lhs[i] = c } source += 1 } } } else { for _ in 0..<self.height { memset(lhs, 0, samplesPerPixel << 1) for _ in 0..<self.width { let pixel = source.pointee let color = pixel.color.normalized() for i in 0..<Pixel.Model.numberOfComponents { let c = UInt16((color[i] * 65535).clamped(to: 0...65535).rounded()) let s = c &- lhs[i] data.encode(s.bigEndian) lhs[i] = c } do { let c = UInt16((pixel.opacity * 65535).clamped(to: 0...65535).rounded()) let s = c &- lhs[Pixel.Model.numberOfComponents] data.encode(s.bigEndian) lhs[Pixel.Model.numberOfComponents] = c } source += 1 } } } } } } return data } func tiff_opacity_data(_ predictor: TIFFPrediction) -> MappedBuffer<UInt8> { let bytesPerSample = 2 var data = MappedBuffer<UInt8>(capacity: self.width * self.height * bytesPerSample, fileBacked: true) self.withUnsafeBufferPointer { guard var source = $0.baseAddress else { return } switch predictor { case .none: let count = self.width * self.height for _ in 0..<count { data.encode(UInt16((source.pointee.opacity * 65535).clamped(to: 0...65535).rounded()).bigEndian) source += 1 } case .subtract: var lhs: UInt16 = 0 for _ in 0..<self.height { lhs = 0 for _ in 0..<self.width { let c = UInt16((source.pointee.opacity * 65535).clamped(to: 0...65535).rounded()) let s = c &- lhs data.encode(s.bigEndian) lhs = c source += 1 } } } } return data } } func tiff_color_data<Pixel: TIFFEncodablePixel>(_ image: Image<Pixel>, _ predictor: TIFFPrediction, _ isOpaque: Bool) -> MappedBuffer<UInt8> { let samplesPerPixel = isOpaque ? Pixel.numberOfComponents - 1 : Pixel.numberOfComponents let bytesPerSample = MemoryLayout<Pixel>.stride / Pixel.numberOfComponents var data = MappedBuffer<UInt8>(capacity: image.width * image.height * samplesPerPixel * bytesPerSample, fileBacked: true) image.withUnsafeBufferPointer { guard var source = $0.baseAddress else { return } switch predictor { case .none: let count = image.width * image.height if isOpaque { for _ in 0..<count { let pixel = source.pointee pixel.tiff_encode_color(&data) source += 1 } } else { for _ in 0..<count { let pixel = source.pointee pixel.tiff_encode_color(&data) pixel.tiff_encode_opacity(&data) source += 1 } } case .subtract: if isOpaque { for _ in 0..<image.height { var lhs = Pixel() for _ in 0..<image.width { let rhs = source.pointee let pixel = rhs.tiff_prediction_2_encode(lhs) pixel.tiff_encode_color(&data) lhs = rhs source += 1 } } } else { for _ in 0..<image.height { var lhs = Pixel() for _ in 0..<image.width { let rhs = source.pointee let pixel = rhs.tiff_prediction_2_encode(lhs) pixel.tiff_encode_color(&data) pixel.tiff_encode_opacity(&data) lhs = rhs source += 1 } } } } } return data } func tiff_opacity_data<Pixel: TIFFEncodablePixel>(_ image: Image<Pixel>, _ predictor: TIFFPrediction) -> MappedBuffer<UInt8> { let bytesPerSample = MemoryLayout<Pixel>.stride / Pixel.numberOfComponents var data = MappedBuffer<UInt8>(capacity: image.width * image.height * bytesPerSample, fileBacked: true) image.withUnsafeBufferPointer { guard var source = $0.baseAddress else { return } switch predictor { case .none: let count = image.width * image.height for _ in 0..<count { let pixel = source.pointee pixel.tiff_encode_opacity(&data) source += 1 } case .subtract: for _ in 0..<image.height { var lhs = Pixel() for _ in 0..<image.width { let rhs = source.pointee let pixel = rhs.tiff_prediction_2_encode(lhs) pixel.tiff_encode_opacity(&data) lhs = rhs source += 1 } } } } return data } func tiff_color_data<Pixel>(_ image: Image<Pixel>, _ predictor: TIFFPrediction, _ isOpaque: Bool) -> MappedBuffer<UInt8> where Pixel.Model == LabColorModel { let samplesPerPixel = isOpaque ? 3 : 4 let bytesPerSample = 2 var data = MappedBuffer<UInt8>(capacity: image.width * image.height * samplesPerPixel * bytesPerSample, fileBacked: true) image.withUnsafeBufferPointer { guard var source = $0.baseAddress else { return } switch predictor { case .none: let count = image.width * image.height if isOpaque { for _ in 0..<count { let color = source.pointee.color.normalized() data.encode(UInt16((color[0] * 65535).clamped(to: 0...65535).rounded()).bigEndian) data.encode(Int16((color[1] * 65535 - 32768).clamped(to: -32768...32767).rounded()).bigEndian) data.encode(Int16((color[2] * 65535 - 32768).clamped(to: -32768...32767).rounded()).bigEndian) source += 1 } } else { for _ in 0..<count { let pixel = source.pointee let color = pixel.color.normalized() data.encode(UInt16((color[0] * 65535).clamped(to: 0...65535).rounded()).bigEndian) data.encode(Int16((color[1] * 65535 - 32768).clamped(to: -32768...32767).rounded()).bigEndian) data.encode(Int16((color[2] * 65535 - 32768).clamped(to: -32768...32767).rounded()).bigEndian) data.encode(UInt16((pixel.opacity * 65535).clamped(to: 0...65535).rounded()).bigEndian) source += 1 } } case .subtract: if isOpaque { for _ in 0..<image.height { var _l1: UInt16 = 0 var _a1: Int16 = 0 var _b1: Int16 = 0 for _ in 0..<image.width { let color = source.pointee.color.normalized() let _l2 = UInt16((color[0] * 65535).clamped(to: 0...65535).rounded()) let _a2 = Int16((color[1] * 65535 - 32768).clamped(to: -32768...32767).rounded()) let _b2 = Int16((color[2] * 65535 - 32768).clamped(to: -32768...32767).rounded()) let _l3 = _l2 &- _l1 let _a3 = _a2 &- _a1 let _b3 = _b2 &- _b1 data.encode(_l3.bigEndian) data.encode(_a3.bigEndian) data.encode(_b3.bigEndian) _l1 = _l2 _a1 = _a2 _b1 = _b2 source += 1 } } } else { for _ in 0..<image.height { var _l1: UInt16 = 0 var _a1: Int16 = 0 var _b1: Int16 = 0 var _o1: UInt16 = 0 for _ in 0..<image.width { let pixel = source.pointee let color = pixel.color.normalized() let _l2 = UInt16((color[0] * 65535).clamped(to: 0...65535).rounded()) let _a2 = Int16((color[1] * 65535 - 32768).clamped(to: -32768...32767).rounded()) let _b2 = Int16((color[2] * 65535 - 32768).clamped(to: -32768...32767).rounded()) let _o2 = UInt16((pixel.opacity * 65535).clamped(to: 0...65535).rounded()) let _l3 = _l2 &- _l1 let _a3 = _a2 &- _a1 let _b3 = _b2 &- _b1 let _o3 = _o2 &- _o1 data.encode(_l3.bigEndian) data.encode(_a3.bigEndian) data.encode(_b3.bigEndian) data.encode(_o3.bigEndian) _l1 = _l2 _a1 = _a2 _b1 = _b2 _o1 = _o2 source += 1 } } } } } return data }
mit
44af4e8467d5f6264dfd610259352240
37.646914
157
0.412982
5.438499
false
false
false
false
sashohadz/swift
customTableViewCell/CustomTableViewCell/CustomTableViewCell/LoginViewController.swift
1
2234
// // LoginViewController.swift // CustomTableViewCell // // Created by Sasho Hadzhiev on 2/7/17. // Copyright © 2017 Sasho Hadzhiev. All rights reserved. // import UIKit import Leanplum enum UserCheckResult{ case OK, Short, Empty } class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var loginDetailslabel: UILabel! @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var profileImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() self.userNameTextField.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.resultLabel.isHidden = true let appDelegate = UIApplication.shared.delegate as! AppDelegate self.profileImageView.image = appDelegate.profileImage?.imageValue() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { userNameTextField.resignFirstResponder() return true } func checkUser() -> UserCheckResult { guard self.userNameTextField.text != nil else {return .Empty} if self.userNameTextField.text!.characters.count < 3 { return .Short } return .OK } func evaluateUserAndPresentResult() { switch self.checkUser() { case .OK: let userNameValue = userNameTextField.text! as String self.resultLabel.textColor = UIColor.green Leanplum.setUserId(userNameValue) self.resultLabel.text = "Logged in as \(userNameValue)" case .Empty: self.resultLabel.textColor = UIColor.red self.resultLabel.text = "Empty username" case .Short: self.resultLabel.textColor = UIColor.red self.resultLabel.text = "Username too short" } self.resultLabel.isHidden = false } @IBAction func loginButtonPressed(_ sender: UIButton) { evaluateUserAndPresentResult() } }
mit
d707fa25b52aa9bd53eadc2c817686df
28.773333
76
0.653829
5.098174
false
false
false
false
yeziahehe/Gank
Pods/SKPhotoBrowser/SKPhotoBrowser/SKPhotoBrowser.swift
1
21025
// // SKPhotoBrowser.swift // SKViewExample // // Created by suzuki_keishi on 2015/10/01. // Copyright © 2015 suzuki_keishi. All rights reserved. // import UIKit public let SKPHOTO_LOADING_DID_END_NOTIFICATION = "photoLoadingDidEndNotification" // MARK: - SKPhotoBrowser open class SKPhotoBrowser: UIViewController { // open function open var currentPageIndex: Int = 0 open var activityItemProvider: UIActivityItemProvider? open var photos: [SKPhotoProtocol] = [] internal lazy var pagingScrollView: SKPagingScrollView = SKPagingScrollView(frame: self.view.frame, browser: self) // appearance fileprivate let bgColor: UIColor = SKPhotoBrowserOptions.backgroundColor // animation fileprivate let animator: SKAnimator = .init() fileprivate var actionView: SKActionView! fileprivate(set) var paginationView: SKPaginationView! var toolbar: SKToolbar! // actions fileprivate var activityViewController: UIActivityViewController! fileprivate var panGesture: UIPanGestureRecognizer? // for status check property fileprivate var isEndAnimationByToolBar: Bool = true fileprivate var isViewActive: Bool = false fileprivate var isPerformingLayout: Bool = false // pangesture property fileprivate var firstX: CGFloat = 0.0 fileprivate var firstY: CGFloat = 0.0 // timer fileprivate var controlVisibilityTimer: Timer! // delegate open weak var delegate: SKPhotoBrowserDelegate? // statusbar initial state private var statusbarHidden: Bool = UIApplication.shared.isStatusBarHidden // strings open var cancelTitle = "Cancel" // MARK: - Initializer required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } public override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) { super.init(nibName: nil, bundle: nil) setup() } public convenience init(photos: [SKPhotoProtocol]) { self.init(photos: photos, initialPageIndex: 0) } @available(*, deprecated: 5.0.0) public convenience init(originImage: UIImage, photos: [SKPhotoProtocol], animatedFromView: UIView) { self.init(nibName: nil, bundle: nil) self.photos = photos self.photos.forEach { $0.checkCache() } animator.senderOriginImage = originImage animator.senderViewForAnimation = animatedFromView } public convenience init(photos: [SKPhotoProtocol], initialPageIndex: Int) { self.init(nibName: nil, bundle: nil) self.photos = photos self.photos.forEach { $0.checkCache() } self.currentPageIndex = min(initialPageIndex, photos.count - 1) animator.senderOriginImage = photos[currentPageIndex].underlyingImage animator.senderViewForAnimation = photos[currentPageIndex] as? UIView } deinit { NotificationCenter.default.removeObserver(self) } func setup() { modalPresentationCapturesStatusBarAppearance = true modalPresentationStyle = .custom modalTransitionStyle = .crossDissolve NotificationCenter.default.addObserver(self, selector: #selector(handleSKPhotoLoadingDidEndNotification(_:)), name: NSNotification.Name(rawValue: SKPHOTO_LOADING_DID_END_NOTIFICATION), object: nil) } // MARK: - override override open func viewDidLoad() { super.viewDidLoad() configureAppearance() configurePagingScrollView() configureGestureControl() configureActionView() configurePaginationView() configureToolbar() animator.willPresent(self) } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) reloadData() var i = 0 for photo: SKPhotoProtocol in photos { photo.index = i i += 1 } } override open func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() isPerformingLayout = true // where did start delegate?.didShowPhotoAtIndex?(self, index: currentPageIndex) // toolbar toolbar.frame = frameForToolbarAtOrientation() // action actionView.updateFrame(frame: view.frame) // paging switch SKCaptionOptions.captionLocation { case .basic: paginationView.updateFrame(frame: view.frame) case .bottom: paginationView.frame = frameForPaginationAtOrientation() } pagingScrollView.updateFrame(view.bounds, currentPageIndex: currentPageIndex) isPerformingLayout = false } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) isViewActive = true } override open var prefersStatusBarHidden: Bool { return !SKPhotoBrowserOptions.displayStatusbar } // MARK: - Notification @objc open func handleSKPhotoLoadingDidEndNotification(_ notification: Notification) { guard let photo = notification.object as? SKPhotoProtocol else { return } DispatchQueue.main.async(execute: { guard let page = self.pagingScrollView.pageDisplayingAtPhoto(photo), let photo = page.photo else { return } if photo.underlyingImage != nil { page.displayImage(complete: true) self.loadAdjacentPhotosIfNecessary(photo) } else { page.displayImageFailure() } }) } open func loadAdjacentPhotosIfNecessary(_ photo: SKPhotoProtocol) { pagingScrollView.loadAdjacentPhotosIfNecessary(photo, currentPageIndex: currentPageIndex) } // MARK: - initialize / setup open func reloadData() { performLayout() view.setNeedsLayout() } open func performLayout() { isPerformingLayout = true // reset local cache pagingScrollView.reload() pagingScrollView.updateContentOffset(currentPageIndex) pagingScrollView.tilePages() delegate?.didShowPhotoAtIndex?(self, index: currentPageIndex) isPerformingLayout = false } open func prepareForClosePhotoBrowser() { cancelControlHiding() if let panGesture = panGesture { view.removeGestureRecognizer(panGesture) } NSObject.cancelPreviousPerformRequests(withTarget: self) } open func dismissPhotoBrowser(animated: Bool, completion: (() -> Void)? = nil) { prepareForClosePhotoBrowser() if !animated { modalTransitionStyle = .crossDissolve } dismiss(animated: !animated) { completion?() self.delegate?.didDismissAtPageIndex?(self.currentPageIndex) } } open func determineAndClose() { delegate?.willDismissAtPageIndex?(self.currentPageIndex) animator.willDismiss(self) } open func popupShare(includeCaption: Bool = true) { let photo = photos[currentPageIndex] guard let underlyingImage = photo.underlyingImage else { return } var activityItems: [AnyObject] = [underlyingImage] if photo.caption != nil && includeCaption { if let shareExtraCaption = SKPhotoBrowserOptions.shareExtraCaption { let caption = photo.caption ?? "" + shareExtraCaption activityItems.append(caption as AnyObject) } else { activityItems.append(photo.caption as AnyObject) } } if let activityItemProvider = activityItemProvider { activityItems.append(activityItemProvider) } activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) activityViewController.completionWithItemsHandler = { (activity, success, items, error) in self.hideControlsAfterDelay() self.activityViewController = nil } if UI_USER_INTERFACE_IDIOM() == .phone { present(activityViewController, animated: true, completion: nil) } else { activityViewController.modalPresentationStyle = .popover let popover: UIPopoverPresentationController! = activityViewController.popoverPresentationController popover.barButtonItem = toolbar.toolActionButton present(activityViewController, animated: true, completion: nil) } } } // MARK: - Public Function For Customizing Buttons public extension SKPhotoBrowser { func updateCloseButton(_ image: UIImage, size: CGSize? = nil) { actionView.updateCloseButton(image: image, size: size) } func updateDeleteButton(_ image: UIImage, size: CGSize? = nil) { actionView.updateDeleteButton(image: image, size: size) } } // MARK: - Public Function For Browser Control public extension SKPhotoBrowser { func initializePageIndex(_ index: Int) { let i = min(index, photos.count - 1) currentPageIndex = i if isViewLoaded { jumpToPageAtIndex(index) if !isViewActive { pagingScrollView.tilePages() } paginationView.update(currentPageIndex) } } func jumpToPageAtIndex(_ index: Int) { if index < photos.count { if !isEndAnimationByToolBar { return } isEndAnimationByToolBar = false let pageFrame = frameForPageAtIndex(index) pagingScrollView.jumpToPageAtIndex(pageFrame) } hideControlsAfterDelay() } func photoAtIndex(_ index: Int) -> SKPhotoProtocol { return photos[index] } @objc func gotoPreviousPage() { jumpToPageAtIndex(currentPageIndex - 1) } @objc func gotoNextPage() { jumpToPageAtIndex(currentPageIndex + 1) } func cancelControlHiding() { if controlVisibilityTimer != nil { controlVisibilityTimer.invalidate() controlVisibilityTimer = nil } } func hideControlsAfterDelay() { // reset cancelControlHiding() // start controlVisibilityTimer = Timer.scheduledTimer(timeInterval: 4.0, target: self, selector: #selector(SKPhotoBrowser.hideControls(_:)), userInfo: nil, repeats: false) } func hideControls() { setControlsHidden(true, animated: true, permanent: false) } @objc func hideControls(_ timer: Timer) { hideControls() delegate?.controlsVisibilityToggled?(self, hidden: true) } func toggleControls() { let hidden = !areControlsHidden() setControlsHidden(hidden, animated: true, permanent: false) delegate?.controlsVisibilityToggled?(self, hidden: areControlsHidden()) } func areControlsHidden() -> Bool { return paginationView.alpha == 0.0 } func getCurrentPageIndex() -> Int { return currentPageIndex } func addPhotos(photos: [SKPhotoProtocol]) { self.photos.append(contentsOf: photos) self.reloadData() } func insertPhotos(photos: [SKPhotoProtocol], at index: Int) { self.photos.insert(contentsOf: photos, at: index) self.reloadData() } } // MARK: - Internal Function internal extension SKPhotoBrowser { func showButtons() { actionView.animate(hidden: false) } func pageDisplayedAtIndex(_ index: Int) -> SKZoomingScrollView? { return pagingScrollView.pageDisplayedAtIndex(index) } func getImageFromView(_ sender: UIView) -> UIImage { UIGraphicsBeginImageContextWithOptions(sender.frame.size, true, 0.0) sender.layer.render(in: UIGraphicsGetCurrentContext()!) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result! } } // MARK: - Internal Function For Frame Calc internal extension SKPhotoBrowser { func frameForToolbarAtOrientation() -> CGRect { let offset: CGFloat = { if #available(iOS 11.0, *) { return view.safeAreaInsets.bottom } else { return 15 } }() return view.bounds.divided(atDistance: 44, from: .maxYEdge).slice.offsetBy(dx: 0, dy: -offset) } func frameForToolbarHideAtOrientation() -> CGRect { return view.bounds.divided(atDistance: 44, from: .maxYEdge).slice.offsetBy(dx: 0, dy: 44) } func frameForPaginationAtOrientation() -> CGRect { let offset = UIDevice.current.orientation.isLandscape ? 35 : 44 return CGRect(x: 0, y: self.view.bounds.size.height - CGFloat(offset), width: self.view.bounds.size.width, height: CGFloat(offset)) } func frameForPageAtIndex(_ index: Int) -> CGRect { let bounds = pagingScrollView.bounds var pageFrame = bounds pageFrame.size.width -= (2 * 10) pageFrame.origin.x = (bounds.size.width * CGFloat(index)) + 10 return pageFrame } } // MARK: - Internal Function For Button Pressed, UIGesture Control internal extension SKPhotoBrowser { @objc func panGestureRecognized(_ sender: UIPanGestureRecognizer) { guard let zoomingScrollView: SKZoomingScrollView = pagingScrollView.pageDisplayedAtIndex(currentPageIndex) else { return } animator.backgroundView.isHidden = true let viewHeight: CGFloat = zoomingScrollView.frame.size.height let viewHalfHeight: CGFloat = viewHeight/2 var translatedPoint: CGPoint = sender.translation(in: self.view) // gesture began if sender.state == .began { firstX = zoomingScrollView.center.x firstY = zoomingScrollView.center.y hideControls() setNeedsStatusBarAppearanceUpdate() } translatedPoint = CGPoint(x: firstX, y: firstY + translatedPoint.y) zoomingScrollView.center = translatedPoint let minOffset: CGFloat = viewHalfHeight / 4 let offset: CGFloat = 1 - (zoomingScrollView.center.y > viewHalfHeight ? zoomingScrollView.center.y - viewHalfHeight : -(zoomingScrollView.center.y - viewHalfHeight)) / viewHalfHeight view.backgroundColor = bgColor.withAlphaComponent(max(0.7, offset)) // gesture end if sender.state == .ended { if zoomingScrollView.center.y > viewHalfHeight + minOffset || zoomingScrollView.center.y < viewHalfHeight - minOffset { determineAndClose() } else { // Continue Showing View setNeedsStatusBarAppearanceUpdate() view.backgroundColor = bgColor let velocityY: CGFloat = CGFloat(0.35) * sender.velocity(in: self.view).y let finalX: CGFloat = firstX let finalY: CGFloat = viewHalfHeight let animationDuration: Double = Double(abs(velocityY) * 0.0002 + 0.2) UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(animationDuration) UIView.setAnimationCurve(UIView.AnimationCurve.easeIn) zoomingScrollView.center = CGPoint(x: finalX, y: finalY) UIView.commitAnimations() } } } @objc func actionButtonPressed(ignoreAndShare: Bool) { delegate?.willShowActionSheet?(currentPageIndex) guard photos.count > 0 else { return } if let titles = SKPhotoBrowserOptions.actionButtonTitles { let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) actionSheetController.addAction(UIAlertAction(title: cancelTitle, style: .cancel)) for idx in titles.indices { actionSheetController.addAction(UIAlertAction(title: titles[idx], style: .default, handler: { (_) -> Void in self.delegate?.didDismissActionSheetWithButtonIndex?(idx, photoIndex: self.currentPageIndex) })) } if UI_USER_INTERFACE_IDIOM() == .phone { present(actionSheetController, animated: true, completion: nil) } else { actionSheetController.modalPresentationStyle = .popover if let popoverController = actionSheetController.popoverPresentationController { popoverController.sourceView = self.view popoverController.barButtonItem = toolbar.toolActionButton } present(actionSheetController, animated: true, completion: { () -> Void in }) } } else { popupShare() } } func deleteImage() { defer { reloadData() } if photos.count > 1 { pagingScrollView.deleteImage() photos.remove(at: currentPageIndex) if currentPageIndex != 0 { gotoPreviousPage() } paginationView.update(currentPageIndex) } else if photos.count == 1 { dismissPhotoBrowser(animated: true) } } } // MARK: - Private Function private extension SKPhotoBrowser { func configureAppearance() { view.backgroundColor = bgColor view.clipsToBounds = true view.isOpaque = false if #available(iOS 11.0, *) { view.accessibilityIgnoresInvertColors = true } } func configurePagingScrollView() { pagingScrollView.delegate = self view.addSubview(pagingScrollView) } func configureGestureControl() { guard !SKPhotoBrowserOptions.disableVerticalSwipe else { return } panGesture = UIPanGestureRecognizer(target: self, action: #selector(SKPhotoBrowser.panGestureRecognized(_:))) panGesture?.minimumNumberOfTouches = 1 panGesture?.maximumNumberOfTouches = 1 if let panGesture = panGesture { view.addGestureRecognizer(panGesture) } } func configureActionView() { actionView = SKActionView(frame: view.frame, browser: self) view.addSubview(actionView) } func configurePaginationView() { paginationView = SKPaginationView(frame: view.frame, browser: self) view.addSubview(paginationView) } func configureToolbar() { toolbar = SKToolbar(frame: frameForToolbarAtOrientation(), browser: self) view.addSubview(toolbar) } func setControlsHidden(_ hidden: Bool, animated: Bool, permanent: Bool) { // timer update cancelControlHiding() // scroll animation pagingScrollView.setControlsHidden(hidden: hidden) // paging animation paginationView.setControlsHidden(hidden: hidden) // action view animation actionView.animate(hidden: hidden) if !permanent { hideControlsAfterDelay() } setNeedsStatusBarAppearanceUpdate() } } // MARK: - UIScrollView Delegate extension SKPhotoBrowser: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { guard isViewActive else { return } guard !isPerformingLayout else { return } // tile page pagingScrollView.tilePages() // Calculate current page let previousCurrentPage = currentPageIndex let visibleBounds = pagingScrollView.bounds currentPageIndex = min(max(Int(floor(visibleBounds.midX / visibleBounds.width)), 0), photos.count - 1) if currentPageIndex != previousCurrentPage { delegate?.didShowPhotoAtIndex?(self, index: currentPageIndex) paginationView.update(currentPageIndex) } } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { hideControlsAfterDelay() let currentIndex = pagingScrollView.contentOffset.x / pagingScrollView.frame.size.width delegate?.didScrollToIndex?(self, index: Int(currentIndex)) } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { isEndAnimationByToolBar = true } }
gpl-3.0
c0c3b844bc798c185c4f0d02c9ccad14
32.477707
171
0.622479
5.535545
false
false
false
false
RxSwiftCommunity/RxSwiftExt
Tests/RxSwift/WeakTarget.swift
2
2805
// // WeakTarget.swift // RxSwiftExt // // Created by Ian Keen on 17/04/2016. // Copyright © 2016 RxSwift Community. All rights reserved. // import Foundation import RxSwift enum RxEvent { case next, error, completed, disposed init<T>(event: Event<T>) { switch event { case .next: self = .next case .error: self = .error case .completed: self = .completed } } } var weakTargetReferenceCount: Int = 0 class WeakTarget<Type> { let listener: ([RxEvent: Int]) -> Void fileprivate let observable: Observable<Type> fileprivate var disposeBag = DisposeBag() fileprivate var events: [RxEvent: Int] = [.next: 0, .error: 0, .completed: 0, .disposed: 0] fileprivate func updateEvents(_ event: RxEvent) { self.events[event] = (self.events[event] ?? 0) + 1 self.listener(self.events) } init(obs: Observable<Type>, listener: @escaping ([RxEvent: Int]) -> Void) { weakTargetReferenceCount += 1 self.listener = listener self.observable = obs } deinit { weakTargetReferenceCount -= 1 } // MARK: - Subscribers fileprivate func subscriber_on(_ event: Event<Type>) { self.updateEvents(RxEvent(event: event)) } fileprivate func subscriber_onNext(_ element: Type) { self.updateEvents(.next) } fileprivate func subscriber_onError(_ error: Error) { self.updateEvents(.error) } fileprivate func subscriber_onComplete() { self.updateEvents(.completed) } fileprivate func subscriber_onDisposed() { self.updateEvents(.disposed) } // MARK: - Subscription Setup func useSubscribe() { self.observable.subscribe(weak: self, WeakTarget.subscriber_on).disposed(by: self.disposeBag) } func useSubscribeNext() { //self.observable.subscribeNext(self.subscriber_onNext).addDisposableTo(self.disposeBag) //uncomment this line to create a retain cycle self.observable.subscribeNext(weak: self, WeakTarget.subscriber_onNext).disposed(by: self.disposeBag) } func useSubscribeError() { self.observable.subscribeError(weak: self, WeakTarget.subscriber_onError).disposed(by: self.disposeBag) } func useSubscribeComplete() { self.observable.subscribeCompleted(weak: self, WeakTarget.subscriber_onComplete).disposed(by: self.disposeBag) } func useSubscribeMulti() { self.observable .subscribe( weak: self, onNext: WeakTarget.subscriber_onNext, onError: WeakTarget.subscriber_onError, onCompleted: WeakTarget.subscriber_onComplete, onDisposed: WeakTarget.subscriber_onDisposed ) .disposed(by: self.disposeBag) } func dispose() { self.disposeBag = DisposeBag() } }
mit
c9e0806eebf90c248e39b0f22287b223
34.948718
143
0.658702
4.229261
false
false
false
false
mattrajca/swift-corelibs-foundation
TestFoundation/TestNSProgressFraction.swift
4
5488
// 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 // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif #if !DARWIN_COMPATIBILITY_TESTS class TestProgressFraction : XCTestCase { static var allTests: [(String, (TestProgressFraction) -> () throws -> Void)] { return [ ("test_equal", test_equal ), ("test_subtract", test_subtract), ("test_multiply", test_multiply), ("test_simplify", test_simplify), ("test_overflow", test_overflow), ("test_addOverflow", test_addOverflow), ("test_andAndSubtractOverflow", test_andAndSubtractOverflow), ("test_fractionFromDouble", test_fractionFromDouble), ("test_unnecessaryOverflow", test_unnecessaryOverflow), ] } func test_equal() { let f1 = _ProgressFraction(completed: 5, total: 10) let f2 = _ProgressFraction(completed: 100, total: 200) XCTAssertEqual(f1, f2) let f3 = _ProgressFraction(completed: 3, total: 10) XCTAssertNotEqual(f1, f3) let f4 = _ProgressFraction(completed: 5, total: 10) XCTAssertEqual(f1, f4) } func test_addSame() { let f1 = _ProgressFraction(completed: 5, total: 10) let f2 = _ProgressFraction(completed: 3, total: 10) let r = f1 + f2 XCTAssertEqual(r.completed, 8) XCTAssertEqual(r.total, 10) } func test_addDifferent() { let f1 = _ProgressFraction(completed: 5, total: 10) let f2 = _ProgressFraction(completed: 300, total: 1000) let r = f1 + f2 XCTAssertEqual(r.completed, 800) XCTAssertEqual(r.total, 1000) } func test_subtract() { let f1 = _ProgressFraction(completed: 5, total: 10) let f2 = _ProgressFraction(completed: 3, total: 10) let r = f1 - f2 XCTAssertEqual(r.completed, 2) XCTAssertEqual(r.total, 10) } func test_multiply() { let f1 = _ProgressFraction(completed: 5, total: 10) let f2 = _ProgressFraction(completed: 1, total: 2) let r = f1 * f2 XCTAssertEqual(r.completed, 5) XCTAssertEqual(r.total, 20) } func test_simplify() { let f1 = _ProgressFraction(completed: 5, total: 10) let f2 = _ProgressFraction(completed: 3, total: 10) let r = (f1 + f2).simplified() XCTAssertEqual(r.completed, 4) XCTAssertEqual(r.total, 5) } func test_overflow() { // These prime numbers are problematic for overflowing let denominators : [Int64] = [5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 69] var f1 = _ProgressFraction(completed: 1, total: 3) for d in denominators { f1 = f1 + _ProgressFraction(completed: 1, total: d) } let fractionResult = f1.fractionCompleted var expectedResult = 1.0 / 3.0 for d in denominators { expectedResult = expectedResult + 1.0 / Double(d) } XCTAssertEqual(fractionResult, expectedResult, accuracy: 0.00001) } func test_addOverflow() { // These prime numbers are problematic for overflowing let denominators : [Int64] = [5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 69] var f1 = _ProgressFraction(completed: 1, total: 3) for d in denominators { f1 = f1 + _ProgressFraction(completed: 1, total: d) } // f1 should be in overflow XCTAssertTrue(f1.overflowed) let f2 = _ProgressFraction(completed: 1, total: 4) + f1 // f2 should also be in overflow XCTAssertTrue(f2.overflowed) // And it should have completed value of about 1.0/4.0 + f1.fractionCompleted let expected = (1.0 / 4.0) + f1.fractionCompleted XCTAssertEqual(expected, f2.fractionCompleted, accuracy: 0.00001) } func test_andAndSubtractOverflow() { let f1 = _ProgressFraction(completed: 48, total: 60) let f2 = _ProgressFraction(completed: 5880, total: 7200) let f3 = _ProgressFraction(completed: 7048893638467736640, total: 8811117048084670800) let result1 = (f3 - f1) + f2 XCTAssertTrue(result1.completed > 0) let result2 = (f3 - f2) + f1 XCTAssertTrue(result2.completed < 60) } func test_fractionFromDouble() { let d = 4.25 // exactly representable in binary let f1 = _ProgressFraction(double: d) let simplified = f1.simplified() XCTAssertEqual(simplified.completed, 17) XCTAssertEqual(simplified.total, 4) } func test_unnecessaryOverflow() { // just because a fraction has a large denominator doesn't mean it needs to overflow let f1 = _ProgressFraction(completed: (Int64.max - 1) / 2, total: Int64.max - 1) let f2 = _ProgressFraction(completed: 1, total: 16) let r = f1 + f2 XCTAssertFalse(r.overflowed) } } #endif
apache-2.0
da1a6c05899b3b15165195a1f8535a91
32.463415
95
0.598943
4.011696
false
true
false
false
tad-iizuka/swift-sdk
Source/NaturalLanguageUnderstandingV1/Models/EmotionOptions.swift
1
1770
/** * Copyright IBM Corporation 2017 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit /** Whether or not to return emotion analysis of the content. */ public struct EmotionOptions: JSONEncodable { /// Set this to false to hide document-level emotion results. public let document: Bool? /// Emotion results will be returned for each target string that is found in the document. public let targets: [String]? /** Initialize a `EmotionOptions` with all member variables. - parameter document: Set this to false to hide document-level emotion results. - parameter targets: Emotion results will be returned for each target string that is found in the document. - returns: An initialized `EmotionOptions`. */ public init(document: Bool? = nil, targets: [String]? = nil) { self.document = document self.targets = targets } /// Used internally to serialize a `EmotionOptions` model to JSON. public func toJSONObject() -> Any { var json = [String: Any]() if let document = document { json["document"] = document } if let targets = targets { json["targets"] = targets } return json } }
apache-2.0
67d4c7030d58574725b8722d16cfd063
33.705882
112
0.683616
4.609375
false
false
false
false
insidegui/PlayAlways
PACore/Source/PlayAlways.swift
1
3517
// // PlayAlways.swift // PlayAways // // Created by Guilherme Rambo on 08/12/16. // Copyright © 2016 Guilherme Rambo. All rights reserved. // import Foundation public struct PlayAlways { public enum PlaygroundError: Error { case creation public var localizedDescription: String { switch self { case .creation: return NSLocalizedString("Unable to create playground at the specified location", comment: "Error message: unable to create playground at the specified location") } } } public let platform: String public let contents: String public init(platform: String, contents: String = "") { self.platform = platform.lowercased() self.contents = contents } var dateString: String { let date = Date() let dateFormat = DateFormatter() dateFormat.dateFormat = "yMMdd_HHmmss" return dateFormat.string(from: date) } var systemFramework: String { switch platform { case "macos": return "Cocoa" default: return "UIKit" } } var currentDir: String { return FileManager.default.currentDirectoryPath } var importHeader: String { return "//: Playground - noun: a place where people can play\n\nimport \(systemFramework)\n\n" } var effectiveContents: String { return importHeader + (contents.isEmpty ? "var str = \"Hello, playground\"" : contents) } var contentHeader: String { return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='\(platform)'>\n\t<timeline fileName='timeline.xctimeline'/>\n</playground>\n" } func createPlaygroundFolder(_ path: String) -> Bool { let fileManager = FileManager.default do { try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) return true } catch let error as NSError { print(error) } return false } func writeFile(_ filename: String, at: String, content: String) -> Bool { let destinationPath = URL(fileURLWithPath: at).appendingPathComponent(filename) do { try content.write(to: destinationPath, atomically: true, encoding: String.Encoding.utf8) return true } catch let error as NSError { print(error) } return false } public func createPlayground(fileName: String? = nil, atDestination: String? = nil) throws -> URL { // essencial Playground structure: // |- folder with name.playground // |-- contents.xcplayground // |-- Contents.swift let chosenFileName = fileName ?? dateString let destinationDir = atDestination ?? currentDir let playgroundDir = URL(fileURLWithPath: destinationDir).appendingPathComponent(chosenFileName + ".playground") if createPlaygroundFolder(playgroundDir.path) && writeFile("contents.xcplayground", at: playgroundDir.path, content: contentHeader) && writeFile("Contents.swift", at: playgroundDir.path, content: effectiveContents) { return playgroundDir } throw PlaygroundError.creation } }
bsd-2-clause
daaa08cce4069a29dc3c47a453746581
29.842105
199
0.596985
5.037249
false
false
false
false
Driftt/drift-sdk-ios
Drift/Models/GoogleMeeting.swift
2
912
// // GoogleMeeting.swift // Drift-SDK // // Created by Eoin O'Connell on 07/02/2018. // Copyright © 2018 Drift. All rights reserved. // struct GoogleMeeting { let startTime:Date? let endTime:Date? let meetingId: String? let meetingURL: String? } class GoogleMeetingDTO: Codable, DTO { typealias DataObject = GoogleMeeting var startTime:Date? var endTime:Date? var meetingId: String? var meetingURL: String? enum CodingKeys: String, CodingKey { case startTime = "start" case endTime = "end" case meetingId = "id" case meetingURL = "url" } func mapToObject() -> GoogleMeeting? { return GoogleMeeting(startTime: startTime, endTime: endTime, meetingId: meetingId, meetingURL: meetingURL) } }
mit
f0681857a040d9adcc2040f28481f56d
22.358974
52
0.568606
4.29717
false
false
false
false
roambotics/swift
SwiftCompilerSources/Sources/SIL/Instruction.swift
2
27236
//===--- Instruction.swift - Defines the Instruction classes --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basic import SILBridging //===----------------------------------------------------------------------===// // Instruction base classes //===----------------------------------------------------------------------===// public class Instruction : ListNode, CustomStringConvertible, Hashable { final public var next: Instruction? { SILInstruction_next(bridged).instruction } final public var previous: Instruction? { SILInstruction_previous(bridged).instruction } // Needed for ReverseList<Instruction>.reversed(). Never use directly. public var _firstInList: Instruction { SILBasicBlock_firstInst(block.bridged).instruction! } // Needed for List<Instruction>.reversed(). Never use directly. public var _lastInList: Instruction { SILBasicBlock_lastInst(block.bridged).instruction! } final public var block: BasicBlock { SILInstruction_getParent(bridged).block } final public var function: Function { block.function } final public var description: String { let stdString = SILNode_debugDescription(bridgedNode) return String(_cxxString: stdString) } final public var operands: OperandArray { return OperandArray(opArray: SILInstruction_getOperands(bridged)) } fileprivate var resultCount: Int { 0 } fileprivate func getResult(index: Int) -> Value { fatalError() } public struct Results : RandomAccessCollection { fileprivate let inst: Instruction fileprivate let numResults: Int public var startIndex: Int { 0 } public var endIndex: Int { numResults } public subscript(_ index: Int) -> Value { inst.getResult(index: index) } } final public var results: Results { Results(inst: self, numResults: resultCount) } final public var location: Location { return Location(bridged: SILInstruction_getLocation(bridged)) } public var mayTrap: Bool { false } final public var mayHaveSideEffects: Bool { return mayTrap || mayWriteToMemory } final public var mayReadFromMemory: Bool { switch SILInstruction_getMemBehavior(bridged) { case MayReadBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior: return true default: return false } } final public var mayWriteToMemory: Bool { switch SILInstruction_getMemBehavior(bridged) { case MayWriteBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior: return true default: return false } } final public var mayReadOrWriteMemory: Bool { switch SILInstruction_getMemBehavior(bridged) { case MayReadBehavior, MayWriteBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior: return true default: return false } } public final var mayRelease: Bool { return SILInstruction_mayRelease(bridged) } public final var hasUnspecifiedSideEffects: Bool { return SILInstruction_hasUnspecifiedSideEffects(bridged) } public final var mayAccessPointer: Bool { return swift_mayAccessPointer(bridged) } public final var mayLoadWeakOrUnowned: Bool { return swift_mayLoadWeakOrUnowned(bridged) } public final var maySynchronizeNotConsideringSideEffects: Bool { return swift_maySynchronizeNotConsideringSideEffects(bridged) } public final var mayBeDeinitBarrierNotConsideringSideEffects: Bool { return swift_mayBeDeinitBarrierNotConsideringSideEffects(bridged) } public func visitReferencedFunctions(_ cl: (Function) -> ()) { } public static func ==(lhs: Instruction, rhs: Instruction) -> Bool { lhs === rhs } public func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } public var bridged: BridgedInstruction { BridgedInstruction(obj: SwiftObject(self)) } var bridgedNode: BridgedNode { BridgedNode(obj: SwiftObject(self)) } } extension BridgedInstruction { public var instruction: Instruction { obj.getAs(Instruction.self) } public func getAs<T: Instruction>(_ instType: T.Type) -> T { obj.getAs(T.self) } public var optional: OptionalBridgedInstruction { OptionalBridgedInstruction(obj: self.obj) } } extension OptionalBridgedInstruction { var instruction: Instruction? { obj.getAs(Instruction.self) } public static var none: OptionalBridgedInstruction { OptionalBridgedInstruction(obj: nil) } } public class SingleValueInstruction : Instruction, Value { final public var definingInstruction: Instruction? { self } final public var definingBlock: BasicBlock { block } fileprivate final override var resultCount: Int { 1 } fileprivate final override func getResult(index: Int) -> Value { self } public static func ==(lhs: SingleValueInstruction, rhs: SingleValueInstruction) -> Bool { lhs === rhs } } public final class MultipleValueInstructionResult : Value { final public var description: String { let stdString = SILNode_debugDescription(bridgedNode) return String(_cxxString: stdString) } public var instruction: Instruction { MultiValueInstResult_getParent(bridged).instruction } public var definingInstruction: Instruction? { instruction } public var definingBlock: BasicBlock { instruction.block } public var index: Int { MultiValueInstResult_getIndex(bridged) } var bridged: BridgedMultiValueResult { BridgedMultiValueResult(obj: SwiftObject(self)) } var bridgedNode: BridgedNode { BridgedNode(obj: SwiftObject(self)) } } extension BridgedMultiValueResult { var result: MultipleValueInstructionResult { obj.getAs(MultipleValueInstructionResult.self) } } public class MultipleValueInstruction : Instruction { fileprivate final override var resultCount: Int { return MultipleValueInstruction_getNumResults(bridged) } fileprivate final override func getResult(index: Int) -> Value { MultipleValueInstruction_getResult(bridged, index).result } } /// Instructions, which have a single operand. public protocol UnaryInstruction : AnyObject { var operands: OperandArray { get } var operand: Value { get } } extension UnaryInstruction { public var operand: Value { operands[0].value } } //===----------------------------------------------------------------------===// // no-value instructions //===----------------------------------------------------------------------===// /// Used for all non-value instructions which are not implemented here, yet. /// See registerBridgedClass() in SILBridgingUtils.cpp. final public class UnimplementedInstruction : Instruction { } public protocol StoringInstruction : AnyObject { var operands: OperandArray { get } } extension StoringInstruction { public var sourceOperand: Operand { return operands[0] } public var destinationOperand: Operand { return operands[1] } public var source: Value { return sourceOperand.value } public var destination: Value { return destinationOperand.value } } final public class StoreInst : Instruction, StoringInstruction { // must match with enum class StoreOwnershipQualifier public enum StoreOwnership: Int { case unqualified = 0, initialize = 1, assign = 2, trivial = 3 } public var destinationOwnership: StoreOwnership { StoreOwnership(rawValue: StoreInst_getStoreOwnership(bridged))! } } final public class StoreWeakInst : Instruction, StoringInstruction { } final public class StoreUnownedInst : Instruction, StoringInstruction { } final public class CopyAddrInst : Instruction { public var sourceOperand: Operand { return operands[0] } public var destinationOperand: Operand { return operands[1] } public var source: Value { return sourceOperand.value } public var destination: Value { return destinationOperand.value } public var isTakeOfSrc: Bool { CopyAddrInst_isTakeOfSrc(bridged) != 0 } public var isInitializationOfDest: Bool { CopyAddrInst_isInitializationOfDest(bridged) != 0 } } final public class EndAccessInst : Instruction, UnaryInstruction { public var beginAccess: BeginAccessInst { return operand as! BeginAccessInst } } final public class EndBorrowInst : Instruction, UnaryInstruction {} final public class DeallocStackInst : Instruction, UnaryInstruction { public var allocstack: AllocStackInst { return operand as! AllocStackInst } } final public class DeallocStackRefInst : Instruction, UnaryInstruction { public var allocRef: AllocRefInstBase { operand as! AllocRefInstBase } } final public class CondFailInst : Instruction, UnaryInstruction { public override var mayTrap: Bool { true } public var message: String { CondFailInst_getMessage(bridged).string } } final public class FixLifetimeInst : Instruction, UnaryInstruction {} final public class DebugValueInst : Instruction, UnaryInstruction {} final public class UnconditionalCheckedCastAddrInst : Instruction { public override var mayTrap: Bool { true } } final public class EndApplyInst : Instruction, UnaryInstruction {} final public class AbortApplyInst : Instruction, UnaryInstruction {} final public class SetDeallocatingInst : Instruction, UnaryInstruction {} final public class DeallocRefInst : Instruction, UnaryInstruction {} public class RefCountingInst : Instruction, UnaryInstruction { public var isAtomic: Bool { RefCountingInst_getIsAtomic(bridged) } } final public class StrongRetainInst : RefCountingInst { } final public class RetainValueInst : RefCountingInst { } final public class StrongReleaseInst : RefCountingInst { } final public class ReleaseValueInst : RefCountingInst { } final public class DestroyValueInst : Instruction, UnaryInstruction {} final public class DestroyAddrInst : Instruction, UnaryInstruction {} final public class InjectEnumAddrInst : Instruction, UnaryInstruction, EnumInstruction { public var caseIndex: Int { InjectEnumAddrInst_caseIndex(bridged) } } final public class UnimplementedRefCountingInst : RefCountingInst {} //===----------------------------------------------------------------------===// // single-value instructions //===----------------------------------------------------------------------===// /// Used for all SingleValueInstructions which are not implemented here, yet. /// See registerBridgedClass() in SILBridgingUtils.cpp. final public class UnimplementedSingleValueInst : SingleValueInstruction { } final public class LoadInst : SingleValueInstruction, UnaryInstruction { // must match with enum class LoadOwnershipQualifier public enum LoadOwnership: Int { case unqualified = 0, take = 1, copy = 2, trivial = 3 } public var ownership: LoadOwnership { LoadOwnership(rawValue: LoadInst_getLoadOwnership(bridged))! } } final public class LoadWeakInst : SingleValueInstruction, UnaryInstruction {} final public class LoadUnownedInst : SingleValueInstruction, UnaryInstruction {} final public class LoadBorrowInst : SingleValueInstruction, UnaryInstruction {} final public class BuiltinInst : SingleValueInstruction { public typealias ID = swift.BuiltinValueKind public var id: ID { return BuiltinInst_getID(bridged) } } final public class UpcastInst : SingleValueInstruction, UnaryInstruction {} final public class UncheckedRefCastInst : SingleValueInstruction, UnaryInstruction {} final public class RawPointerToRefInst : SingleValueInstruction, UnaryInstruction {} final public class AddressToPointerInst : SingleValueInstruction, UnaryInstruction { public var needsStackProtection: Bool { AddressToPointerInst_needsStackProtection(bridged) != 0 } } final public class PointerToAddressInst : SingleValueInstruction, UnaryInstruction {} final public class IndexAddrInst : SingleValueInstruction { public var base: Value { operands[0].value } public var index: Value { operands[1].value } public var needsStackProtection: Bool { IndexAddrInst_needsStackProtection(bridged) != 0 } } final public class InitExistentialRefInst : SingleValueInstruction, UnaryInstruction {} final public class OpenExistentialRefInst : SingleValueInstruction, UnaryInstruction {} final public class InitExistentialValueInst : SingleValueInstruction, UnaryInstruction {} final public class OpenExistentialValueInst : SingleValueInstruction, UnaryInstruction {} final public class InitExistentialAddrInst : SingleValueInstruction, UnaryInstruction {} final public class OpenExistentialAddrInst : SingleValueInstruction, UnaryInstruction {} final public class OpenExistentialBoxInst : SingleValueInstruction, UnaryInstruction {} final public class OpenExistentialBoxValueInst : SingleValueInstruction, UnaryInstruction {} final public class InitExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {} final public class OpenExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {} final public class ValueMetatypeInst : SingleValueInstruction, UnaryInstruction {} final public class ExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {} public class GlobalAccessInst : SingleValueInstruction { final public var global: GlobalVariable { GlobalAccessInst_getGlobal(bridged).globalVar } } public class FunctionRefBaseInst : SingleValueInstruction { public var referencedFunction: Function { FunctionRefBaseInst_getReferencedFunction(bridged).function } public override func visitReferencedFunctions(_ cl: (Function) -> ()) { cl(referencedFunction) } } final public class FunctionRefInst : FunctionRefBaseInst { } final public class DynamicFunctionRefInst : FunctionRefBaseInst { } final public class PreviousDynamicFunctionRefInst : FunctionRefBaseInst { } final public class GlobalAddrInst : GlobalAccessInst {} final public class GlobalValueInst : GlobalAccessInst {} final public class IntegerLiteralInst : SingleValueInstruction {} final public class StringLiteralInst : SingleValueInstruction { public var string: String { StringLiteralInst_getValue(bridged).string } } final public class TupleInst : SingleValueInstruction { } final public class TupleExtractInst : SingleValueInstruction, UnaryInstruction { public var fieldIndex: Int { TupleExtractInst_fieldIndex(bridged) } } final public class TupleElementAddrInst : SingleValueInstruction, UnaryInstruction { public var fieldIndex: Int { TupleElementAddrInst_fieldIndex(bridged) } } final public class StructInst : SingleValueInstruction { } final public class StructExtractInst : SingleValueInstruction, UnaryInstruction { public var fieldIndex: Int { StructExtractInst_fieldIndex(bridged) } } final public class StructElementAddrInst : SingleValueInstruction, UnaryInstruction { public var fieldIndex: Int { StructElementAddrInst_fieldIndex(bridged) } } public protocol EnumInstruction : AnyObject { var caseIndex: Int { get } } final public class EnumInst : SingleValueInstruction, UnaryInstruction, EnumInstruction { public var caseIndex: Int { EnumInst_caseIndex(bridged) } public var operand: Value? { operands.first?.value } } final public class UncheckedEnumDataInst : SingleValueInstruction, UnaryInstruction, EnumInstruction { public var caseIndex: Int { UncheckedEnumDataInst_caseIndex(bridged) } } final public class InitEnumDataAddrInst : SingleValueInstruction, UnaryInstruction, EnumInstruction { public var caseIndex: Int { InitEnumDataAddrInst_caseIndex(bridged) } } final public class UncheckedTakeEnumDataAddrInst : SingleValueInstruction, UnaryInstruction, EnumInstruction { public var caseIndex: Int { UncheckedTakeEnumDataAddrInst_caseIndex(bridged) } } final public class RefElementAddrInst : SingleValueInstruction, UnaryInstruction { public var fieldIndex: Int { RefElementAddrInst_fieldIndex(bridged) } public var fieldIsLet: Bool { RefElementAddrInst_fieldIsLet(bridged) != 0 } } final public class RefTailAddrInst : SingleValueInstruction, UnaryInstruction {} final public class KeyPathInst : SingleValueInstruction { public override func visitReferencedFunctions(_ cl: (Function) -> ()) { var results = KeyPathFunctionResults() for componentIdx in 0..<KeyPathInst_getNumComponents(bridged) { KeyPathInst_getReferencedFunctions(bridged, componentIdx, &results) let numFuncs = results.numFunctions withUnsafePointer(to: &results) { $0.withMemoryRebound(to: BridgedFunction.self, capacity: numFuncs) { let functions = UnsafeBufferPointer(start: $0, count: numFuncs) for idx in 0..<numFuncs { cl(functions[idx].function) } } } } } } final public class UnconditionalCheckedCastInst : SingleValueInstruction, UnaryInstruction { public override var mayTrap: Bool { true } } final public class ConvertFunctionInst : SingleValueInstruction, UnaryInstruction {} final public class ThinToThickFunctionInst : SingleValueInstruction, UnaryInstruction {} final public class ObjCExistentialMetatypeToObjectInst : SingleValueInstruction, UnaryInstruction {} final public class ObjCMetatypeToObjectInst : SingleValueInstruction, UnaryInstruction {} final public class ValueToBridgeObjectInst : SingleValueInstruction, UnaryInstruction {} final public class MarkDependenceInst : SingleValueInstruction { public var value: Value { return operands[0].value } public var base: Value { return operands[1].value } } final public class RefToBridgeObjectInst : SingleValueInstruction, UnaryInstruction {} final public class BridgeObjectToRefInst : SingleValueInstruction, UnaryInstruction {} final public class BridgeObjectToWordInst : SingleValueInstruction, UnaryInstruction {} public typealias AccessKind = swift.SILAccessKind // TODO: add support for begin_unpaired_access final public class BeginAccessInst : SingleValueInstruction, UnaryInstruction { public var accessKind: AccessKind { BeginAccessInst_getAccessKind(bridged) } public var isStatic: Bool { BeginAccessInst_isStatic(bridged) != 0 } } // An instruction that is always paired with a scope ending instruction // such as `begin_access` (ending with `end_access`) and `alloc_stack` // (ending with `dealloc_stack`). public protocol ScopedInstruction { // The type of the ending instructions (while `IteratorProtocol` would be // ideal, for performance reasons we allow the user to specify any type as return) associatedtype EndInstructions // The instructions that end the scope of the instruction denoted // by `self`. var endInstructions: EndInstructions { get } } extension BeginAccessInst : ScopedInstruction { public typealias EndInstructions = LazyMapSequence<LazyFilterSequence<LazyMapSequence<UseList, EndAccessInst?>>, EndAccessInst> public var endInstructions: EndInstructions { uses.lazy.compactMap({ $0.instruction as? EndAccessInst }) } } final public class BeginBorrowInst : SingleValueInstruction, UnaryInstruction {} final public class ProjectBoxInst : SingleValueInstruction, UnaryInstruction { public var fieldIndex: Int { ProjectBoxInst_fieldIndex(bridged) } } final public class CopyValueInst : SingleValueInstruction, UnaryInstruction {} final public class StrongCopyUnownedValueInst : SingleValueInstruction, UnaryInstruction {} final public class StrongCopyUnmanagedValueInst : SingleValueInstruction, UnaryInstruction {} final public class EndCOWMutationInst : SingleValueInstruction, UnaryInstruction {} final public class ClassifyBridgeObjectInst : SingleValueInstruction, UnaryInstruction {} final public class PartialApplyInst : SingleValueInstruction, ApplySite { public var numArguments: Int { PartialApplyInst_numArguments(bridged) } public var isOnStack: Bool { PartialApplyInst_isOnStack(bridged) != 0 } public func calleeArgIndex(callerArgIndex: Int) -> Int { PartialApply_getCalleeArgIndexOfFirstAppliedArg(bridged) + callerArgIndex } public func callerArgIndex(calleeArgIndex: Int) -> Int? { let firstIdx = PartialApply_getCalleeArgIndexOfFirstAppliedArg(bridged) if calleeArgIndex >= firstIdx { let callerIdx = calleeArgIndex - firstIdx if callerIdx < numArguments { return callerIdx } } return nil } } final public class ApplyInst : SingleValueInstruction, FullApplySite { public var numArguments: Int { ApplyInst_numArguments(bridged) } public var singleDirectResult: Value? { self } } final public class ClassMethodInst : SingleValueInstruction, UnaryInstruction {} final public class SuperMethodInst : SingleValueInstruction, UnaryInstruction {} final public class ObjCMethodInst : SingleValueInstruction, UnaryInstruction {} final public class ObjCSuperMethodInst : SingleValueInstruction, UnaryInstruction {} final public class WitnessMethodInst : SingleValueInstruction {} final public class IsUniqueInst : SingleValueInstruction, UnaryInstruction {} final public class IsEscapingClosureInst : SingleValueInstruction, UnaryInstruction {} final public class MarkMustCheckInst : SingleValueInstruction, UnaryInstruction {} //===----------------------------------------------------------------------===// // single-value allocation instructions //===----------------------------------------------------------------------===// public protocol Allocation : SingleValueInstruction { } final public class AllocStackInst : SingleValueInstruction, Allocation { } public class AllocRefInstBase : SingleValueInstruction, Allocation { final public var isObjC: Bool { AllocRefInstBase_isObjc(bridged) != 0 } final public var canAllocOnStack: Bool { AllocRefInstBase_canAllocOnStack(bridged) != 0 } } final public class AllocRefInst : AllocRefInstBase { } final public class AllocRefDynamicInst : AllocRefInstBase { } final public class AllocBoxInst : SingleValueInstruction, Allocation { } final public class AllocExistentialBoxInst : SingleValueInstruction, Allocation { } //===----------------------------------------------------------------------===// // multi-value instructions //===----------------------------------------------------------------------===// final public class BeginCOWMutationInst : MultipleValueInstruction, UnaryInstruction { public var uniquenessResult: Value { return getResult(index: 0) } public var bufferResult: Value { return getResult(index: 1) } } final public class DestructureStructInst : MultipleValueInstruction, UnaryInstruction { } final public class DestructureTupleInst : MultipleValueInstruction, UnaryInstruction { } final public class BeginApplyInst : MultipleValueInstruction, FullApplySite { public var numArguments: Int { BeginApplyInst_numArguments(bridged) } public var singleDirectResult: Value? { nil } } //===----------------------------------------------------------------------===// // terminator instructions //===----------------------------------------------------------------------===// public class TermInst : Instruction { final public var successors: SuccessorArray { SuccessorArray(succArray: TermInst_getSuccessors(bridged)) } public var isFunctionExiting: Bool { false } } final public class UnreachableInst : TermInst { } final public class ReturnInst : TermInst, UnaryInstruction { public override var isFunctionExiting: Bool { true } } final public class ThrowInst : TermInst, UnaryInstruction { public override var isFunctionExiting: Bool { true } } final public class YieldInst : TermInst { } final public class UnwindInst : TermInst { public override var isFunctionExiting: Bool { true } } final public class TryApplyInst : TermInst, FullApplySite { public var numArguments: Int { TryApplyInst_numArguments(bridged) } public var normalBlock: BasicBlock { successors[0] } public var errorBlock: BasicBlock { successors[1] } public var singleDirectResult: Value? { normalBlock.arguments[0] } } final public class BranchInst : TermInst { public var targetBlock: BasicBlock { BranchInst_getTargetBlock(bridged).block } /// Returns the target block argument for the cond_br `operand`. public func getArgument(for operand: Operand) -> Argument { return targetBlock.arguments[operand.index] } } final public class CondBranchInst : TermInst { var trueBlock: BasicBlock { successors[0] } var falseBlock: BasicBlock { successors[1] } var condition: Value { operands[0].value } var trueOperands: OperandArray { operands[1...CondBranchInst_getNumTrueArgs(bridged)] } var falseOperands: OperandArray { let ops = operands return ops[(CondBranchInst_getNumTrueArgs(bridged) &+ 1)..<ops.count] } /// Returns the true or false block argument for the cond_br `operand`. /// /// Return nil if `operand` is the condition itself. public func getArgument(for operand: Operand) -> Argument? { let opIdx = operand.index if opIdx == 0 { return nil } let argIdx = opIdx - 1 let numTrueArgs = CondBranchInst_getNumTrueArgs(bridged) if (0..<numTrueArgs).contains(argIdx) { return trueBlock.arguments[argIdx] } else { return falseBlock.arguments[argIdx - numTrueArgs] } } } final public class SwitchValueInst : TermInst { } final public class SwitchEnumInst : TermInst { public var enumOp: Value { operands[0].value } public struct CaseIndexArray : RandomAccessCollection { fileprivate let switchEnum: SwitchEnumInst public var startIndex: Int { return 0 } public var endIndex: Int { SwitchEnumInst_getNumCases(switchEnum.bridged) } public subscript(_ index: Int) -> Int { SwitchEnumInst_getCaseIndex(switchEnum.bridged, index) } } var caseIndices: CaseIndexArray { CaseIndexArray(switchEnum: self) } var cases: Zip2Sequence<CaseIndexArray, SuccessorArray> { zip(caseIndices, successors) } // This does not handle the special case where the default covers exactly // the "missing" case. public func getUniqueSuccessor(forCaseIndex: Int) -> BasicBlock? { cases.first(where: { $0.0 == forCaseIndex })?.1 } // This does not handle the special case where the default covers exactly // the "missing" case. public func getUniqueCase(forSuccessor: BasicBlock) -> Int? { cases.first(where: { $0.1 == forSuccessor })?.0 } } final public class SwitchEnumAddrInst : TermInst { } final public class DynamicMethodBranchInst : TermInst { } final public class AwaitAsyncContinuationInst : TermInst, UnaryInstruction { } final public class CheckedCastBranchInst : TermInst, UnaryInstruction { } final public class CheckedCastAddrBranchInst : TermInst, UnaryInstruction { }
apache-2.0
db7b1746a9e90b16e03e23ac401f5c05
31.540024
129
0.731238
4.769042
false
false
false
false
GrandCentralBoard/GrandCentralBoard
Pods/MD5/Sources/IntExtension.swift
4
2136
// // IntExtension.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 12/08/14. // Copyright (C) 2014 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. #if os(Linux) import Glibc #else import Darwin #endif /* array of bytes */ extension Int { /** Array of bytes with optional padding (little-endian) */ public func bytes(totalBytes: Int = sizeof(Int)) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } } /** Shift bits */ extension Int { /** Shift bits to the right. All bits are shifted (including sign bit) */ private mutating func shiftRight(count: Int) -> Int { if (self == 0) { return self; } let bitsCount = sizeofValue(self) * 8 if (count >= bitsCount) { return 0 } let maxBitsForValue = Int(floor(log2(Double(self)) + 1)) let shiftCount = Swift.min(count, maxBitsForValue - 1) var shiftedValue:Int = 0; for bitIdx in 0..<bitsCount { // if bit is set then copy to result and shift left 1 let bit = 1 << bitIdx if ((self & bit) == bit) { shiftedValue = shiftedValue | (bit >> shiftCount) } } self = Int(shiftedValue) return self } }
gpl-3.0
1390948a458ed536e380f504dc2455f9
32.888889
217
0.644496
4.339431
false
false
false
false
yangyouyong0/SwiftLearnLog
CiChang/CiChang/CCBookListTableViewController.swift
1
5131
// // CCBookListTableViewController.swift // CiChang // // Created by yangyouyong on 15/7/8. // Copyright © 2015年 yangyouyong. All rights reserved. // import UIKit import Alamofire class CCBookListTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() let url = NSURL(string: "http://beta.cichang.hjapi.com/v1/book/?pageIndex=0&pageSize=10&sort=popular") // self.requestData() // NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: url), queue: NSOperationQueue.mainQueue()){ // (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in //// if (let responseData = data){ // let dataDic:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as! NSDictionary // print("dataDic is \(dataDic)") //// } // } //NSURL("http://beta.cichang.hjapi.com/v1/book/?pageIndex=0&pageSize=10&sort=popular") // NSURLSessionTask *task = // loadDataFromNetwork // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } // internal func requestData() { // let urlStr = "http://cichang.hjapi.com/v2/book/?pageIndex=0&pageSize=100&sort=popular" // Alamofire.request(.GET, URLString: urlStr).response { // (_, _, data, error) in // if data != nil { // if (JSON(data: data as! NSData) != nil){ // let json = JSON(data: data as! NSData) // let items = json["data"]["items"] // for value in items{ // let (_ , dict) = value as (String,JSON) // let book = CCBook().initWithDict(dict.object as! [String : AnyObject]) // print(dict.object) // print("value is \(book)") // self.bookArray.append(book) // } // print("bookArray") // print(self.bookArray) // self.tableView!.reloadData() // } // }else{ // print("noData,\(error)") // } // // } // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
9bdb01a1b110598582439bd8a54f7c65
37.268657
157
0.61876
4.978641
false
false
false
false
sprint84/PhotoCropEditor
CropViewController/CropViewController.swift
1
9097
// // CropViewController.swift // CropViewController // // Created by Guilherme Moura on 2/25/16. // Copyright © 2016 Reefactor, Inc. All rights reserved. // import UIKit public protocol CropViewControllerDelegate: class { func cropViewController(_ controller: CropViewController, didFinishCroppingImage image: UIImage) func cropViewController(_ controller: CropViewController, didFinishCroppingImage image: UIImage, transform: CGAffineTransform, cropRect: CGRect) func cropViewControllerDidCancel(_ controller: CropViewController) } open class CropViewController: UIViewController { open weak var delegate: CropViewControllerDelegate? open var image: UIImage? { didSet { cropView?.image = image } } open var keepAspectRatio = false { didSet { cropView?.keepAspectRatio = keepAspectRatio } } open var cropAspectRatio: CGFloat = 0.0 { didSet { cropView?.cropAspectRatio = cropAspectRatio } } open var cropRect = CGRect.zero { didSet { adjustCropRect() } } open var imageCropRect = CGRect.zero { didSet { cropView?.imageCropRect = imageCropRect } } open var toolbarHidden = false open var rotationEnabled = false { didSet { cropView?.rotationGestureRecognizer.isEnabled = rotationEnabled } } open var rotationTransform: CGAffineTransform { return cropView!.rotation } open var zoomedCropRect: CGRect { return cropView!.zoomedCropRect() } fileprivate var cropView: CropView? public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) initialize() } fileprivate func initialize() { rotationEnabled = true } open override func loadView() { let contentView = UIView() contentView.autoresizingMask = .flexibleWidth contentView.backgroundColor = UIColor.black view = contentView // Add CropView cropView = CropView(frame: contentView.bounds) contentView.addSubview(cropView!) } open override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.isTranslucent = false navigationController?.toolbar.isTranslucent = false navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(CropViewController.cancel(_:))) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(CropViewController.done(_:))) if self.toolbarItems == nil { let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let constrainButton = UIBarButtonItem(title: "Constrain", style: .plain, target: self, action: #selector(CropViewController.constrain(_:))) toolbarItems = [flexibleSpace, constrainButton, flexibleSpace] } navigationController?.isToolbarHidden = toolbarHidden cropView?.image = image cropView?.rotationGestureRecognizer.isEnabled = rotationEnabled } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if cropAspectRatio != 0 { cropView?.cropAspectRatio = cropAspectRatio } if !cropRect.equalTo(CGRect.zero) { adjustCropRect() } if !imageCropRect.equalTo(CGRect.zero) { cropView?.imageCropRect = imageCropRect } cropView?.keepAspectRatio = keepAspectRatio } open func resetCropRect() { cropView?.resetCropRect() } open func resetCropRectAnimated(_ animated: Bool) { cropView?.resetCropRectAnimated(animated) } func cancel(_ sender: UIBarButtonItem) { delegate?.cropViewControllerDidCancel(self) } func done(_ sender: UIBarButtonItem) { if let image = cropView?.croppedImage { delegate?.cropViewController(self, didFinishCroppingImage: image) guard let rotation = cropView?.rotation else { return } guard let rect = cropView?.zoomedCropRect() else { return } delegate?.cropViewController(self, didFinishCroppingImage: image, transform: rotation, cropRect: rect) } } func constrain(_ sender: UIBarButtonItem) { let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let original = UIAlertAction(title: "Original", style: .default) { [unowned self] action in guard let image = self.cropView?.image else { return } guard var cropRect = self.cropView?.cropRect else { return } let width = image.size.width let height = image.size.height let ratio: CGFloat if width < height { ratio = width / height cropRect.size = CGSize(width: cropRect.height * ratio, height: cropRect.height) } else { ratio = height / width cropRect.size = CGSize(width: cropRect.width, height: cropRect.width * ratio) } self.cropView?.cropRect = cropRect } actionSheet.addAction(original) let square = UIAlertAction(title: "Square", style: .default) { [unowned self] action in let ratio: CGFloat = 1.0 // self.cropView?.cropAspectRatio = ratio if var cropRect = self.cropView?.cropRect { let width = cropRect.width cropRect.size = CGSize(width: width, height: width * ratio) self.cropView?.cropRect = cropRect } } actionSheet.addAction(square) let threeByTwo = UIAlertAction(title: "3 x 2", style: .default) { [unowned self] action in self.cropView?.cropAspectRatio = 2.0 / 3.0 } actionSheet.addAction(threeByTwo) let threeByFive = UIAlertAction(title: "3 x 5", style: .default) { [unowned self] action in self.cropView?.cropAspectRatio = 3.0 / 5.0 } actionSheet.addAction(threeByFive) let fourByThree = UIAlertAction(title: "4 x 3", style: .default) { [unowned self] action in let ratio: CGFloat = 3.0 / 4.0 if var cropRect = self.cropView?.cropRect { let width = cropRect.width cropRect.size = CGSize(width: width, height: width * ratio) self.cropView?.cropRect = cropRect } } actionSheet.addAction(fourByThree) let fourBySix = UIAlertAction(title: "4 x 6", style: .default) { [unowned self] action in self.cropView?.cropAspectRatio = 4.0 / 6.0 } actionSheet.addAction(fourBySix) let fiveBySeven = UIAlertAction(title: "5 x 7", style: .default) { [unowned self] action in self.cropView?.cropAspectRatio = 5.0 / 7.0 } actionSheet.addAction(fiveBySeven) let eightByTen = UIAlertAction(title: "8 x 10", style: .default) { [unowned self] action in self.cropView?.cropAspectRatio = 8.0 / 10.0 } actionSheet.addAction(eightByTen) let widescreen = UIAlertAction(title: "16 x 9", style: .default) { [unowned self] action in let ratio: CGFloat = 9.0 / 16.0 if var cropRect = self.cropView?.cropRect { let width = cropRect.width cropRect.size = CGSize(width: width, height: width * ratio) self.cropView?.cropRect = cropRect } } actionSheet.addAction(widescreen) let cancel = UIAlertAction(title: "Cancel", style: .default) { [unowned self] action in self.dismiss(animated: true, completion: nil) } actionSheet.addAction(cancel) present(actionSheet, animated: true, completion: nil) } // MARK: - Private methods fileprivate func adjustCropRect() { imageCropRect = CGRect.zero guard var cropViewCropRect = cropView?.cropRect else { return } cropViewCropRect.origin.x += cropRect.origin.x cropViewCropRect.origin.y += cropRect.origin.y let minWidth = min(cropViewCropRect.maxX - cropViewCropRect.minX, cropRect.width) let minHeight = min(cropViewCropRect.maxY - cropViewCropRect.minY, cropRect.height) let size = CGSize(width: minWidth, height: minHeight) cropViewCropRect.size = size cropView?.cropRect = cropViewCropRect } }
mit
f956d4366a7d603ca276720906f7018d
36.126531
152
0.613896
5.033758
false
false
false
false
myfreeweb/freepass
ios/Freepass/Freepass/Field.swift
1
1690
import SwiftCBOR enum DerivedUsage { case Password(template: String) case Ed25519Key(usage: String) case RawKey init?(fromCbor obj: CBOR) { switch obj["variant"] { case "Password"?: guard case let CBOR.UTF8String(template)? = obj["fields"]?[0] else { return nil } self = .Password(template: template) case "Ed25519Key"?: guard case let CBOR.UTF8String(usage)? = obj["fields"]?[0] else { return nil } self = .Ed25519Key(usage: usage) case "RawKey"?: self = .RawKey default: return nil } } } enum StoredUsage { case Text case Password init?(fromCbor obj: CBOR) { switch obj { case "Text": self = .Text case "Password": self = .Password default: return nil } } } enum Field { case Derived(counter: UInt32, site_name: String?, usage: DerivedUsage) case Stored(data: [UInt8], usage: StoredUsage) init?(fromCbor obj: CBOR) { switch obj["variant"] { case "Derived"?: guard case let CBOR.UnsignedInt(counter)? = obj["fields"]?[0] else { return nil } let site_name: String? if case CBOR.UTF8String(let site_name_)? = obj["fields"]?[1] { site_name = site_name_ } else { site_name = nil } guard let uobj = obj["fields"]?[2], usage = DerivedUsage(fromCbor: uobj) else { return nil } self = .Derived(counter: UInt32(counter), site_name: site_name, usage: usage) case "Stored"?: guard case let CBOR.ByteString(data)? = obj["fields"]?[0] else { return nil } guard let uobj = obj["fields"]?[1], usage = StoredUsage(fromCbor: uobj) else { return nil } self = .Stored(data: data, usage: usage) default: return nil } } init() { self = .Derived(counter: 1, site_name: nil, usage: .Password(template: "Maximum")) } }
unlicense
0f66b9462384fe7e49d99f8a142efafc
27.661017
115
0.659763
3.007117
false
false
false
false
practicalswift/swift
validation-test/compiler_crashers_fixed/01927-swift-type-walk.swift
65
674
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class c { func a: c == { typealias e == F>(mx : S.c> : Any) { } } var d = true } (self.E var f = c, self.init() -> String { override func g<T.advance(" protocol a { protocol a { protocol c { } }(f, V>? = g() { let foo as [".b { func a<T, length: A, f: a { func a" class A : a
apache-2.0
97d60b51cf851c425c65eac487bc08c4
24.923077
79
0.667656
3.12037
false
false
false
false
InsectQY/HelloSVU_Swift
HelloSVU_Swift/Classes/Module/Map/Route/Bus/Detail/Controller/BusRouteDetailViewController.swift
1
9659
// // BusRouteDetailViewController.swift // HelloSVU_Swift // // Created by Insect on 2017/10/16. //Copyright © 2017年 Insect. All rights reserved. // import UIKit class BusRouteDetailViewController: BaseViewController { @IBOutlet private weak var tableView: UITableView! @IBOutlet private weak var pageControl: UIPageControl! @IBOutlet private weak var flowLayout: UICollectionViewFlowLayout! @IBOutlet private weak var collectionView: UICollectionView! /// 点击cell后底部弹出的位置信息窗口 private let window: UIWindow = UIWindow() /// 窗口背后的黑色蒙版 private let hudWindow: UIWindow = UIWindow() /// 公交路径规划方案 var route = AMapRoute() /// 点击的是哪一个方案 var selIndex = 0 /// 起点 var originLoc = "" /// 终点 var destinationLoc = "" /// 当前选择的公交线路 private var selBusLineIndex = 0 // MARK: - LazyLoad private lazy var busSegment: [BusSegment] = { var busSegment = [BusSegment]() for _ in 0 ..< route.transits[selIndex].segments.count { busSegment.append(BusSegment()) } return busSegment }() private lazy var headerView: BusRouteDetailHeaderView = { var headerView = BusRouteDetailHeaderView.loadFromNib() return headerView }() private lazy var footerView: BusRouteDetailFooterView = { var footerView = BusRouteDetailFooterView.loadFromNib() return footerView }() // MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() setUpUI() } } // MARK: - 设置 UI 界面 extension BusRouteDetailViewController { private func setUpUI() { automaticallyAdjustsScrollViewInsets = false setUpCollectionView() setUpTableView() setUpTableViewHeader() setUpTableViewFooter() } // MARK: - 设置 collecitonView private func setUpCollectionView() { pageControl.numberOfPages = route.transits.count pageControl.currentPage = selIndex flowLayout.itemSize = CGSize(width: ScreenW, height: 100) flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 collectionView.register(cellType: BusRouteDetailLineCell.self) collectionView.reloadData() collectionView.layoutIfNeeded() var offset = collectionView.contentOffset offset.x = CGFloat(selIndex) * ScreenW collectionView.setContentOffset(offset, animated: false) } private func setUpTableView() { tableView.register(cellType: BusRouteDetailCell.self) tableView.register(headerFooterViewType: BusRouteDetailCellHeader.self) tableView.register(headerFooterViewType: BusRouteDetailCellFooter.self) tableView.rowHeight = 25 tableView.reloadData() } // MARK: - 刷新界面所有数据 private func reloadAllData() { setUpTableViewHeader() setUpTableViewFooter() tableView.reloadData() } } // MARK: - UICollectionViewDataSource extension BusRouteDetailViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return route.transits.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(for: indexPath, cellType: BusRouteDetailLineCell.self) cell.transit = route.transits[indexPath.item] return cell } } // MARK: - UICollectionViewDelegate extension BusRouteDetailViewController: UICollectionViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == collectionView { selIndex = Int(collectionView.contentOffset.x / ScreenW) pageControl.currentPage = selIndex busSegment.removeAll() for _ in 0 ..< route.transits[selIndex].segments.count { busSegment.append(BusSegment()) } reloadAllData() } } } // MARK: - UITableViewDataSource extension BusRouteDetailViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { /// 最后一段 buslines 数组为空 return route.transits[selIndex].segments.count - 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if busSegment[section].isOpen { return route.transits[selIndex].segments[section].buslines[selBusLineIndex].viaBusStops.count } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: BusRouteDetailCell.ID, for: indexPath) as! BusRouteDetailCell cell.busStop = route.transits[selIndex].segments[indexPath.section].buslines[selBusLineIndex].viaBusStops[indexPath.row] return cell } } // MARK: - UITableViewDelegate extension BusRouteDetailViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 120 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 100 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let segment = route.transits[selIndex].segments[section] let info = busSegment[section] let headerView = tableView.dequeueReusableHeaderFooterView(BusRouteDetailCellHeader.self) headerView.info = info headerView.segment = segment // 途径站点按钮点击 (上下箭头) headerView.viaBtnClick = {[weak self] () in self?.busSegment[section].isOpen = !(self?.busSegment[section].isOpen ?? false) if (self?.busSegment[section].isOpen ?? false) { self?.openSection(section) } else { self?.closeSection(section) } } // 其他公交换乘线路点击 headerView.otherBusLineClick = {[weak self] () in let allLineVc = AllBusLineViewController() allLineVc.segment = segment allLineVc.selBusLineIndex = info.busLineIndex self?.showBottomView(allLineVc, section) // 点击切换了其他公交线路 allLineVc.changeBusLine = {[weak self] (selLineIndex) in self?.busSegment[section].isSpecified = true self?.busSegment[section].busLineIndex = selLineIndex self?.reloadAllData() } } return headerView } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let footerView = tableView.dequeueReusableHeaderFooterView(BusRouteDetailCellFooter.self) footerView.info = busSegment[section]; footerView.segment = route.transits[selIndex].segments[section]; // 加一是为了加载到最后一组只有步行路线的数据(默认不取最后一组) footerView.walking = route.transits[selIndex].segments[section + 1].walking; return footerView } } // MARK: - 设置UITableView头部尾部视图 extension BusRouteDetailViewController { private func setUpTableViewHeader() { let contentHeader = UIView(frame: CGRect(x: 0, y: 0, width: ScreenW, height: 100)) headerView.frame = contentHeader.bounds contentHeader.addSubview(headerView) tableView.tableHeaderView = contentHeader headerView.walking = route.transits[selIndex].segments[0].walking } private func setUpTableViewFooter() { let contentFooter = UIView(frame: CGRect(x: 0, y: 0, width: ScreenW, height: 40)) footerView.frame = contentFooter.bounds contentFooter.addSubview(footerView) tableView.tableFooterView = contentFooter } } // MARK: - 展开关闭列表 extension BusRouteDetailViewController { private func openSection(_ section: Int) { tableView.insertRows(at: getIndexData(section), with: .fade) } private func closeSection(_ section: Int) { tableView.deleteRows(at: getIndexData(section), with: .fade) } /// 获得需要展开的数据 private func getIndexData(_ section: Int) -> [IndexPath] { var indexArray = [IndexPath]() for i in 0 ..< route.transits[selIndex].segments[section].buslines[selBusLineIndex].viaBusStops.count { indexArray.append(IndexPath(row: i, section: section)) } return indexArray } } // MARK: - 显示底部控制器 extension BusRouteDetailViewController { private func showBottomView(_ viewController: AllBusLineViewController,_ selSegmentIndex: Int) { var contentH = CGFloat(route.transits[selIndex].segments[selSegmentIndex].buslines.count * 60 + 90) contentH = contentH >= ScreenH ? ScreenH: contentH SVUAnimation.showBottomView(viewController, viewHeight: contentH, animateDuration: 0.4, completion: nil) } }
apache-2.0
331dd706fd4498347a9b2e887827c596
31.939929
128
0.648788
5.058058
false
false
false
false
lukevanin/OCRAI
CardScanner/PhotoLibraryViewController.swift
1
4085
// // PhotoLibraryViewController.swift // CardScanner // // Created by Luke Van In on 2017/03/05. // Copyright © 2017 Luke Van In. All rights reserved. // import UIKit import Photos private let imageCellIdentifier = "ImageCell" private let unwindSegueIdentifier = "unwindSegue" class PhotoLibraryViewController: UICollectionViewController, ImageSource { private let imageManager = PHImageManager.default() private let photoLibrary = PHPhotoLibrary.shared() var selectedImageData: Data? fileprivate var result: PHFetchResult<PHAsset>? private var currentRequestID: PHImageRequestID? override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadPhotos() startAutomaticUpdates() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stopAutomaticUpdates() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // FIXME: Calculate cell size according to screen real estate. } private func loadPhotos() { // Create options. let options = PHFetchOptions() options.includeAssetSourceTypes = [.typeUserLibrary] options.wantsIncrementalChangeDetails = true options.sortDescriptors = [ NSSortDescriptor(key: "modificationDate", ascending: false) ] // Issue request result = PHAsset.fetchAssets(with: .image, options: options) collectionView?.reloadData() } private func startAutomaticUpdates() { // Observe photo library for automatic updates. photoLibrary.register(self) } private func stopAutomaticUpdates() { photoLibrary.unregisterChangeObserver(self) } // MARK: Collection delegate override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return result?.count ?? 0 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imageCellIdentifier, for: indexPath) as! PhotoLibraryCell if let asset = result?[indexPath.item] { cell.configure(asset) } return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { cancelCurrentImageRequest() guard let asset = result?[indexPath.item] else { return } let options = PHImageRequestOptions() options.deliveryMode = .highQualityFormat options.resizeMode = .fast options.isNetworkAccessAllowed = true options.version = .current currentRequestID = imageManager.requestImageData( for: asset, options: options) { (data, uti, orientation, info) in self.selectedImageData = data self.performSegue(withIdentifier: unwindSegueIdentifier, sender: nil) } } private func cancelCurrentImageRequest() { guard let requestID = currentRequestID else { return } imageManager.cancelImageRequest(requestID) currentRequestID = nil } } extension PhotoLibraryViewController: PHPhotoLibraryChangeObserver { func photoLibraryDidChange(_ changeInstance: PHChange) { guard let result = self.result, let changes = changeInstance.changeDetails(for: result) else { return } DispatchQueue.main.async { [weak self] in self?.result = changes.fetchResultAfterChanges self?.collectionView?.applyChanges(changes, inSection: 0) } } }
mit
c1922988b7e09e3fd8311b15b25f9fe6
29.939394
132
0.651567
5.801136
false
false
false
false
NeoGolightly/CartographyKit
CartographyKit/CartographyKit.swift
1
3552
// // LayoutContraint.swift // FastTap // // Created by mhelmbre on 4/1/15. // Copyright (c) 2015 At-World. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit public typealias View = UIView #else import AppKit public typealias View = NSView #endif import Cartography public struct CartographyKit{ } //TODO: All the rest //Baselines private protocol BasicBaselines{ static func baseline(_ view: View) -> NSLayoutConstraint? static func lastBaseline(_ view: View) -> NSLayoutConstraint? static func firstBaseline(_ view: View) -> NSLayoutConstraint? } //////////////////////////////////////////////////////////////////////////////////////////////// //To other view(s) //////////////////////////////////////////////////////////////////////////////////////////////// private protocol ToOtherViews{ static func topToOtherViewsBottom(_ view1: View, otherView: View, plus: CGFloat) -> NSLayoutConstraint? static func bottomToOtherViewsTop(_ view1: View, otherView: View, minus: CGFloat) -> NSLayoutConstraint? static func topToOtherViewsCenterX(_ view1: View, otherView: View, plus: CGFloat) -> NSLayoutConstraint? } //////////////////// extension CartographyKit{ @discardableResult public static func centerYToView(_ view1: View, view2: View) -> NSLayoutConstraint?{ var c: NSLayoutConstraint? constrain(view1, view2){ view1, view2 in c = view1.centerY == view2.centerY return } return c } @discardableResult public static func centerXToView(_ view1: View, view2: View) -> NSLayoutConstraint?{ var c: NSLayoutConstraint? constrain(view1, view2){ view1, view2 in c = view1.centerX == view2.centerX return } return c } } extension CartographyKit: ToOtherViews{ @discardableResult public static func topToOtherViewsBottom(_ view1: View, otherView: View, plus: CGFloat) -> NSLayoutConstraint?{ var c: NSLayoutConstraint? constrain(view1, otherView){ view1, otherView in c = view1.top == otherView.bottom + plus return } return c } @discardableResult public static func bottomToOtherViewsTop(_ view1: View, otherView: View, minus: CGFloat) -> NSLayoutConstraint?{ var c: NSLayoutConstraint? constrain(view1, otherView){ view1, otherView in c = view1.bottom == otherView.top - minus return } return c } @discardableResult public static func topToOtherViewsCenterX(_ view1: View, otherView: View, plus: CGFloat) -> NSLayoutConstraint?{ var c: NSLayoutConstraint? constrain(view1, otherView){ view1, otherView in c = view1.top == otherView.centerY + plus return } return c } } private protocol LayoutGuides{ static func topToLayoutGuide(_ view: View, layoutguide: LayoutSupport) -> NSLayoutConstraint? static func topBottomLayoutGuide(_ view: View, layoutguide: LayoutSupport) -> NSLayoutConstraint? } extension CartographyKit: LayoutGuides{ @discardableResult public static func topToLayoutGuide(_ view: View, layoutguide: LayoutSupport) -> NSLayoutConstraint?{ var c: NSLayoutConstraint? constrain(view, layoutguide){ view, layoutguide in c = view.top == layoutguide.bottom return } return c } @discardableResult public static func topBottomLayoutGuide(_ view: View, layoutguide: LayoutSupport) -> NSLayoutConstraint?{ var c: NSLayoutConstraint? constrain(view, layoutguide){ view, layoutguide in c = view.bottom == layoutguide.top return } return c } }
mit
7f04244ed09b73d3805f7a7d8a41a61b
26.75
114
0.66357
4.451128
false
false
false
false
fiveagency/ios-five-ui-components
Example/Classes/UserInterface/Home/ExamplesViewController.swift
1
2086
// // ExamplesViewController.swift // Example // // Created by Denis Mendica on 2/13/17. // Copyright © 2017 Five Agency. All rights reserved. // import UIKit class ExamplesViewController: UIViewController { fileprivate let cellIdentifier = String(describing: ExampleTableViewCell.self) fileprivate var viewModel: ExamplesViewModel! @IBOutlet private weak var examplesTableView: UITableView! convenience init(viewModel: ExamplesViewModel) { self.init() self.viewModel = viewModel } override func viewDidLoad() { super.viewDidLoad() setupTableView() setupAppearance() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let navigationController = self.navigationController as? NavigationController else { return } navigationController.applyShadowfullAppearance() } private func setupTableView() { examplesTableView.register(UINib(nibName: cellIdentifier, bundle: nil), forCellReuseIdentifier: cellIdentifier) examplesTableView.estimatedRowHeight = 100 examplesTableView.rowHeight = UITableViewAutomaticDimension } private func setupAppearance() { title = "Five UI Components" examplesTableView.backgroundColor = UIColor.backgroundLightGray navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) } } extension ExamplesViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.numberOfExamples } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ExampleTableViewCell let cellViewModel = viewModel.cellViewModel(at: indexPath.row) cell.setup(with: cellViewModel) return cell } }
mit
85dbdbb0fce7da9481ea4f7c524a7e73
31.076923
121
0.699281
5.743802
false
false
false
false
ORT-Interactive-GmbH/OnlineL10n
SwiftLocalizationUITests/SwiftLocalizationUITests.swift
1
2501
// // SwiftLocalizationUITests.swift // SwiftLocalizationUITests // // Created by Sebastian Westemeyer on 27.04.16. // Copyright © 2016 ORT Interactive. All rights reserved. // import XCTest import OnlineL10n class SwiftLocalizationUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testUILocalization() { let app = XCUIApplication() app.segmentedControls.buttons["Englisch"].tap() let translationComplete = app.staticTexts["Top label text in English"] let exists = NSPredicate(format: "exists == true") expectation(for: exists, evaluatedWith: translationComplete, handler: nil) waitForExpectations(timeout: 5, handler: nil) XCTAssert(app.textFields["text_field"].value as? String == "a beautiful text field", "Text does not match!") XCTAssert(app.textViews["text_view"].value as? String == "a multi-line text view which is\nnot\nentirely\nfilled.", "Text does not match!") app.segmentedControls.buttons["German"].tap() XCTAssert(app.textFields["text_field"].value as? String == "Ein tolles Eingabefeld", "Text does not match!") XCTAssert(app.textViews["text_view"].value as? String == "Eine mehrzeilige Text-Ansicht nicht\nbesonders\ndoll befüllt.", "Text does not match!") app.buttons["button"].tap() app.tables.staticTexts["England"].tap() app.navigationBars["Select country"].buttons["Done"].tap() XCTAssert(app.textFields["text_field"].value as? String == "a beautiful text field", "Text does not match!") XCTAssert(app.textViews["text_view"].value as? String == "a multi-line text view which is\nnot\nentirely\nfilled.", "Text does not match!") } }
mit
16cd506e02a572fde800693e57d270d8
43.589286
182
0.686023
4.261092
false
true
false
false
EgzonArifi/Daliy-Gifs
Daily Gifs/Image.swift
1
4009
// // Image.swift // // Create by Egzon Arifi on 4/3/2017 // Copyright © 2017. All rights reserved. import Foundation class Image{ var downsized : Downsized! var downsizedLarge : Downsized! var downsizedMedium : Downsized! var downsizedSmall : DownsizedSmall! var downsizedStill : Downsized! var fixedHeight : FixedHeight! var fixedHeightDownsampled : FixedHeightDownsampled! var fixedHeightSmall : FixedHeight! var fixedHeightSmallStill : Downsized! var fixedHeightStill : Downsized! var fixedWidth : FixedHeight! var fixedWidthDownsampled : FixedHeightDownsampled! var fixedWidthSmall : FixedHeight! var fixedWidthSmallStill : Downsized! var fixedWidthStill : Downsized! var looping : DownsizedSmall! var original : Original! var originalMp4 : OriginalMp4! var originalStill : Downsized! var preview : OriginalMp4! /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: [String:Any]){ if let downsizedData = dictionary["downsized"] as? [String:Any]{ downsized = Downsized(fromDictionary: downsizedData) } if let downsizedLargeData = dictionary["downsized_large"] as? [String:Any]{ downsizedLarge = Downsized(fromDictionary: downsizedLargeData) } if let downsizedMediumData = dictionary["downsized_medium"] as? [String:Any]{ downsizedMedium = Downsized(fromDictionary: downsizedMediumData) } if let downsizedSmallData = dictionary["downsized_small"] as? [String:Any]{ downsizedSmall = DownsizedSmall(fromDictionary: downsizedSmallData) } if let downsizedStillData = dictionary["downsized_still"] as? [String:Any]{ downsizedStill = Downsized(fromDictionary: downsizedStillData) } if let fixedHeightData = dictionary["fixed_height"] as? [String:Any]{ fixedHeight = FixedHeight(fromDictionary: fixedHeightData) } if let fixedHeightDownsampledData = dictionary["fixed_height_downsampled"] as? [String:Any]{ fixedHeightDownsampled = FixedHeightDownsampled(fromDictionary: fixedHeightDownsampledData) } if let fixedHeightSmallData = dictionary["fixed_height_small"] as? [String:Any]{ fixedHeightSmall = FixedHeight(fromDictionary: fixedHeightSmallData) } if let fixedHeightSmallStillData = dictionary["fixed_height_small_still"] as? [String:Any]{ fixedHeightSmallStill = Downsized(fromDictionary: fixedHeightSmallStillData) } if let fixedHeightStillData = dictionary["fixed_height_still"] as? [String:Any]{ fixedHeightStill = Downsized(fromDictionary: fixedHeightStillData) } if let fixedWidthData = dictionary["fixed_width"] as? [String:Any]{ fixedWidth = FixedHeight(fromDictionary: fixedWidthData) } if let fixedWidthDownsampledData = dictionary["fixed_width_downsampled"] as? [String:Any]{ fixedWidthDownsampled = FixedHeightDownsampled(fromDictionary: fixedWidthDownsampledData) } if let fixedWidthSmallData = dictionary["fixed_width_small"] as? [String:Any]{ fixedWidthSmall = FixedHeight(fromDictionary: fixedWidthSmallData) } if let fixedWidthSmallStillData = dictionary["fixed_width_small_still"] as? [String:Any]{ fixedWidthSmallStill = Downsized(fromDictionary: fixedWidthSmallStillData) } if let fixedWidthStillData = dictionary["fixed_width_still"] as? [String:Any]{ fixedWidthStill = Downsized(fromDictionary: fixedWidthStillData) } if let loopingData = dictionary["looping"] as? [String:Any]{ looping = DownsizedSmall(fromDictionary: loopingData) } if let originalData = dictionary["original"] as? [String:Any]{ original = Original(fromDictionary: originalData) } if let originalMp4Data = dictionary["original_mp4"] as? [String:Any]{ originalMp4 = OriginalMp4(fromDictionary: originalMp4Data) } if let originalStillData = dictionary["original_still"] as? [String:Any]{ originalStill = Downsized(fromDictionary: originalStillData) } if let previewData = dictionary["preview"] as? [String:Any]{ preview = OriginalMp4(fromDictionary: previewData) } } }
mit
dc805afb3f7c12c94c3d611addd2ba97
39.484848
94
0.766966
3.666972
false
false
false
false
boolkybear/iOS-Challenge
CatViewer/CatViewerTests/CatViewerTests.swift
1
4572
// // CatViewerTests.swift // CatViewerTests // // Created by Boolky Bear on 4/2/15. // Copyright (c) 2015 ByBDesigns. All rights reserved. // import UIKit import XCTest class CatViewerTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // func testExample() { // // This is an example of a functional test case. // XCTAssert(true, "Pass") // } // // func testPerformanceExample() { // // This is an example of a performance test case. // self.measureBlock() { // // Put the code you want to measure the time of here. // } // } func testCatRequest() { var isXMLDownloaded = false let expectation = expectationWithDescription("http://thecatapi.com/api/images/get") request(Method.GET, "http://thecatapi.com/api/images/get", parameters: [ "format" : "xml" ]) .validate() .responseString { (request, _, xmlData, error) in if let xmlData = xmlData { if countElements(xmlData) > 0 && error == nil { isXMLDownloaded = true } } expectation.fulfill() } waitForExpectationsWithTimeout(10) { (error) in XCTAssertNil(error, "\(error)") } XCTAssert(isXMLDownloaded, "XML has not been downloaded") } func testCatParse() { var isXMLParsed = false let expectation = expectationWithDescription("http://thecatapi.com/api/images/get") request(Method.GET, "http://thecatapi.com/api/images/get", parameters: [ "format" : "xml" ]) .validate() .response { (request, _, xmlData, error) in if let xmlData = xmlData as? NSData { if xmlData.length > 0 && error == nil { let parser = NSXMLParser(data: xmlData) let catDelegate = CatParserDelegate() parser.delegate = catDelegate XCTAssert(parser.parse(), "XML has not been parsed") XCTAssert(catDelegate.isParsed(), "XML has not been parsed") XCTAssert(catDelegate.count() == 1, "XML is not correct") let cat = catDelegate[0] XCTAssert(countElements(cat.url ?? "") > 0, "URL should not be empty") XCTAssert(countElements(cat.identifier ?? "") > 0, "Identifier should not be empty") XCTAssert(countElements(cat.url ?? "") > 0, "Source Url should not be empty") isXMLParsed = true } } expectation.fulfill() } waitForExpectationsWithTimeout(10) { (error) in XCTAssertNil(error, "\(error)") } XCTAssert(isXMLParsed, "XML has not been parsed correctly") } func testCategoryParse() { var isXMLParsed = false let expectation = expectationWithDescription("http://thecatapi.com/api/categories/list") request(Method.GET, "http://thecatapi.com/api/categories/list") .validate() .response { (request, _, xmlData, error) in if let xmlData = xmlData as? NSData { if xmlData.length > 0 && error == nil { let parser = NSXMLParser(data: xmlData) let categoryDelegate = CategoryParserDelegate() parser.delegate = categoryDelegate XCTAssert(parser.parse(), "XML has not been parsed") XCTAssert(categoryDelegate.isParsed(), "XML has not been parsed") XCTAssert(categoryDelegate.count() > 0, "XML is not correct") let category = categoryDelegate[0] XCTAssert(countElements(category.identifier ?? "") > 0, "Identifier should not be empty") XCTAssert(countElements(category.name ?? "") > 0, "Name should not be empty") isXMLParsed = true } } expectation.fulfill() } waitForExpectationsWithTimeout(10) { (error) in XCTAssertNil(error, "\(error)") } XCTAssert(isXMLParsed, "XML has not been parsed correctly") } func testFetchFail() { var hasFailed = false let expectation = expectationWithDescription("http://thecatapi.com/api/fail") request(Method.GET, "http://thecatapi.com/api/fail") .response { (_, response, _, _) in if let response = response { if response.statusCode == 404 { hasFailed = true } } expectation.fulfill() } waitForExpectationsWithTimeout(10) { (error) in XCTAssertNil(error, "\(error)") } XCTAssert(hasFailed, "This call was supposed to return a 404 error") } }
mit
d77b2c505283dd8eea9d134aced08165
25.894118
111
0.630796
3.787904
false
true
false
false
chatappcodepath/ChatAppSwift
LZChat/Views/MovieCollectionCell.swift
1
1840
// // MovieCollectionCell.swift // LZChat // // Created by Harshit Mapara on 11/26/16. // // License // Copyright (c) 2017 chatappcodepath // Released under an MIT license: http://opensource.org/licenses/MIT // // import UIKit class MovieCollectionCell: UICollectionViewCell { public static let reuseID = "MovieCollectionCellReuseId" @IBOutlet weak var moveThumbnailView: UIImageView! public var movie: MoviePayload? { didSet { if let posterPath = movie?.poster_path { let baseUrl = "http://image.tmdb.org/t/p/w500" let imageUrl:URL! = URL(string: baseUrl + posterPath) //cell.posterImageView.setImageWith(imageUrl!) let imageRequest = URLRequest(url: imageUrl) self.moveThumbnailView.setImageWith(imageRequest, placeholderImage: nil, success: { (imageRequest, imageResponse, image) in if imageResponse != nil { print("Image was NOT cached, fade in image") self.moveThumbnailView.alpha = 0.0 self.moveThumbnailView.image = image UIView.animate(withDuration: 0.3, animations: { () -> Void in self.moveThumbnailView.alpha = 1.0 }) } else { print("Image was cached so just update the image") self.moveThumbnailView.image = image } }, failure: { (imageRequest, iresponse, error) in print("image fetch error \(error.localizedDescription)") }) } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
mit
b0269a583b8a848737b2daee13564ec7
34.384615
139
0.544022
5
false
false
false
false
ldjhust/DBMusic
DBMusic/DBMusic/ChannelList/Controller/ChannelListTableViewController.swift
1
2850
// // ChannelListTableViewController.swift // DBMusic // // Created by ldjhust on 15/9/24. // Copyright © 2015年 example. All rights reserved. // import UIKit import JVFloatingDrawer import SVProgressHUD protocol ChannelListDelegate { func changeChannelId(id: Int) } let cellReuseId = "reuseCellId" class ChannelListTableViewController: UITableViewController { var channelList: [ChannelList]! var selectedChannelId: Int = 0 var channelDelegate: ChannelListDelegate? // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseId) if ReachabilityTool.reachability!.isReachable() { // 获取别到列表 HTTPTool.sharedHTTPTool.getchannelList { (data) -> Void in self.channelList = data for i in 0 ..< self.channelList.count { // 判断当前选中的是哪一个频道 if self.channelList[i].channelId == mainAppDelegate.channelId { self.selectedChannelId = i break } } self.tableView.reloadData() } } else { SVProgressHUD.showErrorWithStatus("No internet connection!", maskType: SVProgressHUDMaskType.Black) // 提示无网络 } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.channelList == nil { return 0 } else { return self.channelList.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier(cellReuseId)! cell.textLabel?.textColor = UIColor.blackColor() cell.textLabel?.text = self.channelList[indexPath.row].channelString if self.selectedChannelId == indexPath.row { cell.textLabel?.textColor = UIColor.blueColor() } return cell } // MARK: TableView Delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.tableView.deselectRowAtIndexPath(indexPath, animated: true) self.selectedChannelId = indexPath.row self.tableView.reloadData() // 改变了频道,刷新数据 // 自动关闭右侧抽屉 (UIApplication.sharedApplication().keyWindow?.rootViewController as! JVFloatingDrawerViewController).toggleDrawerWithSide(JVFloatingDrawerSide.Right, animated: true) { (finished) -> Void in // 改变频道列表 if self.channelDelegate != nil { self.channelDelegate!.changeChannelId(self.channelList[indexPath.row].channelId) } } } }
mit
9aec2d8a142f37a7d57d48c1168b6cb9
27.071429
193
0.693202
4.686542
false
false
false
false
Flappy-BoilerMaker/Flappy-One
Flappy Nyancat/GameScene.swift
1
23017
// // GameScene.swift // Flappy Nyancat // // Created by Frank Hu on 2017/2/21. // Copyright © 2017年 Weichu Hu. All rights reserved. // import Foundation import SpriteKit import AVFoundation import Social import UIKit import Firebase //import GameplayKit struct GameObjects { static let Octocat : UInt32 = 0x1 << 1 static let Ground : UInt32 = 0x1 << 2 static let Wall : UInt32 = 0x1 << 3 static let Score : UInt32 = 0x1 << 4 } class GameRoomTableView: UITableView,UITableViewDelegate,UITableViewDataSource { var items: [Score] = [] override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) self.delegate = self self.dataSource = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell let tmp = self.items[indexPath.row] cell.backgroundColor = UIColor(white: 1, alpha: 0.5) //Score print format add by Frank cell.textLabel?.font = UIFont(name: "Savior1", size: 30) if (tmp.score! < 100) { if (tmp.score! < 10) { cell.textLabel?.text = "\(indexPath.row + 1): \(tmp.score!) stars \(tmp.name!)" } else { cell.textLabel?.text = "\(indexPath.row + 1): \(tmp.score!) stars \(tmp.name!)" } } else { cell.textLabel?.text = "\(indexPath.row + 1): \(tmp.score!) stars \(tmp.name!)" } //cell.textLabel?.text = "\(indexPath.row + 1). Score: \(tmp.score!) by \(tmp.name!)" return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Scoreboard" } } class GameScene: SKScene, SKPhysicsContactDelegate { //var entities = [GKEntity]() //var graphs = [String : GKGraph]() var Ground = SKSpriteNode() var Octocat = SKSpriteNode() var wallPair = SKNode() var moveRemove = SKAction() var gameStart = Bool() var score = Int() let scoreLb = SKLabelNode() var died = Bool() var restart = SKSpriteNode( ) var fb = SKSpriteNode() var uploading: Bool = false var fillin = UITextField() var uploader = SKSpriteNode() var scoreboard = GameRoomTableView() var yes = SKSpriteNode() var no = SKSpriteNode() var ref:FIRDatabaseReference? var scores: [Score]! = [] // Sound Effects var playerBG = AVAudioPlayer() var playerJP = AVAudioPlayer() var playerStop = AVAudioPlayer() var playerBtnPush = AVAudioPlayer() var playerUploadTrue = AVAudioPlayer() var playerUploadFalse = AVAudioPlayer() var playerRestart = AVAudioPlayer() var playerLevelup = AVAudioPlayer() //private var lastUpdateTime : TimeInterval = 0 //private var label : SKLabelNode? //private var spinnyNode : SKShapeNode? func playSound() { do { playerBG = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "NyanCat", ofType: "mp3")!)) playerBG.prepareToPlay() } catch let error { print(error) } do { playerJP = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "jump", ofType: "wav")!)) playerJP.prepareToPlay() } catch let error { print(error) } do { playerStop = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "stop_cut", ofType: "mp3")!)) playerStop.prepareToPlay() } catch let error { print(error) } do { playerBtnPush = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "Push_Btn", ofType: "mp3")!)) playerStop.prepareToPlay() } catch let error { print(error) } do { playerUploadTrue = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "upload_true", ofType: "mp3")!)) playerStop.prepareToPlay() } catch let error { print(error) } do { playerUploadFalse = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "upload_false", ofType: "mp3")!)) playerStop.prepareToPlay() } catch let error { print(error) } do { playerRestart = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "restart", ofType: "mp3")!)) playerStop.prepareToPlay() } catch let error { print(error) } do { playerLevelup = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "levelup", ofType: "mp3")!)) playerStop.prepareToPlay() } catch let error { print(error) } } func restartScene(){ self.playerRestart.play() self.removeAllChildren() self.removeAllActions() self.scoreboard.removeFromSuperview() if uploading == true { cancelUpload() } died = false gameStart = false score = 0 createScene() } func createScene() { //print(UIFont.familyNames) self.physicsWorld.contactDelegate = self for i in 0..<2 { let background = SKSpriteNode(imageNamed: "pixel_background") background.anchorPoint = CGPoint.zero background.position = CGPoint(x: CGFloat(i) * self.frame.width, y: 0) background.name = "background" background.size = (self.view?.bounds.size)! self.addChild(background) } scoreLb.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 + self.frame.height / 2.5 + 8) scoreLb.text = "Star(s): \(score)" // scoreLb.fontName = "04b" // scoreLb.fontSize = 25 scoreLb.fontName = "3Dventure" scoreLb.fontSize = 45 scoreLb.zPosition = 5 //scoreLb.fontColor self.addChild(scoreLb) //set up ground image Ground = SKSpriteNode(imageNamed: "pixel_keyboard") Ground.setScale(0.42) Ground.position = CGPoint(x: self.frame.width / 2, y: 0 + Ground.frame.height / 2) Ground.physicsBody = SKPhysicsBody(rectangleOf: Ground.size) Ground.physicsBody?.categoryBitMask = GameObjects.Ground Ground.physicsBody?.collisionBitMask = GameObjects.Octocat Ground.physicsBody?.contactTestBitMask = GameObjects.Octocat Ground.physicsBody?.affectedByGravity = false Ground.physicsBody?.isDynamic = false Ground.zPosition = 3 self.addChild(Ground) //set up octocat image Octocat = SKSpriteNode(imageNamed: "Frank_icon_double") Octocat.size = CGSize(width: 45, height: 45) Octocat.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2) Octocat.physicsBody = SKPhysicsBody(circleOfRadius: Octocat.frame.height / 2) Octocat.physicsBody?.categoryBitMask = GameObjects.Octocat Octocat.physicsBody?.collisionBitMask = GameObjects.Ground | GameObjects.Wall Octocat.physicsBody?.contactTestBitMask = GameObjects.Ground | GameObjects.Wall | GameObjects.Score Octocat.physicsBody?.affectedByGravity = false Octocat.physicsBody?.isDynamic = true Octocat.zPosition = 2 self.addChild(Octocat) } override func didMove(to view: SKView) { playSound() createScene() } func createBTN(){ self.playerStop.play() self.playerBG.stop() restart = SKSpriteNode(imageNamed: "Restart") restart.size = CGSize(width: 200, height: 100) restart.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 - 50) restart.zPosition = 6 restart.setScale(0) self.addChild(restart) restart.run(SKAction.scale(to: 1.0, duration: 0.3)) } func share(){ //self.playerBtnPush.play() fb = SKSpriteNode(imageNamed: "share_fix") fb.size = CGSize(width: 200, height: 100) fb.position = CGPoint(x: self.frame.width / 2 + 80, y: self.frame.height / 2 - 150) fb.zPosition = 6 fb.setScale(0) self.addChild(fb) fb.run(SKAction.scale(to: 0.7, duration: 0.3)) } //heng li upload btn func uploadBtn() { //self.playerBtnPush.play() uploader = SKSpriteNode(imageNamed: "upload_fix") uploader.size = CGSize(width: 200, height: 100) uploader.position = CGPoint(x: self.frame.width / 2 - 80, y: self.frame.height / 2 - 150) uploader.zPosition = 6 uploader.setScale(0) self.addChild(uploader) uploader.run(SKAction.scale(to: 0.7, duration: 0.3)) } func onUpload() { self.playerBtnPush.play() //self.playerBG.stop() //uploader.removeFromParent() fillin.frame = CGRect(x: self.frame.width / 2 - 80, y: self.frame.height / 2 - 15, width: 160, height: 30) fillin.placeholder = "Enter nick name" fillin.backgroundColor = UIColor.gray self.scene?.view?.addSubview(fillin) yes = SKSpriteNode(imageNamed: "check_icon") yes.size = CGSize(width: 50, height: 50) yes.position = CGPoint(x: self.frame.width / 2 + 35, y: self.frame.height / 2 - 45) yes.zPosition = 10 yes.setScale(0) self.addChild(yes) yes.run(SKAction.scale(to: 1.0, duration: 0.3)) no = SKSpriteNode(imageNamed: "cross_icon") no.size = CGSize(width: 50, height: 50) no.position = CGPoint(x: self.frame.width / 2 - 35, y: self.frame.height / 2 - 45) no.zPosition = 10 no.setScale(0) self.addChild(no) no.run(SKAction.scale(to: 1.0, duration: 0.3)) uploading = true } func cancelUpload() { self.playerBtnPush.play() yes.removeFromParent() no.removeFromParent() fillin.removeFromSuperview() // uploader.removeFromParent() // uploadBtn() fillin.text = "" uploading = false } func insertBoard(new: Int) { var swap: Int = 10 for index in 0...9 { // print("Swap3: \(index)") if score >= self.scoreboard.items[index].score! { swap = index break // print("Swap1: \(swap)") } } if swap != 10 { if swap < 9 { for index in 0...8-swap { // print("Swap2: \(3-index)") self.scoreboard.items[9-index].name = self.scoreboard.items[8-index].name self.scoreboard.items[9-index].score = self.scoreboard.items[8-index].score } } self.scoreboard.items[swap].name = fillin.text self.scoreboard.items[swap].score = score self.scoreboard.reloadData() } } func uploadScore() { if fillin.text != "" { self.playerUploadTrue.play() ref = FIRDatabase.database().reference() let post = ["name": fillin.text!, "score": score] as [String : Any] ref?.child("Score").childByAutoId().setValue(post) if score > self.scoreboard.items[9].score! { insertBoard(new: score) } cancelUpload() } else { self.playerUploadFalse.play() fillin.placeholder = "Cannot be empty" } } func displayScore(){ ref = FIRDatabase.database().reference() ref?.child("Score").queryOrdered(byChild: "score").queryLimited(toLast: 10).observe(.childAdded, with: { snapshot in let dict = snapshot.value as! [String: Any] let name = dict["name"] as? String let score = dict["score"] as? Int // print("test \(name!) and \(score!)") let tmp = Score(player: name!, score: score!) self.scores.append(tmp) if self.scores.count == 10 { self.scoreboard.register(UITableViewCell.self, forCellReuseIdentifier: "cell") self.scoreboard.frame = CGRect(x: self.frame.width / 2 - (300/2), y: (self.frame.height / 2) - (self.frame.height / 2.5) + 8, width: 300, height: 250) self.scoreboard.backgroundColor = UIColor(white: 1, alpha: 0.5) self.scene?.view?.addSubview(self.scoreboard) self.scores.reverse() self.scoreboard.items = self.scores self.scoreboard.reloadData() } }) } func didBegin(_ contact: SKPhysicsContact) { let firstBody = contact.bodyA let secondBody = contact.bodyB if firstBody.categoryBitMask == GameObjects.Score && secondBody.categoryBitMask == GameObjects.Octocat{ score += 1 scoreLb.text = "Star(s): \(score)" if (score % 50 == 0){ self.playerLevelup.play() } firstBody.node?.removeFromParent() } else if firstBody.categoryBitMask == GameObjects.Octocat && secondBody.categoryBitMask == GameObjects.Score { score += 1 if (score % 50 == 0){ self.playerLevelup.play() } scoreLb.text = "Star(s): \(score)" secondBody.node?.removeFromParent() } else if firstBody.categoryBitMask == GameObjects.Octocat && secondBody.categoryBitMask == GameObjects.Wall || firstBody.categoryBitMask == GameObjects.Wall && secondBody.categoryBitMask == GameObjects.Octocat{ enumerateChildNodes(withName: "wallPair", using: ({ (node, error) in node.speed = 0 self.removeAllActions() })) if died == false{ died = true createBTN() share() uploadBtn() scores = [] displayScore() } } else if firstBody.categoryBitMask == GameObjects.Octocat && secondBody.categoryBitMask == GameObjects.Ground || firstBody.categoryBitMask == GameObjects.Ground && secondBody.categoryBitMask == GameObjects.Octocat{ enumerateChildNodes(withName: "wallPair", using: ({ (node, error) in node.speed = 0 self.removeAllActions() })) if died == false{ died = true createBTN() share() uploadBtn() scores = [] displayScore() } } } func createWalls(){ let scoreNode = SKSpriteNode(imageNamed: "star_05") scoreNode.size = CGSize(width: 50, height: 50) scoreNode.position = CGPoint(x: self.frame.width + 25, y: self.frame.height / 2) scoreNode.physicsBody = SKPhysicsBody(rectangleOf: scoreNode.size) scoreNode.physicsBody?.affectedByGravity = false scoreNode.physicsBody?.isDynamic = false scoreNode.physicsBody?.categoryBitMask = GameObjects.Score scoreNode.physicsBody?.collisionBitMask = 0 scoreNode.physicsBody?.contactTestBitMask = GameObjects.Octocat scoreNode.color = SKColor.blue wallPair = SKNode() //let wallPair = SKNode() wallPair.name = "wallPair" let topWall = SKSpriteNode(imageNamed: "top_wall") let btmWall = SKSpriteNode(imageNamed: "Wall_Redbull_02") topWall.position = CGPoint(x: self.frame.width + 25, y: self.frame.height / 2 + 350) btmWall.position = CGPoint(x: self.frame.width + 25, y: self.frame.height / 2 - 350) topWall.setScale(0.5) btmWall.setScale(0.5) topWall.physicsBody = SKPhysicsBody(rectangleOf: topWall.size) topWall.physicsBody?.categoryBitMask = GameObjects.Wall topWall.physicsBody?.collisionBitMask = GameObjects.Octocat topWall.physicsBody?.contactTestBitMask = GameObjects.Octocat topWall.physicsBody?.isDynamic = false topWall.physicsBody?.affectedByGravity = false btmWall.physicsBody = SKPhysicsBody(rectangleOf: btmWall.size) btmWall.physicsBody?.categoryBitMask = GameObjects.Wall btmWall.physicsBody?.collisionBitMask = GameObjects.Octocat btmWall.physicsBody?.contactTestBitMask = GameObjects.Octocat btmWall.physicsBody?.isDynamic = false btmWall.physicsBody?.affectedByGravity = false //topWall.zRotation = CGFloat(M_PI) wallPair.addChild(topWall) wallPair.addChild(btmWall) wallPair.zPosition = 1 let randomPosition = CGFloat.random(min: -120, max: 220) wallPair.position.y = wallPair.position.y + randomPosition wallPair.addChild(scoreNode) wallPair.run(moveRemove) self.addChild(wallPair) } func shareScore(scene: SKScene) { let postText: String = "I collected \(score) stars in Jump! Jump! Frank! Come and beat me in the game!\nhttps://appsto.re/us/jvKeib.i" let postImage: UIImage = getScreenshot(scene: scene) let activityItems = [postText, postImage] as [Any] let activityController = UIActivityViewController( activityItems: activityItems, applicationActivities: nil ) let controller: UIViewController = scene.view!.window!.rootViewController! controller.present( activityController, animated: true, completion: nil ) } func getScreenshot(scene: SKScene) -> UIImage { // let snapshotView = scene.view!.snapshotView(afterScreenUpdates: true) // let bounds = UIScreen.main.bounds // // UIGraphicsBeginImageContextWithOptions(bounds.size, false, 1.0) // // snapshotView?.drawHierarchy(in: bounds, afterScreenUpdates: true) // // let screenshotImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()! // // UIGraphicsEndImageContext() //UIImageWriteToSavedPhotosAlbum(screenshotImage, nil, nil, nil) UIGraphicsBeginImageContextWithOptions(self.view!.bounds.size, false, 1) self.view?.drawHierarchy(in: (self.view?.bounds)!, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if gameStart == false{ gameStart = true self.playerBG.play() self.Octocat.physicsBody?.affectedByGravity = true let spawn = SKAction.run({ () in self.createWalls() }) let delay = SKAction.wait(forDuration: 1.5) let SpawnDelay = SKAction.sequence([spawn, delay]) let spawnDelayForever = SKAction.repeatForever(SpawnDelay) self.run(spawnDelayForever) let distance = CGFloat(self.frame.width + wallPair.frame.width) let movePipes = SKAction.moveBy(x: -distance - 50, y: 0, duration: TimeInterval(0.008 * distance)) let removePipes = SKAction.removeFromParent() moveRemove = SKAction.sequence([movePipes, removePipes]) playerJP.play() Octocat.physicsBody?.velocity = CGVector(dx: 0, dy: 0) Octocat.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 30)) } else{ if died == true{ } else{ playerJP.play() Octocat.physicsBody?.velocity = CGVector(dx: 0, dy: 0) Octocat.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 30)) } } for touch in touches{ let location = touch.location(in: self) if died == true{ if restart.contains(location){ // uploader.removeFromParent() if uploading == true { if yes.contains(location){ uploadScore() } if no.contains(location){ cancelUpload() } } else {restartScene()} } if fb.contains(location){ self.playerBtnPush.play() shareScore(scene: self) } if uploader.contains(location){ if uploading == false { onUpload() } else { } } } } } override func update(_ currentTime: TimeInterval) { /* Called before each frame is rendered */ if gameStart == true{ if died == false{ enumerateChildNodes(withName: "background", using: ({ (node, error) in let bg = node as! SKSpriteNode bg.position = CGPoint(x: bg.position.x - 2, y: bg.position.y) if bg.position.x <= -bg.size.width { bg.position = CGPoint(x: bg.position.x + bg.size.width * 2, y: bg.position.y) } })) } } } }
apache-2.0
99efb10c7fbb002d7a21bd2dc89371ee
34.189602
221
0.553272
4.693861
false
false
false
false
sonnygauran/trailer
PocketTrailer WatchKit Extension/PRRow.swift
1
1203
import WatchKit final class PRRow: NSObject { @IBOutlet weak var titleL: WKInterfaceLabel! @IBOutlet weak var detailsL: WKInterfaceLabel! @IBOutlet weak var totalCommentsL: WKInterfaceLabel! @IBOutlet weak var totalCommentsGroup: WKInterfaceGroup! @IBOutlet weak var unreadCommentsL: WKInterfaceLabel! @IBOutlet weak var unreadCommentsGroup: WKInterfaceGroup! @IBOutlet weak var counterGroup: WKInterfaceGroup! var itemId: String? func populateFrom(itemData: [String : AnyObject]) { let titleData = itemData["title"] as! NSData let title = NSKeyedUnarchiver.unarchiveObjectWithData(titleData) as! NSAttributedString titleL.setAttributedText(title) let subtitleData = itemData["subtitle"] as! NSData let subtitle = NSKeyedUnarchiver.unarchiveObjectWithData(subtitleData) as! NSAttributedString detailsL.setAttributedText(subtitle) itemId = itemData["localId"] as? String let c = itemData["commentCount"] as? Int ?? 0 totalCommentsL.setText("\(c)") totalCommentsGroup.setHidden(c==0) let u = itemData["unreadCount"] as? Int ?? 0 unreadCommentsL.setText("\(u)") unreadCommentsGroup.setHidden(u==0) counterGroup.setHidden(c+u==0) } }
mit
c9c353be641fc2262b43f2bc415b83e2
28.341463
95
0.755611
4.281139
false
false
false
false
stripe/stripe-ios
StripePaymentsUI/StripePaymentsUI/Internal/UI/Views/Inputs/STPInputTextField.swift
1
9196
// // STPInputTextField.swift // StripePaymentsUI // // Created by Cameron Sabol on 10/12/20. // Copyright © 2020 Stripe, Inc. All rights reserved. // @_spi(STP) import StripeUICore import UIKit @_spi(STP) public class STPInputTextField: STPFloatingPlaceholderTextField, STPFormInputValidationObserver { let formatter: STPInputTextFieldFormatter let validator: STPInputTextFieldValidator weak var formContainer: STPFormContainer? = nil var wantsAutoFocus: Bool { return true } let accessoryImageStackView: UIStackView = { let stackView = UIStackView() stackView.alignment = .center stackView.distribution = .fillProportionally stackView.spacing = 6 return stackView }() let errorStateImageView: UIImageView = { let imageView = UIImageView(image: STPImageLibrary.safeImageNamed("form_error_icon")) imageView.contentMode = UIView.ContentMode.scaleAspectFit return imageView }() required init( formatter: STPInputTextFieldFormatter, validator: STPInputTextFieldValidator ) { self.formatter = formatter self.validator = validator super.init(frame: .zero) delegate = formatter validator.textField = self validator.addObserver(self) addTarget(self, action: #selector(textDidChange), for: .editingChanged) } override func setupSubviews() { super.setupSubviews() let fontMetrics = UIFontMetrics(forTextStyle: .body) font = fontMetrics.scaledFont(for: UIFont.systemFont(ofSize: 14)) placeholderLabel.font = font defaultPlaceholderColor = .secondaryLabel floatingPlaceholderColor = .secondaryLabel rightView = accessoryImageStackView rightViewMode = .always errorStateImageView.alpha = 0 accessoryImageStackView.addArrangedSubview(errorStateImageView) } required init?( coder: NSCoder ) { fatalError("init(coder:) has not been implemented") } @_spi(STP) public override var text: String? { didSet { textDidChange() } } internal func addAccessoryViews(_ accessoryViews: [UIView]) { for view in accessoryViews { accessoryImageStackView.addArrangedSubview(view) } } internal func removeAccessoryViews(_ accessoryViews: [UIView]) { for view in accessoryViews { accessoryImageStackView.removeArrangedSubview(view) view.removeFromSuperview() } } @objc func textDidChange() { let text = self.text ?? "" let formatted = formatter.formattedText(from: text, with: defaultTextAttributes) if formatted != attributedText { var updatedCursorPosition: UITextPosition? = nil if let selection = selectedTextRange { let cursorPosition = offset(from: beginningOfDocument, to: selection.start) updatedCursorPosition = position( from: beginningOfDocument, offset: cursorPosition - (text.count - formatted.length) ) } attributedText = formatted sendActions(for: .valueChanged) if let updatedCursorPosition = updatedCursorPosition { selectedTextRange = textRange( from: updatedCursorPosition, to: updatedCursorPosition ) } } validator.inputValue = formatted.string } @objc override public func becomeFirstResponder() -> Bool { self.formContainer?.inputTextFieldWillBecomeFirstResponder(self) let ret = super.becomeFirstResponder() updateTextColor() return ret } @objc override public func resignFirstResponder() -> Bool { let ret = super.resignFirstResponder() if ret { self.formContainer?.inputTextFieldDidResignFirstResponder(self) } updateTextColor() return ret } var isValid: Bool { switch validator.validationState { case .unknown, .valid, .processing: return true case .incomplete: if isEditing { return true } else { return false } case .invalid: return false } } @objc override public var isUserInteractionEnabled: Bool { didSet { if isUserInteractionEnabled { updateTextColor() defaultPlaceholderColor = .secondaryLabel floatingPlaceholderColor = .secondaryLabel } else { textColor = InputFormColors.disabledTextColor defaultPlaceholderColor = InputFormColors.disabledTextColor floatingPlaceholderColor = InputFormColors.disabledTextColor } } } func updateTextColor() { switch validator.validationState { case .unknown: textColor = InputFormColors.textColor errorStateImageView.alpha = 0 case .incomplete: if isEditing || (validator.inputValue?.isEmpty ?? true) { textColor = InputFormColors.textColor errorStateImageView.alpha = 0 } else { textColor = InputFormColors.errorColor errorStateImageView.alpha = 1 } case .invalid: textColor = InputFormColors.errorColor errorStateImageView.alpha = 1 case .valid: textColor = InputFormColors.textColor errorStateImageView.alpha = 0 case .processing: textColor = InputFormColors.textColor errorStateImageView.alpha = 0 } } @objc public override var accessibilityAttributedValue: NSAttributedString? { get { guard let text = text else { return nil } let attributedString = NSMutableAttributedString(string: text) if #available(iOS 13.0, *) { attributedString.addAttribute( .accessibilitySpeechSpellOut, value: NSNumber(value: true), range: attributedString.extent ) } return attributedString } set { // do nothing } } @objc public override var accessibilityAttributedLabel: NSAttributedString? { get { guard let accessibilityLabel = accessibilityLabel else { return nil } let attributedString = NSMutableAttributedString(string: accessibilityLabel) if !isValid { let invalidData = STPLocalizedString( "Invalid data.", "Spoken during VoiceOver when a form field has failed validation." ) let failedString = NSMutableAttributedString( string: invalidData, attributes: [ NSAttributedString.Key.accessibilitySpeechPitch: NSNumber(value: 0.6) ] ) attributedString.append(NSAttributedString(string: " ")) attributedString.append(failedString) } return attributedString } set { // do nothing } } @objc public override func deleteBackward() { let deletingOnEmpty = (text?.count ?? 0) == 0 super.deleteBackward() if deletingOnEmpty { formContainer?.inputTextFieldDidBackspaceOnEmpty(self) } } // Fixes a weird issue related to our custom override of deleteBackwards. This only affects the simulator and iPads with custom keyboards. // copied from STPFormTextField @objc public override var keyCommands: [UIKeyCommand]? { return [ UIKeyCommand( input: "\u{08}", modifierFlags: .command, action: #selector(commandDeleteBackwards) ) ] } @objc func commandDeleteBackwards() { text = "" } // MARK: - STPInputTextFieldValidationObserver func validationDidUpdate( to state: STPValidatedInputState, from previousState: STPValidatedInputState, for unformattedInput: String?, in input: STPFormInput ) { guard input == self, unformattedInput == text else { return } updateTextColor() } } /// :nodoc: extension STPInputTextField: STPFormInput { var validationState: STPValidatedInputState { return validator.validationState } var inputValue: String? { return validator.inputValue } func addObserver(_ validationObserver: STPFormInputValidationObserver) { validator.addObserver(validationObserver) } func removeObserver(_ validationObserver: STPFormInputValidationObserver) { validator.removeObserver(validationObserver) } }
mit
3efddd2c112fc779970f276ed92ccc65
29.855705
142
0.596846
5.801262
false
false
false
false
BenziAhamed/Nevergrid
NeverGrid/Source/MoveInAsClone.swift
1
898
// // MoveInAsClone.swift // MrGreen // // Created by Benzi on 15/08/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // import Foundation import SpriteKit /// action that runs an animated entry of the /// newly cloned clone class MoveInAsClone : EntityAction { override var description:String { return "MoveInAsClone" } override func perform() -> SKAction? { let location = world.location.get(entity) let enemy = world.enemy.get(entity) enemy.enabled = true let cell = world.level.cells.get(location)! cell.occupiedBy = entity let moveTo = SKAction.moveTo(world.gs.getEntityPosition(location), duration: ActionFactory.Timing.EntityMove) let fadeIn = SKAction.fadeInWithDuration(ActionFactory.Timing.EntityMove) return SKAction.group([moveTo,fadeIn]) } }
isc
519732192e7a10aadcacc17f6bda1e19
24.657143
117
0.657016
4.196262
false
false
false
false
LucianoPAlmeida/SwifterSwift
Sources/Extensions/SwiftStdlib/StringExtensions.swift
1
33144
// // StringExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/5/16. // Copyright © 2016 SwifterSwift // #if os(macOS) import Cocoa #else import UIKit #endif // MARK: - Properties public extension String { /// SwifterSwift: String decoded from base64 (if applicable). /// /// "SGVsbG8gV29ybGQh".base64Decoded = Optional("Hello World!") /// public var base64Decoded: String? { // https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift guard let decodedData = Data(base64Encoded: self) else { return nil } return String(data: decodedData, encoding: .utf8) } /// SwifterSwift: String encoded in base64 (if applicable). /// /// "Hello World!".base64Encoded -> Optional("SGVsbG8gV29ybGQh") /// public var base64Encoded: String? { // https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift let plainData = data(using: .utf8) return plainData?.base64EncodedString() } /// SwifterSwift: Array of characters of a string. /// public var charactersArray: [Character] { return Array(self) } /// SwifterSwift: CamelCase of string. /// /// "sOme vAriable naMe".camelCased -> "someVariableName" /// public var camelCased: String { let source = lowercased() let first = source[..<source.index(after: source.startIndex)] if source.contains(" ") { let connected = source.capitalized.replacingOccurrences(of: " ", with: "") let camel = connected.replacingOccurrences(of: "\n", with: "") let rest = String(camel.dropFirst()) return first + rest } let rest = String(source.dropFirst()) return first + rest } /// SwifterSwift: Check if string contains one or more emojis. /// /// "Hello 😀".containEmoji -> true /// public var containEmoji: Bool { // http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji for scalar in unicodeScalars { switch scalar.value { case 0x3030, 0x00AE, 0x00A9, // Special Characters 0x1D000...0x1F77F, // Emoticons 0x2100...0x27BF, // Misc symbols and Dingbats 0xFE00...0xFE0F, // Variation Selectors 0x1F900...0x1F9FF: // Supplemental Symbols and Pictographs return true default: continue } } return false } /// SwifterSwift: First character of string (if applicable). /// /// "Hello".firstCharacterAsString -> Optional("H") /// "".firstCharacterAsString -> nil /// public var firstCharacterAsString: String? { guard let first = self.first else { return nil } return String(first) } /// SwifterSwift: Check if string contains one or more letters. /// /// "123abc".hasLetters -> true /// "123".hasLetters -> false /// public var hasLetters: Bool { return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil } /// SwifterSwift: Check if string contains one or more numbers. /// /// "abcd".hasNumbers -> false /// "123abc".hasNumbers -> true /// public var hasNumbers: Bool { return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil } /// SwifterSwift: Check if string contains only letters. /// /// "abc".isAlphabetic -> true /// "123abc".isAlphabetic -> false /// public var isAlphabetic: Bool { let hasLetters = rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil let hasNumbers = rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil return hasLetters && !hasNumbers } /// SwifterSwift: Check if string contains at least one letter and one number. /// /// // useful for passwords /// "123abc".isAlphaNumeric -> true /// "abc".isAlphaNumeric -> false /// public var isAlphaNumeric: Bool { let hasLetters = rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil let hasNumbers = rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil let comps = components(separatedBy: .alphanumerics) return comps.joined(separator: "").count == 0 && hasLetters && hasNumbers } /// SwifterSwift: Check if string is valid email format. /// /// "[email protected]".isEmail -> true /// public var isEmail: Bool { // http://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift return matches(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}") } /// SwifterSwift: Check if string is a valid URL. /// /// "https://google.com".isValidUrl -> true /// public var isValidUrl: Bool { return URL(string: self) != nil } /// SwifterSwift: Check if string is a valid schemed URL. /// /// "https://google.com".isValidSchemedUrl -> true /// "google.com".isValidSchemedUrl -> false /// public var isValidSchemedUrl: Bool { guard let url = URL(string: self) else { return false } return url.scheme != nil } /// SwifterSwift: Check if string is a valid https URL. /// /// "https://google.com".isValidHttpsUrl -> true /// public var isValidHttpsUrl: Bool { guard let url = URL(string: self) else { return false } return url.scheme == "https" } /// SwifterSwift: Check if string is a valid http URL. /// /// "http://google.com".isValidHttpUrl -> true /// public var isValidHttpUrl: Bool { guard let url = URL(string: self) else { return false } return url.scheme == "http" } /// SwifterSwift: Check if string is a valid file URL. /// /// "file://Documents/file.txt".isValidFileUrl -> true /// public var isValidFileUrl: Bool { return URL(string: self)?.isFileURL ?? false } /// SwifterSwift: Check if string is a valid Swift number. /// /// Note: /// In North America, "." is the decimal separator, /// while in many parts of Europe "," is used, /// /// "123".isNumeric -> true /// "1.3".isNumeric -> true (en_US) /// "1,3".isNumeric -> true (fr_FR) /// "abc".isNumeric -> false /// public var isNumeric: Bool { let scanner = Scanner(string: self) scanner.locale = NSLocale.current return scanner.scanDecimal(nil) && scanner.isAtEnd } /// SwifterSwift: Check if string only contains digits. /// /// "123".isDigits -> true /// "1.3".isDigits -> false /// "abc".isDigits -> false /// public var isDigits: Bool { return CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: self)) } /// SwifterSwift: Last character of string (if applicable). /// /// "Hello".lastCharacterAsString -> Optional("o") /// "".lastCharacterAsString -> nil /// public var lastCharacterAsString: String? { guard let last = self.last else { return nil } return String(last) } /// SwifterSwift: Latinized string. /// /// "Hèllö Wórld!".latinized -> "Hello World!" /// public var latinized: String { return folding(options: .diacriticInsensitive, locale: Locale.current) } /// SwifterSwift: Bool value from string (if applicable). /// /// "1".bool -> true /// "False".bool -> false /// "Hello".bool = nil /// public var bool: Bool? { let selfLowercased = trimmed.lowercased() if selfLowercased == "true" || selfLowercased == "1" { return true } else if selfLowercased == "false" || selfLowercased == "0" { return false } return nil } /// SwifterSwift: Date object from "yyyy-MM-dd" formatted string. /// /// "2007-06-29".date -> Optional(Date) /// public var date: Date? { let selfLowercased = trimmed.lowercased() let formatter = DateFormatter() formatter.timeZone = TimeZone.current formatter.dateFormat = "yyyy-MM-dd" return formatter.date(from: selfLowercased) } /// SwifterSwift: Date object from "yyyy-MM-dd HH:mm:ss" formatted string. /// /// "2007-06-29 14:23:09".dateTime -> Optional(Date) /// public var dateTime: Date? { let selfLowercased = trimmed.lowercased() let formatter = DateFormatter() formatter.timeZone = TimeZone.current formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter.date(from: selfLowercased) } /// SwifterSwift: Integer value from string (if applicable). /// /// "101".int -> 101 /// public var int: Int? { return Int(self) } /// SwifterSwift: Lorem ipsum string of given length. /// /// - Parameter length: number of characters to limit lorem ipsum to (default is 445 - full lorem ipsum). /// - Returns: Lorem ipsum dolor sit amet... string. public static func loremIpsum(ofLength length: Int = 445) -> String { guard length > 0 else { return "" } // https://www.lipsum.com/ let loremIpsum = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. """ if loremIpsum.count > length { return String(loremIpsum[loremIpsum.startIndex..<loremIpsum.index(loremIpsum.startIndex, offsetBy: length)]) } return loremIpsum } /// SwifterSwift: URL from string (if applicable). /// /// "https://google.com".url -> URL(string: "https://google.com") /// "not url".url -> nil /// public var url: URL? { return URL(string: self) } /// SwifterSwift: String with no spaces or new lines in beginning and end. /// /// " hello \n".trimmed -> "hello" /// public var trimmed: String { return trimmingCharacters(in: .whitespacesAndNewlines) } /// SwifterSwift: Readable string from a URL string. /// /// "it's%20easy%20to%20decode%20strings".urlDecoded -> "it's easy to decode strings" /// public var urlDecoded: String { return removingPercentEncoding ?? self } /// SwifterSwift: URL escaped string. /// /// "it's easy to encode strings".urlEncoded -> "it's%20easy%20to%20encode%20strings" /// public var urlEncoded: String { return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } /// SwifterSwift: String without spaces and new lines. /// /// " \n Swifter \n Swift ".withoutSpacesAndNewLines -> "SwifterSwift" /// public var withoutSpacesAndNewLines: String { return replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "\n", with: "") } /// SwifterSwift: Check if the given string contains only white spaces public var isWhitespace: Bool { return self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } } // MARK: - Methods public extension String { /// Float value from string (if applicable). /// /// - Parameter locale: Locale (default is Locale.current) /// - Returns: Optional Float value from given string. public func float(locale: Locale = .current) -> Float? { let formatter = NumberFormatter() formatter.locale = locale formatter.allowsFloats = true return formatter.number(from: self) as? Float } /// Double value from string (if applicable). /// /// - Parameter locale: Locale (default is Locale.current) /// - Returns: Optional Double value from given string. public func double(locale: Locale = .current) -> Double? { let formatter = NumberFormatter() formatter.locale = locale formatter.allowsFloats = true return formatter.number(from: self) as? Double } /// CGFloat value from string (if applicable). /// /// - Parameter locale: Locale (default is Locale.current) /// - Returns: Optional CGFloat value from given string. public func cgFloat(locale: Locale = .current) -> CGFloat? { let formatter = NumberFormatter() formatter.locale = locale formatter.allowsFloats = true return formatter.number(from: self) as? CGFloat } /// SwifterSwift: Array of strings separated by new lines. /// /// "Hello\ntest".lines() -> ["Hello", "test"] /// /// - Returns: Strings separated by new lines. public func lines() -> [String] { var result = [String]() enumerateLines { line, _ in result.append(line) } return result } /// SwifterSwift: Returns a localized string, with an optional comment for translators. /// /// "Hello world".localized -> Hallo Welt /// public func localized(comment: String = "") -> String { return NSLocalizedString(self, comment: comment) } /// SwifterSwift: The most common character in string. /// /// "This is a test, since e is appearing everywhere e should be the common character".mostCommonCharacter() -> "e" /// /// - Returns: The most common character. public func mostCommonCharacter() -> Character? { let mostCommon = withoutSpacesAndNewLines.reduce(into: [Character: Int]()) { let count = $0[$1] ?? 0 $0[$1] = count + 1 }.max { $0.1 < $1.1 }?.0 return mostCommon } /// SwifterSwift: Array with unicodes for all characters in a string. /// /// "SwifterSwift".unicodeArray -> [83, 119, 105, 102, 116, 101, 114, 83, 119, 105, 102, 116] /// /// - Returns: The unicodes for all characters in a string. public func unicodeArray() -> [Int] { return unicodeScalars.map({ $0.hashValue }) } /// SwifterSwift: an array of all words in a string /// /// "Swift is amazing".words() -> ["Swift", "is", "amazing"] /// /// - Returns: The words contained in a string. public func words() -> [String] { // https://stackoverflow.com/questions/42822838 let chararacterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters) let comps = components(separatedBy: chararacterSet) return comps.filter { !$0.isEmpty } } /// SwifterSwift: Count of words in a string. /// /// "Swift is amazing".wordsCount() -> 3 /// /// - Returns: The count of words contained in a string. public func wordCount() -> Int { // https://stackoverflow.com/questions/42822838 return words().count } /// SwifterSwift: Transforms the string into a slug string. /// /// "Swift is amazing".toSlug() -> "swift-is-amazing" /// /// - Returns: The string in slug format. public func toSlug() -> String { let lowercased = self.lowercased() let latinized = lowercased.latinized let withDashes = latinized.replacingOccurrences(of: " ", with: "-") let alphanumerics = NSCharacterSet.alphanumerics var filtered = withDashes.filter { guard String($0) != "-" else { return true } guard String($0) != "&" else { return true } return String($0).rangeOfCharacter(from: alphanumerics) != nil } while filtered.lastCharacterAsString == "-" { filtered = String(filtered.dropLast()) } while filtered.firstCharacterAsString == "-" { filtered = String(filtered.dropFirst()) } return filtered.replacingOccurrences(of: "--", with: "-") } /// SwifterSwift: Safely subscript string with index. /// /// "Hello World!"[3] -> "l" /// "Hello World!"[20] -> nil /// /// - Parameter i: index. public subscript(safe i: Int) -> Character? { guard i >= 0 && i < count else { return nil } return self[index(startIndex, offsetBy: i)] } /// SwifterSwift: Safely subscript string within a half-open range. /// /// "Hello World!"[6..<11] -> "World" /// "Hello World!"[21..<110] -> nil /// /// - Parameter range: Half-open range. public subscript(safe range: CountableRange<Int>) -> String? { guard let lowerIndex = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else { return nil } guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound, limitedBy: endIndex) else { return nil } return String(self[lowerIndex..<upperIndex]) } /// SwifterSwift: Safely subscript string within a closed range. /// /// "Hello World!"[6...11] -> "World!" /// "Hello World!"[21...110] -> nil /// /// - Parameter range: Closed range. public subscript(safe range: ClosedRange<Int>) -> String? { guard let lowerIndex = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else { return nil } guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound + 1, limitedBy: endIndex) else { return nil } return String(self[lowerIndex..<upperIndex]) } #if os(iOS) || os(macOS) /// SwifterSwift: Copy string to global pasteboard. /// /// "SomeText".copyToPasteboard() // copies "SomeText" to pasteboard /// public func copyToPasteboard() { #if os(iOS) UIPasteboard.general.string = self #elseif os(macOS) NSPasteboard.general.clearContents() NSPasteboard.general.setString(self, forType: .string) #endif } #endif /// SwifterSwift: Converts string format to CamelCase. /// /// var str = "sOme vaRiabLe Name" /// str.camelize() /// print(str) // prints "someVariableName" /// public mutating func camelize() { self = camelCased } /// SwifterSwift: Check if string contains only unique characters. /// public func hasUniqueCharacters() -> Bool { guard count > 0 else { return false } var uniqueChars = Set<String>() for char in self { if uniqueChars.contains(String(char)) { return false } uniqueChars.insert(String(char)) } return true } /// SwifterSwift: Check if string contains one or more instance of substring. /// /// "Hello World!".contain("O") -> false /// "Hello World!".contain("o", caseSensitive: false) -> true /// /// - Parameters: /// - string: substring to search for. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: true if string contains one or more instance of substring. public func contains(_ string: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return range(of: string, options: .caseInsensitive) != nil } return range(of: string) != nil } /// SwifterSwift: Count of substring in string. /// /// "Hello World!".count(of: "o") -> 2 /// "Hello World!".count(of: "L", caseSensitive: false) -> 3 /// /// - Parameters: /// - string: substring to search for. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: count of appearance of substring in string. public func count(of string: String, caseSensitive: Bool = true) -> Int { if !caseSensitive { return lowercased().components(separatedBy: string.lowercased()).count - 1 } return components(separatedBy: string).count - 1 } /// SwifterSwift: Check if string ends with substring. /// /// "Hello World!".ends(with: "!") -> true /// "Hello World!".ends(with: "WoRld!", caseSensitive: false) -> true /// /// - Parameters: /// - suffix: substring to search if string ends with. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: true if string ends with substring. public func ends(with suffix: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return lowercased().hasSuffix(suffix.lowercased()) } return hasSuffix(suffix) } /// SwifterSwift: Latinize string. /// /// var str = "Hèllö Wórld!" /// str.latinize() /// print(str) // prints "Hello World!" /// public mutating func latinize() { self = latinized } /// SwifterSwift: Random string of given length. /// /// String.random(ofLength: 18) -> "u7MMZYvGo9obcOcPj8" /// /// - Parameter length: number of characters in string. /// - Returns: random string of given length. public static func random(ofLength length: Int) -> String { guard length > 0 else { return "" } let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" var randomString = "" for _ in 1...length { let randomIndex = arc4random_uniform(UInt32(base.count)) let randomCharacter = base.charactersArray[Int(randomIndex)] randomString.append(randomCharacter) } return randomString } /// SwifterSwift: Reverse string. public mutating func reverse() { let chars: [Character] = reversed() self = String(chars) } /// SwifterSwift: Sliced string from a start index with length. /// /// "Hello World".slicing(from: 6, length: 5) -> "World" /// /// - Parameters: /// - i: string index the slicing should start from. /// - length: amount of characters to be sliced after given index. /// - Returns: sliced substring of length number of characters (if applicable) (example: "Hello World".slicing(from: 6, length: 5) -> "World") public func slicing(from i: Int, length: Int) -> String? { guard length >= 0, i >= 0, i < count else { return nil } guard i.advanced(by: length) <= count else { return self[safe: i..<count] } guard length > 0 else { return "" } return self[safe: i..<i.advanced(by: length)] } /// SwifterSwift: Slice given string from a start index with length (if applicable). /// /// var str = "Hello World" /// str.slice(from: 6, length: 5) /// print(str) // prints "World" /// /// - Parameters: /// - i: string index the slicing should start from. /// - length: amount of characters to be sliced after given index. public mutating func slice(from i: Int, length: Int) { if let str = self.slicing(from: i, length: length) { self = String(str) } } /// SwifterSwift: Slice given string from a start index to an end index (if applicable). /// /// var str = "Hello World" /// str.slice(from: 6, to: 11) /// print(str) // prints "World" /// /// - Parameters: /// - start: string index the slicing should start from. /// - end: string index the slicing should end at. public mutating func slice(from start: Int, to end: Int) { guard end >= start else { return } if let str = self[safe: start..<end] { self = str } } /// SwifterSwift: Slice given string from a start index (if applicable). /// /// var str = "Hello World" /// str.slice(at: 6) /// print(str) // prints "World" /// /// - Parameter i: string index the slicing should start from. public mutating func slice(at i: Int) { guard i < count else { return } if let str = self[safe: i..<count] { self = str } } /// SwifterSwift: Check if string starts with substring. /// /// "hello World".starts(with: "h") -> true /// "hello World".starts(with: "H", caseSensitive: false) -> true /// /// - Parameters: /// - suffix: substring to search if string starts with. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: true if string starts with substring. public func starts(with prefix: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return lowercased().hasPrefix(prefix.lowercased()) } return hasPrefix(prefix) } /// SwifterSwift: Date object from string of date format. /// /// "2017-01-15".date(withFormat: "yyyy-MM-dd") -> Date set to Jan 15, 2017 /// "not date string".date(withFormat: "yyyy-MM-dd") -> nil /// /// - Parameter format: date format. /// - Returns: Date object from string (if applicable). public func date(withFormat format: String) -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.date(from: self) } /// SwifterSwift: Removes spaces and new lines in beginning and end of string. /// /// var str = " \n Hello World \n\n\n" /// str.trim() /// print(str) // prints "Hello World" /// public mutating func trim() { self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } /// SwifterSwift: Truncate string (cut it to a given number of characters). /// /// var str = "This is a very long sentence" /// str.truncate(toLength: 14) /// print(str) // prints "This is a very..." /// /// - Parameters: /// - toLength: maximum number of characters before cutting. /// - trailing: string to add at the end of truncated string (default is "..."). public mutating func truncate(toLength length: Int, trailing: String? = "...") { guard length > 0 else { return } if count > length { self = self[startIndex..<index(startIndex, offsetBy: length)] + (trailing ?? "") } } /// SwifterSwift: Truncated string (limited to a given number of characters). /// /// "This is a very long sentence".truncated(toLength: 14) -> "This is a very..." /// "Short sentence".truncated(toLength: 14) -> "Short sentence" /// /// - Parameters: /// - toLength: maximum number of characters before cutting. /// - trailing: string to add at the end of truncated string. /// - Returns: truncated string (this is an extr...). public func truncated(toLength length: Int, trailing: String? = "...") -> String { guard 1..<count ~= length else { return self } return self[startIndex..<index(startIndex, offsetBy: length)] + (trailing ?? "") } /// SwifterSwift: Convert URL string to readable string. /// /// var str = "it's%20easy%20to%20decode%20strings" /// str.urlDecode() /// print(str) // prints "it's easy to decode strings" /// public mutating func urlDecode() { if let decoded = removingPercentEncoding { self = decoded } } /// SwifterSwift: Escape string. /// /// var str = "it's easy to encode strings" /// str.urlEncode() /// print(str) // prints "it's%20easy%20to%20encode%20strings" /// public mutating func urlEncode() { if let encoded = addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { self = encoded } } /// SwifterSwift: Verify if string matches the regex pattern. /// /// - Parameter pattern: Pattern to verify. /// - Returns: true if string matches the pattern. public func matches(pattern: String) -> Bool { return range(of: pattern, options: String.CompareOptions.regularExpression, range: nil, locale: nil) != nil } /// SwifterSwift: Pad string to fit the length parameter size with another string in the start. /// /// "hue".padStart(10) -> " hue" /// "hue".padStart(10, with: "br") -> "brbrbrbhue" /// /// - Parameter length: The target length to pad. /// - Parameter string: Pad string. Default is " ". public mutating func padStart(_ length: Int, with string: String = " ") { self = paddingStart(length, with: string) } /// SwifterSwift: Returns a string by padding to fit the length parameter size with another string in the start. /// /// "hue".paddingStart(10) -> " hue" /// "hue".paddingStart(10, with: "br") -> "brbrbrbhue" /// /// - Parameter length: The target length to pad. /// - Parameter string: Pad string. Default is " ". /// - Returns: The string with the padding on the start. public func paddingStart(_ length: Int, with string: String = " ") -> String { guard count < length else { return self } let padLength = length - count if padLength < string.count { return string[string.startIndex..<string.index(string.startIndex, offsetBy: padLength)] + self } else { var padding = string while padding.count < padLength { padding.append(string) } return padding[padding.startIndex..<padding.index(padding.startIndex, offsetBy: padLength)] + self } } /// SwifterSwift: Pad string to fit the length parameter size with another string in the start. /// /// "hue".padEnd(10) -> "hue " /// "hue".padEnd(10, with: "br") -> "huebrbrbrb" /// /// - Parameter length: The target length to pad. /// - Parameter string: Pad string. Default is " ". public mutating func padEnd(_ length: Int, with string: String = " ") { self = paddingEnd(length, with: string) } /// SwifterSwift: Returns a string by padding to fit the length parameter size with another string in the end. /// /// "hue".paddingEnd(10) -> "hue " /// "hue".paddingEnd(10, with: "br") -> "huebrbrbrb" /// /// - Parameter length: The target length to pad. /// - Parameter string: Pad string. Default is " ". /// - Returns: The string with the padding on the end. public func paddingEnd(_ length: Int, with string: String = " ") -> String { guard count < length else { return self } let padLength = length - count if padLength < string.count { return self + string[string.startIndex..<string.index(string.startIndex, offsetBy: padLength)] } else { var padding = string while padding.count < padLength { padding.append(string) } return self + padding[padding.startIndex..<padding.index(padding.startIndex, offsetBy: padLength)] } } } // MARK: - Operators public extension String { /// SwifterSwift: Repeat string multiple times. /// /// 'bar' * 3 -> "barbarbar" /// /// - Parameters: /// - lhs: string to repeat. /// - rhs: number of times to repeat character. /// - Returns: new string with given string repeated n times. public static func * (lhs: String, rhs: Int) -> String { guard rhs > 0 else { return "" } return String(repeating: lhs, count: rhs) } /// SwifterSwift: Repeat string multiple times. /// /// 3 * 'bar' -> "barbarbar" /// /// - Parameters: /// - lhs: number of times to repeat character. /// - rhs: string to repeat. /// - Returns: new string with given string repeated n times. public static func * (lhs: Int, rhs: String) -> String { guard lhs > 0 else { return "" } return String(repeating: rhs, count: lhs) } } // MARK: - Initializers public extension String { /// SwifterSwift: Create a new string from a base64 string (if applicable). /// /// String(base64: "SGVsbG8gV29ybGQh") = "Hello World!" /// String(base64: "hello") = nil /// /// - Parameter base64: base64 string. public init?(base64: String) { guard let str = base64.base64Decoded else { return nil } self.init(str) } /// SwifterSwift: Create a new random string of given length. /// /// String(randomOfLength: 10) -> "gY8r3MHvlQ" /// /// - Parameter length: number of characters in string. public init(randomOfLength length: Int) { self = String.random(ofLength: length) } } // MARK: - NSAttributedString extensions public extension String { #if !os(tvOS) && !os(watchOS) /// SwifterSwift: Bold string. public var bold: NSAttributedString { #if os(macOS) return NSMutableAttributedString(string: self, attributes: [.font: NSFont.boldSystemFont(ofSize: NSFont.systemFontSize)]) #else return NSMutableAttributedString(string: self, attributes: [.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)]) #endif } #endif /// SwifterSwift: Underlined string public var underline: NSAttributedString { return NSAttributedString(string: self, attributes: [.underlineStyle: NSUnderlineStyle.styleSingle.rawValue]) } /// SwifterSwift: Strikethrough string. public var strikethrough: NSAttributedString { return NSAttributedString(string: self, attributes: [.strikethroughStyle: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int)]) } #if os(iOS) /// SwifterSwift: Italic string. public var italic: NSAttributedString { return NSMutableAttributedString(string: self, attributes: [.font: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)]) } #endif #if os(macOS) /// SwifterSwift: Add color to string. /// /// - Parameter color: text color. /// - Returns: a NSAttributedString versions of string colored with given color. public func colored(with color: NSColor) -> NSAttributedString { return NSMutableAttributedString(string: self, attributes: [.foregroundColor: color]) } #else /// SwifterSwift: Add color to string. /// /// - Parameter color: text color. /// - Returns: a NSAttributedString versions of string colored with given color. public func colored(with color: UIColor) -> NSAttributedString { return NSMutableAttributedString(string: self, attributes: [.foregroundColor: color]) } #endif } // MARK: - NSString extensions public extension String { /// SwifterSwift: NSString from a string. public var nsString: NSString { return NSString(string: self) } /// SwifterSwift: NSString lastPathComponent. public var lastPathComponent: String { return (self as NSString).lastPathComponent } /// SwifterSwift: NSString pathExtension. public var pathExtension: String { return (self as NSString).pathExtension } /// SwifterSwift: NSString deletingLastPathComponent. public var deletingLastPathComponent: String { return (self as NSString).deletingLastPathComponent } /// SwifterSwift: NSString deletingPathExtension. public var deletingPathExtension: String { return (self as NSString).deletingPathExtension } /// SwifterSwift: NSString pathComponents. public var pathComponents: [String] { return (self as NSString).pathComponents } /// SwifterSwift: NSString appendingPathComponent(str: String) /// /// - Parameter str: the path component to append to the receiver. /// - Returns: a new string made by appending aString to the receiver, preceded if necessary by a path separator. public func appendingPathComponent(_ str: String) -> String { return (self as NSString).appendingPathComponent(str) } /// SwifterSwift: NSString appendingPathExtension(str: String) /// /// - Parameter str: The extension to append to the receiver. /// - Returns: a new string made by appending to the receiver an extension separator followed by ext (if applicable). public func appendingPathExtension(_ str: String) -> String? { return (self as NSString).appendingPathExtension(str) } }
mit
00f1e7fa67c51298916febf72698eb23
31.548134
447
0.668347
3.60348
false
false
false
false
hammond756/Shifty
Shifty/Shifty/SelectRequestsViewController.swift
1
5380
// // SelectRequestsViewController.swift // Shifty // // Created by Aron Hammond on 16/06/15. // Copyright (c) 2015 Aron Hammond. All rights reserved. // // To make requests on the GezochtView, user's have to select one or more dates // from a UITableView. The table view only shows dates that are not yet requested // by the current user and on which he/she does not yet work. import UIKit import SwiftDate import Parse // extension to have NSDate conform to HasDate (duh..) extension NSDate: HasDate { func getWeekOfYear() -> String { return "Week " + String(self.weekOfYear) } var date: NSDate { get { return self } } } class SelectRequestsViewController: ContentViewController { var sectionedDates = [[NSDate]]() var selectedDates = [NSDate]() override func viewDidLoad() { setActivityViewActive(true) showOptionsForCurrentUser() super.viewDidLoad() } // create Requests objects in parse (from selected dates) and pop viewcontroller @IBAction func finishedSelecting(sender: UIBarButtonItem) { for (i,date) in selectedDates.enumerate() { let request = PFObject(className: ParseClass.requests) request[ParseKey.date] = date request[ParseKey.requestedBy] = PFUser.currentUser() request.saveInBackgroundWithBlock() { (succes: Bool, error: NSError?) -> Void in if error != nil { print(error?.description) } else if succes && i == self.selectedDates.count - 1 { self.navigationController?.popViewControllerAnimated(true) } } } } // get requests made by current user func getUserRequests(callback: [NSDate] -> Void) { var previousRequests = [NSDate]() let query = PFQuery(className: ParseClass.requests) query.whereKey(ParseKey.requestedBy, equalTo: PFUser.currentUser()!) query.findObjectsInBackgroundWithBlock() { (objects: [AnyObject]?, error: NSError?) -> Void in if let requests = self.helper.returnObjectAfterErrorCheck(objects, error: error) as? [PFObject] { for request in requests { let date = request[ParseKey.date] as! NSDate previousRequests.append(date) } callback(previousRequests) } } } // check for Constant.amountOfDaysToGenerate days if it is relevant for the user to request func getPossibleDates(previousRequests: [NSDate], callback: (possibleDates: [NSDate]) -> Void) { let today = NSDate() var possibleDates = [NSDate]() let alreadySubmitted = previousRequests.map() { String($0.day) + String($0.month) } for days in 0..<Constant.amountOfDaysToGenerate { let date = today + days.day helper.checkIfDateIsTaken(date) { taken -> Void in let check = String(date.day) + String(date.month) if !taken && !alreadySubmitted.contains(check) { possibleDates.append(date) } if days == Constant.amountOfDaysToGenerate - 1 { callback(possibleDates: possibleDates) } } } } // call getUserRuests, feed result into getPossibleDates, section dates and dispaly func showOptionsForCurrentUser() { getUserRequests() { dates -> Void in self.getPossibleDates(dates) { possibleDates -> Void in self.sectionsInTable = self.helper.getSections(possibleDates) self.sectionedDates = self.helper.splitIntoSections(possibleDates, sections: self.sectionsInTable) self.tableView.reloadData() self.setActivityViewActive(false) } } } } extension SelectRequestsViewController: UITableViewDataSource { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sectionedDates[section].count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) as UITableViewCell let dateForCell = sectionedDates[indexPath.section][indexPath.row] cell.textLabel?.text = dateForCell.toString(format: DateFormat.Custom("EEEE dd MMM")) cell.selectionStyle = .Default return cell } } extension SelectRequestsViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedDate = sectionedDates[indexPath.section][indexPath.row] selectedDates.append(selectedDate) } func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { let deselectedDate = sectionedDates[indexPath.section][indexPath.row] if let index = selectedDates.indexOf(deselectedDate) { selectedDates.removeAtIndex(index) } } }
mit
52db3364be41b7a8d6fa03180ac6e410
33.716129
116
0.616914
5.042174
false
false
false
false
rsyncOSX/RsyncOSX
RsyncOSX/OutputfromProcessRsync.swift
1
574
// // OutputProcessRsync.swift // RsyncOSX // // Created by Thomas Evensen on 10/05/2020. // Copyright © 2020 Thomas Evensen. All rights reserved. // import Foundation final class OutputfromProcessRsync: OutputfromProcess { override func addlinefromoutput(str: String) { if startindex == nil { startindex = 0 } else { startindex = output?.count ?? 0 + 1 } str.enumerateLines { line, _ in guard line.hasSuffix("/") == false else { return } self.output?.append(line) } } }
mit
d94a1bf4e62903ebbc932b3aa99720fb
23.913043
62
0.589878
4.006993
false
false
false
false
apple/swift
test/Index/roles.swift
1
27838
// RUN: %empty-directory(%t) // // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/imported_swift_module.swift // RUN: %target-swift-ide-test -print-indexed-symbols -source-filename %s -I %t | %FileCheck %s import func imported_swift_module.importedFunc // CHECK: [[@LINE-1]]:35 | function/Swift | importedFunc() | s:21imported_swift_module0A4FuncyyF | Ref | rel: 0 import var imported_swift_module.importedGlobal // CHECK: [[@LINE-1]]:34 | variable/Swift | importedGlobal | s:21imported_swift_module0A6GlobalSivp | Ref | rel: 0 // Definition let x = 2 // CHECK: [[@LINE-1]]:5 | variable/Swift | x | s:14swift_ide_test1xSivp | Def | rel: 0 // Definition + Read of x var y = x + 1 // CHECK: [[@LINE-1]]:5 | variable/Swift | y | s:14swift_ide_test1ySivp | Def | rel: 0 // CHECK: [[@LINE-2]]:9 | variable/Swift | x | s:14swift_ide_test1xSivp | Ref,Read,RelCont | rel: 1 // CHECK: [[@LINE-3]]:11 | static-method/infix-operator/Swift | +(_:_:) | s:Si1poiyS2i_SitFZ | Ref,Call,RelCont | rel: 1 // CHECK-NEXT: RelCont | variable/Swift | y | s:14swift_ide_test1ySivp // Read of x + Write of y y = x + 1 // CHECK: [[@LINE-1]]:1 | variable/Swift | y | s:14swift_ide_test1ySivp | Ref,Writ | rel: 0 // CHECK: [[@LINE-2]]:5 | variable/Swift | x | s:14swift_ide_test1xSivp | Ref,Read | rel: 0 // CHECK: [[@LINE-3]]:7 | static-method/infix-operator/Swift | +(_:_:) | s:Si1poiyS2i_SitFZ | Ref,Call | rel: 0 // Read of y + Write of y y += x // CHECK: [[@LINE-1]]:1 | variable/Swift | y | s:14swift_ide_test1ySivp | Ref,Read,Writ | rel: 0 // CHECK: [[@LINE-2]]:3 | static-method/infix-operator/Swift | +=(_:_:) | s:Si2peoiyySiz_SitFZ | Ref,Call | rel: 0 // CHECK: [[@LINE-3]]:6 | variable/Swift | x | s:14swift_ide_test1xSivp | Ref,Read | rel: 0 var z: Int { // CHECK: [[@LINE-1]]:5 | variable/Swift | z | s:14swift_ide_test1zSivp | Def | rel: 0 get { // CHECK: [[@LINE-1]]:3 | function/acc-get/Swift | getter:z | s:14swift_ide_test1zSivg | Def,RelChild,RelAcc | rel: 1 return y // CHECK: [[@LINE-1]]:12 | variable/Swift | y | s:14swift_ide_test1ySivp | Ref,Read,RelCont | rel: 1 // CHECK-NEXT: RelCont | function/acc-get/Swift | getter:z | s:14swift_ide_test1zSivg } set { // CHECK: [[@LINE-1]]:3 | function/acc-set/Swift | setter:z | s:14swift_ide_test1zSivs | Def,RelChild,RelAcc | rel: 1 y = newValue // CHECK: [[@LINE-1]]:5 | variable/Swift | y | s:14swift_ide_test1ySivp | Ref,Writ,RelCont | rel: 1 // CHECK-NEXT: RelCont | function/acc-set/Swift | setter:z | s:14swift_ide_test1zSivs } } // Write + Read of z z = z + 1 // CHECK: [[@LINE-1]]:1 | variable/Swift | z | s:14swift_ide_test1zSivp | Ref,Writ | rel: 0 // CHECK: [[@LINE-2]]:1 | function/acc-set/Swift | setter:z | s:14swift_ide_test1zSivs | Ref,Call,Impl | rel: 0 // CHECK: [[@LINE-3]]:5 | variable/Swift | z | s:14swift_ide_test1zSivp | Ref,Read | rel: 0 // CHECK: [[@LINE-4]]:5 | function/acc-get/Swift | getter:z | s:14swift_ide_test1zSivg | Ref,Call,Impl | rel: 0 // Call func aCalledFunction(a: Int, b: inout Int) { // CHECK: [[@LINE-1]]:6 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Def | rel: 0 // CHECK: [[@LINE-2]]:22 | param/Swift | a | s:{{.*}} | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF // CHECK: [[@LINE-4]]:30 | param/Swift | b | s:{{.*}} | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF var _ = a + b // CHECK: [[@LINE-1]]:11 | param/Swift | a | s:{{.*}} | Ref,Read,RelCont | rel: 1 // CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF // CHECK: [[@LINE-3]]:15 | param/Swift | b | s:{{.*}} | Ref,Read,RelCont | rel: 1 // CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF b = a + 1 // CHECK: [[@LINE-1]]:3 | param/Swift | b | s:{{.*}} | Ref,Writ,RelCont | rel: 1 // CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF // CHECK: [[@LINE-3]]:7 | param/Swift | a | s:{{.*}} | Ref,Read,RelCont | rel: 1 // CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF _ = { ignored in ignored + 1} // CHECK-NOT: [[@LINE-1]]:9 {{.*}} | ignored | {{.*}} } aCalledFunction(a: 1, b: &z) // CHECK: [[@LINE-1]]:1 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Ref,Call | rel: 0 // CHECK: [[@LINE-2]]:27 | variable/Swift | z | s:14swift_ide_test1zSivp | Ref,Read,Writ | rel: 0 func aCaller() { // CHECK: [[@LINE-1]]:6 | function/Swift | aCaller() | s:14swift_ide_test7aCalleryyF | Def | rel: 0 aCalledFunction(a: 1, b: &z) // CHECK: [[@LINE-1]]:3 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Ref,Call,RelCall,RelCont | rel: 1 // CHECK-NEXT: RelCall,RelCont | function/Swift | aCaller() | s:14swift_ide_test7aCalleryyF } let aRef = aCalledFunction // CHECK: [[@LINE-1]]:12 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Ref,RelCont | rel: 1 // RelationChildOf, Implicit struct AStruct { // CHECK: [[@LINE-1]]:8 | struct/Swift | AStruct | [[AStruct_USR:.*]] | Def | rel: 0 let y: Int = 2 // CHECK: [[@LINE-1]]:7 | instance-property/Swift | y | [[AStruct_y_USR:.*]] | Def,RelChild | rel: 1 var x: Int // CHECK: [[@LINE-1]]:7 | instance-property/Swift | x | [[AStruct_x_USR:.*]] | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | struct/Swift | AStruct | [[AStruct_USR]] mutating func aMethod() { // CHECK: [[@LINE-1]]:17 | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | struct/Swift | AStruct | [[AStruct_USR]] x += 1 // CHECK: [[@LINE-1]]:5 | instance-property/Swift | x | [[AStruct_x_USR]] | Ref,Read,Writ,RelCont | rel: 1 // CHECK-NEXT: RelCont | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF // CHECK: [[@LINE-3]]:5 | instance-method/acc-get/Swift | getter:x | s:14swift_ide_test7AStructV1xSivg | Ref,Call,Impl,RelCall,RelCont | rel: 1 // CHECK-NEXT: RelCall,RelCont | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF // CHECK: [[@LINE-5]]:5 | instance-method/acc-set/Swift | setter:x | s:14swift_ide_test7AStructV1xSivs | Ref,Call,Impl,RelCall,RelCont | rel: 1 // CHECK-NEXT: RelCall,RelCont | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF // CHECK: [[@LINE-7]]:7 | static-method/infix-operator/Swift | +=(_:_:) | s:Si2peoiyySiz_SitFZ | Ref,Call,RelCall,RelCont | rel: 1 // CHECK-NEXT: RelCall,RelCont | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF } // RelationChildOf, RelationAccessorOf subscript(index: Int) -> Int { // CHECK: [[@LINE-1]]:3 | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | struct/Swift | AStruct | [[AStruct_USR]] get { // CHECK: [[@LINE-1]]:5 | instance-method/acc-get/Swift | getter:subscript(_:) | s:14swift_ide_test7AStructVyS2icig | Def,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip return x } set { // CHECK: [[@LINE-1]]:5 | instance-method/acc-set/Swift | setter:subscript(_:) | s:14swift_ide_test7AStructVyS2icis | Def,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2ici x = newValue } } } class AClass { // CHECK: [[@LINE-1]]:7 | class/Swift | AClass | [[AClass_USR:.*]] | Def | rel: 0 var y: AStruct // CHECK: [[@LINE-1]]:7 | instance-property/Swift | y | [[AClass_y_USR:.*]] | Def,RelChild | rel: 1 // CHECK: [[@LINE-2]]:7 | instance-method/acc-get/Swift | getter:y | [[AClass_y_get_USR:.*]] | Def,Dyn,Impl,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | instance-property/Swift | y | [[AClass_y_USR]] // CHECK: [[@LINE-4]]:7 | instance-method/acc-set/Swift | setter:y | [[AClass_y_set_USR:.*]] | Def,Dyn,Impl,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | instance-property/Swift | y | [[AClass_y_USR]] var z: [Int] var computed_p: Int { return 0 } // CHECK: [[@LINE-1]]:7 | instance-property/Swift | computed_p | [[AClass_computed_p_USR:.*]] | Def,RelChild | rel: 1 // CHECK: [[@LINE-2]]:23 | instance-method/acc-get/Swift | getter:computed_p | [[AClass_computed_p_get_USR:.*]] | Def,Dyn,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | instance-property/Swift | computed_p | [[AClass_computed_p_USR]] // CHECK-NOT: acc-set/Swift | setter:computed_p | init(x: Int) { y = AStruct(x: x) // CHECK: [[@LINE-1]]:17 | instance-property/Swift | x | [[AStruct_x_USR]] | Ref,RelCont | rel: 1 // CHECK: [[@LINE-2]]:9 | struct/Swift | AStruct | [[AStruct_USR]] | Ref,RelCont | rel: 1 self.z = [1, 2, 3] } subscript(index: Int) -> Int { // CHECK: [[@LINE-1]]:3 | instance-property/subscript/Swift | subscript(_:) | [[AClass_subscript_USR:.*]] | Def,RelChild | rel: 1 get { return z[0] } // CHECK: [[@LINE-1]]:5 | instance-method/acc-get/Swift | getter:subscript(_:) | [[AClass_subscript_get_USR:.*]] | Def,Dyn,RelChild,RelAcc | rel: 1 set { z[0] = newValue } // CHECK: [[@LINE-1]]:5 | instance-method/acc-set/Swift | setter:subscript(_:) | [[AClass_subscript_set_USR:.*]] | Def,Dyn,RelChild,RelAcc | rel: 1 } func foo() -> Int { return z[0] } // CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo() | [[AClass_foo_USR:.*]] | Def,Dyn,RelChild | rel: 1 } let _ = AClass.foo // CHECK: [[@LINE-1]]:16 | instance-method/Swift | foo() | [[AClass_foo_USR]] | Ref | rel: 0 let _ = AClass(x: 1).foo // CHECK: [[@LINE-1]]:22 | instance-method/Swift | foo() | [[AClass_foo_USR]] | Ref | rel: 0 let _ = AClass(x: 1)[1] // CHECK: [[@LINE-1]]:21 | instance-property/subscript/Swift | subscript(_:) | [[AClass_subscript_USR]] | Ref,Read,Dyn,RelRec | rel: 1 // CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]] // CHECK: [[@LINE-3]]:21 | instance-method/acc-get/Swift | getter:subscript(_:) | [[AClass_subscript_get_USR]] | Ref,Call,Dyn,Impl,RelRec | rel: 1 // CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]] let _ = AClass(x: 1)[1] = 2 // CHECK: [[@LINE-1]]:21 | instance-property/subscript/Swift | subscript(_:) | [[AClass_subscript_USR]] | Ref,Writ,Dyn,RelRec | rel: 1 // CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]] // CHECK: [[@LINE-3]]:21 | instance-method/acc-set/Swift | setter:subscript(_:) | [[AClass_subscript_set_USR]] | Ref,Call,Dyn,Impl,RelRec | rel: 1 // CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]] extension AClass { func test_property_refs1() -> AStruct { // CHECK: [[@LINE-1]]:8 | instance-method/Swift | test_property_refs1() | [[test_property_refs1_USR:.*]] | Def,Dyn,RelChild | rel: 1 _ = y // CHECK: [[@LINE-1]]:9 | instance-property/Swift | y | [[AClass_y_USR]] | Ref,Read,Dyn,RelRec,RelCont | rel: 2 // CHECK-NEXT: RelCont | instance-method/Swift | test_property_refs1() | [[test_property_refs1_USR]] // CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]] // CHECK: [[@LINE-4]]:9 | instance-method/acc-get/Swift | getter:y | [[AClass_y_get_USR]] | Ref,Call,Dyn,Impl,RelRec,RelCall,RelCont | rel: 2 // CHECK-NEXT: RelCall,RelCont | instance-method/Swift | test_property_refs1() | [[test_property_refs1_USR]] // CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]] return y // CHECK: [[@LINE-1]]:12 | instance-property/Swift | y | [[AClass_y_USR]] | Ref,Read,Dyn,RelRec,RelCont | rel: 2 // CHECK-NEXT: RelCont | instance-method/Swift | test_property_refs1() | [[test_property_refs1_USR]] // CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]] // CHECK: [[@LINE-4]]:12 | instance-method/acc-get/Swift | getter:y | [[AClass_y_get_USR]] | Ref,Call,Dyn,Impl,RelRec,RelCall,RelCont | rel: 2 // CHECK-NEXT: RelCall,RelCont | instance-method/Swift | test_property_refs1() | [[test_property_refs1_USR]] // CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]] } func test_property_refs2() -> Int { // CHECK: [[@LINE-1]]:8 | instance-method/Swift | test_property_refs2() | [[test_property_refs2_USR:.*]] | Def,Dyn,RelChild | rel: 1 _ = computed_p // CHECK: [[@LINE-1]]:9 | instance-property/Swift | computed_p | [[AClass_computed_p_USR]] | Ref,Read,Dyn,RelRec,RelCont | rel: 2 // CHECK-NEXT: RelCont | instance-method/Swift | test_property_refs2() | [[test_property_refs2_USR]] // CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]] // CHECK: [[@LINE-4]]:9 | instance-method/acc-get/Swift | getter:computed_p | [[AClass_computed_p_get_USR]] | Ref,Call,Dyn,Impl,RelRec,RelCall,RelCont | rel: 2 // CHECK-NEXT: RelCall,RelCont | instance-method/Swift | test_property_refs2() | [[test_property_refs2_USR]] // CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]] return computed_p // CHECK: [[@LINE-1]]:12 | instance-property/Swift | computed_p | [[AClass_computed_p_USR]] | Ref,Read,Dyn,RelRec,RelCont | rel: 2 // CHECK-NEXT: RelCont | instance-method/Swift | test_property_refs2() | [[test_property_refs2_USR]] // CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]] // CHECK: [[@LINE-4]]:12 | instance-method/acc-get/Swift | getter:computed_p | [[AClass_computed_p_get_USR]] | Ref,Call,Dyn,Impl,RelRec,RelCall,RelCont | rel: 2 // CHECK-NEXT: RelCall,RelCont | instance-method/Swift | test_property_refs2() | [[test_property_refs2_USR]] // CHECK-NEXT: RelRec | class/Swift | AClass | [[AClass_USR]] } } // RelationBaseOf, RelationOverrideOf protocol X { // CHECK: [[@LINE-1]]:10 | protocol/Swift | X | [[X_USR:.*]] | Def | rel: 0 var reqProp: Int { get } // CHECK: [[@LINE-1]]:7 | instance-property/Swift | reqProp | [[reqProp_USR:.*]] | Def,RelChild | rel: 1 // CHECK: [[@LINE-2]]:22 | instance-method/acc-get/Swift | getter:reqProp | {{.*}} | Def,Dyn,RelChild,RelAcc | rel: 1 // CHECK-NEXT: RelChild,RelAcc | instance-property/Swift | reqProp | [[reqProp_USR]] } protocol Y {} // CHECK: [[@LINE-1]]:10 | protocol/Swift | Y | [[Y_USR:.*]] | Def | rel: 0 class ImplementsX : X, Y { // CHECK: [[@LINE-1]]:7 | class/Swift | ImplementsX | [[ImplementsX_USR:.*]] | Def | rel: 0 // CHECK: [[@LINE-2]]:21 | protocol/Swift | X | [[X_USR]] | Ref,RelBase | rel: 1 // CHECK-NEXT: RelBase | class/Swift | ImplementsX | [[ImplementsX_USR]] var reqProp: Int { return 1 } // CHECK: [[@LINE-1]]:7 | instance-property/Swift | reqProp | [[reqPropImpl_USR:.*]] | Def,RelChild,RelOver | rel: 2 // CHECK-NEXT: RelOver | instance-property/Swift | reqProp | [[reqProp_USR]] // CHECK-NEXT: RelChild | class/Swift | ImplementsX | [[ImplementsX_USR]] } func TestX(x: X) { _ = x.reqProp // CHECK: [[@LINE-1]]:9 | instance-property/Swift | reqProp | [[reqProp_USR]] | Ref,Read,Dyn,RelRec,RelCont | rel: 2 } protocol AProtocol { // CHECK: [[@LINE-1]]:10 | protocol/Swift | AProtocol | [[AProtocol_USR:.*]] | Def | rel: 0 associatedtype T : X where T:Y // CHECK: [[@LINE-1]]:18 | type-alias/associated-type/Swift | T | [[AProtocol_T_USR:.*]] | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | protocol/Swift | AProtocol | [[AProtocol_USR]] // CHECK: [[@LINE-3]]:22 | protocol/Swift | X | [[X_USR]] | Ref | rel: 0 // CHECK: [[@LINE-4]]:30 | type-alias/associated-type/Swift | T | [[AProtocol_T_USR]] | Ref | rel: 0 // CHECK: [[@LINE-5]]:32 | protocol/Swift | Y | [[Y_USR]] | Ref | rel: 0 func foo() -> Int // CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo() | s:14swift_ide_test9AProtocolP3fooSiyF | Def,Dyn,RelChild | rel: 1 // CHECK-NEXT: RelChild | protocol/Swift | AProtocol | s:14swift_ide_test9AProtocolP } protocol QBase { associatedtype A } protocol Q : QBase where Self.A: AProtocol {} // CHECK: [[@LINE-1]]:34 | protocol/Swift | AProtocol | [[AProtocol_USR]] | Ref | rel: 0 class ASubClass : AClass, AProtocol { // CHECK: [[@LINE-1]]:7 | class/Swift | ASubClass | s:14swift_ide_test9ASubClassC | Def | rel: 0 // CHECK: [[@LINE-2]]:19 | class/Swift | AClass | s:14swift_ide_test6AClassC | Ref,RelBase | rel: 1 // CHECK-NEXT: RelBase | class/Swift | ASubClass | s:14swift_ide_test9ASubClassC // CHECK: [[@LINE-4]]:27 | protocol/Swift | AProtocol | s:14swift_ide_test9AProtocolP | Ref,RelBase | rel: 1 // CHECK-NEXT: RelBase | class/Swift | ASubClass | s:14swift_ide_test9ASubClassC typealias T = ImplementsX override func foo() -> Int { // CHECK: [[@LINE-1]]:17 | instance-method/Swift | foo() | s:14swift_ide_test9ASubClassC3fooSiyF | Def,Dyn,RelChild,RelOver | rel: 3 // CHECK-NEXT: RelOver | instance-method/Swift | foo() | [[AClass_foo_USR]] // CHECK-NEXT: RelOver | instance-method/Swift | foo() | s:14swift_ide_test9AProtocolP3fooSiyF // CHECK-NEXT: RelChild | class/Swift | ASubClass | s:14swift_ide_test9ASubClassC return 1 } } // RelationExtendedBy extension AClass { // CHECK: [[@LINE-1]]:11 | extension/ext-class/Swift | AClass | [[EXT_ACLASS_USR:.*]] | Def | rel: 0 // CHECK: [[@LINE-2]]:11 | class/Swift | AClass | s:14swift_ide_test6AClassC | Ref,RelExt | rel: 1 // CHECK-NEXT: RelExt | extension/ext-class/Swift | AClass | [[EXT_ACLASS_USR]] func bar() -> Int { return 2 } // CHECK: [[@LINE-1]]:8 | instance-method/Swift | bar() | s:14swift_ide_test6AClassC3barSiyF | Def,Dyn,RelChild | rel: 1 // CHECK-NEXT: RelChild | extension/ext-class/Swift | AClass | [[EXT_ACLASS_USR]] } struct OuterS { // CHECK: [[@LINE-1]]:8 | struct/Swift | OuterS | [[OUTERS_USR:.*]] | Def | rel: 0 struct InnerS {} // CHECK: [[@LINE-1]]:10 | struct/Swift | InnerS | [[INNERS_USR:.*]] | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | struct/Swift | OuterS | [[OUTERS_USR]] } extension OuterS.InnerS : AProtocol { // CHECK: [[@LINE-1]]:18 | extension/ext-struct/Swift | InnerS | [[EXT_INNERS_USR:.*]] | Def | rel: 0 // CHECK: [[@LINE-2]]:18 | struct/Swift | InnerS | [[INNERS_USR]] | Ref,RelExt | rel: 1 // CHECK-NEXT: RelExt | extension/ext-struct/Swift | InnerS | [[EXT_INNERS_USR]] // CHECK: [[@LINE-4]]:27 | protocol/Swift | AProtocol | [[AProtocol_USR]] | Ref,RelBase | rel: 1 // CHECK-NEXT: RelBase | extension/ext-struct/Swift | InnerS | [[EXT_INNERS_USR]] // CHECK: [[@LINE-6]]:11 | struct/Swift | OuterS | [[OUTERS_USR]] | Ref | rel: 0 typealias T = ImplementsX func foo() -> Int { return 1 } } protocol ExtendMe {} protocol Whatever {} // CHECK: [[@LINE-1]]:10 | protocol/Swift | Whatever | [[Whatever_USR:.*]] | Def | rel: 0 extension ExtendMe where Self: Whatever {} // CHECK: [[@LINE-1]]:32 | protocol/Swift | Whatever | [[Whatever_USR]] | Ref | rel: 0 var anInstance = AClass(x: 1) // CHECK: [[@LINE-1]]:18 | class/Swift | AClass | s:14swift_ide_test6AClassC | Ref,RelCont | rel: 1 // CHECK: [[@LINE-2]]:18 | constructor/Swift | init(x:) | s:14swift_ide_test6AClassC1xACSi_tcfc | Ref,Call,RelCont | rel: 1 anInstance.y.x = anInstance.y.x // CHECK: [[@LINE-1]]:1 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:12 | instance-property/Swift | y | [[AClass_y_USR]] | Ref,Read,Writ,Dyn,RelRec | rel: 1 // CHECK: [[@LINE-3]]:14 | instance-property/Swift | x | [[AStruct_x_USR]] | Ref,Writ | rel: 0 // CHECK: [[@LINE-4]]:18 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0 // CHECK: [[@LINE-5]]:29 | instance-property/Swift | y | [[AClass_y_USR]] | Ref,Read,Dyn,RelRec | rel: 1 // CHECK: [[@LINE-6]]:31 | instance-property/Swift | x | [[AStruct_x_USR]] | Ref,Read | rel: 0 anInstance.y.aMethod() // CHECK: [[@LINE-1]]:1 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:12 | instance-property/Swift | y | [[AClass_y_USR]] | Ref,Read,Writ,Dyn,RelRec | rel: 1 // CHECK: [[@LINE-3]]:14 | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF | Ref,Call | rel: 0 // FIXME Write role of z occurrence on the RHS? anInstance.z[1] = anInstance.z[0] // CHECK: [[@LINE-1]]:1 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:12 | instance-property/Swift | z | s:14swift_ide_test6AClassC1zSaySiGvp | Ref,Read,Writ,Dyn,RelRec | rel: 1 // CHECK: [[@LINE-3]]:19 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0 // CHECK: [[@LINE-4]]:30 | instance-property/Swift | z | s:14swift_ide_test6AClassC1zSaySiGvp | Ref,Read,Writ,Dyn,RelRec | rel: 1 let otherInstance = AStruct(x: 1) // CHECK: [[@LINE-1]]:29 | instance-property/Swift | x | [[AStruct_x_USR]] | Ref,RelCont | rel: 1 // CHECK: [[@LINE-2]]:21 | struct/Swift | AStruct | [[AStruct_USR]] | Ref,RelCont | rel: 1 _ = AStruct.init(x:) // CHECK: [[@LINE-1]]:18 | instance-property/Swift | x | [[AStruct_x_USR]] | Ref | rel: 0 // CHECK: [[@LINE-2]]:5 | struct/Swift | AStruct | [[AStruct_USR]] | Ref | rel: 0 let _ = otherInstance[0] // CHECK: [[@LINE-1]]:9 | variable/Swift | otherInstance | s:14swift_ide_test13otherInstanceAA7AStructVvp | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:22 | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip | Ref,Read | rel: 0 let _ = anInstance[0] // CHECK: [[@LINE-1]]:9 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:19 | instance-property/subscript/Swift | subscript(_:) | [[AClass_subscript_USR]] | Ref,Read,Dyn,RelRec | rel: 1 let aSubInstance: AClass = ASubClass(x: 1) // CHECK: [[@LINE-1]]:5 | variable/Swift | aSubInstance | s:14swift_ide_test12aSubInstanceAA6AClassCvp | Def | rel: 0 // CHECK: [[@LINE-2]]:28 | class/Swift | ASubClass | s:14swift_ide_test9ASubClassC | Ref,RelCont | rel: 1 // Dynamic, RelationReceivedBy let _ = aSubInstance.foo() // CHECK: [[@LINE-1]]:9 | variable/Swift | aSubInstance | s:14swift_ide_test12aSubInstanceAA6AClassCvp | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:22 | instance-method/Swift | foo() | [[AClass_foo_USR]] | Ref,Call,Dyn,RelRec | rel: 1 // CHECK-NEXT: RelRec | class/Swift | AClass | s:14swift_ide_test6AClassC // RelationContainedBy let contained = 2 // CHECK: [[@LINE-1]]:5 | variable/Swift | contained | s:14swift_ide_test9containedSivp | Def | rel: 0 protocol ProtRoot { func fooCommon() func foo1() func foo2() func foo3(a : Int) func foo3(a : String) } protocol ProtDerived : ProtRoot { func fooCommon() // CHECK: [[@LINE-1]]:8 | instance-method/Swift | fooCommon() | s:14swift_ide_test11ProtDerivedP9fooCommonyyF | Def,Dyn,RelChild,RelOver | rel: 2 func bar1() func bar2() func bar3(_ : Int) func bar3(_ : String) } extension ProtDerived { func fooCommon() {} // CHECK: [[@LINE-1]]:8 | instance-method/Swift | fooCommon() | s:14swift_ide_test11ProtDerivedPAAE9fooCommonyyF | Def,Dyn,RelChild,RelOver | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | fooCommon() | s:14swift_ide_test11ProtDerivedP9fooCommonyyF func foo1() {} // CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo1() | s:14swift_ide_test11ProtDerivedPAAE4foo1yyF | Def,Dyn,RelChild,RelOver | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | foo1() | s:14swift_ide_test8ProtRootP4foo1yyF func bar1() {} // CHECK: [[@LINE-1]]:8 | instance-method/Swift | bar1() | s:14swift_ide_test11ProtDerivedPAAE4bar1yyF | Def,Dyn,RelChild,RelOver | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | bar1() | s:14swift_ide_test11ProtDerivedP4bar1yyF func foo3(a : Int) {} // CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo3(a:) | s:14swift_ide_test11ProtDerivedPAAE4foo31aySi_tF | Def,Dyn,RelChild,RelOver | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | foo3(a:) | s:14swift_ide_test8ProtRootP4foo31aySi_tF func foo3(a : String) {} // CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo3(a:) | s:14swift_ide_test11ProtDerivedPAAE4foo31aySS_tF | Def,Dyn,RelChild,RelOver | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | foo3(a:) | s:14swift_ide_test8ProtRootP4foo31aySS_tF func bar3(_ : Int) {} // CHECK: [[@LINE-1]]:8 | instance-method/Swift | bar3(_:) | s:14swift_ide_test11ProtDerivedPAAE4bar3yySiF | Def,Dyn,RelChild,RelOver | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | bar3(_:) | s:14swift_ide_test11ProtDerivedP4bar3yySiF } enum MyEnum { init() {} func enum_func() {} // CHECK: [[@LINE-1]]:8 | instance-method/Swift | enum_func() | [[MyEnum_enum_func_USR:.*]] | Def,RelChild | rel: 1 } MyEnum().enum_func() // CHECK: [[@LINE-1]]:10 | instance-method/Swift | enum_func() | [[MyEnum_enum_func_USR]] | Ref,Call | rel: 0 class ClassWithFinals { final var prop : Int { get { return 0} } // CHECK: [[@LINE-1]]:26 | instance-method/acc-get/Swift | {{.*}} | Def,RelChild,RelAcc | rel: 1 final var prop2 = 0 // CHECK: [[@LINE-1]]:13 | instance-method/acc-get/Swift | {{.*}} | Def,Impl,RelChild,RelAcc | rel: 1 // CHECK: [[@LINE-2]]:13 | instance-method/acc-set/Swift | {{.*}} | Def,Impl,RelChild,RelAcc | rel: 1 final func foo() {} // CHECK: [[@LINE-1]]:14 | instance-method/Swift | {{.*}} | Def,RelChild | rel: 1 } final class FinalClass { var prop : Int { get { return 0} } // CHECK: [[@LINE-1]]:20 | instance-method/acc-get/Swift | {{.*}} | Def,RelChild,RelAcc | rel: 1 var prop2 = 0 // CHECK: [[@LINE-1]]:7 | instance-method/acc-get/Swift | {{.*}} | Def,Impl,RelChild,RelAcc | rel: 1 // CHECK: [[@LINE-2]]:7 | instance-method/acc-set/Swift | {{.*}} | Def,Impl,RelChild,RelAcc | rel: 1 func foo() {} // CHECK: [[@LINE-1]]:8 | instance-method/Swift | {{.*}} | Def,RelChild | rel: 1 } struct StructWithKeypath { var x: Int = 0 subscript(idx: Int) -> Int { get { } set { } } } _ = \StructWithKeypath.x // CHECK: [[@LINE-1]]:24 | instance-property/Swift | x | s:14swift_ide_test17StructWithKeypathV1xSivp | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:24 | instance-method/acc-get/Swift | getter:x | s:14swift_ide_test17StructWithKeypathV1xSivg | Ref,Call,Impl | rel: 0 _ = \StructWithKeypath.[0] // CHECK: [[@LINE-1]]:24 | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test17StructWithKeypathVyS2icip | Ref,Read | rel: 0 // CHECK: [[@LINE-2]]:24 | instance-method/acc-get/Swift | getter:subscript(_:) | s:14swift_ide_test17StructWithKeypathVyS2icig | Ref,Call,Impl | rel: 0 internal protocol FromInt { init(_ uint64: Int) } extension Int: FromInt { } func test<M>(_: M, value: Int?) { if let idType = M.self as? FromInt.Type { _ = value.flatMap(idType.init) as? M // CHECK: [[@LINE-1]]:34 | constructor/Swift | init(_:) | s:14swift_ide_test7FromIntPyxSicfc | Ref,RelCont | rel: 1 } } func `escapedName`(`x`: Int) {} // CHECK: [[@LINE-1]]:6 | function/Swift | escapedName(x:) | {{.*}} | Def | rel: 0 `escapedName`(`x`: 2) // CHECK: [[@LINE-1]]:1 | function/Swift | escapedName(x:) | {{.*}} | Ref,Call | rel: 0 `escapedName`(`x`:) // CHECK: [[@LINE-1]]:1 | function/Swift | escapedName(x:) | {{.*}} | Ref | rel: 0 protocol WithPrimary<Assoc> { // CHECK: [[@LINE-1]]:22 | type-alias/associated-type/Swift | Assoc | {{.*}} | Ref | rel: 0 // CHECK: [[@LINE-2]]:10 | protocol/Swift | WithPrimary | {{.*}} | Def | rel: 0 associatedtype Assoc // CHECK: [[@LINE-1]]:18 | type-alias/associated-type/Swift | Assoc | {{.*}} | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | protocol/Swift | WithPrimary | {{.*}} }
apache-2.0
f88cc5d91209c21b1b63f847af8c748d
54.56487
164
0.643796
2.879098
false
true
false
false
yangchenghu/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Conversation/Cells/AABubbleServiceCell.swift
11
3134
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation // MARK: - class AABubbleServiceCell : AABubbleCell { private static let serviceBubbleFont = UIFont.boldSystemFontOfSize(12) private static let maxServiceTextWidth: CGFloat = 260 private let serviceText = UILabel() private var bindedLayout: ServiceCellLayout! init(frame: CGRect) { super.init(frame: frame, isFullSize: true) // Configuring service label serviceText.font = AABubbleServiceCell.serviceBubbleFont; serviceText.lineBreakMode = .ByWordWrapping; serviceText.numberOfLines = 0; serviceText.textColor = UIColor.whiteColor() serviceText.contentMode = UIViewContentMode.Center serviceText.textAlignment = NSTextAlignment.Center mainView.addSubview(serviceText) // Setting content and bubble insets contentInsets = UIEdgeInsets(top: 3, left: 8, bottom: 3, right: 8) bubbleInsets = UIEdgeInsets(top: 3, left: 0, bottom: 3, right: 0) // Setting bubble background bindBubbleType(.Service, isCompact: false) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func bind(message: ACMessage, reuse: Bool, cellLayout: CellLayout, setting: CellSetting) { self.bindedLayout = cellLayout as! ServiceCellLayout if (!reuse) { serviceText.text = bindedLayout.text } } override func layoutContent(maxWidth: CGFloat, offsetX: CGFloat) { let insets = fullContentInsets let contentWidth = self.contentView.frame.width let serviceWidth = bindedLayout.textSize.width let serviceHeight = bindedLayout.textSize.height serviceText.frame = CGRectMake((contentWidth - serviceWidth) / 2.0, insets.top, serviceWidth, serviceHeight); layoutBubble(serviceWidth, contentHeight: serviceHeight) } } class ServiceCellLayout: CellLayout { var text: String var textSize: CGSize init(text: String, date: Int64) { // Saving text size self.text = text // Measuring text size self.textSize = UIViewMeasure.measureText(text, width: AABubbleServiceCell.maxServiceTextWidth, font: AABubbleServiceCell.serviceBubbleFont) // Creating layout super.init(height: textSize.height + 6, date: date, key: "service") } } class AABubbleServiceCellLayouter: AABubbleLayouter { func isSuitable(message: ACMessage) -> Bool { return message.content is ACServiceContent } func buildLayout(peer: ACPeer, message: ACMessage) -> CellLayout { var serviceText = Actor.getFormatter().formatFullServiceMessageWithSenderId(message.senderId, withContent: message.content as! ACServiceContent) return ServiceCellLayout(text: serviceText, date: Int64(message.date)) } func cellClass() -> AnyClass { return AABubbleServiceCell.self } }
mit
29cc3d3b57a4f32d57e19844e87ff0a6
30.979592
152
0.662731
4.858915
false
false
false
false
1457792186/JWSwift
熊猫TV2/Pods/Kingfisher/Sources/CacheSerializer.swift
128
3729
// // CacheSerializer.swift // Kingfisher // // Created by Wei Wang on 2016/09/02. // // Copyright (c) 2016 Wei Wang <[email protected]> // // 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 /// An `CacheSerializer` would be used to convert some data to an image object for /// retrieving from disk cache and vice versa for storing to disk cache. public protocol CacheSerializer { /// Get the serialized data from a provided image /// and optional original data for caching to disk. /// /// /// - parameter image: The image needed to be serialized. /// - parameter original: The original data which is just downloaded. /// If the image is retrieved from cache instead of /// downloaded, it will be `nil`. /// /// - returns: A data which will be stored to cache, or `nil` when no valid /// data could be serialized. func data(with image: Image, original: Data?) -> Data? /// Get an image deserialized from provided data. /// /// - parameter data: The data from which an image should be deserialized. /// - parameter options: Options for deserialization. /// /// - returns: An image deserialized or `nil` when no valid image /// could be deserialized. func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? } /// `DefaultCacheSerializer` is a basic `CacheSerializer` used in default cache of /// Kingfisher. It could serialize and deserialize PNG, JEPG and GIF images. For /// image other than these formats, a normalized `pngRepresentation` will be used. public struct DefaultCacheSerializer: CacheSerializer { public static let `default` = DefaultCacheSerializer() private init() {} public func data(with image: Image, original: Data?) -> Data? { let imageFormat = original?.kf.imageFormat ?? .unknown let data: Data? switch imageFormat { case .PNG: data = image.kf.pngRepresentation() case .JPEG: data = image.kf.jpegRepresentation(compressionQuality: 1.0) case .GIF: data = image.kf.gifRepresentation() case .unknown: data = original ?? image.kf.normalized.kf.pngRepresentation() } return data } public func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? { let scale = (options ?? KingfisherEmptyOptionsInfo).scaleFactor let preloadAllGIFData = (options ?? KingfisherEmptyOptionsInfo).preloadAllGIFData return Kingfisher<Image>.image(data: data, scale: scale, preloadAllGIFData: preloadAllGIFData) } }
apache-2.0
ed0440109f45e093a9d46a820fedf759
42.870588
102
0.682489
4.708333
false
false
false
false
microeditionbiz/ML-client
ML-client/View Controllers/CardIssuerCell.swift
1
1173
// // CardIssuerCell.swift // ML-client // // Created by Pablo Romero on 8/14/17. // Copyright © 2017 Pablo Romero. All rights reserved. // import UIKit class CardIssuerCell: UICollectionViewCell { @IBOutlet weak var cardView: UIView! @IBOutlet weak var iconImageView: RemoteImageView! @IBOutlet weak var nameLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() cardView.layer.cornerRadius = 10 cardView.clipsToBounds = true self.clipsToBounds = false self.layer.shadowOffset = CGSize.zero self.layer.shadowRadius = 3.0 self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOpacity = 0.2 self.layer.rasterizationScale = UIScreen.main.scale self.layer.shouldRasterize = true; } func update(withCardIssuer cardIssuer: CardIssuer) { if let stringURL = cardIssuer.secureThumbnail, let url = URL(string: stringURL) { iconImageView.setContent(url: url) } else { iconImageView.setContent(url: nil) } nameLabel.text = cardIssuer.name } }
mit
b756559b66dd30344eaf9b4b7a054a97
26.904762
89
0.638225
4.578125
false
false
false
false
kousun12/RxSwift
Rx.playground/Pages/Introduction.xcplaygroundpage/Contents.swift
4
4689
//: [<< Index](@previous) import RxSwift import Foundation /*: # Introduction ## Why use RxSwift? A vast majority of the code we write revolves around responding to external actions. When a user manipulates a control, we need to write an @IBAction to respond to that. We need to observe Notifications to detect when the keyboard changes position. We must provide blocks to execute when URL Sessions respond with data. And we use KVO to detect changes in variables. All of these various systems makes our code needlessly complex. Wouldn't it be better if there was one consistent system that handled all of our call/response code? Rx is such a system. ## Observables The key to understanding RxSwift is in understanding the notion of Observables. Creating them, manipulating them, and subscribing to them in order to react to changes. ## Creating and Subscribing to Observables The first step in understanding this library is in understanding how to create Observables. There are a number of functions available to make Observables. Creating an Observable is one thing, but if nothing subscribes to the observable, then nothing will come of it so both are explained simultaneously. */ /*: ### empty `empty` creates an empty sequence. The only message it sends is the `.Completed` message. */ example("empty") { let emptySequence: Observable<Int> = empty() let subscription = emptySequence .subscribe { event in print(event) } } /*: ### never `never` creates a sequence that never sends any element or completes. */ example("never") { let neverSequence: Observable<String> = never() let subscription = neverSequence .subscribe { _ in print("This block is never called.") } } /*: ### just `just` represents sequence that contains one element. It sends two messages to subscribers. The first message is the value of single element and the second message is `.Completed`. */ example("just") { let singleElementSequence = just(32) let subscription = singleElementSequence .subscribe { event in print(event) } } /*: ### sequenceOf `sequenceOf` creates a sequence of a fixed number of elements. */ example("sequenceOf") { let sequenceOfElements/* : Observable<Int> */ = sequenceOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) let subscription = sequenceOfElements .subscribe { event in print(event) } } /*: ### from `from` creates a sequence from `SequenceType` */ example("from") { let sequenceFromArray = [1, 2, 3, 4, 5].asObservable() let subscription = sequenceFromArray .subscribe { event in print(event) } } /*: ### create `create` creates sequence using Swift closure. This examples creates custom version of `just` operator. */ example("create") { let myJust = { (singleElement: Int) -> Observable<Int> in return create { observer in observer.on(.Next(singleElement)) observer.on(.Completed) return NopDisposable.instance } } let subscription = myJust(5) .subscribe { event in print(event) } } /*: ### failWith create an Observable that emits no items and terminates with an error */ example("failWith") { let error = NSError(domain: "Test", code: -1, userInfo: nil) let erroredSequence: Observable<Int> = failWith(error) let subscription = erroredSequence .subscribe { event in print(event) } } /*: ### `deferred` do not create the Observable until the observer subscribes, and create a fresh Observable for each observer ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/defer.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/defer.html ) */ example("deferred") { let deferredSequence: Observable<Int> = deferred { print("creating") return create { observer in print("emmiting") observer.on(.Next(0)) observer.on(.Next(1)) observer.on(.Next(2)) return NopDisposable.instance } } _ = deferredSequence .subscribe { event in print(event) } _ = deferredSequence .subscribe { event in print(event) } } /*: There is a lot more useful methods in the RxCocoa library, so check them out: * `rx_observe` exist on every NSObject and wraps KVO. * `rx_tap` exists on buttons and wraps @IBActions * `rx_notification` wraps NotificationCenter events * ... and many others */ //: [Index](Index) - [Next >>](@next)
mit
31d0ef0814cca2b8134bf29a97d4a560
26.421053
366
0.664321
4.34569
false
false
false
false
drmohundro/Nimble
Nimble/Utils/Stringers.swift
1
1370
import Foundation func _identityAsString(value: NSObject?) -> String { if !value.hasValue { return "nil" } return NSString(format: "<%p>", value!) } func _arrayAsString<T>(items: [T], joiner: String = ", ") -> String { return items.reduce("") { accum, item in let prefix = (accum.isEmpty ? "" : joiner) return accum + prefix + "\(item)" } } @objc protocol NMBStringer { func NMB_stringify() -> String } func stringify<S: SequenceType>(value: S) -> String { var generator = value.generate() var strings = [String]() var value: S.Generator.Element? do { value = generator.next() if value.hasValue { strings.append(stringify(value)) } } while value.hasValue let str = ", ".join(strings) return "[\(str)]" } extension NSArray : NMBStringer { func NMB_stringify() -> String { let str = valueForKey("description").componentsJoinedByString(", ") return "[\(str)]" } } func stringify<T>(value: T?) -> String { if value is Double { return NSString(format: "%.4f", (value as Double)) } return toString(value) } extension Optional: Printable { public var description: String { switch self { case let .Some(value): return toString(value) default: return "nil" } } }
apache-2.0
feb65adb0f21ee7aeff7e37e716c1790
22.62069
75
0.581022
4.005848
false
false
false
false
thkl/NetatmoSwift
netatmoclient/NetatmoMeasureProvider.swift
1
6520
// // NetatmoMeasureProvider.swift // netatmoclient // // Created by Thomas Kluge on 04.10.15. // Copyright © 2015 kSquare.de. All rights reserved. // import Foundation import CoreData struct NetatmoMeasure: Equatable { var timestamp : Date var type: Int var value : Double var unit : String { return (NetatmoMeasureUnit(rawValue: self.type)?.unit)! } } func ==(lhs: NetatmoMeasure, rhs: NetatmoMeasure) -> Bool { return (lhs.timestamp.timeIntervalSince1970 == rhs.timestamp.timeIntervalSince1970) && (lhs.type == rhs.type) } extension NetatmoMeasure { init(managedObject : NSManagedObject) { self.timestamp = managedObject.value(forKey: "timestamp") as! Date self.type = managedObject.value(forKey: "type") as! Int self.value = managedObject.value(forKey: "value") as! Double } } class NetatmoMeasureProvider { fileprivate let coreDataStore: CoreDataStore! init(coreDataStore : CoreDataStore?) { if (coreDataStore != nil) { self.coreDataStore = coreDataStore } else { self.coreDataStore = CoreDataStore() } } func save() { try! coreDataStore.managedObjectContext.save() } func createMeasure(_ timeStamp : Date , type : Int, value: AnyObject? , forStation : NetatmoStation? , forModule : NetatmoModule? )->NSManagedObject? { guard let mvalue = value as? Double else { return nil } let test = self.getMeasureWithTimeStamp(timeStamp, andType: type) if (test != nil){ return test! } let newMeasure = NSEntityDescription.insertNewObject(forEntityName: "Measurement", into: coreDataStore.managedObjectContext) //let newMeasure = NSManagedObject(entity: coreDataStore.managedObjectContext.persistentStoreCoordinator!.managedObjectModel.entitiesByName["Measurement"]!, // insertInto: coreDataStore.managedObjectContext) newMeasure.setValue(timeStamp, forKey: "timestamp") newMeasure.setValue(type, forKey: "type") newMeasure.setValue(mvalue , forKey: "value") // Fetch Station or Module if (forStation != nil) { newMeasure.setValue(forStation!.id , forKey: "stationid") } if (forModule != nil) { newMeasure.setValue(forModule!.id , forKey: "moduleid") } try! coreDataStore.managedObjectContext.save() return newMeasure } func insertMeasuresWithJsonData(_ json: NSDictionary , forStation : NetatmoStation? , forModule : NetatmoModule?) { if let body = json["body"] as? Array<NSDictionary> { for dat : NSDictionary in body { let beg_time = (dat["beg_time"] as AnyObject).doubleValue var step : Double = 0 let step_time = (dat["step_time"] as AnyObject).doubleValue let values = dat["value"] as! Array<NSArray> for value : NSArray in values { let dt = Date(timeIntervalSince1970: beg_time! + step) var measurelist = forStation!.measurementTypes if (forModule != nil) { measurelist = forModule!.measurementTypes } var i = 0 for measureType: NetatmoMeasureType in measurelist { self.createMeasure(dt, type: measureType.hashValue , value: value[i] as AnyObject?, forStation: forStation, forModule: forModule) i += 1 } if (step_time != nil ) { step = step + step_time! } } } } } func getLastMeasureDate(_ forStation : NetatmoStation? , forModule : NetatmoModule?)->Date { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Measurement") if (forModule != nil) { fetchRequest.predicate = NSPredicate(format: "moduleid == %@", argumentArray: [forModule!.id]) } else { if (forStation != nil) { fetchRequest.predicate = NSPredicate(format: "stationid == %@ && moduleid = NULL", argumentArray: [forStation!.id]) } } fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)] fetchRequest.fetchLimit = 1 let results = try! coreDataStore.managedObjectContext.fetch(fetchRequest) as! [NSManagedObject] if ( results.first != nil ) { return results.first?.value(forKey: "timestamp") as! Date } else { return Date().addingTimeInterval(-86400) } } fileprivate func getMeasureWithTimeStamp(_ date : Date , andType : Int)->NSManagedObject? { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Measurement") fetchRequest.predicate = NSPredicate(format: "timestamp == %@ && type == %@", argumentArray: [date,andType]) fetchRequest.fetchLimit = 1 let results = try! coreDataStore.managedObjectContext.fetch(fetchRequest) as! [NSManagedObject] return results.first } func getMeasurementfor(_ station : NetatmoStation, module : NetatmoModule?, withTypes:[NetatmoMeasureType], betweenStartDate: Date, andEndDate: Date)->Array<NetatmoMeasure> { return self.getMeasurementfor(station, module: module, withTypes: withTypes, betweenStartDate: betweenStartDate, andEndDate: andEndDate,ascending : false) } func getMeasurementfor(_ station : NetatmoStation, module : NetatmoModule?, withTypes:[NetatmoMeasureType], betweenStartDate: Date, andEndDate: Date, ascending: Bool)->Array<NetatmoMeasure> { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Measurement") var resultArray = Array<NetatmoMeasure>() let types = withTypes.map({$0.hashValue}) if (module == nil) { fetchRequest.predicate = NSPredicate(format: "stationid == %@ && moduleid == NULL && timestamp >= %@ && timestamp <= %@ && type IN %@", argumentArray: [station.id, betweenStartDate,andEndDate,types]) } else { let moduleid = (module != nil) ? module!.id : "" fetchRequest.predicate = NSPredicate(format: "stationid == %@ && moduleid == %@ && timestamp >= %@ && timestamp <= %@ && type IN %@", argumentArray: [station.id,moduleid, betweenStartDate,andEndDate,types]) } fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: ascending)] let results = try! coreDataStore.managedObjectContext.fetch(fetchRequest) as! [NSManagedObject] for obj: NSManagedObject in results { resultArray.append(NetatmoMeasure(managedObject: obj)) } return resultArray } }
apache-2.0
5c85a9aad482de1b437df6d7f3171e60
34.429348
214
0.660684
4.440736
false
false
false
false
lorentey/swift
stdlib/public/core/UTF8.swift
15
12340
//===--- UTF8.swift -------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension Unicode { @frozen public enum UTF8 { case _swift3Buffer(Unicode.UTF8.ForwardParser) } } extension Unicode.UTF8 { /// Returns the number of code units required to encode the given Unicode /// scalar. /// /// Because a Unicode scalar value can require up to 21 bits to store its /// value, some Unicode scalars are represented in UTF-8 by a sequence of up /// to 4 code units. The first code unit is designated a *lead* byte and the /// rest are *continuation* bytes. /// /// let anA: Unicode.Scalar = "A" /// print(anA.value) /// // Prints "65" /// print(UTF8.width(anA)) /// // Prints "1" /// /// let anApple: Unicode.Scalar = "🍎" /// print(anApple.value) /// // Prints "127822" /// print(UTF8.width(anApple)) /// // Prints "4" /// /// - Parameter x: A Unicode scalar value. /// - Returns: The width of `x` when encoded in UTF-8, from `1` to `4`. @_alwaysEmitIntoClient public static func width(_ x: Unicode.Scalar) -> Int { switch x.value { case 0..<0x80: return 1 case 0x80..<0x0800: return 2 case 0x0800..<0x1_0000: return 3 default: return 4 } } } extension Unicode.UTF8: _UnicodeEncoding { public typealias CodeUnit = UInt8 public typealias EncodedScalar = _ValidUTF8Buffer @inlinable public static var encodedReplacementCharacter: EncodedScalar { return EncodedScalar.encodedReplacementCharacter } @inline(__always) @inlinable public static func _isScalar(_ x: CodeUnit) -> Bool { return isASCII(x) } /// Returns whether the given code unit represents an ASCII scalar @_alwaysEmitIntoClient @inline(__always) public static func isASCII(_ x: CodeUnit) -> Bool { return x & 0b1000_0000 == 0 } @inline(__always) @inlinable public static func decode(_ source: EncodedScalar) -> Unicode.Scalar { switch source.count { case 1: return Unicode.Scalar(_unchecked: source._biasedBits &- 0x01) case 2: let bits = source._biasedBits &- 0x0101 var value = (bits & 0b0_______________________11_1111__0000_0000) &>> 8 value |= (bits & 0b0________________________________0001_1111) &<< 6 return Unicode.Scalar(_unchecked: value) case 3: let bits = source._biasedBits &- 0x010101 var value = (bits & 0b0____________11_1111__0000_0000__0000_0000) &>> 16 value |= (bits & 0b0_______________________11_1111__0000_0000) &>> 2 value |= (bits & 0b0________________________________0000_1111) &<< 12 return Unicode.Scalar(_unchecked: value) default: _internalInvariant(source.count == 4) let bits = source._biasedBits &- 0x01010101 var value = (bits & 0b0_11_1111__0000_0000__0000_0000__0000_0000) &>> 24 value |= (bits & 0b0____________11_1111__0000_0000__0000_0000) &>> 10 value |= (bits & 0b0_______________________11_1111__0000_0000) &<< 4 value |= (bits & 0b0________________________________0000_0111) &<< 18 return Unicode.Scalar(_unchecked: value) } } @inline(__always) @inlinable public static func encode( _ source: Unicode.Scalar ) -> EncodedScalar? { var c = source.value if _fastPath(c < (1&<<7)) { return EncodedScalar(_containing: UInt8(c)) } var o = c & 0b0__0011_1111 c &>>= 6 o &<<= 8 if _fastPath(c < (1&<<5)) { return EncodedScalar(_biasedBits: (o | c) &+ 0b0__1000_0001__1100_0001) } o |= c & 0b0__0011_1111 c &>>= 6 o &<<= 8 if _fastPath(c < (1&<<4)) { return EncodedScalar( _biasedBits: (o | c) &+ 0b0__1000_0001__1000_0001__1110_0001) } o |= c & 0b0__0011_1111 c &>>= 6 o &<<= 8 return EncodedScalar( _biasedBits: (o | c ) &+ 0b0__1000_0001__1000_0001__1000_0001__1111_0001) } @inlinable @inline(__always) public static func transcode<FromEncoding: _UnicodeEncoding>( _ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type ) -> EncodedScalar? { if _fastPath(FromEncoding.self == UTF16.self) { let c = _identityCast(content, to: UTF16.EncodedScalar.self) var u0 = UInt16(truncatingIfNeeded: c._storage) if _fastPath(u0 < 0x80) { return EncodedScalar(_containing: UInt8(truncatingIfNeeded: u0)) } var r = UInt32(u0 & 0b0__11_1111) r &<<= 8 u0 &>>= 6 if _fastPath(u0 < (1&<<5)) { return EncodedScalar( _biasedBits: (UInt32(u0) | r) &+ 0b0__1000_0001__1100_0001) } r |= UInt32(u0 & 0b0__11_1111) r &<<= 8 if _fastPath(u0 & (0xF800 &>> 6) != (0xD800 &>> 6)) { u0 &>>= 6 return EncodedScalar( _biasedBits: (UInt32(u0) | r) &+ 0b0__1000_0001__1000_0001__1110_0001) } } else if _fastPath(FromEncoding.self == UTF8.self) { return _identityCast(content, to: UTF8.EncodedScalar.self) } return encode(FromEncoding.decode(content)) } @frozen public struct ForwardParser { public typealias _Buffer = _UIntBuffer<UInt8> @inline(__always) @inlinable public init() { _buffer = _Buffer() } public var _buffer: _Buffer } @frozen public struct ReverseParser { public typealias _Buffer = _UIntBuffer<UInt8> @inline(__always) @inlinable public init() { _buffer = _Buffer() } public var _buffer: _Buffer } } extension UTF8.ReverseParser: Unicode.Parser, _UTFParser { public typealias Encoding = Unicode.UTF8 @inline(__always) @inlinable public func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) { _internalInvariant(_buffer._storage & 0x80 != 0) // this case handled elsewhere if _buffer._storage & 0b0__1110_0000__1100_0000 == 0b0__1100_0000__1000_0000 { // 2-byte sequence. Top 4 bits of decoded result must be nonzero let top4Bits = _buffer._storage & 0b0__0001_1110__0000_0000 if _fastPath(top4Bits != 0) { return (true, 2*8) } } else if _buffer._storage & 0b0__1111_0000__1100_0000__1100_0000 == 0b0__1110_0000__1000_0000__1000_0000 { // 3-byte sequence. The top 5 bits of the decoded result must be nonzero // and not a surrogate let top5Bits = _buffer._storage & 0b0__1111__0010_0000__0000_0000 if _fastPath( top5Bits != 0 && top5Bits != 0b0__1101__0010_0000__0000_0000) { return (true, 3*8) } } else if _buffer._storage & 0b0__1111_1000__1100_0000__1100_0000__1100_0000 == 0b0__1111_0000__1000_0000__1000_0000__1000_0000 { // Make sure the top 5 bits of the decoded result would be in range let top5bits = _buffer._storage & 0b0__0111__0011_0000__0000_0000__0000_0000 if _fastPath( top5bits != 0 && top5bits <= 0b0__0100__0000_0000__0000_0000__0000_0000 ) { return (true, 4*8) } } return (false, _invalidLength() &* 8) } /// Returns the length of the invalid sequence that ends with the LSB of /// buffer. @inline(never) @usableFromInline internal func _invalidLength() -> UInt8 { if _buffer._storage & 0b0__1111_0000__1100_0000 == 0b0__1110_0000__1000_0000 { // 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result // must be nonzero and not a surrogate let top5Bits = _buffer._storage & 0b0__1111__0010_0000 if top5Bits != 0 && top5Bits != 0b0__1101__0010_0000 { return 2 } } else if _buffer._storage & 0b1111_1000__1100_0000 == 0b1111_0000__1000_0000 { // 2-byte prefix of 4-byte sequence // Make sure the top 5 bits of the decoded result would be in range let top5bits = _buffer._storage & 0b0__0111__0011_0000 if top5bits != 0 && top5bits <= 0b0__0100__0000_0000 { return 2 } } else if _buffer._storage & 0b0__1111_1000__1100_0000__1100_0000 == 0b0__1111_0000__1000_0000__1000_0000 { // 3-byte prefix of 4-byte sequence // Make sure the top 5 bits of the decoded result would be in range let top5bits = _buffer._storage & 0b0__0111__0011_0000__0000_0000 if top5bits != 0 && top5bits <= 0b0__0100__0000_0000__0000_0000 { return 3 } } return 1 } @inline(__always) @inlinable public func _bufferedScalar(bitCount: UInt8) -> Encoding.EncodedScalar { let x = UInt32(truncatingIfNeeded: _buffer._storage.byteSwapped) let shift = 32 &- bitCount return Encoding.EncodedScalar(_biasedBits: (x &+ 0x01010101) &>> shift) } } extension Unicode.UTF8.ForwardParser: Unicode.Parser, _UTFParser { public typealias Encoding = Unicode.UTF8 @inline(__always) @inlinable public func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) { _internalInvariant(_buffer._storage & 0x80 != 0) // this case handled elsewhere if _buffer._storage & 0b0__1100_0000__1110_0000 == 0b0__1000_0000__1100_0000 { // 2-byte sequence. At least one of the top 4 bits of the decoded result // must be nonzero. if _fastPath(_buffer._storage & 0b0_0001_1110 != 0) { return (true, 2*8) } } else if _buffer._storage & 0b0__1100_0000__1100_0000__1111_0000 == 0b0__1000_0000__1000_0000__1110_0000 { // 3-byte sequence. The top 5 bits of the decoded result must be nonzero // and not a surrogate let top5Bits = _buffer._storage & 0b0___0010_0000__0000_1111 if _fastPath(top5Bits != 0 && top5Bits != 0b0___0010_0000__0000_1101) { return (true, 3*8) } } else if _buffer._storage & 0b0__1100_0000__1100_0000__1100_0000__1111_1000 == 0b0__1000_0000__1000_0000__1000_0000__1111_0000 { // 4-byte sequence. The top 5 bits of the decoded result must be nonzero // and no greater than 0b0__0100_0000 let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111) if _fastPath( top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 ) { return (true, 4*8) } } return (false, _invalidLength() &* 8) } /// Returns the length of the invalid sequence that starts with the LSB of /// buffer. @inline(never) @usableFromInline internal func _invalidLength() -> UInt8 { if _buffer._storage & 0b0__1100_0000__1111_0000 == 0b0__1000_0000__1110_0000 { // 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result // must be nonzero and not a surrogate let top5Bits = _buffer._storage & 0b0__0010_0000__0000_1111 if top5Bits != 0 && top5Bits != 0b0__0010_0000__0000_1101 { return 2 } } else if _buffer._storage & 0b0__1100_0000__1111_1000 == 0b0__1000_0000__1111_0000 { // Prefix of 4-byte sequence. The top 5 bits of the decoded result // must be nonzero and no greater than 0b0__0100_0000 let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111) if top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 { return _buffer._storage & 0b0__1100_0000__0000_0000__0000_0000 == 0b0__1000_0000__0000_0000__0000_0000 ? 3 : 2 } } return 1 } @inlinable public func _bufferedScalar(bitCount: UInt8) -> Encoding.EncodedScalar { let x = UInt32(_buffer._storage) &+ 0x01010101 return _ValidUTF8Buffer(_biasedBits: x & ._lowBits(bitCount)) } }
apache-2.0
a8ce82a62df2ec2e638968ab4fa1b5b4
36.727829
83
0.575261
3.685987
false
false
false
false
jonnyleeharris/ento
Ento/ento/core/System.swift
1
1866
// // System.swift // // Created by Jonathan Harris on 30/06/2015. // Copyright © 2015 Jonathan Harris. All rights reserved. // import Foundation public class System : Hashable { private var hashNumber:Int; private static var hashCount:Int = 0; internal var engine:Engine?; public var hashValue:Int { get { return hashNumber; } } /** * Used internally to hold the priority of this system within the system list. This is * used to order the systems so they are updated in the correct order. */ internal var priority : Int = 0; /** * Called just after the system is added to the engine, before any calls to the update method. * Override this method to add your own functionality. * * @param engine The engine the system was added to. */ public func addToEngine( engine : Engine ) { self.engine = engine; } /** * Called just after the system is removed from the engine, after all calls to the update method. * Override this method to add your own functionality. * * @param engine The engine the system was removed from. */ public func removeFromEngine( engine : Engine ) { } /** * After the system is added to the engine, this method is called every frame until the system * is removed from the engine. Override this method to add your own functionality. * * <p>If you need to perform an action outside of the update loop (e.g. you need to change the * systems in the engine and you don't want to do it while they're updating) add a listener to * the engine's updateComplete signal to be notified when the update loop completes.</p> * * @param time The duration, in seconds, of the frame. */ public func update( time : Double ) { } public init() { self.hashNumber = System.hashCount++; } } public func == (lhs:System, rhs:System) -> Bool { return lhs.hashValue == rhs.hashValue; }
mit
dcca772a29f84371f908d96c39daa921
23.88
97
0.700804
3.55916
false
false
false
false
benlangmuir/swift
stdlib/public/core/Mirrors.swift
10
9288
//===--- Mirrors.swift - Common _Mirror implementations -------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if SWIFT_ENABLE_REFLECTION extension Float: CustomReflectable { /// A mirror that reflects the `Float` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension Float: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `Float` instance. @available(*, deprecated, message: "Float.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .float(self) } } extension Double: CustomReflectable { /// A mirror that reflects the `Double` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension Double: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `Double` instance. @available(*, deprecated, message: "Double.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .double(self) } } extension Bool: CustomReflectable { /// A mirror that reflects the `Bool` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension Bool: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `Bool` instance. @available(*, deprecated, message: "Bool.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .bool(self) } } extension String: CustomReflectable { /// A mirror that reflects the `String` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension String: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `String` instance. @available(*, deprecated, message: "String.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .text(self) } } extension Character: CustomReflectable { /// A mirror that reflects the `Character` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension Character: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `Character` instance. @available(*, deprecated, message: "Character.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .text(String(self)) } } extension Unicode.Scalar: CustomReflectable { /// A mirror that reflects the `Unicode.Scalar` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension Unicode.Scalar: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `Unicode.Scalar` instance. @available(*, deprecated, message: "Unicode.Scalar.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .uInt(UInt64(self)) } } extension UInt8: CustomReflectable { /// A mirror that reflects the `UInt8` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension UInt8: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `UInt8` instance. @available(*, deprecated, message: "UInt8.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .uInt(UInt64(self)) } } extension Int8: CustomReflectable { /// A mirror that reflects the `Int8` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension Int8: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `Int8` instance. @available(*, deprecated, message: "Int8.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .int(Int64(self)) } } extension UInt16: CustomReflectable { /// A mirror that reflects the `UInt16` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension UInt16: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `UInt16` instance. @available(*, deprecated, message: "UInt16.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .uInt(UInt64(self)) } } extension Int16: CustomReflectable { /// A mirror that reflects the `Int16` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension Int16: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `Int16` instance. @available(*, deprecated, message: "Int16.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .int(Int64(self)) } } extension UInt32: CustomReflectable { /// A mirror that reflects the `UInt32` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension UInt32: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `UInt32` instance. @available(*, deprecated, message: "UInt32.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .uInt(UInt64(self)) } } extension Int32: CustomReflectable { /// A mirror that reflects the `Int32` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension Int32: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `Int32` instance. @available(*, deprecated, message: "Int32.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .int(Int64(self)) } } extension UInt64: CustomReflectable { /// A mirror that reflects the `UInt64` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension UInt64: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `UInt64` instance. @available(*, deprecated, message: "UInt64.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .uInt(UInt64(self)) } } extension Int64: CustomReflectable { /// A mirror that reflects the `Int64` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension Int64: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `Int64` instance. @available(*, deprecated, message: "Int64.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .int(Int64(self)) } } extension UInt: CustomReflectable { /// A mirror that reflects the `UInt` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension UInt: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `UInt` instance. @available(*, deprecated, message: "UInt.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .uInt(UInt64(self)) } } extension Int: CustomReflectable { /// A mirror that reflects the `Int` instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } extension Int: _CustomPlaygroundQuickLookable { /// A custom playground Quick Look for the `Int` instance. @available(*, deprecated, message: "Int.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: _PlaygroundQuickLook { return .int(Int64(self)) } } #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) extension Float80: CustomReflectable { /// A mirror that reflects the Float80 instance. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: EmptyCollection<Void>()) } } #endif #endif
apache-2.0
07664c4e6cc3f8d93a760248079806d2
34.181818
122
0.74171
4.795044
false
false
false
false
mozilla-mobile/firefox-ios
Client/Utils/CumulativeDaysOfUseCounter.swift
2
3380
// 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 // Counter to know if a user has used the app a certain number of days in a row, used for `RatingPromptManager` requirements. class CumulativeDaysOfUseCounter { private let calendar = Calendar.current private let maximumNumberOfDaysToCollect = 7 private let requiredCumulativeDaysOfUseCount = 5 private enum UserDefaultsKey: String { case keyArrayDaysOfUse = "com.moz.arrayDaysOfUse.key" case keyRequiredCumulativeDaysOfUseCount = "com.moz.hasRequiredCumulativeDaysOfUseCount.key" } private(set) var hasRequiredCumulativeDaysOfUse: Bool { get { UserDefaults.standard.object(forKey: UserDefaultsKey.keyRequiredCumulativeDaysOfUseCount.rawValue) as? Bool ?? false } set { UserDefaults.standard.set(newValue, forKey: UserDefaultsKey.keyRequiredCumulativeDaysOfUseCount.rawValue) } } var daysOfUse: [Date]? { get { UserDefaults.standard.array(forKey: UserDefaultsKey.keyArrayDaysOfUse.rawValue) as? [Date] } set { UserDefaults.standard.set(newValue, forKey: UserDefaultsKey.keyArrayDaysOfUse.rawValue) } } func updateCounter(currentDate: Date = Date()) { // If there's no data, add current day of usage guard var daysOfUse = daysOfUse, let lastDayOfUse = daysOfUse.last else { daysOfUse = [currentDate] return } // Append usage days that are not already saved let numberOfDaysSinceLastUse = calendar.numberOfDaysBetween(lastDayOfUse, and: currentDate) if numberOfDaysSinceLastUse >= 1 { daysOfUse.append(currentDate) self.daysOfUse = daysOfUse } // Check if we have 5 consecutive days in the last 7 days hasRequiredCumulativeDaysOfUse = hasRequiredCumulativeDaysOfUse(daysOfUse: daysOfUse) // Clean data older than 7 days cleanDaysOfUseData(daysOfUse: daysOfUse, currentDate: currentDate) } private func hasRequiredCumulativeDaysOfUse(daysOfUse: [Date]) -> Bool { var cumulativeDaysCount = 0 var previousDay: Date? var maxNumberOfConsecutiveDays = 0 daysOfUse.forEach { dayOfUse in if let previousDay = previousDay { let numberOfDaysBetween = calendar.numberOfDaysBetween(previousDay, and: dayOfUse) cumulativeDaysCount = numberOfDaysBetween == 1 ? cumulativeDaysCount + 1 : 0 } else { cumulativeDaysCount += 1 } maxNumberOfConsecutiveDays = max(cumulativeDaysCount, maxNumberOfConsecutiveDays) previousDay = dayOfUse } return maxNumberOfConsecutiveDays >= requiredCumulativeDaysOfUseCount } private func cleanDaysOfUseData(daysOfUse: [Date], currentDate: Date) { var cleanedDaysOfUse = daysOfUse cleanedDaysOfUse.removeAll(where: { let numberOfDays = calendar.numberOfDaysBetween($0, and: currentDate) return numberOfDays >= maximumNumberOfDaysToCollect }) self.daysOfUse = cleanedDaysOfUse } func reset() { hasRequiredCumulativeDaysOfUse = false daysOfUse = nil } }
mpl-2.0
04bfde53f25423527a04fcadca40d40d
39.238095
132
0.690237
4.630137
false
false
false
false
BilalReffas/Dashii
Dashi/DashboardViewController.swift
1
1578
// // DashboardCollectionView.swift // Dashi // // Created by Bilal Karim Reffas on 28.01.17. // Copyright © 2017 Bilal Karim Reffas. All rights reserved. // import UIKit class DashboardViewController: UIViewController, UICollectionViewDelegate { private let dataSource = DashboardDataSource() private let layout = DashboardFlowLayout() private let mosaicLayout = TRMosaicLayout() @IBOutlet private weak var graphCollectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.graphCollectionView.delegate = self self.graphCollectionView?.dataSource = dataSource self.graphCollectionView?.collectionViewLayout = self.mosaicLayout self.mosaicLayout.delegate = layout Networking.request(url: URL(string: "https://pbzj4rft03.execute-api.eu-west-1.amazonaws.com/dev/pictureDataSet")!) { micros in self.dataSource.microscopes = micros DispatchQueue.main.async { self.graphCollectionView.reloadData() } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.graphCollectionView.setNeedsLayout() self.graphCollectionView.layoutIfNeeded() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.performSegue(withIdentifier: "show", sender: nil) } }
mit
234aefec7bb2e3fad00a565237e34c2e
28.203704
134
0.677235
5.1875
false
false
false
false
KoCMoHaBTa/MHAppKit
MHAppKit/ViewControllers/DynamicTableViewController.swift
1
2011
// // DynamicTableViewController.swift // MHAppKit // // Created by Milen Halachev on 2/12/15. // Copyright (c) 2015 Milen Halachev. All rights reserved. // #if canImport(UIKit) && !os(watchOS) import UIKit open class DynamicTableViewController: StaticTableViewController { @IBInspectable open var automaticallyBindTableViewCellAccessoryControlToDelegate: Bool = false open override func viewDidLoad() { super.viewDidLoad() } //MARK: - UITableViewDataSource & UITableViewDelegate open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = self.tableView(tableView, loadCellForRowAtIndexPath: indexPath) cell = self.tableView(tableView, configureCell: cell, forRowAtIndexPath: indexPath) if self.automaticallyBindTableViewCellAccessoryControlToDelegate && cell.accessoryView != nil && cell.accessoryView is UIControl { if let accessoryView = cell.accessoryView as? UIControl { accessoryView.addTarget(self, action: #selector(StaticTableViewController.accessoryViewTouchAction(_:event:)), for: .touchUpInside) } } return cell } open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } //MARK: - Custom UITableViewDataSource & UITableViewDelegate open func tableView(_ tableView: UITableView, loadCellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell { let cellID = "CellID" let cell = tableView.dequeueReusableCell(withIdentifier: cellID) return cell! } open func tableView(_ tableView: UITableView, configureCell cell: UITableViewCell, forRowAtIndexPath indexPath: IndexPath) -> UITableViewCell { return cell } } #endif
mit
26b7215e8f45817e970edee423557647
32.516667
147
0.674789
5.812139
false
false
false
false
thewisecity/declarehome-ios
CookedApp/ParseSubclasses/Group.swift
1
3844
// // Group.swift // CookedApp // // Created by Dexter Lohnes on 10/14/15. // Copyright © 2015 The Wise City. All rights reserved. // class Group : PFObject, PFSubclassing { @NSManaged var name: String? @NSManaged var twitter: String? @NSManaged var facebook: String? @NSManaged var website: String? @NSManaged var state: String? @NSManaged var city: String? @NSManaged var address: String? @NSManaged var neighberhoods: String? @NSManaged var purpose: String? @NSManaged var membersRole: PFRole? @NSManaged var adminsRole: PFRole? @NSManaged var membersArray: [User]? @NSManaged var adminsArray: [User]? override class func initialize() { struct Static { static var onceToken : dispatch_once_t = 0; } dispatch_once(&Static.onceToken) { self.registerSubclass() } } static func parseClassName() -> String { return "Group" } static func createGroup(name:String?, purpose:String?, neighberhoods:String?, address:String?, city:String?, state:String?, website:String?, facebook:String?, twitter:String?, callback: (Group, Bool, NSError?) -> Void) -> Void { Stats.TrackAttemptingGroupCreation() let group = Group() group.name = name group.purpose = purpose group.neighberhoods = neighberhoods group.address = address group.city = city group.state = state group.website = website group.facebook = facebook group.twitter = twitter group.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in callback(group, success, error) } } func isCurrentUserAdmin() -> Bool { return isUserAdmin(PFUser.currentUser() as! User, forceServerContact: false) } func isCurrentUserMember() -> Bool { return isUserMember(PFUser.currentUser() as! User, forceServerContact: false) } func isUserAdmin(user: User, forceServerContact : Bool) -> Bool { var userIsAdmin : Bool = false do { if forceServerContact == true { try self.fetch() } else { try self.fetchIfNeeded() } if let _ = adminsArray { for theUser in adminsArray! { if theUser.objectId == user.objectId { userIsAdmin = true break } } } } catch let error as NSError { print("Error") print(error.localizedDescription) } return userIsAdmin } func isUserMember(user: User, forceServerContact : Bool) -> Bool { var userIsMember : Bool = false do { if forceServerContact == true { try self.fetch() } else { try self.fetchIfNeeded() } if let _ = membersArray { for theUser in membersArray! { if theUser.objectId == user.objectId { userIsMember = true break } } } } catch let error as NSError { print("Error") print(error.localizedDescription) } return userIsMember } func addMember(user: User) { membersArray?.append(user) saveInBackground() } }
gpl-3.0
f2a73c6a7680754d031314320f05fe91
25.6875
230
0.502212
5.110372
false
false
false
false
UIKit0/VPNOn
VPNOn/VPNConfigViewController+Save.swift
21
2121
// // VPNConfigViewController+Save.swift // VPNOn // // Created by Lex on 1/23/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import UIKit import VPNOnKit extension VPNConfigViewController { @IBAction func saveVPN(sender: AnyObject) { if let currentVPN = vpn { currentVPN.title = titleTextField.text currentVPN.server = serverTextField.text currentVPN.account = accountTextField.text currentVPN.group = groupTextField.text currentVPN.alwaysOn = alwaysOnSwitch.on currentVPN.ikev2 = typeSegment.selectedSegmentIndex == 1 currentVPN.certificateURL = certificateURL VPNKeychainWrapper.setPassword(passwordTextField.text, forVPNID: currentVPN.ID) VPNKeychainWrapper.setSecret(secretTextField.text, forVPNID: currentVPN.ID) VPNDataManager.sharedManager.saveContext() NSNotificationCenter.defaultCenter().postNotificationName(kVPNDidUpdate, object: currentVPN) } else { if let lastVPN = VPNDataManager.sharedManager.createVPN( titleTextField.text, server: serverTextField.text, account: accountTextField.text, password: passwordTextField.text, group: groupTextField.text, secret: secretTextField.text, alwaysOn: alwaysOnSwitch.on, ikev2: typeSegment.selectedSegmentIndex == 1, certificateURL: certificateURL ?? "", certificate: temporaryCertificateData ) { NSNotificationCenter.defaultCenter().postNotificationName(kVPNDidCreate, object: lastVPN) } } } func toggleSaveButtonByStatus() { if self.titleTextField.text.isEmpty || self.accountTextField.text.isEmpty || self.serverTextField.text.isEmpty { self.saveButton?.enabled = false } else { self.saveButton?.enabled = true } } }
mit
5db423669fdc232b6a68f42425d4f116
35.568966
109
0.611033
5.36962
false
false
false
false
br1sk/Sonar
Sources/Sonar/APIs/AppleRadar.swift
1
8736
import Alamofire import Foundation private let kRadarDowntimeURL = URL(string: "http://static.ips.apple.com/radar/web/downtime/index.html") final class AppleRadar: BugTracker { private let credentials: (appleID: String, password: String) private let manager: Alamofire.SessionManager private var token: String? /// - parameter appleID: Username to be used on `bugreport.apple.com` authentication. /// - parameter password: Password to be used on `bugreport.apple.com` authentication. init(appleID: String, password: String) { self.credentials = (appleID: appleID, password: password) let configuration = URLSessionConfiguration.default let cookies = HTTPCookieStorage.shared configuration.httpCookieStorage = cookies configuration.httpCookieAcceptPolicy = .always self.manager = Alamofire.SessionManager(configuration: configuration) } /// Login into radar by an apple ID and password. /// /// - parameter getTwoFactorCode: A closure to retrieve a two factor auth code from the user. /// - parameter closure: A closure that will be called when the login is completed, on success it /// will contain a list of `Product`s; on failure a `SonarError`. func login(getTwoFactorCode: @escaping (_ closure: @escaping (_ code: String?) -> Void) -> Void, closure: @escaping (Result<Void, SonarError>) -> Void) { self.manager .request(AppleRadarRouter.accountInfo(appleID: credentials.appleID, password: credentials.password)) .validate() .responseString { [weak self] response in if let httpResponse = response.response, httpResponse.statusCode == 409 { getTwoFactorCode { code in if let code = code { self?.handleTwoFactorChallenge(code: code, headers: httpResponse.allHeaderFields, closure: closure) } else { closure(.failure(SonarError(message: "No 2 factor auth code provided"))) } } } else if case .success = response.result { self?.fetchAccessToken(closure: closure) } else { closure(.failure(SonarError.from(response))) } } } /// Creates a new ticket into apple's radar (needs authentication first). /// /// - parameter radar: The radar model with the information for the ticket. /// - parameter closure: A closure that will be called when the login is completed, on success it will /// contain a radar ID; on failure a `SonarError`. func create(radar: Radar, closure: @escaping (Result<Int, SonarError>) -> Void) { guard let token = self.token else { closure(.failure(SonarError(message: "User is not logged in"))) return } let route = AppleRadarRouter.create(radar: radar, token: token) let (_, method, headers, body, _) = route.components let createMultipart = { (data: MultipartFormData) -> Void in data.append(body ?? Data(), withName: "hJsonScreenVal") } self.manager .upload(multipartFormData: createMultipart, to: route.url, method: method, headers: headers) { result in guard case let .success(upload, _, _) = result else { closure(.failure(.unknownError)) return } upload.validate().responseString { response in guard case let .success(value) = response.result else { closure(.failure(SonarError.from(response))) return } if let radarID = Int(value) { return self.uploadAttachments(radarID: radarID, attachments: radar.attachments, token: token, closure: closure) } if let json = jsonObject(from: value), json["isError"] as? Bool == true { let message = json["message"] as? String ?? "Unknown error occurred" closure(.failure(SonarError(message: message))) } else { closure(.failure(SonarError(message: "Invalid Radar ID received"))) } } } } // MARK: - Private Functions private func handleTwoFactorChallenge(code: String, headers: [AnyHashable: Any], closure: @escaping (Result<Void, SonarError>) -> Void) { guard let sessionID = headers["X-Apple-ID-Session-Id"] as? String, let scnt = headers["scnt"] as? String else { closure(.failure(SonarError(message: "Missing Session-Id or scnt"))) return } self.manager .request(AppleRadarRouter.authorizeTwoFactor(code: code, scnt: scnt, sessionID: sessionID)) .validate() .responseString { [weak self] response in guard case .success = response.result else { closure(.failure(SonarError.from(response))) return } self?.manager .request(AppleRadarRouter.sessionID) .validate() .responseString { [weak self] response in if case .success = response.result { self?.fetchAccessToken(closure: closure) } else { closure(.failure(SonarError.from(response))) } } } } private func fetchAccessToken(closure: @escaping (Result<Void, SonarError>) -> Void) { self.manager .request(AppleRadarRouter.sessionID) .validate() .response { [weak self] _ in self?.manager .request(AppleRadarRouter.accessToken) .validate() .responseJSON { [weak self] response in if case .success(let value) = response.result, let dictionary = value as? NSDictionary, let token = dictionary["accessToken"] as? String { self?.token = token closure(.success(())) } else if response.response?.url == kRadarDowntimeURL { closure(.failure(SonarError(message: "Radar appears to be down"))) } else { closure(.failure(SonarError.from(response))) } } } } private func uploadAttachments(radarID: Int, attachments: [Attachment], token: String, closure: @escaping (Result<Int, SonarError>) -> Void) { if attachments.isEmpty { return closure(.success(radarID)) } var successful = true let group = DispatchGroup() for attachment in attachments { group.enter() let route = AppleRadarRouter.uploadAttachment(radarID: radarID, attachment: attachment, token: token) assert(route.components.data == nil, "The data is uploaded manually, not from the route") self.manager .upload(attachment.data, with: route) .validate(statusCode: [201]) .response { result in defer { group.leave() } successful = successful && result.response?.statusCode == 201 } } group.notify(queue: .main) { if successful { closure(.success(radarID)) } else { closure(.failure(SonarError(message: "Failed to upload attachments"))) } } } } private func jsonObject(from string: String) -> [String: Any]? { guard let data = string.data(using: .utf8) else { return nil } return (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] }
mit
749101a7bce172ff4eef471c56c345de
42.034483
110
0.518086
5.333333
false
false
false
false
asowers1/RevCheckIn
RevCheckIn/loginViewController.swift
1
8386
// // loginViewController.swift // RevCheckIn // // Created by Andrew Sowers on 7/27/14. // Copyright (c) 2014 Andrew Sowers. All rights reserved. // import UIKit import CoreData import Foundation import QuartzCore class loginViewController: UIViewController, UITextFieldDelegate { @IBOutlet var username: UITextField! @IBOutlet var password: UITextField! @IBOutlet weak var newAccountButton: UIButton! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var leadingConstraint: NSLayoutConstraint! @IBOutlet weak var trailingConstraint: NSLayoutConstraint! @IBOutlet var imgView: UIImageView! var usernameString:String="" var passwordString:String="" var existingItem: NSManagedObject! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.hidden = true let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor(),NSFontAttributeName :UIFont(name: "AppleSDGothicNeo-Thin", size: 28.0)] self.navigationController?.navigationBar.titleTextAttributes = titleDict self.title = "Rev Check-in" username.delegate = self password.delegate = self self.newAccountButton.layer.borderWidth = 2.0 self.loginButton.layer.borderWidth = 2.0 self.newAccountButton.layer.borderColor = UIColor.whiteColor().CGColor self.loginButton.layer.borderColor = UIColor.whiteColor().CGColor username.layer.borderWidth = 2.0 password.layer.borderWidth = 2.0 username.layer.borderColor = UIColor.whiteColor().CGColor password.layer.borderColor = UIColor.whiteColor().CGColor } override func viewDidAppear(animated: Bool) { var myList: Array<AnyObject> = [] var appDel2: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate var context2: NSManagedObjectContext = appDel2.managedObjectContext! let freq = NSFetchRequest(entityName: "Active_user") myList = context2.executeFetchRequest(freq, error: nil)! if (myList.count > 0){ var selectedItem: NSManagedObject = myList[0] as NSManagedObject var user: String = selectedItem.valueForKeyPath("username") as String if user != "-1" { println("login successful: \(user)") self.performSegueWithIdentifier("login", sender: self) } else{ println("login unsuccessful") } } } override func prefersStatusBarHidden() -> Bool { return false } func textFieldShouldReturn(textField: UITextField!) -> Bool { if(textField == username){ password.becomeFirstResponder() }else if(textField == password){ password.resignFirstResponder() } return true } @IBAction func startEditingLogin(sender: AnyObject) { println("Started Editing username") } func loginLogic() { var helper: HTTPHelper = HTTPHelper() helper.login(username.text, password: password.text) var myList: Array<AnyObject> = [] var appDel2: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate var context2: NSManagedObjectContext = appDel2.managedObjectContext! let freq = NSFetchRequest(entityName: "Active_user") println("login logic") while myList.isEmpty {myList = context2.executeFetchRequest(freq, error: nil)!} println("got context") var selectedItem: NSManagedObject = myList[0] as NSManagedObject if let user: String = selectedItem.valueForKeyPath("username") as? String { if user != "-1" { println("login successful") //record user device //var helper: HTTPHelper = HTTPHelper() //let device = helper.getDeviceContext() //var coreDataHelper: CoreDataHelper = CoreDataHelper() //let network: HTTPBackground = HTTPBackground() //network.linkUserToDevice(user, device) //println("user:\(user): device:\(device): LINKED") self.performSegueWithIdentifier("login", sender: self) } else{ println("login unsuccessful") let networkIssue = UIAlertController(title: "Login unsuccessful", message: "Your username or password is incorrect", preferredStyle: UIAlertControllerStyle.Alert) networkIssue.addAction(UIAlertAction(title: "Try Again", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(networkIssue, animated: true, completion: nil) } }else{ println("login unsuccessful!") let networkIssue = UIAlertController(title: "Network Issue", message: "Could not log in", preferredStyle: UIAlertControllerStyle.Alert) networkIssue.addAction(UIAlertAction(title: "Try Later", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(networkIssue, animated: true, completion: nil) var helper:HTTPHelper = HTTPHelper() helper.setUserContext("-1") } } @IBAction func cancelLogin(sender: AnyObject) { self.leadingConstraint.constant = 0 self.trailingConstraint.constant = 0 UIView.animateWithDuration(0.25, animations: { self.view.layoutIfNeeded() }) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) var myList: Array<AnyObject> = [] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func login(sender: AnyObject) { if (self.username.text != "" && self.password.text != ""){ self.loginLogic() } else { var field = "username" if (self.password.text == "" && self.username.text != ""){ field = "password" } let incomplete: UIAlertController = UIAlertController(title: "incomplete login", message: "\(field) field cannot be blank", preferredStyle: UIAlertControllerStyle.Alert) incomplete.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(incomplete, animated: true, completion: nil) } } @IBAction func showLogin(sender: AnyObject) { println(self.leadingConstraint.constant) self.leadingConstraint.constant = self.view.frame.origin.x - (self.newAccountButton.frame.size.width + 20) self.trailingConstraint.constant = -1 * (self.newAccountButton.frame.size.width + 20) println(self.leadingConstraint.constant) UIView.animateWithDuration(0.25, animations: { self.view.layoutIfNeeded() }) } @IBAction func register(sender: AnyObject) { Crashlytics.setObjectValue("register", forKey: "loginAction") self.performSegueWithIdentifier("register", sender: self) } @IBAction func sendToWeb(sender: AnyObject) { let viewWeb : UIAlertController = UIAlertController(title: "learn more", message:"visit Push on the web", preferredStyle: UIAlertControllerStyle.ActionSheet) viewWeb.addAction(UIAlertAction(title:"cancel", style: UIAlertActionStyle.Cancel, handler: nil)) viewWeb.addAction(UIAlertAction(title: "view", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in println("Foo") UIApplication.sharedApplication().openURL(NSURL.URLWithString("http://www.experiencepush.com")) })) self.presentViewController(viewWeb, animated: true, completion: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "register" { println("segue") } } }
mit
231590823ba601a55caae70e4ea50c83
38.186916
181
0.628309
5.410323
false
false
false
false
CodeMath/iOS8_Swift_App_LeeDH
Whats The Weather/Whats The Weather/ViewController.swift
1
2904
// // ViewController.swift // Whats The Weather // // Created by 이동혁 on 2015. 5. 6.. // Copyright (c) 2015년 CodeMath. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var userCity: UITextField! @IBAction func findweather(sender: AnyObject) { var url = NSURL( string : "http://www.weather-forecast.com/locations/" + userCity.text.stringByReplacingOccurrencesOfString(" ", withString: "-") + "/forecasts/latest") // nil인지 체크를 해야 크레시가 안일어남.... if url != nil{ let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in var urlError = false var weather = "" if error == nil { var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as NSString! var urlContentArray = urlContent.componentsSeparatedByString("<span class=\"phrase\">") if urlContentArray.count > 0 { var weatherArray = urlContentArray[1].componentsSeparatedByString("</span>") weather = weatherArray[0] as! String weather = weather.stringByReplacingOccurrencesOfString("&deg;", withString: "º") } else{ urlError == true } } else { urlError = true } dispatch_async(dispatch_get_main_queue()){ if urlError == true{ self.showError() } else { self.resultLabel.text = weather } } }) task.resume() } else { showError() } } @IBOutlet weak var resultLabel: UILabel! func showError(){ resultLabel.text = "Was NOT able to find weather for " + userCity.text + ". Please try again" } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
d629a5a6e453465d21efefc0afec48df
27.939394
176
0.438743
6.338496
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/MGalleryVideoItem.swift
1
8579
// // MGalleryVideoItem.swift // TelegramMac // // Created by keepcoder on 19/12/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import TelegramCore import Postbox import SwiftSignalKit import TGUIKit import AVFoundation import AVKit class MGalleryVideoItem: MGalleryItem { var startTime: TimeInterval = 0 private var playAfter:Bool = false private let controller: SVideoController var playerState: Signal<AVPlayerState, NoError> { return controller.status |> map { value in switch value.status { case .playing: return .playing(duration: value.duration) case .paused: return .paused(duration: value.duration) case let .buffering(initial, whilePlaying): if whilePlaying { return .playing(duration: value.duration) } else if !whilePlaying && !initial { return .paused(duration: value.duration) } else { return .waiting } } } |> deliverOnMainQueue } override init(_ context: AccountContext, _ entry: GalleryEntry, _ pagerSize: NSSize) { controller = SVideoController(postbox: context.account.postbox, reference: entry.fileReference(entry.file!)) super.init(context, entry, pagerSize) controller.togglePictureInPictureImpl = { [weak self] enter, control in guard let `self` = self else {return} let frame = control.view.window!.convertToScreen(control.view.convert(control.view.bounds, to: nil)) if enter, let viewer = viewer { closeGalleryViewer(false) showPipVideo(control: control, viewer: viewer, item: self, origin: frame.origin, delegate: viewer.delegate, contentInteractions: viewer.contentInteractions, type: viewer.type) } else if !enter { exitPictureInPicture() } } } deinit { updateMagnifyDisposable.dispose() } override func singleView() -> NSView { return controller.genericView } private var isPausedGlobalPlayer: Bool = false private let updateMagnifyDisposable = MetaDisposable() override func appear(for view: NSView?) { super.appear(for: view) pausepip() if let pauseMusic = context.audioPlayer?.pause() { isPausedGlobalPlayer = pauseMusic } controller.play(startTime) controller.viewDidAppear(false) self.startTime = 0 updateMagnifyDisposable.set((magnify.get() |> deliverOnMainQueue).start(next: { [weak self] value in if value < 1.0 { _ = self?.hideControls(forceHidden: true) } else { _ = self?.unhideControls(forceUnhidden: true) } })) } override var maxMagnify: CGFloat { return min(pagerSize.width / sizeValue.width, pagerSize.height / sizeValue.height) } override func disappear(for view: NSView?) { super.disappear(for: view) if isPausedGlobalPlayer { _ = context.audioPlayer?.play() } if controller.style != .pictureInPicture { controller.pause() } controller.viewDidDisappear(false) updateMagnifyDisposable.set(nil) playAfter = false } override var status:Signal<MediaResourceStatus, NoError> { if media.isStreamable { return .single(.Local) } else { return realStatus } } override var realStatus:Signal<MediaResourceStatus, NoError> { if let message = entry.message { return chatMessageFileStatus(context: context, message: message, file: media) } else { return context.account.postbox.mediaBox.resourceStatus(media.resource) } } var media:TelegramMediaFile { return entry.file! } private var examinatedSize: CGSize? var dimensions: CGSize? { if let examinatedSize = examinatedSize { return examinatedSize } if let dimensions = media.dimensions { return dimensions.size } let linked = link(path: context.account.postbox.mediaBox.resourcePath(media.resource), ext: "mp4") guard let path = linked else { return media.dimensions?.size } let url = URL(fileURLWithPath: path) guard let track = AVURLAsset(url: url).tracks(withMediaType: .video).first else { return media.dimensions?.size } try? FileManager.default.removeItem(at: url) let size = track.naturalSize.applying(track.preferredTransform) self.examinatedSize = NSMakeSize(abs(size.width), abs(size.height)) return examinatedSize } override var notFittedSize: NSSize { if let size = dimensions { return size.fitted(pagerSize) } return pagerSize } override var sizeValue: NSSize { if let size = dimensions { var pagerSize = self.pagerSize var size = size if size.width == 0 || size.height == 0 { size = NSMakeSize(300, 300) } let aspectRatio = size.width / size.height let addition = max(300 - size.width, 300 - size.height) if addition > 0 { size.width += addition * aspectRatio size.height += addition } // let addition = max(400 - size.width, 400 - size.height) // if addition > 0 { // size.width += addition // size.height += addition // } size = size.fitted(pagerSize) return size } return pagerSize } func hideControls(forceHidden: Bool = false) -> Bool { return controller.hideControlsIfNeeded(forceHidden) } func unhideControls(forceUnhidden: Bool = true) -> Bool { return controller.unhideControlsIfNeeded(forceUnhidden) } override func toggleFullScreen() { controller.toggleFullScreen() } override func togglePlayerOrPause() { controller.togglePlayerOrPause() } override func rewindBack() { controller.rewindBackward() } override func rewindForward() { controller.rewindForward() } var isFullscreen: Bool { return controller.isFullscreen } override func request(immediately: Bool) { super.request(immediately: immediately) let signal:Signal<ImageDataTransformation,NoError> = chatMessageVideo(postbox: context.account.postbox, fileReference: entry.fileReference(media), scale: System.backingScale, synchronousLoad: true) let size = sizeValue let arguments = TransformImageArguments(corners: ImageCorners(), imageSize: size, boundingSize: size, intrinsicInsets: NSEdgeInsets(), resizeMode: .none) let result = signal |> mapToThrottled { data -> Signal<CGImage?, NoError> in return .single(data.execute(arguments, data.data)?.generateImage()) } path.set(context.account.postbox.mediaBox.resourceData(media.resource) |> mapToSignal { (resource) -> Signal<String, NoError> in if resource.complete { return .single(link(path:resource.path, ext:kMediaVideoExt)!) } return .never() }) self.image.set(media.previewRepresentations.isEmpty ? .single(GPreviewValueClass(.image(nil, nil))) |> deliverOnMainQueue : result |> map { GPreviewValueClass(.image($0 != nil ? NSImage(cgImage: $0!, size: $0!.backingSize) : nil, nil)) } |> deliverOnMainQueue) fetch() } override func fetch() -> Void { if !media.isStreamable { if let parent = entry.message { _ = messageMediaFileInteractiveFetched(context: context, messageId: parent.id, messageReference: .init(parent), file: media, userInitiated: true).start() } else { _ = freeMediaFileInteractiveFetched(context: context, fileReference: FileMediaReference.standalone(media: media)).start() } } } }
gpl-2.0
93916d8d562bb868d04b5ed2f89930fa
32.639216
268
0.588832
4.927053
false
false
false
false
MatthewYork/DateTools
DateToolsSwift/Tests/DateToolsTests/DateToolsTestsTests/TimePeriodChainTests.swift
4
8269
// // TimePeriodChainTests.swift // DateToolsTests // // Created by Grayson Webster on 8/19/16. // Copyright © 2016 Matthew York. All rights reserved. // import XCTest @testable import DateToolsTests class TimePeriodChainTests : XCTestCase { var formatter = DateFormatter() var controlChain = TimePeriodChain() var firstPeriod = TimePeriod() var secondPeriod = TimePeriod() var thirdPeriod = TimePeriod() override func setUp() { //Initialize control TimePeriodChain self.formatter.dateFormat = "yyyy MM dd HH:mm:ss.SSS" self.formatter.timeZone = TimeZone(abbreviation: "UTC") //Create test TimePeriods that are 1 year long firstPeriod = TimePeriod(beginning: self.formatter.date(from: "2014 11 05 18:15:12.000")!, end: self.formatter.date(from: "2015 11 05 18:15:12.000")!) secondPeriod = TimePeriod(beginning: self.formatter.date(from: "2015 11 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 05 18:15:12.000")!) thirdPeriod = TimePeriod(beginning: self.formatter.date(from: "2016 11 05 18:15:12.000")!, end: self.formatter.date(from: "2017 11 05 18:15:12.000")!) //Add test periods self.controlChain.append(firstPeriod) self.controlChain.append(secondPeriod) self.controlChain.append(thirdPeriod) } override func tearDown() { super.tearDown() } // MARK: - Chain Manipulation func testAppendPeriod() { let testPeriod = TimePeriod(beginning: self.formatter.date(from: "2015 11 05 18:15:12.000")!, end: self.formatter.date(from: "2017 11 05 18:15:12.000")!) //Build test chain let testChain = TimePeriodChain() testChain.periods.append(firstPeriod) testChain.periods.append(TimePeriod(beginning: testChain[0].end!, duration: secondPeriod.duration)) testChain.periods.append(TimePeriod(beginning: testChain[1].end!, duration: thirdPeriod.duration)) testChain.periods.append(TimePeriod(beginning: testChain[2].end!, duration: testPeriod.duration)) //Append to control controlChain.append(testPeriod) XCTAssertTrue(testChain == controlChain) XCTAssertEqual(self.formatter.date(from: "2014 11 05 18:15:12.000")!, controlChain.beginning) XCTAssertEqual(self.formatter.date(from: "2019 11 06 18:15:12.000")!, controlChain.end) //Simple example let simplePeriod = TimePeriod(beginning: self.formatter.date(from: "2015 11 05 18:15:12.000")!, end: self.formatter.date(from: "2015 11 05 18:15:13.000")!) let simpleChain = TimePeriodChain() simpleChain.append(simplePeriod) simpleChain.append(simplePeriod) simpleChain.append(simplePeriod) XCTAssertEqual(self.formatter.date(from: "2015 11 05 18:15:12.000")!, simpleChain.beginning) XCTAssertEqual(self.formatter.date(from: "2015 11 05 18:15:15.000")!, simpleChain.end) } func testAppendGroup() { let testPeriod1 = TimePeriod(beginning: self.formatter.date(from: "2015 11 05 18:15:12.000")!, end: self.formatter.date(from: "2017 11 05 18:15:12.000")!) let testPeriod2 = TimePeriod(beginning: self.formatter.date(from: "2015 11 05 18:15:12.000")!, end: self.formatter.date(from: "2018 11 05 18:15:12.000")!) let testPeriod3 = TimePeriod(beginning: self.formatter.date(from: "2015 11 05 18:15:12.000")!, end: self.formatter.date(from: "2019 11 05 18:15:12.000")!) //Build test chain let testChain = TimePeriodChain() testChain.periods.append(testPeriod1) testChain.periods.append(TimePeriod(beginning: testChain[0].end!, chunk: testPeriod2.chunk)) testChain.periods.append(TimePeriod(beginning: testChain[1].end!, chunk: testPeriod3.chunk)) let appendCollection = TimePeriodCollection(); appendCollection.append(testPeriod1) appendCollection.append(testPeriod2) appendCollection.append(testPeriod3) let appendChain = TimePeriodChain() appendChain.append(contentsOf: appendCollection) XCTAssertTrue(testChain == appendChain) XCTAssertEqual(self.formatter.date(from: "2015 11 05 18:15:12.000")!, appendChain.beginning) XCTAssertEqual(self.formatter.date(from: "2024 11 05 18:15:12.000")!, appendChain.end) } func testInsert() { let testPeriod = TimePeriod(beginning: self.formatter.date(from: "2012 11 05 18:15:12.000")!, end: self.formatter.date(from: "2013 11 05 18:15:12.000")!) controlChain.insert(testPeriod, at: 0) //Check accurate insertion placement XCTAssertTrue(controlChain[0].beginning == testPeriod.beginning) XCTAssertTrue(controlChain[0].end == testPeriod.end) //Check accurate insertion chain modification XCTAssertEqual(self.formatter.date(from: "2012 11 05 18:15:12.000")!, controlChain.beginning) XCTAssertEqual(self.formatter.date(from: "2016 11 04 18:15:12.000")!, controlChain.end) //Doesn't account for leap year } func testRemove() { controlChain.remove(at: 1) //Build test chain let testChain = TimePeriodChain() testChain.append(firstPeriod) testChain.append(thirdPeriod) XCTAssertTrue(controlChain == testChain) } func testRemoveAll() { controlChain.removeAll() XCTAssertTrue(controlChain.count == 0) } func testDuration() { //Simple example let simplePeriod = TimePeriod(beginning: self.formatter.date(from: "2015 11 05 18:15:12.000")!, end: self.formatter.date(from: "2015 11 05 18:15:13.000")!) let simpleChain = TimePeriodChain() simpleChain.append(simplePeriod) simpleChain.append(simplePeriod) simpleChain.append(simplePeriod) XCTAssertEqual(simpleChain.duration, 3.0) } func testPop() { //Build test chain let testChain = TimePeriodChain() testChain.periods.append(firstPeriod) testChain.periods.append(TimePeriod(beginning: testChain[0].end!, chunk: secondPeriod.chunk)) let _ = controlChain.pop()! XCTAssertTrue(testChain == controlChain) //Cannot accurately test popped value due to daylight savings changes } // MARK: - Chain Time Manipulation func testShiftBy() { controlChain.shift(by: 4) let testChain = TimePeriodChain() let testPeriod1 = TimePeriod(beginning: self.formatter.date(from: "2014 11 05 18:15:16.000")!, end: self.formatter.date(from: "2015 11 05 18:15:16.000")!) let testPeriod2 = TimePeriod(beginning: self.formatter.date(from: "2015 11 05 18:15:16.000")!, end: self.formatter.date(from: "2016 11 05 18:15:16.000")!) let testPeriod3 = TimePeriod(beginning: self.formatter.date(from: "2016 11 05 18:15:16.000")!, end: self.formatter.date(from: "2017 11 05 18:15:16.000")!) testChain.append(testPeriod1) testChain.append(testPeriod2) testChain.append(testPeriod3) XCTAssertTrue(controlChain.equals(testChain)) } // MARK: - Chain Relationship func testEquals() { let testChain = TimePeriodChain() let testPeriod1 = TimePeriod(beginning: self.formatter.date(from: "2014 11 05 18:15:12.000")!, end: self.formatter.date(from: "2015 11 05 18:15:12.000")!) let testPeriod2 = TimePeriod(beginning: self.formatter.date(from: "2015 11 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 05 18:15:12.000")!) let testPeriod3 = TimePeriod(beginning: self.formatter.date(from: "2016 11 05 18:15:12.000")!, end: self.formatter.date(from: "2017 11 05 18:15:12.000")!) testChain.append(testPeriod1) testChain.append(testPeriod2) testChain.append(testPeriod3) XCTAssertTrue(controlChain.equals(testChain)) XCTAssertTrue(controlChain == testChain) XCTAssertEqual(controlChain.beginning, testChain.beginning) XCTAssertEqual(controlChain.end, testChain.end) } // MARK: - Updates func testUpdateVariables() { } }
mit
cda12e410c536942d0dd9be3cdb32e9c
44.180328
163
0.66328
3.90184
false
true
false
false
eliperkins/Static
Static/DataSource.swift
2
6811
import UIKit /// Table view data source. /// /// You should always access this object from the main thread since it talks to UIKit. public class DataSource: NSObject { // MARK: - Properties /// The table view that will use this object as its data source. public weak var tableView: UITableView? { willSet { if let tableView = tableView { tableView.dataSource = nil tableView.delegate = nil } } didSet { assert(NSThread.isMainThread(), "You must access Static.DataSource from the main thread.") updateTableView() } } /// Sections to use in the table view. public var sections: [Section] { didSet { assert(NSThread.isMainThread(), "You must access Static.DataSource from the main thread.") refresh() } } private var registeredCellIdentifiers = Set<String>() // MARK: - Initializers /// Initialize with optional `tableView` and `sections`. public init(tableView: UITableView? = nil, sections: [Section]? = nil) { self.tableView = tableView self.sections = sections ?? [] super.init() updateTableView() } deinit { // nil out the table view to ensure the table view data source and delegate niled out tableView = nil } // MARK: - Private private func updateTableView() { guard let tableView = tableView else { return } tableView.dataSource = self tableView.delegate = self refresh() } private func refresh() { refreshTableSections() refreshRegisteredCells() } private func sectionForIndex(index: Int) -> Section? { if sections.count <= index { assert(false, "Invalid section index: \(index)") return nil } return sections[index] } private func rowForIndexPath(indexPath: NSIndexPath) -> Row? { if let section = sectionForIndex(indexPath.section) { let rows = section.rows if rows.count >= indexPath.row { return rows[indexPath.row] } } assert(false, "Invalid index path: \(indexPath)") return nil } private func refreshTableSections(oldSections: [Section]? = nil) { guard let tableView = tableView else { return } guard let oldSections = oldSections else { tableView.reloadData() return } let oldCount = oldSections.count let newCount = sections.count let delta = newCount - oldCount let animation: UITableViewRowAnimation = .Automatic tableView.beginUpdates() if delta == 0 { tableView.reloadSections(NSIndexSet(indexesInRange: NSMakeRange(0, newCount)), withRowAnimation: animation) } else { if delta > 0 { // Insert sections tableView.insertSections(NSIndexSet(indexesInRange: NSMakeRange(oldCount - 1, delta)), withRowAnimation: animation) } else { // Remove sections tableView.deleteSections(NSIndexSet(indexesInRange: NSMakeRange(oldCount - 1, -delta)), withRowAnimation: animation) } // Reload existing sections let commonCount = min(oldCount, newCount) tableView.reloadSections(NSIndexSet(indexesInRange: NSMakeRange(0, commonCount)), withRowAnimation: animation) } tableView.endUpdates() } private func refreshRegisteredCells() { // Filter to only rows with unregistered cells let rows = sections.map({ $0.rows }).reduce([], combine: +).filter() { !self.registeredCellIdentifiers.contains($0.cellIdentifier) } for row in rows { let identifier = row.cellIdentifier // Check again in case there were duplicate new cell classes if registeredCellIdentifiers.contains(identifier) { continue } registeredCellIdentifiers.insert(identifier) tableView?.registerClass(row.cellClass, forCellReuseIdentifier: identifier) } } } extension DataSource: UITableViewDataSource { public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sectionForIndex(section)?.rows.count ?? 0 } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let row = rowForIndexPath(indexPath) { let tableCell = tableView.dequeueReusableCellWithIdentifier(row.cellIdentifier, forIndexPath: indexPath) if let cell = tableCell as? CellType { cell.configure(row: row) } return tableCell } return UITableViewCell() } public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionForIndex(section)?.header?.title } public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return sectionForIndex(section)?.header?.view } public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return sectionForIndex(section)?.header?.viewHeight ?? UITableViewAutomaticDimension } public func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return sectionForIndex(section)?.footer?.title } public func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return sectionForIndex(section)?.footer?.view } public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return sectionForIndex(section)?.footer?.viewHeight ?? UITableViewAutomaticDimension } } extension DataSource: UITableViewDelegate { public func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool { return rowForIndexPath(indexPath)?.isSelectable ?? false } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if let row = rowForIndexPath(indexPath) { row.selection?() } } public func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) { if let row = rowForIndexPath(indexPath) { row.accessory.selection?() } } }
mit
4a1f514289b481f5cbc71a60440e215e
31.588517
132
0.63882
5.537398
false
false
false
false
goktugyil/EZSwiftExtensions
Sources/ArrayExtensions.swift
1
10404
// // ArrayExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import Foundation public func ==<T: Equatable>(lhs: [T]?, rhs: [T]?) -> Bool { switch (lhs, rhs) { case let (lhs?, rhs?): return lhs == rhs case (.none, .none): return true default: return false } } extension Array { ///EZSE: Get a sub array from range of index public func get(at range: ClosedRange<Int>) -> Array { let halfOpenClampedRange = Range(range).clamped(to: Range(indices)) return Array(self[halfOpenClampedRange]) } /// EZSE: Checks if array contains at least 1 item which type is same with given element's type public func containsType<T>(of element: T) -> Bool { let elementType = type(of: element) return contains { type(of: $0) == elementType} } /// EZSE: Decompose an array to a tuple with first element and the rest public func decompose() -> (head: Iterator.Element, tail: SubSequence)? { return (count > 0) ? (self[0], self[1..<count]) : nil } /// EZSE: Iterates on each element of the array with its index. (Index, Element) public func forEachEnumerated(_ body: @escaping (_ offset: Int, _ element: Element) -> Void) { enumerated().forEach(body) } /// EZSE: Gets the object at the specified index, if it exists. public func get(at index: Int) -> Element? { guard index >= 0 && index < count else { return nil } return self[index] } /// EZSE: Prepends an object to the array. public mutating func insertFirst(_ newElement: Element) { insert(newElement, at: 0) } /// EZSE: Returns a random element from the array. public func random() -> Element? { guard count > 0 else { return nil } let index = Int(arc4random_uniform(UInt32(count))) return self[index] } /// EZSE: Reverse the given index. i.g.: reverseIndex(2) would be 2 to the last public func reverseIndex(_ index: Int) -> Int? { guard index >= 0 && index < count else { return nil } return Swift.max(count - 1 - index, 0) } /// EZSE: Shuffles the array in-place using the Fisher-Yates-Durstenfeld algorithm. public mutating func shuffle() { guard count > 1 else { return } var j: Int for i in 0..<(count-2) { j = Int(arc4random_uniform(UInt32(count - i))) if i != i+j { self.swapAt(i, i+j) } } } /// EZSE: Shuffles copied array using the Fisher-Yates-Durstenfeld algorithm, returns shuffled array. public func shuffled() -> Array { var result = self result.shuffle() return result } /// EZSE: Returns an array with the given number as the max number of elements. public func takeMax(_ n: Int) -> Array { return Array(self[0..<Swift.max(0, Swift.min(n, count))]) } /// EZSE: Checks if test returns true for all the elements in self public func testAll(_ body: @escaping (Element) -> Bool) -> Bool { return !contains { !body($0) } } /// EZSE: Checks if all elements in the array are true or false public func testAll(is condition: Bool) -> Bool { return testAll { ($0 as? Bool) ?? !condition == condition } } } extension Array where Element: Equatable { /// EZSE: Checks if the main array contains the parameter array public func contains(_ array: [Element]) -> Bool { return array.testAll { self.index(of: $0) ?? -1 >= 0 } } /// EZSE: Checks if self contains a list of items. public func contains(_ elements: Element...) -> Bool { return elements.testAll { self.index(of: $0) ?? -1 >= 0 } } /// EZSE: Returns the indexes of the object public func indexes(of element: Element) -> [Int] { return enumerated().flatMap { ($0.element == element) ? $0.offset : nil } } /// EZSE: Returns the last index of the object public func lastIndex(of element: Element) -> Int? { return indexes(of: element).last } /// EZSE: Removes the first given object public mutating func removeFirst(_ element: Element) { guard let index = index(of: element) else { return } self.remove(at: index) } /// EZSE: Removes all occurrences of the given object(s), at least one entry is needed. public mutating func removeAll(_ firstElement: Element?, _ elements: Element...) { var removeAllArr = [Element]() if let firstElementVal = firstElement { removeAllArr.append(firstElementVal) } elements.forEach({element in removeAllArr.append(element)}) removeAll(removeAllArr) } /// EZSE: Removes all occurrences of the given object(s) public mutating func removeAll(_ elements: [Element]) { // COW ensures no extra copy in case of no removed elements self = filter { !elements.contains($0) } } /// EZSE: Difference of self and the input arrays. public func difference(_ values: [Element]...) -> [Element] { var result = [Element]() elements: for element in self { for value in values { // if a value is in both self and one of the values arrays // jump to the next iteration of the outer loop if value.contains(element) { continue elements } } // element it's only in self result.append(element) } return result } /// EZSE: Intersection of self and the input arrays. public func intersection(_ values: [Element]...) -> Array { var result = self var intersection = Array() for (i, value) in values.enumerated() { // the intersection is computed by intersecting a couple per loop: // self n values[0], (self n values[0]) n values[1], ... if i > 0 { result = intersection intersection = Array() } // find common elements and save them in first set // to intersect in the next loop value.forEach { (item: Element) -> Void in if result.contains(item) { intersection.append(item) } } } return intersection } /// EZSE: Union of self and the input arrays. public func union(_ values: [Element]...) -> Array { var result = self for array in values { for value in array { if !result.contains(value) { result.append(value) } } } return result } /// EZSE: Returns an array consisting of the unique elements in the array public func unique() -> Array { return reduce([]) { $0.contains($1) ? $0 : $0 + [$1] } } } extension Array where Element: Hashable { /// EZSE: Removes all occurrences of the given object(s) public mutating func removeAll(_ elements: [Element]) { let elementsSet = Set(elements) // COW ensures no extra copy in case of no removed elements self = filter { !elementsSet.contains($0) } } } extension Collection { /// Returns the element at the specified index if it is within bounds, otherwise nil. public subscript (safe index: Index) -> Iterator.Element? { return indices.contains(index) ? self[index] : nil } } // MARK: - Deprecated 1.8 extension Array { /// EZSE: Checks if array contains at least 1 instance of the given object type @available(*, deprecated: 1.8, renamed: "containsType(of:)") public func containsInstanceOf<T>(_ element: T) -> Bool { return containsType(of: element) } /// EZSE: Gets the object at the specified index, if it exists. @available(*, deprecated: 1.8, renamed: "get(at:)") public func get(_ index: Int) -> Element? { return get(at: index) } /// EZSE: Checks if all elements in the array are true of false @available(*, deprecated: 1.8, renamed: "testAll(is:)") public func testIfAllIs(_ condition: Bool) -> Bool { return testAll(is: condition) } } extension Array where Element: Equatable { /// EZSE: Removes the first given object @available(*, deprecated: 1.8, renamed: "removeFirst(_:)") public mutating func removeFirstObject(_ object: Element) { removeFirst(object) } } // MARK: - Deprecated 1.7 extension Array { /// EZSE: Prepends an object to the array. @available(*, deprecated: 1.7, renamed: "insertFirst(_:)") public mutating func insertAsFirst(_ newElement: Element) { insertFirst(newElement) } } extension Array where Element: Equatable { /// EZSE: Checks if the main array contains the parameter array @available(*, deprecated: 1.7, renamed: "contains(_:)") public func containsArray(_ array: [Element]) -> Bool { return contains(array) } /// EZSE: Returns the indexes of the object @available(*, deprecated: 1.7, renamed: "indexes(of:)") public func indexesOf(_ object: Element) -> [Int] { return indexes(of: object) } /// EZSE: Returns the last index of the object @available(*, deprecated: 1.7, renamed: "lastIndex(_:)") public func lastIndexOf(_ object: Element) -> Int? { return lastIndex(of: object) } /// EZSE: Removes the first given object @available(*, deprecated: 1.7, renamed: "removeFirstObject(_:)") public mutating func removeObject(_ object: Element) { removeFirstObject(object) } } // MARK: - Deprecated 1.6 extension Array { /// EZSE: Creates an array with values generated by running each value of self /// through the mapFunction and discarding nil return values. @available(*, deprecated: 1.6, renamed: "flatMap(_:)") public func mapFilter<V>(mapFunction map: (Element) -> (V)?) -> [V] { return flatMap { map($0) } } /// EZSE: Iterates on each element of the array with its index. (Index, Element) @available(*, deprecated: 1.6, renamed: "forEachEnumerated(_:)") public func each(_ call: @escaping (Int, Element) -> Void) { forEachEnumerated(call) } }
mit
7a97e852824556bf808e6f6663a147b5
31.716981
105
0.599481
4.270936
false
false
false
false
optimizely/swift-sdk
Sources/Utils/NetworkReachability.swift
1
3472
// // Copyright 2021, Optimizely, Inc. and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import Network class NetworkReachability { var monitor: AnyObject? let queue = DispatchQueue(label: "reachability") // the number of contiguous download failures (reachability) var numContiguousFails = 0 // the maximum number of contiguous network connection failures allowed before reachability checking var maxContiguousFails: Int static let defaultMaxContiguousFails = 1 #if targetEnvironment(simulator) private var connected = false // initially false for testing support #else private var connected = true // initially true for safety in production #endif var isConnected: Bool { get { var result = false queue.sync { result = connected } return result } // for test support only set { queue.sync { connected = newValue } } } init(maxContiguousFails: Int? = nil) { self.maxContiguousFails = maxContiguousFails ?? NetworkReachability.defaultMaxContiguousFails if #available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) { // NOTE: test with real devices only (simulator not updating properly) self.monitor = NWPathMonitor() (monitor as! NWPathMonitor).pathUpdateHandler = { [weak self] (path: NWPath) -> Void in // "Reachability path: satisfied (Path is satisfied), interface: en0, ipv4, ipv6, dns, expensive, constrained" // "Reachability path: unsatisfied (No network route)" // print("Reachability path: \(path)") // this task runs in sync queue. set private variable (instead of isConnected to avoid deadlock) self?.connected = (path.status == .satisfied) } (monitor as! NWPathMonitor).start(queue: queue) } } func stop() { if #available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) { guard let monitor = monitor as? NWPathMonitor else { return } monitor.pathUpdateHandler = nil monitor.cancel() } } func updateNumContiguousFails(isError: Bool) { numContiguousFails = isError ? (numContiguousFails + 1) : 0 } /// Skip network access when reachability is down (optimization for iOS12+ only) /// - Returns: true when network access should be blocked func shouldBlockNetworkAccess() -> Bool { if numContiguousFails < maxContiguousFails { return false } if #available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) { return !isConnected } else { return false } } }
apache-2.0
3590a83b1124b6ce3f0be88678ef1c45
33.72
126
0.611175
4.788966
false
false
false
false
Arty-Maly/Volna
Volna/AppDelegate.swift
1
9116
import UIKit import CoreData import Firebase import FirebaseMessaging import UserNotifications let themeColor = UIColor(red: 0.01, green: 0.41, blue: 0.22, alpha: 1.0) @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FirebaseApp.configure() let defaults = UserDefaults.standard if !defaults.bool(forKey: "launchedAlready") { defaults.setValue(true, forKey: "launchedAlready") User.resetTimesOpenedAndReview() } if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_, _ in }) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Core Data stack private lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() private lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "Schema", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("Schema.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { // Configure automatic migration. let options = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ] try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { var managedObjectContext: NSManagedObjectContext? if #available(iOS 10.0, *){ managedObjectContext = self.persistentContainer.viewContext } else{ // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext?.persistentStoreCoordinator = coordinator } return managedObjectContext! }() // iOS-10 @available(iOS 10.0, *) lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Schema") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() 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 parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) // print("\(self.applicationDocumentsDirectory)") return container }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
gpl-3.0
c7e23970ba49d5aec754f44bca1e52bb
54.92638
291
0.679903
6.065203
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/SteviaLayout/Source/Stevia+Operators.swift
2
5279
// // Stevia+Operators.swift // Stevia // // Created by Sacha Durand Saint Omer on 10/02/16. // Copyright © 2016 Sacha Durand Saint Omer. All rights reserved. // #if canImport(UIKit) import UIKit prefix operator | @discardableResult public prefix func | (p: UIView) -> UIView { return p.leading(0) } postfix operator | @discardableResult public postfix func | (p: UIView) -> UIView { return p.trailing(0) } infix operator ~ : HeightPrecedence precedencegroup HeightPrecedence { lowerThan: AdditionPrecedence } @discardableResult public func ~ (left: UIView, right: CGFloat) -> UIView { return left.height(right) } @discardableResult public func ~ (left: UIView, right: SteviaFlexibleMargin) -> UIView { return left.height(right) } @discardableResult public func ~ (left: [UIView], right: CGFloat) -> [UIView] { for l in left { l.height(right) } return left } @discardableResult public func ~ (left: [UIView], right: SteviaFlexibleMargin) -> [UIView] { for l in left { l.height(right) } return left } prefix operator |- @discardableResult public prefix func |- (p: CGFloat) -> SideConstraint { var s = SideConstraint() s.constant = p return s } @discardableResult public prefix func |- (v: UIView) -> UIView { v.leading(8) return v } postfix operator -| @discardableResult public postfix func -| (p: CGFloat) -> SideConstraint { var s = SideConstraint() s.constant = p return s } @discardableResult public postfix func -| (v: UIView) -> UIView { v.trailing(8) return v } public struct SideConstraint { var constant: CGFloat! } public struct PartialConstraint { var view1: UIView! var constant: CGFloat! var views: [UIView]? } @discardableResult public func - (left: UIView, right: CGFloat) -> PartialConstraint { var p = PartialConstraint() p.view1 = left p.constant = right return p } // Side Constraints @discardableResult public func - (left: SideConstraint, right: UIView) -> UIView { if let spv = right.superview { let c = constraint(item: right, attribute: .leading, toItem: spv, attribute: .leading, constant: left.constant) spv.addConstraint(c) } return right } @discardableResult public func - (left: [UIView], right: SideConstraint) -> [UIView] { let lastView = left[left.count-1] if let spv = lastView.superview { let c = constraint(item: lastView, attribute: .trailing, toItem: spv, attribute: .trailing, constant: -right.constant) spv.addConstraint(c) } return left } @discardableResult public func - (left: UIView, right: SideConstraint) -> UIView { if let spv = left.superview { let c = constraint(item: left, attribute: .trailing, toItem: spv, attribute: .trailing, constant: -right.constant) spv.addConstraint(c) } return left } @discardableResult public func - (left: PartialConstraint, right: UIView) -> [UIView] { if let views = left.views { if let spv = right.superview { let lastView = views[views.count-1] let c = constraint(item: lastView, attribute: .trailing, toItem: right, attribute: .leading, constant: -left.constant) spv.addConstraint(c) } return views + [right] } else { // were at the end?? nooope?/? if let spv = right.superview { let c = constraint(item: left.view1, attribute: .trailing, toItem: right, attribute: .leading, constant: -left.constant) spv.addConstraint(c) } return [left.view1, right] } } @discardableResult public func - (left: UIView, right: UIView) -> [UIView] { if let spv = left.superview { let c = constraint(item: right, attribute: .leading, toItem: left, attribute: .trailing, constant: 8) spv.addConstraint(c) } return [left, right] } @discardableResult public func - (left: [UIView], right: CGFloat) -> PartialConstraint { var p = PartialConstraint() p.constant = right p.views = left return p } @discardableResult public func - (left: [UIView], right: UIView) -> [UIView] { let lastView = left[left.count-1] if let spv = lastView.superview { let c = constraint(item: lastView, attribute: .trailing, toItem: right, attribute: .leading, constant: -8) spv.addConstraint(c) } return left + [right] } //// Test space in Horizointal layout "" public struct Space { var previousViews: [UIView]! } @discardableResult public func - (left: UIView, right: String) -> Space { return Space(previousViews: [left]) } @discardableResult public func - (left: [UIView], right: String) -> Space { return Space(previousViews: left) } @discardableResult public func - (left: Space, right: UIView) -> [UIView] { var va = left.previousViews va?.append(right) return va! } #endif
mit
e3cb801805a44c2f451f7a1cd1c6eeff
24.133333
73
0.608943
4.075676
false
false
false
false
CoderST/XMLYDemo
XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/PopularViewController/Model/HotRecommendsItem.swift
1
688
// // HotRecommendsItem.swift // XMLYDemo // // Created by xiudou on 2016/12/22. // Copyright © 2016年 CoderST. All rights reserved. // import UIKit class HotRecommendsItem: BaseModel { var title : String = "" var list : [HotRecommendsSubItem] = [HotRecommendsSubItem]() override func setValue(_ value: Any?, forKey key: String) { if key == "list"{ if let listArray = value as? [[String : AnyObject]]{ for listDict in listArray { list.append(HotRecommendsSubItem(dict: listDict)) } } }else{ super.setValue(value, forKey: key) } } }
mit
c7811a2d1963d863f5a1f65ba0d8d9d3
22.62069
69
0.553285
4.335443
false
false
false
false
jindulys/Leetcode_Solutions_Swift
Sources/String/294_FlipGameII.swift
1
1158
// // 294_FlipGameII.swift // LeetcodeSwift // // Created by yansong li on 2016-11-26. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** Title:294 Flip Game URL: https://leetcode.com/problems/flip-game-ii/ Space: O(2^(n/2)) Time: O(2^(n/2)) */ class FlipGameII_Solution { var canWinDict: [String : Bool] = [:] func canWin(_ s: String) -> Bool { guard s.characters.count > 1 else { return false } let characters = [Character](s.characters) return canWin(characters) } func canWin(_ c: [Character]) -> Bool { let currentString = String(c) if let validResult = self.canWinDict[currentString] { return validResult } for i in 0..<c.count - 1 { if c[i] == c[i + 1] && c[i] == "+" { var newCharacters = c newCharacters[i] = "-" newCharacters[i+1] = "-" if !canWin(newCharacters) { self.canWinDict[currentString] = true return true } } } self.canWinDict[currentString] = false return false } func test() { let test = "+++++" let result = canWin(test) print(result) } }
mit
2118763e80d71560b011e03439da00e2
20.830189
57
0.57822
3.240896
false
true
false
false
mercadopago/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/MPToolbar.swift
2
2377
// // MPToolbar.swift // MercadoPagoSDK // // Created by Matias Gualino on 27/5/15. // Copyright (c) 2015 MercadoPago. All rights reserved. // import Foundation import UIKit public class MPToolbar : UIToolbar { var textFieldContainer : UITextField? var keyboardDelegate: KeyboardDelegate? public init(prevEnabled: Bool, nextEnabled: Bool, delegate: KeyboardDelegate, textFieldContainer: UITextField) { super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 44)) self.keyboardDelegate = delegate self.textFieldContainer = textFieldContainer self.barStyle = UIBarStyle.Default self.translucent = true self.sizeToFit() var items : [UIBarButtonItem] = [] // Create a done button to show on keyboard to resign it. Adding a selector to resign it. let doneButton = UIBarButtonItem(title: "OK", style: UIBarButtonItemStyle.Plain, target: self, action: "done") let prev = UIBarButtonItem(image: MercadoPago.getImage("IQButtonBarArrowLeft"), style: UIBarButtonItemStyle.Plain, target: self, action: "prev") let fixed = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil) fixed.width = 23 let next = UIBarButtonItem(image: MercadoPago.getImage("IQButtonBarArrowRight"), style: UIBarButtonItemStyle.Plain, target: self, action: "next") prev.enabled = prevEnabled next.enabled = nextEnabled items.append(prev) items.append(fixed) items.append(next) // Create a fake button to maintain flexibleSpace between doneButton and nilButton. (Actually it moves done button to right side. let nilButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) items.append(nilButton) items.append(doneButton) // Adding button to toolBar. self.items = items switch textFieldContainer.keyboardAppearance { case UIKeyboardAppearance.Dark: self.barStyle = UIBarStyle.Black default: self.barStyle = UIBarStyle.Default } textFieldContainer.inputAccessoryView = self } func prev() { keyboardDelegate?.prev(textFieldContainer) } func next() { keyboardDelegate?.next(textFieldContainer) } func done() { keyboardDelegate?.done(textFieldContainer) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
ba7889dd8de8386de9362f2e7c23f69b
28
147
0.745057
4.098276
false
false
false
false
audrl1010/EasyMakePhotoPicker
Example/EasyMakePhotoPicker/DurationLabel.swift
1
1315
// // DurationLabel.swift // KaKaoChatInputView // // Created by myung gi son on 2017. 5. 30.. // Copyright © 2017년 grutech. All rights reserved. // import UIKit class DurationLabel: UILabel { struct Constant { static let padding = UIEdgeInsets(top: 5, left: 3, bottom: 5, right: 3) } struct Color { static let bgColor = UIColor( red: 0/255, green: 0/255, blue: 0/255, alpha: 0.35) static let durationLabelTextColor = UIColor.white } struct Font { static let durationLabelFont = UIFont.systemFont(ofSize: 14) } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { backgroundColor = Color.bgColor textColor = Color.durationLabelTextColor font = Font.durationLabelFont text = "00:00" } override func drawText(in rect: CGRect) { super.drawText(in: rect.inset(by: Constant.padding)) } override var intrinsicContentSize: CGSize { let size = super.intrinsicContentSize return CGSize( width: size.width + Constant.padding.left + Constant.padding.right, height: size.height + Constant.padding.top + Constant.padding.bottom) } }
mit
c1ecb7fd316aaad98150cf3160d9131a
19.5
75
0.654726
3.916418
false
false
false
false
vulgur/WeeklyFoodPlan
WeeklyFoodPlan/WeeklyFoodPlan/Views/PlanList/PlanCell.swift
1
1935
// // PlanCell.swift // WeeklyFoodPlan // // Created by vulgur on 2017/3/3. // Copyright © 2017年 MAD. All rights reserved. // import UIKit protocol PlanCellDelegate { func editButtonTapped(section: Int) func pickButtonTapped(section: Int) } class PlanCell: UICollectionViewCell { @IBOutlet var tableView: UITableView! @IBOutlet var dateLabel: UILabel! @IBOutlet var pickButton: UIButton! @IBOutlet var editButton: UIButton! let cellIdentifier = "PlanMealCell" var isLocked: Bool { return !self.pickButton.isEnabled } var section:Int = 0 var plan = DailyPlan() var delegate: PlanCellDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code tableView.dataSource = self tableView.delegate = self tableView.tableFooterView = UIView() tableView.estimatedRowHeight = 80 tableView.rowHeight = UITableViewAutomaticDimension } @IBAction func pickButtonTapped(_ sender: UIButton) { delegate?.pickButtonTapped(section: section) } @IBAction func editButtonTapped(_ sender: UIButton) { delegate?.editButtonTapped(section: section) } } extension PlanCell: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return plan.meals.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! PlanMealCell let meal = plan.meals[indexPath.row] cell.config(with: meal) cell.mealCollectionView.reloadData() return cell } } extension PlanCell: UITableViewDelegate { }
mit
ceb34bc8f10713f17e136bcbae5ddd9a
24.090909
113
0.67029
4.953846
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/ViewControllers/BiometricsSettingsViewController.swift
1
10888
// // BiometricsSettingsViewController.swift // breadwallet // // Created by Adrian Corscadden on 2017-03-27. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit import LocalAuthentication class BiometricsSettingsViewController: UIViewController, Subscriber, Trackable { lazy var biometricType = LAContext.biometricType() var explanatoryText: String { return biometricType == .touch ? S.TouchIdSettings.explanatoryText : S.FaceIDSettings.explanatoryText } var unlockTitleText: String { return biometricType == .touch ? S.TouchIdSettings.unlockTitleText : S.FaceIDSettings.unlockTitleText } var transactionsTitleText: String { return biometricType == .touch ? S.TouchIdSettings.transactionsTitleText : S.FaceIDSettings.transactionsTitleText } var imageName: String { return biometricType == .touch ? "TouchId-Large" : "FaceId-Large" } private let imageView = UIImageView() private let explanationLabel = UILabel.wrapping(font: Theme.body1, color: Theme.secondaryText) // Toggle for enabling Touch ID or Face ID to unlock the BRD app. private let unlockTitleLabel = UILabel.wrapping(font: Theme.body1, color: Theme.primaryText) // Toggle for enabling Touch ID or Face ID for sending money. private let transactionsTitleLabel = UILabel.wrapping(font: Theme.body1, color: Theme.primaryText) private let unlockToggle = UISwitch() private let transactionsToggle = UISwitch() private let unlockToggleSeparator = UIView() private let transactionsToggleSeparator = UIView() private var hasSetInitialValueForUnlockToggle = false private var hasSetInitialValueForTransactions = false private var walletAuthenticator: WalletAuthenticator init(_ walletAuthenticator: WalletAuthenticator) { self.walletAuthenticator = walletAuthenticator super.init(nibName: nil, bundle: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setWhiteStyle() } override func viewDidLoad() { super.viewDidLoad() [imageView, explanationLabel, unlockTitleLabel, transactionsTitleLabel, unlockToggle, transactionsToggle, unlockToggleSeparator, transactionsToggleSeparator].forEach({ view.addSubview($0) }) setUpAppearance() addConstraints() setData() addFaqButton() } private func setUpAppearance() { view.backgroundColor = Theme.primaryBackground explanationLabel.textAlignment = .center unlockToggleSeparator.backgroundColor = Theme.tertiaryBackground transactionsToggleSeparator.backgroundColor = Theme.tertiaryBackground [unlockTitleLabel, transactionsTitleLabel].forEach({ $0.adjustsFontSizeToFitWidth = true $0.minimumScaleFactor = 0.5 }) } private func addConstraints() { let screenHeight: CGFloat = UIScreen.main.bounds.height let topMarginPercent: CGFloat = 0.08 let imageTopMargin: CGFloat = (screenHeight * topMarginPercent) let leftRightMargin: CGFloat = 40.0 imageView.constrain([ imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor), imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: imageTopMargin) ]) explanationLabel.constrain([ explanationLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: leftRightMargin), explanationLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -leftRightMargin), explanationLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: C.padding[2]) ]) // // unlock BRD toggle and associated labels // unlockTitleLabel.constrain([ unlockTitleLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: C.padding[2]), unlockTitleLabel.rightAnchor.constraint(equalTo: unlockToggle.leftAnchor, constant: -C.padding[2]), unlockTitleLabel.topAnchor.constraint(equalTo: explanationLabel.bottomAnchor, constant: C.padding[5]) ]) unlockToggle.constrain([ unlockToggle.centerYAnchor.constraint(equalTo: unlockTitleLabel.centerYAnchor), unlockToggle.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -C.padding[2]) ]) unlockToggleSeparator.constrain([ unlockToggleSeparator.topAnchor.constraint(equalTo: unlockTitleLabel.bottomAnchor, constant: C.padding[1]), unlockToggleSeparator.leftAnchor.constraint(equalTo: view.leftAnchor), unlockToggleSeparator.rightAnchor.constraint(equalTo: view.rightAnchor), unlockToggleSeparator.heightAnchor.constraint(equalToConstant: 1.0) ]) // // send money toggle and associated labels // transactionsTitleLabel.constrain([ transactionsTitleLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: C.padding[2]), transactionsTitleLabel.rightAnchor.constraint(equalTo: transactionsToggle.leftAnchor, constant: -C.padding[2]), transactionsTitleLabel.topAnchor.constraint(equalTo: unlockTitleLabel.bottomAnchor, constant: C.padding[5]) ]) transactionsToggle.constrain([ transactionsToggle.centerYAnchor.constraint(equalTo: transactionsTitleLabel.centerYAnchor), transactionsToggle.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -C.padding[2]) ]) unlockToggle.setContentCompressionResistancePriority(.required, for: .horizontal) transactionsToggle.setContentCompressionResistancePriority(.required, for: .horizontal) transactionsToggleSeparator.constrain([ transactionsToggleSeparator.topAnchor.constraint(equalTo: transactionsTitleLabel.bottomAnchor, constant: C.padding[1]), transactionsToggleSeparator.leftAnchor.constraint(equalTo: view.leftAnchor), transactionsToggleSeparator.rightAnchor.constraint(equalTo: view.rightAnchor), transactionsToggleSeparator.heightAnchor.constraint(equalToConstant: 1.0) ]) } private func setData() { imageView.image = UIImage(named: imageName) explanationLabel.text = explanatoryText unlockTitleLabel.text = unlockTitleText transactionsTitleLabel.text = transactionsTitleText unlockToggle.isOn = walletAuthenticator.isBiometricsEnabledForUnlocking transactionsToggle.isOn = walletAuthenticator.isBiometricsEnabledForTransactions transactionsToggle.isEnabled = unlockToggle.isOn unlockToggle.valueChanged = { [weak self] in guard let `self` = self else { return } self.toggleChanged(toggle: self.unlockToggle) self.saveEvent("event.enableBiometrics", attributes: ["isEnabled": "\(self.unlockToggle.isOn)", "type": "unlock"]) } transactionsToggle.valueChanged = { [weak self] in guard let `self` = self else { return } self.toggleChanged(toggle: self.transactionsToggle) self.saveEvent("event.enableBiometrics", attributes: ["isEnabled": "\(self.transactionsToggle.isOn)", "type": "sending"]) } } private func toggleChanged(toggle: UISwitch) { if toggle == unlockToggle { // If the unlock toggle is off, the transactions toggle is forced to off and disabled. // i.e., Only allow Touch/Face ID for sending transactions if the user has enabled Touch/Face ID // for unlocking the app. if !toggle.isOn { self.walletAuthenticator.isBiometricsEnabledForUnlocking = false self.walletAuthenticator.isBiometricsEnabledForTransactions = false self.transactionsToggle.setOn(false, animated: true) } else { if LAContext.canUseBiometrics || E.isSimulator { LAContext.checkUserBiometricsAuthorization(callback: { (result) in if result == .success { self.walletAuthenticator.isBiometricsEnabledForUnlocking = true } else { self.unlockToggle.setOn(false, animated: true) } }) } else { self.presentCantUseBiometricsAlert() self.unlockToggle.setOn(false, animated: true) } } self.transactionsToggle.isEnabled = self.unlockToggle.isOn } else if toggle == transactionsToggle { self.walletAuthenticator.isBiometricsEnabledForTransactions = toggle.isOn } } private func addFaqButton() { let negativePadding = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) negativePadding.width = -16.0 let faqButton = UIButton.buildFaqButton(articleId: ArticleIds.enableTouchId) faqButton.tintColor = .white navigationItem.rightBarButtonItems = [negativePadding, UIBarButtonItem(customView: faqButton)] } fileprivate func presentCantUseBiometricsAlert() { let unavailableAlertTitle = LAContext.biometricType() == .face ? S.FaceIDSettings.unavailableAlertTitle : S.TouchIdSettings.unavailableAlertTitle let unavailableAlertMessage = LAContext.biometricType() == .face ? S.FaceIDSettings.unavailableAlertMessage : S.TouchIdSettings.unavailableAlertMessage let alert = UIAlertController(title: unavailableAlertTitle, message: unavailableAlertMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: S.Button.settings, style: .default, handler: { _ in guard let url = URL(string: "App-Prefs:root") else { return } UIApplication.shared.open(url) })) present(alert, animated: true, completion: nil) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
d97c07c770c2fca121143036e2f01f6e
42.374502
159
0.658492
5.532012
false
false
false
false
kidaa/codecombat-ios
CodeCombatTests/DocumentNodeTests.swift
2
2111
// // DocumentNodeTests.swift // CodeCombat // // Created by Michael Schmatz on 8/27/14. // Copyright (c) 2014 CodeCombat. All rights reserved. // import Foundation import XCTest class DocumentNodeTests: XCTestCase { var defaultNode:DocumentNode! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. defaultNode = DocumentNode() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testInitiallyNoChildren() { XCTAssertEqual(defaultNode.children.count, 0, "The number of children of an initialized node should be zero") } func testInitiallyNameEmpty() { XCTAssertEqual(defaultNode.name, "", "The node should have an empty string as the name") } func testInitialRangeNil() { XCTAssertTrue(defaultNode.range.location == 0, "The range should initially be 0") } func testInitialSourceTextNil() { XCTAssertTrue(defaultNode.sourceText == nil, "The sourceText should initially be nil") } func testDefaultNodeDescription() { XCTAssertEqual(defaultNode.description(), "", "The description on an empty node should return an empty string") } func testNonDefaultDescription() { let exampleString:NSString = "This is a test string intended to test some of the functions of DocumentNodes." defaultNode.sourceText = exampleString defaultNode.range = NSRange(location: 0, length: 4) XCTAssertEqual(defaultNode.description(), "0-4: (no name) - Data: \"This\"\n") } func testGetData() { let exampleString:NSString = "Test String" defaultNode.sourceText = exampleString defaultNode.range = NSRange(location: 0, length: 4) XCTAssertEqual(defaultNode.data, "Test", "The data getter should work") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
e45e73dbc00d0a8c25289b510c8eecc9
29.594203
115
0.702984
4.316973
false
true
false
false
scoremedia/Fisticuffs
Tests/FisticuffsTests/UIKitBindingSpec.swift
1
12902
// The MIT License (MIT) // // Copyright (c) 2015 theScore Inc. // // 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 import Quick import Nimble @testable import Fisticuffs class UIKitBindingSpec: QuickSpec { override func spec() { describe("UILabel") { it("should support binding it's text value") { let name = Observable("") let label = UILabel() label.b_text.bind(name) name.value = "Fred" expect(label.text) == "Fred" } } describe("UIControl") { it("should support binding it's enabled value") { let enabled = Observable(false) let control = UIControl() control.b_enabled.bind(enabled) expect(control.isEnabled) == false enabled.value = true expect(control.isEnabled) == true } it("should allow subscribing to arbitrary control events") { var receivedEvent = false let control = UIControl() _ = control.b_controlEvent(.allEvents).subscribe { receivedEvent = true } control.sendActions(for: .editingDidBegin) expect(receivedEvent) == true } } describe("UIButton") { it("should support binding an action for when the user taps") { var receivedTap = false let button = UIButton() _ = button.b_onTap.subscribe { receivedTap = true } button.sendActions(for: .touchUpInside) expect(receivedTap) == true } } describe("UIDatePicker") { it("should support 2 way binding on its text value") { let initial = Date() let value = Observable(initial) let datePicker = UIDatePicker() datePicker.b_date.bind(value) expect(datePicker.date) == initial // pretend the user goes to the next day let tomorrow = initial.addingTimeInterval(24 * 60 * 60) datePicker.date = tomorrow datePicker.sendActions(for: .valueChanged) expect(datePicker.date) == tomorrow expect(value.value) == tomorrow // modify it programmatically let yesterday = initial.addingTimeInterval(-24 * 60 * 60) value.value = yesterday expect(datePicker.date) == yesterday expect(value.value) == yesterday } } describe("UITextField") { it("should support 2 way binding on its text value") { let value = Observable("Hello") let textField = UITextField() textField.b_text.bind(value) expect(textField.text) == "Hello" // pretend the user types " world" textField.text = (textField.text ?? "") + " world" textField.sendActions(for: .editingChanged) expect(textField.text) == "Hello world" expect(value.value) == "Hello world" // modify it programmatically value.value = "Bye" expect(textField.text) == "Bye" expect(value.value) == "Bye" } } describe("UIBarButtonItem") { let barButtonItem = UIBarButtonItem() it("should support taps") { var receivedAction = false let disposable = barButtonItem.b_onTap.subscribe { receivedAction = true } defer { disposable.dispose() } // simulate a tap _ = barButtonItem.target?.perform(barButtonItem.action, with: barButtonItem) expect(receivedAction) == true } it("should support binding it's title") { let title = Observable("Hello") barButtonItem.b_title.bind(title) expect(barButtonItem.title) == "Hello" title.value = "World" expect(barButtonItem.title) == "World" } } describe("UIPageControl") { it("should support binding numberOfPages") { let numberOfPages = Observable(5) let pageControl = UIPageControl() pageControl.b_numberOfPages.bind(numberOfPages) expect(pageControl.numberOfPages) == 5 numberOfPages.value = 11 expect(pageControl.numberOfPages) == 11 } it("should support binding currentPage") { let pageControl = UIPageControl() pageControl.numberOfPages = 11 let currentPage = Observable(2) pageControl.b_currentPage.bind(currentPage) expect(pageControl.currentPage) == 2 pageControl.currentPage += 1 pageControl.sendActions(for: .valueChanged) expect(pageControl.currentPage) == 3 expect(currentPage.value) == 3 currentPage.value = 8 expect(pageControl.currentPage) == 8 expect(currentPage.value) == 8 } } describe("UITableViewCell") { it("should support binding it's accessoryType value") { let accessoryType = Observable(UITableViewCell.AccessoryType.none) let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.b_accessoryType.bind(accessoryType) expect(cell.accessoryType) == UITableViewCell.AccessoryType.none accessoryType.value = .checkmark expect(cell.accessoryType) == UITableViewCell.AccessoryType.checkmark } } describe("UISearchBar") { it("should support 2 way binding on its text value") { let value = Observable("Hello") let searchBar = UISearchBar() searchBar.b_text.bind(value) expect(searchBar.text) == "Hello" // pretend the user types " world" searchBar.text = (searchBar.text ?? "") + " world" searchBar.delegate?.searchBar?(searchBar, textDidChange: searchBar.text!) expect(searchBar.text) == "Hello world" expect(value.value) == "Hello world" // modify it programmatically value.value = "Bye" expect(searchBar.text) == "Bye" expect(value.value) == "Bye" } } describe("UISwitch") { it("should support 2 way binding on its 'on' value") { let on = Observable(false) let toggle = UISwitch() toggle.b_on.bind(on) expect(toggle.isOn) == false // pretend the user toggles switch ON toggle.isOn = true toggle.sendActions(for: .valueChanged) expect(toggle.isOn) == true expect(on.value) == true // modify it programmatically on.value = false expect(toggle.isOn) == false expect(on.value) == false } } describe("UISlider") { it("should support 2 way binding on its 'value' value") { let value = Observable(Float(0.0)) let slider = UISlider() slider.minimumValue = 0.0 slider.maximumValue = 1.0 slider.value = 0.5 slider.b_value.bind(value) expect(slider.value) == 0.0 // pretend the user toggles switch ON slider.value = 0.5 slider.sendActions(for: .valueChanged) expect(slider.value) == 0.5 expect(value.value) == 0.5 // modify it programmatically value.value = 0.25 expect(slider.value) == 0.25 expect(value.value) == 0.25 } } describe("UISegmentedControl") { let items = Observable([1, 2, 3]) let selection = Observable(1) let segmentedControl = UISegmentedControl() segmentedControl.b_configure(items, selection: selection, display: { segmentValue in .title(String(segmentValue)) }) it("should update it's items when its `items` subscription changes") { items.value = [1, 2, 3, 4] let segments = (0..<segmentedControl.numberOfSegments).map { index in segmentedControl.titleForSegment(at: index) } .compactMap { title in title } expect(segments) == ["1", "2", "3", "4"] } it("should keep its selection in sync with the specified `selection` observable") { selection.value = 2 expect(segmentedControl.selectedSegmentIndex) == items.value.firstIndex(of: selection.value) // Simulate the user switching selection segmentedControl.selectedSegmentIndex = 0 segmentedControl.sendActions(for: .valueChanged) expect(selection.value) == items.value.first } } describe("UIAlertAction") { it("should support binding its enabled value") { let enabled = Observable(false) let action = UIAlertAction(title: "Test", style: .default, handler: nil) action.b_enabled.bind(enabled) expect(action.isEnabled) == false enabled.value = true expect(action.isEnabled) == true } } describe("UICollectionView") { it("should not crash when adding/deleting items before the collection view has appeared on screen") { let items = Observable<[Int]>([1, 2, 3]) let reuseIdentifier = "Cell" let frame = CGRect(x: 0, y: 0, width: 320, height: 480) let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout) collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) collectionView.b_configure(items, block: { config in config.useCell(reuseIdentifier: reuseIdentifier) { _, _ in } }) items.value.append(5) } } } }
mit
bf4ca2146c8d825dd69c64570f73664d
36.725146
113
0.49938
5.770125
false
false
false
false
CPRTeam/CCIP-iOS
Pods/CryptoSwift/Sources/CryptoSwift/UInt16+Extension.swift
1
1547
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // /** array of bytes */ extension UInt16 { @_specialize(where T == ArraySlice<UInt8>) init<T: Collection>(bytes: T) where T.Element == UInt8, T.Index == Int { self = UInt16(bytes: bytes, fromIndex: bytes.startIndex) } @_specialize(where T == ArraySlice<UInt8>) init<T: Collection>(bytes: T, fromIndex index: T.Index) where T.Element == UInt8, T.Index == Int { if bytes.isEmpty { self = 0 return } let count = bytes.count let val0 = count > 0 ? UInt16(bytes[index.advanced(by: 0)]) << 8 : 0 let val1 = count > 1 ? UInt16(bytes[index.advanced(by: 1)]) : 0 self = val0 | val1 } }
gpl-3.0
819c8ef48788bbf8315fe6877ee77a83
40.783784
217
0.704398
3.933842
false
false
false
false
iOSTestApps/firefox-ios
Client/Frontend/Browser/Browser.swift
5
11755
/* 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 WebKit import Storage import Shared protocol BrowserHelper { static func name() -> String func scriptMessageHandlerName() -> String? func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) } @objc protocol BrowserDelegate { func browser(browser: Browser, didAddSnackbar bar: SnackBar) func browser(browser: Browser, didRemoveSnackbar bar: SnackBar) optional func browser(browser: Browser, didCreateWebView webView: WKWebView) optional func browser(browser: Browser, willDeleteWebView webView: WKWebView) } class Browser: NSObject { var webView: WKWebView? = nil var browserDelegate: BrowserDelegate? = nil var bars = [SnackBar]() var favicons = [Favicon]() var sessionData: SessionData? var screenshot: UIImage? private var helperManager: HelperManager? = nil var lastRequest: NSURLRequest? = nil private var configuration: WKWebViewConfiguration? = nil init(configuration: WKWebViewConfiguration) { self.configuration = configuration } class func toTab(browser: Browser) -> RemoteTab? { if let displayURL = browser.displayURL { let history = browser.historyList.filter(RemoteTab.shouldIncludeURL).reverse() return RemoteTab(clientGUID: nil, URL: displayURL, title: browser.displayTitle, history: history, lastUsed: NSDate.now(), icon: nil) } return nil } weak var navigationDelegate: WKNavigationDelegate? { didSet { if let webView = webView { webView.navigationDelegate = navigationDelegate } } } func createWebview() { if webView == nil { assert(configuration != nil, "Create webview can only be called once") configuration!.userContentController = WKUserContentController() configuration!.preferences = WKPreferences() configuration!.preferences.javaScriptCanOpenWindowsAutomatically = false let webView = WKWebView(frame: CGRectZero, configuration: configuration!) configuration = nil webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.allowsBackForwardNavigationGestures = true webView.backgroundColor = UIColor.lightGrayColor() // Turning off masking allows the web content to flow outside of the scrollView's frame // which allows the content appear beneath the toolbars in the BrowserViewController webView.scrollView.layer.masksToBounds = false webView.navigationDelegate = navigationDelegate helperManager = HelperManager(webView: webView) // Pulls restored session data from a previous SavedTab to load into the Browser. If it's nil, a session restore // has already been triggered via custom URL, so we use the last request to trigger it again; otherwise, // we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL // to trigger the session restore via custom handlers if let sessionData = self.sessionData { var updatedURLs = [String]() for url in sessionData.urls { let updatedURL = WebServer.sharedInstance.updateLocalURL(url)!.absoluteString! updatedURLs.append(updatedURL) } let currentPage = sessionData.currentPage self.sessionData = nil var jsonDict = [String: AnyObject]() jsonDict["history"] = updatedURLs jsonDict["currentPage"] = currentPage let escapedJSON = JSON.stringify(jsonDict, pretty: false).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! let restoreURL = NSURL(string: "\(WebServer.sharedInstance.base)/about/sessionrestore?history=\(escapedJSON)") webView.loadRequest(NSURLRequest(URL: restoreURL!)) } else if let request = lastRequest { webView.loadRequest(request) } self.webView = webView browserDelegate?.browser?(self, didCreateWebView: webView) } } deinit { if let webView = webView { browserDelegate?.browser?(self, willDeleteWebView: webView) } } var loading: Bool { return webView?.loading ?? false } var estimatedProgress: Double { return webView?.estimatedProgress ?? 0 } var backList: [WKBackForwardListItem]? { return webView?.backForwardList.backList as? [WKBackForwardListItem] } var forwardList: [WKBackForwardListItem]? { return webView?.backForwardList.forwardList as? [WKBackForwardListItem] } var historyList: [NSURL] { func listToUrl(item: WKBackForwardListItem) -> NSURL { return item.URL } var tabs = self.backList?.map(listToUrl) ?? [NSURL]() tabs.append(self.url!) return tabs } var title: String? { return webView?.title } var displayTitle: String { if let title = webView?.title { if !title.isEmpty { return title } } return displayURL?.absoluteString ?? "" } var displayFavicon: Favicon? { var width = 0 var largest: Favicon? for icon in favicons { if icon.width > width { width = icon.width! largest = icon } } return largest } var url: NSURL? { return webView?.URL ?? lastRequest?.URL } var displayURL: NSURL? { if let url = webView?.URL ?? lastRequest?.URL { if ReaderModeUtils.isReaderModeURL(url) { return ReaderModeUtils.decodeURL(url) } if ErrorPageHelper.isErrorPageURL(url) { let decodedURL = ErrorPageHelper.decodeURL(url) if !AboutUtils.isAboutURL(decodedURL) { return decodedURL } else { return nil } } if !AboutUtils.isAboutURL(url) { return url } } return nil } var canGoBack: Bool { return webView?.canGoBack ?? false } var canGoForward: Bool { return webView?.canGoForward ?? false } func goBack() { webView?.goBack() } func goForward() { webView?.goForward() } func goToBackForwardListItem(item: WKBackForwardListItem) { webView?.goToBackForwardListItem(item) } func loadRequest(request: NSURLRequest) -> WKNavigation? { lastRequest = request if let webView = webView { return webView.loadRequest(request) } return nil } func stop() { webView?.stopLoading() } func reload() { webView?.reload() } func addHelper(helper: BrowserHelper, name: String) { helperManager!.addHelper(helper, name: name) } func getHelper(#name: String) -> BrowserHelper? { return helperManager?.getHelper(name: name) } func hideContent(animated: Bool = false) { webView?.userInteractionEnabled = false if animated { UIView.animateWithDuration(0.25, animations: { () -> Void in self.webView?.alpha = 0.0 }) } else { webView?.alpha = 0.0 } } func showContent(animated: Bool = false) { webView?.userInteractionEnabled = true if animated { UIView.animateWithDuration(0.25, animations: { () -> Void in self.webView?.alpha = 1.0 }) } else { webView?.alpha = 1.0 } } func addSnackbar(bar: SnackBar) { bars.append(bar) browserDelegate?.browser(self, didAddSnackbar: bar) } func removeSnackbar(bar: SnackBar) { if let index = find(bars, bar) { bars.removeAtIndex(index) browserDelegate?.browser(self, didRemoveSnackbar: bar) } } func removeAllSnackbars() { // Enumerate backwards here because we'll remove items from the list as we go. for var i = bars.count-1; i >= 0; i-- { let bar = bars[i] removeSnackbar(bar) } } func expireSnackbars() { // Enumerate backwards here because we may remove items from the list as we go. for var i = bars.count-1; i >= 0; i-- { let bar = bars[i] if !bar.shouldPersist(self) { removeSnackbar(bar) } } } } private class HelperManager: NSObject, WKScriptMessageHandler { private var helpers = [String: BrowserHelper]() private weak var webView: WKWebView? init(webView: WKWebView) { self.webView = webView } @objc func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { for helper in helpers.values { if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { if scriptMessageHandlerName == message.name { helper.userContentController(userContentController, didReceiveScriptMessage: message) return } } } } func addHelper(helper: BrowserHelper, name: String) { if let existingHelper = helpers[name] { assertionFailure("Duplicate helper added: \(name)") } helpers[name] = helper // If this helper handles script messages, then get the handler name and register it. The Browser // receives all messages and then dispatches them to the right BrowserHelper. if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { webView?.configuration.userContentController.addScriptMessageHandler(self, name: scriptMessageHandlerName) } } func getHelper(#name: String) -> BrowserHelper? { return helpers[name] } } extension WKWebView { func runScriptFunction(function: String, fromScript: String, callback: (AnyObject?) -> Void) { if let path = NSBundle.mainBundle().pathForResource(fromScript, ofType: "js") { if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String { evaluateJavaScript(source, completionHandler: { (obj, err) -> Void in if let err = err { println("Error injecting \(err)") return } self.evaluateJavaScript("__firefox__.\(fromScript).\(function)", completionHandler: { (obj, err) -> Void in self.evaluateJavaScript("delete window.__firefox__.\(fromScript)", completionHandler: { (obj, err) -> Void in }) if let err = err { println("Error running \(err)") return } callback(obj) }) }) } } } }
mpl-2.0
d897b259385565145e44314320bc888a
33.072464
171
0.598979
5.498129
false
false
false
false
benlangmuir/swift
test/Interop/Cxx/operators/non-member-inline-typechecker.swift
3
1091
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-experimental-cxx-interop import NonMemberInline let lhs = LoadableIntWrapper(value: 42) let rhs = LoadableIntWrapper(value: 23) let resultPlus = lhs + rhs let resultMinus = lhs - rhs let resultStar = lhs * rhs let resultSlash = lhs / rhs let resultPercent = lhs % rhs let resultCaret = lhs ^ rhs let resultAmp = lhs & rhs let resultPipe = lhs | rhs let resultLessLess = lhs << rhs let resultGreaterGreater = lhs >> rhs let resultLess = lhs < rhs let resultGreater = lhs > rhs let resultEqualEqual = lhs == rhs let resultExclaimEqual = lhs != rhs let resultLessEqual = lhs <= rhs let resultGreaterEqual = lhs >= rhs public func ==(ptr: UnsafePointer<UInt8>, count: Int) -> Bool { let lhs = UnsafeBufferPointer<UInt8>(start: ptr, count: count) let rhs = UnsafeBufferPointer<UInt8>(start: ptr, count: count) return lhs.elementsEqual(rhs, by: ==) } var lhsBool = LoadableBoolWrapper(value: true) var rhsBool = LoadableBoolWrapper(value: false) let resultAmpAmp = lhsBool && rhsBool let resultPipePipe = lhsBool && rhsBool
apache-2.0
7a93ee9939094d6c57745f5b096c58b1
29.305556
84
0.736939
3.577049
false
false
false
false
SuPair/firefox-ios
Sync/StorageClient.swift
1
32087
/* 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 Alamofire import Shared import Account import XCGLogger import Deferred import SwiftyJSON private let log = Logger.syncLogger // Not an error that indicates a server problem, but merely an // error that encloses a StorageResponse. open class StorageResponseError<T>: MaybeErrorType, SyncPingFailureFormattable { open let response: StorageResponse<T> open var failureReasonName: SyncPingFailureReasonName { return .httpError } public init(_ response: StorageResponse<T>) { self.response = response } open var description: String { return "Error." } } open class RequestError: MaybeErrorType, SyncPingFailureFormattable { open var failureReasonName: SyncPingFailureReasonName { return .httpError } open var description: String { return "Request error." } } open class BadRequestError<T>: StorageResponseError<T> { open let request: URLRequest? public init(request: URLRequest?, response: StorageResponse<T>) { self.request = request super.init(response) } override open var description: String { return "Bad request." } } open class ServerError<T>: StorageResponseError<T> { override open var description: String { return "Server error." } override public init(_ response: StorageResponse<T>) { super.init(response) } } open class NotFound<T>: StorageResponseError<T> { override open var description: String { return "Not found. (\(T.self))" } override public init(_ response: StorageResponse<T>) { super.init(response) } } open class RecordParseError: MaybeErrorType, SyncPingFailureFormattable { open var description: String { return "Failed to parse record." } open var failureReasonName: SyncPingFailureReasonName { return .otherError } } open class MalformedMetaGlobalError: MaybeErrorType, SyncPingFailureFormattable { open var description: String { return "Supplied meta/global for upload did not serialize to valid JSON." } open var failureReasonName: SyncPingFailureReasonName { return .otherError } } open class RecordTooLargeError: MaybeErrorType, SyncPingFailureFormattable { open let guid: GUID open let size: ByteCount open var failureReasonName: SyncPingFailureReasonName { return .otherError } public init(size: ByteCount, guid: GUID) { self.size = size self.guid = guid } open var description: String { return "Record \(self.guid) too large: \(size) bytes." } } /** * Raised when the storage client is refusing to make a request due to a known * server backoff. * If you want to bypass this, remove the backoff from the BackoffStorage that * the storage client is using. */ open class ServerInBackoffError: MaybeErrorType, SyncPingFailureFormattable { fileprivate let until: Timestamp open var failureReasonName: SyncPingFailureReasonName { return .otherError } open var description: String { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .medium let s = formatter.string(from: Date.fromTimestamp(self.until)) return "Server in backoff until \(s)." } public init(until: Timestamp) { self.until = until } } // Returns milliseconds. Handles decimals. private func optionalSecondsHeader(_ input: AnyObject?) -> Timestamp? { if input == nil { return nil } if let val = input as? String { if let timestamp = decimalSecondsStringToTimestamp(val) { return timestamp } } if let seconds: Double = input as? Double { // Oh for a BigDecimal library. return Timestamp(seconds * 1000) } if let seconds: NSNumber = input as? NSNumber { // Who knows. return seconds.uint64Value * 1000 } return nil } private func optionalIntegerHeader(_ input: AnyObject?) -> Int64? { if input == nil { return nil } if let val = input as? String { return Scanner(string: val).scanLongLong() } if let val: Double = input as? Double { // Oh for a BigDecimal library. return Int64(val) } if let val: NSNumber = input as? NSNumber { // Who knows. return val.int64Value } return nil } private func optionalUIntegerHeader(_ input: AnyObject?) -> Timestamp? { if input == nil { return nil } if let val = input as? String { return Scanner(string: val).scanUnsignedLongLong() } if let val: Double = input as? Double { // Oh for a BigDecimal library. return Timestamp(val) } if let val: NSNumber = input as? NSNumber { // Who knows. return val.uint64Value } return nil } public enum SortOption: String { case NewestFirst = "newest" case OldestFirst = "oldest" case Index = "index" } public struct ResponseMetadata { public let status: Int public let alert: String? public let nextOffset: String? public let records: UInt64? public let quotaRemaining: Int64? public let timestampMilliseconds: Timestamp // Non-optional. Server timestamp when handling request. public let lastModifiedMilliseconds: Timestamp? // Included for all success responses. Collection or record timestamp. public let backoffMilliseconds: UInt64? public let retryAfterMilliseconds: UInt64? public init(response: HTTPURLResponse) { self.init(status: response.statusCode, headers: response.allHeaderFields) } init(status: Int, headers: [AnyHashable: Any]) { self.status = status alert = headers["X-Weave-Alert"] as? String nextOffset = headers["X-Weave-Next-Offset"] as? String records = optionalUIntegerHeader(headers["X-Weave-Records"] as AnyObject?) quotaRemaining = optionalIntegerHeader(headers["X-Weave-Quota-Remaining"] as AnyObject?) timestampMilliseconds = optionalSecondsHeader(headers["X-Weave-Timestamp"] as AnyObject?) ?? 0 lastModifiedMilliseconds = optionalSecondsHeader(headers["X-Last-Modified"] as AnyObject?) backoffMilliseconds = optionalSecondsHeader(headers["X-Weave-Backoff"] as AnyObject?) ?? optionalSecondsHeader(headers["X-Backoff"] as AnyObject?) retryAfterMilliseconds = optionalSecondsHeader(headers["Retry-After"] as AnyObject?) } } public struct StorageResponse<T> { public let value: T public let metadata: ResponseMetadata init(value: T, metadata: ResponseMetadata) { self.value = value self.metadata = metadata } init(value: T, response: HTTPURLResponse) { self.value = value self.metadata = ResponseMetadata(response: response) } } public typealias BatchToken = String public typealias ByteCount = Int public struct POSTResult { public let success: [GUID] public let failed: [GUID: String] public let batchToken: BatchToken? public init(success: [GUID], failed: [GUID: String], batchToken: BatchToken? = nil) { self.success = success self.failed = failed self.batchToken = batchToken } public static func fromJSON(_ json: JSON) -> POSTResult? { if json.isError() { return nil } let batchToken = json["batch"].string if let s = json["success"].array, let f = json["failed"].dictionary { var failed = false let stringOrFail: (JSON) -> String = { $0.string ?? { failed = true; return "" }() } // That's the basic structure. Now let's transform the contents. let successGUIDs = s.map(stringOrFail) if failed { return nil } let failedGUIDs = mapValues(f, f: stringOrFail) if failed { return nil } return POSTResult(success: successGUIDs, failed: failedGUIDs, batchToken: batchToken) } return nil } } public typealias Authorizer = (URLRequest) -> URLRequest // TODO: don't be so naïve. Use a combination of uptime and wall clock time. public protocol BackoffStorage { var serverBackoffUntilLocalTimestamp: Timestamp? { get set } func clearServerBackoff() func isInBackoff(_ now: Timestamp) -> Timestamp? // Returns 'until' for convenience. } // Don't forget to batch downloads. open class Sync15StorageClient { fileprivate let authorizer: Authorizer fileprivate let serverURI: URL open static let maxRecordSizeBytes: Int = 262_140 // A shade under 256KB. open static let maxPayloadSizeBytes: Int = 1_000_000 // A shade under 1MB. open static let maxPayloadItemCount: Int = 100 // Bug 1250747 will raise this. var backoff: BackoffStorage let workQueue: DispatchQueue let resultQueue: DispatchQueue public init(token: TokenServerToken, workQueue: DispatchQueue, resultQueue: DispatchQueue, backoff: BackoffStorage) { self.workQueue = workQueue self.resultQueue = resultQueue self.backoff = backoff // This is a potentially dangerous assumption, but failable initializers up the stack are a giant pain. // We want the serverURI to *not* have a trailing slash: to efficiently wipe a user's storage, we delete // the user root (like /1.5/1234567) and not an "empty collection" (like /1.5/1234567/); the storage // server treats the first like a DROP table and the latter like a DELETE *, and the former is more // efficient than the latter. self.serverURI = URL(string: token.api_endpoint.hasSuffix("/") ? String(token.api_endpoint[..<token.api_endpoint.index(before: token.api_endpoint.endIndex)]) : token.api_endpoint)! self.authorizer = { (r: URLRequest) -> URLRequest in var req = r let helper = HawkHelper(id: token.id, key: token.key.data(using: .utf8, allowLossyConversion: false)!) req.setValue(helper.getAuthorizationValueFor(r), forHTTPHeaderField: "Authorization") return req } } public init(serverURI: URL, authorizer: @escaping Authorizer, workQueue: DispatchQueue, resultQueue: DispatchQueue, backoff: BackoffStorage) { self.serverURI = serverURI self.authorizer = authorizer self.workQueue = workQueue self.resultQueue = resultQueue self.backoff = backoff } func updateBackoffFromResponse<T>(_ response: StorageResponse<T>) { // N.B., we would not have made this request if a backoff were set, so // we can safely avoid doing the write if there's no backoff in the // response. // This logic will have to change if we ever invalidate that assumption. if let ms = response.metadata.backoffMilliseconds ?? response.metadata.retryAfterMilliseconds { log.info("Backing off for \(ms)ms.") self.backoff.serverBackoffUntilLocalTimestamp = ms + Date.now() } } func errorWrap<T, U>(_ deferred: Deferred<Maybe<T>>, handler: @escaping (DataResponse<U>) -> Void) -> (DataResponse<U>) -> Void { return { response in log.verbose("Response is \(response.response ??? "nil").") /** * Returns true if handled. */ func failFromResponse(_ HTTPResponse: HTTPURLResponse?) -> Bool { guard let HTTPResponse = HTTPResponse else { // TODO: better error. log.error("No response") let result = Maybe<T>(failure: RecordParseError()) deferred.fill(result) return true } log.debug("Status code: \(HTTPResponse.statusCode).") let storageResponse = StorageResponse(value: HTTPResponse, metadata: ResponseMetadata(response: HTTPResponse)) self.updateBackoffFromResponse(storageResponse) if HTTPResponse.statusCode >= 500 { log.debug("ServerError.") let result = Maybe<T>(failure: ServerError(storageResponse)) deferred.fill(result) return true } if HTTPResponse.statusCode == 404 { log.debug("NotFound<\(T.self)>.") let result = Maybe<T>(failure: NotFound(storageResponse)) deferred.fill(result) return true } if HTTPResponse.statusCode >= 400 { log.debug("BadRequestError.") let result = Maybe<T>(failure: BadRequestError(request: response.request, response: storageResponse)) deferred.fill(result) return true } return false } // Check for an error from the request processor. if response.result.isFailure { log.error("Response: \(response.response?.statusCode ?? 0). Got error \(response.result.error ??? "nil").") // If we got one, we don't want to hit the response nil case above and // return a RecordParseError, because a RequestError is more fitting. if let response = response.response { if failFromResponse(response) { log.error("This was a failure response. Filled specific error type.") return } } log.error("Filling generic RequestError.") deferred.fill(Maybe<T>(failure: RequestError())) return } if failFromResponse(response.response) { return } handler(response) } } lazy fileprivate var alamofire: SessionManager = { let ua = UserAgent.syncUserAgent let configuration = URLSessionConfiguration.ephemeral var defaultHeaders = SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:] defaultHeaders["User-Agent"] = ua configuration.httpAdditionalHeaders = defaultHeaders return SessionManager(configuration: configuration) }() func requestGET(_ url: URL) -> DataRequest { var req = URLRequest(url: url as URL) req.httpMethod = URLRequest.Method.get.rawValue req.setValue("application/json", forHTTPHeaderField: "Accept") let authorized: URLRequest = self.authorizer(req) return alamofire.request(authorized) .validate(contentType: ["application/json"]) } func requestDELETE(_ url: URL) -> DataRequest { var req = URLRequest(url: url as URL) req.httpMethod = URLRequest.Method.delete.rawValue req.setValue("1", forHTTPHeaderField: "X-Confirm-Delete") let authorized: URLRequest = self.authorizer(req) return alamofire.request(authorized) } func requestWrite(_ url: URL, method: String, body: String, contentType: String, ifUnmodifiedSince: Timestamp?) -> Request { var req = URLRequest(url: url as URL) req.httpMethod = method req.setValue(contentType, forHTTPHeaderField: "Content-Type") if let ifUnmodifiedSince = ifUnmodifiedSince { req.setValue(millisecondsToDecimalSeconds(ifUnmodifiedSince), forHTTPHeaderField: "X-If-Unmodified-Since") } req.httpBody = body.data(using: .utf8)! let authorized: URLRequest = self.authorizer(req) return alamofire.request(authorized) } func requestPUT(_ url: URL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request { return self.requestWrite(url, method: URLRequest.Method.put.rawValue, body: body.stringify()!, contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince) } func requestPOST(_ url: URL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request { return self.requestWrite(url, method: URLRequest.Method.post.rawValue, body: body.stringify()!, contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince) } func requestPOST(_ url: URL, body: [String], ifUnmodifiedSince: Timestamp?) -> Request { let content = body.joined(separator: "\n") return self.requestWrite(url, method: URLRequest.Method.post.rawValue, body: content, contentType: "application/newlines", ifUnmodifiedSince: ifUnmodifiedSince) } func requestPOST(_ url: URL, body: [JSON], ifUnmodifiedSince: Timestamp?) -> Request { return self.requestPOST(url, body: body.map { $0.stringify()! }, ifUnmodifiedSince: ifUnmodifiedSince) } /** * Returns true and fills the provided Deferred if our state shows that we're in backoff. * Returns false otherwise. */ fileprivate func checkBackoff<T>(_ deferred: Deferred<Maybe<T>>) -> Bool { if let until = self.backoff.isInBackoff(Date.now()) { deferred.fill(Maybe<T>(failure: ServerInBackoffError(until: until))) return true } return false } fileprivate func doOp<T>(_ op: (URL) -> DataRequest, path: String, f: @escaping (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> { let deferred = Deferred<Maybe<StorageResponse<T>>>(defaultQueue: self.resultQueue) if self.checkBackoff(deferred) { return deferred } // Special case "": we want /1.5/1234567 and not /1.5/1234567/. See note about trailing slashes above. let url: URL if path == "" { url = self.serverURI // No trailing slash. } else { url = self.serverURI.appendingPathComponent(path) } let req = op(url) let handler = self.errorWrap(deferred) { (response: DataResponse<JSON>) in if let json: JSON = response.result.value { if let v = f(json) { let storageResponse = StorageResponse<T>(value: v, response: response.response!) deferred.fill(Maybe(success: storageResponse)) } else { deferred.fill(Maybe(failure: RecordParseError())) } return } deferred.fill(Maybe(failure: RecordParseError())) } _ = req.responseParsedJSON(true, completionHandler: handler) return deferred } // Sync storage responds with a plain timestamp to a PUT, not with a JSON body. fileprivate func putResource<T>(_ path: String, body: JSON, ifUnmodifiedSince: Timestamp?, parser: @escaping (String) -> T?) -> Deferred<Maybe<StorageResponse<T>>> { let url = self.serverURI.appendingPathComponent(path) return self.putResource(url, body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: parser) } fileprivate func putResource<T>(_ URL: Foundation.URL, body: JSON, ifUnmodifiedSince: Timestamp?, parser: @escaping (String) -> T?) -> Deferred<Maybe<StorageResponse<T>>> { let deferred = Deferred<Maybe<StorageResponse<T>>>(defaultQueue: self.resultQueue) if self.checkBackoff(deferred) { return deferred } let req = self.requestPUT(URL, body: body, ifUnmodifiedSince: ifUnmodifiedSince) as! DataRequest let handler = self.errorWrap(deferred) { (response: DataResponse<String>) in if let data = response.result.value { if let v = parser(data) { let storageResponse = StorageResponse<T>(value: v, response: response.response!) deferred.fill(Maybe(success: storageResponse)) } else { deferred.fill(Maybe(failure: RecordParseError())) } return } deferred.fill(Maybe(failure: RecordParseError())) } req.responseString(completionHandler: handler) return deferred } fileprivate func getResource<T>(_ path: String, f: @escaping (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> { return doOp(self.requestGET, path: path, f: f) } fileprivate func deleteResource<T>(_ path: String, f: @escaping (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> { return doOp(self.requestDELETE, path: path, f: f) } func wipeStorage() -> Deferred<Maybe<StorageResponse<JSON>>> { // In Sync 1.5 it's preferred that we delete the root, not /storage. return deleteResource("", f: { $0 }) } func getInfoCollections() -> Deferred<Maybe<StorageResponse<InfoCollections>>> { return getResource("info/collections", f: InfoCollections.fromJSON) } func getMetaGlobal() -> Deferred<Maybe<StorageResponse<MetaGlobal>>> { return getResource("storage/meta/global") { json in // We have an envelope. Parse the meta/global record embedded in the 'payload' string. let envelope = EnvelopeJSON(json) if envelope.isValid() { return MetaGlobal.fromJSON(JSON(parseJSON: envelope.payload)) } return nil } } func getCryptoKeys(_ syncKeyBundle: KeyBundle, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Record<KeysPayload>>>> { let syncKey = Keys(defaultBundle: syncKeyBundle) let encoder = RecordEncoder<KeysPayload>(decode: { KeysPayload($0) }, encode: { $0.json }) let encrypter = syncKey.encrypter("keys", encoder: encoder) let client = self.clientForCollection("crypto", encrypter: encrypter) return client.get("keys") } func uploadMetaGlobal(_ metaGlobal: MetaGlobal, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> { let payload = metaGlobal.asPayload() if payload.json.isError() { return Deferred(value: Maybe(failure: MalformedMetaGlobalError())) } let record: JSON = JSON(["payload": payload.json.stringify() ?? JSON.null as Any, "id": "global"]) return putResource("storage/meta/global", body: record, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp) } // The crypto/keys record is a special snowflake: it is encrypted with the Sync key bundle. All other records are // encrypted with the bulk key bundle (including possibly a per-collection bulk key) stored in crypto/keys. func uploadCryptoKeys(_ keys: Keys, withSyncKeyBundle syncKeyBundle: KeyBundle, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> { let syncKey = Keys(defaultBundle: syncKeyBundle) let encoder = RecordEncoder<KeysPayload>(decode: { KeysPayload($0) }, encode: { $0.json }) let encrypter = syncKey.encrypter("keys", encoder: encoder) let client = self.clientForCollection("crypto", encrypter: encrypter) let record = Record(id: "keys", payload: keys.asPayload()) return client.put(record, ifUnmodifiedSince: ifUnmodifiedSince) } // It would be convenient to have the storage client manage Keys, but of course we need to use a different set of // keys to fetch crypto/keys itself. See uploadCryptoKeys. func clientForCollection<T>(_ collection: String, encrypter: RecordEncrypter<T>) -> Sync15CollectionClient<T> { let storage = self.serverURI.appendingPathComponent("storage", isDirectory: true) return Sync15CollectionClient(client: self, serverURI: storage, collection: collection, encrypter: encrypter) } } private let DefaultInfoConfiguration = InfoConfiguration(maxRequestBytes: 1_048_576, maxPostRecords: 100, maxPostBytes: 1_048_576, maxTotalRecords: 10_000, maxTotalBytes: 104_857_600) /** * We'd love to nest this in the overall storage client, but Swift * forbids the nesting of a generic class inside another class. */ open class Sync15CollectionClient<T: CleartextPayloadJSON> { fileprivate let client: Sync15StorageClient fileprivate let encrypter: RecordEncrypter<T> fileprivate let collectionURI: URL fileprivate let collectionQueue = DispatchQueue(label: "com.mozilla.sync.collectionclient", attributes: []) fileprivate let infoConfig = DefaultInfoConfiguration public init(client: Sync15StorageClient, serverURI: URL, collection: String, encrypter: RecordEncrypter<T>) { self.client = client self.encrypter = encrypter self.collectionURI = serverURI.appendingPathComponent(collection, isDirectory: false) } var maxBatchPostRecords: Int { get { return infoConfig.maxPostRecords } } fileprivate func uriForRecord(_ guid: String) -> URL { return self.collectionURI.appendingPathComponent(guid) } open func newBatch(ifUnmodifiedSince: Timestamp? = nil, onCollectionUploaded: @escaping (POSTResult, Timestamp?) -> DeferredTimestamp) -> Sync15BatchClient<T> { return Sync15BatchClient(config: infoConfig, ifUnmodifiedSince: ifUnmodifiedSince, serializeRecord: self.serializeRecord, uploader: self.post, onCollectionUploaded: onCollectionUploaded) } // Exposed so we can batch by size. open func serializeRecord(_ record: Record<T>) -> String? { return self.encrypter.serializer(record)?.stringify() } open func post(_ lines: [String], ifUnmodifiedSince: Timestamp?, queryParams: [URLQueryItem]? = nil) -> Deferred<Maybe<StorageResponse<POSTResult>>> { let deferred = Deferred<Maybe<StorageResponse<POSTResult>>>(defaultQueue: client.resultQueue) if self.client.checkBackoff(deferred) { return deferred } let requestURI: URL if let queryParams = queryParams { requestURI = self.collectionURI.withQueryParams(queryParams) } else { requestURI = self.collectionURI } let req = client.requestPOST(requestURI, body: lines, ifUnmodifiedSince: ifUnmodifiedSince) as! DataRequest _ = req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (response: DataResponse<JSON>) in if let json: JSON = response.result.value, let result = POSTResult.fromJSON(json) { let storageResponse = StorageResponse(value: result, response: response.response!) deferred.fill(Maybe(success: storageResponse)) return } else { log.warning("Couldn't parse JSON response.") } deferred.fill(Maybe(failure: RecordParseError())) }) return deferred } open func post(_ records: [Record<T>], ifUnmodifiedSince: Timestamp?, queryParams: [URLQueryItem]? = nil) -> Deferred<Maybe<StorageResponse<POSTResult>>> { // TODO: charset // TODO: if any of these fail, we should do _something_. Right now we just ignore them. let lines = optFilter(records.map(self.serializeRecord)) return self.post(lines, ifUnmodifiedSince: ifUnmodifiedSince, queryParams: queryParams) } open func put(_ record: Record<T>, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> { if let body = self.encrypter.serializer(record) { return self.client.putResource(uriForRecord(record.id), body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp) } return deferMaybe(RecordParseError()) } open func get(_ guid: String) -> Deferred<Maybe<StorageResponse<Record<T>>>> { let deferred = Deferred<Maybe<StorageResponse<Record<T>>>>(defaultQueue: client.resultQueue) if self.client.checkBackoff(deferred) { return deferred } let req = client.requestGET(uriForRecord(guid)) _ = req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (response: DataResponse<JSON>) in if let json: JSON = response.result.value { let envelope = EnvelopeJSON(json) let record = Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory) if let record = record { let storageResponse = StorageResponse(value: record, response: response.response!) deferred.fill(Maybe(success: storageResponse)) return } } else { log.warning("Couldn't parse JSON response.") } deferred.fill(Maybe(failure: RecordParseError())) }) return deferred } /** * Unlike every other Sync client, we use the application/json format for fetching * multiple requests. The others use application/newlines. We don't want to write * another Serializer, and we're loading everything into memory anyway. * * It is the caller's responsibility to check whether the returned payloads are invalid. * * Only non-JSON and malformed envelopes will be dropped. */ open func getSince(_ since: Timestamp, sort: SortOption?=nil, limit: Int?=nil, offset: String?=nil) -> Deferred<Maybe<StorageResponse<[Record<T>]>>> { let deferred = Deferred<Maybe<StorageResponse<[Record<T>]>>>(defaultQueue: client.resultQueue) // Fills the Deferred for us. if self.client.checkBackoff(deferred) { return deferred } var params: [URLQueryItem] = [ URLQueryItem(name: "full", value: "1"), URLQueryItem(name: "newer", value: millisecondsToDecimalSeconds(since)), ] if let offset = offset { params.append(URLQueryItem(name: "offset", value: offset)) } if let limit = limit { params.append(URLQueryItem(name: "limit", value: "\(limit)")) } if let sort = sort { params.append(URLQueryItem(name: "sort", value: sort.rawValue)) } log.debug("Issuing GET with newer = \(since), offset = \(offset ??? "nil"), sort = \(sort ??? "nil").") let req = client.requestGET(self.collectionURI.withQueryParams(params)) _ = req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (response: DataResponse<JSON>) in log.verbose("Response is \(response).") guard let json: JSON = response.result.value else { log.warning("Non-JSON response.") deferred.fill(Maybe(failure: RecordParseError())) return } guard let arr = json.array else { log.warning("Non-array response.") deferred.fill(Maybe(failure: RecordParseError())) return } func recordify(_ json: JSON) -> Record<T>? { let envelope = EnvelopeJSON(json) return Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory) } let records = arr.compactMap(recordify) let response = StorageResponse(value: records, response: response.response!) deferred.fill(Maybe(success: response)) }) return deferred } }
mpl-2.0
a01038f7a13e87bd0a44a534706422c4
38.081608
188
0.63442
4.865939
false
false
false
false
swimmath27/GameOfGames
GameOfGames/Pojos/Game.swift
1
11658
// // Game.swift // GameOfGames // // Created by Michael Lombardo on 5/31/16. // Copyright © 2016 Michael Lombardo. All rights reserved. // import Foundation //import UIKit class Game { ///////////////////// game constants ////////////////////// internal static let MIN_PLAYER_COUNT = 6; internal static let MAX_PLAYER_COUNT = 14; internal static let NUM_CARDS_TO_WIN = 20; internal static let RULEBOOK_URL = "http://nathanand.co/wp-content/uploads/2016/05/The-Game-of-Games-Rulebook.pdf"; /////////////////////////////////////////////////////////// fileprivate(set) static var instance: Game = Game(); fileprivate var deck: Deck = Deck.singleton; fileprivate var numPlayers = 0; fileprivate var currentTurn = 0; fileprivate var currentCard: Card = Card(suit: Card.Suit.joke,rank: 0); fileprivate var team1:[Int] = [Int]() fileprivate var team2:[Int] = [Int]() fileprivate var team1Name:String = "" fileprivate var team2Name:String = "" fileprivate var playerOrder:[Int] = [Int]() fileprivate var players:[Player] = [Player]() fileprivate var whichTeamGoesFirst:Int = 1; // team 1 goes first by default but this is changed later fileprivate var team1CardsWon:[Card] = [Card]() fileprivate var team2CardsWon:[Card] = [Card]() fileprivate var team1CardsPerRound:[Int] = [Int]() fileprivate var team2CardsPerRound:[Int] = [Int]() fileprivate var quickStarted = false; fileprivate(set) var team1Score: Int = 0 fileprivate(set) var team2Score: Int = 0 //uh... "internal" means public? internal var messageTitle:String = ""; internal var message:String = ""; internal var readyToGo:Bool = false; fileprivate init() { } class func load(_ completion: ()->()) { } class func getInstance() -> Game { return instance; } func getOrderedCards() -> [Card] { return self.deck.deck; } func setNumPlayers(_ num: Int) { self.numPlayers = num; players = [Player](repeating: Player(""), count: num); self.playerOrder = [Int]() var i = 3; // 3 is the first variable player; 1 and 2 are captains while i <= self.numPlayers { self.playerOrder.append(i); i += 1; } self.updateTeamsFromOrder() } fileprivate func updateTeamsFromOrder() { self.team1 = [1]; self.team2 = [2]; for i in 0...(playerOrder.count-1) { if i%2 == 0 { // evens -> team 1 (cuz 0 indexing) self.team1.append(playerOrder[i]) } else { // odds -> team 2 self.team2.append(playerOrder[i]) } } } func getNumPlayers() -> Int { return self.numPlayers; } func setPlayerName(_ num:Int, name:String) { if (num <= self.numPlayers) { players[num-1].setName(name); } } func getPlayer(_ num:Int) -> Player { return players[num-1]; } func getPlayerName(_ num:Int) -> String { return players[num-1].name; } func shuffleTeams() { playerOrder.shuffle(); self.updateTeamsFromOrder() } func getTeam(_ which:Int) -> [Int] { if which == 1 { return team1 } else if which == 2 { return team2 } else { return [] } } func setTeamName(_ whichTeam:Int, name:String) { if whichTeam == 1 { team1Name = name; } else if whichTeam == 2 { team2Name = name; } } func getTeamName(_ whichTeam:Int) -> String { if whichTeam == 1 { return team1Name } else if whichTeam == 2 { return team2Name } return "" } func setTeamGoingFirst(_ team:Int) { if team == 1 { whichTeamGoesFirst = 1; } if team == 2 { whichTeamGoesFirst = 2; } } func getTeam1Score() -> Int { return team1Score; } func getTeam1Cards() -> [Card] { return team1CardsWon; } func addTeam1Score(_ score: Int) { team1Score += score; } func addTeam2Score(_ score: Int) { team2Score += score; } func getTeam2Score() -> Int { return team2Score; } func getTeam2Cards() -> [Card] { return team2CardsWon; } func getTeamScore(_ which : Int) -> Int { if which == 1 { return team1Score } if which == 2 { return team2Score } return 0; } func getTeamCards(_ which : Int) -> [Card] { if which == 1 { return team1CardsWon } if which == 2 { return team2CardsWon } return []; } func getCurrentRound() ->Int { return (currentTurn / numPlayers) + 1; } func getCurrentTurn() ->Int { return currentTurn + 1; } func getCurrentPlayer() -> Int { let numInRound = currentTurn % numPlayers; if numInRound%2 == (whichTeamGoesFirst==1 ? 0 : 1) { return team1[Int(numInRound/2)] } else { return team2[Int(numInRound/2)] } } func getCurrentPlayerName() -> String { return self.getPlayerName(self.getCurrentPlayer()); } func getCurrentTeam() -> Int { let numInRound = currentTurn % numPlayers; if numInRound%2 == (whichTeamGoesFirst==1 ? 0 : 1) { return 1 } else { return 2 } } func getCurrentTeamName() ->String { return self.getTeamName(self.getCurrentTeam()); } func hasNextCard() -> Bool { return deck.hasNextCard(); } func drawCard() -> Card { if deck.hasNextCard() { self.currentCard = deck.nextCard(); } return currentCard; } //todo: make sure this undoes everything we needed func undoLastTurn() { //we don't need to undraw a card because we won't draw a card, we'll simply use currentCard currentTurn -= 1 if self.getCurrentTeam() == 1 && team1CardsWon.contains(currentCard) { team1CardsWon.remove( at: team1CardsWon.index(of: currentCard)!) team1CardsPerRound[self.getCurrentRound()] -= 1; } else if self.getCurrentTeam() == 2 && team2CardsWon.contains(currentCard) { team2CardsWon.remove( at: team2CardsWon.index(of: currentCard)!) team2CardsPerRound[self.getCurrentRound()] -= 1; } } // shuffles the last card drawn back into the deck func undoLastTurnAndReshuffle() { self.undrawCard() // shuffles it back into the deck //TODO: NEED TO REMOVE IT FROM WHOEVER WON IT'S CARDS currentTurn -= 1 } func undrawCard() { deck.undrawCard() // shuffles it back into the deck } func getCurrentCard() -> Card? { return self.currentCard; } func advanceTurn() { currentTurn += 1; } func cardWasWon() { let numInRound = currentTurn % numPlayers; if numInRound%2 == (whichTeamGoesFirst==1 ? 0 : 1) { // team 1 won the card team1CardsWon.append(currentCard) if (currentCard.suit != .random) { // random cards aren't worth points addOneToTeamInCurrentRound(1) } } else { // team 2 won the card team2CardsWon.append(currentCard) if (currentCard.suit != .random) { // random cards aren't worth points addOneToTeamInCurrentRound(2) } } self.message = self.currentCard.getWonMessage() self.messageTitle = self.currentCard.getWonMessageTitle(); self.advanceTurn(); } func cardWasLost() { self.message = self.currentCard.getLostMessage() self.messageTitle = self.currentCard.getLostMessageTitle(); self.advanceTurn(); } func cardWasStolen() { let numInRound = currentTurn % numPlayers; if numInRound%2 == (whichTeamGoesFirst==1 ? 0 : 1) { // even, first team (because 0 index) -> second team steals team2CardsWon.append(currentCard) addOneToTeamInCurrentRound(2); } else { // team 2 -> 1 steals team1CardsWon.append(currentCard) addOneToTeamInCurrentRound(1) } self.message = self.currentCard.getStolenMessage() self.messageTitle = self.currentCard.getStolenMessageTitle(); self.advanceTurn(); } func addOneToTeamInCurrentRound(_ which:Int) { let roundNum = self.getCurrentRound()-1; // zero indexing if which == 1 { while (team1CardsPerRound.count <= roundNum) { //it's a while just in case they didn't get any cards in previous rounds team1CardsPerRound.append(0); } team1CardsPerRound[roundNum] += 1; } else if which == 2 { while (team2CardsPerRound.count <= roundNum) { //it's a while just in case they didn't get any cards in previous rounds team2CardsPerRound.append(0); } team2CardsPerRound[roundNum] += 1; } } func isNewRound() -> Bool { return (currentTurn % numPlayers) == 0; } func getTeamCardsInLastRound(_ team:Int) -> Int { if self.getCurrentRound() < 2 { //there was no last round return 0; } return self.getTeamCardsInRound(team, round: self.getCurrentRound()-1); } func getTeamCardsInCurrentRound(_ team:Int) -> Int { return self.getTeamCardsInRound(team, round: self.getCurrentRound()); } func getTeamCardsInRound(_ team:Int, round:Int) -> Int { if team == 1 { while (team1CardsPerRound.count < round) { //it's a while just in case they didn't get any cards in previous rounds team1CardsPerRound.append(0); } return team1CardsPerRound[round-1] } else if team == 2 { //padd the array wiht 0's while (team2CardsPerRound.count < round) { //it's a while just in case they didn't get any cards in previous rounds team2CardsPerRound.append(0); } return team2CardsPerRound[round-1] } return 0; } func getCardsWonInLastRound() -> Int { if self.getCurrentRound() < 2 { //there was no last round return 0; } return self.getCardsWonInRound(self.getCurrentRound()-1); } func getCardsWonInCurrentRound() -> Int { return self.getCardsWonInRound(self.getCurrentRound()); } func getCardsWonInRound(_ round:Int) -> Int { return team1CardsPerRound[round-1] + team2CardsPerRound[round-1] } func quickStart(_ playerCount:Int) { print("quick starting"); quickStarted = true; self.setNumPlayers(playerCount); team1Name = "The Crustaceans" team2Name = "The Fish" self.players = [Player](); let playerNames = ["Lobster", "Great White", "Crab", "Tuna","Shrimp", "Manta Ray", "Barnacle", "Swordfish", "Krill", "Eel", "Crayfish", "BlowFish", "Prawn", "Flounder"] for name in playerNames { self.players.append(Player(name)); } } func wasQuickStarted() -> Bool { return self.quickStarted; } func sendPlayerToEndOfTeam(_ playerIndex:Int, team:Int) { var index = playerIndex if (team != 1 && team != 2) { return } //shift that player to the back if (team == 1) { while index < team1.count-1 { swap(&team1[index], &team1[index+1]) index += 1 } } else if team == 2 { while index < self.getTeam(team).count-1 { swap(&team2[index], &team2[index+1]) index += 1 } } } func swapPlayersInTeam(_ player1:Int, player2:Int, team:Int) { if (team != 1 && team != 2) { return } //shift that player to the back if (team == 1) { if (player1 < 0 || player1 >= team1.count || player2 < 0 || player2 >= team1.count) { return } swap(&team1[player1], &team1[player2]) } else if team == 2 { if (player1 < 0 || player1 >= team2.count || player2 < 0 || player2 >= team2.count) { return } swap(&team2[player1], &team2[player2]) } } }
mit
f39f390e9bdb4437140a936754942ecc
23.489496
172
0.603414
3.664571
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/UI/User/BulkStatsAllocationViewController.swift
1
6713
// // BulkStatsAllocationViewController.swift // Habitica // // Created by Phillip Thelen on 30.11.17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import UIKit import Habitica_Models import ReactiveSwift import FirebaseAnalytics class BulkStatsAllocationViewController: UIViewController, Themeable { private let disposable = ScopedDisposable(CompositeDisposable()) private let userRepository = UserRepository() private var user: UserProtocol? private var pointsToAllocate: Int = 0 var pointsAllocated: Int { get { var value = 0 value += strengthSliderView.value value += intelligenceSliderView.value value += constitutionSliderView.value value += perceptionSliderView.value return value } } @IBOutlet weak var headerWrapper: UIView! @IBOutlet weak var allocatedCountLabel: UILabel! @IBOutlet weak var allocatedLabel: UILabel! @IBOutlet weak var strengthSliderView: StatsSliderView! @IBOutlet weak var intelligenceSliderView: StatsSliderView! @IBOutlet weak var constitutionSliderView: StatsSliderView! @IBOutlet weak var perceptionSliderView: StatsSliderView! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var saveButton: UIButton! @IBOutlet weak var buttonSeparator: UIView! override func viewDidLoad() { super.viewDidLoad() disposable.inner.add(userRepository.getUser().take(first: 1).on(value: {[weak self]user in self?.user = user self?.pointsToAllocate = user.stats?.points ?? 0 self?.updateUI() }).start()) ThemeService.shared.addThemeable(themable: self) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) Analytics.logEvent("open_bulk_stats", parameters: nil) } func applyTheme(theme: Theme) { view.backgroundColor = theme.contentBackgroundColor headerWrapper.backgroundColor = theme.windowBackgroundColor allocatedLabel.textColor = theme.secondaryTextColor cancelButton.tintColor = theme.tintColor buttonSeparator.backgroundColor = theme.separatorColor saveButton.layer.shadowColor = ThemeService.shared.theme.buttonShadowColor.cgColor saveButton.layer.shadowRadius = 2 saveButton.layer.shadowOffset = CGSize(width: 1, height: 1) saveButton.layer.shadowOpacity = 0.5 saveButton.layer.masksToBounds = false updateUI() } private func updateUI() { strengthSliderView.maxValue = pointsToAllocate intelligenceSliderView.maxValue = pointsToAllocate constitutionSliderView.maxValue = pointsToAllocate perceptionSliderView.maxValue = pointsToAllocate if let stats = user?.stats { strengthSliderView.originalValue = stats.strength intelligenceSliderView.originalValue = stats.intelligence constitutionSliderView.originalValue = stats.constitution perceptionSliderView.originalValue = stats.perception } strengthSliderView.allocateAction = {[weak self] value in self?.checkRedistribution(excludedSlider: self?.strengthSliderView) self?.updateAllocatedCountLabel() } intelligenceSliderView.allocateAction = {[weak self] value in self?.checkRedistribution(excludedSlider: self?.intelligenceSliderView) self?.updateAllocatedCountLabel() } constitutionSliderView.allocateAction = {[weak self] value in self?.checkRedistribution(excludedSlider: self?.constitutionSliderView) self?.updateAllocatedCountLabel() } perceptionSliderView.allocateAction = {[weak self] value in self?.checkRedistribution(excludedSlider: self?.perceptionSliderView) self?.updateAllocatedCountLabel() } updateAllocatedCountLabel() } private func checkRedistribution(excludedSlider: StatsSliderView?) { let diff = pointsAllocated - pointsToAllocate if diff > 0 { var highestSlider: StatsSliderView? if excludedSlider != strengthSliderView { highestSlider = getSliderWithHigherValue(first: highestSlider, second: strengthSliderView) } if excludedSlider != intelligenceSliderView { highestSlider = getSliderWithHigherValue(first: highestSlider, second: intelligenceSliderView) } if excludedSlider != constitutionSliderView { highestSlider = getSliderWithHigherValue(first: highestSlider, second: constitutionSliderView) } if excludedSlider != perceptionSliderView { highestSlider = getSliderWithHigherValue(first: highestSlider, second: perceptionSliderView) } highestSlider?.value -= diff } } private func getSliderWithHigherValue(first: StatsSliderView?, second: StatsSliderView?) -> StatsSliderView? { guard let firstSlider = first else { return second } guard let secondSlider = second else { return first } if firstSlider.value > secondSlider.value { return firstSlider } else { return secondSlider } } private func updateAllocatedCountLabel() { allocatedCountLabel.text = "\(pointsAllocated)/\(pointsToAllocate)" if pointsAllocated > 0 { allocatedCountLabel.textColor = ThemeService.shared.theme.tintColor saveButton.backgroundColor = ThemeService.shared.theme.tintColor saveButton.setTitleColor(.white, for: .normal) } else { allocatedCountLabel.textColor = ThemeService.shared.theme.secondaryTextColor saveButton.backgroundColor = ThemeService.shared.theme.windowBackgroundColor saveButton.setTitleColor(ThemeService.shared.theme.quadTextColor, for: .normal) } } @IBAction func cancelButtonTapped(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func saveButtonTapped(_ sender: Any) { dismiss(animated: true, completion: nil) userRepository.bulkAllocate(strength: strengthSliderView.value, intelligence: intelligenceSliderView.value, constitution: constitutionSliderView.value, perception: perceptionSliderView.value).observeCompleted {} } }
gpl-3.0
9197c3597196aefb9c4209bb526887d7
39.191617
114
0.662843
5.501639
false
false
false
false
milseman/swift
test/attr/attr_objc_swift3_deprecated.swift
14
2352
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify %s -swift-version 3 -warn-swift3-objc-inference-complete // REQUIRES: objc_interop import Foundation class ObjCSubclass : NSObject { func foo() { } // expected-warning{{inference of '@objc' for members of Objective-C-derived classes is deprecated}} // expected-note@-1{{add `@objc` to continue exposing an Objective-C entry point (Swift 3 behavior)}}{{3-3=@objc }} // expected-note@-2{{add `@nonobjc` to suppress the Objective-C entry point (Swift 4 behavior)}}{{3-3=@nonobjc }} var bar: NSObject? = nil // expected-warning{{inference of '@objc' for members of Objective-C-derived classes is deprecated}} // expected-note@-1{{add `@objc` to continue exposing an Objective-C entry point (Swift 3 behavior)}}{{3-3=@objc }} // expected-note@-2{{add `@nonobjc` to suppress the Objective-C entry point (Swift 4 behavior)}}{{3-3=@nonobjc }} } class DynamicMembers { dynamic func foo() { } // expected-warning{{inference of '@objc' for 'dynamic' members is deprecated}}{{3-3=@objc }} dynamic var bar: NSObject? = nil // expected-warning{{inference of '@objc' for 'dynamic' members is deprecated}}{{3-3=@objc }} } class GenericClass<T>: NSObject {} class SubclassOfGeneric: GenericClass<Int> { func foo() { } // expected-warning{{inference of '@objc' for members of Objective-C-derived classes is deprecated}} // expected-note@-1{{add `@objc` to continue exposing an Objective-C entry point (Swift 3 behavior)}}{{3-3=@objc }} // expected-note@-2{{add `@nonobjc` to suppress the Objective-C entry point (Swift 4 behavior)}}{{3-3=@nonobjc }} } @objc(SubclassOfGenericCustom) class SubclassOfGenericCustomName: GenericClass<Int> { func foo() { } // expected-warning{{inference of '@objc' for members of Objective-C-derived classes is deprecated}} // expected-note@-1{{add `@objc` to continue exposing an Objective-C entry point (Swift 3 behavior)}}{{3-3=@objc }} // expected-note@-2{{add `@nonobjc` to suppress the Objective-C entry point (Swift 4 behavior)}}{{3-3=@nonobjc }} } // Suppress diagnostices about references to inferred @objc declarations // in this mode. func test(sc: ObjCSubclass, dm: DynamicMembers) { _ = #selector(sc.foo) _ = #selector(getter: dm.bar) _ = #keyPath(DynamicMembers.bar) }
apache-2.0
45bbe34c5106aba0cbb1fbe9272be901
53.697674
152
0.704082
3.769231
false
false
false
false
abarisain/skugga
Apple/iOS/Share/ShareViewController.swift
1
6268
// // ShareViewController.swift // Share // // Created by arnaud on 15/02/2015. // Copyright (c) 2015 NamelessDev. All rights reserved. // import UIKit import Social import MobileCoreServices import UserNotifications import UpdAPI class ShareViewController: SLComposeServiceViewController { override func viewDidLoad() { super.viewDidLoad() placeholder = "Ready to upload!" } override func presentationAnimationDidFinish() { textView.isUserInteractionEnabled = false textView.isEditable = false } override func isContentValid() -> Bool { // Do validation of contentText and/or NSExtensionContext attachments here return true } override func didSelectPost() { let item = self.extensionContext!.inputItems[0] as! NSExtensionItem if let attachments = item.attachments { if attachments.count > 0 { let attachment = attachments.first as! NSItemProvider if attachment.hasItemConformingToTypeIdentifier(kUTTypeFileURL as String) { uploadAttachmentForType(attachment, type: kUTTypeFileURL as String) return } else if attachment.hasItemConformingToTypeIdentifier(kUTTypeImage as String) { uploadAttachmentForType(attachment, type: kUTTypeImage as String) return } } } else { NSLog("No Attachments") } let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil) self.extensionContext!.cancelRequest(withError: cancelError) super.didSelectPost() } override func configurationItems() -> [Any]! { // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here. return [AnyObject]() } func uploadAttachmentForType(_ attachment : NSItemProvider, type: String) { UNUserNotificationCenter.current().getNotificationSettings { (settings: UNNotificationSettings) in var backgroundUpload = false var progressNotifier: ProgressNotifier! = nil if (settings.alertSetting == .enabled) { backgroundUpload = true progressNotifier = NotificationProgressNotifier(vc: self) } else { progressNotifier = AlertProgressNotifier(vc: self) } attachment.loadItem(forTypeIdentifier: type, options: nil, completionHandler: { (item: NSSecureCoding?, error: Error?) -> Void in if let urlItem = item as? URL { var tmpFileURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) tmpFileURL.appendPathComponent(UUID.init().uuidString + "." + urlItem.pathExtension) var attachmentURL: URL? = nil do { try FileManager.default.copyItem(at: urlItem, to: tmpFileURL) attachmentURL = tmpFileURL; } catch { print("Error while copying the image to a temporary directory: \(error)") } progressNotifier.uploadStarted(itemURL: attachmentURL) do { var innerError: Error? let _ = try UploadClient(configuration: Configuration.updApiConfiguration).upload(file: urlItem, progress: { (progress) in progressNotifier.uploadProgress(progress) }, success: { (data: [AnyHashable: Any]) -> Void in var url = data["name"] as! String url = Configuration.endpoint + url UIPasteboard.general.string = url progressNotifier.uploadSuccess(url: url) self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) }, failure: { (error: Error) -> Void in innerError = error }) if let innerError = innerError { throw innerError } } catch { //TODO : fix this and remove the inner error //NSLog("Failed to upload file \(error) \(error.userInfo)") //progressNotifier.uploadFailed(error: error) if (backgroundUpload) { self.extensionContext!.cancelRequest(withError: error) } } } else { let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: nil) self.extensionContext!.cancelRequest(withError: cancelError) } } ) } } }
apache-2.0
0f40bba3342ad27ab5581ffc6b45f0a2
41.351351
146
0.45485
7.122727
false
false
false
false
harlanhaskins/swift
test/Driver/PrivateDependencies/fail-added-fine.swift
1
2148
/// bad ==> main | bad --> other // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/fail-simple-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s // CHECK-INITIAL-NOT: warning // CHECK-INITIAL: Handled main.swift // CHECK-INITIAL: Handled other.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./other.swift ./bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-ADDED %s // RUN: %FileCheck -check-prefix=CHECK-RECORD-ADDED %s < %t/main~buildrecord.swiftdeps // CHECK-ADDED-NOT: Handled // CHECK-ADDED: Handled bad.swift // CHECK-ADDED-NOT: Handled // CHECK-RECORD-ADDED-DAG: "./bad.swift": !private [ // CHECK-RECORD-ADDED-DAG: "./main.swift": [ // CHECK-RECORD-ADDED-DAG: "./other.swift": [ // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/fail-simple-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./bad.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-ADDED %s // RUN: %FileCheck -check-prefix=CHECK-RECORD-ADDED %s < %t/main~buildrecord.swiftdeps
apache-2.0
51f652909bfde06098e48d476b629a17
66.125
351
0.718808
3.191679
false
false
false
false
DigitalRogues/FRDLivelyButton-Swift
FRDLivelyButton-Swift/FRDLivelyButton-Swift.swift
1
21101
// // FRDLively-Swift.swift // Last Layer // // Created by punk on 11/8/16. // // import UIKit enum kFRDLivelyButtonStyle { case kFRDLivelyButtonStyleHamburger case kFRDLivelyButtonStyleClose case kFRDLivelyButtonStylePlus case kFRDLivelyButtonStyleCirclePlus case kFRDLivelyButtonStyleCircleClose case kFRDLivelyButtonStyleCaretUp case kFRDLivelyButtonStyleCaretDown case kFRDLivelyButtonStyleCaretLeft case kFRDLivelyButtonStyleCaretRight case kFRDLivelyButtonStyleArrowLeft case kFRDLivelyButtonStyleArrowRight } // enum buttonProp: String { // case kFRDLivelyButtonHighlightScale = "kFRDLivelyButtonHighlightScale" // case kFRDLivelyButtonLineWidth = "kFRDLivelyButtonLineWidth" // case kFRDLivelyButtonColor = "kFRDLivelyButtonColor" // case kFRDLivelyButtonHighlightedColor = "kFRDLivelyButtonHighlightedColor" // case kFRDLivelyButtonHighlightAnimationDuration = "kFRDLivelyButtonHighlightAnimationDuration" // case kFRDLivelyButtonUnHighlightAnimationDuration = "kFRDLivelyButtonUnHighlightAnimationDuration" // case kFRDLivelyButtonStyleChangeAnimationDuration = "kFRDLivelyButtonStyleChangeAnimationDuration" // } class FRDLivelyButton: UIButton { var buttonStyle: kFRDLivelyButtonStyle? var dimension: CGFloat = 0 var offset: CGPoint = CGPoint(x: 0, y: 0) var centerPoint: CGPoint = CGPoint(x: 0, y: 0) var circleLayer: CAShapeLayer = CAShapeLayer() var line1Layer: CAShapeLayer = CAShapeLayer() var line2Layer: CAShapeLayer = CAShapeLayer() var line3Layer: CAShapeLayer = CAShapeLayer() var shapeLayers = Array<CAShapeLayer>() let options = FRDLivelyButtonObject() let GOLDEN_RATIO: CGFloat = 1.618 override init(frame: CGRect) { super.init(frame: frame) // Initialization code self.commonInitializer() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInitializer() } func commonInitializer() { self.line1Layer = CAShapeLayer() self.line2Layer = CAShapeLayer() self.line3Layer = CAShapeLayer() self.circleLayer = CAShapeLayer() // options = FRDLivelyButton.defaultOptions() // i think this configs and adds all the blank paths to the main view let array = [line1Layer, line2Layer, line3Layer, circleLayer] array.forEach { (obj) in let layer = obj layer.fillColor = UIColor.clear.cgColor layer.anchorPoint = CGPoint(x: 0.0, y: 0.0) layer.lineJoin = kCALineJoinRound layer.lineCap = kCALineCapRound layer.contentsScale = self.layer.contentsScale // initialize with an empty path so we can animate the path w/o having to check for NULLs. let dummyPath = CGMutablePath() layer.path = dummyPath self.layer.addSublayer(layer) } self.addTarget(self, action: #selector(showHighlight), for: .touchDown) self.addTarget(self, action: #selector(showUnHighlight), for: .touchUpInside) self.addTarget(self, action: #selector(showUnHighlight), for: .touchUpOutside) // // in case the button is not square, the offset will be use to keep our CGPath's centered in it. let width: Double = Double(self.frame.width) - Double(self.contentEdgeInsets.left + self.contentEdgeInsets.right) let height: Double = Double(self.frame.height) - Double(self.contentEdgeInsets.top + self.contentEdgeInsets.bottom) self.dimension = CGFloat(min(width, height)) self.offset = CGPoint(x: (self.frame.width - self.dimension) / 2.0, y: (self.frame.height - self.dimension) / 2.0) self.centerPoint = CGPoint(x: self.bounds.midX, y: self.bounds.midY) // set some options on existing objects? let layerArray = [line1Layer, line2Layer, line3Layer, circleLayer] layerArray.forEach { (obj) in let layer = obj layer.lineWidth = options.kFRDLivelyButtonLineWidth layer.strokeColor = options.kFRDLivelyButtonColor } } // func setOptions(options: Dictionary<buttonProp, Any>) { // //self.options = options // // // set some options on existing objects? // let array = [line1Layer, line2Layer, line3Layer, circleLayer] // array.forEach { (obj) in // let layer = obj // layer.lineWidth = options//(valueForOptionKey(key: buttonProp.kFRDLivelyButtonLineWidth) as! CGFloat) // layer.strokeColor = (valueForOptionKey(key: buttonProp.kFRDLivelyButtonColor) as! CGColor) // } // } // func valueForOptionKey(key: buttonProp) -> Any { // if self.options[key] != nil { // return self.options[key]! // } // return FRDLivelyButton.defaultOptions()[key] as Any // } func shapedLayers() -> Array<CAShapeLayer> { if shapeLayers.count == 0 { shapeLayers = [circleLayer, line1Layer, line2Layer, line3Layer] } return shapeLayers } // class func defaultOptions() -> Dictionary<buttonProp, Any> { // let dic = [buttonProp.kFRDLivelyButtonColor: UIColor.black, buttonProp.kFRDLivelyButtonHighlightedColor: UIColor.lightGray, buttonProp.kFRDLivelyButtonHighlightAnimationDuration: 0.1, buttonProp.kFRDLivelyButtonHighlightScale: 0.9, buttonProp.kFRDLivelyButtonLineWidth: 1.0, buttonProp.kFRDLivelyButtonUnHighlightAnimationDuration: 0.15, buttonProp.kFRDLivelyButtonStyleChangeAnimationDuration: 0.3] as [buttonProp: Any] // // return dic // } func transformWithScale(scale: CGFloat) -> CGAffineTransform { let transform = CGAffineTransform(translationX: (self.dimension + 2 * (self.offset.x)) * ((1 - scale) / 2.0), y: (self.dimension + 2 * (self.offset.y)) * ((1 - scale) / 2.0)) return transform.scaledBy(x: scale, y: scale) } func createCenteredCircle(withRadius radius: CGFloat) -> CGMutablePath { let path = CGMutablePath() path.move(to: CGPoint(x: (self.centerPoint.x) + radius, y: (self.centerPoint.y))) // note: if clockwise is set to true, the circle will not draw on an actual device, // event hough it is fine on the simulator... path.addArc(center: CGPoint(x: (self.centerPoint.x), y: (self.centerPoint.y)), radius: radius, startAngle: 0, endAngle: 2 * .pi, clockwise: false) return path } func createCenteredLine(withRadius radius: CGFloat, angle: CGFloat, offset: CGPoint) -> CGMutablePath { let path = CGMutablePath() let fangle = Float(angle) let c: CGFloat = CGFloat(cosf(fangle)) let s: CGFloat = CGFloat(sinf(fangle)) path.move(to: CGPoint(x: (self.centerPoint.x) + offset.x + radius * c, y: (self.centerPoint.y) + offset.y + radius * s)) path.addLine(to: CGPoint(x: (self.centerPoint.x) + offset.x - radius * c, y: (self.centerPoint.y) + offset.y - radius * s)) return path } func createLine(from p1: CGPoint, to p2: CGPoint) -> CGMutablePath { let path = CGMutablePath() path.move(to: CGPoint(x: (self.offset.x) + p1.x, y: (self.offset.y) + p1.y)) path.addLine(to: CGPoint(x: (self.offset.x) + p2.x, y: (self.offset.y) + p2.y)) return path } func setStyle(style: kFRDLivelyButtonStyle, animated: Bool) { buttonStyle = style var newCirclePath = CGMutablePath() var newLine1Path = CGMutablePath() var newLine2Path = CGMutablePath() var newLine3Path = CGMutablePath() var newCircleAlpha: CGFloat = 0.0 var newLine1Alpha: CGFloat = 0.0 if style == kFRDLivelyButtonStyle.kFRDLivelyButtonStyleHamburger { newCirclePath = self.createCenteredCircle(withRadius: self.dimension / 20.0) newCircleAlpha = 0.0 newLine1Path = self.createCenteredLine(withRadius: self.dimension / 2.0, angle: 0, offset: CGPoint(x: 0, y: 0)) newLine1Alpha = 1.0 newLine2Path = self.createCenteredLine(withRadius: self.dimension / 2.0, angle: 0, offset: CGPoint(x: 0, y: -self.dimension / 2.0 / GOLDEN_RATIO)) newLine3Path = self.createCenteredLine(withRadius: self.dimension / 2.0, angle: 0, offset: CGPoint(x: 0, y: self.dimension / 2.0 / GOLDEN_RATIO)) } else if style == kFRDLivelyButtonStyle.kFRDLivelyButtonStylePlus { newCirclePath = self.createCenteredCircle(withRadius: self.dimension / 20.0) newCircleAlpha = 0.0 newLine1Path = self.createCenteredLine(withRadius: self.dimension / 20.0, angle: 0, offset: CGPoint(x: 0, y: 0)) newLine1Alpha = 0.0 newLine2Path = self.createCenteredLine(withRadius: self.dimension / 2.0, angle: +(CGFloat)(M_PI_2), offset: CGPoint(x: 0, y: 0)) newLine3Path = self.createCenteredLine(withRadius: self.dimension / 2.0, angle: 0, offset: CGPoint(x: 0, y: 0)) } else if style == kFRDLivelyButtonStyle.kFRDLivelyButtonStyleCirclePlus { newCirclePath = self.createCenteredCircle(withRadius: self.dimension / 2.0) newCircleAlpha = 1.0 newLine1Path = self.createCenteredLine(withRadius: self.dimension / 20.0, angle: 0, offset: CGPoint(x: 0, y: 0)) newLine1Alpha = 0.0 newLine2Path = self.createCenteredLine(withRadius: self.dimension / 2.0 / GOLDEN_RATIO, angle: CGFloat(M_PI_2), offset: CGPoint(x: 0, y: 0)) newLine3Path = self.createCenteredLine(withRadius: self.dimension / 2.0 / GOLDEN_RATIO, angle: 0, offset: CGPoint(x: 0, y: 0)) } else if style == kFRDLivelyButtonStyle.kFRDLivelyButtonStyleClose { newCirclePath = self.createCenteredCircle(withRadius: self.dimension / 20.0) newCircleAlpha = 0.0 newLine1Path = self.createCenteredLine(withRadius: self.dimension / 20.0, angle: 0, offset: CGPoint(x: 0, y: 0)) newLine1Alpha = 0.0 newLine2Path = self.createCenteredLine(withRadius: self.dimension / 2.0, angle: +(CGFloat)(M_PI_4), offset: CGPoint(x: 0, y: 0)) newLine3Path = self.createCenteredLine(withRadius: self.dimension / 2.0, angle: -(CGFloat)(M_PI_4), offset: CGPoint(x: 0, y: 0)) } else if style == kFRDLivelyButtonStyle.kFRDLivelyButtonStyleCircleClose { newCirclePath = self.createCenteredCircle(withRadius: self.dimension / 2.0) newCircleAlpha = 1.0 newLine1Path = self.createCenteredLine(withRadius: self.dimension / 20.0, angle: 0, offset: CGPoint(x: 0, y: 0)) newLine1Alpha = 0.0 newLine2Path = self.createCenteredLine(withRadius: self.dimension / 2.0 / GOLDEN_RATIO, angle: +(CGFloat)(M_PI_4), offset: CGPoint(x: 0, y: 0)) newLine3Path = self.createCenteredLine(withRadius: self.dimension / 2.0 / GOLDEN_RATIO, angle: -(CGFloat)(M_PI_4), offset: CGPoint(x: 0, y: 0)) } else if style == kFRDLivelyButtonStyle.kFRDLivelyButtonStyleCaretUp { newCirclePath = self.createCenteredCircle(withRadius: self.dimension / 20.0) newCircleAlpha = 0.0 newLine1Path = self.createCenteredLine(withRadius: self.dimension / 20.0, angle: 0, offset: CGPoint(x: 0, y: 0)) newLine1Alpha = 0.0 newLine2Path = self.createCenteredLine(withRadius: self.dimension / 4.0 - self.line2Layer.lineWidth / 2.0, angle: CGFloat(M_PI_4), offset: CGPoint(x: self.dimension / 6.0, y: 0.0)) newLine3Path = self.createCenteredLine(withRadius: self.dimension / 4.0 - self.line3Layer.lineWidth / 2.0, angle: CGFloat(3) * CGFloat(M_PI_4), offset: CGPoint(x: -self.dimension / 6.0, y: 0.0)) } else if style == kFRDLivelyButtonStyle.kFRDLivelyButtonStyleCaretDown { newCirclePath = self.createCenteredCircle(withRadius: self.dimension / 20.0) newCircleAlpha = 0.0 newLine1Path = self.createCenteredLine(withRadius: self.dimension / 20.0, angle: 0, offset: CGPoint(x: 0, y: 0)) newLine1Alpha = 0.0 newLine2Path = self.createCenteredLine(withRadius: self.dimension / 4.0 - self.line2Layer.lineWidth / 2.0, angle: -(CGFloat)(M_PI_4), offset: CGPoint(x: self.dimension / 6.0, y: 0.0)) newLine3Path = self.createCenteredLine(withRadius: self.dimension / 4.0 - self.line3Layer.lineWidth / 2.0, angle: CGFloat(-3) * CGFloat(M_PI_4), offset: CGPoint(x: -self.dimension / 6.0, y: 0.0)) } else if style == kFRDLivelyButtonStyle.kFRDLivelyButtonStyleCaretLeft { newCirclePath = self.createCenteredCircle(withRadius: self.dimension / 20.0) newCircleAlpha = 0.0 newLine1Path = self.createCenteredLine(withRadius: self.dimension / 20.0, angle: 0, offset: CGPoint(x: 0, y: 0)) newLine1Alpha = 0.0 newLine2Path = self.createCenteredLine(withRadius: self.dimension / 4.0 - self.line2Layer.lineWidth / 2.0, angle: CGFloat(-3) * CGFloat(M_PI_4), offset: CGPoint(x: 0.0, y: self.dimension / 6.0)) newLine3Path = self.createCenteredLine(withRadius: self.dimension / 4.0 - self.line3Layer.lineWidth / 2.0, angle: CGFloat(3) * CGFloat(M_PI_4), offset: CGPoint(x: 0.0, y: -self.dimension / 6.0)) } else if style == kFRDLivelyButtonStyle.kFRDLivelyButtonStyleCaretRight { newCirclePath = self.createCenteredCircle(withRadius: self.dimension / 20.0) newCircleAlpha = 0.0 newLine1Path = self.createCenteredLine(withRadius: self.dimension / 20.0, angle: 0, offset: CGPoint(x: 0, y: 0)) newLine1Alpha = 0.0 newLine2Path = self.createCenteredLine(withRadius: self.dimension / 4.0 - self.line2Layer.lineWidth / 2.0, angle: -(CGFloat)(M_PI_4), offset: CGPoint(x: 0.0, y: self.dimension / 6.0)) newLine3Path = self.createCenteredLine(withRadius: self.dimension / 4.0 - self.line3Layer.lineWidth / 2.0, angle: CGFloat(M_PI_4), offset: CGPoint(x: 0.0, y: -self.dimension / 6.0)) } else if style == kFRDLivelyButtonStyle.kFRDLivelyButtonStyleArrowLeft { newCirclePath = self.createCenteredCircle(withRadius: self.dimension / 20.0) newCircleAlpha = 0.0 newLine1Path = self.createCenteredLine(withRadius: self.dimension / 2.0, angle: .pi, offset: CGPoint(x: 0, y: 0)) newLine1Alpha = 1.0 newLine2Path = self.createLine(from: CGPoint(x: 0, y: self.dimension / 2.0), to: CGPoint(x: self.dimension / 2.0 / GOLDEN_RATIO, y: self.dimension / 2 + self.dimension / 2.0 / GOLDEN_RATIO)) newLine3Path = self.createLine(from: CGPoint(x: 0, y: self.dimension / 2.0), to: CGPoint(x: self.dimension / 2.0 / GOLDEN_RATIO, y: self.dimension / 2 - self.dimension / 2.0 / GOLDEN_RATIO)) } else if style == kFRDLivelyButtonStyle.kFRDLivelyButtonStyleArrowRight { newCirclePath = self.createCenteredCircle(withRadius: self.dimension / 20.0) newCircleAlpha = 0.0 newLine1Path = self.createCenteredLine(withRadius: self.dimension / 2.0, angle: 0, offset: CGPoint(x: 0, y: 0)) newLine1Alpha = 1.0 newLine2Path = self.createLine(from: CGPoint(x: self.dimension, y: self.dimension / 2.0), to: CGPoint(x: self.dimension - self.dimension / 2.0 / GOLDEN_RATIO, y: self.dimension / 2 + self.dimension / 2.0 / GOLDEN_RATIO)) newLine3Path = self.createLine(from: CGPoint(x: self.dimension, y: self.dimension / 2.0), to: CGPoint(x: self.dimension - self.dimension / 2.0 / GOLDEN_RATIO, y: self.dimension / 2 - self.dimension / 2.0 / GOLDEN_RATIO)) } else { assert(false, "unknown type") } let duration: TimeInterval = options.kFRDLivelyButtonStyleChangeAnimationDuration // valueForOptionKey(key: buttonProp.kFRDLivelyButtonStyleChangeAnimationDuration) as! Double if animated { let circleAnim = CABasicAnimation(keyPath: "path") circleAnim.isRemovedOnCompletion = false circleAnim.duration = CFTimeInterval(duration) circleAnim.fromValue = circleLayer.path circleAnim.toValue = newCirclePath circleAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) circleLayer.add(circleAnim, forKey: "animateCirclePath") let circleAlphaAnim = CABasicAnimation(keyPath: "opacity") circleAlphaAnim.isRemovedOnCompletion = false circleAlphaAnim.duration = CFTimeInterval(duration) circleAlphaAnim.fromValue = self.circleLayer.opacity circleAlphaAnim.toValue = newCircleAlpha circleAlphaAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) circleLayer.add(circleAlphaAnim, forKey: "animateCircleOpacityPath") let line1Anim = CABasicAnimation(keyPath: "path") line1Anim.isRemovedOnCompletion = false line1Anim.duration = CFTimeInterval(duration) line1Anim.fromValue = line1Layer.path line1Anim.toValue = newLine1Path line1Anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) line1Layer.add(line1Anim, forKey: "animateLine1Path") let line1AlphaAnim = CABasicAnimation(keyPath: "opacity") line1AlphaAnim.isRemovedOnCompletion = false line1AlphaAnim.duration = CFTimeInterval(duration) line1AlphaAnim.fromValue = line1Layer.opacity line1AlphaAnim.toValue = newLine1Alpha line1AlphaAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) line1Layer.add(line1AlphaAnim, forKey: "animateLine1OpacityPath") let line2Anim = CABasicAnimation(keyPath: "path") line2Anim.isRemovedOnCompletion = false line2Anim.duration = CFTimeInterval(duration) line2Anim.fromValue = line2Layer.path line2Anim.toValue = newLine2Path line2Anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) line2Layer.add(line2Anim, forKey: "animateLine2Path") let line3Anim = CABasicAnimation(keyPath: "path") line3Anim.isRemovedOnCompletion = false line3Anim.duration = CFTimeInterval(duration) line3Anim.fromValue = line3Layer.path line3Anim.toValue = newLine3Path line3Anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) line3Layer.add(line3Anim, forKey: "animateLine3Path") circleLayer.path = newCirclePath circleLayer.opacity = Float(newCircleAlpha) line1Layer.path = newLine1Path line1Layer.opacity = Float(newLine1Alpha) line2Layer.path = newLine2Path line3Layer.path = newLine3Path } } func showHighlight() { let highlightScale = options.kFRDLivelyButtonHighlightScale shapeLayers.forEach { (layer) in layer.strokeColor = options.kFRDLivelyButtonHighlightedColor var transform: CGAffineTransform = transformWithScale(scale: highlightScale) let scaledPath = layer.path?.copy(using: &transform) let anim = CABasicAnimation(keyPath: "path") anim.duration = options.kFRDLivelyButtonHighlightAnimationDuration anim.isRemovedOnCompletion = false anim.fromValue = layer.path anim.toValue = scaledPath anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) layer.add(anim, forKey: "layerAnim") layer.path = scaledPath } } func showUnHighlight() { let unHighlightScale = CGFloat(1) / options.kFRDLivelyButtonHighlightScale shapeLayers.forEach { (layer) in layer.strokeColor = options.kFRDLivelyButtonColor let path = layer.path var transform = transformWithScale(scale: unHighlightScale) let finalPath = path?.mutableCopy(using: &transform) var upTransform = transformWithScale(scale: unHighlightScale * 1.07) let scaledUpPath = path?.mutableCopy(using: &upTransform) var downTransform = transformWithScale(scale: unHighlightScale * 0.97) let scaledDownPath = path?.mutableCopy(using: &downTransform) let values = [layer.path!, scaledUpPath!, scaledDownPath!, finalPath!] let times = [0.0, 0.85, 0.93, 1.0] let anim = CAKeyframeAnimation(keyPath: "path") anim.duration = options.kFRDLivelyButtonUnHighlightAnimationDuration anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) anim.isRemovedOnCompletion = false anim.values = values anim.keyTimes = times as [NSNumber]? layer.add(anim, forKey: "keyanim") layer.path = finalPath } } }
mit
413fd51c39c076c586eb0f5c8c81f2f9
54.970822
434
0.667362
3.99111
false
false
false
false