repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lyp1992/douyu-Swift | YPTV/YPTV/Classes/Tools/YPPageView/YPPageStyle.swift | 1 | 985 | //
// YPPageStyle.swift
// YPPageView
//
// Created by 赖永鹏 on 2018/11/22.
// Copyright © 2018年 LYP. All rights reserved.
//
import UIKit
class YPPageStyle {
// 是否可以滚动
var isScrollEnable : Bool = false
// 设置label的属性
var titleHeight : CGFloat = 40
var normalColor : UIColor = UIColor.white
var selectColor : UIColor = UIColor.orange
var fontSize : CGFloat = 15
var titleMargin : CGFloat = 30
// 设置底部bottomLine
var isBottomLineShow : Bool = false
var bottomLineHeight : CGFloat = 2
var bottomLineColor : UIColor = UIColor.orange
// 缩放
var isScaleAble : Bool = true
var scale : CGFloat = 1.2
// 是否需要显示coverView
var isShowCoverView : Bool = false
var coverBgColor : UIColor = UIColor.black
var coverAlpha : CGFloat = 0.4
var coverMargin : CGFloat = 8
var coverHeight : CGFloat = 25
var coverRadius : CGFloat = 12
}
| mit | b75a87aa2454f321bc9316128f3005cd | 21.682927 | 50 | 0.643011 | 3.974359 | false | false | false | false |
GarenChen/SunshineAlbum | SunshineAlbum/Classes/View/VideoCropButton.swift | 1 | 1271 | //
// VideoCropButton.swift
// SunshineAlbum
//
// Created by Garen on 2017/9/11.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import UIKit
class VideoCropButton: UIButton {
var title: String? {
didSet {
setTitle(title, for: .normal)
}
}
var didClick: ((_ sender: VideoCropButton) -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
private func setupViews() {
layer.cornerRadius = frame.size.height / 2
layer.masksToBounds = true
layer.borderWidth = 4
layer.borderColor = UIColor.white.cgColor
setBackgroundImage(SAUIConfig.shared.tintColor.toImage(), for: .normal)
setTitleColor(.white, for: .normal)
titleLabel?.font = UIFont.systemFont(ofSize: 14)
addTarget(self, action: #selector(click(_:)), for: .touchUpInside)
}
@objc private func click(_ sender: VideoCropButton) {
didClick?(sender)
transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: {
self.transform = CGAffineTransform.identity
}, completion: nil)
}
}
| mit | 1374fcd6e5de37ddcef850468f53fe85 | 21.245614 | 142 | 0.696372 | 3.464481 | false | false | false | false |
boborbt/SSRadioButtonsController | SSRadioButtonController/SSRadioButtonsController.swift | 1 | 3597 | //
// RadioButtonsController.swift
// TestApp
//
// Created by Al Shamas Tufail on 24/03/2015.
// Copyright (c) 2015 Al Shamas Tufail. All rights reserved.
//
import Foundation
import UIKit
/// RadioButtonControllerDelegate. Delegate optionally implements didSelectButton that receives selected button.
@objc protocol SSRadioButtonControllerDelegate {
/**
This function is called when a button is selected. If 'shouldLetDeSelect' is true, and a button is deselected, this function
is called with a nil.
*/
@objc optional func didSelectButton(_ aButton: UIButton?)
}
class SSRadioButtonsController : NSObject
{
fileprivate var buttonsArray = [UIButton]()
// fileprivate weak var currentSelectedButton:UIButton? = nil
weak var delegate : SSRadioButtonControllerDelegate? = nil
/**
Set whether a selected radio button can be deselected or not. Default value is false.
*/
var shouldLetDeSelect = false
/**
Variadic parameter init that accepts UIButtons.
- parameter buttons: Buttons that should behave as Radio Buttons
*/
init(buttons: UIButton...) {
super.init()
for aButton in buttons {
aButton.addTarget(self, action: #selector(SSRadioButtonsController.pressed(_:)), for: UIControl.Event.touchUpInside)
}
self.buttonsArray = buttons
}
/**
Add a UIButton to Controller
- parameter button: Add the button to controller.
*/
func addButton(_ aButton: UIButton) {
buttonsArray.append(aButton)
aButton.addTarget(self, action: #selector(SSRadioButtonsController.pressed(_:)), for: UIControl.Event.touchUpInside)
}
/**
Remove a UIButton from controller.
- parameter button: Button to be removed from controller.
*/
func removeButton(_ aButton: UIButton) {
var iteratingButton: UIButton? = nil
if(buttonsArray.contains(aButton))
{
iteratingButton = aButton
}
if(iteratingButton != nil) {
buttonsArray.remove(at: buttonsArray.firstIndex(of: iteratingButton!)!)
iteratingButton!.removeTarget(self, action: #selector(SSRadioButtonsController.pressed(_:)), for: UIControl.Event.touchUpInside)
iteratingButton!.isSelected = false
}
}
/**
Set an array of UIButons to behave as controller.
- parameter buttonArray: Array of buttons
*/
func setButtonsArray(_ aButtonsArray: [UIButton]) {
for aButton in aButtonsArray {
aButton.addTarget(self, action: #selector(SSRadioButtonsController.pressed(_:)), for: UIControl.Event.touchUpInside)
}
buttonsArray = aButtonsArray
}
@objc func pressed(_ sender: UIButton) {
var currentSelectedButton: UIButton? = nil
if(sender.isSelected) {
if shouldLetDeSelect {
sender.isSelected = false
currentSelectedButton = nil
}
} else {
for aButton in buttonsArray {
aButton.isSelected = false
}
sender.isSelected = true
currentSelectedButton = sender
}
delegate?.didSelectButton?(currentSelectedButton)
}
/**
Get the currently selected button.
- returns: Currenlty selected button.
*/
func selectedButton() -> UIButton? {
guard let index = buttonsArray.firstIndex(where: { button in button.isSelected }) else { return nil }
return buttonsArray[index]
}
}
| mit | 00f1ecd17a17eedfa605754fe369fcf1 | 32.616822 | 140 | 0.641646 | 5.197977 | false | false | false | false |
ps2/rileylink_ios | MinimedKit/PumpEvents/JournalEntryInsulinMarkerPumpEvent.swift | 1 | 1053 | //
// JournalEntryInsulinMarkerPumpEvent.swift
// RileyLink
//
// Created by Pete Schwamb on 7/16/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct JournalEntryInsulinMarkerPumpEvent: TimestampedPumpEvent {
public let length: Int
public let rawData: Data
public let timestamp: DateComponents
public let amount: Double
public init?(availableData: Data, pumpModel: PumpModel) {
length = 8
guard length <= availableData.count else {
return nil
}
rawData = availableData.subdata(in: 0..<length)
timestamp = DateComponents(pumpEventData: availableData, offset: 2)
let lowBits = rawData[1]
let highBits = rawData[4]
amount = Double((Int(highBits & 0b1100000) << 3) + Int(lowBits)) / 10.0
}
public var dictionaryRepresentation: [String: Any] {
return [
"_type": "JournalEntryInsulinMarker",
"amount": amount,
]
}
}
| mit | 7a2d8874a02f0ebc42d6a4a318960d51 | 25.974359 | 79 | 0.615019 | 4.554113 | false | false | false | false |
AckeeCZ/ACKategories | ACKategoriesCoreTests/CollectionTests.swift | 1 | 857 | //
// CollectionTests.swift
// UnitTests
//
// Created by Marek Fořt on 2/4/19.
// Copyright © 2019 Ackee, s.r.o. All rights reserved.
//
import XCTest
import ACKategoriesCore
final class CollectionTests: XCTestCase {
func testNonEmpty() {
var array: [Int]? = nil
XCTAssertNil(array.nonEmpty)
array = []
XCTAssertNil(array.nonEmpty)
array = [1]
XCTAssertNotNil(array.nonEmpty)
}
func testIsNotEmptyOptional() {
var array: [Int]? = nil
XCTAssertFalse(array.isNotEmpty)
array = []
XCTAssertFalse(array.isNotEmpty)
array = [1]
XCTAssertTrue(array.isNotEmpty)
}
func testIsNotEmpty() {
var array: [Int] = []
XCTAssertFalse(array.isNotEmpty)
array = [1]
XCTAssertTrue(array.isNotEmpty)
}
}
| mit | 084099cdcdaff1be021c88cf4904b472 | 17.191489 | 55 | 0.594152 | 4.150485 | false | true | false | false |
Muxing1991/Standford_Developing_iOS8_With_Swift | GraphsViewController.swift | 1 | 2715 | //
// GraphsViewController.swift
// Calculator-second-edition
//
// Created by 杨威 on 16/5/4.
// Copyright © 2016年 Muxing1991. All rights reserved.
//
import UIKit
class GraphsViewController: UIViewController, GraphDataSource, UIPopoverPresentationControllerDelegate {
//显示表达式的标签
@IBOutlet weak var graph: GraphAxes!{
didSet{
graph.addGestureRecognizer(UIPinchGestureRecognizer(target: graph, action: "pinching:"))
graph.addGestureRecognizer(UIPanGestureRecognizer(target: graph, action: "panning:"))
graph.addGestureRecognizer(UITapGestureRecognizer(target: graph, action: "doubleTapping:"))
graph.myFunc = self
graph.expression = displayExpression()
}
}
//var model: ((CGFloat) -> CGFloat?)?
//修改model 改为Brain的program
var model: AnyObject?{
didSet{
brain.program = model as! Array<String>
}
}
private var brain = CalculatorBrain()
func myFunc(sender: UIView, x: CGFloat) -> CGFloat? {
// if let brainModel = model{
// brain.program = brainModel as! Array<String>
// 性能提高的关键就在这里 因为在segue 到 graph后 model是没有变化的 不能每次手势就转型一次 这样的效率会非常低 而这个版本用属性观察器 在model被赋值后 对brain这个私有属性进行赋值 这样在重新绘制中都不需要对model来转型了
if model != nil{
brain.variableValue["M"] = Double(x)
if let result = brain.evaluate(){
return CGFloat(result)
}
return nil
}
return nil
}
func displayExpression() -> String?{
//此时brain还是一个空的brain 问题在这里
let discription = brain.description
let disArray = discription.componentsSeparatedByString(",")
var str = disArray.reverse()[0]
if str.containsString("M"){
str = str.stringByReplacingOccurrencesOfString("M", withString: "x")
return "Expression: y = " + str
}
return nil
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let id = segue.identifier{
switch id{
case "state":
if let svc = segue.destinationViewController as? StateViewController{
//获取这个segue目标
if let spc = svc.popoverPresentationController{
spc.delegate = self
}
svc.state = brain.description.stringByReplacingOccurrencesOfString(",", withString: "\n")
}
default: break
}
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
}
| mit | e1a81b97517f6431a55fd405a79b2552 | 27.413793 | 130 | 0.674353 | 4.406417 | false | false | false | false |
robtimp/xswift | exercises/wordy/Sources/Wordy/WordyExample.swift | 2 | 3556 | import Foundation
private extension String {
func trimWhiteSpace() -> String {
let removeSpaces = trimCharacters(" ", sourceText: self)
if removeSpaces.hasSuffix("\n") {
return String(removeSpaces.dropLast())
}
return removeSpaces
}
func trimCharacters(_ charToTrim: Character, sourceText: String) -> String {
var editCharacterView = Array(sourceText)
var editString = String(editCharacterView)
let trimFirst = sourceText.first == charToTrim
let trimLast = sourceText.last == charToTrim
if trimFirst { editCharacterView = Array(editCharacterView.dropFirst()) }
if trimLast { editCharacterView = Array(editCharacterView.dropLast()) }
if trimFirst || trimLast == true {
editString = trimCharacters(charToTrim, sourceText: String(editCharacterView))
}
return editString
}
func replacingOccurrencesCustom(_ of: String, with: String) -> String {
return replacingOccurrences(of: of, with: with)
}
func componentsSeparatedByStringCustom(_ input: String) -> [String] {
return components(separatedBy: input)
}
}
enum CalculateError: Error {
case error
}
struct WordProblem {
var textIn = ""
init(_ text: String) {
self.textIn = text
}
private let operans =
["plus": "+",
"minus": "-",
"multiplied by": "*",
"divided by": "/"]
private let funcs =
["+": { (a: Int, b: Int) -> Int in return a + b },
"-": { (a: Int, b: Int) -> Int in return a - b },
"*": { (a: Int, b: Int) -> Int in return a * b },
"/": { (a: Int, b: Int) -> Int in return a / b }]
func answer() throws -> Int {
guard let toReturn = calculate(textIn) else {
throw CalculateError.error
}
return toReturn
}
func calculate(_ textIn: String) -> Int? {
let calcStack = replaceText(textIn).componentsSeparatedByStringCustom(" ")
if calcStack.count == 3 {
let a = Int(calcStack[0])
let operA = funcs[calcStack[1]]
let b = Int(calcStack[2])
if a != nil || operA != nil || b == nil {
return operA!(a!, b!)
}
}
if calcStack.count == 5 {
let a = Int(calcStack[0])
let operA = funcs[calcStack[1]]
let b = Int(calcStack[2])
let operB = funcs[calcStack[3]]
let c = Int(calcStack[4])
if a != nil || operA != nil || b == nil ||
operB != nil || c != nil {
let left = operA!(a!, b!)
return operB!(left, c!) }
}
return nil
}
private func replaceText( _ textInp: String) -> String {
var textInp = textInp
for key in Array(operans.keys) {
let toBeReplaced = key
let toReplaceValue = operans[key]!
textInp = textInp.replacingOccurrencesCustom(toBeReplaced, with: toReplaceValue)
}
func checkCharInSet(_ input: Character) -> Bool {
let temp = " 0987654321+-*/".index(of: input)
if temp == nil {
return false
} else {
return true}
}
var newTextIn = Array(textInp)
newTextIn = newTextIn.filter(checkCharInSet)
let newTextInString: [String] = newTextIn.map { String($0) }
return newTextInString.joined(separator: "").trimWhiteSpace()
}
}
| mit | d65b9841aa79c4e560493e709c0c678c | 29.135593 | 92 | 0.54387 | 4.373924 | false | false | false | false |
MichaelSelsky/TheBeatingAtTheGates | Carthage/Checkouts/VirtualGameController/Source/External/VgcSharedViews.swift | 1 | 54835 | //
// VirtualGameControllerSharedViews.swift
//
//
// Created by Rob Reuss on 9/28/15.
//
//
import Foundation
import UIKit
import VirtualGameController
import AVFoundation
public let animationSpeed = 0.35
var peripheralManager = VgcManager.peripheral
// A simple mock-up of a game controller (Peripheral)
@objc public class PeripheralControlPadView: NSObject {
var custom = VgcManager.elements.custom
var elements = VgcManager.elements
var parentView: UIView!
var controlOverlay: UIView!
var controlLabel: UILabel!
#if !os(tvOS)
var motionSwitch : UISwitch!
#endif
var activityIndicator : UIActivityIndicatorView!
var leftShoulderButton: VgcButton!
var rightShoulderButton: VgcButton!
var leftTriggerButton: VgcButton!
var rightTriggerButton: VgcButton!
var centerTriggerButton: VgcButton!
var playerIndexLabel: UILabel!
var keyboardTextField: UITextField!
var keyboardControlView: UIView!
var keyboardLabel: UILabel!
public var flashView: UIImageView!
public var viewController: UIViewController!
public var serviceSelectorView: ServiceSelectorView!
@objc public init(vc: UIViewController) {
super.init()
viewController = vc
parentView = viewController.view
NSNotificationCenter.defaultCenter().addObserver(self, selector: "peripheralDidDisconnect:", name: VgcPeripheralDidDisconnectNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "peripheralDidConnect:", name: VgcPeripheralDidConnectNotification, object: nil)
// Notification that a player index has been set
NSNotificationCenter.defaultCenter().addObserver(self, selector: "gotPlayerIndex:", name: VgcNewPlayerIndexNotification, object: nil)
parentView.backgroundColor = UIColor.darkGrayColor()
flashView = UIImageView(frame: CGRect(x: 0, y: 0, width: parentView.bounds.size.width, height: parentView.bounds.size.height))
flashView.backgroundColor = UIColor.redColor()
flashView.alpha = 0
flashView.userInteractionEnabled = false
parentView.addSubview(flashView)
let buttonSpacing: CGFloat = 1.0
let buttonHeight: CGFloat = (0.15 * parentView.bounds.size.height)
let stickSideSize = parentView.bounds.size.height * 0.25
var marginSize: CGFloat = parentView.bounds.size.width * 0.03
if VgcManager.peripheral.deviceInfo.profileType != .MicroGamepad {
leftShoulderButton = VgcButton(frame: CGRect(x: 0, y: 0, width: (parentView.bounds.width * 0.50) - buttonSpacing, height: buttonHeight), element: elements.leftShoulder)
leftShoulderButton.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleRightMargin]
parentView.addSubview(leftShoulderButton)
rightShoulderButton = VgcButton(frame: CGRect(x: (parentView.bounds.width * 0.50), y: 0, width: (parentView.bounds.width * 0.50) - buttonSpacing, height: buttonHeight), element: elements.rightShoulder)
rightShoulderButton.valueLabel.textAlignment = .Left
rightShoulderButton.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleLeftMargin]
parentView.addSubview(rightShoulderButton)
leftTriggerButton = VgcButton(frame: CGRect(x: 0, y: buttonHeight + buttonSpacing, width: (parentView.bounds.width * 0.50) - buttonSpacing, height: buttonHeight), element: elements.leftTrigger)
leftTriggerButton.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleTopMargin, UIViewAutoresizing.FlexibleRightMargin]
parentView.addSubview(leftTriggerButton)
rightTriggerButton = VgcButton(frame: CGRect(x: (parentView.bounds.width * 0.50), y: buttonHeight + buttonSpacing, width: parentView.bounds.width * 0.50, height: buttonHeight), element: elements.rightTrigger)
rightTriggerButton.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleLeftMargin, UIViewAutoresizing.FlexibleTopMargin]
rightTriggerButton.valueLabel.textAlignment = .Left
parentView.addSubview(rightTriggerButton)
/*
// FOR TESTING CUSTOM ELEMENTS
centerTriggerButton = VgcButton(frame: CGRect(x: (parentView.bounds.width * 0.25), y: buttonHeight + buttonSpacing, width: parentView.bounds.width * 0.50, height: buttonHeight), element: custom[CustomElementType.FiddlestickX.rawValue]!)
centerTriggerButton.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleLeftMargin, UIViewAutoresizing.FlexibleTopMargin]
centerTriggerButton.valueLabel.textAlignment = .Center
parentView.addSubview(centerTriggerButton)
*/
var yPosition = (buttonHeight * 2) + (buttonSpacing * 2)
let padHeightWidth = parentView.bounds.size.width * 0.50
let abxyButtonPad = VgcAbxyButtonPad(frame: CGRect(x: (parentView.bounds.size.width * 0.50), y: yPosition, width: padHeightWidth, height: padHeightWidth))
abxyButtonPad.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleLeftMargin, UIViewAutoresizing.FlexibleTopMargin, UIViewAutoresizing.FlexibleRightMargin]
parentView.addSubview(abxyButtonPad)
let dpadPad = VgcStick(frame: CGRect(x: 0, y: yPosition, width: padHeightWidth - buttonSpacing, height: padHeightWidth), xElement: elements.dpadXAxis, yElement: elements.dpadYAxis)
dpadPad.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleRightMargin, UIViewAutoresizing.FlexibleTopMargin]
dpadPad.nameLabel.text = "dpad"
dpadPad.valueLabel.textAlignment = .Right
dpadPad.layer.cornerRadius = 0
dpadPad.controlView.layer.cornerRadius = 0
parentView.addSubview(dpadPad)
yPosition += padHeightWidth + 10
let leftThumbstickPad = VgcStick(frame: CGRect(x: marginSize, y: yPosition, width: stickSideSize , height: stickSideSize), xElement: elements.leftThumbstickXAxis, yElement: elements.leftThumbstickYAxis)
leftThumbstickPad.nameLabel.text = "L Thumb"
parentView.addSubview(leftThumbstickPad)
let rightThumbstickPad = VgcStick(frame: CGRect(x: parentView.bounds.size.width - stickSideSize - marginSize, y: yPosition, width: stickSideSize, height: stickSideSize), xElement: elements.rightThumbstickXAxis, yElement: elements.rightThumbstickYAxis)
rightThumbstickPad.nameLabel.text = "R Thumb"
parentView.addSubview(rightThumbstickPad)
let cameraBackground = UIView(frame: CGRect(x: parentView.bounds.size.width * 0.50 - 25, y: parentView.bounds.size.height - 49, width: 50, height: 40))
cameraBackground.backgroundColor = UIColor.lightGrayColor()
cameraBackground.layer.cornerRadius = 5
parentView.addSubview(cameraBackground)
let cameraImage = UIImageView(image: UIImage(named: "camera"))
cameraImage.contentMode = .Center
cameraImage.frame = CGRect(x: parentView.bounds.size.width * 0.50 - 25, y: parentView.bounds.size.height - 49, width: 50, height: 40)
cameraImage.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleTopMargin]
cameraImage.userInteractionEnabled = true
parentView.addSubview(cameraImage)
let gr = UITapGestureRecognizer(target: vc, action: "displayPhotoPicker:")
cameraImage.gestureRecognizers = [gr]
playerIndexLabel = UILabel(frame: CGRect(x: parentView.bounds.size.width * 0.50 - 50, y: parentView.bounds.size.height - 75, width: 100, height: 25))
playerIndexLabel.text = "Player: 0"
playerIndexLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleRightMargin, UIViewAutoresizing.FlexibleTopMargin]
playerIndexLabel.textColor = UIColor.grayColor()
playerIndexLabel.textAlignment = .Center
playerIndexLabel.font = UIFont(name: playerIndexLabel.font.fontName, size: 14)
parentView.addSubview(playerIndexLabel)
// This is hidden because it is only used to display the keyboard below in playerTappedToShowKeyboard
keyboardTextField = UITextField(frame: CGRect(x: -10, y: parentView.bounds.size.height + 30, width: 10, height: 10))
keyboardTextField.addTarget(self, action: "textFieldDidChange:", forControlEvents: .EditingChanged)
keyboardTextField.autocorrectionType = .No
parentView.addSubview(keyboardTextField)
// Set iCadeControllerMode when testing the use of an iCade controller
// Instead of displaying the button to the user to display an on-screen keyboard
// for string input, we make the hidden keyboardTextField the first responder so
// it receives controller input
if VgcManager.iCadeControllerMode != .Disabled {
keyboardTextField.becomeFirstResponder()
} else {
// let keyboardLabel = UIButton(frame: CGRect(x: marginSize, y: parentView.bounds.size.height - 46, width: 100, height: 44))
// keyboardLabel.backgroundColor = UIColor(white: CGFloat(0.76), alpha: 1.0)
// keyboardLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleTopMargin]
// keyboardLabel.setTitle("Keyboard", forState: .Normal)
// keyboardLabel.setTitleColor(UIColor.blackColor(), forState: .Normal)
// keyboardLabel.titleLabel!.font = UIFont(name: keyboardLabel.titleLabel!.font.fontName, size: 18)
// keyboardLabel.layer.cornerRadius = 2
// keyboardLabel.addTarget(self, action: "playerTappedToShowKeyboard:", forControlEvents: .TouchUpInside)
// keyboardLabel.userInteractionEnabled = true
// parentView.addSubview(keyboardLabel)
let keyboardBackground = UIView(frame: CGRect(x: marginSize, y: parentView.bounds.size.height - 49, width: 89, height: 42))
keyboardBackground.backgroundColor = UIColor.lightGrayColor()
keyboardBackground.layer.cornerRadius = 5
parentView.addSubview(keyboardBackground)
let keyboardImage = UIImageView(image: UIImage(named: "keyboard"))
keyboardImage.contentMode = .ScaleAspectFill
keyboardImage.frame = CGRect(x: marginSize - 6, y: parentView.bounds.size.height - 55, width: 100, height: 42)
keyboardImage.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleTopMargin]
keyboardImage.userInteractionEnabled = true
parentView.addSubview(keyboardImage)
let gr = UITapGestureRecognizer(target: self, action: "playerTappedToShowKeyboard:")
keyboardImage.gestureRecognizers = [gr]
}
/* Uncomment to sample software-based controller pause behavior, and comment out camera image
above since the two icons occupy the same space.
let pauseButtonSize = CGFloat(64.0)
let pauseButtonLabel = UIButton(frame: CGRect(x: (parentView.bounds.size.width * 0.50) - (pauseButtonSize * 0.50), y: parentView.bounds.size.height - (parentView.bounds.size.height * 0.15), width: pauseButtonSize, height: pauseButtonSize))
pauseButtonLabel.backgroundColor = UIColor(white: CGFloat(0.76), alpha: 1.0)
pauseButtonLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleTopMargin]
pauseButtonLabel.setTitle("||", forState: .Normal)
pauseButtonLabel.setTitleColor(UIColor.blackColor(), forState: .Normal)
pauseButtonLabel.titleLabel!.font = UIFont(name: pauseButtonLabel.titleLabel!.font.fontName, size: 35)
pauseButtonLabel.layer.cornerRadius = 10
pauseButtonLabel.addTarget(self, action: "playerTappedToPause:", forControlEvents: .TouchUpInside)
pauseButtonLabel.userInteractionEnabled = true
parentView.addSubview(pauseButtonLabel)
*/
let motionLabel = UILabel(frame: CGRect(x: parentView.bounds.size.width - 63, y: parentView.bounds.size.height - 58, width: 50, height: 25))
motionLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleTopMargin]
motionLabel.text = "Motion"
motionLabel.textAlignment = .Center
motionLabel.textColor = UIColor.whiteColor()
//motionLabel.backgroundColor = UIColor.redColor()
motionLabel.font = UIFont(name: motionLabel.font.fontName, size: 10)
parentView.addSubview(motionLabel)
#if !(os(tvOS))
motionSwitch = UISwitch(frame:CGRect(x: parentView.bounds.size.width - 63, y: parentView.bounds.size.height - 37, width: 45, height: 30))
motionSwitch.on = false
//motionSwitch.setOn(true, animated: false);
motionSwitch.addTarget(self, action: "motionSwitchDidChange:", forControlEvents: .ValueChanged);
motionSwitch.backgroundColor = UIColor.lightGrayColor()
motionSwitch.layer.cornerRadius = 15
parentView.addSubview(motionSwitch);
#endif
} else {
marginSize = 10
parentView.backgroundColor = UIColor.blackColor()
let dpadSize = parentView.bounds.size.height * 0.50
let lightBlackColor = UIColor.init(red: 0.08, green: 0.08, blue: 0.08, alpha: 1.0)
let leftThumbstickPad = VgcStick(frame: CGRect(x: (parentView.bounds.size.width - dpadSize) * 0.50, y: 24, width: dpadSize, height: parentView.bounds.size.height * 0.50), xElement: elements.dpadXAxis, yElement: elements.dpadYAxis)
leftThumbstickPad.nameLabel.text = "dpad"
leftThumbstickPad.nameLabel.textColor = UIColor.lightGrayColor()
leftThumbstickPad.nameLabel.font = UIFont(name: leftThumbstickPad.nameLabel.font.fontName, size: 15)
leftThumbstickPad.valueLabel.textColor = UIColor.lightGrayColor()
leftThumbstickPad.valueLabel.font = UIFont(name: leftThumbstickPad.nameLabel.font.fontName, size: 15)
leftThumbstickPad.backgroundColor = lightBlackColor
leftThumbstickPad.controlView.backgroundColor = lightBlackColor
parentView.addSubview(leftThumbstickPad)
let buttonHeight = parentView.bounds.size.height * 0.20
let aButton = VgcButton(frame: CGRect(x: 0, y: parentView.bounds.size.height - (buttonHeight * 2) - 20, width: (parentView.bounds.width) - buttonSpacing, height: buttonHeight), element: elements.buttonA)
aButton.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleTopMargin, UIViewAutoresizing.FlexibleRightMargin]
aButton.nameLabel.font = UIFont(name: aButton.nameLabel.font.fontName, size: 40)
aButton.valueLabel.font = UIFont(name: aButton.valueLabel.font.fontName, size: 20)
aButton.baseGrayShade = 0.08
aButton.nameLabel.textColor = UIColor.lightGrayColor()
aButton.valueLabel.textColor = UIColor.lightGrayColor()
parentView.addSubview(aButton)
let xButton = VgcButton(frame: CGRect(x: 0, y: parentView.bounds.size.height - buttonHeight - 10, width: parentView.bounds.width, height: buttonHeight), element: elements.buttonX)
xButton.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleLeftMargin, UIViewAutoresizing.FlexibleTopMargin]
xButton.valueLabel.textAlignment = .Right
xButton.nameLabel.font = UIFont(name: xButton.nameLabel.font.fontName, size: 40)
xButton.valueLabel.font = UIFont(name: xButton.valueLabel.font.fontName, size: 20)
xButton.baseGrayShade = 0.08
xButton.nameLabel.textColor = UIColor.lightGrayColor()
xButton.valueLabel.textColor = UIColor.lightGrayColor()
parentView.addSubview(xButton)
}
controlOverlay = UIView(frame: CGRect(x: 0, y: 0, width: parentView.bounds.size.width, height: parentView.bounds.size.height))
controlOverlay.backgroundColor = UIColor.blackColor()
controlOverlay.alpha = 0.9
parentView.addSubview(controlOverlay)
controlLabel = UILabel(frame: CGRect(x: 0, y: controlOverlay.bounds.size.height * 0.35, width: controlOverlay.bounds.size.width, height: 25))
controlLabel.autoresizingMask = [UIViewAutoresizing.FlexibleRightMargin , UIViewAutoresizing.FlexibleBottomMargin]
controlLabel.text = "Seeking Centrals..."
controlLabel.textAlignment = .Center
controlLabel.textColor = UIColor.whiteColor()
controlLabel.font = UIFont(name: controlLabel.font.fontName, size: 20)
controlOverlay.addSubview(controlLabel)
activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, controlOverlay.bounds.size.height * 0.40, controlOverlay.bounds.size.width, 50)) as UIActivityIndicatorView
activityIndicator.autoresizingMask = [UIViewAutoresizing.FlexibleRightMargin , UIViewAutoresizing.FlexibleBottomMargin]
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.White
controlOverlay.addSubview(activityIndicator)
activityIndicator.startAnimating()
serviceSelectorView = ServiceSelectorView(frame: CGRectMake(25, controlOverlay.bounds.size.height * 0.50, controlOverlay.bounds.size.width - 50, controlOverlay.bounds.size.height - 200))
serviceSelectorView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleRightMargin]
controlOverlay.addSubview(serviceSelectorView)
}
@objc func peripheralDidConnect(notification: NSNotification) {
vgcLogDebug("Animating control overlay up")
UIView.animateWithDuration(animationSpeed, delay: 0.0, options: .CurveEaseIn, animations: {
self.controlOverlay.frame = CGRect(x: 0, y: -self.parentView.bounds.size.height, width: self.parentView.bounds.size.width, height: self.parentView.bounds.size.height)
}, completion: { finished in
})
}
#if !os(tvOS)
@objc func peripheralDidDisconnect(notification: NSNotification) {
vgcLogDebug("Animating control overlay down")
UIView.animateWithDuration(animationSpeed, delay: 0.0, options: .CurveEaseIn, animations: {
self.controlOverlay.frame = CGRect(x: 0, y: 0, width: self.parentView.bounds.size.width, height: self.parentView.bounds.size.height)
}, completion: { finished in
self.serviceSelectorView.refresh()
if self.motionSwitch != nil { self.motionSwitch.on = false }
})
}
#endif
@objc func gotPlayerIndex(notification: NSNotification) {
let playerIndex: Int = notification.object as! Int
if playerIndexLabel != nil { playerIndexLabel.text = "Player \(playerIndex + 1)" }
}
@objc func playerTappedToPause(sender: AnyObject) {
// Pause toggles, so we send both states at once
elements.pauseButton.value = 1.0
VgcManager.peripheral.sendElementState(elements.pauseButton)
}
@objc func playerTappedToShowKeyboard(sender: AnyObject) {
if VgcManager.iCadeControllerMode != .Disabled { return }
keyboardControlView = UIView(frame: CGRect(x: 0, y: parentView.bounds.size.height, width: parentView.bounds.size.width, height: parentView.bounds.size.height))
keyboardControlView.backgroundColor = UIColor.darkGrayColor()
parentView.addSubview(keyboardControlView)
let dismissKeyboardGR = UITapGestureRecognizer(target: self, action:Selector("dismissKeyboard"))
keyboardControlView.gestureRecognizers = [dismissKeyboardGR]
keyboardLabel = UILabel(frame: CGRect(x: 0, y: 0, width: keyboardControlView.bounds.size.width, height: keyboardControlView.bounds.size.height * 0.60))
keyboardLabel.text = ""
keyboardLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleRightMargin, UIViewAutoresizing.FlexibleTopMargin]
keyboardLabel.textColor = UIColor.whiteColor()
keyboardLabel.textAlignment = .Center
keyboardLabel.font = UIFont(name: keyboardLabel.font.fontName, size: 40)
keyboardLabel.adjustsFontSizeToFitWidth = true
keyboardLabel.numberOfLines = 5
keyboardControlView.addSubview(keyboardLabel)
UIView.animateWithDuration(animationSpeed, delay: 0.0, options: .CurveEaseIn, animations: {
self.keyboardControlView.frame = self.parentView.bounds
}, completion: { finished in
})
keyboardTextField.becomeFirstResponder()
}
func dismissKeyboard() {
keyboardTextField.resignFirstResponder()
UIView.animateWithDuration(animationSpeed, delay: 0.0, options: .CurveEaseIn, animations: {
self.keyboardControlView.frame = CGRect(x: 0, y: self.parentView.bounds.size.height, width: self.parentView.bounds.size.width, height: self.parentView.bounds.size.height)
}, completion: { finished in
})
}
func textFieldDidChange(sender: AnyObject) {
if VgcManager.iCadeControllerMode != .Disabled {
vgcLogDebug("Sending iCade character: \(keyboardTextField.text) using iCade mode: \(VgcManager.iCadeControllerMode.description)")
var element: Element!
var value: Int
(element, value) = VgcManager.iCadePeripheral.elementForCharacter(keyboardTextField.text!, controllerElements: elements)
keyboardTextField.text = ""
if element == nil { return }
element.value = value
VgcManager.peripheral.sendElementState(element)
} else {
keyboardLabel.text = keyboardTextField.text!
VgcManager.elements.custom[CustomElementType.Keyboard.rawValue]!.value = keyboardTextField.text!
VgcManager.peripheral.sendElementState(VgcManager.elements.custom[CustomElementType.Keyboard.rawValue]!)
keyboardTextField.text = ""
}
}
#if !(os(tvOS))
func motionSwitchDidChange(sender:UISwitch!) {
vgcLogDebug("User modified motion switch: \(sender.on)")
if sender.on == true {
VgcManager.peripheral.motion.start()
} else {
VgcManager.peripheral.motion.stop()
}
}
#endif
}
// Provides a view over the Peripheral control pad that allows the end user to
// select which Central/Bridge to connect to.
public class ServiceSelectorView: UIView, UITableViewDataSource, UITableViewDelegate {
var tableView: UITableView!
override init(frame: CGRect) {
super.init(frame: frame)
tableView = UITableView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
tableView.layer.cornerRadius = 20.0
tableView.backgroundColor = UIColor.clearColor()
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = 44.0
self.addSubview(tableView)
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
public func refresh() {
vgcLogDebug("Refreshing server selector view")
self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Automatic)
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableView.frame = CGRectMake(0, 0, tableView.bounds.size.width, CGFloat(tableView.rowHeight) * CGFloat(VgcManager.peripheral.availableServices.count))
return VgcManager.peripheral.availableServices.count
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
let serviceName = VgcManager.peripheral.availableServices[indexPath.row].fullName
cell.textLabel?.font = UIFont(name: cell.textLabel!.font.fontName, size: 16)
cell.textLabel?.text = serviceName
cell.backgroundColor = UIColor.grayColor()
cell.alpha = 1.0
cell.textLabel?.textColor = UIColor.whiteColor()
return cell
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if VgcManager.peripheral.availableServices.count > 0 {
let service = VgcManager.peripheral.availableServices[indexPath.row]
VgcManager.peripheral.connectToService(service)
}
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// Basic button element, with support for 3d touch
class VgcButton: UIView {
let element: Element!
var nameLabel: UILabel!
var valueLabel: UILabel!
var _baseGrayShade: Float = 0.76
var baseGrayShade: Float {
get {
return _baseGrayShade
}
set {
_baseGrayShade = newValue
self.backgroundColor = UIColor(white: CGFloat(_baseGrayShade), alpha: 1.0)
}
}
var value: Float {
get {
return self.value
}
set {
self.value = newValue
}
}
init(frame: CGRect, element: Element) {
self.element = element
super.init(frame: frame)
baseGrayShade = 0.76
nameLabel = UILabel(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
nameLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight]
nameLabel.text = element.name
nameLabel.textAlignment = .Center
nameLabel.font = UIFont(name: nameLabel.font.fontName, size: 20)
self.addSubview(nameLabel)
valueLabel = UILabel(frame: CGRect(x: 10, y: frame.size.height * 0.70, width: frame.size.width - 20, height: frame.size.height * 0.30))
valueLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleTopMargin]
valueLabel.text = "0.0"
valueLabel.textAlignment = .Center
valueLabel.font = UIFont(name: valueLabel.font.fontName, size: 10)
valueLabel.textAlignment = .Right
self.addSubview(valueLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func percentageForce(touch: UITouch) -> Float {
let force = Float(touch.force)
let maxForce = Float(touch.maximumPossibleForce)
let percentageForce: Float
if (force == 0) { percentageForce = 0 } else { percentageForce = force / maxForce }
return percentageForce
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
// If 3d touch is not supported, just send a "1" value
if (self.traitCollection.forceTouchCapability == .Available) {
element.value = self.percentageForce(touch!)
valueLabel.text = "\(element.value)"
let colorValue = CGFloat(baseGrayShade - (element.value as! Float / 10))
self.backgroundColor = UIColor(red: colorValue, green: colorValue, blue: colorValue, alpha: 1)
} else {
element.value = 1.0
valueLabel.text = "\(element.value)"
self.backgroundColor = UIColor(red: 0.30, green: 0.30, blue: 0.30, alpha: 1)
}
VgcManager.peripheral.sendElementState(element)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
// If 3d touch is not supported, just send a "1" value
if (self.traitCollection.forceTouchCapability == .Available) {
element.value = self.percentageForce(touch!)
valueLabel.text = "\(element.value)"
let colorValue = CGFloat(baseGrayShade - (element.value as! Float) / 10)
self.backgroundColor = UIColor(red: colorValue, green: colorValue, blue: colorValue, alpha: 1)
} else {
element.value = 1.0
valueLabel.text = "\(element.value)"
self.backgroundColor = UIColor(red: 0.30, green: 0.30, blue: 0.30, alpha: 1)
}
VgcManager.peripheral.sendElementState(element)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
element.value = 0.0
valueLabel.text = "\(element.value)"
VgcManager.peripheral.sendElementState(element)
self.backgroundColor = UIColor(white: CGFloat(baseGrayShade), alpha: 1.0)
}
}
class VgcStick: UIView {
let xElement: Element!
let yElement: Element!
var nameLabel: UILabel!
var valueLabel: UILabel!
var controlView: UIView!
var touchesView: UIView!
var value: Float {
get {
return self.value
}
set {
self.value = newValue
}
}
init(frame: CGRect, xElement: Element, yElement: Element) {
self.xElement = xElement
self.yElement = yElement
super.init(frame: frame)
nameLabel = UILabel(frame: CGRect(x: 0, y: frame.size.height - 20, width: frame.size.width, height: 15))
nameLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight]
nameLabel.textAlignment = .Center
nameLabel.font = UIFont(name: nameLabel.font.fontName, size: 10)
self.addSubview(nameLabel)
valueLabel = UILabel(frame: CGRect(x: 10, y: 10, width: frame.size.width - 20, height: 15))
valueLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleTopMargin]
valueLabel.text = "0.0/0.0"
valueLabel.font = UIFont(name: valueLabel.font.fontName, size: 10)
valueLabel.textAlignment = .Center
self.addSubview(valueLabel)
let controlViewSide = frame.height * 0.40
controlView = UIView(frame: CGRect(x: controlViewSide, y: controlViewSide, width: controlViewSide, height: controlViewSide))
controlView.layer.cornerRadius = controlView.bounds.size.width / 2
controlView.backgroundColor = UIColor.blackColor()
self.addSubview(controlView)
self.backgroundColor = peripheralBackgroundColor
self.layer.cornerRadius = frame.width / 2
self.centerController(0.0)
if VgcManager.peripheral.deviceInfo.profileType == .MicroGamepad {
touchesView = self
controlView.userInteractionEnabled = false
controlView.hidden = true
} else {
touchesView = controlView
controlView.userInteractionEnabled = true
controlView.hidden = false
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func percentageForce(touch: UITouch) -> Float {
let force = Float(touch.force)
let maxForce = Float(touch.maximumPossibleForce)
let percentageForce: Float
if (force == 0) { percentageForce = 0 } else { percentageForce = force / maxForce }
return percentageForce
}
// Manage the frequency of updates
var lastMotionRefresh: NSDate = NSDate()
func processTouch(touch: UITouch!) {
if touch!.view == touchesView {
// Avoid updating too often
if lastMotionRefresh.timeIntervalSinceNow > -(1 / 60) { return } else { lastMotionRefresh = NSDate() }
// Prevent the stick from leaving the view center area
var newX = touch!.locationInView(self).x
var newY = touch!.locationInView(self).y
let movementMarginSize = self.bounds.size.width * 0.25
if newX < movementMarginSize { newX = movementMarginSize}
if newX > self.bounds.size.width - movementMarginSize { newX = self.bounds.size.width - movementMarginSize }
if newY < movementMarginSize { newY = movementMarginSize }
if newY > self.bounds.size.height - movementMarginSize { newY = self.bounds.size.height - movementMarginSize }
controlView.center = CGPoint(x: newX, y: newY)
// Regularize the value between -1 and 1
let rangeSize = self.bounds.size.height - (movementMarginSize * 2.0)
let xValue = (((newX / rangeSize) - 0.5) * 2.0) - 1.0
var yValue = (((newY / rangeSize) - 0.5) * 2.0) - 1.0
yValue = -(yValue)
xElement.value = Float(xValue)
yElement.value = Float(yValue)
VgcManager.peripheral.sendElementState(xElement)
VgcManager.peripheral.sendElementState(yElement)
valueLabel.text = "\(round(xValue * 100.0) / 100)/\(round(yValue * 100.0) / 100)"
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
self.processTouch(touch)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
if touch!.view == touchesView {
self.centerController(0.1)
}
xElement.value = Float(0)
yElement.value = Float(0)
VgcManager.peripheral.sendElementState(xElement)
VgcManager.peripheral.sendElementState(yElement)
}
// Re-center the control element
func centerController(duration: Double) {
UIView.animateWithDuration(duration, delay: 0.0, options: .CurveEaseIn, animations: {
self.controlView.center = CGPoint(x: ((self.bounds.size.height * 0.50)), y: ((self.bounds.size.width * 0.50)))
}, completion: { finished in
self.valueLabel.text = "0/0"
})
}
}
class VgcAbxyButtonPad: UIView {
let elements = VgcManager.elements
var aButton: VgcButton!
var bButton: VgcButton!
var xButton: VgcButton!
var yButton: VgcButton!
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = peripheralBackgroundColor
let buttonWidth = frame.size.width * 0.33333
let buttonHeight = frame.size.height * 0.33333
let buttonMargin: CGFloat = 10.0
let fontSize: CGFloat = 35.0
yButton = VgcButton(frame: CGRect(x: buttonWidth, y: buttonMargin, width: buttonWidth, height: buttonHeight), element: elements.buttonY)
yButton.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleLeftMargin, UIViewAutoresizing.FlexibleRightMargin, UIViewAutoresizing.FlexibleBottomMargin]
yButton.nameLabel.textAlignment = .Center
yButton.valueLabel.textAlignment = .Center
yButton.layer.cornerRadius = yButton.bounds.size.width / 2
yButton.nameLabel.textColor = UIColor.blueColor()
yButton.baseGrayShade = 0.0
yButton.valueLabel.textColor = UIColor.whiteColor()
yButton.nameLabel.font = UIFont(name: yButton.nameLabel.font.fontName, size: fontSize)
self.addSubview(yButton)
xButton = VgcButton(frame: CGRect(x: buttonMargin, y: buttonHeight, width: buttonWidth, height: buttonHeight), element: elements.buttonX)
xButton.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleTopMargin, UIViewAutoresizing.FlexibleRightMargin, UIViewAutoresizing.FlexibleBottomMargin]
xButton.nameLabel.textAlignment = .Center
xButton.valueLabel.textAlignment = .Center
xButton.layer.cornerRadius = xButton.bounds.size.width / 2
xButton.nameLabel.textColor = UIColor.yellowColor()
xButton.baseGrayShade = 0.0
xButton.valueLabel.textColor = UIColor.whiteColor()
xButton.nameLabel.font = UIFont(name: xButton.nameLabel.font.fontName, size: fontSize)
self.addSubview(xButton)
bButton = VgcButton(frame: CGRect(x: frame.size.width - buttonWidth - buttonMargin, y: buttonHeight, width: buttonWidth, height: buttonHeight), element: elements.buttonB)
bButton.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleLeftMargin, UIViewAutoresizing.FlexibleTopMargin, UIViewAutoresizing.FlexibleBottomMargin]
bButton.nameLabel.textAlignment = .Center
bButton.valueLabel.textAlignment = .Center
bButton.layer.cornerRadius = bButton.bounds.size.width / 2
bButton.nameLabel.textColor = UIColor.greenColor()
bButton.baseGrayShade = 0.0
bButton.valueLabel.textColor = UIColor.whiteColor()
bButton.nameLabel.font = UIFont(name: bButton.nameLabel.font.fontName, size: fontSize)
self.addSubview(bButton)
aButton = VgcButton(frame: CGRect(x: buttonWidth, y: buttonHeight * 2.0 - buttonMargin, width: buttonWidth, height: buttonHeight), element: elements.buttonA)
aButton.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleLeftMargin, UIViewAutoresizing.FlexibleRightMargin, UIViewAutoresizing.FlexibleTopMargin]
aButton.nameLabel.textAlignment = .Center
aButton.valueLabel.textAlignment = .Center
aButton.layer.cornerRadius = aButton.bounds.size.width / 2
aButton.nameLabel.textColor = UIColor.redColor()
aButton.baseGrayShade = 0.0
aButton.valueLabel.textColor = UIColor.whiteColor()
aButton.nameLabel.font = UIFont(name: aButton.nameLabel.font.fontName, size: fontSize)
self.addSubview(aButton)
}
}
public class ElementDebugView: UIView {
var elementLabelLookup = Dictionary<Int, UILabel>()
var elementBackgroundLookup = Dictionary<Int, UIView>()
var controllerVendorName: UILabel!
var scrollView: UIScrollView!
var controller: VgcController!
var titleRegion: UIView!
var imageView: UIImageView!
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public init(frame: CGRect, controller: VgcController) {
self.controller = controller
super.init(frame: frame)
let debugViewTapGR = UITapGestureRecognizer(target: self, action: "receivedDebugViewTap")
let debugViewDoubleTapGR = UITapGestureRecognizer(target: self, action: "receivedDebugViewDoubleTap")
debugViewDoubleTapGR.numberOfTapsRequired = 2
self.gestureRecognizers = [debugViewTapGR, debugViewDoubleTapGR]
debugViewTapGR.requireGestureRecognizerToFail(debugViewDoubleTapGR)
self.backgroundColor = UIColor.whiteColor()
//self.layer.cornerRadius = 15
self.layer.shadowOffset = CGSizeMake(5, 5)
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowRadius = 3.0
self.layer.shadowOpacity = 0.3
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.mainScreen().scale
titleRegion = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 140))
titleRegion.autoresizingMask = [UIViewAutoresizing.FlexibleWidth]
titleRegion.backgroundColor = UIColor.lightGrayColor()
titleRegion.clipsToBounds = true
self.addSubview(titleRegion)
imageView = UIImageView(frame: CGRect(x: self.bounds.size.width - 110, y: 150, width: 100, height: 100))
imageView.contentMode = .ScaleAspectFit
self.addSubview(imageView)
controllerVendorName = UILabel(frame: CGRect(x: 0, y: 0, width: titleRegion.frame.size.width, height: 50))
controllerVendorName.backgroundColor = UIColor.lightGrayColor()
controllerVendorName.autoresizingMask = [UIViewAutoresizing.FlexibleWidth]
controllerVendorName.text = controller.deviceInfo.vendorName
controllerVendorName.textAlignment = .Center
controllerVendorName.font = UIFont(name: controllerVendorName.font.fontName, size: 20)
controllerVendorName.clipsToBounds = true
titleRegion.addSubview(controllerVendorName)
var labelHeight: CGFloat = 20.0
let deviceDetailsFontSize: CGFloat = 14.0
let leftMargin: CGFloat = 40.0
var yPosition = controllerVendorName.bounds.size.height
let controllerTypeLabel = UILabel(frame: CGRect(x: leftMargin, y: yPosition, width: titleRegion.frame.size.width - 50, height: labelHeight))
controllerTypeLabel.backgroundColor = UIColor.lightGrayColor()
controllerTypeLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth]
controllerTypeLabel.text = "Controller Type: " + controller.deviceInfo.controllerType.description
controllerTypeLabel.textAlignment = .Left
controllerTypeLabel.font = UIFont(name: controllerTypeLabel.font.fontName, size: deviceDetailsFontSize)
titleRegion.addSubview(controllerTypeLabel)
yPosition += labelHeight
let profileTypeLabel = UILabel(frame: CGRect(x: leftMargin, y: yPosition, width: titleRegion.frame.size.width - 50, height: labelHeight))
profileTypeLabel.backgroundColor = UIColor.lightGrayColor()
profileTypeLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth]
profileTypeLabel.text = "Profile Type: " + controller.profileType.description
profileTypeLabel.textAlignment = .Left
profileTypeLabel.font = UIFont(name: profileTypeLabel.font.fontName, size: deviceDetailsFontSize)
titleRegion.addSubview(profileTypeLabel)
yPosition += labelHeight
let attachedLabel = UILabel(frame: CGRect(x: leftMargin, y: yPosition, width: titleRegion.frame.size.width - 50, height: labelHeight))
attachedLabel.backgroundColor = UIColor.lightGrayColor()
attachedLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth]
attachedLabel.text = "Attached to Device: " + "\(controller.deviceInfo.attachedToDevice)"
attachedLabel.textAlignment = .Left
attachedLabel.font = UIFont(name: profileTypeLabel.font.fontName, size: deviceDetailsFontSize)
titleRegion.addSubview(attachedLabel)
yPosition += labelHeight
let supportsMotionLabel = UILabel(frame: CGRect(x: leftMargin, y: yPosition, width: titleRegion.frame.size.width - 50, height: labelHeight))
supportsMotionLabel.backgroundColor = UIColor.lightGrayColor()
supportsMotionLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth]
supportsMotionLabel.text = "Supports Motion: " + "\(controller.deviceInfo.supportsMotion)"
supportsMotionLabel.textAlignment = .Left
supportsMotionLabel.font = UIFont(name: supportsMotionLabel.font.fontName, size: deviceDetailsFontSize)
titleRegion.addSubview(supportsMotionLabel)
// Scrollview allows the element values to scroll vertically, especially important on phones
scrollView = UIScrollView(frame: CGRect(x: 0, y: titleRegion.bounds.size.height + 10, width: frame.size.width, height: frame.size.height - titleRegion.bounds.size.height - 10))
scrollView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
self.addSubview(scrollView)
labelHeight = CGFloat(22.0)
yPosition = CGFloat(10.0)
if deviceIsTypeOfBridge() && VgcManager.bridgeRelayOnly {
let elementLabel = UILabel(frame: CGRect(x: 10, y: yPosition, width: frame.size.width - 20, height: labelHeight * 2))
elementLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleRightMargin]
elementLabel.text = "In relay-only mode - no data will display here."
elementLabel.textAlignment = .Center
elementLabel.font = UIFont(name: controllerVendorName.font.fontName, size: 16)
elementLabel.numberOfLines = 2
scrollView.addSubview(elementLabel)
return
}
for element in VgcManager.elements.elementsForController(controller) {
let elementBackground = UIView(frame: CGRect(x: (frame.size.width * 0.50) + 15, y: yPosition, width: 0, height: labelHeight))
elementBackground.backgroundColor = UIColor.lightGrayColor()
elementBackground.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleLeftMargin]
scrollView.addSubview(elementBackground)
let elementLabel = UILabel(frame: CGRect(x: 10, y: yPosition, width: frame.size.width * 0.50, height: labelHeight))
elementLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleRightMargin]
elementLabel.text = "\(element.name):"
elementLabel.textAlignment = .Right
elementLabel.font = UIFont(name: controllerVendorName.font.fontName, size: 16)
scrollView.addSubview(elementLabel)
let elementValue = UILabel(frame: CGRect(x: (frame.size.width * 0.50) + 15, y: yPosition, width: frame.size.width * 0.50, height: labelHeight))
elementValue.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleLeftMargin]
elementValue.text = "0"
elementValue.font = UIFont(name: controllerVendorName.font.fontName, size: 16)
scrollView.addSubview(elementValue)
elementBackgroundLookup[element.identifier] = elementBackground
elementLabelLookup[element.identifier] = elementValue
yPosition += labelHeight
}
scrollView.contentSize = CGSize(width: frame.size.width, height: yPosition + 40)
}
// Demonstrate bidirectional communication using a simple tap on the
// Central debug view to send a message to one or all Peripherals.
// Use of a custom element is demonstrated; both standard and custom
// are supported.
public func receivedDebugViewTap() {
// Test vibrate using standard system element
controller.vibrateDevice()
// Test vibrate using custom element
/*
let element = controller.elements.custom[CustomElementType.VibrateDevice.rawValue]!
element.value = 1
VgcController.sendElementStateToAllPeripherals(element)
*/
}
public func receivedDebugViewDoubleTap() {
let imageElement = VgcManager.elements.elementFromIdentifier(ElementType.Image.rawValue)
let imageData = UIImageJPEGRepresentation(UIImage(named: "digit.jpg")!, 1.0)
imageElement.value = imageData!
imageElement.clearValueAfterTransfer = true
controller.sendElementStateToPeripheral(imageElement)
return
let element = controller.elements.rightTrigger
element.value = 1.0
controller.sendElementStateToPeripheral(element)
}
public func receivedDebugViewTripleTap() {
let imageElement = VgcManager.elements.elementFromIdentifier(ElementType.Image.rawValue)
let imageData = UIImageJPEGRepresentation(UIImage(named: "digit.jpg")!, 1.0)
imageElement.value = imageData!
imageElement.clearValueAfterTransfer = true
controller.sendElementStateToPeripheral(imageElement)
// Test simple float mode
//let rightShoulder = controller.elements.rightShoulder
//rightShoulder.value = 1.0
//controller.sendElementStateToPeripheral(rightShoulder)
//VgcController.sendElementStateToAllPeripherals(rightShoulder)
// Test string mode
let keyboard = controller.elements.custom[CustomElementType.Keyboard.rawValue]!
keyboard.value = "1 2 3 4 5 6 7 8"
keyboard.value = "Before newline\nAfter newline\n\n\n"
controller.sendElementStateToPeripheral(keyboard)
//VgcController.sendElementStateToAllPeripherals(keyboard)
}
// The Central is in charge of managing the toggled state of the
// pause button on a controller; we're doing that here just using
// the current background color to track state.
public func togglePauseState() {
if (self.backgroundColor == UIColor.whiteColor()) {
self.backgroundColor = UIColor.lightGrayColor()
} else {
self.backgroundColor = UIColor.whiteColor()
}
}
// Instead of refreshing individual values by setting up handlers, we use a
// global handler and refresh all the values.
public func refresh(controller: VgcController) {
self.controllerVendorName.text = controller.deviceInfo.vendorName
for element in controller.elements.elementsForController(controller) {
if let label = self.elementLabelLookup[element.identifier] {
let keypath = element.getterKeypath(controller)
var value: AnyObject
if element.type == .Custom {
if element.dataType == .Data {
value = ""
} else {
value = (controller.elements.custom[element.identifier]?.value)!
}
if element.dataType == .String && value as! NSObject == 0 { value = "" }
} else if keypath != "" {
value = controller.valueForKeyPath(keypath)!
} else {
value = ""
}
// PlayerIndex uses enumerated values that are offset by 1
if element == controller.elements.playerIndex {
label.text = "\(controller.playerIndex.rawValue + 1)"
continue
}
label.text = "\(value)"
let stringValue = "\(value)"
// Pause will be empty
if stringValue == "" { continue }
if element.dataType == .Float {
let valFloat = Float(stringValue)! as Float
if let backgroundView = self.elementBackgroundLookup[element.identifier] {
var width = label.bounds.size.width * CGFloat(valFloat)
if (width > 0 && width < 0.1) || (width < 0 && width > -0.1) { width = 0 }
backgroundView.frame = CGRect(x: (label.bounds.size.width) + 15, y: backgroundView.frame.origin.y, width: width, height: backgroundView.bounds.size.height)
}
} else if element.dataType == .Int {
let valInt = Int(stringValue)! as Int
if let backgroundView = self.elementBackgroundLookup[element.identifier] {
var width = label.bounds.size.width * CGFloat(valInt)
if (width > 0 && width < 0.1) || (width < 0 && width > -0.1) { width = 0 }
backgroundView.frame = CGRect(x: (label.bounds.size.width) + 15, y: backgroundView.frame.origin.y, width: width, height: backgroundView.bounds.size.height)
}
} else if element.dataType == .String {
if stringValue != "" {
label.backgroundColor = UIColor.lightGrayColor()
} else {
label.backgroundColor = UIColor.clearColor()
}
}
}
}
}
}
| mit | a543e401369ca7952530691989601238 | 49.726179 | 273 | 0.663864 | 5.345063 | false | false | false | false |
SunnyPRO/Taylor | TaylorFrameworkTests/TemperTests/NSFileManagerTests.swift | 1 | 1758 | //
// NSFileManagerTests.swift
// Temper
//
// Created by Seremet Mihai on 10/7/15.
// Copyright © 2015 Yopeso. All rights reserved.
//
import Foundation
import Nimble
import Quick
@testable import TaylorFramework
class NSFileManagerTests: QuickSpec {
override func spec() {
describe("NSFileManager") {
it("should remove file at path") {
let manager = FileManager.default
let path = manager.currentDirectoryPath as NSString
let filePath = path.appendingPathComponent("file.txt") as String
let content = "ia ibu"
do {
try content.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
} catch _ { }
expect(manager.fileExists(atPath: filePath)).to(beTrue())
manager.removeFileAtPath(filePath)
expect(manager.fileExists(atPath: filePath)).to(beFalse())
}
it("should't remove directory at path") {
let manager = FileManager.default
expect(manager.fileExists(atPath: manager.currentDirectoryPath)).to(beTrue())
if manager.fileExists(atPath: (manager.currentDirectoryPath as NSString).appendingPathComponent("blablabla")) {
do {
try manager.removeItem(atPath: (manager.currentDirectoryPath as NSString).appendingPathComponent("blablabla"))
} catch let error {
print(error)
}
}
expect(manager.fileExists(atPath: (manager.currentDirectoryPath as NSString).appendingPathComponent("blablabla"))).to(beFalse())
}
}
}
}
| mit | 952fc28770a8b72014f3ced52ef91dc4 | 39.860465 | 144 | 0.586796 | 5.260479 | false | true | false | false |
volodg/iAsync.reactiveKit | Sources/AsyncStreamValue.swift | 1 | 6720 | //
// AsyncStreamValue.swift
// iAsync_reactiveKit
//
// Created by Gorbenko Vladimir on 10/02/16.
// Copyright © 2016 EmbeddedSystems. All rights reserved.
//
import Foundation
import iAsync_utils
import ReactiveKit
public struct AsyncValue<ValueT, ErrorT: Error> {
public var result: Result<ValueT, ErrorT>? = nil
public var loading: Bool = false
public init() {}
public init(result: Result<ValueT, ErrorT>?, loading: Bool = false) {
self.result = result
self.loading = loading
}
public func mapStream<R>(_ f: (ValueT) -> Signal1<R>) -> Signal1<AsyncValue<R, ErrorT>> {
switch result {
case .some(.success(let v)):
return f(v).map { (val: R) -> AsyncValue<R, ErrorT> in
let result = AsyncValue<R, ErrorT>(result: .success(val), loading: self.loading)
return result
}
case .some(.failure(let error)):
let value = AsyncValue<R, ErrorT>(result: .failure(error), loading: self.loading)
return Signal.next(value)
case .none:
let value = AsyncValue<R, ErrorT>(result: .none, loading: self.loading)
return Signal.next(value)
}
}
public func mapStream2<R>(_ f: (ValueT) -> Signal1<AsyncValue<R, ErrorT>>) -> Signal1<AsyncValue<R, ErrorT>> {
switch result {
case .some(.success(let v)):
return f(v)
case .some(.failure(let error)):
let value = AsyncValue<R, ErrorT>(result: .failure(error), loading: self.loading)
return Signal1.next(value)
case .none:
let value = AsyncValue<R, ErrorT>(result: .none, loading: self.loading)
return Signal1.next(value)
}
}
}
public extension AsyncStreamType {
func bindedToObservableAsyncVal<B : BindableProtocol>
(_ bindable: B) -> AsyncStream<ValueT, NextT, ErrorT> where
B.Element == AsyncValue<ValueT, ErrorT>, B: PropertyProtocol, B.ProperyElement == AsyncValue<ValueT, ErrorT> {
return AsyncStream { observer -> Disposable in
var result = bindable.value
result.loading = true
let bindedSignal = Property(result)
let disposes = CompositeDisposable()
let dispose1 = bindable.bind(signal: bindedSignal.toSignal().ignoreTerminal())
disposes.add(disposable: dispose1)
let dispose2 = self.observe { event -> () in
switch event {
case .success(let value):
result.result = .success(value)
result.loading = false
bindedSignal.value = result
case .failure(let error):
if bindable.value.result?.value == nil {
result.result = .failure(error)
}
result.loading = false
bindedSignal.value = result
default:
break
}
observer(event)
}
disposes.add(disposable: dispose2)
return disposes
}
}
}
extension MergedAsyncStream {
public func mergedStream<
T: AsyncStreamType,
B: BindableProtocol>(
_ factory : @escaping () -> T,
key : KeyT,//TODO remove key parameter
bindable: B,
lazy : Bool = true
) -> StreamT where T.ValueT == ValueT, T.NextT == NextT, T.ErrorT == ErrorT,
B.Element == AsyncValue<ValueT, ErrorT>,
B: PropertyProtocol, B.ProperyElement == AsyncValue<ValueT, ErrorT> {
let bindedFactory = { () -> AsyncStream<ValueT, NextT, ErrorT> in
let stream = factory()
return stream.bindedToObservableAsyncVal(bindable)
}
return mergedStream(bindedFactory, key: key, getter: { () -> AsyncEvent<ValueT, NextT, ErrorT>? in
guard let result = bindable.value.result else { return nil }
switch result {
case .success(let value) where lazy:
return .success(value)
default:
return nil
}
})
}
public func mergedStream<
T: AsyncStreamType,
B: BindableProtocol>(
_ factory: @escaping () -> T,
key : KeyT,
holder : inout B,
lazy : Bool = true
) -> StreamT where T.ValueT == ValueT, T.NextT == NextT, T.ErrorT == ErrorT,
B: NSObjectProtocol,
B: PropertyProtocol, B.ProperyElement == [KeyT:AsyncValue<ValueT, ErrorT>] {
let bindedFactory = { [weak holder] () -> AsyncStream<ValueT, NextT, ErrorT> in
let stream = factory()
let bindable = BindableWithBlock<ValueT, ErrorT>(putVal: { val in
holder?.value[key] = val
}, getVal: { () -> AsyncValue<ValueT, ErrorT> in
if let result = holder?.value[key] {
return result
}
let result = AsyncValue<ValueT, ErrorT>()
holder?.value[key] = result
return result
})
return stream.bindedToObservableAsyncVal(bindable)
}
return mergedStream(bindedFactory, key: key, getter: { [weak holder] () -> AsyncEvent<ValueT, NextT, ErrorT>? in
guard let result = holder?.value[key]?.result else { return nil }
switch result {
case .success(let value) where lazy:
return .success(value)
default:
return nil
}
})
}
}
private struct BindableWithBlock<ValueT, ErrorT: Error> : PropertyProtocol, BindableProtocol {
typealias Event = AsyncValue<ValueT, ErrorT>
typealias Element = AsyncValue<ValueT, ErrorT>
typealias Error = NoError
typealias ProperyElement = AsyncValue<ValueT, ErrorT>
private let stream = PublishSubject<Element, NoError>()
public var value: AsyncValue<ValueT, ErrorT> {
get {
return getVal()
}
set {
putVal(newValue)
stream.next(newValue)
}
}
private let getVal: () -> Event
private let putVal: (Event) -> ()
init(putVal: @escaping (Event) -> (), getVal: @escaping () -> Event) {
self.putVal = putVal
self.getVal = getVal
}
func bind(signal: Signal<Element, NoError>) -> Disposable {
return signal.observe { event in
switch event {
case .next(let val):
self.putVal(val)
default:
fatalError()
}
self.stream.on(event)
}
}
}
| gpl-3.0 | f1f057861c90169f180a8fb3d6215f08 | 30.251163 | 120 | 0.552761 | 4.589481 | false | false | false | false |
phatblat/realm-cocoa | Realm/Tests/SwiftUITestHost/SwiftUITestHostApp.swift | 1 | 11042 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2021 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import RealmSwift
import SwiftUI
struct ReminderRowView: View {
@ObservedRealmObject var list: ReminderList
@ObservedRealmObject var reminder: Reminder
@State var hasFocus: Bool
@State var showReminderForm = false
var body: some View {
NavigationLink(destination: ReminderFormView(list: list,
reminder: reminder,
showReminderForm: $showReminderForm), isActive: $showReminderForm) {
Text(reminder.title)
}.isDetailLink(true)
}
}
struct ReminderFormView: View {
@ObservedRealmObject var list: ReminderList
@ObservedRealmObject var reminder: Reminder
@Binding var showReminderForm: Bool
var body: some View {
Form {
TextField("title", text: $reminder.title).accessibility(identifier: "formTitle")
DatePicker("date", selection: $reminder.date)
Picker("priority", selection: $reminder.priority, content: {
ForEach(Reminder.Priority.allCases) { priority in
Text(priority.description).tag(priority)
}
}).accessibilityIdentifier("picker")
}
.navigationTitle(reminder.title)
.navigationBarItems(trailing: Button("Save") {
if reminder.realm == nil {
$list.reminders.append(reminder)
}
showReminderForm.toggle()
}.disabled(reminder.title.isEmpty))
}
}
struct ReminderListView: View {
@ObservedRealmObject var list: ReminderList
@State var newReminderAdded = false
@State var showReminderForm = false
func shouldFocusReminder(_ reminder: Reminder) -> Bool {
return newReminderAdded && list.reminders.last == reminder
}
var body: some View {
VStack {
List {
ForEach(list.reminders) { reminder in
ReminderRowView(list: list,
reminder: reminder,
hasFocus: shouldFocusReminder(reminder))
}
.onMove(perform: $list.reminders.move)
.onDelete(perform: $list.reminders.remove)
}
}.navigationTitle(list.name)
.navigationBarItems(trailing: HStack {
EditButton()
Button("add") {
newReminderAdded = true
$list.reminders.append(Reminder())
}.accessibility(identifier: "addReminder")
})
}
}
struct ReminderListRowView: View {
@ObservedRealmObject var list: ReminderList
var body: some View {
HStack {
Image(systemName: list.icon)
TextField("List Name", text: $list.name).accessibility(identifier: "listRow")
Spacer()
Text("\(list.reminders.count)")
}.frame(minWidth: 100).accessibility(identifier: "hstack")
}
}
struct ReminderListResultsView: View {
@ObservedResults(ReminderList.self) var reminders
@Binding var searchFilter: String
var body: some View {
List {
ForEach(reminders) { list in
NavigationLink(destination: ReminderListView(list: list)) {
ReminderListRowView(list: list).tag(list)
}.accessibilityIdentifier(list.name)
}.onDelete(perform: $reminders.remove)
}.onChange(of: searchFilter) { value in
$reminders.filter = value.isEmpty ? nil : NSPredicate(format: "name CONTAINS[c] %@", value)
}
}
}
public extension Color {
static let lightText = Color(UIColor.lightText)
static let darkText = Color(UIColor.darkText)
static let label = Color(UIColor.label)
static let secondaryLabel = Color(UIColor.secondaryLabel)
static let tertiaryLabel = Color(UIColor.tertiaryLabel)
static let quaternaryLabel = Color(UIColor.quaternaryLabel)
static let systemBackground = Color(UIColor.systemBackground)
static let secondarySystemBackground = Color(UIColor.secondarySystemBackground)
static let tertiarySystemBackground = Color(UIColor.tertiarySystemBackground)
}
struct SearchView: View {
@Binding var searchFilter: String
var body: some View {
VStack {
Spacer()
HStack {
Image(systemName: "magnifyingglass").foregroundColor(.gray)
.padding(.leading, 7)
.padding(.top, 7)
.padding(.bottom, 7)
TextField("search", text: $searchFilter)
.padding(.top, 7)
.padding(.bottom, 7)
}.background(RoundedRectangle(cornerRadius: 15)
.fill(Color.secondarySystemBackground))
Spacer()
}.frame(maxHeight: 40).padding()
}
}
struct Footer: View {
@ObservedResults(ReminderList.self) var lists
var body: some View {
HStack {
Button(action: {
$lists.append(ReminderList())
}, label: {
HStack {
Image(systemName: "plus.circle")
Text("Add list")
}
}).buttonStyle(BorderlessButtonStyle())
.padding()
.accessibility(identifier: "addList")
Spacer()
}
}
}
struct ContentView: View {
@State var searchFilter: String = ""
var body: some View {
NavigationView {
VStack {
SearchView(searchFilter: $searchFilter)
ReminderListResultsView(searchFilter: $searchFilter)
Spacer()
Footer()
}
.navigationBarItems(trailing: EditButton())
.navigationTitle("reminders")
}
}
}
struct MultiRealmContentView: View {
struct RealmView: View {
@Environment(\.realm) var realm
var body: some View {
Text(realm.configuration.inMemoryIdentifier ?? "no memory identifier")
.accessibilityIdentifier("test_text_view")
}
}
@State var showSheet = false
var body: some View {
NavigationView {
VStack {
NavigationLink("Realm A", destination: RealmView().environment(\.realmConfiguration, Realm.Configuration(inMemoryIdentifier: "realm_a")))
NavigationLink("Realm B", destination: RealmView().environment(\.realmConfiguration, Realm.Configuration(inMemoryIdentifier: "realm_b")))
Button("Realm C") {
showSheet = true
}
}.sheet(isPresented: $showSheet, content: {
RealmView().environment(\.realmConfiguration, Realm.Configuration(inMemoryIdentifier: "realm_c"))
})
}
}
}
struct UnmanagedObjectTestView: View {
struct NestedViewOne: View {
struct NestedViewTwo: View {
@Environment(\.realm) var realm
@Environment(\.presentationMode) var presentationMode
@ObservedRealmObject var reminderList: ReminderList
var body: some View {
Button("Delete") {
$reminderList.delete()
presentationMode.wrappedValue.dismiss()
}
}
}
@ObservedRealmObject var reminderList: ReminderList
@Environment(\.presentationMode) var presentationMode
@State var shown = false
var body: some View {
NavigationLink("Next", destination: NestedViewTwo(reminderList: reminderList)).onAppear {
if shown {
presentationMode.wrappedValue.dismiss()
}
shown = true
}
}
}
@ObservedRealmObject var reminderList = ReminderList()
@Environment(\.realm) var realm
@State var passToNestedView = false
var body: some View {
NavigationView {
Form {
TextField("name", text: $reminderList.name).accessibilityIdentifier("name")
NavigationLink("test", destination: NestedViewOne(reminderList: reminderList), isActive: $passToNestedView)
}.navigationBarItems(trailing: Button("Add", action: {
try! realm.write { realm.add(reminderList) }
passToNestedView = true
}).accessibility(identifier: "addReminder"))
}.onAppear {
print("ReminderList: \(reminderList)")
}
}
}
struct ObservedResultsKeyPathTestView: View {
@ObservedResults(ReminderList.self, keyPaths: ["reminders.isFlagged"]) var reminders
var body: some View {
VStack {
List {
ForEach(reminders) { list in
ObservedResultsKeyPathTestRow(list: list)
}.onDelete(perform: $reminders.remove)
}
.navigationBarItems(trailing: EditButton())
.navigationTitle("reminders")
Footer()
}
}
}
struct ObservedResultsKeyPathTestRow: View {
var list: ReminderList
var body: some View {
HStack {
Image(systemName: list.icon)
Text(list.name)
}.frame(minWidth: 100).accessibility(identifier: "hstack")
}
}
@main
struct App: SwiftUI.App {
var body: some Scene {
if let realmPath = ProcessInfo.processInfo.environment["REALM_PATH"] {
Realm.Configuration.defaultConfiguration =
Realm.Configuration(fileURL: URL(string: realmPath)!, deleteRealmIfMigrationNeeded: true)
} else {
Realm.Configuration.defaultConfiguration =
Realm.Configuration(deleteRealmIfMigrationNeeded: true)
}
let view: AnyView = {
switch ProcessInfo.processInfo.environment["test_type"] {
case "multi_realm_test":
return AnyView(MultiRealmContentView())
case "unmanaged_object_test":
return AnyView(UnmanagedObjectTestView())
case "observed_results_key_path":
return AnyView(ObservedResultsKeyPathTestView())
default:
return AnyView(ContentView())
}
}()
return WindowGroup {
view
}
}
}
| apache-2.0 | b5ac98aface93feb3a6ba687787f8b03 | 33.50625 | 153 | 0.579967 | 5.290848 | false | false | false | false |
nixzhu/MonkeyKing | China/AlipayViewController.swift | 1 | 6391 |
import MonkeyKing
import UIKit
class AlipayViewController: UIViewController {
@IBOutlet private var segmentedControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
}
private func registerAccount() {
// Distinguish from authorization
let account = MonkeyKing.Account.alipay(appID: Configs.Alipay.appID)
MonkeyKing.registerAccount(account)
}
// MARK: Share
@IBAction func shareTextToAlipay(_ sender: UIButton) {
let info = MonkeyKing.Info(
title: "Friends Text, \(UUID().uuidString)",
description: nil,
thumbnail: nil,
media: nil
)
shareInfo(info)
}
@IBAction func shareImageToAlipay(_ sender: UIButton) {
let info = MonkeyKing.Info(
title: nil,
description: nil,
thumbnail: nil,
media: .image(UIImage(named: "rabbit")!)
)
shareInfo(info)
}
@IBAction func shareURLToAlipay(_ sender: UIButton) {
let info = MonkeyKing.Info(
title: "Friends URL, \(UUID().uuidString)",
description: "Description URL, \(UUID().uuidString)",
thumbnail: UIImage(named: "rabbit"),
media: .url(URL(string: "http://soyep.com")!)
)
shareInfo(info)
}
private func shareInfo(_ info: MonkeyKing.Info) {
registerAccount()
var message: MonkeyKing.Message?
switch segmentedControl.selectedSegmentIndex {
case 0:
message = MonkeyKing.Message.alipay(.friends(info: info))
case 1:
guard info.media != nil else {
print("目前支付宝生活圈还不支持纯文本的分享")
break
}
message = MonkeyKing.Message.alipay(.timeline(info: info))
default:
break
}
if let message = message {
MonkeyKing.deliver(message) { result in
print("result: \(result)")
}
}
}
// MARK: Pay
@IBAction func pay(_ sender: UIButton) {
registerAccount()
let request = URLRequest(url: URL(string: "https://www.example.com/pay.php?payType=alipay")!)
let task = URLSession.shared.dataTask(with: request) { data, _, error in
if let error = error {
print(error)
} else {
guard let data = data else { return }
guard let urlString = String(data: data, encoding: .utf8) else { return }
guard let url = URL(string: urlString) else { return }
MonkeyKing.deliver(.alipay(url: url)) { result in
print("result:", result)
}
}
}
task.resume()
}
// MARK: Oauth
@IBAction func oauth(_ sender: UIButton) {
let appID = Configs.Alipay.oauthID
let pid = Configs.Alipay.pid
let account = MonkeyKing.Account.alipay(appID: appID)
MonkeyKing.registerAccount(account)
// ref: https://docs.open.alipay.com/218/105327
// 获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
let signType: String = "RSA"
let sign: String = "RIJ7binMneL9f1OITLXeGfTeDJwgPeZ5Aqk1nPlCHfL1q1hnSUx4x%2BgmmnxDpzJ%2F9K6fzdytkDFlsgcnAUQx2jzAysniUDSFdbKzpacsLXSFJvINUNYowUfR%2FgaY%2FiDV9PICo%2B8Zs4az%2FChoTvxLUbZrFVufSthf2ySBbBNDlck%3D"
let dic: [String: String] = [
"apiname": "com.alipay.account.auth",
"app_id": appID,
"app_name": "mc",
"auth_type": "AUTHACCOUNT",
"biz_type": "openservice",
"method": "alipay.open.auth.sdk.code.get",
"pid": pid,
"product_id": "APP_FAST_LOGIN",
"scope": "kuaijie",
"target_id": "\(Int(Date().timeIntervalSince1970 * 1000.0))",
"sign": sign,
"sign_type": signType,
]
let keys = dic.keys.sorted { $0 < $1 }
var array: [String] = []
for k in keys {
if let v = dic[k] {
array.append(k + "=" + v)
}
}
var dataString: String = array.joined(separator: "&")
dataString += "&sign=\(sign)"
dataString += "&sign_type=\(signType)"
MonkeyKing.oauth(for: .alipay, dataString: dataString) { result in
switch result {
case .success(let dictionary):
print("dictionary \(String(describing: dictionary))")
case .failure(let error):
print("error \(String(describing: error))")
}
}
}
@IBAction func certify() {
// REF: https://docs.open.alipay.com/271/dz10yd
let urlStr = "https://openapi.alipay.com/gateway.do?alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2015111100758155&biz_content=%7B%22biz_no%22%3A%22ZM201611253000000121200404215172%22%7D&charset=GBK&format=json&method=zhima.customer.certification.certify&return_url=http%3A%2F%2Fwww.taobao.com&sign=MhtfosO8AKbwctDgfGitzLvhbcvi%2FMv3iBES7fRnIXn%2BHcdwq9UWltTs6mEvjk2UoHdLoFrvcSJipiE3sL8kdJMd51t87vcwPCfk7BA5KPwa4%2B1IYzYaK6WwbqOoQB%2FqiJVfni602HiE%2BZAomW7WA3Tjhjy3D%2B9xrLFCipiroDQ%3D&sign_type=RSA2×tamp=2016-11-25+15%3A00%3A59&version=1.0&sign=MhtfosO8AKbwctDgfGitzLvhbcvi%2FMv3iBES7fRnIXn%2BHcdwq9UWltTs6mEvjk2UoHdLoFrvcSJipiE3sL8kdJMd51t87vcwPCfk7BA5KPwa4%2B1IYzYaK6WwbqOoQB%2FqiJVfni602HiE%2BZAomW7WA3Tjhjy3D%2B9xrLFCipiroDQ%3D"
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "!*'();:@&=+$,%#[]|")
let encodingURLStr = urlStr.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)!
let scheme = "alipays://platformapi/startapp?appId=20000067&url=" + encodingURLStr
MonkeyKing.openScheme(scheme) { url in
print("callback: \(String(describing: url))")
}
}
}
extension Dictionary {
var toString: String? {
guard
let jsonData = try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted),
let theJSONText = String(data: jsonData, encoding: .utf8)
else { return nil }
return theJSONText
}
}
| mit | a2abde633f01fb786557cc64f7589e3e | 34.162921 | 752 | 0.602652 | 3.653824 | false | false | false | false |
Aster0id/Swift-StudyNotes | Swift-StudyNotes/L2-S3.swift | 1 | 4214 | //
// L2-S3.swift
// Swift-StudyNotes
//
// Created by 牛萌 on 15/5/13.
// Copyright (c) 2015年 Aster0id.Team. All rights reserved.
//
import Foundation
/**
* @class
* @brief 2.3 字符串和字符
*/
class Lesson2Section3 {
func run(flag:Bool) {
if !flag {
return
}
//MARK: Begin Runing
println("\n\n------------------------------------")
println(">>>>> Lesson2-Section3 begin running\n\n")
// -----------------------------------------
// MARK: 字符串
// -----------------------------------------
var emptyString = ""// empty string literal
var anotherEmptyString = String()// initializer syntax
// 这两个字符串都为空,并且两者等价
// 用isEmpty判断是否字符串为空
if emptyString.isEmpty {
println("Nothing to see here")
}
/*
//!!!!!
注意: 在 Objective-C 和 Cocoa 中,您通过选择两个不同的类( NSString 和 NSMutableString )来指定该字符串是否可以被修改,Swift 中的字符串是否可以修改仅通 过定义的是变量还是常量来决定,实现了多种类型可变性操作的统一。
*/
var variableString = "Horse"
variableString += " and carriage"
// variableString 现在为 "Horse and carriage"
let constantString = "Highlander"
//error: constantString += " and another Highlander"
// 这会报告一个编译错误(compile-time error) - 常量不可以被修改。
//-- 计算字符数量
let unusualMenagerie = "Koala ????, Snail ????, Penguin ????,Dromedary ????"
println("unusualMenagerie has \(count(unusualMenagerie)) characters")
//## 打印: unusualMenagerie has 51 characters
println("unusualMenagerie length is \(unusualMenagerie.lengthOfBytesUsingEncoding(NSASCIIStringEncoding))")
//## 打印: unusualMenagerie length is 51
let string1 = "hello"
let character1: Character = "!"
let stringPlusCharacter = string1 + String(character1)
//-- 字符串插值
// 字符串插值是一种全新的构建字符串的方式,可以在其中包含常量、变量、字面量和表达式。
// 您插入的字符串字面量的每一项都被包裹在以反斜线为前缀的圆括号中:
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)" //## 结果: message is "3 times 2.5 is 7.5"
//-- 字符串比较
// 通过调用字符串的 hasPrefix/hasSuffix 方法来检查字符串是否拥有特定前缀/后缀
//-- 字符串的大写和小写
let normal = "Could you help me, please?"
let shouty = normal.uppercaseString
// shouty 值为 "COULD YOU HELP ME, PLEASE?"
let whispered = normal.lowercaseString
// whispered 值为 "could you help me, please?"
//-----------------------------------
//-- Unicode
let dogString = "Dog!🐶"
//-- UTF8
for codeUnit in dogString.utf8 {
print("\(codeUnit) ")
}
print("\n")
//## 打印: 68 111 103 33 240 159 144 182
//-- UTF16
for codeUnit in dogString.utf16 {
print("\(codeUnit) ")
}
print("\n")
//## 打印: 68 111 103 33 55357 56374
//-- Unicode标量 (Unicode Scalars)
for scalar in dogString.unicodeScalars {
print("\(scalar.value) ")
}
print("\n")
//## 打印: 68 111 103 33 128054
for scalar in dogString.unicodeScalars {
print("\(scalar) ")
}
print("\n")
//## 打印: D o g ! 🐶
//MARK: End Runing
println("\n\nLesson2-Section3 end running <<<<<<<")
println("------------------------------------\n\n")
}
} | mit | 5fcb4f54c64b7a8202a84bac624b5035 | 27.585938 | 143 | 0.483598 | 4.391357 | false | false | false | false |
alessandrostone/Menubar-Colors | sources/AppDelegate.swift | 1 | 5801 | //
// AppDelegate.swift
// Menubar Colors
//
// Created by Nikolai Vazquez on 7/19/15.
// Copyright (c) 2015 Nikolai Vazquez. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Cocoa
@NSApplicationMain
// - MARK: AppDelegate Class
class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: Variables
@IBOutlet weak var colorPanel: ColorPanel!
@IBOutlet weak var statusMenu: StatusMenu!
var statusItem: NSStatusItem!
let aboutWindowController: AboutWindowController = AboutWindowController(windowNibName: "AboutWindow")
// MARK: NSApplicationDelegate Methods
func applicationDidFinishLaunching(aNotification: NSNotification) {
let statusBar = NSStatusBar.systemStatusBar()
statusItem = statusBar.statusItemWithLength(-1)
let icon = NSImage(named: "menu-icon")
icon?.template = true
statusItem.image = icon
let button = statusItem.button
button?.toolTip = "Click to show color panel\nRight click to show menu"
button?.target = self
button?.action = "statusButtonPressed:"
button?.sendActionOn(Int(NSEventMask.LeftMouseUpMask.union(.RightMouseUpMask).rawValue))
statusMenu.delegate = self
// MARK: Populate "Reset Location" menu
let menu: NSMenu = statusMenu.resetPositionMenu
for location in Location.CasesArray {
let item = NSMenuItem(
title: location.description,
action: "setResetLocation:",
keyEquivalent: ""
)
if location == Preferences.sharedPreferences().resetLocation {
item.state = NSOnState
}
menu.addItem(item)
}
colorPanel.showsAlpha = Preferences.sharedPreferences().showsAlpha
if let item = statusMenu.itemWithTitle("Show Alpha") {
item.state = colorPanel.showsAlpha ? NSOnState : NSOffState
}
}
// MARK: Selector Methods
func statusButtonPressed(sender: NSStatusBarButton) {
if let event = NSApplication.sharedApplication().currentEvent {
if event.modifierFlags.contains(.ControlKeyMask) || event.type == .RightMouseUp {
// Handle right mouse click
statusItem.menu = statusMenu
statusItem.popUpStatusItemMenu(statusMenu)
} else {
// Handle left mouse click
self.toggleColorPanel(sender)
}
}
}
func setResetLocation(sender: NSMenuItem) {
if let location = Location.CasesDictionary[sender.title] {
colorPanel.moveToScreenLocation(location)
Preferences.sharedPreferences().resetLocation = location
if sender.action == "setResetLocation:" {
for item in sender.menu!.itemArray {
if item.action == sender.action {
item.state = (item == sender) ? NSOnState : NSOffState
}
}
}
}
}
// MARK: IB Methods
@IBAction func toggleColorPanel(sender: AnyObject) {
if colorPanel.visible {
colorPanel.close()
} else {
colorPanel.open(sender)
}
}
@IBAction func toggleStartAtLogin(sender: AnyObject) {
let manager = LoginItemsManager()
manager.toggleStartAtLogin()
}
@IBAction func showAbout(sender: AnyObject?) {
aboutWindowController.showWindow(sender)
}
@IBAction func openProjectURL(sender: AnyObject?) {
NSWorkspace.sharedWorkspace().openURL(NSURL(string: "https://github.com/nvzqz/Menubar-Colors")!)
}
}
// MARK: - NSMenuDelegate Extension
extension AppDelegate: NSMenuDelegate {
// MARK: NSMenuDelegate Methods
func menuWillOpen(menu: NSMenu) {
if let statusMenu = menu as? StatusMenu {
if let startAtLoginItem = statusMenu.itemWithTitle("Start at Login") {
let manager = LoginItemsManager()
if manager.startAtLogin {
startAtLoginItem.state = NSOnState
} else {
startAtLoginItem.state = NSOffState
}
}
if colorPanel.visible {
statusMenu.toggleColorsItem.title = "Hide Colors"
} else {
statusMenu.toggleColorsItem.title = "Show Colors"
}
}
}
func menuDidClose(menu: NSMenu) {
statusItem.menu = nil
}
}
| mit | af97452d724fea1fef197826c7427c27 | 32.33908 | 106 | 0.611963 | 5.245027 | false | false | false | false |
ktatroe/MPA-Horatio | HoratioDemo/HoratioDemo/Classes/Persistence/UpgradeObjectStoreOperation.swift | 2 | 1790 | //
// Copyright © 2016 Kevin Tatroe. All rights reserved.
// See LICENSE.txt for this sample’s licensing information
import Foundation
import CoreData
typealias DataStoreUpgradeBlock = (Void) -> Void
/**
An `Operation` subclass that performs updates on the local storage for each version of the
app skipped since the last run.
*/
class UpgradeObjectStoreOperation: Operation {
// MARK: Constants
struct Versions {
static let V100 = 389.0
static let Current = Versions.V100
}
struct UserDefaults {
static let LastVersion = "LastLaunchVersion"
static let NeverLaunched = 0.0
}
// MARK: Properties
let lastVersion: Double
// MARK: Initialization
override init() {
self.lastVersion = NSUserDefaults.standardUserDefaults().doubleForKey(UserDefaults.LastVersion)
super.init()
addCondition(MutuallyExclusive<UpgradeObjectStoreOperation>())
self.name = "Upgrade Object Store"
}
// MARK: Execution
override func execute() {
guard let _ = Container.resolve(PersistentStoreController.self) else {
finish()
return
}
upgradeToVersion(currentVersion: Versions.V100, fromVersion: lastVersion, upgradeBlock: nil)
// save last version as current
NSUserDefaults.standardUserDefaults().setDouble(Versions.Current, forKey: UserDefaults.LastVersion)
finish()
}
// MARK: - Private
func upgradeToVersion(currentVersion current: Double, fromVersion from: Double, upgradeBlock: DataStoreUpgradeBlock?) -> Bool {
guard from < current else { return false }
guard let upgradeBlock = upgradeBlock else { return false }
upgradeBlock()
return true
}
}
| mit | 9696885a0f37d057638d69a7a0acee79 | 22.207792 | 131 | 0.670957 | 5.005602 | false | false | false | false |
eondich/BritLitGenerator | BritLitGenerator/BritLitGenerator/AppDelegate.swift | 1 | 3122 | //
// AppDelegate.swift
// The Wonderific British Literature Generator for the Common Fluckadrift
//
// Created by Elena Ondich on 12/30/15.
// Copyright © 2015 Elena Ondich. All rights reserved.
//
// TO DO:
// Clean up code- make variable names better, comment everything, make code more elegant where possible, delete extraneous stuff, etc
// Color scheme
// Word choice
// Built-in data
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// To do: Deal with circumstances where user leaves app
var window: UIWindow?
var testStory: StoryBits?
var randomStoryViewController: RandomStoryViewController?
var editViewController: EditViewController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Set up view controllers that will appear in tabs
// Main view controller where random stories are generated
self.randomStoryViewController = RandomStoryViewController()
let mainNavigationController = UINavigationController(rootViewController: self.randomStoryViewController!)
mainNavigationController.tabBarItem = UITabBarItem(title: "Get a story", image: UIImage(named: "dice"), tag: 0)
// View controller for editing data
self.editViewController = EditViewController()
self.editViewController?.typeNo = 0
let editNavigationController = UINavigationController(rootViewController: self.editViewController!)
editNavigationController.tabBarItem = UITabBarItem(title: "Edit", image: UIImage(named: "pen"), tag: 0)
// Images from https://icons8.com/
// Set up tab bar controller and set as default
let tabBarController = UITabBarController()
tabBarController.viewControllers = [mainNavigationController, editNavigationController]
tabBarController.tabBar.tintColor = UIColor(red: 0.8, green: 0.52, blue: 0.0, alpha: 1.0)
let startupViewController = tabBarController
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.rootViewController = startupViewController
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
}
// Saves story data to a plist
func saveStory(story: StoryBits) {
let data = story.dict
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let storyURL = documentsURL.URLByAppendingPathComponent("story.plist")
data.writeToURL(storyURL, atomically: true)
}
}
| mit | 70add3422233a932ea725bcfdc27bcc1 | 35.290698 | 133 | 0.697853 | 5.533688 | false | false | false | false |
clappr/clappr-ios | Sources/Clappr_iOS/Classes/Plugin/Core/MediaControl/FullscreenButton.swift | 1 | 2165 | open class FullscreenButton: MediaControl.Element {
public var fullscreenIcon = UIImage.fromName("fullscreen", for: FullscreenButton.self)
public var windowedIcon = UIImage.fromName("fullscreen_exit", for: FullscreenButton.self)
public var button: UIButton! {
didSet {
button.accessibilityIdentifier = "FullscreenButton"
button.setImage(fullscreenIcon, for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
button.addTarget(self, action: #selector(toggleFullscreenButton), for: .touchUpInside)
view.isHidden = core?.options[kFullscreenDisabled] as? Bool ?? false
view.addSubview(button)
}
}
open var isOnFullscreen = false {
didSet {
let icon = isOnFullscreen ? windowedIcon : fullscreenIcon
button.setImage(icon, for: .normal)
}
}
open class override var name: String {
return "FullscreenButton"
}
override open var panel: MediaControlPanel {
return .bottom
}
override open var position: MediaControlPosition {
return .right
}
override open func bindEvents() {
bindCoreEvents()
}
private func bindCoreEvents() {
guard let core = core else { return }
listenTo(core,
eventName: Event.didEnterFullscreen.rawValue) { [weak self] (_: EventUserInfo) in self?.isOnFullscreen = true }
listenTo(core,
eventName: Event.didExitFullscreen.rawValue) { [weak self] (_: EventUserInfo) in self?.isOnFullscreen = false }
}
override open func render() {
setupButton()
}
private func setupButton() {
button = UIButton(type: .custom)
button.bindFrameToSuperviewBounds()
}
@objc open func toggleFullscreenButton() {
let event: InternalEvent = isOnFullscreen ? .userRequestExitFullscreen : .userRequestEnterInFullscreen
core?.trigger(event.rawValue)
}
}
| bsd-3-clause | 8ce7550c3b4b57177d4703194e0a08e6 | 32.828125 | 128 | 0.626328 | 5.130332 | false | false | false | false |
ivan-milinkovic/SwiftWhenThen | Sources/SwiftWhenThen/SWT.swift | 1 | 2498 | import Foundation
public class SWTCompletion {
fileprivate let currentWt : SWT
fileprivate init(currentWt : SWT) {
// keep the current instance in memory
self.currentWt = currentWt
}
// note: can't use dispatch_once as it requires a token to be a global or a static varible
// which does not fit this use case, because locking should be done on per instance level
fileprivate var lock = NSLock()
fileprivate var isDone: Bool = false
public func done () {
let lockStatus = lock.try()
if lockStatus {
if !isDone { // prevent multiple done calls doing harm
isDone = true
currentWt.onClosureDone()
}
lock.unlock()
}
else {
// the property is unecpectedly being accessed from another thread
// do nothing, completion can be marked only once
}
}
}
public class SWT {
public typealias SWTClosure = (_ swtCompletion: SWTCompletion) -> Void
public typealias SWTCompletionClosure = ()->()
fileprivate var dispatchGroup : DispatchGroup
fileprivate var finalClosure : SWTCompletionClosure? = nil
fileprivate var closures : [SWTClosure]? = nil
fileprivate init () {
dispatchGroup = DispatchGroup()
}
fileprivate func onClosureStart() {
self.dispatchGroup.enter()
}
fileprivate func onClosureDone() {
self.dispatchGroup.leave()
}
fileprivate func start() {
dispatchGroup = DispatchGroup()
if let closures = closures {
for closure in closures {
let swtCompletion = SWTCompletion(currentWt: self)
onClosureStart()
closure(swtCompletion)
}
}
// callback to execute the final "then" closure
dispatchGroup.notify(queue: DispatchQueue.main) {
if let finalClosure = self.finalClosure { // intentionally capture self
finalClosure()
}
}
}
public class func when(_ closures: SWTClosure...) -> SWT {
let instance = SWT()
instance.closures = closures
return instance
}
public func then(_ closure: @escaping SWTCompletionClosure) {
finalClosure = closure
// all setup, go!
start()
}
}
| mit | f2fa9b4f6b8ceac52edb59ea284477e1 | 25.294737 | 94 | 0.566853 | 5.418655 | false | false | false | false |
lanjing99/iOSByTutorials | iOS 9 by tutorials/01-swift-2/starter/Chapter1_Swift2.playground/Pages/Errors.xcplaygroundpage/Contents.swift | 1 | 2714 | //: Go back to [Control Flow](@previous)
//: ## Error Handling
import Foundation
//: In Swift 2.0, methods and functions can now declare that they "throw" an error. By declaring this, you are relying on the consumer to handle any potential errors that might come about when the method is called.
protocol JSONParsable {
static func parse(json: [String: AnyObject]) throws -> Self
}
//: Create your own error type.
enum ParseError: ErrorType {
case MissingAttribute(message: String)
}
/*:
Pretty easy, right? This error has a single case and includes an associative value of the type `String` as a message. Now when you throw this error type you can include some extra information about what is missing. Being that enums are used when creating `ErrorType`s you can include any kind of associative values that you deem necessary for your use case.
Define a `struct` that implements `JSONParsable` and throws some errors.
*/
struct Person: JSONParsable {
let firstName: String
let lastName: String
static func parse(json: [String : AnyObject]) throws -> Person {
guard let firstName = json["first_name"] as? String else {
let message = "Expected first_name String"
throw ParseError.MissingAttribute(message: message) // 1
}
guard let lastName = json["last_name"] as? String else {
let message = "Expected last_name String"
throw ParseError.MissingAttribute(message: message) // 2
}
return Person(firstName: firstName, lastName: lastName)
}
}
//: When calling a method that `throws` it is required by the compiler that you precede the call to that method with **`try`**. And then, in order to capture the thrown errors you will need to wrap your "trying" call in a `do {}` block followed by `catch {}` blocks for the type of errors you are catching.
do {
let person = try Person.parse(["foo": "bar"])
} catch ParseError.MissingAttribute(let message) {
print(message)
} catch {
print("Unexpected ErrorType")
}
//: In a case where you can guarantee that a call will never throw an error or when catching the error does not provide any benefit (such as a critical situation where the app cannot continue operating); you can bypass the `do/catch` requirement. To do so, you simply type an `!` after `try`. Try (no pun intended) entering the following into the playground. You should notice a runtime error appear. Uncomment the following line to see the error.
// let p1 = try! Person.parse(["foo": "bar"])
//: Notice that this line does not fail because it meets the requirements of the `parse()` implementation.
let p2 = try! Person.parse(["first_name": "Ray",
"last_name": "Wenderlich"])
//: Move on to [String Validation](@next)
| mit | 85428ff54c3d78e9fb98800162f8046e | 45.793103 | 447 | 0.725866 | 4.234009 | false | false | false | false |
hilen/TSWeChat | TSWeChat/Classes/Chat/TSChatViewController+TestData.swift | 1 | 3688 | //
// TSChatViewController+TestData.swift
// TSWeChat
//
// Created by Hilen on 3/1/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
import SwiftyJSON
// MARK: - @extension TSChatViewController
// 聊天测试数据 , 仅仅是测试
extension TSChatViewController {
//第一次请求的数据
func firstFetchMessageList() {
guard let list = self.fetchData() else {return}
self.itemDataSouce.insert(contentsOf: list, at: 0)
self.listTableView.reloadData {
self.isReloading = false
self.listTableView.scrollBottomToLastRow()
}
}
/**
下拉加载更多请求,模拟一下请求时间
*/
func pullToLoadMore() {
self.isEndRefreshing = false
self.indicatorView.startAnimating()
self.isReloading = true
let backgroundQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background)
backgroundQueue.async(execute: {
guard let list = self.fetchData() else {
self.indicatorView.stopAnimating()
self.isReloading = false
return
}
sleep(1)
DispatchQueue.main.async(execute: { () -> Void in
self.itemDataSouce.insert(contentsOf: list, at: 0)
self.indicatorView.stopAnimating()
// self!.listTableView.tableHeaderView = nil
self.updateTableWithNewRowCount(list.count)
self.isEndRefreshing = true
})
})
}
//获取聊天列表数据
func fetchData() -> [ChatModel]? {
guard let JSONData = Data.ts_dataFromJSONFile("chat") else {
return nil
}
var list = [ChatModel]()
do {
let jsonObj = try JSON(data: JSONData)
var temp: ChatModel?
for dict in jsonObj["data"].arrayObject! {
guard let model = TSMapper<ChatModel>().map(JSON: dict as! [String : Any]) else {
continue
}
/**
* 1,刷新获取的第一条数据,加上时间 model
* 2,当后面的数据比前面一条多出 2 分钟以上,加上时间 model
*/
if temp == nil || model.isLateForTwoMinutes(temp!) {
guard let timestamp = model.timestamp else {
continue
}
list.insert(ChatModel(timestamp: timestamp), at: list.count)
}
list.insert(model, at: list.count)
temp = model
}
} catch {
print("Error \(error)")
}
return list
}
//下拉刷新加载数据, inert rows
func updateTableWithNewRowCount(_ count: Int) {
var contentOffset = self.self.listTableView.contentOffset
UIView.setAnimationsEnabled(false)
self.listTableView.beginUpdates()
var heightForNewRows: CGFloat = 0
var indexPaths = [IndexPath]()
for i in 0 ..< count {
let indexPath = IndexPath(row: i, section: 0)
indexPaths.append(indexPath)
heightForNewRows += self.tableView(self.listTableView, heightForRowAt: indexPath)
}
contentOffset.y += heightForNewRows
self.listTableView.insertRows(at: indexPaths, with: UITableView.RowAnimation.none)
self.listTableView.endUpdates()
UIView.setAnimationsEnabled(true)
self.self.listTableView.setContentOffset(contentOffset, animated: false)
}
}
| mit | f12abaab1a03f8575af4fcbaa4df308f | 31.738318 | 97 | 0.556095 | 4.892458 | false | false | false | false |
ziogaschr/SwiftPasscodeLock | PasscodeLockTests/PasscodeLock/ChangePasscodeStateTests.swift | 2 | 2060 | //
// ChangePasscodeStateTests.swift
// PasscodeLock
//
// Created by Yanko Dimitrov on 8/28/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import XCTest
class ChangePasscodeStateTests: XCTestCase {
var passcodeLock: FakePasscodeLock!
var passcodeState: ChangePasscodeState!
var repository: FakePasscodeRepository!
override func setUp() {
super.setUp()
repository = FakePasscodeRepository()
let config = FakePasscodeLockConfiguration(repository: repository)
passcodeState = ChangePasscodeState()
passcodeLock = FakePasscodeLock(state: passcodeState, configuration: config)
}
func testAcceptCorrectPasscode() {
class MockDelegate: FakePasscodeLockDelegate {
var didChangedState = false
override func passcodeLockDidChangeState(_ lock: PasscodeLockType) {
didChangedState = true
}
}
let delegate = MockDelegate()
passcodeLock.delegate = delegate
passcodeState.acceptPasscode(repository.fakePasscode, fromLock: passcodeLock)
XCTAssert(passcodeLock.state is SetPasscodeState, "Should change the state to SetPasscodeState")
XCTAssertEqual(delegate.didChangedState, true, "Should call the delegate when the passcode is correct")
}
func testAcceptIncorrectPasscode() {
class MockDelegate: FakePasscodeLockDelegate {
var called = false
override func passcodeLockDidFail(_ lock: PasscodeLockType) {
called = true
}
}
let delegate = MockDelegate()
passcodeLock.delegate = delegate
passcodeState.acceptPasscode(["0", "0", "0", "0"], fromLock: passcodeLock)
XCTAssertEqual(delegate.called, true, "Should call the delegate when the passcode is incorrect")
}
}
| mit | 44534dc2c5e5566094ba44a64e9374e7 | 29.279412 | 111 | 0.614376 | 6.073746 | false | true | false | false |
kissybnts/v-project | Sources/App/Language/Sentence/SentenceController.swift | 1 | 2167 | import Vapor
import HTTP
final class SentenceController: ResourceRepresentable {
func index(_ req: Request) throws -> ResponseRepresentable {
let userId = try req.userId()
let sentences = try Sentence.makeQuery().filter(Sentence.Properties.userId, userId).sort(Sentence.Properties.id, .ascending).all()
return try sentences.makeJSON()
}
func create(_ req: Request) throws -> ResponseRepresentable {
let sentence = try req.sentence()
let userId = try req.userId()
try sentence.checkIsSameUserId(requesterUserId: userId)
try CategoryService.checkIsUsers(categoryId: sentence.categoryId, userId: sentence.userId)
try sentence.save()
return sentence
}
func show(_ req: Request, sentence: Sentence) -> ResponseRepresentable {
return sentence
}
func update(_ req: Request, sentence: Sentence) throws -> ResponseRepresentable {
let userId = try req.userId()
try sentence.checkIsSameUserId(requesterUserId: userId)
try sentence.update(for: req)
try sentence.save()
return sentence
}
func delete(_ req: Request, sentence: Sentence) throws -> ResponseRepresentable {
let userId = try req.userId()
try sentence.checkIsSameUserId(requesterUserId: userId)
try sentence.delete()
return Response(status: .ok)
}
func clear(_ req: Request) throws -> ResponseRepresentable {
let userId = try req.userId()
try SentenceService.clearSentences(userId: userId)
return Response(status: .ok)
}
func makeResource() -> Resource<Sentence> {
return Resource(
index: index,
store: create,
show: show,
update: update,
destroy: delete,
clear: clear
)
}
}
extension SentenceController: EmptyInitializable {}
extension Request {
fileprivate func sentence() throws -> Sentence {
guard let json = json else {
throw Abort.badRequest
}
return try Sentence(json: json)
}
}
| mit | 5c21df3cd7193a02d903ccf69b3c479f | 29.957143 | 138 | 0.622058 | 5.063084 | false | false | false | false |
zhouxj6112/ARKit | ARKitInteraction/ARKitInteraction/Additional View Controllers/StatusViewController.swift | 1 | 5118 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Utility class for showing messages above the AR view.
*/
import Foundation
import ARKit
/**
Displayed at the top of the main interface of the app that allows users to see
the status of the AR experience, as well as the ability to control restarting
the experience altogether.
- Tag: StatusViewController
*/
class StatusViewController: UIViewController {
// MARK: - Types
enum MessageType {
case trackingStateEscalation
case planeEstimation
case contentPlacement
case focusSquare
static var all: [MessageType] = [
.trackingStateEscalation,
.planeEstimation,
.contentPlacement,
.focusSquare
]
}
// MARK: - IBOutlets
@IBOutlet weak private var messagePanel: UIVisualEffectView!
@IBOutlet weak private var messageLabel: UILabel!
@IBOutlet weak private var restartExperienceButton: UIButton!
// MARK: - Properties
/// Trigerred when the "Restart Experience" button is tapped.
var restartExperienceHandler: () -> Void = {}
/// Seconds before the timer message should fade out. Adjust if the app needs longer transient messages.
private let displayDuration: TimeInterval = 6
// Timer for hiding messages.
private var messageHideTimer: Timer?
private var timers: [MessageType: Timer] = [:]
// MARK: - Message Handling
func showMessage(_ text: String, autoHide: Bool = true) {
// Cancel any previous hide timer.
messageHideTimer?.invalidate()
messageLabel.text = text
// Make sure status is showing.
setMessageHidden(false, animated: true)
if autoHide {
messageHideTimer = Timer.scheduledTimer(withTimeInterval: displayDuration, repeats: false, block: { [weak self] _ in
self?.setMessageHidden(true, animated: true)
})
}
}
func scheduleMessage(_ text: String, inSeconds seconds: TimeInterval, messageType: MessageType) {
cancelScheduledMessage(for: messageType)
let timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { [weak self] timer in
self?.showMessage(text)
timer.invalidate()
})
timers[messageType] = timer
}
func cancelScheduledMessage(`for` messageType: MessageType) {
timers[messageType]?.invalidate()
timers[messageType] = nil
}
func cancelAllScheduledMessages() {
for messageType in MessageType.all {
cancelScheduledMessage(for: messageType)
}
}
// MARK: - ARKit
func showTrackingQualityInfo(for trackingState: ARCamera.TrackingState, autoHide: Bool) {
showMessage(trackingState.presentationString, autoHide: autoHide)
}
func escalateFeedback(for trackingState: ARCamera.TrackingState, inSeconds seconds: TimeInterval) {
cancelScheduledMessage(for: .trackingStateEscalation)
let timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { [unowned self] _ in
self.cancelScheduledMessage(for: .trackingStateEscalation)
var message = trackingState.presentationString
if let recommendation = trackingState.recommendation {
message.append(": \(recommendation)")
}
self.showMessage(message, autoHide: false)
})
timers[.trackingStateEscalation] = timer
}
// MARK: - IBActions
@IBAction private func restartExperience(_ sender: UIButton) {
restartExperienceHandler()
}
// MARK: - Panel Visibility
private func setMessageHidden(_ hide: Bool, animated: Bool) {
// The panel starts out hidden, so show it before animating opacity.
messagePanel.isHidden = false
guard animated else {
messagePanel.alpha = hide ? 0 : 1
return
}
UIView.animate(withDuration: 0.2, delay: 0, options: [.beginFromCurrentState], animations: {
self.messagePanel.alpha = hide ? 0 : 1
}, completion: nil)
}
}
extension ARCamera.TrackingState {
var presentationString: String {
switch self {
case .notAvailable:
return "TRACKING UNAVAILABLE"
case .normal:
return "TRACKING NORMAL"
case .limited(.excessiveMotion):
return "TRACKING LIMITED\nExcessive motion"
case .limited(.insufficientFeatures):
return "TRACKING LIMITED\nLow detail"
case .limited(.initializing):
return "Initializing"
case .limited(.relocalizing):
return "limited";
}
}
var recommendation: String? {
switch self {
case .limited(.excessiveMotion):
return "Try slowing down your movement, or reset the session."
case .limited(.insufficientFeatures):
return "Try pointing at a flat surface, or reset the session."
default:
return nil
}
}
}
| apache-2.0 | 976b9c307b9901e92b31462d97265b45 | 29.272189 | 128 | 0.64269 | 5.231084 | false | false | false | false |
velvetroom/columbus | Source/View/PlansDetail/VPlansDetailListHeader.swift | 1 | 1087 | import UIKit
final class VPlansDetailListHeader:UICollectionReusableView
{
weak var labelDuration:UILabel!
weak var labelDistance:UILabel!
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
isUserInteractionEnabled = false
factoryViews()
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: internal
func config(controller:CPlansDetail)
{
guard
let travels:[DPlanTravel] = controller.model.plan?.travelsList,
let distanceSettings:DSettingsDistance = controller.model.settings?.distance
else
{
return
}
let distance:String? = VFormat.factoryDistance(
travels:travels,
distanceSettings:distanceSettings)
let duration:String? = VFormat.factoryDuration(travels:travels)
labelDistance.text = distance
labelDuration.text = duration
}
}
| mit | 9ea13e35ed77f0021f7c8f27e52055e0 | 22.630435 | 88 | 0.594296 | 5.276699 | false | false | false | false |
ben-ng/swift | test/NameBinding/reference-dependencies-members.swift | 1 | 2987 | // RUN: rm -rf %t && mkdir -p %t
// RUN: cp %s %t/main.swift
// RUN: %target-swift-frontend -typecheck -primary-file %t/main.swift %S/Inputs/reference-dependencies-members-helper.swift -emit-reference-dependencies-path - > %t.swiftdeps
// RUN: %FileCheck -check-prefix=PROVIDES-NOMINAL %s < %t.swiftdeps
// RUN: %FileCheck -check-prefix=PROVIDES-NOMINAL-NEGATIVE %s < %t.swiftdeps
// RUN: %FileCheck -check-prefix=PROVIDES-MEMBER %s < %t.swiftdeps
// RUN: %FileCheck -check-prefix=PROVIDES-MEMBER-NEGATIVE %s < %t.swiftdeps
// RUN: %FileCheck -check-prefix=DEPENDS-NOMINAL %s < %t.swiftdeps
// RUN: %FileCheck -check-prefix=DEPENDS-NOMINAL-NEGATIVE %s < %t.swiftdeps
// RUN: %FileCheck -check-prefix=DEPENDS-MEMBER %s < %t.swiftdeps
// RUN: %FileCheck -check-prefix=DEPENDS-MEMBER-NEGATIVE %s < %t.swiftdeps
// PROVIDES-NOMINAL-LABEL: {{^provides-nominal:$}}
// PROVIDES-NOMINAL-NEGATIVE-LABEL: {{^provides-nominal:$}}
// PROVIDES-MEMBER-LABEL: {{^provides-member:$}}
// PROVIDES-MEMBER-NEGATIVE-LABEL: {{^provides-member:$}}
// DEPENDS-NOMINAL-LABEL: {{^depends-nominal:$}}
// DEPENDS-NOMINAL-NEGATIVE-LABEL: {{^depends-nominal:$}}
// DEPENDS-MEMBER-LABEL: {{^depends-member:$}}
// DEPENDS-MEMBER-NEGATIVE-LABEL: {{^depends-member:$}}
// PROVIDES-NOMINAL-DAG: 4Base"
class Base {
// PROVIDES-MEMBER-DAG: - ["{{.+}}4Base", ""]
// PROVIDES-MEMBER-NEGATIVE-NOT: - ["{{.+}}4Base", "{{.+}}"]
func foo() {}
}
// PROVIDES-NOMINAL-DAG: 3Sub"
// DEPENDS-NOMINAL-DAG: 9OtherBase"
class Sub : OtherBase {
// PROVIDES-MEMBER-DAG: - ["{{.+}}3Sub", ""]
// PROVIDES-MEMBER-NEGATIVE-NOT: - ["{{.+}}3Sub", "{{.+}}"]
// DEPENDS-MEMBER-DAG: - ["{{.+}}9OtherBase", ""]
// DEPENDS-MEMBER-DAG: - ["{{.+}}9OtherBase", "foo"]
// DEPENDS-MEMBER-DAG: - ["{{.+}}9OtherBase", "init"]
func foo() {}
}
// PROVIDES-NOMINAL-DAG: 9SomeProto"
// PROVIDES-MEMBER-DAG: - ["{{.+}}9SomeProto", ""]
protocol SomeProto {}
// PROVIDES-NOMINAL-DAG: 10OtherClass"
// PROVIDES-MEMBER-DAG: - ["{{.+}}10OtherClass", ""]
// DEPENDS-NOMINAL-DAG: 10OtherClass"
// DEPENDS-NOMINAL-DAG: 9SomeProto"
// DEPENDS-MEMBER-DAG: - ["{{.+}}9SomeProto", ""]
// DEPENDS-MEMBER-DAG: - ["{{.+}}10OtherClass", "deinit"]
extension OtherClass : SomeProto {}
// PROVIDES-NOMINAL-NEGATIVE-NOT: 11OtherStruct"{{$}}
// DEPENDS-NOMINAL-DAG: 11OtherStruct"
extension OtherStruct {
// PROVIDES-MEMBER-DAG: - ["{{.+}}11OtherStruct", ""]
// PROVIDES-MEMBER-DAG: - ["{{.+}}11OtherStruct", "foo"]
// PROVIDES-MEMBER-DAG: - ["{{.+}}11OtherStruct", "bar"]
// PROVIDES-MEMBER-NEGATIVE-NOT: "baz"
// DEPENDS-MEMBER-DAG: - ["{{.+}}11OtherStruct", "foo"]
// DEPENDS-MEMBER-DAG: - ["{{.+}}11OtherStruct", "bar"]
// DEPENDS-MEMBER-DAG: - !private ["{{.+}}11OtherStruct", "baz"]
// DEPENDS-MEMBER-NEGATIVE-NOT: - ["{{.+}}11OtherStruct", ""]
func foo() {}
var bar: () { return () }
private func baz() {}
}
// PROVIDES-NOMINAL-NEGATIVE-LABEL: {{^depends-nominal:$}}
// PROVIDES-MEMBER-NEGATIVE-LABEL: {{^depends-member:$}}
| apache-2.0 | 56a9212c3c80de13414e20f19cb7b482 | 41.070423 | 174 | 0.643455 | 3.437284 | false | false | false | false |
rnystrom/GitHawk | Classes/Systems/PhotoViewHandler.swift | 1 | 2649 | //
// PhotoViewHandler.swift
// Freetime
//
// Created by Ryan Nystrom on 7/5/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import NYTPhotoViewer
import SDWebImage
import Squawk
final class PhotoViewHandler: NSObject,
IssueCommentImageCellDelegate,
NYTPhotosViewControllerDelegate,
IssueCommentHtmlCellImageDelegate {
private weak var viewController: UIViewController?
private weak var referenceImageView: UIImageView?
private var singlePhotoDataSource: NYTPhotoViewerSinglePhotoDataSource?
init(viewController: UIViewController?) {
self.viewController = viewController
}
// MARK: IssueCommentImageCellDelegate
func didTapImage(cell: IssueCommentImageCell, image: UIImage, animatedImageData: Data?) {
referenceImageView = cell.imageView
let photo = IssueCommentPhoto(image: image, data: animatedImageData)
let dataSource = NYTPhotoViewerSinglePhotoDataSource(photo: photo)
singlePhotoDataSource = dataSource
viewController?.route_present(to: NYTPhotosViewController(
dataSource: dataSource,
initialPhoto: photo,
delegate: self
))
}
// MARK: NYTPhotosViewControllerDelegate
func photosViewController(_ photosViewController: NYTPhotosViewController, referenceViewFor photo: NYTPhoto) -> UIView? {
return referenceImageView
}
func photosViewControllerDidDismiss(_ photosViewController: NYTPhotosViewController) {
referenceImageView = nil
}
// MARK: IssueCommentHtmlCellImageDelegate
func webViewDidTapImage(cell: IssueCommentHtmlCell, url: URL) {
// cannot download svgs yet
guard url.pathExtension != "svg" else { return }
let isGif = url.pathExtension.lowercased() == "gif"
let photo = IssueCommentPhoto()
let dataSource = NYTPhotoViewerSinglePhotoDataSource(photo: photo)
singlePhotoDataSource = dataSource
let controller = NYTPhotosViewController(dataSource: dataSource, initialPhoto: photo, delegate: self)
viewController?.route_present(to: controller)
SDWebImageDownloader.shared().downloadImage(
with: url,
options: [.highPriority],
progress: nil
) { (image, data, _, _) in
if image != nil || data != nil {
if isGif {
photo.imageData = data
} else {
photo.image = image
}
controller.update(photo)
} else {
Squawk.showGenericError()
}
}
}
}
| mit | 54ab90161bf21763ecf891739fafc100 | 30.903614 | 125 | 0.662764 | 5.505198 | false | false | false | false |
mcxiaoke/learning-ios | cocoa_programming_for_osx/13_BasicCoreData/CarLot/CarLot/Document.swift | 1 | 1399 | //
// Document.swift
// CarLot
//
// Created by mcxiaoke on 16/5/4.
// Copyright © 2016年 mcxiaoke. All rights reserved.
//
import Cocoa
class Document: NSPersistentDocument {
@IBOutlet weak var tableView:NSTableView!
@IBOutlet weak var arrayController:NSArrayController!
@IBAction func addCar(car:AnyObject) {
let windowController = windowControllers[0]
let window = windowController.window!
let endedEditing = window.makeFirstResponder(window)
if !endedEditing {
print("Unable to end editing.")
return
}
let car = arrayController.newObject() as! NSObject
arrayController.addObject(car)
arrayController.rearrangeObjects()
let sortedCars = arrayController.arrangedObjects as! [NSObject]
let row = sortedCars.indexOf(car)!
print("starting edit car in row \(row)")
tableView.editColumn(0, row: row, withEvent: nil, select: true)
}
override init() {
super.init()
// Add your subclass-specific initialization here.
}
override class func autosavesInPlace() -> Bool {
return true
}
override var windowNibName: String? {
// Returns the nib file name of the document
// If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead.
return "Document"
}
}
| apache-2.0 | cbebc0f665ed022af65342fe086e0744 | 27.489796 | 194 | 0.711318 | 4.488746 | false | false | false | false |
JamieScanlon/AugmentKit | AugmentKit/Renderer/Render Modules/RenderModule.swift | 1 | 12785 | //
// RenderModule.swift
// AugmentKit
//
// MIT License
//
// Copyright (c) 2019 JamieScanlon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import MetalKit
import AugmentKitShader
// MARK: - RenderModule protocol
protocol RenderModule: ShaderModule {
//
// State
//
var renderDistance: Double { get set }
//
// Bootstrap
//
// Load the data from the Model Provider.
func loadAssets(forGeometricEntities: [AKGeometricEntity], fromModelProvider: ModelProvider?, textureLoader: MTKTextureLoader, completion: (() -> Void))
/// After this function is called, The Render Pass Desciptors, Textures, Buffers, Render Pipeline State Descriptors, and Depth Stencil Descriptors should all be set up.
func loadPipeline(withModuleEntities: [AKEntity], metalLibrary: MTLLibrary, renderDestination: RenderDestinationProvider, modelManager: ModelManager, renderPass: RenderPass?, numQualityLevels: Int, completion: (([DrawCallGroup]) -> Void)?)
//
// Per Frame Updates
//
// Update the buffer data for the geometric entities
func updateBuffers(withModuleEntities: [AKEntity], cameraProperties: CameraProperties, environmentProperties: EnvironmentProperties, shadowProperties: ShadowProperties, argumentBufferProperties: ArgumentBufferProperties, forRenderPass renderPass: RenderPass)
// Update the render encoder for the draw call. At the end of this method it is expected that
// drawPrimatives or drawIndexedPrimatives is called.
func draw(withRenderPass renderPass: RenderPass, sharedModules: [SharedRenderModule]?)
}
// MARK: - RenderModule extensions
extension RenderModule {
/// Calls `drawIndexedPrimitives` for every submesh in the `drawData`
func draw(withDrawData drawData: DrawData, with renderEncoder: MTLRenderCommandEncoder, baseIndex: Int = 0, environmentData: EnvironmentData? = nil, includeGeometry: Bool = true, includeSkeleton: Bool = false, includeLighting: Bool = true) {
if includeGeometry {
// Set mesh's vertex buffers
for (index, vertexBuffer) in drawData.vertexBuffers.enumerated() {
renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, index: index)
}
// Set mesh's raw vertex buffer
if let vertexBuffer = drawData.rawVertexBuffers.first {
renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, index: Int(kBufferIndexRawVertexData.rawValue))
}
if includeSkeleton {
var jointCount = drawData.skeleton?.jointCount ?? 0
renderEncoder.setVertexBytes(&jointCount, length: 8, index: Int(kBufferIndexMeshJointCount.rawValue))
}
}
// Draw each submesh of our mesh
for submeshData in drawData.subData {
guard drawData.instanceCount > 0 else {
continue
}
guard let indexBuffer = submeshData.indexBuffer else {
continue
}
let indexCount = Int(submeshData.indexCount)
let indexType = submeshData.indexType
var materialUniforms = submeshData.materialUniforms
if includeLighting {
// Set textures based off material flags
encodeTextures(for: renderEncoder, subData: submeshData, environmentData: environmentData)
renderEncoder.setFragmentBytes(&materialUniforms, length: RenderModuleConstants.alignedMaterialSize, index: Int(kBufferIndexMaterialUniforms.rawValue))
}
if includeGeometry {
renderEncoder.drawIndexedPrimitives(type: .triangle, indexCount: indexCount, indexType: indexType, indexBuffer: indexBuffer, indexBufferOffset: 0, instanceCount: drawData.instanceCount, baseVertex: 0, baseInstance: baseIndex)
}
}
}
// MARK: Encoding Textures
func encodeTextures(for renderEncoder: MTLRenderCommandEncoder, subData drawSubData: DrawSubData, environmentData: EnvironmentData? = nil) {
if let baseColorTexture = drawSubData.baseColorTexture {
renderEncoder.setFragmentTexture(baseColorTexture, index: Int(kTextureIndexColor.rawValue))
}
if let ambientOcclusionTexture = drawSubData.ambientOcclusionTexture, AKCapabilities.AmbientOcclusionMap {
renderEncoder.setFragmentTexture(ambientOcclusionTexture, index: Int(kTextureIndexAmbientOcclusion.rawValue))
}
if let emissionTexture = drawSubData.emissionTexture, AKCapabilities.EmissionMap {
renderEncoder.setFragmentTexture(emissionTexture, index: Int(kTextureIndexEmissionMap.rawValue))
}
if let normalTexture = drawSubData.normalTexture, AKCapabilities.NormalMap {
renderEncoder.setFragmentTexture(normalTexture, index: Int(kTextureIndexNormal.rawValue))
}
if let roughnessTexture = drawSubData.roughnessTexture, AKCapabilities.RoughnessMap {
renderEncoder.setFragmentTexture(roughnessTexture, index: Int(kTextureIndexRoughness.rawValue))
}
if let metallicTexture = drawSubData.metallicTexture, AKCapabilities.MetallicMap {
renderEncoder.setFragmentTexture(metallicTexture, index: Int(kTextureIndexMetallic.rawValue))
}
if let subsurfaceTexture = drawSubData.subsurfaceTexture, AKCapabilities.SubsurfaceMap {
renderEncoder.setFragmentTexture(subsurfaceTexture, index: Int(kTextureIndexSubsurfaceMap.rawValue))
}
if let specularTexture = drawSubData.specularTexture, AKCapabilities.SpecularMap {
renderEncoder.setFragmentTexture(specularTexture, index: Int(kTextureIndexSpecularMap.rawValue))
}
if let specularTintTexture = drawSubData.specularTintTexture, AKCapabilities.SpecularTintMap {
renderEncoder.setFragmentTexture(specularTintTexture, index: Int(kTextureIndexSpecularTintMap.rawValue))
}
if let anisotropicTexture = drawSubData.anisotropicTexture, AKCapabilities.AnisotropicMap {
renderEncoder.setFragmentTexture(anisotropicTexture, index: Int(kTextureIndexAnisotropicMap.rawValue))
}
if let sheenTexture = drawSubData.sheenTexture, AKCapabilities.SheenMap {
renderEncoder.setFragmentTexture(sheenTexture, index: Int(kTextureIndexSheenMap.rawValue))
}
if let sheenTintTexture = drawSubData.sheenTintTexture, AKCapabilities.SheenTintMap {
renderEncoder.setFragmentTexture(sheenTintTexture, index: Int(kTextureIndexSheenTintMap.rawValue))
}
if let clearcoatTexture = drawSubData.clearcoatTexture, AKCapabilities.ClearcoatMap {
renderEncoder.setFragmentTexture(clearcoatTexture, index: Int(kTextureIndexClearcoatMap.rawValue))
}
if let clearcoatGlossTexture = drawSubData.clearcoatGlossTexture, AKCapabilities.ClearcoatGlossMap {
renderEncoder.setFragmentTexture(clearcoatGlossTexture, index: Int(kTextureIndexClearcoatGlossMap.rawValue))
}
if let texture = environmentData?.environmentTexture, AKCapabilities.EnvironmentMap {
renderEncoder.setFragmentTexture(texture, index: Int(kTextureIndexEnvironmentMap.rawValue))
}
if let texture = environmentData?.diffuseIBLTexture, AKCapabilities.ImageBasedLighting {
renderEncoder.setFragmentTexture(texture, index: Int(kTextureIndexDiffuseIBLMap.rawValue))
}
if let texture = environmentData?.specularIBLTexture, AKCapabilities.ImageBasedLighting {
renderEncoder.setFragmentTexture(texture, index: Int(kTextureIndexSpecularIBLMap.rawValue))
}
if let texture = environmentData?.bdrfLookupTexture, AKCapabilities.ImageBasedLighting {
renderEncoder.setFragmentTexture(texture, index: Int(kTextureIndexBDRFLookupMap.rawValue))
}
}
func createMTLTexture(inBundle bundle: Bundle, fromAssetPath assetPath: String, withTextureLoader textureLoader: MTKTextureLoader?) -> MTLTexture? {
do {
let textureURL: URL? = {
guard let aURL = URL(string: assetPath) else {
return nil
}
if aURL.scheme == nil {
// If there is no scheme, assume it's a file in the bundle.
let last = aURL.lastPathComponent
if let bundleURL = bundle.url(forResource: last, withExtension: nil) {
return bundleURL
} else if let bundleURL = bundle.url(forResource: aURL.path, withExtension: nil) {
return bundleURL
} else {
return aURL
}
} else {
return aURL
}
}()
guard let aURL = textureURL else {
return nil
}
return try textureLoader?.newTexture(URL: aURL, options: nil)
} catch {
print("Unable to loader texture with assetPath \(assetPath) with error \(error)")
let newError = AKError.recoverableError(.modelError(.unableToLoadTexture(AssetErrorInfo(path: assetPath, underlyingError: error))))
recordNewError(newError)
}
return nil
}
// MARK: Render Distance
func anchorDistance(withTransform transform: matrix_float4x4, cameraProperties: CameraProperties?) -> Float {
guard let cameraProperties = cameraProperties else {
return 0
}
let point = SIMD3<Float>(transform.columns.3.x, transform.columns.3.x, transform.columns.3.z)
return length(point - cameraProperties.position)
}
// MARK: Util
func getRGB(from colorTemperature: CGFloat) -> SIMD3<Float> {
let temp = Float(colorTemperature) / 100
var red: Float = 127
var green: Float = 127
var blue: Float = 127
if temp <= 66 {
red = 255
green = temp
green = 99.4708025861 * log(green) - 161.1195681661
if temp <= 19 {
blue = 0
} else {
blue = temp - 10
blue = 138.5177312231 * log(blue) - 305.0447927307
}
} else {
red = temp - 60
red = 329.698727446 * pow(red, -0.1332047592)
green = temp - 60
green = 288.1221695283 * pow(green, -0.0755148492 )
blue = 255
}
let clamped = clamp(SIMD3<Float>(red, green, blue), min: 0, max: 255) / 255
return SIMD3<Float>(clamped.x, clamped.y, clamped.z)
}
}
// MARK: - RenderModuleConstants
enum RenderModuleConstants {
static let alignedMaterialSize = (MemoryLayout<MaterialUniforms>.stride & ~0xFF) + 0x100
}
// MARK: - SharedRenderModule protocol
/// A shared render module is a `RenderModule` responsible for setting up and updating shared buffers. Although it does have a draw() method, typically this method does not do anything. Instead, the module that uses this shared module is responsible for encoding the shared buffer and issuing the draw call
protocol SharedRenderModule: RenderModule {
var sharedUniformsBuffer: GPUPassBuffer<SharedUniforms>? { get }
}
| mit | 998aeb16b3e6fbc57af4d8337b935155 | 43.702797 | 306 | 0.660461 | 5.320433 | false | false | false | false |
warnerbros/cpe-manifest-ios-experience | Source/Shared Controllers/TalentImageGalleryViewController.swift | 1 | 4525 | //
// TalentImageGalleryViewController.swift
//
import UIKit
import CPEData
class TalentImageGalleryViewController: SceneDetailViewController {
fileprivate struct Constants {
static let CollectionViewItemSpacing: CGFloat = 10
static let CollectionViewItemAspectRatio: CGFloat = 3 / 4
}
@IBOutlet weak fileprivate var galleryScrollView: ImageGalleryScrollView!
@IBOutlet weak private var galleryCollectionView: UICollectionView!
var talent: Person!
var initialPage = 0
private var galleryDidScrollToPageObserver: NSObjectProtocol?
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
galleryScrollView.cleanInvisibleImages()
}
override func viewDidLoad() {
self.title = String.localize("talentdetail.gallery")
super.viewDidLoad()
galleryScrollView.currentPage = initialPage
galleryScrollView.removeToolbar()
galleryDidScrollToPageObserver = NotificationCenter.default.addObserver(forName: .imageGalleryDidScrollToPage, object: nil, queue: OperationQueue.main, using: { [weak self] (notification) in
if let strongSelf = self, let page = notification.userInfo?[NotificationConstants.page] as? Int {
let pageIndexPath = IndexPath(item: page, section: 0)
strongSelf.galleryCollectionView.selectItem(at: pageIndexPath, animated: false, scrollPosition: UICollectionViewScrollPosition())
var cellIsShowing = false
for cell in strongSelf.galleryCollectionView.visibleCells {
if let indexPath = strongSelf.galleryCollectionView.indexPath(for: cell), indexPath.row == page {
cellIsShowing = true
break
}
}
if !cellIsShowing {
strongSelf.galleryCollectionView.scrollToItem(at: pageIndexPath, at: .centeredHorizontally, animated: true)
}
}
})
galleryCollectionView.register(UINib(nibName: SimpleImageCollectionViewCell.NibName, bundle: Bundle.frameworkResources), forCellWithReuseIdentifier: SimpleImageCollectionViewCell.BaseReuseIdentifier)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let gallery = talent.gallery {
galleryScrollView.load(with: gallery)
galleryScrollView.gotoPage(initialPage, animated: false)
}
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return (DeviceType.IS_IPAD ? .landscape : .portrait)
}
}
extension TalentImageGalleryViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (talent.gallery?.numPictures ?? 0)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let collectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: SimpleImageCollectionViewCell.BaseReuseIdentifier, for: indexPath)
guard let cell = collectionViewCell as? SimpleImageCollectionViewCell else {
return collectionViewCell
}
cell.showsSelectedBorder = true
cell.isSelected = (indexPath.row == galleryScrollView.currentPage)
cell.imageURL = talent.gallery?.picture(atIndex: indexPath.row)?.thumbnailImageURL
return cell
}
}
extension TalentImageGalleryViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
galleryScrollView.gotoPage(indexPath.row, animated: true)
Analytics.log(event: .extrasTalentGalleryAction, action: .selectImage, itemId: talent.id)
}
}
extension TalentImageGalleryViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = collectionView.frame.height
return CGSize(width: height * Constants.CollectionViewItemAspectRatio, height: height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return Constants.CollectionViewItemSpacing
}
}
| apache-2.0 | 76ff57236418c68c8d6ba5c95ee5b3f3 | 38.692982 | 207 | 0.719337 | 6.073826 | false | false | false | false |
Ramotion/reel-search | RAMReelExample/RAMReelExample/ViewController.swift | 1 | 1393 | //
// ViewController.swift
// RAMReel
//
// Created by Mikhail Stepkin on 4/2/15.
// Copyright (c) 2015 Ramotion. All rights reserved.
//
import UIKit
import RAMReel
@available(iOS 8.2, *)
class ViewController: UIViewController, UICollectionViewDelegate {
var dataSource: SimplePrefixQueryDataSource!
var ramReel: RAMReel<RAMCell, RAMTextField, SimplePrefixQueryDataSource>!
override func viewDidLoad() {
super.viewDidLoad()
dataSource = SimplePrefixQueryDataSource(data)
ramReel = RAMReel(frame: view.bounds, dataSource: dataSource, placeholder: "Start by typing…", attemptToDodgeKeyboard: true) {
print("Plain:", $0)
}
ramReel.hooks.append {
let r = Array($0.reversed())
let j = String(r)
print("Reversed:", j)
}
view.addSubview(ramReel.view)
ramReel.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
fileprivate let data: [String] = {
do {
guard let dataPath = Bundle.main.path(forResource: "data", ofType: "txt") else {
return []
}
let data = try WordReader(filepath: dataPath)
return data.words
}
catch let error {
print(error)
return []
}
}()
}
| mit | 38657b75deb04fa96434e01a4784d165 | 26.27451 | 134 | 0.570812 | 4.560656 | false | false | false | false |
lhwsygdtc900723/firefox-ios | Storage/FileAccessor.swift | 3 | 4058 | /* 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
/**
* A convenience class for file operations under a given root directory.
* Note that while this class is intended to be used to operate only on files
* under the root, this is not strictly enforced: clients can go outside
* the path using ".." or symlinks.
*/
public class FileAccessor {
public let rootPath: String
public init(rootPath: String) {
self.rootPath = rootPath
}
/**
* Gets the absolute directory path at the given relative path, creating it if it does not exist.
*/
public func getAndEnsureDirectory(relativeDir: String? = nil, error: NSErrorPointer = nil) -> String? {
var absolutePath = rootPath
if let relativeDir = relativeDir {
absolutePath = absolutePath.stringByAppendingPathComponent(relativeDir)
}
return createDir(absolutePath, error: error) ? absolutePath : nil
}
/**
* Gets the file or directory at the given path, relative to the root.
*/
public func remove(relativePath: String, error: NSErrorPointer = nil) -> Bool {
let path = rootPath.stringByAppendingPathComponent(relativePath)
return NSFileManager.defaultManager().removeItemAtPath(path, error: error)
}
/**
* Removes the contents of the directory without removing the directory itself.
*/
public func removeFilesInDirectory(relativePath: String = "", error: NSErrorPointer = nil) -> Bool {
let fileManager = NSFileManager.defaultManager()
let path = rootPath.stringByAppendingPathComponent(relativePath)
if let files = fileManager.contentsOfDirectoryAtPath(path, error: error) {
var success = true
for file in files {
if let filename = file as? String {
success = success && remove(relativePath.stringByAppendingPathComponent(filename), error: error)
}
}
return success
}
return false
}
/**
* Determines whether a file exists at the given path, relative to the root.
*/
public func exists(relativePath: String) -> Bool {
let path = rootPath.stringByAppendingPathComponent(relativePath)
return NSFileManager.defaultManager().fileExistsAtPath(path)
}
/**
* Moves the file or directory to the given destination, with both paths relative to the root.
* The destination directory is created if it does not exist.
*/
public func move(fromRelativePath: String, toRelativePath: String, error: NSErrorPointer = nil) -> Bool {
let fromPath = rootPath.stringByAppendingPathComponent(fromRelativePath)
let toPath = rootPath.stringByAppendingPathComponent(toRelativePath)
let toDir = toPath.stringByDeletingLastPathComponent
if !createDir(toDir, error: error) {
return false
}
return NSFileManager.defaultManager().moveItemAtPath(fromPath, toPath: toPath, error: error)
}
public func copy(fromRelativePath: String, toAbsolutePath: String, error: NSErrorPointer = nil) -> Bool {
let fromPath = rootPath.stringByAppendingPathComponent(fromRelativePath)
let toDir = toAbsolutePath.stringByDeletingLastPathComponent
if !createDir(toDir, error: error) {
return false
}
return NSFileManager.defaultManager().copyItemAtPath(fromPath, toPath: toAbsolutePath, error: error)
}
/**
* Creates a directory with the given path, including any intermediate directories.
* Does nothing if the directory already exists.
*/
private func createDir(absolutePath: String, error: NSErrorPointer = nil) -> Bool {
return NSFileManager.defaultManager().createDirectoryAtPath(absolutePath, withIntermediateDirectories: true, attributes: nil, error: error)
}
}
| mpl-2.0 | dbca8b9ed68b8f985431ee06a38fdd23 | 38.784314 | 147 | 0.682602 | 5.249677 | false | false | false | false |
jcfausto/transit-app | TransitApp/TransitAppTests/StopSpecs.swift | 1 | 1276 | //
// StopSpecs.swift
// TransitApp
//
// Created by Julio Cesar Fausto on 24/02/16.
// Copyright © 2016 Julio Cesar Fausto. All rights reserved.
//
import Quick
import Nimble
@testable import TransitApp
class StopSpecs: QuickSpec {
override func spec() {
describe("Stop") {
var stop: Stop!
beforeEach {
let latitude = 52.530227
let longitude = 13.403356
let name = "Stop1"
let time = NSDate(datetimeString: "2015-04-17T13:38:00+02:00")
stop = Stop(name: name, latitude: latitude, longitude: longitude, time: time)
}
it("has a name"){
expect(stop.name).to(equal("Stop1"))
}
it("has a latitude") {
expect(stop.latitude).to(equal(52.530227))
}
it("has a longitude") {
expect(stop.longitude).to(equal(13.403356))
}
it("has a time") {
expect(stop.time).to(equal(NSDate(datetimeString: "2015-04-17T13:38:00+02:00")))
}
}
}
}
| mit | 3822ca19ef8f4ca34496c54d6640e7ba | 24 | 96 | 0.454118 | 4.366438 | false | false | false | false |
m-schmidt/Refracto | Refracto/DisclosureIndicator.swift | 1 | 929 | // DisclosureIndicator.swift - Themeable Disclosure Indicator for UITableView
import UIKit
class DisclosureIndicator: UIView {
convenience init() {
self.init(frame: CGRect(x: 0, y: 0, width: 11, height: 18))
isOpaque = false
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
context.setFillColor(UIColor.clear.cgColor)
context.fill(self.bounds)
let x = self.bounds.maxX - 3
let y = self.bounds.midY
let r = CGFloat(4.5)
context.move(to: CGPoint(x: x-r, y: y-r))
context.addLine(to: CGPoint(x: x, y: y))
context.addLine(to: CGPoint(x: x-r, y: y+r))
context.setLineCap(.round)
context.setLineJoin(.round)
context.setLineWidth(2)
context.setStrokeColor(Colors.settingsCellSecondaryForeground.cgColor)
context.strokePath()
}
}
| bsd-3-clause | 5dc76a70ae5f73291479c57997f70a9e | 29.966667 | 78 | 0.634015 | 3.936441 | false | false | false | false |
khizkhiz/swift | validation-test/compiler_crashers_fixed/01375-clang-declvisitor-base-clang-declvisitor-make-const-ptr.swift | 1 | 1071 | // RUN: not %target-swift-frontend %s -parse
// REQUIRES: objc_interop
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
}
import Foundation
var d, i: A {
deinit {
(i(c> T! {
}
}
typealias h.Type
}
extension NSData {
typealias d>() {
d<B : AnyObject.b where S(p: ((e()
struct c == [c<U : Any) -> T, T) {
a
import Foundation
var b() -> <T).B<S : (f<c<T, T where k) -> {
}
}
return nil
map() {
import Foundation
class func a() -> {
class func g<T : A : a {
assert()
class c
}
}
print(e<b
var b: P> (e?
"""foo")
}
let a {
func x):Any) {
}
}
class A = {
func e()
class c = F>()")
let end = i() -> (z(Any) {
assert(() -> Any in
let h: String {
}
protocol A {
private class a!))
return d.c(AnyObject, AnyObject) {
[unowned self.h: B
}
}
}
default:
}
convenience init(bytes: Sequence> V>(Any, Any) {
}
var f.E == B
self.init(f<T) {
}
self.init(range: d : ExtensibleCollectionType>(")
return NSData((a)
struct D : A) {
func g> Any) -> {
}
}
func a<T : a {
f
| apache-2.0 | 4b6b86af5dc6febc1042610f4c8925f9 | 13.875 | 87 | 0.610644 | 2.612195 | false | false | false | false |
stone-payments/onestap-sdk-ios | OnestapSDK/Core/Enums/OSTEnvironmentsEnum.swift | 1 | 3449 | //
// OSTEnvironmentsEnum.swift
// OnestapSDK
//
// Created by Munir Wanis on 18/08/17.
// Copyright © 2017 Stone Payments. All rights reserved.
//
import Foundation
public enum OSTEnvironmentEnum: String {
/// Sandbox Environment
case sandbox
/// Production Environment
case production
/**
Create `FCEnvironmentEnum` by passing a `String`.
Default value is `.sandbox`.
- parameters:
- rawValue: String that contains corresponding value to the enumerator
*/
public init(rawValue: String) {
ApiUrls.isStaging = false
switch rawValue.lowercased() {
case "production":
self = .production
case "sandbox":
self = .sandbox
case "staging":
ApiUrls.isStaging = true
self = .sandbox
default:
self = .sandbox
}
}
/**
Return Web URL to open login page
*/
internal var webURL: URL {
get {
switch self {
case .production:
return ApiUrls.onestapProductionWebUrl
case .sandbox:
if ApiUrls.isStaging { fallthrough }
return ApiUrls.onestapSandboxWebUrl
default:
return ApiUrls.onestapStagingWebUrl
}
}
}
/**
Return API URL to communicate with the Authentication API
*/
internal var authClientApiURL: URL {
get {
switch self {
case .production:
return ApiUrls.onestapProductionAuthUrl
case .sandbox:
if ApiUrls.isStaging { fallthrough }
return ApiUrls.onestapSandboxAuthUrl
default:
return ApiUrls.onestapStagingAuthUrl
}
}
}
/**
Return API URL to communicate with the Management API
*/
internal var userManagementURL: URL {
get {
switch self {
case .production:
return ApiUrls.onestapProductionUserManagementUrl
case .sandbox:
if ApiUrls.isStaging { fallthrough }
return ApiUrls.onestapSandboxUserManagementUrl
default:
return ApiUrls.onestapStagingUserManagementUrl
}
}
}
private struct ApiUrls {
private static let version = "v1"
static var isStaging: Bool = false
static let onestapStagingWebUrl: URL! = URL(string: "https://signin-stg.onestap.com/")
static let onestapStagingAuthUrl: URL! = URL(string: "https://authclient-stg.onestap.com/\(version)/")
static let onestapStagingUserManagementUrl: URL! = URL(string: "https://api-stg.onestap.com/")
static let onestapSandboxWebUrl: URL! = URL(string: "https://signin-sandbox.onestap.com/")
static let onestapSandboxAuthUrl: URL! = URL(string: "https://authclient-sandbox.onestap.com/\(version)/")
static let onestapSandboxUserManagementUrl: URL! = URL(string: "https://api-sandbox.onestap.com/")
static let onestapProductionWebUrl: URL! = URL(string: "https://signin.onestap.com/")
static let onestapProductionAuthUrl: URL! = URL(string: "https://authclient.onestap.com/\(version)/")
static let onestapProductionUserManagementUrl: URL! = URL(string: "https://api.onestap.com/")
}
}
| apache-2.0 | 96bc98de6f2dc0d9456fcdf2f2f6eda3 | 30.925926 | 114 | 0.586137 | 5.123328 | false | false | false | false |
xwu/swift | test/ModuleInterface/ModuleCache/module-cache-diagnostics.swift | 4 | 8148 | // RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/modulecache)
//
// Setup builds a module TestModule that depends on OtherModule and LeafModule (built from other.swift and leaf.swift).
// During setup, input and intermediate mtimes are all set to a constant 'old' time (long in the past).
//
// We then revert LeafModule.swiftinterface to have a warning-provoking entry in it, and check that we get no diagnostic.
//
// We then modify LeafModule.swiftinterface to have an error in it, and check that we get a diagnostic and failure.
//
// We then modify LeafModule.swiftinterface to have an error in an @inlinable function body, and check we get a diagnostic and failure.
//
// Setup phase 1: Write input files.
//
// RUN: echo 'public func LeafFunc() -> Int { return 10; }' >%t/leaf.swift
//
// RUN: echo 'import LeafModule' >%t/other.swift
// RUN: echo 'public func OtherFunc() -> Int { return LeafFunc(); }' >>%t/other.swift
//
//
// Setup phase 2: build modules, pushing timestamps of inputs and intermediates into the past as we go.
//
// RUN: %{python} %S/Inputs/make-old.py %t/leaf.swift %t/other.swift
// RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -I %t -emit-module-interface-path %t/LeafModule.swiftinterface -module-name LeafModule %t/leaf.swift -emit-module -o /dev/null
// RUN: %{python} %S/Inputs/make-old.py %t/LeafModule.swiftinterface
// RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -I %t -module-cache-path %t/modulecache -emit-module-interface-path %t/OtherModule.swiftinterface -module-name OtherModule %t/other.swift -emit-module -o /dev/null
// RUN: %{python} %S/Inputs/make-old.py %t/modulecache/LeafModule-*.swiftmodule %t/OtherModule.swiftinterface
// RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -I %t -module-cache-path %t/modulecache -emit-module -o %t/TestModule.swiftmodule -module-name TestModule %s
// RUN: %{python} %S/Inputs/make-old.py %t/modulecache/OtherModule-*.swiftmodule
//
//
// Actual test: add an inlinable func with an unused var to LeafModule.swiftinterface (which should emit a warning); check we do get a rebuild, but no warning. (For astooscopelookup testing, must filter out that warning; see the sed command below.)
//
// RUN: %{python} %S/Inputs/check-is-old.py %t/OtherModule.swiftinterface %t/LeafModule.swiftinterface
// RUN: %{python} %S/Inputs/check-is-old.py %t/modulecache/OtherModule-*.swiftmodule %t/modulecache/LeafModule-*.swiftmodule
// RUN: cp %t/LeafModule.swiftinterface %t/LeafModule.swiftinterface.backup
// RUN: echo "@inlinable func foo() { var x = 10 }" >>%t/LeafModule.swiftinterface
// RUN: %{python} %S/Inputs/make-old.py %t/LeafModule.swiftinterface
// RUN: %{python} %S/Inputs/check-is-old.py %t/LeafModule.swiftinterface
// RUN: rm %t/TestModule.swiftmodule
// RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -I %t -module-cache-path %t/modulecache -emit-module -o %t/TestModule.swiftmodule -module-name TestModule %s 2>&1 | sed '/WARNING: TRYING Scope exclusively/d' >%t/warn.txt
// RUN: %{python} %S/Inputs/check-is-new.py %t/modulecache/OtherModule-*.swiftmodule %t/modulecache/LeafModule-*.swiftmodule
// "check warn.txt exists and is empty"
// RUN: test -e %t/warn.txt -a ! -s %t/warn.txt
//
//
// Next test: make LeafModule.swiftinterface import NotAModule (which should emit an error); check we do not get a rebuild, do get an error.
//
// RUN: %{python} %S/Inputs/make-old.py %t/modulecache/*.swiftmodule %t/*.swiftinterface
// RUN: %{python} %S/Inputs/check-is-old.py %t/OtherModule.swiftinterface %t/LeafModule.swiftinterface
// RUN: %{python} %S/Inputs/check-is-old.py %t/modulecache/OtherModule-*.swiftmodule %t/modulecache/LeafModule-*.swiftmodule
// RUN: echo "import NotAModule" >>%t/LeafModule.swiftinterface
// RUN: %{python} %S/Inputs/make-old.py %t/LeafModule.swiftinterface
// RUN: %{python} %S/Inputs/check-is-old.py %t/LeafModule.swiftinterface
// RUN: rm %t/TestModule.swiftmodule
// RUN: not %target-swift-frontend -disable-implicit-concurrency-module-import -I %t -module-cache-path %t/modulecache -emit-module -o %t/TestModule.swiftmodule -module-name TestModule %s >%t/err.txt 2>&1
// RUN: %{python} %S/Inputs/check-is-old.py %t/modulecache/OtherModule-*.swiftmodule %t/modulecache/LeafModule-*.swiftmodule
// RUN: %FileCheck %s -check-prefix=CHECK-ERROR <%t/err.txt
// CHECK-ERROR: LeafModule.swiftinterface:7:8: error: no such module 'NotAModule'
// CHECK-ERROR: OtherModule.swiftinterface:4:8: error: failed to build module 'LeafModule' for importation due to the errors above; the textual interface may be broken by project issues or a compiler bug
// CHECK-ERROR: module-cache-diagnostics.swift:{{[0-9]+}}:8: error: failed to build module 'OtherModule' for importation due to the errors above; the textual interface may be broken by project issues or a compiler bug
// CHECK-ERROR-NOT: error:
//
//
// Next test: same as above, but with a .dia file
//
// RUN: %{python} %S/Inputs/check-is-old.py %t/OtherModule.swiftinterface %t/LeafModule.swiftinterface
// RUN: %{python} %S/Inputs/check-is-old.py %t/modulecache/OtherModule-*.swiftmodule %t/modulecache/LeafModule-*.swiftmodule
// RUN: not %target-swift-frontend -disable-implicit-concurrency-module-import -I %t -module-cache-path %t/modulecache -serialize-diagnostics -serialize-diagnostics-path %t/err.dia -emit-module -o %t/TestModule.swiftmodule -module-name TestModule %s
// RUN: %{python} %S/Inputs/check-is-old.py %t/modulecache/OtherModule-*.swiftmodule %t/modulecache/LeafModule-*.swiftmodule
// RUN: c-index-test -read-diagnostics %t/err.dia 2>&1 | %FileCheck %s -check-prefix=CHECK-ERROR
//
//
// Next test: add an inlinable function body with an cannot find to LeafModule.swiftinterface; check we do not get a rebuild and report the additional error correctly.
//
// RUN: mv %t/LeafModule.swiftinterface.backup %t/LeafModule.swiftinterface
// RUN: echo "@inlinable func bar() { var x = unresolved }" >>%t/LeafModule.swiftinterface
// RUN: %{python} %S/Inputs/make-old.py %t/LeafModule.swiftinterface
// RUN: %{python} %S/Inputs/check-is-old.py %t/OtherModule.swiftinterface %t/LeafModule.swiftinterface
// RUN: %{python} %S/Inputs/check-is-old.py %t/modulecache/OtherModule-*.swiftmodule %t/modulecache/LeafModule-*.swiftmodule
// RUN: not %target-swift-frontend -disable-implicit-concurrency-module-import -I %t -module-cache-path %t/modulecache -emit-module -o %t/TestModule.swiftmodule -module-name TestModule %s >%t/err-inline.txt 2>&1
// RUN: %{python} %S/Inputs/check-is-old.py %t/modulecache/OtherModule-*.swiftmodule %t/modulecache/LeafModule-*.swiftmodule
// RUN: %FileCheck %s -check-prefix=CHECK-ERROR-INLINE <%t/err-inline.txt
// CHECK-ERROR-INLINE: LeafModule.swiftinterface:6:33: error: cannot find 'unresolved' in scope
// CHECK-ERROR-INLINE: OtherModule.swiftinterface:4:8: error: failed to build module 'LeafModule' for importation due to the errors above; the textual interface may be broken by project issues or a compiler bug
// CHECK-ERROR-INLINE: module-cache-diagnostics.swift:{{[0-9]+}}:8: error: failed to build module 'OtherModule' for importation due to the errors above; the textual interface may be broken by project issues or a compiler bug
// CHECK-ERROR-INLINE-NOT: error:
//
//
// Next test: same as above, but with a .dia file
//
// RUN: %{python} %S/Inputs/check-is-old.py %t/OtherModule.swiftinterface %t/LeafModule.swiftinterface
// RUN: %{python} %S/Inputs/check-is-old.py %t/modulecache/OtherModule-*.swiftmodule %t/modulecache/LeafModule-*.swiftmodule
// RUN: not %target-swift-frontend -disable-implicit-concurrency-module-import -I %t -module-cache-path %t/modulecache -serialize-diagnostics -serialize-diagnostics-path %t/err-inline.dia -emit-module -o %t/TestModule.swiftmodule -module-name TestModule %s
// RUN: %{python} %S/Inputs/check-is-old.py %t/modulecache/OtherModule-*.swiftmodule %t/modulecache/LeafModule-*.swiftmodule
// RUN: c-index-test -read-diagnostics %t/err-inline.dia 2>&1 | %FileCheck %s -check-prefix=CHECK-ERROR-INLINE
import OtherModule
public func TestFunc() {
print(OtherFunc())
}
| apache-2.0 | d374f1e39a720a41572283e60fb127ed | 78.106796 | 256 | 0.748036 | 3.533391 | false | true | false | false |
Finb/V2ex-Swift | View/V2PhotoBrowser/V2Photo.swift | 1 | 2572 | //
// V2Photo.swift
// V2ex-Swift
//
// Created by huangfeng on 2/22/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
import Kingfisher
class V2Photo :NSObject{
static let V2PHOTO_PROGRESS_NOTIFICATION = "ME.FIN.V2PHOTO_PROGRESS_NOTIFICATION"
static let V2PHOTO_LOADING_DID_END_NOTIFICATION = "ME.FIN.V2PHOTO_LOADING_DID_END_NOTIFICATION"
var underlyingImage:UIImage?
var url:URL
init(url:URL) {
if let scheme = url.scheme?.lowercased() , !["https","http"].contains(scheme){
assert(true, "url.scheme must be a HTTP/HTTPS request")
}
self.url = url
}
func performLoadUnderlyingImageAndNotify(){
if self.underlyingImage != nil{
return ;
}
let resource = ImageResource(downloadURL: self.url)
KingfisherManager.shared.cache.retrieveImage(forKey: resource.cacheKey, options: nil) { (image, cacheType) -> () in
if image != nil {
dispatch_sync_safely_main_queue({ () -> () in
self.imageLoadingComplete(image)
})
}
else{
KingfisherManager.shared.downloader.downloadImage(with: resource.downloadURL, options: nil, progressBlock: { (receivedSize, totalSize) -> () in
let progress = Float(receivedSize) / Float(totalSize)
let dict = [
"progress":progress,
"photo":self
] as [String : Any]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: V2Photo.V2PHOTO_PROGRESS_NOTIFICATION), object: dict)
}){ (image, error, imageURL, originalData) -> () in
dispatch_sync_safely_main_queue({ () -> () in
self.imageLoadingComplete(image)
})
if let image = image {
//保存图片缓存
KingfisherManager.shared.cache.store(image, original: originalData, forKey: resource.cacheKey, toDisk: true, completionHandler: nil)
}
}
}
}
}
func imageLoadingComplete(_ image:UIImage?){
self.underlyingImage = image
NotificationCenter.default.post(name: Notification.Name(rawValue: V2Photo.V2PHOTO_LOADING_DID_END_NOTIFICATION), object: self)
}
}
| mit | 31c5234631077aaaad2ae830d7cbd5bf | 36.632353 | 160 | 0.540445 | 4.874286 | false | false | false | false |
bradhilton/SwiftCollection | Pods/OrderedObjectSet/Sources/ObjectWrapper.swift | 2 | 539 | //
// ObjectObjectWrapper.swift
// OrderedObjectSet
//
// Created by Bradley Hilton on 2/22/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
struct ObjectWrapper : Hashable {
let object: AnyObject
func hash(into hasher: inout Hasher) {
hasher.combine(Unmanaged.passUnretained(object).toOpaque().hashValue)
}
init(_ object: AnyObject) {
self.object = object
}
}
func ==(lhs: ObjectWrapper, rhs: ObjectWrapper) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| mit | 849230c73e507b92a04477667a4a9ab9 | 19.692308 | 77 | 0.644981 | 4.10687 | false | false | false | false |
shorlander/firefox-ios | Storage/SQL/SQLiteBookmarksSyncing.swift | 1 | 61100 | /* 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 Deferred
import Foundation
import Shared
import XCGLogger
private let log = Logger.syncLogger
extension SQLiteBookmarks: LocalItemSource {
public func getLocalItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> {
return self.db.getMirrorItemFromTable(TableBookmarksLocal, guid: guid)
}
public func getLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID {
return self.db.getMirrorItemsFromTable(TableBookmarksLocal, guids: guids)
}
public func prefetchLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID {
log.debug("Not implemented for SQLiteBookmarks.")
return succeed()
}
}
extension SQLiteBookmarks: MirrorItemSource {
public func getMirrorItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> {
return self.db.getMirrorItemFromTable(TableBookmarksMirror, guid: guid)
}
public func getMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID {
return self.db.getMirrorItemsFromTable(TableBookmarksMirror, guids: guids)
}
public func prefetchMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID {
log.debug("Not implemented for SQLiteBookmarks.")
return succeed()
}
}
extension SQLiteBookmarks {
func getSQLToOverrideFolder(_ folder: GUID, atModifiedTime modified: Timestamp) -> (sql: [String], args: Args) {
return self.getSQLToOverrideFolders([folder], atModifiedTime: modified)
}
func getSQLToOverrideFolders(_ folders: [GUID], atModifiedTime modified: Timestamp) -> (sql: [String], args: Args) {
if folders.isEmpty {
return (sql: [], args: [])
}
let vars = BrowserDB.varlist(folders.count)
let args: Args = folders
// Copy it to the local table.
// Most of these will be NULL, because we're only dealing with folders,
// and typically only the Mobile Bookmarks root.
let overrideSQL = "INSERT OR IGNORE INTO \(TableBookmarksLocal) " +
"(guid, type, bmkUri, title, parentid, parentName, feedUri, siteUri, pos," +
" description, tags, keyword, folderName, queryId, is_deleted, " +
" local_modified, sync_status, faviconID) " +
"SELECT guid, type, bmkUri, title, parentid, parentName, " +
"feedUri, siteUri, pos, description, tags, keyword, folderName, queryId, " +
"is_deleted, " +
"\(modified) AS local_modified, \(SyncStatus.changed.rawValue) AS sync_status, faviconID " +
"FROM \(TableBookmarksMirror) WHERE guid IN \(vars)"
// Copy its mirror structure.
let dropSQL = "DELETE FROM \(TableBookmarksLocalStructure) WHERE parent IN \(vars)"
let copySQL = "INSERT INTO \(TableBookmarksLocalStructure) " +
"SELECT * FROM \(TableBookmarksMirrorStructure) WHERE parent IN \(vars)"
// Mark as overridden.
let markSQL = "UPDATE \(TableBookmarksMirror) SET is_overridden = 1 WHERE guid IN \(vars)"
return (sql: [overrideSQL, dropSQL, copySQL, markSQL], args: args)
}
func getSQLToOverrideNonFolders(_ records: [GUID], atModifiedTime modified: Timestamp) -> (sql: [String], args: Args) {
log.info("Getting SQL to override \(records).")
if records.isEmpty {
return (sql: [], args: [])
}
let vars = BrowserDB.varlist(records.count)
let args: Args = records.map { $0 }
// Copy any that aren't overridden to the local table.
let overrideSQL =
"INSERT OR IGNORE INTO \(TableBookmarksLocal) " +
"(guid, type, bmkUri, title, parentid, parentName, feedUri, siteUri, pos," +
" description, tags, keyword, folderName, queryId, is_deleted, " +
" local_modified, sync_status, faviconID) " +
"SELECT guid, type, bmkUri, title, parentid, parentName, " +
"feedUri, siteUri, pos, description, tags, keyword, folderName, queryId, " +
"is_deleted, " +
"\(modified) AS local_modified, \(SyncStatus.changed.rawValue) AS sync_status, faviconID " +
"FROM \(TableBookmarksMirror) WHERE guid IN \(vars) AND is_overridden = 0"
// Mark as overridden.
let markSQL = "UPDATE \(TableBookmarksMirror) SET is_overridden = 1 WHERE guid IN \(vars)"
return (sql: [overrideSQL, markSQL], args: args)
}
/**
* Insert a bookmark into the specified folder.
* If the folder doesn't exist, or is deleted, insertion will fail.
*
* Preconditions:
* * `deferred` has not been filled.
* * this function is called inside a transaction that hasn't been finished.
*
* Postconditions:
* * `deferred` has been filled with success or failure.
* * the transaction will include any status/overlay changes necessary to save the bookmark.
* * the return value determines whether the transaction should be committed, and
* matches the success-ness of the Deferred.
*
* Sorry about the long line. If we break it, the indenting below gets crazy.
*/
fileprivate func insertBookmarkInTransaction(_ deferred: Success, url: URL, title: String, favicon: Favicon?, intoFolder parent: GUID, withTitle parentTitle: String, conn: SQLiteDBConnection, err: inout NSError?) -> Bool {
log.debug("Inserting bookmark in transaction on thread \(Thread.current)")
// Keep going if this returns true.
func change(_ sql: String, args: Args?, desc: String) -> Bool {
err = conn.executeChange(sql, withArgs: args)
if let err = err {
log.error(desc)
deferred.fillIfUnfilled(Maybe(failure: DatabaseError(err: err)))
return false
}
return true
}
let urlString = url.absoluteString
let newGUID = Bytes.generateGUID()
let now = Date.now()
let parentArgs: Args = [parent]
//// Insert the new bookmark and icon without touching structure.
var args: Args = [
newGUID,
BookmarkNodeType.bookmark.rawValue,
urlString,
title,
parent,
parentTitle,
Date.nowNumber(),
SyncStatus.new.rawValue,
]
let faviconID: Int?
// Insert the favicon.
if let icon = favicon {
faviconID = self.favicons.insertOrUpdate(conn, obj: icon)
} else {
faviconID = nil
}
log.debug("Inserting bookmark with GUID \(newGUID) and specified icon \(faviconID ??? "nil").")
// If the caller didn't provide an icon (and they usually don't!),
// do a reverse lookup in history. We use a view to make this simple.
let iconValue: String
if let faviconID = faviconID {
iconValue = "?"
args.append(faviconID )
} else {
iconValue = "(SELECT iconID FROM \(ViewIconForURL) WHERE url = ?)"
args.append(urlString )
}
let insertSQL = "INSERT INTO \(TableBookmarksLocal) " +
"(guid, type, bmkUri, title, parentid, parentName, local_modified, sync_status, faviconID) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, \(iconValue))"
if !change(insertSQL, args: args, desc: "Error inserting \(newGUID).") {
return false
}
let bumpParentStatus = { (status: Int) -> Bool in
let bumpSQL = "UPDATE \(TableBookmarksLocal) SET sync_status = \(status), local_modified = \(now) WHERE guid = ?"
return change(bumpSQL, args: parentArgs, desc: "Error bumping \(parent)'s modified time.")
}
func overrideParentMirror() -> Bool {
// We do this slightly tortured work so that we can reuse these queries
// in a different context.
let (sql, args) = getSQLToOverrideFolder(parent, atModifiedTime: now)
var generator = sql.makeIterator()
while let query = generator.next() {
if !change(query, args: args, desc: "Error running overriding query.") {
return false
}
}
return true
}
//// Make sure our parent is overridden and appropriately bumped.
// See discussion here: <https://github.com/mozilla/firefox-ios/commit/2041f1bbde430de29aefb803aae54ed26db47d23#commitcomment-14572312>
// Note that this isn't as obvious as you might think. We must:
let localStatusFactory: (SDRow) -> (Int, Bool) = { row in
let status = row["sync_status"] as! Int
let deleted = (row["is_deleted"] as! Int) != 0
return (status, deleted)
}
let overriddenFactory: (SDRow) -> Bool = { row in
row.getBoolean("is_overridden")
}
// TODO: these can be merged into a single query.
let mirrorStatusSQL = "SELECT is_overridden FROM \(TableBookmarksMirror) WHERE guid = ?"
let localStatusSQL = "SELECT sync_status, is_deleted FROM \(TableBookmarksLocal) WHERE guid = ?"
let mirrorStatus = conn.executeQuery(mirrorStatusSQL, factory: overriddenFactory, withArgs: parentArgs)[0]
let localStatus = conn.executeQuery(localStatusSQL, factory: localStatusFactory, withArgs: parentArgs)[0]
let parentExistsInMirror = mirrorStatus != nil
let parentExistsLocally = localStatus != nil
// * Figure out if we were already overridden. We only want to re-clone
// if we weren't.
if !parentExistsLocally {
if !parentExistsInMirror {
deferred.fillIfUnfilled(Maybe(failure: DatabaseError(description: "Folder \(parent) doesn't exist in either mirror or local.")))
return false
}
// * Mark the parent folder as overridden if necessary.
// Overriding the parent involves copying the parent's structure, so that
// we can amend it, but also the parent's row itself so that we know it's
// changed.
_ = overrideParentMirror()
} else {
let (status, deleted) = localStatus!
if deleted {
log.error("Trying to insert into deleted local folder.")
deferred.fillIfUnfilled(Maybe(failure: DatabaseError(description: "Local folder \(parent) is deleted.")))
return false
}
// * Bump the overridden parent's modified time. We already copied its
// structure and values, and if it's in the local table it'll either
// already be New or Changed.
if let syncStatus = SyncStatus(rawValue: status) {
switch syncStatus {
case .synced:
log.debug("We don't expect folders to ever be marked as Synced.")
if !bumpParentStatus(SyncStatus.changed.rawValue) {
return false
}
case .new:
fallthrough
case .changed:
// Leave it marked as new or changed, but bump the timestamp.
if !bumpParentStatus(syncStatus.rawValue) {
return false
}
}
} else {
log.warning("Local folder marked with unknown state \(status). This should never occur.")
if !bumpParentStatus(SyncStatus.changed.rawValue) {
return false
}
}
}
/// Add the new bookmark as a child in the modified local structure.
// We always append the new row: after insertion, the new item will have the largest index.
let newIndex = "(SELECT (COALESCE(MAX(idx), -1) + 1) AS newIndex FROM \(TableBookmarksLocalStructure) WHERE parent = ?)"
let structureSQL = "INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) " +
"VALUES (?, ?, \(newIndex))"
let structureArgs: Args = [parent, newGUID, parent]
if !change(structureSQL, args: structureArgs, desc: "Error adding new item \(newGUID) to local structure.") {
return false
}
log.debug("Returning true to commit transaction on thread \(Thread.current)")
/// Fill the deferred and commit the transaction.
deferred.fill(Maybe(success: ()))
return true
}
/**
* Assumption: the provided folder GUID exists in either the local table or the mirror table.
*/
func insertBookmark(_ url: URL, title: String, favicon: Favicon?, intoFolder parent: GUID, withTitle parentTitle: String) -> Success {
log.debug("Inserting bookmark task on thread \(Thread.current)")
let deferred = Success()
var error: NSError?
error = self.db.transaction(synchronous: false, err: &error) { (conn, err) -> Bool in
self.insertBookmarkInTransaction(deferred, url: url, title: title, favicon: favicon, intoFolder: parent, withTitle: parentTitle, conn: conn, err: &err)
}
log.debug("Returning deferred on thread \(Thread.current)")
return deferred
}
}
private extension BookmarkMirrorItem {
// Let's say the buffer structure table looks like this:
// ===============================
// | parent | child | idx |
// -------------------------------
// | aaaa | bbbb | 5 |
// | aaaa | cccc | 8 |
// | aaaa | dddd | 19 |
// ===============================
// And the self.children array has 5 children (2 new to insert).
// Then this function should be called with offset = 3 and nextIdx = 20
func getChildrenArgs(offset: Int = 0, nextIdx: Int = 0) -> [Args] {
// Only folders have children, and we manage roots ourselves.
if self.type != .folder ||
self.guid == BookmarkRoots.RootGUID {
return []
}
let parent = self.guid
var idx = nextIdx
return self.children?.suffix(from: offset).map { child in
let ret: Args = [parent, child, idx]
idx += 1
return ret
} ?? []
}
func getUpdateOrInsertArgs() -> Args {
let args: Args = [
self.type.rawValue ,
self.serverModified,
self.isDeleted ? 1 : 0 ,
self.hasDupe ? 1 : 0,
self.parentID,
self.parentName ?? "", // Workaround for dirty data before Bug 1318414.
self.feedURI,
self.siteURI,
self.pos,
self.title,
self.description,
self.bookmarkURI,
self.tags,
self.keyword,
self.folderName,
self.queryID,
self.guid,
]
return args
}
}
private func deleteStructureForGUIDs(_ guids: [GUID], fromTable table: String, connection: SQLiteDBConnection, withMaxVars maxVars: Int=BrowserDB.MaxVariableNumber) -> NSError? {
log.debug("Deleting \(guids.count) parents from \(table).")
let chunks = chunk(guids, by: maxVars)
for chunk in chunks {
let delStructure = "DELETE FROM \(table) WHERE parent IN \(BrowserDB.varlist(chunk.count))"
let args: Args = chunk.flatMap { $0 }
if let error = connection.executeChange(delStructure, withArgs: args) {
log.error("Updating structure: \(error.description).")
return error
}
}
return nil
}
private func insertStructureIntoTable(_ table: String, connection: SQLiteDBConnection, children: [Args], maxVars: Int) -> NSError? {
if children.isEmpty {
return nil
}
// Insert the new structure rows. This uses three vars per row.
let maxRowsPerInsert: Int = maxVars / 3
let chunks = chunk(children, by: maxRowsPerInsert)
for chunk in chunks {
log.verbose("Inserting \(chunk.count)…")
let childArgs: Args = chunk.flatMap { $0 } // Flatten [[a, b, c], [...]] into [a, b, c, ...].
let ins = "INSERT INTO \(table) (parent, child, idx) VALUES " +
Array<String>(repeating: "(?, ?, ?)", count: chunk.count).joined(separator: ", ")
log.debug("Inserting \(chunk.count) records (out of \(children.count)).")
if let error = connection.executeChange(ins, withArgs: childArgs) {
return error
}
}
return nil
}
/**
* This stores incoming records in a buffer.
* When appropriate, the buffer is merged with the mirror and local storage
* in the DB.
*/
open class SQLiteBookmarkBufferStorage: BookmarkBufferStorage {
let db: BrowserDB
public init(db: BrowserDB) {
self.db = db
}
open func synchronousBufferCount() -> Int? {
return self.db.runQuery("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", args: nil, factory: IntFactory).value.successValue?[0]
}
/**
* Remove child records for any folders that've been deleted or are empty.
*/
fileprivate func deleteChildrenInTransactionWithGUIDs(_ guids: [GUID], connection: SQLiteDBConnection, withMaxVars maxVars: Int=BrowserDB.MaxVariableNumber) -> NSError? {
return deleteStructureForGUIDs(guids, fromTable: TableBookmarksBufferStructure, connection: connection, withMaxVars: maxVars)
}
open func isEmpty() -> Deferred<Maybe<Bool>> {
return self.db.queryReturnsNoResults("SELECT 1 FROM \(TableBookmarksBuffer)")
}
/**
* This is a little gnarly because our DB access layer is rough.
* Within a single transaction, we walk the list of items, attempting to update
* and inserting if the update failed. (TODO: batch the inserts!)
* Once we've added all of the records, we flatten all of their children
* into big arg lists and hard-update the structure table.
*/
open func applyRecords(_ records: [BookmarkMirrorItem]) -> Success {
return self.applyRecords(records, withMaxVars: BrowserDB.MaxVariableNumber)
}
open func applyRecords(_ records: [BookmarkMirrorItem], withMaxVars maxVars: Int) -> Success {
let deferred = Deferred<Maybe<()>>(defaultQueue: DispatchQueue.main)
let guids = records.map { $0.guid }
let deleted = records.filter { $0.isDeleted }.map { $0.guid }
let values = records.map { $0.getUpdateOrInsertArgs() }
let children = records.filter { !$0.isDeleted }.flatMap { $0.getChildrenArgs() }
let folders = records.filter { $0.type == BookmarkNodeType.folder }.map { $0.guid }
var err: NSError?
_ = self.db.transaction(&err) { (conn, err) -> Bool in
// These have the same values in the same order.
let update =
"UPDATE \(TableBookmarksBuffer) SET " +
"type = ?, server_modified = ?, is_deleted = ?, " +
"hasDupe = ?, parentid = ?, parentName = ?, " +
"feedUri = ?, siteUri = ?, pos = ?, title = ?, " +
"description = ?, bmkUri = ?, tags = ?, keyword = ?, " +
"folderName = ?, queryId = ? " +
"WHERE guid = ?"
// We used to use INSERT OR IGNORE here, but it muffles legitimate errors. The only
// real use for that is/was to catch duplicates, but the UPDATE we run first should
// serve that purpose just as well.
let insert =
"INSERT INTO \(TableBookmarksBuffer) " +
"(type, server_modified, is_deleted, hasDupe, parentid, parentName, " +
"feedUri, siteUri, pos, title, description, bmkUri, tags, keyword, folderName, queryId, guid) " +
"VALUES " +
"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
for args in values {
if let error = conn.executeChange(update, withArgs: args) {
log.error("Updating mirror in buffer: \(error.description).")
err = error
deferred.fill(Maybe(failure: DatabaseError(err: error)))
return false
}
if conn.numberOfRowsModified > 0 {
continue
}
if let error = conn.executeChange(insert, withArgs: args) {
log.error("Inserting mirror into buffer: \(error.description).")
err = error
deferred.fill(Maybe(failure: DatabaseError(err: error)))
return false
}
}
// Delete existing structure for any folders we've seen. We always trust the folders,
// not the children's parent pointers, so we do this here: we'll insert their current
// children right after, when we process the child structure rows.
// We only drop the child structure for deleted folders, not the record itself.
// Deleted records stay in the buffer table so that we know about the deletion
// when we do a real sync!
log.debug("\(folders.count) folders and \(deleted.count) deleted maybe-folders to drop from buffer structure table.")
if let error = self.deleteChildrenInTransactionWithGUIDs(folders + deleted, connection: conn) {
deferred.fill(Maybe(failure: DatabaseError(err: error)))
return false
}
// (Re-)insert children in chunks.
log.debug("Inserting \(children.count) children.")
if let error = insertStructureIntoTable(TableBookmarksBufferStructure, connection: conn, children: children, maxVars: maxVars) {
log.error("Updating buffer structure: \(error.description).")
err = error
deferred.fill(Maybe(failure: DatabaseError(err: error)))
return false
}
// Drop pending deletions of items we just received.
// In practice that means we have made the choice that we will always
// discard local deletions if there was a modification or a deletion made remotely.
log.debug("Deleting \(guids.count) pending deletions.")
let chunks = chunk(guids, by: BrowserDB.MaxVariableNumber)
for chunk in chunks {
let delPendingDeletions = "DELETE FROM \(TablePendingBookmarksDeletions) WHERE id IN \(BrowserDB.varlist(chunk.count))"
let args: Args = chunk.flatMap { $0 }
if let error = conn.executeChange(delPendingDeletions, withArgs: args) {
log.error("Deleting pending deletions: \(error.description).")
err = error
deferred.fill(Maybe(failure: DatabaseError(err: error)))
return false
}
}
if err == nil {
deferred.fillIfUnfilled(Maybe(success: ()))
return true
}
deferred.fillIfUnfilled(Maybe(failure: DatabaseError(err: err)))
return false
}
return deferred
}
open func doneApplyingRecordsAfterDownload() -> Success {
self.db.checkpoint()
return succeed()
}
}
extension SQLiteBookmarkBufferStorage: BufferItemSource {
public func getBufferItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> {
return self.db.getMirrorItemFromTable(TableBookmarksBuffer, guid: guid)
}
public func getBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID {
return self.db.getMirrorItemsFromTable(TableBookmarksBuffer, guids: guids)
}
public func getBufferChildrenGUIDsForParent(_ guid: GUID) -> Deferred<Maybe<[GUID]>> {
return self.getChildrenGUIDsOf(guid)
}
public func prefetchBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID {
log.debug("Not implemented.")
return succeed()
}
}
extension BrowserDB {
fileprivate func getMirrorItemFromTable(_ table: String, guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> {
let args: Args = [guid]
let sql = "SELECT * FROM \(table) WHERE guid = ?"
return self.runQuery(sql, args: args, factory: BookmarkFactory.mirrorItemFactory)
>>== { cursor in
guard let item = cursor[0] else {
return deferMaybe(DatabaseError(description: "Expected to find \(guid) in \(table) but did not."))
}
return deferMaybe(item)
}
}
fileprivate func getMirrorItemsFromTable<T: Collection>(_ table: String, guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID {
var acc: [GUID: BookmarkMirrorItem] = [:]
func accumulate(_ args: Args) -> Success {
let sql = "SELECT * FROM \(table) WHERE guid IN \(BrowserDB.varlist(args.count))"
return self.runQuery(sql, args: args, factory: BookmarkFactory.mirrorItemFactory)
>>== { cursor in
cursor.forEach { row in
guard let row = row else { return } // Oh, Cursor.
acc[row.guid] = row
}
return succeed()
}
}
let args: Args = guids.map { $0 }
if args.count < BrowserDB.MaxVariableNumber {
return accumulate(args) >>> { deferMaybe(acc) }
}
let chunks = chunk(args, by: BrowserDB.MaxVariableNumber)
return walk(chunks.lazy.map { Array($0) }, f: accumulate)
>>> { deferMaybe(acc) }
}
}
extension MergedSQLiteBookmarks: BookmarkBufferStorage {
public func synchronousBufferCount() -> Int? {
return self.buffer.synchronousBufferCount()
}
public func isEmpty() -> Deferred<Maybe<Bool>> {
return self.buffer.isEmpty()
}
public func applyRecords(_ records: [BookmarkMirrorItem]) -> Success {
return self.buffer.applyRecords(records)
}
public func doneApplyingRecordsAfterDownload() -> Success {
// It doesn't really matter which one we checkpoint -- they're both backed by the same DB.
return self.buffer.doneApplyingRecordsAfterDownload()
}
public func validate() -> Success {
return self.buffer.validate()
}
public func getBufferedDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> {
return self.buffer.getBufferedDeletions()
}
public func applyBufferCompletionOp(_ op: BufferCompletionOp, itemSources: ItemSources) -> Success {
return self.buffer.applyBufferCompletionOp(op, itemSources: itemSources)
}
}
extension MergedSQLiteBookmarks: BufferItemSource {
public func getBufferItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> {
return self.buffer.getBufferItemWithGUID(guid)
}
public func getBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID {
return self.buffer.getBufferItemsWithGUIDs(guids)
}
public func getBufferChildrenGUIDsForParent(_ guid: GUID) -> Deferred<Maybe<[GUID]>> {
return self.buffer.getChildrenGUIDsOf(guid)
}
public func prefetchBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID {
return self.buffer.prefetchBufferItemsWithGUIDs(guids)
}
}
extension MergedSQLiteBookmarks: MirrorItemSource {
public func getMirrorItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> {
return self.local.getMirrorItemWithGUID(guid)
}
public func getMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID {
return self.local.getMirrorItemsWithGUIDs(guids)
}
public func prefetchMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID {
return self.local.prefetchMirrorItemsWithGUIDs(guids)
}
}
extension MergedSQLiteBookmarks: LocalItemSource {
public func getLocalItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> {
return self.local.getLocalItemWithGUID(guid)
}
public func getLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID {
return self.local.getLocalItemsWithGUIDs(guids)
}
public func prefetchLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID {
return self.local.prefetchLocalItemsWithGUIDs(guids)
}
}
extension MergedSQLiteBookmarks: ShareToDestination {
public func shareItem(_ item: ShareItem) -> Success {
return self.local.shareItem(item)
}
}
// Not actually implementing SyncableBookmarks, just a utility for MergedSQLiteBookmarks to do so.
extension SQLiteBookmarks {
public func isUnchanged() -> Deferred<Maybe<Bool>> {
return self.db.queryReturnsNoResults("SELECT 1 FROM \(TableBookmarksLocal)")
}
// Retrieve all the local bookmarks that are not present remotely in order to avoid merge logic later.
public func getLocalBookmarksModifications(limit: Int) -> Deferred<Maybe<(deletions: [GUID], additions: [BookmarkMirrorItem])>> {
let deletionsQuery =
"SELECT id FROM \(TablePendingBookmarksDeletions) " +
"LIMIT ?"
let deletionsArgs: Args = [limit]
return db.runQuery(deletionsQuery, args: deletionsArgs, factory: StringFactory) >>== {
let deletedGUIDs = $0.asArray()
let newLimit = limit - deletedGUIDs.count
let additionsQuery =
"SELECT * FROM \(TableBookmarksLocal) AS bookmarks " +
"WHERE type = \(BookmarkNodeType.bookmark.rawValue) AND sync_status = \(SyncStatus.new.rawValue) AND parentID = ? " +
"AND NOT EXISTS (SELECT 1 FROM \(TableBookmarksBuffer) buf WHERE buf.guid = bookmarks.guid) " +
"LIMIT ?"
let additionsArgs: Args = [BookmarkRoots.MobileFolderGUID, newLimit]
return self.db.runQuery(additionsQuery, args: additionsArgs, factory: BookmarkFactory.mirrorItemFactory) >>== {
return deferMaybe((deletedGUIDs, $0.asArray()))
}
}
}
public func getLocalDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> {
let sql =
"SELECT guid, local_modified FROM \(TableBookmarksLocal) " +
"WHERE is_deleted = 1"
return self.db.runQuery(sql, args: nil, factory: { ($0["guid"] as! GUID, $0.getTimestamp("local_modified")!) })
>>== { deferMaybe($0.asArray()) }
}
}
extension MergedSQLiteBookmarks: SyncableBookmarks {
public func isUnchanged() -> Deferred<Maybe<Bool>> {
return self.local.isUnchanged()
}
public func getLocalBookmarksModifications(limit: Int) -> Deferred<Maybe<(deletions: [GUID], additions: [BookmarkMirrorItem])>> {
return self.local.getLocalBookmarksModifications(limit: limit)
}
public func getLocalDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> {
return self.local.getLocalDeletions()
}
public func treeForMirror() -> Deferred<Maybe<BookmarkTree>> {
return self.local.treeForMirror()
}
public func treesForEdges() -> Deferred<Maybe<(local: BookmarkTree, buffer: BookmarkTree)>> {
return self.local.treeForLocal() >>== { local in
return self.local.treeForBuffer() >>== { buffer in
return deferMaybe((local: local, buffer: buffer))
}
}
}
}
// MARK: - Validation of buffer contents.
// Note that these queries tend to not have exceptions for deletions.
// That's because a record can't be deleted in isolation -- if it's
// deleted its parent should be changed, too -- and so our views will
// correctly reflect that. We'll have updated rows in the structure table,
// and updated values -- and thus a complete override -- for the parent and
// the deleted child.
private let allBufferStructuresReferToRecords = [
"SELECT s.child AS pointee, s.parent AS pointer FROM",
ViewBookmarksBufferStructureOnMirror,
"s LEFT JOIN",
ViewBookmarksBufferOnMirror,
"b ON b.guid = s.child WHERE b.guid IS NULL",
].joined(separator: " ")
private let allNonDeletedBufferRecordsAreInStructure = [
"SELECT b.guid AS missing, b.parentid AS parent FROM",
ViewBookmarksBufferOnMirror, "b LEFT JOIN",
ViewBookmarksBufferStructureOnMirror,
"s ON b.guid = s.child WHERE s.child IS NULL AND",
"b.is_deleted IS 0 AND b.parentid IS NOT '\(BookmarkRoots.RootGUID)'",
].joined(separator: " ")
private let allRecordsAreChildrenOnce = [
"SELECT s.child FROM",
ViewBookmarksBufferStructureOnMirror,
"s INNER JOIN (",
"SELECT child, COUNT(*) AS dupes FROM", ViewBookmarksBufferStructureOnMirror,
"GROUP BY child HAVING dupes > 1",
") i ON s.child = i.child",
].joined(separator: " ")
private let bufferParentidMatchesStructure = [
"SELECT b.guid, b.parentid, s.parent, s.child, s.idx FROM",
TableBookmarksBuffer, "b JOIN", TableBookmarksBufferStructure,
"s ON b.guid = s.child WHERE b.parentid IS NOT s.parent",
].joined(separator: " ")
public enum BufferInconsistency {
case missingValues
case missingStructure
case overlappingStructure
case parentIDDisagreement
public var query: String {
switch self {
case .missingValues:
return allBufferStructuresReferToRecords
case .missingStructure:
return allNonDeletedBufferRecordsAreInStructure
case .overlappingStructure:
return allRecordsAreChildrenOnce
case .parentIDDisagreement:
return bufferParentidMatchesStructure
}
}
public var trackingEvent: String {
switch self {
case .missingValues:
return "missingvalues"
case .missingStructure:
return "missingstructure"
case .overlappingStructure:
return "overlappingstructure"
case .parentIDDisagreement:
return "parentiddisagreement"
}
}
public var description: String {
switch self {
case .missingValues:
return "Not all buffer structures refer to records."
case .missingStructure:
return "Not all buffer records are in structure."
case .overlappingStructure:
return "Some buffer structures refer to the same records."
case .parentIDDisagreement:
return "Some buffer record parent IDs don't match structure."
}
}
var idsFactory: (SDRow) -> [String] {
switch self {
case .missingValues:
return self.getConcernedIDs(colNames: ["pointee", "pointer"])
case .missingStructure:
return self.getConcernedIDs(colNames: ["missing", "parent"])
case .overlappingStructure:
return self.getConcernedIDs(colNames: ["child"])
case .parentIDDisagreement:
return self.getConcernedIDs(colNames: ["guid", "parentid", "parent", "child"])
}
}
private func getConcernedIDs(colNames: [String]) -> ((SDRow) -> [String]) {
return { (row: SDRow) in
colNames.flatMap({ row[$0] as? String})
}
}
public static let all: [BufferInconsistency] = [.missingValues, .missingStructure, .overlappingStructure, .parentIDDisagreement]
}
public struct BufferInvalidError: MaybeErrorType {
public let description = "Bookmarks buffer contains invalid data"
public let inconsistencies: [BufferInconsistency: [GUID]]
public let validationDuration: Int64
public init(inconsistencies: [BufferInconsistency: [GUID]], validationDuration: Int64) {
self.inconsistencies = inconsistencies
self.validationDuration = validationDuration
}
}
extension SQLiteBookmarkBufferStorage {
public func validate() -> Success {
func idsFor(inconsistency inc: BufferInconsistency) -> () -> Deferred<Maybe<(type: BufferInconsistency, ids: [String])>> {
return {
self.db.runQuery(inc.query, args: nil, factory: inc.idsFactory)
>>== { deferMaybe((type: inc, ids: $0.asArray().reduce([], +))) }
}
}
let start = Date.now()
let ops = BufferInconsistency.all.map { idsFor(inconsistency: $0) }
return accumulate(ops) >>== { results in
var inconsistencies = [BufferInconsistency: [GUID]]()
results.forEach { type, ids in
guard !ids.isEmpty else { return }
inconsistencies[type] = ids
}
return inconsistencies.isEmpty ? succeed() :
deferMaybe(BufferInvalidError(inconsistencies: inconsistencies, validationDuration: Int64(Date.now() - start)))
}
}
public func getBufferedDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> {
let sql =
"SELECT guid, server_modified FROM \(TableBookmarksBuffer) " +
"WHERE is_deleted = 1"
return self.db.runQuery(sql, args: nil, factory: { ($0["guid"] as! GUID, $0.getTimestamp("server_modified")!) })
>>== { deferMaybe($0.asArray()) }
}
}
extension SQLiteBookmarks {
fileprivate func structureQueryForTable(_ table: String, structure: String) -> String {
// We use a subquery so we get back rows for overridden folders, even when their
// children aren't in the shadowing table.
let sql =
"SELECT s.parent AS parent, s.child AS child, COALESCE(m.type, -1) AS type " +
"FROM \(structure) s LEFT JOIN \(table) m ON s.child = m.guid AND m.is_deleted IS NOT 1 " +
"ORDER BY s.parent, s.idx ASC"
return sql
}
fileprivate func remainderQueryForTable(_ table: String, structure: String) -> String {
// This gives us value rows that aren't children of a folder.
// You might notice that these complementary LEFT JOINs are how you
// express a FULL OUTER JOIN in sqlite.
// We exclude folders here because if they have children, they'll appear
// in the structure query, and if they don't, they'll appear in the bottom
// half of this query.
let sql =
"SELECT m.guid AS guid, m.type AS type " +
"FROM \(table) m LEFT JOIN \(structure) s ON s.child = m.guid " +
"WHERE m.is_deleted IS NOT 1 AND m.type IS NOT \(BookmarkNodeType.folder.rawValue) AND s.child IS NULL " +
"UNION ALL " +
// This gives us folders with no children.
"SELECT m.guid AS guid, m.type AS type " +
"FROM \(table) m LEFT JOIN \(structure) s ON s.parent = m.guid " +
"WHERE m.is_deleted IS NOT 1 AND m.type IS \(BookmarkNodeType.folder.rawValue) AND s.parent IS NULL "
return sql
}
fileprivate func statusQueryForTable(_ table: String) -> String {
return "SELECT guid, is_deleted FROM \(table)"
}
fileprivate func treeForTable(_ table: String, structure: String, alwaysIncludeRoots includeRoots: Bool) -> Deferred<Maybe<BookmarkTree>> {
// The structure query doesn't give us non-structural rows -- that is, if you
// make a value-only change to a record, and it's not otherwise mentioned by
// way of being a child of a structurally modified folder, it won't appear here at all.
// It also doesn't give us empty folders, because they have no children.
// We run a separate query to get those.
let structureSQL = self.structureQueryForTable(table, structure: structure)
let remainderSQL = self.remainderQueryForTable(table, structure: structure)
let statusSQL = self.statusQueryForTable(table)
func structureFactory(_ row: SDRow) -> StructureRow {
let typeCode = row["type"] as! Int
let type = BookmarkNodeType(rawValue: typeCode) // nil if typeCode is invalid (e.g., -1).
return (parent: row["parent"] as! GUID, child: row["child"] as! GUID, type: type)
}
func nonStructureFactory(_ row: SDRow) -> BookmarkTreeNode {
let guid = row["guid"] as! GUID
let typeCode = row["type"] as! Int
if let type = BookmarkNodeType(rawValue: typeCode) {
switch type {
case .folder:
return BookmarkTreeNode.folder(guid: guid, children: [])
default:
return BookmarkTreeNode.nonFolder(guid: guid)
}
} else {
return BookmarkTreeNode.unknown(guid: guid)
}
}
func statusFactory(_ row: SDRow) -> (GUID, Bool) {
return (row["guid"] as! GUID, row.getBoolean("is_deleted"))
}
return self.db.runQuery(statusSQL, args: nil, factory: statusFactory)
>>== { cursor in
var deleted = Set<GUID>()
var modified = Set<GUID>()
cursor.forEach { pair in
let (guid, del) = pair! // Oh, cursor.
if del {
deleted.insert(guid)
} else {
modified.insert(guid)
}
}
return self.db.runQuery(remainderSQL, args: nil, factory: nonStructureFactory)
>>== { cursor in
let nonFoldersAndEmptyFolders = cursor.asArray()
return self.db.runQuery(structureSQL, args: nil, factory: structureFactory)
>>== { cursor in
let structureRows = cursor.asArray()
let tree = BookmarkTree.mappingsToTreeForStructureRows(structureRows, withNonFoldersAndEmptyFolders: nonFoldersAndEmptyFolders, withDeletedRecords: deleted, modifiedRecords: modified, alwaysIncludeRoots: includeRoots)
return deferMaybe(tree)
}
}
}
}
public func treeForMirror() -> Deferred<Maybe<BookmarkTree>> {
return self.treeForTable(TableBookmarksMirror, structure: TableBookmarksMirrorStructure, alwaysIncludeRoots: true)
}
public func treeForBuffer() -> Deferred<Maybe<BookmarkTree>> {
return self.treeForTable(TableBookmarksBuffer, structure: TableBookmarksBufferStructure, alwaysIncludeRoots: false)
}
public func treeForLocal() -> Deferred<Maybe<BookmarkTree>> {
return self.treeForTable(TableBookmarksLocal, structure: TableBookmarksLocalStructure, alwaysIncludeRoots: false)
}
}
// MARK: - Applying merge operations.
public extension SQLiteBookmarkBufferStorage {
public func applyBufferCompletionOp(_ op: BufferCompletionOp, itemSources: ItemSources) -> Success {
log.debug("Marking buffer rows as applied.")
if op.isNoOp {
log.debug("Nothing to do.")
return succeed()
}
var queries: [(sql: String, args: Args?)] = []
op.processedBufferChanges.subsetsOfSize(BrowserDB.MaxVariableNumber).forEach { guids in
let varlist = BrowserDB.varlist(guids.count)
let args: Args = guids.map { $0 }
queries.append((sql: "DELETE FROM \(TableBookmarksBufferStructure) WHERE parent IN \(varlist)", args: args))
queries.append((sql: "DELETE FROM \(TableBookmarksBuffer) WHERE guid IN \(varlist)", args: args))
}
return self.db.run(queries)
}
public func getChildrenGUIDsOf(_ guid: GUID) -> Deferred<Maybe<[GUID]>> {
let sql = "SELECT child FROM \(TableBookmarksBufferStructure) WHERE parent = ? ORDER BY idx ASC"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: StringFactory) >>== { deferMaybe($0.asArray()) }
}
}
extension MergedSQLiteBookmarks {
public func applyLocalOverrideCompletionOp(_ op: LocalOverrideCompletionOp, itemSources: ItemSources) -> Success {
log.debug("Applying local op to merged.")
if op.isNoOp {
log.debug("Nothing to do.")
return succeed()
}
let deferred = Success()
var err: NSError?
let resultError = self.local.db.transaction(&err) { (conn, err: inout NSError?) in
// This is a little tortured because we want it all to happen in a single transaction.
// We walk through the accrued work items, applying them in the right order (e.g., structure
// then value), doing so with the ugly NSError-based transaction API.
// If at any point we fail, we abort, roll back the transaction (return false),
// and reject the deferred.
func change(_ sql: String, args: Args?=nil) -> Bool {
if let e = conn.executeChange(sql, withArgs: args) {
err = e
deferred.fillIfUnfilled(Maybe(failure: DatabaseError(err: e)))
return false
}
return true
}
// So we can trample the DB in any order.
if !change("PRAGMA defer_foreign_keys = ON") {
return false
}
log.debug("Deleting \(op.mirrorItemsToDelete.count) mirror items.")
op.mirrorItemsToDelete
.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in
guard err == nil else { return }
let args: Args = guids.map { $0 }
let varlist = BrowserDB.varlist(guids.count)
let sqlMirrorStructure = "DELETE FROM \(TableBookmarksMirrorStructure) WHERE parent IN \(varlist)"
if !change(sqlMirrorStructure, args: args) {
return
}
let sqlMirror = "DELETE FROM \(TableBookmarksMirror) WHERE guid IN \(varlist)"
_ = change(sqlMirror, args: args)
}
if err != nil {
return false
}
// Copy from other tables for simplicity.
// Do this *before* we throw away local and buffer changes!
// This is one reason why the local override step needs to be processed before the buffer is cleared.
op.mirrorValuesToCopyFromBuffer
.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in
let args: Args = guids.map { $0 }
let varlist = BrowserDB.varlist(guids.count)
let copySQL = [
"INSERT OR REPLACE INTO \(TableBookmarksMirror)",
"(guid, type, parentid, parentName, feedUri, siteUri, pos, title, description,",
"bmkUri, tags, keyword, folderName, queryId, server_modified)",
"SELECT guid, type, parentid, parentName, feedUri, siteUri, pos, title, description,",
"bmkUri, tags, keyword, folderName, queryId, server_modified",
"FROM \(TableBookmarksBuffer)",
"WHERE guid IN",
varlist
].joined(separator: " ")
_ = change(copySQL, args: args)
}
if err != nil {
return false
}
op.mirrorValuesToCopyFromLocal
.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in
let args: Args = guids.map { $0 }
let varlist = BrowserDB.varlist(guids.count)
let copySQL = [
"INSERT OR REPLACE INTO \(TableBookmarksMirror)",
"(guid, type, parentid, parentName, feedUri, siteUri, pos, title, description,",
"bmkUri, tags, keyword, folderName, queryId, faviconID, server_modified)",
"SELECT guid, type, parentid, parentName, feedUri, siteUri, pos, title, description,",
"bmkUri, tags, keyword, folderName, queryId, faviconID,",
// This will be fixed up in batches after the initial copy.
"0 AS server_modified",
"FROM \(TableBookmarksLocal) WHERE guid IN",
varlist
].joined(separator: " ")
_ = change(copySQL, args: args)
}
op.modifiedTimes.forEach { (time, guids) in
if err != nil { return }
// This will never be too big: we upload in chunks
// smaller than 999!
precondition(guids.count < BrowserDB.MaxVariableNumber)
log.debug("Swizzling server modified time to \(time) for \(guids.count) GUIDs.")
let args: Args = guids.map { $0 }
let varlist = BrowserDB.varlist(guids.count)
let updateSQL = [
"UPDATE \(TableBookmarksMirror) SET server_modified = \(time)",
"WHERE guid IN",
varlist,
].joined(separator: " ")
_ = change(updateSQL, args: args)
}
if err != nil {
return false
}
log.debug("Marking \(op.processedLocalChanges.count) local changes as processed.")
op.processedLocalChanges
.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in
guard err == nil else { return }
let args: Args = guids.map { $0 }
let varlist = BrowserDB.varlist(guids.count)
let sqlLocalStructure = "DELETE FROM \(TableBookmarksLocalStructure) WHERE parent IN \(varlist)"
if !change(sqlLocalStructure, args: args) {
return
}
let sqlLocal = "DELETE FROM \(TableBookmarksLocal) WHERE guid IN \(varlist)"
if !change(sqlLocal, args: args) {
return
}
// If the values change, we'll handle those elsewhere, but at least we need to mark these as non-overridden.
let sqlMirrorOverride = "UPDATE \(TableBookmarksMirror) SET is_overridden = 0 WHERE guid IN \(varlist)"
_ = change(sqlMirrorOverride, args: args)
}
if err != nil {
return false
}
if !op.mirrorItemsToUpdate.isEmpty {
let updateSQL = [
"UPDATE \(TableBookmarksMirror) SET",
"type = ?, server_modified = ?, is_deleted = ?,",
"hasDupe = ?, parentid = ?, parentName = ?,",
"feedUri = ?, siteUri = ?, pos = ?, title = ?,",
"description = ?, bmkUri = ?, tags = ?, keyword = ?,",
"folderName = ?, queryId = ?, is_overridden = 0",
"WHERE guid = ?",
].joined(separator: " ")
op.mirrorItemsToUpdate.forEach { (_, mirrorItem) in
// Break out of the loop if we failed.
guard err == nil else { return }
let args = mirrorItem.getUpdateOrInsertArgs()
_ = change(updateSQL, args: args)
}
if err != nil {
return false
}
}
if !op.mirrorItemsToInsert.isEmpty {
let insertSQL = [
"INSERT OR IGNORE INTO \(TableBookmarksMirror) (",
"type, server_modified, is_deleted,",
"hasDupe, parentid, parentName,",
"feedUri, siteUri, pos, title,",
"description, bmkUri, tags, keyword,",
"folderName, queryId, guid",
"VALUES",
"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
].joined(separator: " ")
op.mirrorItemsToInsert.forEach { (_, mirrorItem) in
// Break out of the loop if we failed.
guard err == nil else { return }
let args = mirrorItem.getUpdateOrInsertArgs()
_ = change(insertSQL, args: args)
}
if err != nil {
return false
}
}
if !op.mirrorStructures.isEmpty {
let structureRows =
op.mirrorStructures.flatMap { (parent, children) in
return children.enumerated().map { (idx, child) -> Args in
let vals: Args = [parent, child, idx]
return vals
}
}
let parents = op.mirrorStructures.map { $0.0 }
if let e = deleteStructureForGUIDs(parents, fromTable: TableBookmarksMirrorStructure, connection: conn) {
err = e
deferred.fill(Maybe(failure: DatabaseError(err: err)))
return false
}
if let e = insertStructureIntoTable(TableBookmarksMirrorStructure, connection: conn, children: structureRows, maxVars: BrowserDB.MaxVariableNumber) {
err = e
deferred.fill(Maybe(failure: DatabaseError(err: err)))
return false
}
}
// Commit the result.
return true
}
if let err = resultError {
log.warning("Got error “\(err.localizedDescription)”")
deferred.fillIfUnfilled(Maybe(failure: DatabaseError(err: err)))
} else {
deferred.fillIfUnfilled(Maybe(success: ()))
}
return deferred
}
public func applyBufferUpdatedCompletionOp(_ op: BufferUpdatedCompletionOp) -> Success {
log.debug("Applying buffer updates.")
if op.isNoOp {
log.debug("Nothing to do.")
return succeed()
}
let deferred = Success()
var err: NSError?
let resultError = self.local.db.transaction(&err) { (conn, err: inout NSError?) in
func change(_ sql: String, args: Args?=nil) -> Bool {
if let e = conn.executeChange(sql, withArgs: args) {
err = e
deferred.fillIfUnfilled(Maybe(failure: DatabaseError(err: e)))
return false
}
return true
}
// So we can trample the DB in any order.
if !change("PRAGMA defer_foreign_keys = ON") {
return false
}
op.deletedValues
.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in
guard err == nil else { return }
let args: Args = guids.map { $0 }
let varlist = BrowserDB.varlist(guids.count)
// This will leave the idx column sparse for the buffer children.
let sqlBufferStructure = "DELETE FROM \(TableBookmarksBufferStructure) WHERE child IN \(varlist)"
if !change(sqlBufferStructure, args: args) {
return
}
// This will also delete items from the pending deletions table on cascade.
let sqlBuffer = "DELETE FROM \(TableBookmarksBuffer) WHERE guid IN \(varlist)"
if !change(sqlBuffer, args: args) {
return
}
}
if err != nil {
return false
}
let insertSQL = [
"INSERT OR IGNORE INTO \(TableBookmarksBuffer) (",
"type, server_modified, is_deleted,",
"hasDupe, parentid, parentName,",
"feedUri, siteUri, pos, title,",
"description, bmkUri, tags, keyword,",
"folderName, queryId, guid)",
"VALUES",
"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
].joined(separator: " ")
let args = op.mobileRoot.getUpdateOrInsertArgs()
_ = change(insertSQL, args: args)
if err != nil {
return false
}
// We update server_modified in another operation because the first statement is an INSERT OR IGNORE
// and we can't turn that into a INSERT OR REPLACE because this will cascade delete children
// in the buffer structure table.
let updateMobileRootTimeSQL = [
"UPDATE \(TableBookmarksBuffer) SET server_modified = \(op.modifiedTime)",
"WHERE guid = ?",
].joined(separator: " ")
_ = change(updateMobileRootTimeSQL, args: [op.mobileRoot.guid])
if err != nil {
return false
}
op.bufferValuesToMoveFromLocal
.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in
let args: Args = guids.map { $0 }
let varlist = BrowserDB.varlist(guids.count)
let copySQL = [
"INSERT OR REPLACE INTO \(TableBookmarksBuffer)",
"(guid, type, parentid, parentName, feedUri, siteUri, pos, title, description,",
"bmkUri, tags, keyword, folderName, queryId, server_modified)",
"SELECT guid, type, parentid, parentName, feedUri, siteUri, pos, title, description,",
"bmkUri, tags, keyword, folderName, queryId,",
"\(op.modifiedTime) AS server_modified",
"FROM \(TableBookmarksLocal) WHERE guid IN",
varlist
].joined(separator: " ")
if !change(copySQL, args: args) {
return
}
}
if err != nil {
return false
}
op.bufferValuesToMoveFromLocal
.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in
guard err == nil else { return }
let args: Args = guids.map { $0 }
let varlist = BrowserDB.varlist(guids.count)
// This will leave the idx column sparse for the local children.
let sqlLocalStructure = "DELETE FROM \(TableBookmarksLocalStructure) WHERE child IN \(varlist)"
if !change(sqlLocalStructure, args: args) {
return
}
let sqlLocal = "DELETE FROM \(TableBookmarksLocal) WHERE guid IN \(varlist)"
if !change(sqlLocal, args: args) {
return
}
}
if err != nil {
return false
}
if op.bufferValuesToMoveFromLocal.count > 0 {
guard let allChildren = op.mobileRoot.children else {
log.error("Absent mobileRoot children. Aborting.")
return false
}
let offset = allChildren.count - op.bufferValuesToMoveFromLocal.count
let sqlNextIdx = "SELECT (COALESCE(MAX(idx), -1) + 1) AS newIndex FROM \(TableBookmarksBufferStructure) WHERE parent = ?"
let nextIdxArgs: Args = [BookmarkRoots.MobileFolderGUID]
let nextIdx = conn.executeQuery(sqlNextIdx, factory: IntFactory, withArgs: nextIdxArgs).asArray()[0]
let toInsertArgs = Array(op.mobileRoot.getChildrenArgs(offset: offset, nextIdx: nextIdx))
if let e = insertStructureIntoTable(TableBookmarksBufferStructure, connection: conn, children: toInsertArgs, maxVars: BrowserDB.MaxVariableNumber) {
err = e
deferred.fill(Maybe(failure: DatabaseError(err: err)))
return false
}
}
if err != nil {
return false
}
// Commit the result.
return true
}
if let err = resultError {
log.warning("Got error “\(err.localizedDescription)”")
deferred.fillIfUnfilled(Maybe(failure: DatabaseError(err: err)))
} else {
deferred.fillIfUnfilled(Maybe(success: ()))
}
return deferred
}
}
| mpl-2.0 | c4b792727a72b306d7d85d1a6644dfad | 41.870175 | 249 | 0.585235 | 4.972731 | false | false | false | false |
Rahulclaritaz/rahul | ixprez/ixprez/XPMyUploadViewController.swift | 1 | 35879 | //
// XPMyUploadViewController.swift
// ixprez
//
// Created by Quad on 5/17/17.
// Copyright © 2017 Claritaz Techlabs. All rights reserved.
//
import UIKit
class XPMyUploadViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
{
@IBOutlet weak var segmentationController: UISegmentedControl!
@IBOutlet weak var myUploadCollectionView: UICollectionView!
var isFromMenu : Bool!
var screenSize : CGRect!
var screenWidth : CGFloat!
var screenHeight : CGFloat!
var getUploadData = MyUploadWebServices()
var getUploadURL = URLDirectory.MyUpload()
var customAlertController : DOAlertController!
var recordPublicUpload = [[String : Any]]()
var recordPrivateUpload = [[String : Any]]()
var flag : Bool!
var flagDelete : Bool!
let imageCatch = NSCache<NSString,UIImage>()
var activityIndicator = UIActivityIndicatorView()
var nsuerDefault = UserDefaults.standard
var userEmail : String!
override func viewWillAppear(_ animated: Bool)
{
print("view Will Appear")
if segmentationController.selectedSegmentIndex == 0
{
getMyUploadPublicList()
}
else
{
getMyUploadPrivateList()
}
}
@IBAction func segmentAction(_ sender: UISegmentedControl)
{
if sender.selectedSegmentIndex == 0
{
getMyUploadPublicList()
}
else
{
getMyUploadPrivateList()
}
}
/* func setupView()
{
setupSegmentedControl()
updateView()
}
func setupSegmentedControl()
{
segmentationController.removeAllSegments()
segmentationController.insertSegment(withTitle: "Public Upload", at: 0, animated: false)
segmentationController.insertSegment(withTitle: "Private Upload", at: 1, animated: false)
segmentationController.addTarget(self, action: #selector(getAction(sender:)), for: .valueChanged)
}
func updateView()
{
if segmentationController.selectedSegmentIndex == 0
{
segmentationController.isSelected = true
getMyUploadPublicList()
}
else
{
segmentationController.isSelected = true
getMyUploadPrivateList()
}
}
func getAction(sender: UISegmentedControl)
{
updateView()
}
*/
override func viewDidLoad()
{
super.viewDidLoad()
userEmail = nsuerDefault.string(forKey: "emailAddress")
getMyUploadPublicList()
if Reachability.isConnectedToNetwork() == true
{
print("Internet connection OK")
}
else
{
print("NO Internet Connection")
let alertData = UIAlertController(title: "No Internet Connection ", message: "Make sure Your device is connected to the internet", preferredStyle: .alert)
alertData.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertData, animated: true, completion: nil)
}
print(isFromMenu)
self.navigationController?.navigationBar.tintColor = UIColor.white
self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style: .plain, target:nil, action:nil)
navigationController?.navigationBar.barTintColor = UIColor(red: 103.0/255.0, green: 68.0/255.0, blue: 240.0/255.0, alpha: 1.0)
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
flag = true
flagDelete = true
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge, spinColor:.white, bgColor: UIColor.lightGray, placeInTheCenterOf: self.myUploadCollectionView)
//setLoadingScreen()
}
func setLoadingScreen()
{
self.activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.white
self.activityIndicator.center = self.view.center
self.myUploadCollectionView.addSubview(self.activityIndicator)
}
func numberOfSections(in collectionView: UICollectionView) -> Int
{
return 1
}
func getMyUploadPublicList()
{
self.activityIndicator.startAnimating()
flag = true
let dicData = [ "user_email" : userEmail , "index" : 0 , "limit" : 30] as [String : Any]
getUploadData.getPublicPrivateMyUploadWebService(urlString: getUploadURL.publicMyUpload(), dicData: dicData as NSDictionary, callback:{(dicc, err) in
if err == nil
{
print("check user like ",dicc)
self.recordPublicUpload = dicc
DispatchQueue.main.async
{
self.activityIndicator.stopAnimating()
self.myUploadCollectionView.reloadData()
}
}
else
{
DispatchQueue.main.async
{
self.activityIndicator.startAnimating()
}
}
})
}
@IBAction func backButtonAction (_ sender : Any)
{
guard (isFromMenu) else
{
self.navigationController?.popViewController(animated: true)
return
}
self.dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
if (flag == true)
{
return recordPublicUpload.count
}
if (flag == false)
{
return recordPrivateUpload.count
}
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let uploadCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myuploadcell", for: indexPath) as! MyUploadCollectionViewCell
uploadCell.layer.cornerRadius = 3.0
uploadCell.layer.masksToBounds = true
uploadCell.layer.borderWidth = 2.0
uploadCell.layer.borderColor = UIColor.getXprezBlueColor().cgColor
let noDataLabel: UILabel = UILabel(frame:CGRect(x: 0, y: 0, width: myUploadCollectionView.bounds.size.width, height: myUploadCollectionView.bounds.size.height))
uploadCell.imgUpload.image = nil
if ( flag == true)
{
uploadCell.imgDelete.image = UIImage(named: "uploadUnDelete")
let publicUploadData = recordPublicUpload[indexPath.item]
guard (publicUploadData["msg"] as? String) != nil else
{
uploadCell.isHidden = false
myUploadCollectionView.backgroundView?.isHidden = true
uploadCell.deleteInfoView.isHidden = true
uploadCell.infoViewDetails.isHidden = true
uploadCell.lblUploadTitle.text = publicUploadData["title"] as? String
let publicUploadExe = publicUploadData["filemimeType"] as! String
if publicUploadExe == "video/mp4"
{
let img = UIImage(named: "privatePublicBigPlay")
uploadCell.btnplayAudioVideo.setImage(img, for: .normal)
//thumbnailPath
var publicUploadThum = publicUploadData["thumbnailPath"] as! String
publicUploadThum.replace("/root/cpanel3-skel/public_html/Xpress/", with: "http://103.235.104.118:3000/")
uploadCell.imgUpload.getImageFromUrl(publicUploadThum)
}
else
{
let img = UIImage(named: "privateAudio")
uploadCell.imgUpload.image = nil
uploadCell.btnplayAudioVideo.setImage(img, for: .normal)
uploadCell.imgUpload.backgroundColor = UIColor.getLightBlueColor()
}
uploadCell.btnplayAudioVideo.tag = indexPath.item
uploadCell.btnplayAudioVideo.addTarget(self, action: #selector(myUplaodPlayVideoAudio(sender:)), for: .touchUpInside)
uploadCell.btnDeleteVideo.tag = indexPath.item
uploadCell.btnDeleteVideo.addTarget(self, action: #selector(deleteVideo(sender :)), for: .touchUpInside)
return uploadCell
}
uploadCell.isHidden = true
noDataLabel.text = "No data available"
noDataLabel.textColor = UIColor.black
noDataLabel.textAlignment = .center
myUploadCollectionView.backgroundView = noDataLabel
}
if ( flag == false)
{
uploadCell.imgDelete.image = UIImage(named: "uploadUnDelete")
let privateUploadData = recordPrivateUpload[indexPath.item]
// noDataLabel.removeFromSuperview()
guard (privateUploadData["msg"] as? String) != nil else
{
uploadCell.isHidden = false
myUploadCollectionView.backgroundView?.isHidden = true
uploadCell.deleteInfoView.isHidden = true
uploadCell.infoViewDetails.isHidden = true
uploadCell.lblUploadTitle.text = privateUploadData["title"] as? String
let privateUploadExe = privateUploadData["filemimeType"] as! String
uploadCell.imgUpload.image = nil
if privateUploadExe == "video/mp4"
{
let img = UIImage(named: "privatePublicBigPlay")
uploadCell.btnplayAudioVideo.setImage(img, for: .normal)
//thumbnailPath
var privateUploadThum = privateUploadData["thumbnailPath"] as! String
privateUploadThum.replace("/root/cpanel3-skel/public_html/Xpress/", with: "http://103.235.104.118:3000/")
uploadCell.imgUpload.getImageFromUrl(privateUploadThum)
}
else
{
uploadCell.imgUpload.image = nil
let img = UIImage(named: "privateAudio")
uploadCell.btnplayAudioVideo.setImage(img, for: .normal)
uploadCell.imgUpload.backgroundColor = UIColor.getLightBlueColor()
}
uploadCell.btnplayAudioVideo.tag = indexPath.item
uploadCell.btnplayAudioVideo.addTarget(self, action: #selector(myUplaodPlayVideoAudio(sender:)), for: .touchUpInside)
uploadCell.btnDeleteVideo.tag = indexPath.item
uploadCell.btnDeleteVideo.addTarget(self, action: #selector(deleteVideo(sender :)), for: .touchUpInside)
return uploadCell
}
uploadCell.isHidden = true
noDataLabel.text = "No data available"
noDataLabel.textColor = UIColor.black
noDataLabel.textAlignment = .center
myUploadCollectionView.backgroundView = noDataLabel
}
return uploadCell
}
func infoUpload(sender : UIButton )
{
let indexPathValue = IndexPath(item: sender.tag, section: 0)
//let myCell = myUploadCollectionView.dequeueReusableCell(withReuseIdentifier: "", for: indexPathValue) as! MyUploadCollectionViewCell
let myCell = myUploadCollectionView.cellForItem(at: indexPathValue) as! MyUploadCollectionViewCell
myCell.deleteInfoView.alpha = 1
// myCell.infoViewDetails.isHidden = false
if flag == true
{
let myUploadPublicInfo = recordPublicUpload[indexPathValue.item]
let dateInfo = myUploadPublicInfo["createdAt"] as! String
let dataStringFormatter = DateFormatter()
dataStringFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date1 = dataStringFormatter.date(from: dateInfo)
print("first formate date1",date1!)
let dataStringFormatterTime = DateFormatter()
dataStringFormatterTime.dateFormat = "hh:mm"
let time1 : String = dataStringFormatterTime.string(from: date1!)
print("time data",time1)
let dataStringFormatterDay = DateFormatter()
dataStringFormatterDay.dateFormat = "MMM d, YYYY"
let day1 : String = dataStringFormatterDay.string(from: date1!)
print("day data",day1)
let privilegeInfo = myUploadPublicInfo["privacy"] as! String
let likeInfo = myUploadPublicInfo["likeCount"] as! Int
let viewInfo = myUploadPublicInfo["view_count"] as! Int
myCell.infoDate.text = day1
myCell.infoTime.text = time1
myCell.infoPrivilege.text = privilegeInfo
myCell.infoLikeCount.text = String(likeInfo)
myCell.infoViewCount.text = String(viewInfo)
print(myUploadPublicInfo)
myCell.infoViewDetails.isHidden = false
}
if flag == false
{
let indexPathValue = IndexPath(item: sender.tag, section: 0)
let myUploadPrivateInfo = recordPrivateUpload[indexPathValue.item]
let dateInfo = myUploadPrivateInfo["createdAt"] as! String
let myDate = String()
print ("hhhhhhhhh",myDate.getDatePart(dateString: dateInfo))
let dataStringFormatter = DateFormatter()
dataStringFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date1 = dataStringFormatter.date(from: dateInfo)
print("first formate date1",date1!)
let dataStringFormatterTime = DateFormatter()
dataStringFormatterTime.dateFormat = "hh:mm"
let time1 : String = dataStringFormatterTime.string(from: date1!)
print("time data",time1)
let dataStringFormatterDay = DateFormatter()
dataStringFormatterDay.dateFormat = "MMM d, YYYY"
let day1 : String = dataStringFormatterDay.string(from: date1!)
print("day data",day1)
let privilegeInfo = myUploadPrivateInfo["privacy"] as! String
let likeInfo = myUploadPrivateInfo["likeCount"] as! Int
let viewInfo = myUploadPrivateInfo["view_count"] as! Int
myCell.infoDate.text = day1
myCell.infoTime.text = time1
myCell.infoPrivilege.text = privilegeInfo
myCell.infoLikeCount.text = String(likeInfo)
myCell.infoViewCount.text = String(viewInfo)
print(myUploadPrivateInfo)
myCell.infoViewDetails.isHidden = false
}
}
func deleteVideo(sender : UIButton)
{
//uploadDelete
let indexValue = IndexPath(item: sender.tag, section: 0)
let myCell = myUploadCollectionView.cellForItem(at: indexValue) as! MyUploadCollectionViewCell
myCell.imgDelete.image = nil
if flag == true
{
if (flagDelete == true)
{
myCell.imgDelete.image = UIImage(named: "uploadDelete")
myCell.deleteInfoView.isHidden = false
myCell.deleteInfoView.alpha = 0.5
myCell.infoViewDetails.isHidden = true
myCell.btnInfoDelete.tag = indexValue.item
myCell.btnDeleteMyUpload.tag = indexValue.item
myCell.btnDeleteMyUpload.addTarget(self, action: #selector(videoDelete(sender:)), for: .touchUpInside)
myCell.btnInfoDelete.addTarget(self, action: #selector(infoUpload(sender:)), for: .touchUpInside)
flagDelete = false
}
else
{
myCell.deleteInfoView.isHidden = true
myCell.imgDelete.image = UIImage(named: "uploadUnDelete")
flagDelete = true
}
}
if flag == false
{
myCell.imgDelete.image = nil
if (flagDelete == true)
{
flagDelete = false
myCell.imgDelete.image = UIImage(named: "uploadDelete")
myCell.deleteInfoView.isHidden = false
myCell.deleteInfoView.alpha = 0.5
myCell.infoViewDetails.isHidden = true
myCell.btnInfoDelete.tag = indexValue.item
myCell.btnDeleteMyUpload.tag = indexValue.item
myCell.btnDeleteMyUpload.addTarget(self, action: #selector(videoDelete(sender:)), for: .touchUpInside)
myCell.btnInfoDelete.addTarget(self, action: #selector(infoUpload(sender:)), for: .touchUpInside)
}
else
{
myCell.deleteInfoView.isHidden = true
myCell.imgDelete.image = UIImage(named: "uploadUnDelete")
flagDelete = true
}
}
}
func videoDelete(sender: UIButton)
{
let indexPathValue = NSIndexPath(item: sender.tag, section: 0)
if flag == true
{
let currentData = recordPublicUpload[indexPathValue.item]
let infoId = currentData["_id"] as! String
let fileTypeData = currentData["filemimeType"] as! String
let fileType : String!
if (fileTypeData == "video/mp4")
{
fileType = "video"
}
else
{
fileType = "audio"
}
getDeleteAction(infoId: infoId, fileType: fileType, indexPath: indexPathValue as IndexPath)
}
if flag == false
{
let currentData = recordPrivateUpload[indexPathValue.item]
let infoId = currentData["_id"] as! String
let fileType : String!
let fileTypeData = currentData["filemimeType"] as! String
if (fileTypeData == "video/mp4")
{
fileType = "video"
}
else
{
fileType = "audio"
}
getDeleteAction(infoId: infoId, fileType: fileType, indexPath: indexPathValue as IndexPath)
}
}
func getDeleteAction(infoId : String ,fileType : String,indexPath : IndexPath)
{
let message = "Are You Sure You Want to Delete This?"
let cancelButtonTitle = "Cancel"
let otherButtonTitle = "Delete"
if flag == true
{
let dicData = ["file_type":fileType,"id": infoId]
customAlertController = DOAlertController(title: nil, message: message, preferredStyle: .alert)
changecustomAlertController()
let cancelAction = DOAlertAction(title: cancelButtonTitle, style: .cancel, handler: {
action in
})
let otherAction = DOAlertAction(title: otherButtonTitle, style: .destructive, handler:{
action in
self.getUploadData.getDeleteMyUploadWebService(urlString: self.getUploadURL.deleteMyUploadPublic(), dicData: dicData as NSDictionary, callback: { (dicc,error) in
self.recordPublicUpload.remove(at: indexPath.item)
DispatchQueue.main.async(execute: {
self.myUploadCollectionView.performBatchUpdates({
self.myUploadCollectionView.deleteItems(at: [indexPath])
}, completion: {
(finishd : Bool) in
// self.myUploadCollectionView.reloadData()
self.myUploadCollectionView.reloadItems(at: self.myUploadCollectionView.indexPathsForVisibleItems)
})
})
})
})
customAlertController.addAction(cancelAction)
customAlertController.addAction(otherAction)
self.present(customAlertController, animated: true, completion: nil)
}
if flag == false
{
let dicData = ["file_type":fileType,"id": infoId]
customAlertController = DOAlertController(title: nil, message: message, preferredStyle: .alert)
changecustomAlertController()
// customAlertController.overlayColor = UIColor(red:255/255, green:255/255, blue:255/255, alpha:0.1)
let cancelAction = DOAlertAction(title: cancelButtonTitle, style: .cancel, handler: {
action in
print("hi")
})
let otherAction = DOAlertAction(title: otherButtonTitle, style: .default, handler:{
action in
self.getUploadData.getDeleteMyUploadWebService(urlString: self.getUploadURL.deleteMyUploadPrivate(), dicData: dicData as NSDictionary, callback: { (dicc,error) in
self.recordPrivateUpload.remove(at: indexPath.item)
DispatchQueue.main.async
{
self.myUploadCollectionView.performBatchUpdates({
self.myUploadCollectionView.deleteItems(at: [indexPath])
}, completion: {
(finish : Bool) in
self.myUploadCollectionView.reloadItems(at: self.myUploadCollectionView.indexPathsForVisibleItems)
})
}
})
})
customAlertController.addAction(cancelAction)
customAlertController.addAction(otherAction)
self.present(customAlertController, animated: true, completion: nil)
}
}
func changecustomAlertController()
{
customAlertController.alertView.layer.cornerRadius = 6.0
customAlertController.alertViewBgColor = UIColor(red:255/255, green:255/255, blue:255/255, alpha:0.7)
customAlertController.titleFont = UIFont(name: "Mosk", size: 17.0)
customAlertController.titleTextColor = UIColor.green
customAlertController.messageFont = UIFont(name: "Mosk", size: 15.0)
customAlertController.messageTextColor = UIColor.black
customAlertController.alertView.sizeToFit()
customAlertController.buttonFont[.cancel] = UIFont(name: "Mosk", size: 15.0)
customAlertController.buttonBgColor[.cancel] = UIColor.getLightBlueColor()
customAlertController.buttonFont[.default] = UIFont(name: "Mosk", size: 15.0)
customAlertController.buttonBgColor[.default] = UIColor.getOrangeColor()
}
func myUplaodPlayVideoAudio( sender : UIButton)
{
if flag == true
{
let indexPathValue = IndexPath(item: sender.tag, section: 0)
let myUploadPlayData = recordPublicUpload[indexPathValue.item]
let playUploadTitle = myUploadPlayData["title"] as! String
var playUploadVideoPath = myUploadPlayData["tokenizedUrl"] as? String
let playFilemimeType = myUploadPlayData["filemimeType"] as! String
let playID = myUploadPlayData["_id"] as! String
let checkUserLike = myUploadPlayData["isUserLiked"] as! Int
print("mathan mathan ",checkUserLike)
// playUploadVideoPath?.replace("/root/cpanel3-skel/public_html/Xpress/", with: "http://103.235.104.118:3000/")
let playUploadLikeCount = myUploadPlayData["likeCount"] as! Int
let playUploadViewCount = myUploadPlayData["view_count"] as! Int
let playUploadSmiley = myUploadPlayData["emotionCount"] as! Int
let playViewController = self.storyboard?.instantiateViewController(withIdentifier: "XPMyUploadPlayViewController" ) as! XPMyUploadPlayViewController
playViewController.playTitle = playUploadTitle
playViewController.playUrlString = playUploadVideoPath!
playViewController.playLike = playUploadLikeCount
playViewController.playView = playUploadViewCount
playViewController.playSmiley = playUploadSmiley
playViewController.nextID = playID
playViewController.nextFileType = playFilemimeType
playViewController.checkLike = checkUserLike
self.navigationController?.pushViewController(playViewController, animated: true)
}
if flag == false
{
let indexPathValue = IndexPath(item: sender.tag, section: 0)
let myUploadPlayData = recordPrivateUpload[indexPathValue.item]
let playUploadTitle = myUploadPlayData["title"] as! String
var playUploadVideoPath = myUploadPlayData["tokenizedUrl"] as? String
// playUploadVideoPath?.replace("/root/cpanel3-skel/public_html/Xpress/", with: "http://103.235.104.118:3000/")
let playFilemimeType = myUploadPlayData["filemimeType"] as! String
let playID = myUploadPlayData["_id"] as! String
let playUploadLikeCount = myUploadPlayData["likeCount"] as! Int
let playUploadViewCount = myUploadPlayData["view_count"] as! Int
let playUploadSmiley = myUploadPlayData["emotionCount"] as! Int
let checkUserLike = myUploadPlayData["isUserLiked"] as! Int
print(playUploadVideoPath!)
let playViewController = self.storyboard?.instantiateViewController(withIdentifier: "XPMyUploadPlayViewController" ) as! XPMyUploadPlayViewController
playViewController.playTitle = playUploadTitle
playViewController.playUrlString = playUploadVideoPath!
playViewController.playLike = playUploadLikeCount
playViewController.playView = playUploadViewCount
playViewController.playSmiley = playUploadSmiley
playViewController.nextID = playID
playViewController.nextFileType = playFilemimeType
playViewController.checkLike = checkUserLike
self.navigationController?.pushViewController(playViewController, animated: true)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
if indexPath.item % 2 == 0
{
let widthOfCell = UIScreen.main.bounds.width / 2 - 20
let heightOfCell = widthOfCell * 1.15
var returnCell = CGSize(width: widthOfCell, height: heightOfCell)
returnCell.height += 5
returnCell.width += 5
return returnCell
}
else
{
let widthOfCell = UIScreen.main.bounds.width / 2 - 20
let heightOfCell = widthOfCell * 1
var returnCell = CGSize(width: widthOfCell, height: heightOfCell)
returnCell.height += 5
returnCell.width += 5
return returnCell
}
// CGFloat widthOfCell =(self.view.frame.size.width-30)/2;
// CGFloat heightOfCell =widthOfCell * 1.33;
//return CGSize(width: myUploadCollectionView.frame.size.width / 2 - 20, height: myUploadCollectionView.frame.size.width / 2 - 20 )
// return CGSize(width: widthOfCell, height: heightOfCell)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 10;
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 10;
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//let leftRightInset = collectionView.frame.size.width / 14.0
return UIEdgeInsetsMake(10, 10, 10, 10)
}
/*
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView
{
var header : HeaderMyuploadCollectionReusableView!
if kind == UICollectionElementKindSectionHeader {
header =
collectionView.dequeueReusableSupplementaryView(ofKind: kind,
withReuseIdentifier: "header", for: indexPath)
as? HeaderMyuploadCollectionReusableView
header.segmentPublicPrivateUpload.addTarget(self, action: #selector(loadData(sender :)), for: .valueChanged)
}
return header!
}
func loadData(sender : UISegmentedControl)
{
if sender.selectedSegmentIndex == 0
{
getMyUploadPublicList()
print ("publicvideo")
}
else if(sender.selectedSegmentIndex == 1)
{
print("private Video")
getMyUploadPrivateList()
}
else
{
print("Video")
}
}
*/
func getMyUploadPrivateList()
{
self.activityIndicator.startAnimating()
flag = false
let dicData = [ "user_email" : userEmail , "index" : 0 , "limit" : 30] as [String : Any]
getUploadData.getPublicPrivateMyUploadWebService(urlString: getUploadURL.privateMyUpload(), dicData: dicData as NSDictionary, callback:{(dicc, err) in
if err == nil
{
print(dicc)
self.recordPrivateUpload = dicc
DispatchQueue.main.async {
self.myUploadCollectionView.reloadData()
self.activityIndicator.stopAnimating()
}
}
else
{
DispatchQueue.main.async {
self.activityIndicator.startAnimating()
}
}
})
}
}
| mit | 0323539e8b0284e1b761b19e661b8f50 | 27.610845 | 183 | 0.51388 | 6.609801 | false | false | false | false |
limaoxuan/MXAutoLayoutScrollView | MXAutoLayoutScrollView/MXAutoLayoutScrollView/AppDelegate.swift | 1 | 6172 | //
// AppDelegate.swift
// MXAutoLayoutScrollView
//
// Created by 李茂轩 on 15/3/30.
// Copyright (c) 2015年 limaoxuan. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.lex.MXAutoLayoutScrollView" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
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 = NSBundle.mainBundle().URLForResource("MXAutoLayoutScrollView", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return 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
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MXAutoLayoutScrollView.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = 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 \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// 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
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| apache-2.0 | b3e987832f2d207256b0c5d1bf1e1626 | 54.531532 | 290 | 0.717716 | 5.744641 | false | false | false | false |
git-hushuai/MOMO | MMHSMeterialProject/UINavigationController/BusinessFile/订单Item/OptimizeItemTableView/TKOptimizeOrderCell.swift | 1 | 13383 | //
// TKOptimizeOrderCell.swift
// MMHSMeterialProject
//
// Created by hushuaike on 16/4/10.
// Copyright © 2016年 hushuaike. All rights reserved.
//
import UIKit
class TKOptimizeOrderCell: UITableViewCell {
var orderIDLabel:UILabel = UILabel();
var showTimeLabel:UILabel = UILabel();
var logoView:UIImageView = UIImageView();
var jobNameLabel:UILabel = UILabel();
var firstBaseInfoLabel:UILabel = UILabel();
var secondBaseInfoLabel:UILabel = UILabel();
var threeBaseInfoLabel :UILabel = UILabel();
var fourBaseInfoLabel:UILabel = UILabel();
var baseInfoLogoView:UIImageView = UIImageView();
var baseInfoPhoneView:UIImageView = UIImageView();
var baseInfoEmailView :UIImageView = UIImageView();
var baseInfoLogoLabel:UILabel = UILabel();
var baseInfoPhoneLabel:UILabel = UILabel();
var baseInfoEmailLabel:UILabel = UILabel.init();
var advisorContentLabel:UILabel = UILabel.init();
var topCaverView:UILabel = UILabel.init();
var bottomCarverView:UILabel = UILabel.init();
var resumeModel : TKJobItemModel?{
didSet{
self.setCellSubInfoWithModle(resumeModel!);
}
}
func setCellSubInfoWithModle(resumeModel:TKJobItemModel){
self.contentView.eds_segmentLineColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0);
if resumeModel.order_id == nil{
resumeModel.order_id = NSNumber.init(int: -1);
}
let order_idInfo = String.init(format: "%@", (resumeModel.order_id)!);
if(order_idInfo != "" && resumeModel.order_id!.intValue > 0){
self.orderIDLabel.text = String.init(format: "订单号 : %@", (resumeModel.order_id)!);
self.orderIDLabel.sd_layout()
.heightIs(30);
self.orderIDLabel.eds_segmentLineColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0);
// self.contentView.eds_showTopSegmentLine = true;
}else{
self.orderIDLabel.sd_layout()
.heightIs(0);
// self.contentView.eds_showTopSegmentLine = false;
}
self.orderIDLabel.updateLayout();
self.logoView.sd_setImageWithURL(NSURL.init(string: resumeModel.logo), placeholderImage: UIImage.init(named: "缺X3"), options: SDWebImageOptions.RetryFailed);
self.jobNameLabel.text = resumeModel.expected_job;
if Int(resumeModel.sex) == 0{
self.firstBaseInfoLabel.text = "女";
}else if(Int(resumeModel.sex) == 1){
self.firstBaseInfoLabel.text = "男";
}else{
self.firstBaseInfoLabel.text = "";
}
self.secondBaseInfoLabel.text = resumeModel.position;
self.threeBaseInfoLabel.text = resumeModel.degree;
self.fourBaseInfoLabel.text = String.init(format: "%@年工作年限", resumeModel.year_work);
self.baseInfoLogoView.image = UIImage.init(named: "姓名@2x");
self.baseInfoLogoView.updateLayout();
self.baseInfoPhoneView.image = UIImage.init(named: "电话@2x");
self.baseInfoPhoneView.updateLayout();
self.baseInfoEmailView.image = UIImage.init(named: "邮箱@2x");
self.baseInfoEmailView.updateLayout();
if resumeModel.name == nil{
resumeModel.name = "暂无";
}
self.baseInfoLogoLabel.text = resumeModel.name.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 ? resumeModel.name : "暂无";
if resumeModel.phone == nil{
resumeModel.phone = NSNumber.init(int: -1);
}
let phoneStr = String.init(format: "%@", (resumeModel.phone)!);
if phoneStr != "<null>" && resumeModel.phone.intValue > 0{
self.baseInfoPhoneLabel.text = phoneStr;
}else{
self.baseInfoPhoneLabel.text = "暂无";
}
if resumeModel.email == nil{
resumeModel.email = "暂无";
}else{
self.baseInfoEmailLabel.text = resumeModel.email.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 ? resumeModel.email : "暂无";}
self.advisorContentLabel.font = UIFont.systemFontOfSize(12.0);
self.advisorContentLabel.textAlignment = .Center;
self.advisorContentLabel.textColor = RGBA(0xa4, g: 0xb8, b: 0xcd, a: 1.0);
self.advisorContentLabel.text = resumeModel.content;
// print("resume status string:\( resumeModel.resume_status!)");
if resumeModel.resume_status == nil{
resumeModel.resume_status = NSNumber.init(int: -1);
}
let resume_statusStr = String.init(format: "%@", resumeModel.resume_status!);
if resume_statusStr != "nil"{
if (resumeModel.resume_status == 2 || resumeModel.resume_status == 1){
self.advisorContentLabel.sd_layout()
.heightIs(0);
self.bottomCarverView.hidden = true;
}else{
if resumeModel.content.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 {
self.advisorContentLabel.sd_layout()
.heightIs(30);
self.bottomCarverView.hidden = false;
}else{
self.advisorContentLabel.sd_layout()
.heightIs(0);
self.bottomCarverView.hidden = true;
}
}
}else{
self.advisorContentLabel.sd_layout()
.heightIs(0);
self.bottomCarverView.hidden = true;
}
self.advisorContentLabel.updateLayout();
// self.contentView.eds_showBottomSegmentLine = true;
self.contentView.layoutSubviews();
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier);
self.contentView.addSubview(self.orderIDLabel);
self.orderIDLabel.font = UIFont.systemFontOfSize(14.0);
self.orderIDLabel.textColor = RGBA(0x47, g: 0x47, b: 0x47, a: 1.0);
self.orderIDLabel.sd_layout()
.leftSpaceToView(self.contentView,14.0)
.topSpaceToView(self.contentView,0);
self.orderIDLabel.textAlignment = .Left;
self.orderIDLabel.textColor = RGBA(0x47, g: 0x47, b: 0x47, a: 1.0)
self.orderIDLabel.setSingleLineAutoResizeWithMaxWidth(260);
self.contentView.addSubview(self.topCaverView);
self.topCaverView.sd_layout()
.topSpaceToView(self.orderIDLabel,0)
.leftEqualToView(self.contentView)
.rightEqualToView(self.contentView)
.heightIs(0.5);
self.contentView.addSubview(self.showTimeLabel);
self.showTimeLabel.sd_layout()
.rightSpaceToView(self.contentView,14)
self.showTimeLabel.setSingleLineAutoResizeWithMaxWidth(120);
self.showTimeLabel.font = UIFont.systemFontOfSize(14.0);
self.showTimeLabel.textAlignment = .Right;
self.contentView.addSubview(self.logoView);
self.logoView.sd_layout()
.leftSpaceToView(self.contentView,14.0)
.topSpaceToView(self.orderIDLabel,10)
.widthIs(50)
.heightIs(50);
self.contentView.addSubview(self.jobNameLabel);
self.jobNameLabel.sd_layout()
.leftSpaceToView(self.logoView,14)
.topSpaceToView(self.orderIDLabel,10)
.heightIs(20);
self.jobNameLabel.setSingleLineAutoResizeWithMaxWidth(200);
self.jobNameLabel.textAlignment = .Left;
self.contentView.addSubview(self.firstBaseInfoLabel);
self.firstBaseInfoLabel.font = UIFont.systemFontOfSize(16.0);
self.firstBaseInfoLabel.textAlignment = NSTextAlignment.Left;
self.firstBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0);
self.firstBaseInfoLabel.sd_layout()
.leftEqualToView(self.jobNameLabel)
.topSpaceToView(self.jobNameLabel,10)
.heightIs(20.0);
self.firstBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(40);
self.firstBaseInfoLabel.isAttributedContent = false;
self.firstBaseInfoLabel.textAlignment = .Left;
self.contentView.addSubview(self.secondBaseInfoLabel);
self.secondBaseInfoLabel.font = UIFont.systemFontOfSize(16.0);
self.secondBaseInfoLabel.textAlignment = NSTextAlignment.Left;
self.secondBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0);
self.secondBaseInfoLabel.sd_layout()
.leftSpaceToView(self.firstBaseInfoLabel,20)
.topSpaceToView(self.jobNameLabel,10)
.heightIs(20);
self.secondBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(120);
self.secondBaseInfoLabel.isAttributedContent = false;
self.secondBaseInfoLabel.textAlignment = .Left;
self.contentView.addSubview(self.threeBaseInfoLabel);
self.threeBaseInfoLabel.font = UIFont.systemFontOfSize(16.0);
self.threeBaseInfoLabel.textAlignment = NSTextAlignment.Left;
self.threeBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0);
self.threeBaseInfoLabel.sd_layout()
.leftSpaceToView(self.secondBaseInfoLabel,20)
.topSpaceToView(self.jobNameLabel,10)
.heightIs(20);
self.threeBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(120);
self.threeBaseInfoLabel.isAttributedContent = false;
self.threeBaseInfoLabel.textAlignment = .Left;
self.contentView.addSubview(self.fourBaseInfoLabel);
self.fourBaseInfoLabel.font = UIFont.systemFontOfSize(16.0);
self.fourBaseInfoLabel.textAlignment = NSTextAlignment.Left;
self.fourBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0);
self.fourBaseInfoLabel.sd_layout()
.leftSpaceToView(self.threeBaseInfoLabel,20)
.topSpaceToView(self.jobNameLabel,10)
.heightIs(20);
self.fourBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(120);
self.fourBaseInfoLabel.isAttributedContent = false;
self.fourBaseInfoLabel.textAlignment = .Left;
self.contentView.addSubview(self.baseInfoLogoView);
self.baseInfoLogoView.sd_layout()
.leftSpaceToView(self.logoView,14.0)
.topSpaceToView(self.firstBaseInfoLabel,10)
.widthIs(16.0)
.heightIs(16.0);
self.contentView.addSubview(self.baseInfoLogoLabel);
self.baseInfoLogoLabel.sd_layout()
.leftSpaceToView(self.baseInfoLogoView,14)
.topEqualToView(self.baseInfoLogoView)
.heightIs(16)
self.baseInfoLogoLabel.setSingleLineAutoResizeWithMaxWidth(100);
self.baseInfoLogoLabel.textAlignment = .Left;
self.baseInfoLogoLabel.font = UIFont.systemFontOfSize(12.0);
self.baseInfoLogoLabel.textColor = RGBA(0x91, g: 0x91, b: 0x91, a: 1.0);
self.contentView.addSubview(self.baseInfoPhoneView);
self.baseInfoPhoneView.sd_layout()
.leftSpaceToView(self.baseInfoLogoView,100)
.topEqualToView(self.baseInfoLogoView)
.widthIs(16)
.heightIs(16);
self.contentView.addSubview(self.baseInfoPhoneLabel);
self.baseInfoPhoneLabel.sd_layout()
.leftSpaceToView(self.baseInfoPhoneView,14)
.topEqualToView(self.baseInfoLogoView)
.heightIs(16);
self.baseInfoPhoneLabel.setSingleLineAutoResizeWithMaxWidth(120);
self.baseInfoPhoneLabel.textAlignment = .Left;
self.baseInfoPhoneLabel.font = UIFont.systemFontOfSize(12.0);
self.baseInfoPhoneLabel.textColor = RGBA(0x91, g: 0x91, b: 0x91, a: 1.0);
self.contentView.addSubview(self.baseInfoEmailView);
self.baseInfoEmailView.sd_layout()
.leftEqualToView(self.baseInfoLogoView)
.topSpaceToView(self.baseInfoLogoView,10)
.widthIs(16.0)
.heightIs(16.0);
self.contentView.addSubview(self.baseInfoEmailLabel);
self.baseInfoEmailLabel.sd_layout()
.leftSpaceToView(self.baseInfoEmailView,14)
.topEqualToView(self.baseInfoEmailView)
.heightIs(16);
self.baseInfoEmailLabel.setSingleLineAutoResizeWithMaxWidth(240);
self.baseInfoEmailLabel.textAlignment = .Left;
self.baseInfoEmailLabel.font = UIFont.systemFontOfSize(12.0);
self.baseInfoEmailLabel.textColor = RGBA(0x91, g: 0x91, b: 0x91, a: 1.0);
self.contentView.addSubview(self.advisorContentLabel);
self.advisorContentLabel.sd_layout()
.leftEqualToView(self.contentView)
.rightEqualToView(self.contentView)
.topSpaceToView(self.baseInfoEmailView,10);
self.contentView.addSubview(self.bottomCarverView);
self.bottomCarverView.sd_layout()
.topSpaceToView(self.baseInfoEmailView,10)
.leftEqualToView(self.contentView)
.rightEqualToView(self.contentView)
.heightIs(0.5);
self.topCaverView.backgroundColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0);
self.bottomCarverView.backgroundColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0);
self.setupAutoHeightWithBottomView(self.advisorContentLabel, bottomMargin: 0);
}
// MARK: rgb color
func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat)->UIColor {
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) }
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | e54caa5fa69520150c508547bab2bb3f | 38.898204 | 165 | 0.672745 | 4.461332 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Objects/Spotify/HATSpotifyProfile.swift | 1 | 2552 | //
/**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* 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/
*/
// MARK: Struct
public struct HATSpotifyProfile: HATObject {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `spotifyID` in JSON is `id`
* `uri` in JSON is `uri`
* `href` in JSON is `href`
* `email` in JSON is `email`
* `images` in JSON is `images`
* `country` in JSON is `country`
* `product` in JSON is `product`
* `birthdate` in JSON is `birthdate`
* `followers` in JSON is `followers`
* `dateCreated` in JSON is `dateCreated`
* `shouldDisplayName` in JSON is `display_name`
* `externalUrls` in JSON is `external_urls`
*/
private enum CodingKeys: String, CodingKey {
case spotifyID = "id"
case uri = "uri"
case href = "href"
case email = "email"
case images = "images"
case country = "country"
case product = "product"
case birthdate = "birthdate"
case followers = "followers"
case dateCreated = "dateCreated"
case shouldDisplayName = "display_name"
case externalUrls = "external_urls"
}
// MARK: - Variables
/// The user's spotify ID
public var spotifyID: String = ""
/// The profile page for the particular user
public var uri: String = ""
/// The spotify's HREF
public var href: String = ""
/// User's email
public var email: String = ""
/// Images user has saved
public var images: [HATSpotifyProfileImages] = []
/// User's country
public var country: String = ""
/// The product user is registered
public var product: String = ""
/// User's birthdate
public var birthdate: String = ""
/// User's followers
public var followers: HATSpotifyProfileFollowers = HATSpotifyProfileFollowers()
/// Date user created the spotify account
public var dateCreated: String = ""
/// A flag indicating if user has choosen to share his name or not
public var shouldDisplayName: String?
/// Any external URLs user has added to the account
public var externalUrls: HATSpotifyProfileExternalURLObject = HATSpotifyProfileExternalURLObject()
}
| mpl-2.0 | a2ca63c5d18efd99164b97c9d88e017c | 31.303797 | 102 | 0.628527 | 4.281879 | false | false | false | false |
matthijs2704/vapor-apns | Sources/VaporAPNS/ApplePushMessage.swift | 1 | 1523 | //
// VaporAPNSPush.swift
// VaporAPNS
//
// Created by Matthijs Logemann on 23/09/2016.
//
//
import Foundation
import JSON
/// Apple Push Notification Message
public struct ApplePushMessage {
/// Message ID
public let messageId: String = UUID().uuidString
public let topic: String?
public let collapseIdentifier: String?
public let expirationDate: Date?
/// APNS Priority
public let priority: Priority
/// Push notification delivery priority
///
/// - energyEfficient: Send the push message at a time that takes into account power considerations for the device.
/// - immediately: Send the push message immediately. Notifications with this priority must trigger an alert, sound, or badge on the target device. It is an error to use this priority for a push notification that contains only the content-available key.
public enum Priority: Int {
case energyEfficient = 5
case immediately = 10
}
/// APNS Payload
public let payload: Payload
/// Use sandbox server URL or not
public let sandbox:Bool
public init(topic: String? = nil, priority: Priority, expirationDate: Date? = nil, payload: Payload, sandbox:Bool = true, collapseIdentifier: String? = nil) {
self.topic = topic
self.priority = priority
self.expirationDate = expirationDate
self.payload = payload
self.sandbox = sandbox
self.collapseIdentifier = collapseIdentifier
}
}
| mit | 19bf6baa384d7c059d61bc6618c4d16f | 29.46 | 261 | 0.674984 | 4.789308 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals/Business/TasksRequester.swift | 1 | 1498 | //
// TasksRequester.swift
// YourGoals
//
// Created by André Claaßen on 04.11.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
class TasksRequester : StorageManagerWorker {
/// is there any active task?
///
/// This request is nesseccary to decide, if you should see the active tasks pane
///
/// - Parameter date: date
/// - Returns: true, if there are active tasks
/// false, if there are no active tasks
func areThereActiveTasks(forDate date: Date) throws -> Bool {
let activeTasks = try TaskProgressManager(manager: self.manager).activeTasks(forDate: date)
return activeTasks.count > 0
}
/// is there any active task, which isn't a commtted task?
///
/// This request is nesseccary to decide, if you should see the active tasks pane
///
/// - Parameter date: date
/// - Returns: true, if there are active tasks which aren't committed
/// false, if there are no active tasks or all active tasks are committed
func areThereActiveTasksWhichAreNotCommitted(forDate date: Date) throws -> Bool {
let activeTasks = try TaskProgressManager(manager: self.manager).activeTasks(forDate: date)
guard activeTasks.count > 0 else {
return false
}
let tasksNotCommitted = activeTasks.filter{ $0.committingState(forDate: date) == .notCommitted }
return tasksNotCommitted.count > 0
}
}
| lgpl-3.0 | 8073029eed909363edca3efc2d600d21 | 35.414634 | 104 | 0.653717 | 4.35277 | false | false | false | false |
drinkapoint/DrinkPoint-iOS | DrinkPoint/Pods/FacebookShare/Sources/Share/Dialogs/ShareDialog/ShareDialogMode.swift | 1 | 2564 | // Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright 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 FBSDKShareKit
/**
Modes for the `ShareDialog`.
The automatic mode will progressively check the availability of different modes and open the most appropriate mode
for the dialog that is available.
*/
public enum ShareDialogMode {
/// Acts with the most appropriate mode that is available.
case Automatic
/// Displays the dialog in the main native Facebook app.
case Native
/// Displays the dialog in the iOS integrated share sheet.
case ShareSheet
/// Displays the dialog in Safari.
case Browser
/// Displays the dialog in a UIWebView within the app.
case Web
/// Displays the feed dialog in Safari.
case FeedBrowser
/// Displays the feed dialog in a UIWebView within the app.
case FeedWeb
}
extension ShareDialogMode {
internal init(sdkShareMode: FBSDKShareDialogMode) {
switch sdkShareMode {
case .Automatic: self = .Automatic
case .Native: self = .Native
case .ShareSheet: self = .ShareSheet
case .Browser: self = .Browser
case .Web: self = .Web
case .FeedBrowser: self = .FeedBrowser
case .FeedWeb: self = .FeedWeb
}
}
internal var sdkShareMode: FBSDKShareDialogMode {
switch self {
case .Automatic: return .Automatic
case .Native: return .Native
case .ShareSheet: return .ShareSheet
case .Browser: return .Browser
case .Web: return .Web
case .FeedBrowser: return .FeedBrowser
case .FeedWeb: return .FeedWeb
}
}
}
| mit | 5f89b544000581834f95c71990dd013a | 33.648649 | 115 | 0.726989 | 4.498246 | false | false | false | false |
fewspider/FFSideMenu | Example/FFSideMenu/LeftMenuController.swift | 1 | 4647 | //
// LeftMenuController.swift
// FFSideMenu
//
// Created by fewspider on 15/10/1.
// Copyright © 2015年 CocoaPods. All rights reserved.
//
import UIKit
class LeftMenuController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var items = [
[
"identifier": "testOne",
"text": "left test one"
],
[
"identifier": "testTwo",
"text": "left test two"
],
[
"identifier": "testThree",
"text": "left test three"
],
[
"identifier": "testFour",
"text": "left test four"
],
[
"identifier": "testFive",
"text": "left test Five"
],
[
"identifier": "testSix",
"text": "left test Six"
],
[
"identifier": "testSevent",
"text": "left test sevent"
]
]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.autoresizingMask = UIViewAutoresizing.FlexibleRightMargin
// 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()
// self.tableView.contentInset = UIEdgeInsetsMake(64,0,0,0)
self.tableView.backgroundColor = UIColor(red:0, green:0.75, blue:1, alpha:1)
self.tableView.tableFooterView = UIView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(items[indexPath.row]["identifier"]!, forIndexPath: indexPath)
// Configure the cell...
cell.textLabel?.text = items[indexPath.row]["text"]
cell.backgroundColor = tableView.backgroundColor
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = UIColor.yellowColor()
cell.selectedBackgroundView = selectedBackgroundView
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 false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 357e9727e738a491329108cf08f1fb9d | 32.410072 | 157 | 0.643842 | 5.356401 | false | true | false | false |
J-Mendes/Weather | Weather/Weather/Core Layer/Data Model/Forecast.swift | 1 | 1404 | //
// Forecast.swift
// Weather
//
// Created by Jorge Mendes on 05/07/17.
// Copyright © 2017 Jorge Mendes. All rights reserved.
//
import Foundation
struct Forecast {
fileprivate let ImageUrlTemplate: String = "http://l.yimg.com/a/i/us/we/52/%@.gif"
internal var code: String!
internal var date: Date!
internal var high: String!
internal var low: String!
internal var text: String!
internal var imageUrl: String {
return code != nil && !code.isEmpty ? String(format: self.ImageUrlTemplate, self.code) : ""
}
init() {
self.code = ""
self.date = Date()
self.high = ""
self.low = ""
self.text = ""
}
init(dictionary: [String: Any]) {
self.init()
if let code: String = dictionary["code"] as? String {
self.code = code
}
if let dateString: String = dictionary["date"] as? String,
let date: Date = dateString.dateValueFromShortDate() {
self.date = date
}
if let high: String = dictionary["high"] as? String {
self.high = high
}
if let low: String = dictionary["low"] as? String {
self.low = low
}
if let text: String = dictionary["text"] as? String {
self.text = text
}
}
}
| gpl-3.0 | eadc0552690d53579b97c9a11167bd92 | 23.189655 | 99 | 0.525303 | 4.11437 | false | false | false | false |
mindz-eye/MYTableViewIndex | MYTableViewIndex/Public/TableViewIndex.swift | 1 | 16784 | //
// TableViewIndex.swift
// TableViewIndex
//
// Created by Makarov Yury on 28/04/16.
// Copyright © 2016 Makarov Yury. All rights reserved.
//
import UIKit
@objc(MYTableViewIndex)
@objcMembers
open class TableViewIndex : UIControl {
// MARK: - Properties
/// Data source for the table index object. See TableViewIndexDataSource protocol for details.
@IBOutlet public weak var dataSource: TableViewIndexDataSource? {
didSet { reloadData() }
}
/// Delegate for the table index object. See TableViewIndexDelegate protocol for details.
@IBOutlet public weak var delegate: TableViewIndexDelegate?
/// Background view is displayed below the index items and can be customized with any UIView.
/// If not set or set to nil, creates a default view which mimics the system index appearance.
public var backgroundView: UIView! {
didSet {
if let view = backgroundView {
insertSubview(view, at: 0)
} else {
backgroundView = BackgroundView()
}
}
}
/// Font for the index view items. If not set, uses a default font which is chosen to
/// match system appearance.
/// Use resetFont to fall back to default font.
public var font: UIFont {
get { return style.font }
set { style = style.copy(applyingFont: newValue) }
}
/// Minimum width of the view. Equals to 44 points by default to enable easy tapping
/// Use resetMinWidth to fall back to default spacing.
public var minWidth: CGFloat {
get { return style.minWidth }
set { style = style.copy(applyingMinWidth: newValue) }
}
/// Vertical spacing between the items. Equals to 1 point by default to match system appearance.
/// Use resetItemSpacing to fall back to default spacing.
public var itemSpacing: CGFloat {
get { return style.itemSpacing }
set { style = style.copy(applyingItemSpacing: newValue) }
}
/// The distance that index items are inset from the enclosing background view. The property
/// doesn't change the position of index items. Instead, it changes the size of the background view
/// to match the inset. In other words, the background view "wraps" the content. Affects intrinsic
/// content size.
/// Set inset value to CGFloat.max to make the background view fill all the available space.
/// Default value matches the system index appearance.
/// Use resetIndexInset to fall back to default inset.
/// Left and right values are flipped when using right-to-left user interface direction.
public var indexInset: UIEdgeInsets {
get { return style.indexInset }
set { style = style.copy(applyingIndexInset: newValue) }
}
/// The distance from the left (or right in case of right-to-left languages) border of the background view
/// for which index items are shifted inside it.
/// The property only affects the position of the index items and doesn't change the size of the background view.
/// Default value matches the system index appearance.
/// Use resetIndexOffset to fall back to default offset.
public var indexOffset: UIOffset {
get { return style.indexOffset }
set { style = style.copy(applyingIndexOffset: newValue) }
}
/// The list of all items provided by the data source.
public private(set) var items: [UIView] = []
/// Returns a set of items suitable for displaying within the current bounds. If there is not enough space
/// to display all the items provided by the data source, some of them are replaced with a special truncation item.
/// To customize the class of truncation item, use the corresponding TableViewIndexDataSource method.
public var displayedItems: [UIView] {
return indexView.items ?? []
}
private var truncation: Truncation<UIView>?
func setStyle(_ style:Style) {
self.style = style
}
private var style: Style! {
didSet {
applyItemAttributes()
setNeedsLayout()
}
}
private lazy var indexView: IndexView = { [unowned self] in
let view = IndexView()
self.addSubview(view)
return view
}()
// MARK: - Initialization
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
backgroundColor = UIColor.clear
style = Style(userInterfaceDirection: UIView.my_userInterfaceLayoutDirection(for: self))
backgroundView = BackgroundView()
isExclusiveTouch = true
isMultipleTouchEnabled = false
isAccessibilityElement = true
accessibilityTraits = UIAccessibilityTraits.adjustable
accessibilityLabel = NSLocalizedString("Table index", comment: "Accessibility title for the section index control")
}
// MARK: - Updates
/// Forces table index to reload its items. This causes table index to discard its current items
/// and refill itself from the data source.
public func reloadData() {
items = queryItems()
truncation = queryTruncation()
applyItemAttributes()
setNeedsLayout()
}
private func queryItems() -> [UIView] {
return dataSource != nil ? dataSource!.indexItems(for: self) : []
}
private func queryTruncation() -> Truncation<UIView>? {
guard let dataSource = dataSource else {
return nil
}
var truncationItemClass = TruncationItem.self
// Check if the data source provides a custom class for truncation item
if dataSource.responds(to: #selector(TableViewIndexDataSource.truncationItemClass(for:))) {
truncationItemClass = dataSource.truncationItemClass!(for: self) as! TruncationItem.Type
}
// Now we now the item class and can create truncation items on demand
return Truncation(items: items, truncationItemFactory: {
return truncationItemClass.init()
})
}
private func applyItemAttributes() {
for item in items {
item.applyAttributes(style)
}
}
private func selectIndex(_ index: Int) {
guard index != currentIndex else { return }
currentIndex = index
if let delegate = self.delegate
, delegate.responds(to: #selector(TableViewIndexDelegate.tableViewIndex(_:didSelect:at:))) {
let shouldProduceFeedback = delegate.tableViewIndex!(self, didSelect: items[index], at: index)
if shouldProduceFeedback {
notifyFeedbackGenerator()
}
}
let currentItem = items[index]
let titleText: String
if let labelText = currentItem.accessibilityLabel {
titleText = labelText
} else if let labelText = (currentItem as? UILabel)?.text {
titleText = labelText
} else {
titleText = String.localizedStringWithFormat(NSLocalizedString("Section %d", comment: "Accessibility title for a numbered section"), currentIndex + 1)
}
let selectedText = NSLocalizedString("Selected", comment: "Accessibility title for the selected state")
UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: "\(titleText), \(selectedText)")
}
// MARK: - Layout
/// Returns a drawing area for the index items.
public func indexRect() -> CGRect {
return indexView.frame
}
/// Returns a drawing area for the background view.
public func backgroundRect() -> CGRect {
return backgroundView.frame
}
open override func layoutSubviews() {
super.layoutSubviews()
var visibleItems = items
if let truncation = truncation {
visibleItems = truncation.truncate(forHeight: bounds.height, style: style)
}
let layout = Layout(items: visibleItems, style: style, bounds: bounds)
indexView.frame = layout.contentFrame
backgroundView.frame = layout.backgroundFrame
indexView.reload(with: visibleItems, layout: layout.itemLayout)
}
override open var intrinsicContentSize: CGSize {
let layout = ItemLayout(items: items, style: style)
let width = layout.size.width + style.indexInset.left + style.indexInset.right
let minWidth: CGFloat = CGFloat(self.minWidth)
return CGSize(width: max(width, minWidth), height: UIView.noIntrinsicMetric)
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: intrinsicContentSize.width, height: size.height)
}
@available(iOS 9.0, *)
open override var semanticContentAttribute: UISemanticContentAttribute {
get { return super.semanticContentAttribute }
set {
super.semanticContentAttribute = newValue
style = style.copy(applyingUserInterfaceDirection: UIView.my_userInterfaceLayoutDirection(for: self))
}
}
// MARK: - Style
/// Resets font to default value to match the system index appearance.
public func resetFont() {
style = Style(userInterfaceDirection: style.userInterfaceDirection, itemSpacing: style.itemSpacing, indexInset: style.indexInset, indexOffset: style.indexOffset)
}
/// Resets itemSpacing to default value to match the system index appearance.
public func resetItemSpacing() {
style = Style(userInterfaceDirection: style.userInterfaceDirection, font: style.font, indexInset: style.indexInset, indexOffset: style.indexOffset)
}
/// Resets indexInset to default value to match the system index appearance.
public func resetIndexInset() {
style = Style(userInterfaceDirection: style.userInterfaceDirection, font: style.font, itemSpacing: style.itemSpacing, indexOffset: style.indexOffset)
}
/// Resets indexOffset to default value to match the system index appearance.
public func resetIndexOffset() {
style = Style(userInterfaceDirection: style.userInterfaceDirection, font: style.font, itemSpacing: style.itemSpacing, indexInset: style.indexInset)
}
/// Convenience method to reset basic styling to match the system index appearance.
/// This includes background, font, itemSpacing, indexInset and indexOffset.
public func resetAppearance() {
style = Style(userInterfaceDirection: style.userInterfaceDirection)
backgroundView = nil
}
// MARK: - Touches
private var currentTouch: UITouch?
private var currentIndex: Int = 0
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first , bounds.contains(touch.location(in: self)) {
beginTouch(touch)
processTouch(touch)
}
super.touchesBegan(touches, with: event)
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = currentTouch , touches.contains(touch) {
processTouch(touch)
}
super.touchesMoved(touches, with: event)
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = currentTouch , touches.contains(touch) {
finalizeTouch()
}
super.touchesEnded(touches, with: event)
}
override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = currentTouch, touches.contains(touch) {
finalizeTouch()
}
super.touchesCancelled(touches, with: event)
}
private func beginTouch(_ touch: UITouch) {
currentTouch = touch
isHighlighted = true
prepareFeedbackGenerator()
}
private func processTouch(_ touch: UITouch) {
if items.isEmpty {
return
}
let location = touch.location(in: indexView)
let progress = max(0, min(location.y / indexView.bounds.height, 0.9999))
let idx = Int(floor(progress * CGFloat(items.count)))
if idx == currentIndex {
return
}
selectIndex(idx)
}
private func finalizeTouch() {
currentTouch = nil
isHighlighted = false
cleanupFeedbackGenerator()
}
// Prevent iOS 13 modal pan gesture (or really any pan gesture) from firing when touched
open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let _ = gestureRecognizer.self as? UIPanGestureRecognizer {
return false
} else {
return true
}
}
// MARK: - Haptic Feedback support
@available(iOS 10.0, *)
private var feedbackGenerator: UISelectionFeedbackGenerator {
if feedbackGeneratorInstance == nil {
feedbackGeneratorInstance = UISelectionFeedbackGenerator()
}
return feedbackGeneratorInstance as! UISelectionFeedbackGenerator
}
private var feedbackGeneratorInstance: Any? = nil
private func prepareFeedbackGenerator() {
if #available(iOS 10.0, *) {
feedbackGenerator.prepare()
}
}
private func notifyFeedbackGenerator() {
if #available(iOS 10.0, *) {
feedbackGenerator.selectionChanged()
feedbackGenerator.prepare()
}
}
private func cleanupFeedbackGenerator() {
if #available(iOS 10.0, *) {
feedbackGeneratorInstance = nil
}
}
// MARK: - Accessibility support
open override func accessibilityIncrement() {
let newIndex = currentIndex - 1
if newIndex >= 0 {
selectIndex(newIndex)
}
}
open override func accessibilityDecrement() {
let newIndex = currentIndex + 1
if newIndex < items.count {
selectIndex(newIndex)
}
}
}
// MARK: - Protocols
@objc(MYTableViewIndexDataSource)
public protocol TableViewIndexDataSource : NSObjectProtocol {
/// Provides a set of items to display in the table index. The library provides
/// a default set of views tuned for displaying text, images, search indicator and
/// truncation items.
/// You can use any UIView subclass as an item basically, though using UITableView
/// is not recommended :)
/// Check IndexItem protocol for item customization points.
@objc(indexItemsForTableViewIndex:)
func indexItems(for tableViewIndex: TableViewIndex) -> [UIView]
/// Provides a class for truncation items. Truncation items are useful when there's not enough
/// space for displaying all the items provided by the data source. When this happens, table
/// index omits some of the items from being displayed and inserts one or more truncation items
/// instead.
/// Table index uses TruncationItem class by default, which is tuned to match the native index
/// appearance.
@objc(truncationItemClassForTableViewIndex:)
optional func truncationItemClass(for tableViewIndex: TableViewIndex) -> AnyClass
}
@objc(MYTableViewIndexDelegate)
public protocol TableViewIndexDelegate : NSObjectProtocol {
/// Called as a result of recognizing an index touch. Can be used to scroll table/collection view to
/// a corresponding section.
/// Return true to produce a haptic feedback (iPhone 7 with iOS 10 or later).
@objc(tableViewIndex:didSelectItem:atIndex:)
optional func tableViewIndex(_ tableViewIndex: TableViewIndex, didSelect item: UIView, at index: Int) -> Bool
}
// MARK: - IB support
private var strongDataSourceKey = 0
@IBDesignable
extension TableViewIndex {
class TableDataSource : NSObject, TableViewIndexDataSource {
func indexItems(for tableViewIndex: TableViewIndex) -> [UIView] {
return UILocalizedIndexedCollation.current().sectionIndexTitles.map{ title -> UIView in
return StringItem(text: title)
}
}
}
open override func prepareForInterfaceBuilder() {
let strongDataSource = TableDataSource()
setAssociatedObject(self, key: &strongDataSourceKey, value: strongDataSource, policy: .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
dataSource = strongDataSource
}
}
| mit | 2ba1c50e7b166208c03f478554a31257 | 36.130531 | 169 | 0.653518 | 5.295992 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKitUI/helper/RxTripKit/TKBuzzRealTime+Rx.swift | 1 | 3149 | //
// TKBuzzRealTime+Rx.swift
// TripKit
//
// Created by Adrian Schönig on 03.04.19.
// Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import RxSwift
import TripKit
extension TKRealTimeFetcher: ReactiveCompatible {}
extension Reactive where Base: TKRealTimeFetcher {
/// Stream real-time updates for the trip
///
/// - Parameters:
/// - trip: The trip to update
/// - updateInterval: The frequency at which the trip should be updated (default is every 10 seconds)
/// - active: Optional stream whether updates should keep being performed, e.g., you can create a bunch of these, but only the active one will be updated. It's expected that these go back and forth between `true` and `false`
///
/// - returns: Stream of the trip, *whenever* it gets updated, i.e., if there's no update the stream won't fire.
public static func streamUpdates(_ trip: Trip, updateInterval: DispatchTimeInterval = .seconds(10), active: Observable<Bool> = .just(true)) -> Observable<Trip> {
guard trip.wantsRealTimeUpdates else { return .never() }
return active
.flatMapLatest { active -> Observable<Int> in
if active {
return Observable<Int>
.interval(updateInterval, scheduler: MainScheduler.instance)
.startWith(0) // update as soon as we become active
} else {
return .never()
}
}
.map { _ in trip }
.filter { $0.managedObjectContext != nil && $0.wantsRealTimeUpdates }
.flatMapLatest(Self.update)
.filter(\.1)
.map { trip, _ in trip }
}
/// Perform one-off real-time update of the provided trip
///
/// No need to call this if `trip.wantsRealTimeUpdates == false`. It'd just complete immediately.
///
/// - Parameter trip: The trip to update
///
/// - returns: One-off callback with the update. Note that the `Trip` object returned in the callback will always be the same object provided to the method, i.e., trips are updated in-place.
public static func update(_ trip: Trip) -> Single<(Trip, didUpdate: Bool)> {
guard trip.wantsRealTimeUpdates else {
TKLog.debug("Don't bother calling this for trips that don't want updates")
return .just((trip, false))
}
return Single.create { subscriber in
TKTripFetcher.update(trip) { result in
subscriber(result.map { ($0.0, $0.didUpdate)} )
}
return Disposables.create()
}
}
/// Perform one-off updates of the visible trips of each trip group
///
/// - Parameter tripGroups: Trip groups, where only the visible trip will be updated
///
/// - returns: Progress of the update, but it won't indicate which trips did get updated
public static func update(tripGroups: [TripGroup]) -> Observable<TKRealTimeUpdateProgress<Void>> {
let trips = tripGroups
.compactMap(\.visibleTrip)
.filter(\.wantsRealTimeUpdates)
let individualUpdates = trips
.map(update)
.map { $0.asObservable() }
return Observable
.combineLatest(individualUpdates) { _ in .updated(()) }
.startWith(.updating)
}
}
| apache-2.0 | b7cb4fe47d9a97f9e6819c6bc0377bdb | 35.172414 | 228 | 0.660311 | 4.235532 | false | false | false | false |
henry0312/KonachanFrame | KonachanFrame/PreferencesController.swift | 1 | 3057 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Tsukasa ŌMOTO <[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.
*/
/* This file is available under an MIT license. */
import Cocoa
class PreferencesController: NSWindowController {
@IBOutlet var textField : NSTextField!
@IBOutlet var slider : NSSlider!
var timeInterval: Double!
override init(window: NSWindow?) {
super.init(window: window)
// Initialization code here.
}
/**
* work around
* http://stackoverflow.com/questions/24220638/subclassing-nswindowcontroller-in-swift-and-initwindownibname
*/
override init() { super.init() }
required init?(coder: NSCoder) { super.init(coder: coder) }
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
timeInterval = (NSApplication.sharedApplication().delegate as AppDelegate).konachanController.timeInterval
//timeInterval = (NSApp.delegate as AppDelegate).konachanController.timeInterval
textField.doubleValue = timeInterval / 60
slider.doubleValue = timeInterval / 60
}
func windowWillClose(notification: NSNotification!) {
let konachanController = (NSApplication.sharedApplication().delegate as AppDelegate).konachanController
//let konachanController = (NSApp.delegate as AppDelegate).konachanController
if self.timeInterval != konachanController.timeInterval {
// Update timeInterval
konachanController.stopTimer()
konachanController.timeInterval = self.timeInterval
konachanController.startTimer()
}
}
@IBAction func takeTimeInterval(sender : AnyObject) {
let newValue = (sender.doubleValue < 3) ? 3 : sender.doubleValue
timeInterval = newValue * 60
textField.doubleValue = newValue
slider.doubleValue = newValue
}
}
| mit | 8ac6cd9f825491760965a9b0bc080883 | 39.746667 | 134 | 0.717605 | 4.952998 | false | false | false | false |
RuiAAPeres/PageMenu | Classes/CAPSPageMenu.swift | 1 | 51527 | // CAPSPageMenu.swift
//
// Niklas Fahl
//
// Copyright (c) 2014 The Board of Trustees of The University of Alabama All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// Neither the name of the University nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import UIKit
@objc public protocol CAPSPageMenuDelegate {
// MARK: - Delegate functions
optional func willMoveToPage(controller: UIViewController, index: Int)
optional func didMoveToPage(controller: UIViewController, index: Int)
}
class MenuItemView: UIView {
// MARK: - Menu item view
var titleLabel : UILabel?
var menuItemSeparator : UIView?
func setUpMenuItemView(menuItemWidth: CGFloat, menuScrollViewHeight: CGFloat, indicatorHeight: CGFloat, separatorPercentageHeight: CGFloat, separatorWidth: CGFloat, separatorRoundEdges: Bool, menuItemSeparatorColor: UIColor) {
titleLabel = UILabel(frame: CGRectMake(0.0, 0.0, menuItemWidth, menuScrollViewHeight - indicatorHeight))
menuItemSeparator = UIView(frame: CGRectMake(menuItemWidth - (separatorWidth / 2), floor(menuScrollViewHeight * ((1.0 - separatorPercentageHeight) / 2.0)), separatorWidth, floor(menuScrollViewHeight * separatorPercentageHeight)))
menuItemSeparator!.backgroundColor = menuItemSeparatorColor
if separatorRoundEdges {
menuItemSeparator!.layer.cornerRadius = menuItemSeparator!.frame.width / 2
}
menuItemSeparator!.hidden = true
self.addSubview(menuItemSeparator!)
self.addSubview(titleLabel!)
}
func setTitleText(text: NSString) {
if titleLabel != nil {
titleLabel!.text = text as String
titleLabel!.numberOfLines = 0
titleLabel!.sizeToFit()
}
}
}
public enum CAPSPageMenuOption {
case SelectionIndicatorHeight(CGFloat)
case MenuItemSeparatorWidth(CGFloat)
case ScrollMenuBackgroundColor(UIColor)
case ViewBackgroundColor(UIColor)
case BottomMenuHairlineColor(UIColor)
case SelectionIndicatorColor(UIColor)
case MenuItemSeparatorColor(UIColor)
case MenuMargin(CGFloat)
case MenuHeight(CGFloat)
case SelectedMenuItemLabelColor(UIColor)
case UnselectedMenuItemLabelColor(UIColor)
case UseMenuLikeSegmentedControl(Bool)
case MenuItemSeparatorRoundEdges(Bool)
case MenuItemFont(UIFont)
case MenuItemSeparatorPercentageHeight(CGFloat)
case MenuItemWidth(CGFloat)
case EnableHorizontalBounce(Bool)
case AddBottomMenuHairline(Bool)
case MenuItemWidthBasedOnTitleTextWidth(Bool)
case ScrollAnimationDurationOnMenuItemTap(Int)
case CenterMenuItems(Bool)
case HideTopMenuBar(Bool)
}
public class CAPSPageMenu: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
// MARK: - Properties
let menuScrollView = UIScrollView()
let controllerScrollView = UIScrollView()
var controllerArray : [UIViewController] = []
var menuItems : [MenuItemView] = []
var menuItemWidths : [CGFloat] = []
public var menuHeight : CGFloat = 34.0
public var menuMargin : CGFloat = 15.0
public var menuItemWidth : CGFloat = 111.0
public var selectionIndicatorHeight : CGFloat = 3.0
var totalMenuItemWidthIfDifferentWidths : CGFloat = 0.0
public var scrollAnimationDurationOnMenuItemTap : Int = 500 // Millisecons
var startingMenuMargin : CGFloat = 0.0
var selectionIndicatorView : UIView = UIView()
var currentPageIndex : Int = 0
var lastPageIndex : Int = 0
public var selectionIndicatorColor : UIColor = UIColor.whiteColor()
public var selectedMenuItemLabelColor : UIColor = UIColor.whiteColor()
public var unselectedMenuItemLabelColor : UIColor = UIColor.lightGrayColor()
public var scrollMenuBackgroundColor : UIColor = UIColor.blackColor()
public var viewBackgroundColor : UIColor = UIColor.whiteColor()
public var bottomMenuHairlineColor : UIColor = UIColor.whiteColor()
public var menuItemSeparatorColor : UIColor = UIColor.lightGrayColor()
public var menuItemFont : UIFont = UIFont.systemFontOfSize(15.0)
public var menuItemSeparatorPercentageHeight : CGFloat = 0.2
public var menuItemSeparatorWidth : CGFloat = 0.5
public var menuItemSeparatorRoundEdges : Bool = false
public var addBottomMenuHairline : Bool = true
public var menuItemWidthBasedOnTitleTextWidth : Bool = false
public var useMenuLikeSegmentedControl : Bool = false
public var centerMenuItems : Bool = false
public var enableHorizontalBounce : Bool = true
public var hideTopMenuBar : Bool = false
var currentOrientationIsPortrait : Bool = true
var pageIndexForOrientationChange : Int = 0
var didLayoutSubviewsAfterRotation : Bool = false
var didScrollAlready : Bool = false
var lastControllerScrollViewContentOffset : CGFloat = 0.0
var lastScrollDirection : CAPSPageMenuScrollDirection = .Other
var startingPageForScroll : Int = 0
var didTapMenuItemToScroll : Bool = false
var pagesAddedDictionary : [Int : Int] = [:]
public weak var delegate : CAPSPageMenuDelegate?
var tapTimer : NSTimer?
enum CAPSPageMenuScrollDirection : Int {
case Left
case Right
case Other
}
// MARK: - View life cycle
/**
Initialize PageMenu with view controllers
- parameter viewControllers: List of view controllers that must be subclasses of UIViewController
- parameter frame: Frame for page menu view
- parameter options: Dictionary holding any customization options user might want to set
*/
public init(viewControllers: [UIViewController], frame: CGRect, options: [String: AnyObject]?) {
super.init(nibName: nil, bundle: nil)
controllerArray = viewControllers
self.view.frame = frame
}
public convenience init(viewControllers: [UIViewController], frame: CGRect, pageMenuOptions: [CAPSPageMenuOption]?) {
self.init(viewControllers:viewControllers, frame:frame, options:nil)
if let options = pageMenuOptions {
for option in options {
switch (option) {
case let .SelectionIndicatorHeight(value):
selectionIndicatorHeight = value
case let .MenuItemSeparatorWidth(value):
menuItemSeparatorWidth = value
case let .ScrollMenuBackgroundColor(value):
scrollMenuBackgroundColor = value
case let .ViewBackgroundColor(value):
viewBackgroundColor = value
case let .BottomMenuHairlineColor(value):
bottomMenuHairlineColor = value
case let .SelectionIndicatorColor(value):
selectionIndicatorColor = value
case let .MenuItemSeparatorColor(value):
menuItemSeparatorColor = value
case let .MenuMargin(value):
menuMargin = value
case let .MenuHeight(value):
menuHeight = value
case let .SelectedMenuItemLabelColor(value):
selectedMenuItemLabelColor = value
case let .UnselectedMenuItemLabelColor(value):
unselectedMenuItemLabelColor = value
case let .UseMenuLikeSegmentedControl(value):
useMenuLikeSegmentedControl = value
case let .MenuItemSeparatorRoundEdges(value):
menuItemSeparatorRoundEdges = value
case let .MenuItemFont(value):
menuItemFont = value
case let .MenuItemSeparatorPercentageHeight(value):
menuItemSeparatorPercentageHeight = value
case let .MenuItemWidth(value):
menuItemWidth = value
case let .EnableHorizontalBounce(value):
enableHorizontalBounce = value
case let .AddBottomMenuHairline(value):
addBottomMenuHairline = value
case let .MenuItemWidthBasedOnTitleTextWidth(value):
menuItemWidthBasedOnTitleTextWidth = value
case let .ScrollAnimationDurationOnMenuItemTap(value):
scrollAnimationDurationOnMenuItemTap = value
case let .CenterMenuItems(value):
centerMenuItems = value
case let .HideTopMenuBar(value):
hideTopMenuBar = value
}
}
if hideTopMenuBar {
addBottomMenuHairline = false
menuHeight = 0.0
}
}
setUpUserInterface()
if menuScrollView.subviews.count == 0 {
configureUserInterface()
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Container View Controller
public override func shouldAutomaticallyForwardAppearanceMethods() -> Bool {
return true
}
public override func shouldAutomaticallyForwardRotationMethods() -> Bool {
return true
}
// MARK: - UI Setup
func setUpUserInterface() {
let viewsDictionary = ["menuScrollView":menuScrollView, "controllerScrollView":controllerScrollView]
// Set up controller scroll view
controllerScrollView.pagingEnabled = true
controllerScrollView.translatesAutoresizingMaskIntoConstraints = false
controllerScrollView.alwaysBounceHorizontal = enableHorizontalBounce
controllerScrollView.bounces = enableHorizontalBounce
controllerScrollView.frame = CGRectMake(0.0, menuHeight, self.view.frame.width, self.view.frame.height)
self.view.addSubview(controllerScrollView)
let controllerScrollView_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|[controllerScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let controllerScrollView_constraint_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:|[controllerScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
self.view.addConstraints(controllerScrollView_constraint_H)
self.view.addConstraints(controllerScrollView_constraint_V)
// Set up menu scroll view
menuScrollView.translatesAutoresizingMaskIntoConstraints = false
menuScrollView.frame = CGRectMake(0.0, 0.0, self.view.frame.width, menuHeight)
self.view.addSubview(menuScrollView)
let menuScrollView_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|[menuScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let menuScrollView_constraint_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:[menuScrollView(\(menuHeight))]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
self.view.addConstraints(menuScrollView_constraint_H)
self.view.addConstraints(menuScrollView_constraint_V)
// Add hairline to menu scroll view
if addBottomMenuHairline {
let menuBottomHairline : UIView = UIView()
menuBottomHairline.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(menuBottomHairline)
let menuBottomHairline_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|[menuBottomHairline]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["menuBottomHairline":menuBottomHairline])
let menuBottomHairline_constraint_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(menuHeight)-[menuBottomHairline(0.5)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["menuBottomHairline":menuBottomHairline])
self.view.addConstraints(menuBottomHairline_constraint_H)
self.view.addConstraints(menuBottomHairline_constraint_V)
menuBottomHairline.backgroundColor = bottomMenuHairlineColor
}
// Disable scroll bars
menuScrollView.showsHorizontalScrollIndicator = false
menuScrollView.showsVerticalScrollIndicator = false
controllerScrollView.showsHorizontalScrollIndicator = false
controllerScrollView.showsVerticalScrollIndicator = false
// Set background color behind scroll views and for menu scroll view
self.view.backgroundColor = viewBackgroundColor
menuScrollView.backgroundColor = scrollMenuBackgroundColor
}
func configureUserInterface() {
// Add tap gesture recognizer to controller scroll view to recognize menu item selection
let menuItemTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleMenuItemTap:"))
menuItemTapGestureRecognizer.numberOfTapsRequired = 1
menuItemTapGestureRecognizer.numberOfTouchesRequired = 1
menuItemTapGestureRecognizer.delegate = self
menuScrollView.addGestureRecognizer(menuItemTapGestureRecognizer)
// Set delegate for controller scroll view
controllerScrollView.delegate = self
// When the user taps the status bar, the scroll view beneath the touch which is closest to the status bar will be scrolled to top,
// but only if its `scrollsToTop` property is YES, its delegate does not return NO from `shouldScrollViewScrollToTop`, and it is not already at the top.
// If more than one scroll view is found, none will be scrolled.
// Disable scrollsToTop for menu and controller scroll views so that iOS finds scroll views within our pages on status bar tap gesture.
menuScrollView.scrollsToTop = false;
controllerScrollView.scrollsToTop = false;
// Configure menu scroll view
if useMenuLikeSegmentedControl {
menuScrollView.scrollEnabled = false
menuScrollView.contentSize = CGSizeMake(self.view.frame.width, menuHeight)
menuMargin = 0.0
} else {
menuScrollView.contentSize = CGSizeMake((menuItemWidth + menuMargin) * CGFloat(controllerArray.count) + menuMargin, menuHeight)
}
// Configure controller scroll view content size
controllerScrollView.contentSize = CGSizeMake(self.view.frame.width * CGFloat(controllerArray.count), 0.0)
var index : CGFloat = 0.0
for controller in controllerArray {
if index == 0.0 {
// Add first two controllers to scrollview and as child view controller
addPageAtIndex(0)
}
// Set up menu item for menu scroll view
var menuItemFrame : CGRect = CGRect()
if useMenuLikeSegmentedControl {
menuItemFrame = CGRectMake(self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), 0.0, CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), menuHeight)
} else if menuItemWidthBasedOnTitleTextWidth {
let controllerTitle : String? = controller.title
let titleText : String = controllerTitle != nil ? controllerTitle! : "Menu \(Int(index) + 1)"
let itemWidthRect : CGRect = (titleText as NSString).boundingRectWithSize(CGSizeMake(1000, 1000), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:menuItemFont], context: nil)
menuItemWidth = itemWidthRect.width
menuItemFrame = CGRectMake(totalMenuItemWidthIfDifferentWidths + menuMargin + (menuMargin * index), 0.0, menuItemWidth, menuHeight)
totalMenuItemWidthIfDifferentWidths += itemWidthRect.width
menuItemWidths.append(itemWidthRect.width)
} else {
if centerMenuItems && index == 0.0 {
startingMenuMargin = ((self.view.frame.width - ((CGFloat(controllerArray.count) * menuItemWidth) + (CGFloat(controllerArray.count - 1) * menuMargin))) / 2.0) - menuMargin
if startingMenuMargin < 0.0 {
startingMenuMargin = 0.0
}
menuItemFrame = CGRectMake(startingMenuMargin + menuMargin, 0.0, menuItemWidth, menuHeight)
} else {
menuItemFrame = CGRectMake(menuItemWidth * index + menuMargin * (index + 1) + startingMenuMargin, 0.0, menuItemWidth, menuHeight)
}
}
let menuItemView : MenuItemView = MenuItemView(frame: menuItemFrame)
if useMenuLikeSegmentedControl {
menuItemView.setUpMenuItemView(CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor)
} else {
menuItemView.setUpMenuItemView(menuItemWidth, menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor)
}
// Configure menu item label font if font is set by user
menuItemView.titleLabel!.font = menuItemFont
menuItemView.titleLabel!.textAlignment = NSTextAlignment.Center
menuItemView.titleLabel!.textColor = unselectedMenuItemLabelColor
// Set title depending on if controller has a title set
if controller.title != nil {
menuItemView.titleLabel!.text = controller.title!
} else {
menuItemView.titleLabel!.text = "Menu \(Int(index) + 1)"
}
// Add separator between menu items when using as segmented control
if useMenuLikeSegmentedControl {
if Int(index) < controllerArray.count - 1 {
menuItemView.menuItemSeparator!.hidden = false
}
}
// Add menu item view to menu scroll view
menuScrollView.addSubview(menuItemView)
menuItems.append(menuItemView)
index++
}
// Set new content size for menu scroll view if needed
if menuItemWidthBasedOnTitleTextWidth {
menuScrollView.contentSize = CGSizeMake((totalMenuItemWidthIfDifferentWidths + menuMargin) + CGFloat(controllerArray.count) * menuMargin, menuHeight)
}
// Set selected color for title label of selected menu item
if menuItems.count > 0 {
if menuItems[currentPageIndex].titleLabel != nil {
menuItems[currentPageIndex].titleLabel!.textColor = selectedMenuItemLabelColor
}
}
// Configure selection indicator view
var selectionIndicatorFrame : CGRect = CGRect()
if useMenuLikeSegmentedControl {
selectionIndicatorFrame = CGRectMake(0.0, menuHeight - selectionIndicatorHeight, self.view.frame.width / CGFloat(controllerArray.count), selectionIndicatorHeight)
} else if menuItemWidthBasedOnTitleTextWidth {
selectionIndicatorFrame = CGRectMake(menuMargin, menuHeight - selectionIndicatorHeight, menuItemWidths[0], selectionIndicatorHeight)
} else {
if centerMenuItems {
selectionIndicatorFrame = CGRectMake(startingMenuMargin + menuMargin, menuHeight - selectionIndicatorHeight, menuItemWidth, selectionIndicatorHeight)
} else {
selectionIndicatorFrame = CGRectMake(menuMargin, menuHeight - selectionIndicatorHeight, menuItemWidth, selectionIndicatorHeight)
}
}
selectionIndicatorView = UIView(frame: selectionIndicatorFrame)
selectionIndicatorView.backgroundColor = selectionIndicatorColor
menuScrollView.addSubview(selectionIndicatorView)
if menuItemWidthBasedOnTitleTextWidth && centerMenuItems {
self.configureMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems()
let leadingAndTrailingMargin = self.getMarginForMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems()
selectionIndicatorView.frame = CGRectMake(leadingAndTrailingMargin, menuHeight - selectionIndicatorHeight, menuItemWidths[0], selectionIndicatorHeight)
}
}
// Adjusts the menu item frames to size item width based on title text width and center all menu items in the center
// if the menuItems all fit in the width of the view. Otherwise, it will adjust the frames so that the menu items
// appear as if only menuItemWidthBasedOnTitleTextWidth is true.
private func configureMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() {
// only center items if the combined width is less than the width of the entire view's bounds
if menuScrollView.contentSize.width < CGRectGetWidth(self.view.bounds) {
// compute the margin required to center the menu items
let leadingAndTrailingMargin = self.getMarginForMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems()
// adjust the margin of each menu item to make them centered
for (index, menuItem) in menuItems.enumerate() {
let controllerTitle = controllerArray[index].title!
let itemWidthRect = controllerTitle.boundingRectWithSize(CGSizeMake(1000, 1000), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:menuItemFont], context: nil)
menuItemWidth = itemWidthRect.width
var margin: CGFloat
if index == 0 {
// the first menu item should use the calculated margin
margin = leadingAndTrailingMargin
} else {
// the other menu items should use the menuMargin
let previousMenuItem = menuItems[index-1]
let previousX = CGRectGetMaxX(previousMenuItem.frame)
margin = previousX + menuMargin
}
menuItem.frame = CGRectMake(margin, 0.0, menuItemWidth, menuHeight)
}
} else {
// the menuScrollView.contentSize.width exceeds the view's width, so layout the menu items normally (menuItemWidthBasedOnTitleTextWidth)
for (index, menuItem) in menuItems.enumerate() {
var menuItemX: CGFloat
if index == 0 {
menuItemX = menuMargin
} else {
menuItemX = CGRectGetMaxX(menuItems[index-1].frame) + menuMargin
}
menuItem.frame = CGRectMake(menuItemX, 0.0, CGRectGetWidth(menuItem.bounds), CGRectGetHeight(menuItem.bounds))
}
}
}
// Returns the size of the left and right margins that are neccessary to layout the menuItems in the center.
private func getMarginForMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() -> CGFloat {
let menuItemsTotalWidth = menuScrollView.contentSize.width - menuMargin * 2
let leadingAndTrailingMargin = (CGRectGetWidth(self.view.bounds) - menuItemsTotalWidth) / 2
return leadingAndTrailingMargin
}
// MARK: - Scroll view delegate
public func scrollViewDidScroll(scrollView: UIScrollView) {
if !didLayoutSubviewsAfterRotation {
if scrollView.isEqual(controllerScrollView) {
if scrollView.contentOffset.x >= 0.0 && scrollView.contentOffset.x <= (CGFloat(controllerArray.count - 1) * self.view.frame.width) {
if (currentOrientationIsPortrait && UIApplication.sharedApplication().statusBarOrientation.isPortrait) || (!currentOrientationIsPortrait && UIApplication.sharedApplication().statusBarOrientation.isLandscape) {
// Check if scroll direction changed
if !didTapMenuItemToScroll {
if didScrollAlready {
var newScrollDirection : CAPSPageMenuScrollDirection = .Other
if (CGFloat(startingPageForScroll) * scrollView.frame.width > scrollView.contentOffset.x) {
newScrollDirection = .Right
} else if (CGFloat(startingPageForScroll) * scrollView.frame.width < scrollView.contentOffset.x) {
newScrollDirection = .Left
}
if newScrollDirection != .Other {
if lastScrollDirection != newScrollDirection {
let index : Int = newScrollDirection == .Left ? currentPageIndex + 1 : currentPageIndex - 1
if index >= 0 && index < controllerArray.count {
// Check dictionary if page was already added
if pagesAddedDictionary[index] != index {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
}
}
}
lastScrollDirection = newScrollDirection
}
if !didScrollAlready {
if (lastControllerScrollViewContentOffset > scrollView.contentOffset.x) {
if currentPageIndex != controllerArray.count - 1 {
// Add page to the left of current page
let index : Int = currentPageIndex - 1
if pagesAddedDictionary[index] != index && index < controllerArray.count && index >= 0 {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
lastScrollDirection = .Right
}
} else if (lastControllerScrollViewContentOffset < scrollView.contentOffset.x) {
if currentPageIndex != 0 {
// Add page to the right of current page
let index : Int = currentPageIndex + 1
if pagesAddedDictionary[index] != index && index < controllerArray.count && index >= 0 {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
lastScrollDirection = .Left
}
}
didScrollAlready = true
}
lastControllerScrollViewContentOffset = scrollView.contentOffset.x
}
var ratio : CGFloat = 1.0
// Calculate ratio between scroll views
ratio = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width)
if menuScrollView.contentSize.width > self.view.frame.width {
var offset : CGPoint = menuScrollView.contentOffset
offset.x = controllerScrollView.contentOffset.x * ratio
menuScrollView.setContentOffset(offset, animated: false)
}
// Calculate current page
let width : CGFloat = controllerScrollView.frame.size.width;
let page : Int = Int((controllerScrollView.contentOffset.x + (0.5 * width)) / width)
// Update page if changed
if page != currentPageIndex {
lastPageIndex = currentPageIndex
currentPageIndex = page
if pagesAddedDictionary[page] != page && page < controllerArray.count && page >= 0 {
addPageAtIndex(page)
pagesAddedDictionary[page] = page
}
if !didTapMenuItemToScroll {
// Add last page to pages dictionary to make sure it gets removed after scrolling
if pagesAddedDictionary[lastPageIndex] != lastPageIndex {
pagesAddedDictionary[lastPageIndex] = lastPageIndex
}
// Make sure only up to 3 page views are in memory when fast scrolling, otherwise there should only be one in memory
let indexLeftTwo : Int = page - 2
if pagesAddedDictionary[indexLeftTwo] == indexLeftTwo {
pagesAddedDictionary.removeValueForKey(indexLeftTwo)
removePageAtIndex(indexLeftTwo)
}
let indexRightTwo : Int = page + 2
if pagesAddedDictionary[indexRightTwo] == indexRightTwo {
pagesAddedDictionary.removeValueForKey(indexRightTwo)
removePageAtIndex(indexRightTwo)
}
}
}
// Move selection indicator view when swiping
moveSelectionIndicator(page)
}
} else {
var ratio : CGFloat = 1.0
ratio = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width)
if menuScrollView.contentSize.width > self.view.frame.width {
var offset : CGPoint = menuScrollView.contentOffset
offset.x = controllerScrollView.contentOffset.x * ratio
menuScrollView.setContentOffset(offset, animated: false)
}
}
}
} else {
didLayoutSubviewsAfterRotation = false
// Move selection indicator view when swiping
moveSelectionIndicator(currentPageIndex)
}
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if scrollView.isEqual(controllerScrollView) {
// Call didMoveToPage delegate function
let currentController = controllerArray[currentPageIndex]
delegate?.didMoveToPage?(currentController, index: currentPageIndex)
// Remove all but current page after decelerating
for key in pagesAddedDictionary.keys {
if key != currentPageIndex {
removePageAtIndex(key)
}
}
didScrollAlready = false
startingPageForScroll = currentPageIndex
// Empty out pages in dictionary
pagesAddedDictionary.removeAll(keepCapacity: false)
}
}
func scrollViewDidEndTapScrollingAnimation() {
// Call didMoveToPage delegate function
let currentController = controllerArray[currentPageIndex]
delegate?.didMoveToPage?(currentController, index: currentPageIndex)
// Remove all but current page after decelerating
for key in pagesAddedDictionary.keys {
if key != currentPageIndex {
removePageAtIndex(key)
}
}
startingPageForScroll = currentPageIndex
didTapMenuItemToScroll = false
// Empty out pages in dictionary
pagesAddedDictionary.removeAll(keepCapacity: false)
}
// MARK: - Handle Selection Indicator
func moveSelectionIndicator(pageIndex: Int) {
if pageIndex >= 0 && pageIndex < controllerArray.count {
UIView.animateWithDuration(0.15, animations: { () -> Void in
var selectionIndicatorWidth : CGFloat = self.selectionIndicatorView.frame.width
var selectionIndicatorX : CGFloat = 0.0
if self.useMenuLikeSegmentedControl {
selectionIndicatorX = CGFloat(pageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count))
selectionIndicatorWidth = self.view.frame.width / CGFloat(self.controllerArray.count)
} else if self.menuItemWidthBasedOnTitleTextWidth {
selectionIndicatorWidth = self.menuItemWidths[pageIndex]
selectionIndicatorX = CGRectGetMinX(self.menuItems[pageIndex].frame)
} else {
if self.centerMenuItems && pageIndex == 0 {
selectionIndicatorX = self.startingMenuMargin + self.menuMargin
} else {
selectionIndicatorX = self.menuItemWidth * CGFloat(pageIndex) + self.menuMargin * CGFloat(pageIndex + 1) + self.startingMenuMargin
}
}
self.selectionIndicatorView.frame = CGRectMake(selectionIndicatorX, self.selectionIndicatorView.frame.origin.y, selectionIndicatorWidth, self.selectionIndicatorView.frame.height)
// Switch newly selected menu item title label to selected color and old one to unselected color
if self.menuItems.count > 0 {
if self.menuItems[self.lastPageIndex].titleLabel != nil && self.menuItems[self.currentPageIndex].titleLabel != nil {
self.menuItems[self.lastPageIndex].titleLabel!.textColor = self.unselectedMenuItemLabelColor
self.menuItems[self.currentPageIndex].titleLabel!.textColor = self.selectedMenuItemLabelColor
}
}
})
}
}
// MARK: - Tap gesture recognizer selector
func handleMenuItemTap(gestureRecognizer : UITapGestureRecognizer) {
let tappedPoint : CGPoint = gestureRecognizer.locationInView(menuScrollView)
if tappedPoint.y < menuScrollView.frame.height {
// Calculate tapped page
var itemIndex : Int = 0
if useMenuLikeSegmentedControl {
itemIndex = Int(tappedPoint.x / (self.view.frame.width / CGFloat(controllerArray.count)))
} else if menuItemWidthBasedOnTitleTextWidth {
var menuItemLeftBound: CGFloat
var menuItemRightBound: CGFloat
if centerMenuItems {
menuItemLeftBound = CGRectGetMinX(menuItems[0].frame)
menuItemRightBound = CGRectGetMaxX(menuItems[menuItems.count-1].frame)
if (tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound) {
for (index, _) in controllerArray.enumerate() {
menuItemLeftBound = CGRectGetMinX(menuItems[index].frame)
menuItemRightBound = CGRectGetMaxX(menuItems[index].frame)
if tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound {
itemIndex = index
break
}
}
}
} else {
// Base case being first item
menuItemLeftBound = 0.0
menuItemRightBound = menuItemWidths[0] + menuMargin + (menuMargin / 2)
if !(tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound) {
for i in 1...controllerArray.count - 1 {
menuItemLeftBound = menuItemRightBound + 1.0
menuItemRightBound = menuItemLeftBound + menuItemWidths[i] + menuMargin
if tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound {
itemIndex = i
break
}
}
}
}
} else {
let rawItemIndex : CGFloat = ((tappedPoint.x - startingMenuMargin) - menuMargin / 2) / (menuMargin + menuItemWidth)
// Prevent moving to first item when tapping left to first item
if rawItemIndex < 0 {
itemIndex = -1
} else {
itemIndex = Int(rawItemIndex)
}
}
if itemIndex >= 0 && itemIndex < controllerArray.count {
// Update page if changed
if itemIndex != currentPageIndex {
startingPageForScroll = itemIndex
lastPageIndex = currentPageIndex
currentPageIndex = itemIndex
didTapMenuItemToScroll = true
// Add pages in between current and tapped page if necessary
let smallerIndex : Int = lastPageIndex < currentPageIndex ? lastPageIndex : currentPageIndex
let largerIndex : Int = lastPageIndex > currentPageIndex ? lastPageIndex : currentPageIndex
if smallerIndex + 1 != largerIndex {
for index in (smallerIndex + 1)...(largerIndex - 1) {
if pagesAddedDictionary[index] != index {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
}
}
addPageAtIndex(itemIndex)
// Add page from which tap is initiated so it can be removed after tap is done
pagesAddedDictionary[lastPageIndex] = lastPageIndex
}
// Move controller scroll view when tapping menu item
let duration : Double = Double(scrollAnimationDurationOnMenuItemTap) / Double(1000)
UIView.animateWithDuration(duration, animations: { () -> Void in
let xOffset : CGFloat = CGFloat(itemIndex) * self.controllerScrollView.frame.width
self.controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: self.controllerScrollView.contentOffset.y), animated: false)
})
if tapTimer != nil {
tapTimer!.invalidate()
}
let timerInterval : NSTimeInterval = Double(scrollAnimationDurationOnMenuItemTap) * 0.001
tapTimer = NSTimer.scheduledTimerWithTimeInterval(timerInterval, target: self, selector: "scrollViewDidEndTapScrollingAnimation", userInfo: nil, repeats: false)
}
}
}
// MARK: - Remove/Add Page
func addPageAtIndex(index : Int) {
// Call didMoveToPage delegate function
let currentController = controllerArray[index]
delegate?.willMoveToPage?(currentController, index: index)
let newVC = controllerArray[index]
newVC.willMoveToParentViewController(self)
newVC.view.frame = CGRectMake(self.view.frame.width * CGFloat(index), menuHeight, self.view.frame.width, self.view.frame.height - menuHeight)
self.addChildViewController(newVC)
self.controllerScrollView.addSubview(newVC.view)
newVC.didMoveToParentViewController(self)
}
func removePageAtIndex(index : Int) {
let oldVC = controllerArray[index]
oldVC.willMoveToParentViewController(nil)
oldVC.view.removeFromSuperview()
oldVC.removeFromParentViewController()
}
// MARK: - Orientation Change
override public func viewDidLayoutSubviews() {
// Configure controller scroll view content size
controllerScrollView.contentSize = CGSizeMake(self.view.frame.width * CGFloat(controllerArray.count), self.view.frame.height - menuHeight)
let oldCurrentOrientationIsPortrait : Bool = currentOrientationIsPortrait
currentOrientationIsPortrait = UIApplication.sharedApplication().statusBarOrientation.isPortrait
if (oldCurrentOrientationIsPortrait && UIDevice.currentDevice().orientation.isLandscape) || (!oldCurrentOrientationIsPortrait && UIDevice.currentDevice().orientation.isPortrait) {
didLayoutSubviewsAfterRotation = true
//Resize menu items if using as segmented control
if useMenuLikeSegmentedControl {
menuScrollView.contentSize = CGSizeMake(self.view.frame.width, menuHeight)
// Resize selectionIndicator bar
let selectionIndicatorX : CGFloat = CGFloat(currentPageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count))
let selectionIndicatorWidth : CGFloat = self.view.frame.width / CGFloat(self.controllerArray.count)
selectionIndicatorView.frame = CGRectMake(selectionIndicatorX, self.selectionIndicatorView.frame.origin.y, selectionIndicatorWidth, self.selectionIndicatorView.frame.height)
// Resize menu items
var index : Int = 0
for item : MenuItemView in menuItems as [MenuItemView] {
item.frame = CGRectMake(self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), 0.0, self.view.frame.width / CGFloat(controllerArray.count), menuHeight)
item.titleLabel!.frame = CGRectMake(0.0, 0.0, self.view.frame.width / CGFloat(controllerArray.count), menuHeight)
item.menuItemSeparator!.frame = CGRectMake(item.frame.width - (menuItemSeparatorWidth / 2), item.menuItemSeparator!.frame.origin.y, item.menuItemSeparator!.frame.width, item.menuItemSeparator!.frame.height)
index++
}
} else if menuItemWidthBasedOnTitleTextWidth && centerMenuItems {
self.configureMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems()
let selectionIndicatorX = CGRectGetMinX(menuItems[currentPageIndex].frame)
selectionIndicatorView.frame = CGRectMake(selectionIndicatorX, menuHeight - selectionIndicatorHeight, menuItemWidths[currentPageIndex], selectionIndicatorHeight)
} else if centerMenuItems {
startingMenuMargin = ((self.view.frame.width - ((CGFloat(controllerArray.count) * menuItemWidth) + (CGFloat(controllerArray.count - 1) * menuMargin))) / 2.0) - menuMargin
if startingMenuMargin < 0.0 {
startingMenuMargin = 0.0
}
let selectionIndicatorX : CGFloat = self.menuItemWidth * CGFloat(currentPageIndex) + self.menuMargin * CGFloat(currentPageIndex + 1) + self.startingMenuMargin
selectionIndicatorView.frame = CGRectMake(selectionIndicatorX, self.selectionIndicatorView.frame.origin.y, self.selectionIndicatorView.frame.width, self.selectionIndicatorView.frame.height)
// Recalculate frame for menu items if centered
var index : Int = 0
for item : MenuItemView in menuItems as [MenuItemView] {
if index == 0 {
item.frame = CGRectMake(startingMenuMargin + menuMargin, 0.0, menuItemWidth, menuHeight)
} else {
item.frame = CGRectMake(menuItemWidth * CGFloat(index) + menuMargin * CGFloat(index + 1) + startingMenuMargin, 0.0, menuItemWidth, menuHeight)
}
index++
}
}
for view : UIView in controllerScrollView.subviews {
view.frame = CGRectMake(self.view.frame.width * CGFloat(currentPageIndex), menuHeight, controllerScrollView.frame.width, self.view.frame.height - menuHeight)
}
let xOffset : CGFloat = CGFloat(self.currentPageIndex) * controllerScrollView.frame.width
controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: controllerScrollView.contentOffset.y), animated: false)
let ratio : CGFloat = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width)
if menuScrollView.contentSize.width > self.view.frame.width {
var offset : CGPoint = menuScrollView.contentOffset
offset.x = controllerScrollView.contentOffset.x * ratio
menuScrollView.setContentOffset(offset, animated: false)
}
}
// Hsoi 2015-02-05 - Running on iOS 7.1 complained: "'NSInternalInconsistencyException', reason: 'Auto Layout
// still required after sending -viewDidLayoutSubviews to the view controller. ViewController's implementation
// needs to send -layoutSubviews to the view to invoke auto layout.'"
//
// http://stackoverflow.com/questions/15490140/auto-layout-error
//
// Given the SO answer and caveats presented there, we'll call layoutIfNeeded() instead.
self.view.layoutIfNeeded()
}
// MARK: - Move to page index
/**
Move to page at index
- parameter index: Index of the page to move to
*/
public func moveToPage(index: Int) {
if index >= 0 && index < controllerArray.count {
// Update page if changed
if index != currentPageIndex {
startingPageForScroll = index
lastPageIndex = currentPageIndex
currentPageIndex = index
didTapMenuItemToScroll = true
// Add pages in between current and tapped page if necessary
let smallerIndex : Int = lastPageIndex < currentPageIndex ? lastPageIndex : currentPageIndex
let largerIndex : Int = lastPageIndex > currentPageIndex ? lastPageIndex : currentPageIndex
if smallerIndex + 1 != largerIndex {
for i in (smallerIndex + 1)...(largerIndex - 1) {
if pagesAddedDictionary[i] != i {
addPageAtIndex(i)
pagesAddedDictionary[i] = i
}
}
}
addPageAtIndex(index)
// Add page from which tap is initiated so it can be removed after tap is done
pagesAddedDictionary[lastPageIndex] = lastPageIndex
}
// Move controller scroll view when tapping menu item
let duration : Double = Double(scrollAnimationDurationOnMenuItemTap) / Double(1000)
UIView.animateWithDuration(duration, animations: { () -> Void in
let xOffset : CGFloat = CGFloat(index) * self.controllerScrollView.frame.width
self.controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: self.controllerScrollView.contentOffset.y), animated: false)
})
}
}
}
| bsd-3-clause | f8b47ff70c990c00cd8986906f1f45af | 51.524975 | 388 | 0.598735 | 6.739079 | false | false | false | false |
yeziahehe/Gank | Pods/JTAppleCalendar/Sources/InternalQueryFunctions.swift | 1 | 21453 | //
// InternalQueryFunctions.swift
//
// Copyright (c) 2016-2017 JTAppleCalendar (https://github.com/patchthecode/JTAppleCalendar)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
extension JTAppleCalendarView {
func validForwardAndBackwordSelectedIndexes(forIndexPath indexPath: IndexPath) -> Set<IndexPath> {
var retval: Set<IndexPath> = []
if let validForwardIndex = calendarViewLayout.indexPath(direction: .next, of: indexPath.section, item: indexPath.item),
validForwardIndex.section == indexPath.section,
selectedCellData[validForwardIndex] != nil {
retval.insert(validForwardIndex)
}
if
let validBackwardIndex = calendarViewLayout.indexPath(direction: .previous, of: indexPath.section, item: indexPath.item),
validBackwardIndex.section == indexPath.section,
selectedCellData[validBackwardIndex] != nil {
retval.insert(validBackwardIndex)
}
return retval
}
func targetPointForItemAt(indexPath: IndexPath) -> CGPoint? {
guard let targetCellFrame = calendarViewLayout.layoutAttributesForItem(at: indexPath)?.frame else { // Jt101 This was changed !!
return nil
}
let theTargetContentOffset: CGFloat = scrollDirection == .horizontal ? targetCellFrame.origin.x : targetCellFrame.origin.y
var fixedScrollSize: CGFloat = 0
switch scrollingMode {
case .stopAtEachSection, .stopAtEachCalendarFrame, .nonStopToSection:
if scrollDirection == .horizontal || (scrollDirection == .vertical && !calendarViewLayout.thereAreHeaders) {
// Horizontal has a fixed width.
// Vertical with no header has fixed height
fixedScrollSize = calendarViewLayout.sizeOfContentForSection(0)
} else {
// JT101 will remodel this code. Just a quick fix
fixedScrollSize = calendarViewLayout.sizeOfContentForSection(0)
}
case .stopAtEach(customInterval: let customVal):
fixedScrollSize = customVal
default:
break
}
var section = theTargetContentOffset / fixedScrollSize
let roundedSection = round(section)
if abs(roundedSection - section) < errorDelta { section = roundedSection }
section = CGFloat(Int(section))
let destinationRectOffset = (fixedScrollSize * section)
var x: CGFloat = 0
var y: CGFloat = 0
if scrollDirection == .horizontal {
x = destinationRectOffset
} else {
y = destinationRectOffset
}
return CGPoint(x: x, y: y)
}
func calendarOffsetIsAlreadyAtScrollPosition(forOffset offset: CGPoint) -> Bool {
var retval = false
// If the scroll is set to animate, and the target content
// offset is already on the screen, then the
// didFinishScrollingAnimation
// delegate will not get called. Once animation is on let's
// force a scroll so the delegate MUST get caalled
let theOffset = scrollDirection == .horizontal ? offset.x : offset.y
let divValue = scrollDirection == .horizontal ? frame.width : frame.height
let sectionForOffset = Int(theOffset / divValue)
let calendarCurrentOffset = scrollDirection == .horizontal ? contentOffset.x : contentOffset.y
if calendarCurrentOffset == theOffset || (scrollingMode.pagingIsEnabled() && (sectionForOffset == currentSection())) {
retval = true
}
return retval
}
func calendarOffsetIsAlreadyAtScrollPosition(forIndexPath indexPath: IndexPath) -> Bool {
var retval = false
// If the scroll is set to animate, and the target content offset
// is already on the screen, then the didFinishScrollingAnimation
// delegate will not get called. Once animation is on let's force
// a scroll so the delegate MUST get caalled
if let attributes = calendarViewLayout.layoutAttributesForItem(at: indexPath) { // JT101 this was changed!!!!
let layoutOffset: CGFloat
let calendarOffset: CGFloat
if scrollDirection == .horizontal {
layoutOffset = attributes.frame.origin.x
calendarOffset = contentOffset.x
} else {
layoutOffset = attributes.frame.origin.y
calendarOffset = contentOffset.y
}
if calendarOffset == layoutOffset {
retval = true
}
}
return retval
}
func indexPathOfdateCellCounterPath(_ date: Date, dateOwner: DateOwner) -> IndexPath? {
if (_cachedConfiguration.generateInDates == .off ||
_cachedConfiguration.generateInDates == .forFirstMonthOnly) &&
_cachedConfiguration.generateOutDates == .off {
return nil
}
var retval: IndexPath?
if dateOwner != .thisMonth {
// If the cell is anything but this month, then the cell belongs
// to either a previous of following month
// Get the indexPath of the counterpartCell
let counterPathIndex = pathsFromDates([date])
if !counterPathIndex.isEmpty {
retval = counterPathIndex[0]
}
} else {
// If the date does belong to this month,
// then lets find out if it has a counterpart date
if date < startOfMonthCache || date > endOfMonthCache {
return retval
}
guard let dayIndex = calendar.dateComponents([.day], from: date).day else {
print("Invalid Index")
return nil
}
if case 1...13 = dayIndex {
// then check the previous month
// get the index path of the last day of the previous month
let periodApart = calendar.dateComponents([.month], from: startOfMonthCache, to: date)
guard
let monthSectionIndex = periodApart.month, monthSectionIndex - 1 >= 0 else {
// If there is no previous months,
// there are no counterpart dates
return retval
}
let previousMonthInfo = monthInfo[monthSectionIndex - 1]
// If there are no postdates for the previous month,
// then there are no counterpart dates
if previousMonthInfo.outDates < 1 || dayIndex > previousMonthInfo.outDates {
return retval
}
guard
let prevMonth = calendar.date(byAdding: .month, value: -1, to: date),
let lastDayOfPrevMonth = calendar.endOfMonth(for: prevMonth) else {
assert(false, "Error generating date in indexPathOfdateCellCounterPath(). Contact the developer on github")
return retval
}
let indexPathOfLastDayOfPreviousMonth = pathsFromDates([lastDayOfPrevMonth])
if indexPathOfLastDayOfPreviousMonth.isEmpty {
print("out of range error in indexPathOfdateCellCounterPath() upper. This should not happen. Contact developer on github")
return retval
}
let lastDayIndexPath = indexPathOfLastDayOfPreviousMonth[0]
var section = lastDayIndexPath.section
var itemIndex = lastDayIndexPath.item + dayIndex
// Determine if the sections/item needs to be adjusted
let numberOfItemsInSection = collectionView(self, numberOfItemsInSection: section)
guard numberOfItemsInSection > 0 else {
assert(false, "Number of sections in calendar = 0. Possible fixes (1) is your calendar visible size 0,0? (2) is your calendar already loaded/visible?")
return nil
}
let extraSection = itemIndex / numberOfItemsInSection
let extraIndex = itemIndex % numberOfItemsInSection
section += extraSection
itemIndex = extraIndex
let reCalcRapth = IndexPath(item: itemIndex, section: section)
retval = reCalcRapth
} else if case 25...31 = dayIndex { // check the following month
let periodApart = calendar.dateComponents([.month], from: startOfMonthCache, to: date)
let monthSectionIndex = periodApart.month!
if monthSectionIndex + 1 >= monthInfo.count {
return retval
}
// If there is no following months, there are no counterpart dates
let followingMonthInfo = monthInfo[monthSectionIndex + 1]
if followingMonthInfo.inDates < 1 {
return retval
}
// If there are no predates for the following month then there are no counterpart dates
let lastDateOfCurrentMonth = calendar.endOfMonth(for: date)!
let lastDay = calendar.component(.day, from: lastDateOfCurrentMonth)
let section = followingMonthInfo.startSection
let index = dayIndex - lastDay + (followingMonthInfo.inDates - 1)
if index < 0 {
return retval
}
retval = IndexPath(item: index, section: section)
}
}
return retval
}
func sizesForMonthSection() -> [AnyHashable:CGFloat] {
var retval: [AnyHashable:CGFloat] = [:]
guard
let headerSizes = calendarDelegate?.calendarSizeForMonths(self),
headerSizes.defaultSize > 0 else {
return retval
}
// Build the default
retval["default"] = headerSizes.defaultSize
// Build the every-month data
if let allMonths = headerSizes.months {
for (size, months) in allMonths {
for month in months {
assert(retval[month] == nil, "You have duplicated months. Please revise your month size data.")
retval[month] = size
}
}
}
// Build the specific month data
if let specificSections = headerSizes.dates {
for (size, dateArray) in specificSections {
let paths = pathsFromDates(dateArray)
for path in paths {
retval[path.section] = size
}
}
}
return retval
}
func pathsFromDates(_ dates: [Date]) -> [IndexPath] {
var returnPaths: [IndexPath] = []
for date in dates {
if calendar.startOfDay(for: date) >= startOfMonthCache! && calendar.startOfDay(for: date) <= endOfMonthCache! {
let periodApart = calendar.dateComponents([.month], from: startOfMonthCache, to: date)
let day = calendar.dateComponents([.day], from: date).day!
guard let monthSectionIndex = periodApart.month else { continue }
let currentMonthInfo = monthInfo[monthSectionIndex]
if let indexPath = currentMonthInfo.indexPath(forDay: day) {
returnPaths.append(indexPath)
}
}
}
return returnPaths
}
func cellStateFromIndexPath(_ indexPath: IndexPath,
withDateInfo info: (date: Date, owner: DateOwner)? = nil,
cell: JTAppleCell? = nil,
isSelected: Bool? = nil,
selectionType: SelectionType? = nil) -> CellState {
let validDateInfo: (date: Date, owner: DateOwner)
if let nonNilDateInfo = info {
validDateInfo = nonNilDateInfo
} else {
guard let newDateInfo = dateOwnerInfoFromPath(indexPath) else {
developerError(string: "Error this should not be nil. Contact developer Jay on github by opening a request")
return CellState(isSelected: false,
text: "",
dateBelongsTo: .thisMonth,
date: Date(),
day: .sunday,
row: { return 0 },
column: { return 0 },
dateSection: { return (range: (Date(), Date()), month: 0, rowCount: 0) },
selectedPosition: {return .left},
cell: {return nil},
selectionType: nil)
}
validDateInfo = newDateInfo
}
let date = validDateInfo.date
let dateBelongsTo = validDateInfo.owner
let currentDay = calendar.component(.day, from: date)
let componentWeekDay = calendar.component(.weekday, from: date)
let cellText = String(describing: currentDay)
let dayOfWeek = DaysOfWeek(rawValue: componentWeekDay)!
let selectedPosition = { [unowned self] () -> SelectionRangePosition in
let selectedDates = self.selectedDatesSet
if !selectedDates.contains(date) || selectedDates.isEmpty { return .none }
let dateBefore = self._cachedConfiguration.calendar.date(byAdding: .day, value: -1, to: date)!
let dateAfter = self._cachedConfiguration.calendar.date(byAdding: .day, value: 1, to: date)!
let dateBeforeIsSelected = selectedDates.contains(dateBefore)
let dateAfterIsSelected = selectedDates.contains(dateAfter)
var position: SelectionRangePosition
if dateBeforeIsSelected, dateAfterIsSelected {
position = .middle
} else if !dateBeforeIsSelected, dateAfterIsSelected {
position = .left
} else if dateBeforeIsSelected, !dateAfterIsSelected {
position = .right
} else if !dateBeforeIsSelected, !dateAfterIsSelected {
position = .full
} else {
position = .none
}
return position
}
let cellState = CellState(
isSelected: isSelected ?? (selectedCellData[indexPath] != nil),
text: cellText,
dateBelongsTo: dateBelongsTo,
date: date,
day: dayOfWeek,
row: { return indexPath.item / maxNumberOfDaysInWeek },
column: { return indexPath.item % maxNumberOfDaysInWeek },
dateSection: { [unowned self] in
return self.monthInfoFromSection(indexPath.section)!
},
selectedPosition: selectedPosition,
cell: { return cell },
selectionType: selectionType
)
return cellState
}
func monthInfoFromSection(_ section: Int) -> (range: (start: Date, end: Date), month: Int, rowCount: Int)? {
guard let monthIndex = monthMap[section] else {
return nil
}
let monthData = monthInfo[monthIndex]
guard
let monthDataMapSection = monthData.sectionIndexMaps[section],
let indices = monthData.boundaryIndicesFor(section: monthDataMapSection) else {
return nil
}
let startIndexPath = IndexPath(item: indices.startIndex, section: section)
let endIndexPath = IndexPath(item: indices.endIndex, section: section)
guard
let startDate = dateOwnerInfoFromPath(startIndexPath)?.date,
let endDate = dateOwnerInfoFromPath(endIndexPath)?.date else {
return nil
}
if let monthDate = calendar.date(byAdding: .month, value: monthIndex, to: startDateCache) {
let monthNumber = calendar.dateComponents([.month], from: monthDate)
let numberOfRowsForSection = monthData.numberOfRows(for: section, developerSetRows: _cachedConfiguration.numberOfRows)
return ((startDate, endDate), monthNumber.month!, numberOfRowsForSection)
}
return nil
}
func dateSegmentInfoFrom(visible indexPaths: [IndexPath]) -> DateSegmentInfo {
var inDates = [(Date, IndexPath)]()
var monthDates = [(Date, IndexPath)]()
var outDates = [(Date, IndexPath)]()
for indexPath in indexPaths {
let info = dateOwnerInfoFromPath(indexPath)
if let validInfo = info {
switch validInfo.owner {
case .thisMonth:
monthDates.append((validInfo.date, indexPath))
case .previousMonthWithinBoundary, .previousMonthOutsideBoundary:
inDates.append((validInfo.date, indexPath))
default:
outDates.append((validInfo.date, indexPath))
}
}
}
let retval = DateSegmentInfo(indates: inDates, monthDates: monthDates, outdates: outDates)
return retval
}
func dateOwnerInfoFromPath(_ indexPath: IndexPath) -> (date: Date, owner: DateOwner)? { // Returns nil if date is out of scope
guard let monthIndex = monthMap[indexPath.section] else {
return nil
}
let monthData = monthInfo[monthIndex]
// Calculate the offset
let offSet: Int
var numberOfDaysToAddToOffset: Int = 0
switch monthData.sectionIndexMaps[indexPath.section]! {
case 0:
offSet = monthData.inDates
default:
offSet = 0
let currentSectionIndexMap = monthData.sectionIndexMaps[indexPath.section]!
numberOfDaysToAddToOffset = monthData.sections[0..<currentSectionIndexMap].reduce(0, +)
numberOfDaysToAddToOffset -= monthData.inDates
}
var dayIndex = 0
var dateOwner: DateOwner = .thisMonth
let date: Date?
if indexPath.item >= offSet && indexPath.item + numberOfDaysToAddToOffset < monthData.numberOfDaysInMonth + offSet {
// This is a month date
dayIndex = monthData.startDayIndex + indexPath.item - offSet + numberOfDaysToAddToOffset
date = calendar.date(byAdding: .day, value: dayIndex, to: startOfMonthCache)
} else if indexPath.item < offSet {
// This is a preDate
dayIndex = indexPath.item - offSet + monthData.startDayIndex
date = calendar.date(byAdding: .day, value: dayIndex, to: startOfMonthCache)
if date! < startOfMonthCache {
dateOwner = .previousMonthOutsideBoundary
} else {
dateOwner = .previousMonthWithinBoundary
}
} else {
// This is a postDate
dayIndex = monthData.startDayIndex - offSet + indexPath.item + numberOfDaysToAddToOffset
date = calendar.date(byAdding: .day, value: dayIndex, to: startOfMonthCache)
if date! > endOfMonthCache {
dateOwner = .followingMonthOutsideBoundary
} else {
dateOwner = .followingMonthWithinBoundary
}
}
guard let validDate = date else { return nil }
return (validDate, dateOwner)
}
func datesAtCurrentOffset(_ offset: CGPoint? = nil) -> DateSegmentInfo {
let rect: CGRect?
if let offset = offset {
rect = CGRect(x: offset.x, y: offset.y, width: frame.width, height: frame.height)
} else {
rect = nil
}
let emptySegment = DateSegmentInfo(indates: [], monthDates: [], outdates: [])
if !isCalendarLayoutLoaded {
return emptySegment
}
let cellAttributes = calendarViewLayout.elementsAtRect(excludeHeaders: true, from: rect)
let indexPaths: [IndexPath] = cellAttributes.map { $0.indexPath }.sorted()
return dateSegmentInfoFrom(visible: indexPaths)
}
}
| gpl-3.0 | 57bbc2331192c49c26f7ad7f6c71ca2e | 45.840611 | 171 | 0.588263 | 5.608627 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPress/WordPressTest/PostListFilterTests.swift | 2 | 2071 | import XCTest
@testable import WordPress
class PostListFilterTests: XCTestCase {
func testSortDescriptorForPublished() {
let filter = PostListFilter.publishedFilter()
let descriptors = filter.sortDescriptors
XCTAssertEqual(descriptors.count, 1)
XCTAssertEqual(descriptors[0].key, "date_created_gmt")
XCTAssertEqual(descriptors[0].ascending, false)
}
func testSortDescriptorForDrafs() {
let filter = PostListFilter.draftFilter()
let descriptors = filter.sortDescriptors
XCTAssertEqual(descriptors.count, 1)
XCTAssertEqual(descriptors[0].key, "dateModified")
XCTAssertEqual(descriptors[0].ascending, false)
}
func testSortDescriptorForScheduled() {
let filter = PostListFilter.scheduledFilter()
let descriptors = filter.sortDescriptors
XCTAssertEqual(descriptors.count, 1)
XCTAssertEqual(descriptors[0].key, "date_created_gmt")
XCTAssertEqual(descriptors[0].ascending, true)
}
func testSortDescriptorForTrashed() {
let filter = PostListFilter.trashedFilter()
let descriptors = filter.sortDescriptors
XCTAssertEqual(descriptors.count, 1)
XCTAssertEqual(descriptors[0].key, "date_created_gmt")
XCTAssertEqual(descriptors[0].ascending, false)
}
func testSectionIdentifiersMatchSortDescriptors() {
// Every filter must use the same field as the base for the sort
// descriptor and the sectionIdentifier.
//
// See https://github.com/wordpress-mobile/WordPress-iOS/issues/6476 for
// more background on the issue.
//
// This doesn't test anything that the above tests haven't tested before
// in theory, but is added as a safeguard, in case we add new filters.
for filter in PostListFilter.postListFilters() {
let descriptors = filter.sortDescriptors
XCTAssertEqual(descriptors.count, 1)
XCTAssertEqual(descriptors[0].key, filter.sortField.keyPath)
}
}
}
| gpl-2.0 | 02e26c1061420a5ac0000d151ed9181d | 37.351852 | 80 | 0.681796 | 5.026699 | false | true | false | false |
Johennes/firefox-ios | Storage/PageMetadata.swift | 1 | 1384 | /* 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
/*
* Value types representing a page's metadata
*/
public struct PageMetadata {
public let id: Int?
public let siteURL: String
public let mediaURL: String?
public let title: String?
public let description: String?
public let type: String?
public let providerName: String?
public init(id: Int?, siteURL: String, mediaURL: String?, title: String?, description: String?, type: String?, providerName: String?) {
self.id = id
self.siteURL = siteURL
self.mediaURL = mediaURL
self.title = title
self.description = description
self.type = type
self.providerName = providerName
}
public static func fromDictionary(dict: [String: AnyObject]) -> PageMetadata? {
guard let siteURL = dict["url"] as? String else {
return nil
}
return PageMetadata(id: nil, siteURL: siteURL, mediaURL: dict["image_url"] as? String,
title: dict["title"] as? String, description: dict["description"] as? String,
type: dict["type"] as? String, providerName: dict["provider_name"] as? String)
}
}
| mpl-2.0 | f91917d6e7ba6f47b246fb73170be52b | 35.421053 | 139 | 0.633671 | 4.407643 | false | false | false | false |
jpchmura/JPCPaperViewController | Source/PaperCollectionViewController.swift | 1 | 13661 | //
// PaperCollectionViewController.swift
// Planty
//
// Created by Jon Chmura on 1/17/15.
// Copyright (c) 2015 Thinkering. All rights reserved.
//
import UIKit
import pop
@objc public protocol PaperCollectionViewDataSource: UICollectionViewDataSource {
func registerReusableViews(collectionView: UICollectionView)
// TODO: Add blocks to assist with reloading data and batch updates
}
public class PaperCollectionViewController: UICollectionViewController, UINavigationControllerDelegate, UIGestureRecognizerDelegate, PaperCollectionViewDataSource, PaperTransitionControllerDelegate {
var transitionController: PaperTransitionController!
public var paperBackgroundView: PaperBackgroundView? {
get {
return self.collectionView?.backgroundView as? PaperBackgroundView
}
}
public var paperCollectionViewLayout: PaperMinimizedLayout? {
get {
return self.collectionView?.collectionViewLayout as? PaperMinimizedLayout
}
}
/// If you are using a data source object other than self set it here. It will need to be managed as! controllers are pushed and popped.
public var dataSource: PaperCollectionViewDataSource?
private var paperDataSource: PaperCollectionViewDataSource? {
get {
return self.collectionView!.dataSource as? PaperCollectionViewDataSource
}
}
/// Optionally provide a custom constructor for the full screen collection view.
/// If not provided a PaperFullScreenViewController will be created using this View Controller's data source.
/// If the layout of the provided collection view is not a PaperFullScreenLayout this is considered a programming error and will result in a failed assertion.
public var fullScreenViewControllerConstructor: ((activeSection: Int) -> PaperFullScreenViewController)?
private var sectionTransitionActive = false
public var activeSection: Int = 0 {
didSet {
if oldValue == activeSection {
return
}
if !self.sectionTransitionActive {
self.sectionTransitionActive = true
let newLayout = PaperMinimizedLayout()
newLayout.activeSection = activeSection
let layoutTransition = self.collectionView!.startInteractiveTransitionToCollectionViewLayout(newLayout, completion: { (completed, finished) -> Void in
self.sectionTransitionActive = false
self.collectionView!.contentOffset = CGPointZero
})
let springAnim = POPSpringAnimation()
springAnim.property = POPAnimatableProperty.propertyWithName("transitionProgress", initializer: { (prop: POPMutableAnimatableProperty!) -> Void in
prop.readBlock = { (me: AnyObject!, values: UnsafeMutablePointer<CGFloat>) -> Void in
values[0] = layoutTransition.transitionProgress
}
prop.writeBlock = { (me: AnyObject!, values: UnsafePointer<CGFloat>) -> Void in
layoutTransition.transitionProgress = values[0]
layoutTransition.invalidateLayout()
}
// Dynamics threshold: Docs aren't clear on this. Using their example value
prop.threshold = 0.01
}) as! POPAnimatableProperty
springAnim.velocity = 0
springAnim.toValue = 1
springAnim.completionBlock = { (anim: POPAnimation!, finish: Bool) -> Void in
self.collectionView!.finishInteractiveTransition()
(self.collectionViewLayout as? PaperMinimizedLayout)?.activeSection = self.activeSection
}
layoutTransition.pop_addAnimation(springAnim, forKey: "progressAnim")
}
}
}
// MARK: - View controller lifecycle
public override func loadView() {
super.loadView()
// We need to be the delegate so we can drive the push and pop
self.transitionController = PaperTransitionController(collectionView: self.collectionView!)
self.transitionController.delegate = self
self.automaticallyAdjustsScrollViewInsets = false
// We need to be the navigation controller delegate so we can provide our transition controller
self.navigationController?.delegate = self
self.navigationController?.navigationBarHidden = true
self.collectionView!.backgroundView = PaperBackgroundView(frame: CGRectZero)
// We need to be the delegate of the background collection view so we can drive section transitions
self.paperBackgroundView?.collectionView.delegate = self
}
public override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
// Our layout must be a PaperMinimized layout. If not this is a programming error
assert(self.collectionViewLayout is PaperMinimizedLayout, "The collectionViewLayout was not a PaperMinimized layout! This is a programming error. If you are using storyboards make sure you set the a custom layout type in the inspector")
}
// MARK: - Manage pushed view controllers
private func pushFullScreenViewController() {
var fullScreenVC: PaperFullScreenViewController!
if let constructor = self.fullScreenViewControllerConstructor {
fullScreenVC = constructor(activeSection: self.activeSection)
}
else {
let layout = PaperFullScreenLayout()
layout.activeSection = self.activeSection
fullScreenVC = PaperFullScreenViewController(collectionViewLayout: layout)
fullScreenVC.collectionView?.dataSource = self.collectionView?.dataSource
}
(fullScreenVC.collectionView?.dataSource as? PaperCollectionViewDataSource)?.registerReusableViews(fullScreenVC.collectionView!)
fullScreenVC.useLayoutToLayoutNavigationTransitions = true
self.navigationController?.pushViewController(fullScreenVC, animated: true)
}
// MARK: - Setup Transitions Layouts
public override func collectionView(collectionView: UICollectionView, transitionLayoutForOldLayout fromLayout: UICollectionViewLayout, newLayout toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout! {
if (fromLayout is PaperFullScreenLayout) || (toLayout is PaperFullScreenLayout) {
return PaperTransitionLayout(currentLayout: fromLayout, nextLayout: toLayout)
}
else {
let visibleCellAttr = fromLayout.layoutAttributesForElementsInRect(self.collectionView!.bounds) as! [UICollectionViewLayoutAttributes]
var rect = visibleCellAttr.first?.frame
var cellOffsetX: CGFloat = 0.0
var indexPaths = [NSIndexPath]()
var from = (fromLayout as! PaperMinimizedLayout).activeSection
var to = (toLayout as! PaperMinimizedLayout).activeSection
// Left
if from < to {
for attr in visibleCellAttr {
if CGRectGetMaxX(attr.frame) > CGRectGetMaxX(rect!) {
rect = attr.frame
}
indexPaths.append(attr.indexPath)
}
if let lastRect = rect {
cellOffsetX = CGRectGetMaxX(lastRect) - CGRectGetMaxX(self.collectionView!.bounds)
}
}
// Right
else {
for attr in visibleCellAttr {
if CGRectGetMinX(attr.frame) < CGRectGetMinX(rect!) {
rect = attr.frame
}
indexPaths.append(attr.indexPath)
}
if let lastRect = rect {
cellOffsetX = self.collectionView!.contentOffset.x - CGRectGetMinX(lastRect)
}
}
if cellOffsetX < 0 {
cellOffsetX = 0.0
}
let transitionLayout = PaperSectionTransitionLayout(currentLayout: fromLayout, nextLayout: toLayout)
transitionLayout.from = from
transitionLayout.to = to
transitionLayout.itemsVisible = indexPaths
transitionLayout.cellOffsetX = cellOffsetX
return transitionLayout
}
}
// MARK: - PaperTransitionControllerDelegate (Interactive / Animated Transitioning)
func interactionShouldBeginAtPoint(point: CGPoint) -> Bool {
return true
}
func interactionBeganAtPoint(point: CGPoint) {
if let viewController = self.navigationController?.topViewController {
if viewController is PaperCollectionViewController {
self.pushFullScreenViewController()
}
else {
self.navigationController?.popViewControllerAnimated(true)
}
}
}
func transitionProgress(progress: Float, toViewController: UICollectionViewController, fromViewController: UICollectionViewController, collectionView: UICollectionView) {
func dataSource(viewController: UICollectionViewController) -> UICollectionViewDataSource {
if let dataSource = (viewController as? PaperFullScreenViewController)?.dataSource {
return dataSource
}
else if let dataSource = (viewController as? PaperCollectionViewController)?.dataSource {
return dataSource
}
else {
return viewController
}
}
// When progress is greater than 50% set new data source
if progress > 0.5 {
collectionView.dataSource = dataSource(toViewController)
}
// Otherwise set from data source
else {
collectionView.dataSource = dataSource(fromViewController)
}
}
// MARK: - UINavigationControllerDelegate (Interactive / Animated Transitioning)
public func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if (animationController is PaperTransitionController) && ((animationController as! PaperTransitionController) == self.transitionController) {
return self.transitionController
}
return nil
}
public func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if !(fromVC is UICollectionViewController) || !(toVC is UICollectionViewController) || !self.transitionController.interactionActive {
return nil
}
self.transitionController.navigationOperation = operation
return self.transitionController
}
// MARK: - PaperCollectionViewDataSource
public func registerReusableViews(collectionView: UICollectionView) {
// Not implemented here
}
// MARK: UICollectionViewDelegate
public override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
public override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if collectionView == self.collectionView {
self.transitionController.pushCellAtIndexPath(indexPath)
}
}
// MARK: UIScrollViewDelegate (Section Transition)
// We will monitor scrolling keep sections in sync between the background collection view and the foreground collection view
public override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if scrollView == self.paperBackgroundView?.collectionView {
// The background view is expected to have one cell per section of the primary data source
// The item number of the background view equals the section number of our data source
let screenMidPoint = CGPointMake(scrollView.contentOffset.x + scrollView.frame.width * 0.5, scrollView.frame.height * 0.5)
let secIdx = self.paperBackgroundView!.collectionView.indexPathForItemAtPoint(screenMidPoint)?.item
// To be safe make sure we find a cell. There may be some edge cases where the user aggressively scrolls past the content in the background and we miss the cell. Thats fine we'll update when the collection view finishes bouncing.
if let secIdx = secIdx {
self.activeSection = secIdx
}
}
}
}
| mit | 1c444316df4766fca0638374d1e4d4df | 38.031429 | 288 | 0.636337 | 6.783019 | false | false | false | false |
apple/swift-log | 1 | 918 | // swift-tools-version:5.0
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Logging API open source project
//
// Copyright (c) 2018-2019 Apple Inc. and the Swift Logging API project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift Logging API project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import PackageDescription
let package = Package(
name: "swift-log",
products: [
.library(name: "Logging", targets: ["Logging"]),
],
targets: [
.target(
name: "Logging",
dependencies: []
),
.testTarget(
name: "LoggingTests",
dependencies: ["Logging"]
),
]
)
| apache-2.0 | d623f2b40e066aa5b9806ac021e2052d | 26.818182 | 80 | 0.503268 | 4.882979 | false | true | false | false |
|
eldesperado/SpareTimeAlarmApp | SpareTimeMusicApp/ThemeManager.swift | 1 | 3541 | //
// ThemeManager.swift
// SpareTimeAlarmApp
//
// Created by Pham Nguyen Nhat Trung on 8/27/15.
// Copyright (c) 2015 Pham Nguyen Nhat Trung. All rights reserved.
//
import UIKit
class ThemeManager: NSObject {
// Public Attributes
var stylesheet: ThemeComponent.Theme?
var currentThemeType: ThemeComponent.ThemeType?
// Constants
private let storedKeyInUserDefaults = "com.xmsofresh.SpareTimeAppAlarm.ThemeManager"
// MARK: Singleton
private static let sharedInstance = ThemeManager()
// MARK: Public Methods
func saveTheme(theme: ThemeComponent.ThemeType) {
if let newTheme = loadTheme(theme) {
// Update Stylesheet
stylesheet = newTheme
// Update current theme
currentThemeType = theme
// Save to NSUserDefaults
NSUserDefaults.standardUserDefaults().setValue(theme.getString(), forKey: storedKeyInUserDefaults)
NSUserDefaults.standardUserDefaults().synchronize()
// Post notification
postThemeUpdateNotification()
}
}
static func getSharedInstance() -> ThemeManager {
return sharedInstance
}
func getThemeComponent(component: ThemeComponent.ThemeAttribute) -> AnyObject? {
if let currentTheme = ThemeManager.sharedInstance.stylesheet,
attributeValue = currentTheme[component] {
switch (component) {
case .BackgroundColor:
return UIColor(rgba: attributeValue)
case .BackgroundImage:
return UIImage(named: attributeValue)
case .MandatoryColor:
return UIColor(rgba: attributeValue)
}
} else {
return nil
}
}
// MARK: Initialization
override init() {
super.init()
// Setup Theme
setup()
}
// MARK: Setup
private func setup() {
// Get Current Theme stored in userDefaults
let themeName: String = (NSUserDefaults.standardUserDefaults().objectForKey(storedKeyInUserDefaults) ?? ThemeComponent.ThemeType.Default.getString()) as! String
// Get the current theme type
if let currTheme = ThemeComponent.ThemeType(string: themeName) {
currentThemeType = currTheme
}
// Load stored stylesheet
if let theme = getStylesheetFromFile(themeName) {
stylesheet = theme
}
}
// Load Theme
private func loadTheme(theme: ThemeComponent.ThemeType) -> ThemeComponent.Theme? {
if let resultTheme: ThemeComponent.Theme = getStylesheetFromFile(theme.getString()) {
return resultTheme
} else {
return nil
}
}
private func loadTheme(stylesheetDictionary: NSDictionary) -> ThemeComponent.Theme {
var theme: ThemeComponent.Theme = [ThemeComponent.ThemeAttribute.BackgroundImage : "",
ThemeComponent.ThemeAttribute.BackgroundColor : "",
ThemeComponent.ThemeAttribute.MandatoryColor : ""]
for (key, value) in stylesheetDictionary {
if let k = ThemeComponent.ThemeAttribute(string: key as! String) {
theme.updateValue(value as! String, forKey: k)
}
}
return theme
}
private func postThemeUpdateNotification() {
ThemeObserver.post(sender: self)
}
// Helpers
private func getStylesheetFromFile(fileName: String) -> ThemeComponent.Theme? {
if let stylesheetPath = NSBundle.mainBundle().pathForResource(fileName, ofType: "plist") {
if let stylesheetData = NSDictionary(contentsOfFile: stylesheetPath) {
let stylesheet = loadTheme(stylesheetData)
return stylesheet
} else {
return nil
}
} else {
return nil
}
}
}
| mit | a3b66d57c8d9a378827309aaea2b58b8 | 28.508333 | 164 | 0.685117 | 5.022695 | false | false | false | false |
nathawes/swift | test/NameLookup/scope_map-astscopelookup.swift | 4 | 29087 | // REQUIRES: enable-astscope-lookup
// Note: test of the scope map. All of these tests are line- and
// column-sensitive, so any additions should go at the end.
struct S0 {
class InnerC0 { }
}
extension S0 {
}
class C0 {
}
enum E0 {
case C0
case C1(Int, Int)
}
struct GenericS0<T, U> {
}
func genericFunc0<T, U>(t: T, u: U, i: Int = 10) {
}
class ContainsGenerics0 {
init<T, U>(t: T, u: U) {
}
deinit {
}
}
typealias GenericAlias0<T> = [T]
#if arch(unknown)
struct UnknownArchStruct { }
#else
struct OtherArchStruct { }
#endif
func functionBodies1(a: Int, b: Int?) {
let (x1, x2) = (a, b),
(y1, y2) = (b, a)
let (z1, z2) = (a, a)
do {
let a1 = a
let a2 = a
do {
let b1 = b
let b2 = b
}
}
do {
let b1 = b
let b2 = b
}
func f(_ i: Int) -> Int { return i }
let f2 = f(_:)
struct S7 { }
typealias S7Alias = S7
if let b1 = b, let b2 = b {
let c1 = b
} else {
let c2 = b
}
guard let b1 = b, { $0 > 5 }(b1), let b2 = b else {
let c = 5
return
}
while let b3 = b, let b4 = b {
let c = 5
}
repeat { } while true;
for (x, y) in [(1, "hello"), (2, "world")] where x % 2 == 0 {
}
do {
try throwing()
} catch let mine as MyError where mine.value == 17 {
} catch {
}
switch MyEnum.second(1) {
case .second(let x) where x == 17:
break;
case .first:
break;
default:
break;
}
for (var i = 0; i != 10; i += 1) { }
}
func throwing() throws { }
struct MyError : Error {
var value: Int
}
enum MyEnum {
case first
case second(Int)
case third
}
struct StructContainsAbstractStorageDecls {
subscript (i: Int, j: Int) -> Int {
set {
}
get {
return i + j
}
}
var computed: Int {
get {
return 0
}
set {
}
}
}
class ClassWithComputedProperties {
var willSetProperty: Int = 0 {
willSet { }
}
var didSetProperty: Int = 0 {
didSet { }
}
}
func funcWithComputedProperties(i: Int) {
var computed: Int {
set {
}
get {
return 0
}
}, var (stored1, stored2) = (1, 2),
var alsoComputed: Int {
return 17
}
do { }
}
func closures() {
{ x, y in
return { $0 + $1 }(x, y)
}(1, 2) +
{ a, b in a * b }(3, 4)
}
{ closures() }()
func defaultArguments(i: Int = 1,
j: Int = { $0 + $1 }(1, 2)) {
func localWithDefaults(i: Int = 1,
j: Int = { $0 + $1 }(1, 2)) {
}
let a = i + j
{ $0 }(a)
}
struct PatternInitializers {
var (a, b) = (1, 2),
(c, d) = (1.5, 2.5)
}
protocol ProtoWithSubscript {
subscript(native: Int) -> Int { get set }
}
func localPatternsWithSharedType() {
let i, j, k: Int
}
class LazyProperties {
var value: Int = 17
lazy var prop: Int = self.value
}
func HasLabeledDo() {
label:
do {
for x in 0..<100 {
if x % 3 == 0 {
break label
}
}
}
}
// RUN: not %target-swift-frontend -dump-scope-maps expanded %s 2> %t.expanded
// RUN: %FileCheck -check-prefix CHECK-EXPANDED %s < %t.expanded
// CHECK-EXPANDED: ***Complete scope map***
// CHECK-EXPANDED-NEXT: ASTSourceFileScope {{.*}}, (uncached) [1:1 - 5{{[0-9]*}}:1] 'SOURCE_DIR{{[/]}}test{{[/]}}NameBinding{{[/]}}scope_map-astscopelookup.swift'
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [5:1 - 7:1] 'S0'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [5:11 - 7:1] 'S0'
// CHECK-EXPANDED-NEXT: `-NominalTypeDeclScope {{.*}}, [6:3 - 6:19] 'InnerC0'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [6:17 - 6:19] 'InnerC0'
// CHECK-EXPANDED-NEXT: |-ExtensionDeclScope {{.*}}, [9:1 - 10:1] 'S0'
// CHECK-EXPANDED-NEXT: `-ExtensionBodyScope {{.*}}, [9:14 - 10:1] 'S0'
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [12:1 - 13:1] 'C0'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [12:10 - 13:1] 'C0'
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [15:1 - 18:1] 'E0'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [15:9 - 18:1] 'E0'
// CHECK-EXPANDED-NEXT: |-EnumElementScope {{.*}}, [16:8 - 16:8]
// CHECK-EXPANDED-NEXT: `-EnumElementScope {{.*}}, [17:8 - 17:19]
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [17:10 - 17:19]
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [20:1 - 21:1] 'GenericS0'
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [20:17 - 21:1] param 0 'T'
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [20:17 - 21:1] param 1 'U'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [20:24 - 21:1] 'GenericS0'
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [23:1 - 24:1] 'genericFunc0(t:u:i:)'
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [23:18 - 24:1] param 0 'T'
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [23:18 - 24:1] param 1 'U'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [23:24 - 24:1]
// CHECK-EXPANDED-NEXT: |-DefaultArgumentInitializerScope {{.*}}, [23:46 - 23:46]
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [23:50 - 24:1]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [23:50 - 24:1]
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [26:1 - 32:1] 'ContainsGenerics0'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [26:25 - 32:1] 'ContainsGenerics0'
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [27:3 - 28:3] 'init(t:u:)'
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [27:7 - 28:3] param 0 'T'
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [27:7 - 28:3] param 1 'U'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [27:13 - 28:3]
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [27:26 - 28:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [27:26 - 28:3]
// CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [30:3 - 31:3] 'deinit'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [30:3 - 31:3]
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [30:10 - 31:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [30:10 - 31:3]
// CHECK-EXPANDED-NEXT: |-TypeAliasDeclScope {{.*}}, [34:1 - 34:32] <no extended nominal?!>
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [34:24 - 34:32] param 0 'T'
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [39:1 - 39:26] 'OtherArchStruct'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [39:24 - 39:26] 'OtherArchStruct'
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [42:1 - 101:1] 'functionBodies1(a:b:)'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [42:21 - 101:1]
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [42:39 - 101:1]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [42:39 - 101:1]
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [43:7 - 43:23] entry 0 'x1' 'x2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [43:18 - 43:23] entry 0 'x1' 'x2'
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [44:7 - 44:23] entry 1 'y1' 'y2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [44:18 - 44:23] entry 1 'y1' 'y2'
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [45:7 - 45:23] entry 0 'z1' 'z2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [45:18 - 45:23] entry 0 'z1' 'z2'
// CHECK-EXPANDED-NEXT: |-BraceStmtScope {{.*}}, [46:6 - 53:3]
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [47:9 - 47:14] entry 0 'a1'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [47:14 - 47:14] entry 0 'a1'
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [48:9 - 48:14] entry 0 'a2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [48:14 - 48:14] entry 0 'a2'
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [49:8 - 52:5]
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [50:11 - 50:16] entry 0 'b1'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [50:16 - 50:16] entry 0 'b1'
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [51:11 - 51:16] entry 0 'b2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [51:16 - 51:16] entry 0 'b2'
// CHECK-EXPANDED-NEXT: |-BraceStmtScope {{.*}}, [54:6 - 57:3]
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [55:9 - 55:14] entry 0 'b1'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [55:14 - 55:14] entry 0 'b1'
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [56:9 - 56:14] entry 0 'b2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [56:14 - 56:14] entry 0 'b2'
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [58:3 - 58:38] 'f(_:)'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [58:9 - 58:38]
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [58:27 - 58:38]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [58:27 - 58:38]
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [59:7 - 59:16] entry 0 'f2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [59:12 - 59:16] entry 0 'f2'
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [60:3 - 60:15] 'S7'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [60:13 - 60:15] 'S7'
// CHECK-EXPANDED-NEXT: |-TypeAliasDeclScope {{.*}}, [61:3 - 61:23] <no extended nominal?!>
// CHECK-EXPANDED-NEXT: |-IfStmtScope {{.*}}, [63:3 - 67:3]
// CHECK-EXPANDED-NEXT: |-ConditionalClauseScope, [63:6 - 65:3] index 0
// CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [63:18 - 65:3] let b1
// CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [63:18 - 65:3] index 1
// CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [63:29 - 65:3] let b2
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [63:29 - 65:3]
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [64:9 - 64:14] entry 0 'c1'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [64:14 - 64:14] entry 0 'c1'
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [65:10 - 67:3]
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [66:9 - 66:14] entry 0 'c2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [66:14 - 66:14] entry 0 'c2'
// CHECK-EXPANDED-NEXT: `-GuardStmtScope {{.*}}, [69:3 - 100:38]
// CHECK-EXPANDED-NEXT: |-ConditionalClauseScope, [69:9 - 69:53] index 0
// CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [69:21 - 69:53] let b1
// CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [69:21 - 69:53] index 1
// CHECK-EXPANDED-NEXT: |-WholeClosureScope {{.*}}, [69:21 - 69:30]
// CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [69:21 - 69:30]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [69:21 - 69:30]
// CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [69:37 - 69:53] index 2
// CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [69:53 - 69:53] let b2
// CHECK-EXPANDED-NEXT: |-BraceStmtScope {{.*}}, [69:53 - 72:3]
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [70:9 - 70:13] entry 0 'c'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [70:13 - 70:13] entry 0 'c'
// CHECK-EXPANDED-NEXT: `-LookupParentDiversionScope, [72:3 - 100:38]
// CHECK-EXPANDED-NEXT: |-WhileStmtScope {{.*}}, [74:3 - 76:3]
// CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [74:9 - 76:3] index 0
// CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [74:21 - 76:3] let b3
// CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [74:21 - 76:3] index 1
// CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [74:32 - 76:3] let b4
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [74:32 - 76:3]
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [75:9 - 75:13] entry 0 'c'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [75:13 - 75:13] entry 0 'c'
// CHECK-EXPANDED-NEXT: |-RepeatWhileScope {{.*}}, [78:3 - 78:20]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [78:10 - 78:12]
// CHECK-EXPANDED-NEXT: |-ForEachStmtScope {{.*}}, [80:3 - 82:3]
// CHECK-EXPANDED-NEXT: `-ForEachPatternScope, [80:52 - 82:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [80:63 - 82:3]
// CHECK-EXPANDED-NEXT: |-DoCatchStmtScope {{.*}}, [84:3 - 88:3]
// CHECK-EXPANDED-NEXT: |-BraceStmtScope {{.*}}, [84:6 - 86:3]
// CHECK-EXPANDED-NEXT: |-CatchStmtScope {{.*}}, [86:31 - 87:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [86:54 - 87:3]
// CHECK-EXPANDED-NEXT: `-CatchStmtScope {{.*}}, [87:11 - 88:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [87:11 - 88:3]
// CHECK-EXPANDED-NEXT: |-SwitchStmtScope {{.*}}, [90:3 - 99:3]
// CHECK-EXPANDED-NEXT: |-CaseStmtScope {{.*}}, [91:29 - 92:10]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [92:5 - 92:10]
// CHECK-EXPANDED-NEXT: |-CaseStmtScope {{.*}}, [95:5 - 95:10]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [95:5 - 95:10]
// CHECK-EXPANDED-NEXT: `-CaseStmtScope {{.*}}, [98:5 - 98:10]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [98:5 - 98:10]
// CHECK-EXPANDED-NEXT: `-ForEachStmtScope {{.*}}, [100:3 - 100:38]
// CHECK-EXPANDED-NEXT: `-ForEachPatternScope, [100:36 - 100:38]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [100:36 - 100:38]
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [103:1 - 103:26] 'throwing()'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [103:14 - 103:26]
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [103:24 - 103:26]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [103:24 - 103:26]
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [105:1 - 107:1] 'MyError'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [105:24 - 107:1] 'MyError'
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [106:7 - 106:14] entry 0 'value'
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [109:1 - 113:1] 'MyEnum'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [109:13 - 113:1] 'MyEnum'
// CHECK-EXPANDED-NEXT: |-EnumElementScope {{.*}}, [110:8 - 110:8]
// CHECK-EXPANDED-NEXT: |-EnumElementScope {{.*}}, [111:8 - 111:18]
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [111:14 - 111:18]
// CHECK-EXPANDED-NEXT: `-EnumElementScope {{.*}}, [112:8 - 112:8]
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [115:1 - 131:1] 'StructContainsAbstractStorageDecls'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [115:43 - 131:1] 'StructContainsAbstractStorageDecls'
// CHECK-EXPANDED-NEXT: |-SubscriptDeclScope {{.*}}, [116:3 - 122:3] main.(file).StructContainsAbstractStorageDecls.subscript(_:_:)@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:116:3
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [116:13 - 122:3]
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [117:5 - 118:5] '_'
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [117:9 - 118:5]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [117:9 - 118:5]
// CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [119:5 - 121:5] '_'
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [119:9 - 121:5]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [119:9 - 121:5]
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [124:21 - 130:3] entry 0 'computed'
// CHECK-EXPANDED-NEXT: `-VarDeclScope {{.*}}, [124:21 - 130:3] main.(file).StructContainsAbstractStorageDecls.computed@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:124:7
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [125:5 - 127:5] '_'
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [125:9 - 127:5]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [125:9 - 127:5]
// CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [128:5 - 129:5] '_'
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [128:9 - 129:5]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [128:9 - 129:5]
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [133:1 - 141:1] 'ClassWithComputedProperties'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [133:35 - 141:1] 'ClassWithComputedProperties'
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [134:7 - 136:3] entry 0 'willSetProperty'
// CHECK-EXPANDED-NEXT: |-PatternEntryInitializerScope {{.*}}, [134:30 - 134:30] entry 0 'willSetProperty'
// CHECK-EXPANDED-NEXT: `-VarDeclScope {{.*}}, [134:32 - 136:3] main.(file).ClassWithComputedProperties.willSetProperty@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:134:7
// CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [135:5 - 135:15] '_'
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [135:13 - 135:15]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [135:13 - 135:15]
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [138:7 - 140:3] entry 0 'didSetProperty'
// CHECK-EXPANDED-NEXT: |-PatternEntryInitializerScope {{.*}}, [138:29 - 138:29] entry 0 'didSetProperty'
// CHECK-EXPANDED-NEXT: `-VarDeclScope {{.*}}, [138:31 - 140:3] main.(file).ClassWithComputedProperties.didSetProperty@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:138:7
// CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [139:5 - 139:14] '_'
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [139:12 - 139:14]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [139:12 - 139:14]
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [143:1 - 156:1] 'funcWithComputedProperties(i:)'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [143:32 - 156:1]
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [143:41 - 156:1]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [143:41 - 156:1]
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [144:21 - 150:3] entry 0 'computed'
// CHECK-EXPANDED-NEXT: `-VarDeclScope {{.*}}, [144:21 - 150:3] main.(file).funcWithComputedProperties(i:).computed@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:144:7
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [145:5 - 146:5] '_'
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [145:9 - 146:5]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [145:9 - 146:5]
// CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [147:5 - 149:5] '_'
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [147:9 - 149:5]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [147:9 - 149:5]
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [150:6 - 150:36] entry 1 'stored1' 'stored2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [150:31 - 150:36] entry 1 'stored1' 'stored2'
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [151:25 - 153:3] entry 2 'alsoComputed'
// CHECK-EXPANDED-NEXT: `-VarDeclScope {{.*}}, [151:25 - 153:3] main.(file).funcWithComputedProperties(i:).alsoComputed@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:151:7
// CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [151:25 - 153:3] '_'
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [151:25 - 153:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [151:25 - 153:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [155:6 - 155:8]
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [158:1 - 163:1] 'closures()'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [158:14 - 163:1]
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [158:17 - 163:1]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [158:17 - 163:1]
// CHECK-EXPANDED-NEXT: |-WholeClosureScope {{.*}}, [159:3 - 161:3]
// CHECK-EXPANDED-NEXT: `-ClosureParametersScope {{.*}}, [159:5 - 161:3]
// CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [159:10 - 161:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [159:10 - 161:3]
// CHECK-EXPANDED-NEXT: `-WholeClosureScope {{.*}}, [160:12 - 160:22]
// CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [160:12 - 160:22]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [160:12 - 160:22]
// CHECK-EXPANDED-NEXT: `-WholeClosureScope {{.*}}, [162:3 - 162:19]
// CHECK-EXPANDED-NEXT: `-ClosureParametersScope {{.*}}, [162:5 - 162:19]
// CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [162:10 - 162:19]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [162:10 - 162:19]
// CHECK-EXPANDED-NEXT: `-TopLevelCodeScope {{.*}}, [165:1 - 195:1]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [165:1 - 195:1]
// CHECK-EXPANDED-NEXT: |-WholeClosureScope {{.*}}, [165:1 - 165:14]
// CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [165:1 - 165:14]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [165:1 - 165:14]
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [167:1 - 176:1] 'defaultArguments(i:j:)'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [167:22 - 176:1]
// CHECK-EXPANDED-NEXT: |-DefaultArgumentInitializerScope {{.*}}, [167:32 - 167:32]
// CHECK-EXPANDED-NEXT: |-DefaultArgumentInitializerScope {{.*}}, [168:32 - 168:48]
// CHECK-EXPANDED-NEXT: `-WholeClosureScope {{.*}}, [168:32 - 168:42]
// CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [168:32 - 168:42]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [168:32 - 168:42]
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [168:51 - 176:1]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [168:51 - 176:1]
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [170:3 - 172:3] 'localWithDefaults(i:j:)'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [170:25 - 172:3]
// CHECK-EXPANDED-NEXT: |-DefaultArgumentInitializerScope {{.*}}, [170:35 - 170:35]
// CHECK-EXPANDED-NEXT: |-DefaultArgumentInitializerScope {{.*}}, [171:35 - 171:51]
// CHECK-EXPANDED-NEXT: `-WholeClosureScope {{.*}}, [171:35 - 171:45]
// CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [171:35 - 171:45]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [171:35 - 171:45]
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [171:54 - 172:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [171:54 - 172:3]
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [174:7 - 175:11] entry 0 'a'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [174:11 - 175:11] entry 0 'a'
// CHECK-EXPANDED-NEXT: `-WholeClosureScope {{.*}}, [175:3 - 175:8]
// CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [175:3 - 175:8]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [175:3 - 175:8]
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [178:1 - 181:1] 'PatternInitializers'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [178:28 - 181:1] 'PatternInitializers'
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [179:7 - 179:21] entry 0 'a' 'b'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [179:16 - 179:21] entry 0 'a' 'b'
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [180:7 - 180:25] entry 1 'c' 'd'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [180:16 - 180:25] entry 1 'c' 'd'
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [183:1 - 185:1] 'ProtoWithSubscript'
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [183:29 - 185:1] param 0 'Self : ProtoWithSubscript'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [183:29 - 185:1] 'ProtoWithSubscript'
// CHECK-EXPANDED-NEXT: `-SubscriptDeclScope {{.*}}, [184:3 - 184:43] main.(file).ProtoWithSubscript.subscript(_:)@SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift:184:3
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [184:12 - 184:43]
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [184:35 - 184:35] '_'
// CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [184:39 - 184:39] '_'
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [187:1 - 189:1] 'localPatternsWithSharedType()'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [187:33 - 189:1]
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [187:36 - 189:1]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [187:36 - 189:1]
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [188:7 - 188:7] entry 0 'i'
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [188:10 - 188:10] entry 1 'j'
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [188:13 - 188:16] entry 2 'k'
// CHECK-EXPANDED-NEXT: `-NominalTypeDeclScope {{.*}}, [191:1 - 195:1] 'LazyProperties'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [191:22 - 195:1] 'LazyProperties'
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [192:7 - 192:20] entry 0 'value'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [192:20 - 192:20] entry 0 'value'
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [194:12 - 194:29] entry 0 'prop'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [194:24 - 194:29] entry 0 'prop'
// RUN: not %target-swift-frontend -dump-scope-maps 71:8,27:20,6:18,167:32,180:18,194:26 %s 2> %t.searches
// RUN: %FileCheck -check-prefix CHECK-SEARCHES %s < %t.searches
// CHECK-SEARCHES: ***Scope at 71:8***
// CHECK-SEARCHES-NEXT: BraceStmtScope {{.*}}, [69:53 - 7{{[0-9]}}:3]
// CHECK-SEARCHES-NEXT: Local bindings: c
// CHECK-SEARCHES-NEXT: ***Scope at 27:20***
// CHECK-SEARCHES-NEXT: ParameterListScope {{.*}}, [27:13 - 28:3]
// CHECK-SEARCHES-NEXT: ***Scope at 6:18***
// CHECK-SEARCHES-NEXT: NominalTypeBodyScope {{.*}}, [6:17 - 6:19] 'InnerC0'
// CHECK-SEARCHES-NEXT: {{.*}} Module name=main
// CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift"
// CHECK-SEARCHES-NEXT: {{.*}} StructDecl name=S0
// CHECK-SEARCHES-NEXT: {{.*}} ClassDecl name=InnerC0
// CHECK-SEARCHES-NEXT: ***Scope at 167:32***
// CHECK-SEARCHES-NEXT: DefaultArgumentInitializerScope {{.*}}, [167:32 - 167:32]
// CHECK-SEARCHES-NEXT: {{.*}} Module name=main
// CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift"
// CHECK-SEARCHES-NEXT: {{.*}} AbstractFunctionDecl name=defaultArguments(i:j:) : (Int, Int) -> ()
// CHECK-SEARCHES-NEXT: {{.*}} Initializer DefaultArgument index=0
// CHECK-SEARCHES-NEXT: ***Scope at 180:18***
// CHECK-SEARCHES-NEXT: PatternEntryInitializerScope {{.*}}, [180:16 - 180:25] entry 1 'c' 'd'
// CHECK-SEARCHES-NEXT: {{.*}} Module name=main
// CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift"
// CHECK-SEARCHES-NEXT: {{.*}} StructDecl name=PatternInitializers
// CHECK-SEARCHES-NEXT: {{.*}} Initializer PatternBinding {{.*}} #1
// CHECK-SEARCHES-NEXT: ***Scope at 194:26***
// CHECK-SEARCHES-NEXT: PatternEntryInitializerScope {{.*}}, [194:24 - 194:29] entry 0 'prop'
// CHECK-SEARCHES-NEXT: {{.*}} Module name=main
// CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="SOURCE_DIR/test/NameBinding/scope_map-astscopelookup.swift"
// CHECK-SEARCHES-NEXT: {{.*}} ClassDecl name=LazyProperties
// CHECK-SEARCHES-NEXT: {{.*}} Initializer PatternBinding {{.*}} #0
// CHECK-SEARCHES-NEXT: Local bindings: self
// CHECK-SEARCHES-NOT: ***Complete scope map***
// REQUIRES: asserts
// absence of assertions can change the "uncached" bit and cause failures
| apache-2.0 | 7ee785e9b016135c32d0b9b10fd1cf26 | 55.370155 | 200 | 0.581187 | 3.560656 | false | false | false | false |
lingoslinger/SwiftLibraries | SwiftLibraries/View Controllers/LibraryTableViewController.swift | 1 | 4069 | //
// LibraryTableViewController.swift
// SwiftLibraries
//
// Created by Allan Evans on 7/21/16.
// Copyright © 2016 - 2021 Allan Evans. All rights reserved. Seriously.
//
import UIKit
import Foundation
typealias SessionCompletionHandler = (_ data : Data?, _ response : URLResponse?, _ error : Error?) -> Void
class LibraryTableViewController: UITableViewController {
var libraryArray = [Library]()
var sectionDictionary = Dictionary<String, [Library]>()
var sectionTitles = [String]()
// MARK: - view lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let libraryURLSession = LibraryURLSession();
let completionHander : SessionCompletionHandler = {(data : Data?, response : URLResponse?, error : Error?) -> Void in
if (error == nil) {
let decoder = JSONDecoder()
guard let libraryArray = try? decoder.decode([Library].self, from: data!) else {
fatalError("Unable to decode JSON library data")
}
self.libraryArray = libraryArray
DispatchQueue.main.async(execute: {
self.setupSectionsWithLibraryArray()
self.tableView.reloadData()
})
} else {
DispatchQueue.main.async {
self.showErrorDialogWithMessage(message: error?.localizedDescription ?? "Unknown network error")
}
}
}
libraryURLSession.sendRequest(completionHander)
}
// MARK: - UITableViewDataSource and UITableViewDelegate methods
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionTitles.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionTitle = self.sectionTitles[section]
let sectionArray = self.sectionDictionary[sectionTitle]
return sectionArray?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LibraryTableViewCell")
let sectionTitle = self.sectionTitles[indexPath.section]
let sectionArray = self.sectionDictionary[sectionTitle]
let library = sectionArray?[indexPath.row]
cell?.textLabel?.text = library?.name
return cell!
}
override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return index
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionTitles[section]
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return self.sectionTitles
}
// MARK: - navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "LibraryDetailViewController" {
guard let indexPath = self.tableView.indexPathForSelectedRow else { return }
let detailViewController = segue.destination as! LibraryDetailViewController
let sectionTitle = self.sectionTitles[indexPath.section]
let sectionArray = self.sectionDictionary[sectionTitle]
detailViewController.detailLibrary = sectionArray?[indexPath.row]
}
}
// MARK: - private methods
func setupSectionsWithLibraryArray() {
for library in libraryArray {
let firstLetterOfName = String.init(library.name?.first ?? Character.init(""))
if (sectionDictionary[firstLetterOfName] == nil) {
let sectionArray = [Library]()
sectionDictionary[firstLetterOfName] = sectionArray
}
sectionDictionary[firstLetterOfName]?.append(library)
}
let unsortedLetters = self.sectionDictionary.keys
sectionTitles = unsortedLetters.sorted()
}
}
| mit | 96375ef7270cb70fb848cdad8e067086 | 39.68 | 125 | 0.646755 | 5.595598 | false | false | false | false |
practicalswift/swift | test/Constraints/gather_all_adjacencies.swift | 47 | 680 | // RUN: %target-swift-frontend -typecheck %s
// SR-5120 / rdar://problem/32618740
protocol InitCollection: Collection {
init(_ array: [Iterator.Element])
}
protocol InitAny {
init()
}
extension Array: InitCollection {
init(_ array: [Iterator.Element]) {
self = array
}
}
extension String: InitAny {
init() {
self = "bar"
}
}
class Foo {
func foo<T: InitCollection, U: InitAny>(of type: U.Type) -> T
where T.Iterator.Element == U
{
return T.init([U.init()])
}
func foo<T: InitCollection, U: InitAny>(of type: U.Type) -> T?
where T.Iterator.Element == U
{
return T.init([U.init()])
}
}
let _: [String] = Foo().foo(of: String.self)
| apache-2.0 | 236f0564cdbbfa9d67aee1f58262f325 | 16.894737 | 64 | 0.619118 | 3.00885 | false | false | false | false |
sessionm/ios-smp-example | Inbox/MessagesTableViewController.swift | 1 | 4447 | //
// MessagesTableViewController.swift
// SMPExample
//
// Copyright © 2018 SessionM. All rights reserved.
//
import SessionMInboxKit
import UIKit
class MessageCell: UITableViewCell {
@IBOutlet var subject: UILabel!
@IBOutlet var createdTime: UILabel!
}
class MessagesTableViewController: UITableViewController {
private let inboxManager = SMInboxManager.instance()
private var messages: [SMInboxMessage] = []
private var selectedMessages: [SMInboxMessage] = []
@IBAction private func onRefresh(_ sender: UIRefreshControl) {
fetchMessages()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
fetchMessages()
}
private func fetchMessages() {
self.refreshControl?.beginRefreshing()
inboxManager.fetchMessages(completionHandler: { (messages: [SMInboxMessage]?, error: SMError?) in
if let err = error {
Util.failed(self, message: err.message)
} else if let newMessages = messages {
self.messages = newMessages
self.tableView.reloadData()
}
self.refreshControl?.endRefreshing()
})
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int { return 1 }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let message = messages[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath) as? MessageCell
if let c = cell {
c.subject.text = message.subject
if let time = message.createdTime {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
if let date = formatter.date(from: time) {
if Calendar.current.isDateInToday(date) {
formatter.dateStyle = .none
formatter.timeStyle = .short
} else {
formatter.dateStyle = .short
formatter.timeStyle = .none
}
c.createdTime.text = formatter.string(from: date)
} else {
c.createdTime.text = ""
}
}
switch message.state {
case .new:
c.subject.font = UIFont.boldSystemFont(ofSize: c.subject.font.pointSize)
c.createdTime.font = UIFont.boldSystemFont(ofSize: c.subject.font.pointSize)
c.backgroundColor = UIColor.white
case .read:
c.subject.font = UIFont.systemFont(ofSize: c.subject.font.pointSize)
c.createdTime.font = UIFont.systemFont(ofSize: c.subject.font.pointSize)
c.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
default:
break
}
c.tag = indexPath.row
}
return cell!
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination as! MessageDetailViewController
let cell = sender as! MessageCell
destination.message = messages[cell.tag]
inboxManager.updateMessage(destination.message!, toState: .read, completionHandler: { (messages: [SMInboxMessage]?, error: SMError?) in })
}
@IBAction private func createRandomInboxMessage(_ sender: UIBarButtonItem) {
let subject = UUID().uuidString as NSString
let body = UUID().uuidString.lowercased()
let newMessage = SMNewInboxMessage(subject: subject.substring(to: subject.length/2), body: body)
inboxManager.createMessage(newMessage) { (message, error) in
if let err = error {
Util.failed(self, message: err.message)
} else {
self.fetchMessages()
}
}
}
@IBAction private func logout(_ sender: AnyObject) {
if let provider = SessionM.authenticationProvider() as? SessionMOAuthProvider {
provider.logOutUser { (authState, error) in
LoginViewController.loginIfNeeded(self)
}
}
}
}
| mit | 1897d0bbea880ba2571d69c3a572405e | 36.677966 | 146 | 0.60009 | 5.035108 | false | false | false | false |
toshiapp/toshi-ios-client | Toshi/Controllers/Dapps/DappsNavigationController.swift | 1 | 4811 | // Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import UIKit
final class DappsNavigationController: UINavigationController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
override init(rootViewController: UIViewController) {
if let profileData = UserDefaultsWrapper.selectedApp {
super.init(nibName: nil, bundle: nil)
let profile: Profile
do {
let jsonDecoder = JSONDecoder()
profile = try jsonDecoder.decode(Profile.self, from: profileData)
} catch {
viewControllers = [rootViewController]
configureTabBarItem()
return
}
viewControllers = [rootViewController, ProfileViewController(profile: profile)]
} else {
super.init(rootViewController: rootViewController)
}
configureTabBarItem()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
setNavigationBarHidden(true, animated: false)
configureTabBarItem()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureTabBarItem() {
tabBarItem = UITabBarItem(title: Localized.tab_bar_title_dapps, image: ImageAsset.tab1, tag: 0)
tabBarItem.titlePositionAdjustment.vertical = TabBarItemTitleOffset
}
override func popToRootViewController(animated: Bool) -> [UIViewController]? {
UserDefaultsWrapper.selectedApp = nil
return super.popToRootViewController(animated: animated)
}
override func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
UserDefaultsWrapper.selectedApp = nil
return super.popToViewController(viewController, animated: animated)
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if let colorChangingViewController = viewController as? NavBarColorChanging {
setNavigationBarColors(with: colorChangingViewController)
}
super.pushViewController(viewController, animated: animated)
if let viewController = viewController as? ProfileViewController {
UserDefaultsWrapper.selectedApp = viewController.profile.data
}
}
override func popViewController(animated: Bool) -> UIViewController? {
UserDefaultsWrapper.selectedApp = nil
guard let colorChangingViewController = previousViewController as? NavBarColorChanging else {
// Just call super and be done with it.
return super.popViewController(animated: animated)
}
setNavigationBarColors(with: colorChangingViewController)
// Start the transition by calling super so we get a transition coordinator
let poppedViewController = super.popViewController(animated: animated)
transitionCoordinator?.animate(alongsideTransition: nil, completion: { [weak self] _ in
guard let topColorChangingViewController = self?.topViewController as? NavBarColorChanging else { return }
self?.setNavigationBarColors(with: topColorChangingViewController)
})
return poppedViewController
}
private var previousViewController: UIViewController? {
guard viewControllers.count > 1 else {
return nil
}
return viewControllers[viewControllers.count - 2]
}
private func setNavigationBarColors(with colorChangingObject: NavBarColorChanging) {
navigationBar.tintColor = colorChangingObject.navTintColor
navigationBar.barTintColor = colorChangingObject.navBarTintColor
navigationBar.shadowImage = colorChangingObject.navShadowImage
if let titleColor = colorChangingObject.navTitleColor {
navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: titleColor]
} else {
navigationBar.titleTextAttributes = nil
}
}
}
| gpl-3.0 | 40ab12e4cbb6f2e4f7a1745d7b747a64 | 38.434426 | 118 | 0.696113 | 5.888617 | false | false | false | false |
justinmakaila/JSONMapping | JSONMappingTests/JSONTransformObject.swift | 1 | 629 | import CoreData
import JSONMapping
class JSONTransformObject: NSManagedObject {
@NSManaged
var customString: String?
override func parseJSON(json: JSONObject, propertyDescription: NSPropertyDescription) -> Any? {
let localKey = propertyDescription.name
if localKey == "customString" {
if let strings = json["strings"] as? JSONObject {
if let value = strings["custom"] as? String {
return value
}
}
}
return super.parseJSON(json: json, propertyDescription: propertyDescription)
}
}
| mit | 86894505d976468f3b9c2b4572eba07d | 28.952381 | 99 | 0.599364 | 5.517544 | false | false | false | false |
Authman2/Pix | Pix/ActivityPage.swift | 1 | 4208 | //
// ActivityPage.swift
// Pix
//
// Created by Adeola Uthman on 1/3/17.
// Copyright © 2017 Adeola Uthman. All rights reserved.
//
import UIKit
import PullToRefreshSwift
import DynamicColor
import IGListKit
class ActivityPage: UIViewController, IGListAdapterDataSource {
/********************************
*
* METHODS
*
********************************/
/* The IG adapter. */
lazy var adapter: IGListAdapter = {
return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 1);
}();
/* The collection view. */
let collectionView: IGListCollectionView = {
let layout = UICollectionViewFlowLayout();
layout.minimumLineSpacing = 0;
layout.minimumInteritemSpacing = 0;
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0);
let view = IGListCollectionView(frame: CGRect.zero, collectionViewLayout: layout);
view.alwaysBounceVertical = true;
return view;
}();
/* An array of activities to display. */
var activities: [Activity] = [Activity]();
/********************************
*
* METHODS
*
********************************/
override func viewDidLoad() {
super.viewDidLoad();
navigationItem.title = "Activity";
self.setupCollectionView();
view.addSubview(collectionView);
self.reloadActivites();
// Pull To Refresh
var options = PullToRefreshOption();
options.backgroundColor = UIColor.lightGray.lighter(amount: 20);
collectionView.addPullRefresh(options: options) { (Void) in
self.reloadActivites();
self.adapter.performUpdates(animated: true, completion: nil);
self.collectionView.stopPullRefreshEver();
}
// Clear activity button
let clearBtn = UIBarButtonItem(title: "Clear", style: .plain, target: self, action: #selector(clearActivity));
clearBtn.tintColor = .white;
navigationItem.rightBarButtonItem = clearBtn;
} // End of viewdidload.
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews();
collectionView.frame = view.bounds;
} // End of viewDidLayoutSubviews().
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated);
self.adapter.performUpdates(animated: true, completion: nil);
} // End of viewdidappear.
@objc func clearActivity() {
activities.removeAll();
notificationActivityLog.removeAll();
if let cUser = Networking.currentUser {
UserDefaults.standard.setValue(notificationActivityLog, forKey: "\(cUser.uid)_activity_log");
}
self.adapter.performUpdates(animated: true, completion: nil);
}
func setupCollectionView() {
collectionView.register(ActivityCell.self, forCellWithReuseIdentifier: "Cell");
collectionView.register(ActivityRequestCell.self, forCellWithReuseIdentifier: "Cell");
collectionView.backgroundColor = .white;
adapter.collectionView = collectionView;
adapter.dataSource = self;
}
/* Reloads the activites to make sure any new ones are properly added. */
func reloadActivites() {
activities.removeAll();
for itm in notificationActivityLog {
let item = itm.toActivity();
self.activities.append(item);
}
}
/********************************
*
* COLLECTION VIEW
*
********************************/
func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] {
return activities;
}
func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController {
return ActivitySectionController();
}
func emptyView(for listAdapter: IGListAdapter) -> UIView? {
return EmptyActivityView();
}
}
| gpl-3.0 | cf88a26f6a99b7e872e5d431cb6ae3a4 | 27.425676 | 118 | 0.580461 | 5.700542 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Cocoa/Components/Currency/Money/Money+Components+Style.swift | 1 | 4827 | //
// Xcore
// Copyright © 2017 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
extension Money.Components {
/// A structure representing formatting used to display money components.
public struct Style {
public let id: Identifier<Self>
public let join: (Money.Components) -> String
public let range: (Money.Components) -> Range
public init(
id: Identifier<Self>,
join: @escaping (Money.Components) -> String,
range: @escaping (Money.Components) -> Range
) {
self.id = id
self.join = join
self.range = range
}
}
}
// MARK: - Equatable
extension Money.Components.Style: Equatable {
public static func ==(lhs: Self, rhs: Self) -> Bool {
lhs.id == rhs.id
}
}
// MARK: - Hashable
extension Money.Components.Style: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
// MARK: - Built-in
extension Money.Components.Style {
/// ```swift
/// let amount = Money(120.30)
/// .style(.default) // ← Specifying style format
///
/// print(amount) // "$120.30"
/// ```
public static var `default`: Self {
.init(
id: #function,
join: { "\($0.majorUnit)\($0.decimalSeparator)\($0.minorUnit)" },
range: { $0.ranges }
)
}
/// ```swift
/// let amount = Money(120.30)
/// .style(.removeMinorUnit) // ← Specifying style format
///
/// print(amount) // "$120"
/// ```
public static var removeMinorUnit: Self {
.init(
id: #function,
join: { $0.majorUnit },
range: { ($0.ranges.majorUnit, nil) }
)
}
/// ```swift
/// let amount = Money(120.30)
/// .style(.removeMinorUnitIfZero) // ← Specifying style format
///
/// print(amount) // "$120.30"
///
/// let amount = Money(120.00)
/// .style(.removeMinorUnitIfZero) // ← Specifying style format
///
/// print(amount) // "$120"
/// ```
public static var removeMinorUnitIfZero: Self {
.init(
id: #function,
join: {
guard $0.isMinorUnitValueZero else {
return "\($0.majorUnit)\($0.decimalSeparator)\($0.minorUnit)"
}
return $0.majorUnit
},
range: {
let ranges = $0.ranges
guard $0.isMinorUnitValueZero else {
return ranges
}
return (ranges.majorUnit, nil)
}
)
}
/// Abbreviate amount to compact format.
///
/// ```swift
/// 987 // → 987
/// 1200 // → 1.2K
/// 12000 // → 12K
/// 120000 // → 120K
/// 1200000 // → 1.2M
/// 1340 // → 1.3K
/// 132456 // → 132.5K
/// ```
///
/// - Parameters:
/// - threshold: A property to only abbreviate if `amount` is greater then
/// this value.
/// - thresholdAbs: A boolean property indicating whether threshold is of
/// absolute value (e.g., `"abs(value)"`).
/// - fallback: The formatting style to use when threshold isn't reached.
/// - Returns: Abbreviated version of `self`.
public static func abbreviation(
threshold: Decimal,
thresholdAbs: Bool = true,
fallback: Self = .default
) -> Self {
func canAbbreviation(amount: Decimal) -> (amount: Double, threshold: Double)? {
let compareAmount = thresholdAbs ? abs(amount) : amount
guard
compareAmount >= 1000,
compareAmount >= threshold,
let amountValue = Double(exactly: NSDecimalNumber(decimal: amount.rounded(fractionDigits: 2))),
let thresholdValue = Double(exactly: NSDecimalNumber(decimal: threshold))
else {
return nil
}
return (amountValue, thresholdValue)
}
return .init(
id: .init(rawValue: "abbreviation\(threshold)\(fallback.id)"),
join: {
guard let value = canAbbreviation(amount: $0.amount) else {
return fallback.join($0)
}
return $0.currencySymbol + value.amount.abbreviate(
threshold: value.threshold,
thresholdAbs: thresholdAbs,
locale: CurrencyFormatter.shared.locale
)
},
range: {
guard canAbbreviation(amount: $0.amount) != nil else {
return fallback.range($0)
}
return (nil, nil)
}
)
}
}
| mit | 6ba56f84e691cbc0adf17169380ce003 | 27.426036 | 111 | 0.506661 | 4.48972 | false | false | false | false |
zzyyzz1992/ZZParallaxCollection | ZZParallaxCollection/ParallaxHeader.swift | 1 | 4526 | //
// ParallaxHeader.swift
// ZZParallaxCollection
//
// Created by 张泽阳 on 5/31/15.
// Copyright (c) 2015 Zhang Zeyang. All rights reserved.
//
import UIKit
/**
the Parallax header view,
which contains the parallaxy image
*/
class ParallaxHeader : UIView
{
// MARK: - properties
private var heightConstraints:[NSLayoutConstraint]?
private var imageView = UIImageView()
private var imageContainer = UIView()
private var paddingX:CGFloat?
private var paddingY:CGFloat?
/// header view's height, also image container's first height
var minimumHeight:CGFloat?{
didSet{
self.bounds.size.height = minimumHeight!
}
}
/// image container's height
var height:CGFloat?{
didSet{
if height < minimumHeight {height = minimumHeight}
if let c = heightConstraints {
self.removeConstraints(c)
}
heightConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-(diff)-[ic]", options: [], metrics: ["diff":(minimumHeight! - height!)], views: ["ic":imageContainer])
self.addConstraints(heightConstraints!)
}
}
// MARK: - to make the parallax effect in the axis of x
func setDX(dx:CGFloat){
self.frame.origin.x = dx
}
/**
setup initial layout
*/
func doSetup(){
imageContainer.translatesAutoresizingMaskIntoConstraints = false
imageView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(imageContainer)
imageContainer.addSubview(imageView)
imageContainer.backgroundColor = UIColor.blackColor()
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageContainer.clipsToBounds = true
//constraints for container
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[ic]-(0)-|", options: [], metrics: nil, views: ["ic":imageContainer]))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(0)-[ic]-(0)-|", options: [], metrics: nil, views: ["ic":imageContainer]))
// MARK: - constraints for imageView
// imageView's size constraints
imageContainer.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(<=0)-[iv]-(<=0)-|", options: [], metrics: nil, views: ["iv":imageView]))
imageContainer.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(<=0)-[iv]-(<=0)-|", options: [], metrics: nil, views: ["iv":imageView]))
//center XY
let cX = NSLayoutConstraint(item: imageView, attribute: .CenterX, relatedBy: .Equal, toItem: imageContainer, attribute: .CenterX, multiplier: 1.0, constant: 0)
cX.priority = 999
imageContainer.addConstraint(cX)
let cY = NSLayoutConstraint(item: imageView, attribute: .CenterY, relatedBy: .Equal, toItem: imageContainer, attribute: .CenterY, multiplier: 1.0, constant: 0)
cY.priority = 1000
imageContainer.addConstraint(cY)
//aspect ratio
let iSize = imageView.image!.size
let cRatio = NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: imageView, attribute: .Width, multiplier: iSize.height / iSize.width, constant: 0)
imageView.addConstraint(cRatio)
//default W&H
let widthC = NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: minimumHeight! + paddingX!)
widthC.priority = 998
imageView.addConstraint(widthC)
let heightC = NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: minimumHeight! / iSize.height * iSize.width + paddingY!)
heightC.priority = 997
imageView.addConstraint(heightC)
}
// MARK: - headerView class contructor
class func headerView(imageName imageName:String,fixedHeaderHeight height:CGFloat, paddingSize:CGSize) -> ParallaxHeader{
let header = ParallaxHeader()
if let i = UIImage(named: imageName){
header.imageView.image = i
}else{
print("image:\(imageName) not exist!")
}
header.minimumHeight = height
header.paddingX = paddingSize.width
header.paddingY = paddingSize.height
header.doSetup()
return header
}
} | gpl-2.0 | 234fa8cc26464372d8cf4b21ba0f660c | 41.650943 | 220 | 0.656195 | 4.923747 | false | false | false | false |
julongdragon/myweb | Sources/App/Models/Product.swift | 1 | 1170 | import Fluent
import PostgreSQLProvider
import FluentProvider
final class Product : Model {
var storage = Storage()
var item : String
var price : String
init(item:String,price:String){
self.item = item
self.price = price
}
init(row: Row) throws {
self.item = try row.get("item")
self.price = try row.get("price")
}
}
extension Product : RowRepresentable {
func makeRow() throws -> Row {
var row = Row()
try row.set("item", item)
try row.set("price", price)
return row
}
}
extension Product : Preparation {
static func prepare(_ database: Database) throws {
try database.create(self, closure: { (product) in
product.id()
product.string("item")
product.string("price")
})
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
extension Product : JSONRepresentable {
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("id", id?.string)
try json.set("item", item)
try json.set("price",price)
return json
}
}
| mit | fa092c3144479d76d8773d87b6fa8e4d | 24.434783 | 57 | 0.580342 | 4.163701 | false | false | false | false |
ashleybrgr/surfPlay | surfPlay/Pods/FaveButton/Source/Helpers/Easing.swift | 5 | 4293 | //
// Easing.swift
// FaveButton
//
// Copyright © 2016 Jansel Valentin.
//
// 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
// file taken from https://github.com/xhamr/swift-penner-easing-functions
typealias Easing = (_ t:CGFloat,_ b:CGFloat,_ c:CGFloat,_ d:CGFloat)-> CGFloat
typealias ElasticEasing = (_ t:CGFloat,_ b:CGFloat,_ c:CGFloat,_ d:CGFloat,_ a:CGFloat,_ p:CGFloat)-> CGFloat
// ELASTIC EASING
struct Elastic{
static var EaseIn :Easing = { (_t,b,c,d) -> CGFloat in
var t = _t
if t==0{ return b }
t/=d
if t==1{ return b+c }
let p = d * 0.3
let a = c
let s = p/4
t -= 1
return -(a*pow(2,10*t) * sin( (t*d-s)*(2*CGFloat(M_PI))/p )) + b;
}
static var EaseOut :Easing = { (_t,b,c,d) -> CGFloat in
var t = _t
if t==0{ return b }
t/=d
if t==1{ return b+c}
let p = d * 0.3
let a = c
let s = p/4
return (a*pow(2,-10*t) * sin( (t*d-s)*(2*CGFloat(M_PI))/p ) + c + b);
}
static var EaseInOut :Easing = { (_t,b,c,d) -> CGFloat in
var t = _t
if t==0{ return b}
t = t/(d/2)
if t==2{ return b+c }
let p = d * (0.3*1.5)
let a = c
let s = p/4
if t < 1 {
t -= 1
return -0.5*(a*pow(2,10*t) * sin((t*d-s)*(2*CGFloat(M_PI))/p )) + b;
}
t -= 1
return a*pow(2,-10*t) * sin( (t*d-s)*(2*CGFloat(M_PI))/p )*0.5 + c + b;
}
}
extension Elastic{
static var ExtendedEaseIn :ElasticEasing = { (_t,b,c,d,_a,_p) -> CGFloat in
var t = _t
var a = _a
var p = _p
var s:CGFloat = 0.0
if t==0{ return b }
t /= d
if t==1{ return b+c }
if a < abs(c) {
a=c; s = p/4
}else {
s = p/(2*CGFloat(M_PI)) * asin (c/a);
}
t -= 1
return -(a*pow(2,10*t) * sin( (t*d-s)*(2*CGFloat(M_PI))/p )) + b;
}
static var ExtendedEaseOut :ElasticEasing = { (_t,b,c,d,_a,_p) -> CGFloat in
var s:CGFloat = 0.0
var t = _t
var a = _a
var p = _p
if t==0 { return b }
t /= d
if t==1 {return b+c}
if a < abs(c) {
a=c; s = p/4;
}else {
s = p/(2*CGFloat(M_PI)) * asin (c/a)
}
return (a*pow(2,-10*t) * sin( (t*d-s)*(2*CGFloat(M_PI))/p ) + c + b)
}
static var ExtendedEaseInOut :ElasticEasing = { (_t,b,c,d,_a,_p) -> CGFloat in
var s:CGFloat = 0.0
var t = _t
var a = _a
var p = _p
if t==0{ return b }
t /= d/2
if t==2{ return b+c }
if a < abs(c) {
a=c; s=p/4;
}else {
s = p/(2*CGFloat(M_PI)) * asin (c/a)
}
if t < 1 {
t -= 1
return -0.5*(a*pow(2,10*t) * sin( (t*d-s)*(2*CGFloat(M_PI))/p )) + b;
}
t -= 1
return a*pow(2,-10*t) * sin( (t*d-s)*(2*CGFloat(M_PI))/p )*0.5 + c + b;
}
}
| apache-2.0 | 5203eabcca62f46004dd6962d17246ea | 26.87013 | 109 | 0.486486 | 3.26885 | false | false | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/WMFPasswordResetter.swift | 1 | 2265 |
public enum WMFPasswordResetterError: LocalizedError {
case cannotExtractResetStatus
case resetStatusNotSuccess
public var errorDescription: String? {
switch self {
case .cannotExtractResetStatus:
return "Could not extract status"
case .resetStatusNotSuccess:
return "Password reset did not succeed"
}
}
}
public typealias WMFPasswordResetterResultBlock = (WMFPasswordResetterResult) -> Void
public struct WMFPasswordResetterResult {
var status: String
init(status:String) {
self.status = status
}
}
public class WMFPasswordResetter {
private let manager = AFHTTPSessionManager.wmf_createDefault()
public func isFetching() -> Bool {
return manager.operationQueue.operationCount > 0
}
public func resetPassword(siteURL: URL, token: String, userName:String?, email:String?, success: @escaping WMFPasswordResetterResultBlock, failure: @escaping WMFErrorHandler){
let manager = AFHTTPSessionManager(baseURL: siteURL)
manager.responseSerializer = WMFApiJsonResponseSerializer.init();
var parameters = [
"action": "resetpassword",
"token": token,
"format": "json"
];
if let userName = userName, userName.count > 0 {
parameters["user"] = userName
}else {
if let email = email, email.count > 0 {
parameters["email"] = email
}
}
_ = manager.wmf_apiPOSTWithParameters(parameters, success: { (_, response) in
guard
let response = response as? [String : AnyObject],
let resetpassword = response["resetpassword"] as? [String: Any],
let status = resetpassword["status"] as? String
else {
failure(WMFPasswordResetterError.cannotExtractResetStatus)
return
}
guard status == "success" else {
failure(WMFPasswordResetterError.resetStatusNotSuccess)
return
}
success(WMFPasswordResetterResult.init(status: status))
}, failure: { (_, error) in
failure(error)
})
}
}
| mit | d493cba06e30afde8703c43e65a94df4 | 33.846154 | 179 | 0.603532 | 5.405728 | false | false | false | false |
xtcan/playerStudy_swift | TCVideo_Study/TCVideo_Study/Classes/Home/Other/HomeViewModel.swift | 1 | 1262 | //
// HomeViewModel.swift
// TCVideo_Study
//
// Created by tcan on 17/5/27.
// Copyright © 2017年 tcan. All rights reserved.
//
//获取数据
import UIKit
class HomeViewModel: NSObject {
lazy var homePageContentModels = [HomePageContentModel]()
}
extension HomeViewModel{
func loadHomeData(type : HomeCategoryType, index : Int, finishedCallback : @escaping () -> ()) {
NetworkTool.requestData(.get, URLString: "http://qf.56.com/home/v4/moreAnchor.ios", parameters: ["type" : type.type, "index" : index, "size" : 48]) { (result) -> Void in
guard let resultDict = result as? [String : Any] else { return }
guard let messageDict = resultDict["message"] as? [String : Any] else {return}
guard let dataArray = messageDict["anchors"] as? [[String : Any]] else { return }
//遍历数据
for (index , dict) in dataArray.enumerated() {
//字典转模型
let contentModel = HomePageContentModel(dict : dict)
contentModel.isEvenIndex = index % 2 == 0
self.homePageContentModels .append(contentModel)
}
finishedCallback()
}
}
}
| apache-2.0 | 4cc596ccc4f4b88606213e3bb82e437b | 30.615385 | 177 | 0.575831 | 4.296167 | false | false | false | false |
GianniCarlo/Audiobook-Player | Shared/Models/Book+CoreDataClass.swift | 1 | 8550 | //
// Book+CoreDataClass.swift
// BookPlayerKit
//
// Created by Gianni Carlo on 4/23/19.
// Copyright © 2019 Tortuga Power. All rights reserved.
//
//
import CoreData
import Foundation
@objc(Book)
public class Book: LibraryItem {
var filename: String {
return self.title + "." + self.ext
}
public var currentChapter: Chapter?
// needed to invalide cache of folder
override public func setCurrentTime(_ time: Double) {
self.currentTime = time
self.folder?.resetCachedProgress()
}
var displayTitle: String {
return self.title
}
public override var progress: Double {
guard self.duration > 0 else { return 0 }
return self.currentTime
}
public override var progressPercentage: Double {
guard self.duration > 0 else { return 0 }
return self.currentTime / self.duration
}
public var percentage: Double {
return round(self.progressPercentage * 100)
}
public var hasChapters: Bool {
return !(self.chapters?.array.isEmpty ?? true)
}
public var hasArtwork: Bool {
return self.artworkData != nil
}
public override func getItem(with relativePath: String) -> LibraryItem? {
return self.relativePath == relativePath ? self : nil
}
public override func jumpToStart() {
self.setCurrentTime(0.0)
}
public override func markAsFinished(_ flag: Bool) {
self.isFinished = flag
// To avoid progress display side-effects
if !flag,
self.currentTime.rounded(.up) == self.duration.rounded(.up) {
self.setCurrentTime(0.0)
}
self.folder?.updateCompletionState()
}
public func currentTimeInContext(_ prefersChapterContext: Bool) -> TimeInterval {
guard !self.isFault else {
return 0.0
}
guard
prefersChapterContext,
self.hasChapters,
let start = self.currentChapter?.start else {
return self.currentTime
}
return self.currentTime - start
}
public func maxTimeInContext(_ prefersChapterContext: Bool, _ prefersRemainingTime: Bool) -> TimeInterval {
guard !self.isFault else {
return 0.0
}
guard
prefersChapterContext,
self.hasChapters,
let duration = self.currentChapter?.duration else {
let time = prefersRemainingTime
? self.currentTimeInContext(prefersChapterContext) - self.duration
: self.duration
return time
}
let time = prefersRemainingTime
? self.currentTimeInContext(prefersChapterContext) - duration
: duration
return time
}
public func durationTimeInContext(_ prefersChapterContext: Bool) -> TimeInterval {
guard !self.isFault else {
return 0.0
}
guard
prefersChapterContext,
self.hasChapters,
let duration = self.currentChapter?.duration else {
return self.duration
}
return duration
}
public override func awakeFromFetch() {
super.awakeFromFetch()
self.updateCurrentChapter()
}
public func updateCurrentChapter() {
guard let chapters = self.chapters?.array as? [Chapter], !chapters.isEmpty else {
return
}
guard let currentChapter = (chapters.first { (chapter) -> Bool in
chapter.start <= self.currentTime && chapter.end > self.currentTime
}) else { return }
self.currentChapter = currentChapter
}
public func updatePlayDate() {
let now = Date()
self.lastPlayDate = now
guard let folder = self.folder else { return }
folder.lastPlayDate = now
}
public override func getBookToPlay() -> Book? {
return self
}
public func nextChapter() -> Chapter? {
guard let chapters = self.chapters?.array as? [Chapter],
!chapters.isEmpty,
let chapter = self.currentChapter else {
return nil
}
if self.currentChapter == chapters.last { return nil }
return chapters[Int(chapter.index)]
}
public func previousChapter() -> Chapter? {
guard let chapters = self.chapters?.array as? [Chapter],
!chapters.isEmpty,
let chapter = self.currentChapter else {
return nil
}
if self.currentChapter == chapters.first { return nil }
return chapters[Int(chapter.index) - 2]
}
public func nextBook() -> Book? {
if
let folder = self.folder,
let next = folder.getNextBook(after: self) {
return next
}
guard UserDefaults.standard.bool(forKey: Constants.UserDefaults.autoplayEnabled.rawValue) else {
return nil
}
let item = self.folder ?? self
guard let nextItem = item.library?.getNextItem(after: item) else { return nil }
if let book = nextItem as? Book {
return book
} else if let folder = nextItem as? Folder, let book = folder.getBookToPlay() {
return book
}
return nil
}
public func getInterval(from proposedInterval: TimeInterval) -> TimeInterval {
let interval = proposedInterval > 0
? self.getForwardInterval(from: proposedInterval)
: self.getRewindInterval(from: proposedInterval)
return interval
}
private func getRewindInterval(from proposedInterval: TimeInterval) -> TimeInterval {
guard let chapter = self.currentChapter else { return proposedInterval }
if self.currentTime + proposedInterval > chapter.start {
return proposedInterval
}
let chapterThreshold: TimeInterval = 3
if chapter.start + chapterThreshold > currentTime {
return proposedInterval
}
return -(self.currentTime - chapter.start)
}
private func getForwardInterval(from proposedInterval: TimeInterval) -> TimeInterval {
guard let chapter = self.currentChapter else { return proposedInterval }
if self.currentTime + proposedInterval < chapter.end {
return proposedInterval
}
if chapter.end < currentTime {
return proposedInterval
}
return chapter.end - self.currentTime + 0.01
}
enum CodingKeys: String, CodingKey {
case currentTime, duration, identifier, relativePath, percentCompleted, title, author, ext, folder
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(currentTime, forKey: .currentTime)
try container.encode(duration, forKey: .duration)
try container.encode(identifier, forKey: .identifier)
try container.encode(relativePath, forKey: .identifier)
try container.encode(percentCompleted, forKey: .percentCompleted)
try container.encode(title, forKey: .title)
try container.encode(author, forKey: .author)
try container.encode(ext, forKey: .ext)
}
public required convenience init(from decoder: Decoder) throws {
// Create NSEntityDescription with NSManagedObjectContext
guard let contextUserInfoKey = CodingUserInfoKey.context,
let managedObjectContext = decoder.userInfo[contextUserInfoKey] as? NSManagedObjectContext,
let entity = NSEntityDescription.entity(forEntityName: "Book", in: managedObjectContext) else {
fatalError("Failed to decode Book!")
}
self.init(entity: entity, insertInto: nil)
let values = try decoder.container(keyedBy: CodingKeys.self)
currentTime = try values.decode(Double.self, forKey: .currentTime)
duration = try values.decode(Double.self, forKey: .duration)
identifier = try values.decode(String.self, forKey: .identifier)
relativePath = try values.decode(String.self, forKey: .identifier)
percentCompleted = try values.decode(Double.self, forKey: .percentCompleted)
title = try values.decode(String.self, forKey: .title)
author = try values.decode(String.self, forKey: .author)
ext = try values.decode(String.self, forKey: .ext)
}
}
extension CodingUserInfoKey {
public static let context = CodingUserInfoKey(rawValue: "context")
}
| gpl-3.0 | 782476183771fba24b1d4341135ccd7b | 29.208481 | 111 | 0.627325 | 5.002341 | false | false | false | false |
kesun421/firefox-ios | Client/Frontend/Browser/BrowserTrayAnimators.swift | 2 | 15158 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
class TrayToBrowserAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if let bvc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? BrowserViewController,
let tabTray = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? TabTrayController {
transitionFromTray(tabTray, toBrowser: bvc, usingContext: transitionContext)
}
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.4
}
}
private extension TrayToBrowserAnimator {
func transitionFromTray(_ tabTray: TabTrayController, toBrowser bvc: BrowserViewController, usingContext transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard let selectedTab = bvc.tabManager.selectedTab else { return }
let tabManager = bvc.tabManager
let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs
guard let expandFromIndex = displayedTabs.index(of: selectedTab) else { return }
bvc.view.frame = transitionContext.finalFrame(for: bvc)
// Hide browser components
bvc.toggleSnackBarVisibility(show: false)
toggleWebViewVisibility(false, usingTabManager: bvc.tabManager)
bvc.homePanelController?.view.isHidden = true
bvc.webViewContainerBackdrop.isHidden = true
bvc.statusBarOverlay.isHidden = false
if let url = selectedTab.url, !url.isReaderModeURL {
bvc.hideReaderModeBar(animated: false)
}
// Take a snapshot of the collection view that we can scale/fade out. We don't need to wait for screen updates since it's already rendered on the screen
let tabCollectionViewSnapshot = tabTray.collectionView.snapshotView(afterScreenUpdates: false)!
tabTray.collectionView.alpha = 0
tabCollectionViewSnapshot.frame = tabTray.collectionView.frame
container.insertSubview(tabCollectionViewSnapshot, at: 0)
// Create a fake cell to use for the upscaling animation
let startingFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView, atIndex: expandFromIndex)
let cell = createTransitionCellFromTab(bvc.tabManager.selectedTab, withFrame: startingFrame)
cell.backgroundHolder.layer.cornerRadius = 0
container.insertSubview(bvc.view, aboveSubview: tabCollectionViewSnapshot)
container.insertSubview(cell, aboveSubview: bvc.view)
// Flush any pending layout/animation code in preperation of the animation call
container.layoutIfNeeded()
let finalFrame = calculateExpandedCellFrameFromBVC(bvc)
bvc.footer.alpha = shouldDisplayFooterForBVC(bvc) ? 1 : 0
bvc.urlBar.isTransitioning = true
// Re-calculate the starting transforms for header/footer views in case we switch orientation
resetTransformsForViews([bvc.header, bvc.readerModeBar, bvc.footer])
transformHeaderFooterForBVC(bvc, toFrame: startingFrame, container: container)
UIView.animate(withDuration: self.transitionDuration(using: transitionContext),
delay: 0, usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: UIViewAnimationOptions(),
animations: {
// Scale up the cell and reset the transforms for the header/footers
cell.frame = finalFrame
container.layoutIfNeeded()
cell.title.transform = CGAffineTransform(translationX: 0, y: -cell.title.frame.height)
bvc.tabTrayDidDismiss(tabTray)
UIApplication.shared.windows.first?.backgroundColor = UIConstants.AppBackgroundColor
tabTray.navigationController?.setNeedsStatusBarAppearanceUpdate()
tabTray.toolbar.transform = CGAffineTransform(translationX: 0, y: UIConstants.BottomToolbarHeight)
tabCollectionViewSnapshot.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
tabCollectionViewSnapshot.alpha = 0
}, completion: { finished in
// Remove any of the views we used for the animation
cell.removeFromSuperview()
tabCollectionViewSnapshot.removeFromSuperview()
bvc.footer.alpha = 1
bvc.toggleSnackBarVisibility(show: true)
toggleWebViewVisibility(true, usingTabManager: bvc.tabManager)
bvc.webViewContainerBackdrop.isHidden = false
bvc.homePanelController?.view.isHidden = false
bvc.urlBar.isTransitioning = false
transitionContext.completeTransition(true)
})
}
}
class BrowserToTrayAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if let bvc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? BrowserViewController,
let tabTray = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? TabTrayController {
transitionFromBrowser(bvc, toTabTray: tabTray, usingContext: transitionContext)
}
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.4
}
}
private extension BrowserToTrayAnimator {
func transitionFromBrowser(_ bvc: BrowserViewController, toTabTray tabTray: TabTrayController, usingContext transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard let selectedTab = bvc.tabManager.selectedTab else { return }
let tabManager = bvc.tabManager
let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs
guard let scrollToIndex = displayedTabs.index(of: selectedTab) else { return }
tabTray.view.frame = transitionContext.finalFrame(for: tabTray)
// Insert tab tray below the browser and force a layout so the collection view can get it's frame right
container.insertSubview(tabTray.view, belowSubview: bvc.view)
// Force subview layout on the collection view so we can calculate the correct end frame for the animation
tabTray.view.layoutSubviews()
tabTray.collectionView.scrollToItem(at: IndexPath(item: scrollToIndex, section: 0), at: .centeredVertically, animated: false)
// Build a tab cell that we will use to animate the scaling of the browser to the tab
let expandedFrame = calculateExpandedCellFrameFromBVC(bvc)
let cell = createTransitionCellFromTab(bvc.tabManager.selectedTab, withFrame: expandedFrame)
cell.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
// Take a snapshot of the collection view to perform the scaling/alpha effect
let tabCollectionViewSnapshot = tabTray.collectionView.snapshotView(afterScreenUpdates: true)!
tabCollectionViewSnapshot.frame = tabTray.collectionView.frame
tabCollectionViewSnapshot.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
tabCollectionViewSnapshot.alpha = 0
tabTray.view.insertSubview(tabCollectionViewSnapshot, belowSubview: tabTray.toolbar)
if let toast = bvc.clipboardBarDisplayHandler?.clipboardToast {
toast.removeFromSuperview()
}
container.addSubview(cell)
cell.layoutIfNeeded()
cell.title.transform = CGAffineTransform(translationX: 0, y: -cell.title.frame.size.height)
// Hide views we don't want to show during the animation in the BVC
bvc.homePanelController?.view.isHidden = true
bvc.statusBarOverlay.isHidden = true
bvc.toggleSnackBarVisibility(show: false)
toggleWebViewVisibility(false, usingTabManager: bvc.tabManager)
bvc.urlBar.isTransitioning = true
// Since we are hiding the collection view and the snapshot API takes the snapshot after the next screen update,
// the screenshot ends up being blank unless we set the collection view hidden after the screen update happens.
// To work around this, we dispatch the setting of collection view to hidden after the screen update is completed.
DispatchQueue.main.async {
tabTray.collectionView.isHidden = true
let finalFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView,
atIndex: scrollToIndex)
tabTray.toolbar.transform = CGAffineTransform(translationX: 0, y: UIConstants.BottomToolbarHeight)
UIView.animate(withDuration: self.transitionDuration(using: transitionContext),
delay: 0, usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: UIViewAnimationOptions(),
animations: {
cell.frame = finalFrame
cell.title.transform = CGAffineTransform.identity
cell.layoutIfNeeded()
UIApplication.shared.windows.first?.backgroundColor = TabTrayControllerUX.BackgroundColor
tabTray.navigationController?.setNeedsStatusBarAppearanceUpdate()
transformHeaderFooterForBVC(bvc, toFrame: finalFrame, container: container)
bvc.urlBar.updateAlphaForSubviews(0)
bvc.footer.alpha = 0
tabCollectionViewSnapshot.alpha = 1
tabTray.toolbar.transform = CGAffineTransform.identity
resetTransformsForViews([tabCollectionViewSnapshot])
}, completion: { finished in
// Remove any of the views we used for the animation
cell.removeFromSuperview()
tabCollectionViewSnapshot.removeFromSuperview()
tabTray.collectionView.isHidden = false
bvc.toggleSnackBarVisibility(show: true)
toggleWebViewVisibility(true, usingTabManager: bvc.tabManager)
bvc.homePanelController?.view.isHidden = false
bvc.urlBar.isTransitioning = false
transitionContext.completeTransition(true)
})
}
}
}
private func transformHeaderFooterForBVC(_ bvc: BrowserViewController, toFrame finalFrame: CGRect, container: UIView) {
let footerForTransform = footerTransform(bvc.footer.frame, toFrame: finalFrame, container: container)
let headerForTransform = headerTransform(bvc.header.frame, toFrame: finalFrame, container: container)
bvc.footer.transform = footerForTransform
bvc.header.transform = headerForTransform
bvc.readerModeBar?.transform = headerForTransform
}
private func footerTransform( _ frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform {
let frame = container.convert(frame, to: container)
let endY = finalFrame.maxY - (frame.size.height / 2)
let endX = finalFrame.midX
let translation = CGPoint(x: endX - frame.midX, y: endY - frame.midY)
let scaleX = finalFrame.width / frame.width
var transform = CGAffineTransform.identity
transform = transform.translatedBy(x: translation.x, y: translation.y)
transform = transform.scaledBy(x: scaleX, y: scaleX)
return transform
}
private func headerTransform(_ frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform {
let frame = container.convert(frame, to: container)
let endY = finalFrame.minY + (frame.size.height / 2)
let endX = finalFrame.midX
let translation = CGPoint(x: endX - frame.midX, y: endY - frame.midY)
let scaleX = finalFrame.width / frame.width
var transform = CGAffineTransform.identity
transform = transform.translatedBy(x: translation.x, y: translation.y)
transform = transform.scaledBy(x: scaleX, y: scaleX)
return transform
}
//MARK: Private Helper Methods
private func calculateCollapsedCellFrameUsingCollectionView(_ collectionView: UICollectionView, atIndex index: Int) -> CGRect {
if let attr = collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: index, section: 0)) {
return collectionView.convert(attr.frame, to: collectionView.superview)
} else {
return CGRect.zero
}
}
private func calculateExpandedCellFrameFromBVC(_ bvc: BrowserViewController) -> CGRect {
var frame = bvc.webViewContainer.frame
// If we're navigating to a home panel and we were expecting to show the toolbar, add more height to end frame since
// there is no toolbar for home panels
if !bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) {
return frame
} else if let url = bvc.tabManager.selectedTab?.url, url.isAboutURL && bvc.toolbar == nil {
frame.size.height += UIConstants.BottomToolbarHeight
}
return frame
}
private func shouldDisplayFooterForBVC(_ bvc: BrowserViewController) -> Bool {
if bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) {
if let url = bvc.tabManager.selectedTab?.url {
return !url.isAboutURL
}
}
return false
}
private func toggleWebViewVisibility(_ show: Bool, usingTabManager tabManager: TabManager) {
for i in 0..<tabManager.count {
if let tab = tabManager[i] {
tab.webView?.isHidden = !show
}
}
}
private func resetTransformsForViews(_ views: [UIView?]) {
for view in views {
// Reset back to origin
view?.transform = CGAffineTransform.identity
}
}
private func transformToolbarsToFrame(_ toolbars: [UIView?], toRect endRect: CGRect) {
for toolbar in toolbars {
// Reset back to origin
toolbar?.transform = CGAffineTransform.identity
// Transform from origin to where we want them to end up
if let toolbarFrame = toolbar?.frame {
toolbar?.transform = CGAffineTransformMakeRectToRect(toolbarFrame, toFrame: endRect)
}
}
}
private func createTransitionCellFromTab(_ tab: Tab?, withFrame frame: CGRect) -> TabCell {
let cell = TabCell(frame: frame)
cell.screenshotView.image = tab?.screenshot
cell.titleText.text = tab?.displayTitle
if let tab = tab, tab.isPrivate {
cell.style = .dark
}
if let favIcon = tab?.displayFavicon {
cell.favicon.sd_setImage(with: URL(string: favIcon.url)!)
} else {
let defaultFavicon = UIImage(named: "defaultFavicon")
if tab?.isPrivate ?? false {
cell.favicon.image = defaultFavicon
cell.favicon.tintColor = (tab?.isPrivate ?? false) ? UIColor.white : UIColor.darkGray
} else {
cell.favicon.image = defaultFavicon
}
}
return cell
}
| mpl-2.0 | e48dc71af9e975451b3708468287b022 | 46.074534 | 170 | 0.707613 | 5.620319 | false | false | false | false |
ello/ello-ios | Sources/Networking/ElloProvider_Specs.swift | 1 | 3041 | ////
/// ElloProvider_Specs.swift
//
import Moya
struct ElloProvider_Specs {
static var errorStatusCode: ErrorStatusCode = .status404
static func errorEndpointsClosure(_ target: ElloAPI) -> Endpoint {
let sampleResponseClosure = { () -> EndpointSampleResponse in
return .networkResponse(
ElloProvider_Specs.errorStatusCode.rawValue,
ElloProvider_Specs.errorStatusCode.defaultData
)
}
return Endpoint(
url: url(target),
sampleResponseClosure: sampleResponseClosure,
method: target.method,
task: target.task,
httpHeaderFields: target.headers
)
}
static func recordedEndpointsClosure(_ recordings: [RecordedResponse]) -> (_ target: ElloAPI) ->
Endpoint
{
var playback = recordings
return { (target: ElloAPI) -> Endpoint in
var responseClosure: ((_ target: ElloAPI) -> EndpointSampleResponse)?
for (index, recording) in playback.enumerated()
where recording.endpoint.debugDescription == target.debugDescription {
responseClosure = recording.responseClosure
playback.remove(at: index)
break
}
let sampleResponseClosure: () -> EndpointSampleResponse
if let responseClosure = responseClosure {
sampleResponseClosure = {
return responseClosure(target)
}
}
else {
sampleResponseClosure = {
return EndpointSampleResponse.networkResponse(200, target.sampleData)
}
}
return Endpoint(
url: url(target),
sampleResponseClosure: sampleResponseClosure,
method: target.method,
task: target.task,
httpHeaderFields: target.headers
)
}
}
}
extension ElloProvider {
static func StubbingProvider() -> MoyaProvider<ElloAPI> {
return MoyaProvider<ElloAPI>(
endpointClosure: ElloProvider.endpointClosure,
stubClosure: MoyaProvider.immediatelyStub
)
}
static func DelayedStubbingProvider() -> MoyaProvider<ElloAPI> {
return MoyaProvider<ElloAPI>(
endpointClosure: ElloProvider.endpointClosure,
stubClosure: MoyaProvider.delayedStub(1)
)
}
static func ErrorStubbingProvider() -> MoyaProvider<ElloAPI> {
return MoyaProvider<ElloAPI>(
endpointClosure: ElloProvider_Specs.errorEndpointsClosure,
stubClosure: MoyaProvider.immediatelyStub
)
}
static func RecordedStubbingProvider(_ recordings: [RecordedResponse]) -> MoyaProvider<ElloAPI>
{
return MoyaProvider<ElloAPI>(
endpointClosure: ElloProvider_Specs.recordedEndpointsClosure(recordings),
stubClosure: MoyaProvider.immediatelyStub
)
}
}
| mit | 216676c27a367efac4a1d5da55938060 | 30.350515 | 100 | 0.60046 | 6.193483 | false | false | false | false |
open-telemetry/opentelemetry-swift | Examples/OTLP Exporter/main.swift | 1 | 4080 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import OpenTelemetryProtocolExporter
import OpenTelemetryApi
import OpenTelemetrySdk
import ResourceExtension
import StdoutExporter
import ZipkinExporter
import SignPostIntegration
import GRPC
import NIO
import NIOSSL
let sampleKey = "sampleKey"
let sampleValue = "sampleValue"
var resources = DefaultResources().get()
let instrumentationScopeName = "OTLPExporter"
let instrumentationScopeVersion = "semver:0.1.0"
var instrumentationScopeInfo = InstrumentationScopeInfo(name: instrumentationScopeName, version: instrumentationScopeVersion)
var tracer: TracerSdk
tracer = OpenTelemetrySDK.instance.tracerProvider.get(instrumentationName: instrumentationScopeName, instrumentationVersion: instrumentationScopeVersion) as! TracerSdk
let configuration = ClientConnection.Configuration(
target: .hostAndPort("localhost", 4317),
eventLoopGroup: MultiThreadedEventLoopGroup(numberOfThreads: 1)
)
let client = ClientConnection(configuration: configuration)
let otlpTraceExporter = OtlpTraceExporter(channel: client)
let stdoutExporter = StdoutExporter()
let spanExporter = MultiSpanExporter(spanExporters: [otlpTraceExporter, stdoutExporter])
let spanProcessor = SimpleSpanProcessor(spanExporter: spanExporter)
OpenTelemetrySDK.instance.tracerProvider.addSpanProcessor(spanProcessor)
if #available(macOS 10.14, *) {
OpenTelemetrySDK.instance.tracerProvider.addSpanProcessor(SignPostIntegration())
}
func createSpans() {
let parentSpan1 = tracer.spanBuilder(spanName: "Main").setSpanKind(spanKind: .client).startSpan()
parentSpan1.setAttribute(key: sampleKey, value: sampleValue)
OpenTelemetry.instance.contextProvider.setActiveSpan(parentSpan1)
for _ in 1...3 {
doWork()
}
Thread.sleep(forTimeInterval: 0.5)
let parentSpan2 = tracer.spanBuilder(spanName: "Another").setSpanKind(spanKind: .client).setActive(true).startSpan()
parentSpan2.setAttribute(key: sampleKey, value: sampleValue)
// do more Work
for _ in 1...3 {
doWork()
}
Thread.sleep(forTimeInterval: 0.5)
parentSpan2.end()
parentSpan1.end()
}
func doWork() {
let childSpan = tracer.spanBuilder(spanName: "doWork").setSpanKind(spanKind: .client).startSpan()
childSpan.setAttribute(key: sampleKey, value: sampleValue)
Thread.sleep(forTimeInterval: Double.random(in: 0..<10)/100)
childSpan.end()
}
// Create a Parent span (Main) and do some Work (child Spans). Repeat for another Span.
createSpans()
//Metrics
let otlpMetricExporter = OtlpMetricExporter(channel: client)
let processor = MetricProcessorSdk()
let meterProvider = MeterProviderSdk(metricProcessor: processor, metricExporter: otlpMetricExporter, metricPushInterval: 0.1)
var meter = meterProvider.get(instrumentationName: "otlp_example_meter'")
var exampleCounter = meter.createIntCounter(name: "otlp_example_counter")
var exampleMeasure = meter.createIntMeasure(name: "otlp_example_measure")
var exampleObserver = meter.createIntObserver(name: "otlp_example_observation") { observer in
var taskInfo = mach_task_basic_info()
var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size) / 4
let _: kern_return_t = withUnsafeMutablePointer(to: &taskInfo) {
$0.withMemoryRebound(to: integer_t.self, capacity: 1) {
task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count)
}
}
labels1 = ["dim1": "value1"]
observer.observe(value: Int(taskInfo.resident_size), labels: labels1)
}
var labels1 = ["dim1": "value1"]
for _ in 1...3000 {
exampleCounter.add(value: 1, labelset: meter.getLabelSet(labels: labels1))
exampleMeasure.record(value: 100, labelset: meter.getLabelSet(labels: labels1))
exampleMeasure.record(value: 500, labelset: meter.getLabelSet(labels: labels1))
exampleMeasure.record(value: 5, labelset: meter.getLabelSet(labels: labels1))
exampleMeasure.record(value: 750, labelset: meter.getLabelSet(labels: labels1))
sleep(1)
}
| apache-2.0 | 65d7ce726d85c7e2c75d904b5a8651e0 | 37.490566 | 167 | 0.763725 | 4.088176 | false | false | false | false |
hollance/swift-algorithm-club | Minimum Spanning Tree/Prim.swift | 4 | 1127 | //
// Prim.swift
//
//
// Created by xiang xin on 16/3/17.
//
//
func minimumSpanningTreePrim<T>(graph: Graph<T>) -> (cost: Int, tree: Graph<T>) {
var cost: Int = 0
var tree = Graph<T>()
guard let start = graph.vertices.first else {
return (cost: cost, tree: tree)
}
var visited = Set<T>()
var priorityQueue = PriorityQueue<(vertex: T, weight: Int, parent: T?)>(
sort: { $0.weight < $1.weight })
priorityQueue.enqueue((vertex: start, weight: 0, parent: nil))
while let head = priorityQueue.dequeue() {
let vertex = head.vertex
if visited.contains(vertex) {
continue
}
visited.insert(vertex)
cost += head.weight
if let prev = head.parent {
tree.addEdge(vertex1: prev, vertex2: vertex, weight: head.weight)
}
if let neighbours = graph.adjList[vertex] {
for neighbour in neighbours {
let nextVertex = neighbour.vertex
if !visited.contains(nextVertex) {
priorityQueue.enqueue((vertex: nextVertex, weight: neighbour.weight, parent: vertex))
}
}
}
}
return (cost: cost, tree: tree)
}
| mit | 301e8a38dc2f8c852519c583eede02ea | 24.044444 | 95 | 0.611358 | 3.532915 | false | false | false | false |
YesVideo/swix | swix/swix/swix/matrix/m-complex-math.swift | 1 | 3349 | //
// twoD-complex-math.swift
// swix
//
// Created by Scott Sievert on 7/15/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Swift
import Accelerate
public func rank(x:matrix)->Double{
let (_, S, _) = svd(x, compute_uv:false)
let m:Double = (x.shape.0 < x.shape.1 ? x.shape.1 : x.shape.0).double
let tol = S.max() * m * DOUBLE_EPSILON
return sum(S > tol)
}
public func dot(x: matrix, y: matrix) -> matrix{
return x.dot(y)
}
public func dot(A: matrix, x: ndarray) -> ndarray{
return A.dot(x)
}
public func svd(x: matrix, compute_uv:Bool=true) -> (matrix, ndarray, matrix){
let (m, n) = x.shape
let nS = m < n ? m : n // number singular values
let sigma = zeros(nS)
let vt = zeros((n,n))
var u = zeros((m,m))
var xx = zeros_like(x)
xx.flat = x.flat
xx = xx.T
let c_uv:CInt = compute_uv==true ? 1 : 0
svd_objc(!xx, m.cint, n.cint, !sigma, !vt, !u, c_uv)
// to get the svd result to match Python
let v = transpose(vt)
u = transpose(u)
return (u, sigma, v)
}
public func pinv(x:matrix)->matrix{
var (u, s, v) = svd(x)
let m = u.shape.0
let n = v.shape.1
let ma = m < n ? n : m
let cutoff = DOUBLE_EPSILON * ma.double * max(s)
let i = s > cutoff
let ipos = argwhere(i)
s[ipos] = 1 / s[ipos]
let ineg = argwhere(1-i)
s[ineg] = zeros_like(ineg)
var z = zeros((n, m))
z["diag"] = s
let res = v.T.dot(z).dot(u.T)
return res
}
public func inv(x: matrix) -> matrix{
assert(x.shape.0 == x.shape.1, "To take an inverse of a matrix, the matrix must be square. If you want the inverse of a rectangular matrix, use psuedoinverse.")
let y = x.copy()
let (M, N) = x.shape
var ipiv:Array<__CLPK_integer> = Array(count:M*M, repeatedValue:0)
var lwork:__CLPK_integer = __CLPK_integer(N*N)
// var work:[CDouble] = [CDouble](count:lwork, repeatedValue:0)
var work = [CDouble](count: Int(lwork), repeatedValue: 0.0)
var info:__CLPK_integer=0
var nc = __CLPK_integer(N)
dgetrf_(&nc, &nc, !y, &nc, &ipiv, &info)
dgetri_(&nc, !y, &nc, &ipiv, &work, &lwork, &info)
return y
}
public func solve(A: matrix, b: ndarray) -> ndarray{
let (m, n) = A.shape
assert(b.n == m, "Ax = b, A.rows == b.n. Sizes must match which makes sense mathematically")
assert(n == m, "Matrix must be square -- dictated by OpenCV")
let x = zeros(n)
CVWrapper.solve(!A, b:!b, x:!x, m:m.cint, n:n.cint)
return x
}
public func eig(x: matrix)->ndarray{
// matrix, value, vectors
let (m, n) = x.shape
assert(m == n, "Input must be square")
let value_real = zeros(m)
let value_imag = zeros(n)
var vector = zeros((n,n))
var work:[Double] = Array(count:n*n, repeatedValue:0.0)
var lwork = __CLPK_integer(4 * n)
var info = __CLPK_integer(1)
// don't compute right or left eigenvectors
let job = "N"
var jobvl = (job.cStringUsingEncoding(NSUTF8StringEncoding)?[0])!
var jobvr = (job.cStringUsingEncoding(NSUTF8StringEncoding)?[0])!
work[0] = Double(lwork)
var nc = __CLPK_integer(n)
dgeev_(&jobvl, &jobvr, &nc, !x, &nc,
!value_real, !value_imag, !vector, &nc, !vector, &nc,
&work, &lwork, &info)
vector = vector.T
return value_real
}
| mit | 239a5b424cffdf5bc079cb8c5dae8088 | 29.445455 | 164 | 0.589131 | 2.892055 | false | false | false | false |
emilstahl/swift | test/Parse/pointer_conversion.swift | 12 | 14124 | // RUN: %target-parse-verify-swift
// XFAIL: linux
class C {}
class D {}
func takesMutablePointer(x: UnsafeMutablePointer<Int>) {}
func takesMutableVoidPointer(x: UnsafeMutablePointer<Void>) {}
func takesMutableInt8Pointer(x: UnsafeMutablePointer<Int8>) {}
func takesMutableArrayPointer(x: UnsafeMutablePointer<[Int]>) {}
func takesConstPointer(x: UnsafePointer<Int>) -> Character { return "x" }
func takesConstInt8Pointer(x: UnsafePointer<Int8>) {}
func takesConstUInt8Pointer(x: UnsafePointer<UInt8>) {}
func takesConstVoidPointer(x: UnsafePointer<Void>) {}
func takesAutoreleasingPointer(x: AutoreleasingUnsafeMutablePointer<C>) {}
func mutablePointerArguments(p: UnsafeMutablePointer<Int>,
cp: UnsafePointer<Int>,
ap: AutoreleasingUnsafeMutablePointer<Int>) {
takesMutablePointer(nil)
takesMutablePointer(p)
takesMutablePointer(cp) // expected-error{{cannot convert value of type 'UnsafePointer<Int>' to expected argument type 'UnsafeMutablePointer<Int>'}}
takesMutablePointer(ap) // expected-error{{cannot convert value of type 'AutoreleasingUnsafeMutablePointer<Int>' to expected argument type 'UnsafeMutablePointer<Int>'}}
var i: Int = 0
var f: Float = 0
takesMutablePointer(&i)
takesMutablePointer(&f) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
takesMutablePointer(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'UnsafeMutablePointer<Int>'}}
takesMutablePointer(f) // expected-error{{cannot convert value of type 'Float' to expected argument type 'UnsafeMutablePointer<Int>'}}
var ii: [Int] = [0, 1, 2]
var ff: [Float] = [0, 1, 2]
takesMutablePointer(&ii)
takesMutablePointer(&ff) // expected-error{{cannot convert value of type '[Float]' to expected argument type 'Int'}}
takesMutablePointer(ii) // expected-error{{cannot convert value of type '[Int]' to expected argument type 'UnsafeMutablePointer<Int>'}}
takesMutablePointer(ff) // expected-error{{cannot convert value of type '[Float]' to expected argument type 'UnsafeMutablePointer<Int>'}}
takesMutableArrayPointer(&i) // expected-error{{cannot convert value of type 'Int' to expected argument type '[Int]'}}
takesMutableArrayPointer(&ii)
// We don't allow these conversions outside of function arguments.
var x: UnsafeMutablePointer<Int> = &i // expected-error{{cannot pass immutable value of type 'Int' as inout argument}}
x = &ii // expected-error{{cannot assign value of type '[Int]' to type 'Int'}}
_ = x
}
func mutableVoidPointerArguments(p: UnsafeMutablePointer<Int>,
cp: UnsafePointer<Int>,
ap: AutoreleasingUnsafeMutablePointer<Int>,
fp: UnsafeMutablePointer<Float>) {
takesMutableVoidPointer(nil)
takesMutableVoidPointer(p)
takesMutableVoidPointer(fp)
takesMutableVoidPointer(cp) // expected-error{{cannot convert value of type 'UnsafePointer<Int>' to expected argument type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>')}}
takesMutableVoidPointer(ap) // expected-error{{cannot convert value of type 'AutoreleasingUnsafeMutablePointer<Int>' to expected argument type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>')}}
var i: Int = 0
var f: Float = 0
takesMutableVoidPointer(&i)
takesMutableVoidPointer(&f)
takesMutableVoidPointer(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>')}}
takesMutableVoidPointer(f) // expected-error{{cannot convert value of type 'Float' to expected argument type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>')}}
var ii: [Int] = [0, 1, 2]
var dd: [CInt] = [1, 2, 3]
var ff: [Int] = [0, 1, 2]
takesMutableVoidPointer(&ii)
takesMutableVoidPointer(&dd)
takesMutableVoidPointer(&ff)
takesMutableVoidPointer(ii) // expected-error{{cannot convert value of type '[Int]' to expected argument type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>')}}
takesMutableVoidPointer(ff) // expected-error{{cannot convert value of type '[Int]' to expected argument type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>')}}
// We don't allow these conversions outside of function arguments.
var x: UnsafeMutablePointer<Void> = &i // expected-error{{cannot convert value of type 'inout Int' to specified type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>')}}
x = p // expected-error{{cannot assign value of type 'UnsafeMutablePointer<Int>' to type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>')}}
x = &ii // expected-error{{cannot assign value of type 'inout [Int]' (aka 'inout Array<Int>') to type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>')}}
_ = x
}
func constPointerArguments(p: UnsafeMutablePointer<Int>,
cp: UnsafePointer<Int>,
ap: AutoreleasingUnsafeMutablePointer<Int>) {
takesConstPointer(nil)
takesConstPointer(p)
takesConstPointer(cp)
takesConstPointer(ap)
var i: Int = 0
var f: Float = 0
takesConstPointer(&i)
takesConstPointer(&f) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
var ii: [Int] = [0, 1, 2]
var ff: [Float] = [0, 1, 2]
takesConstPointer(&ii)
takesConstPointer(&ff) // expected-error{{cannot convert value of type '[Float]' to expected argument type 'Int'}}
takesConstPointer(ii)
takesConstPointer(ff) // expected-error{{cannot convert value of type '[Float]' to expected argument type 'UnsafePointer<Int>'}}
takesConstPointer([0, 1, 2])
// <rdar://problem/22308330> QoI: CSDiags doesn't handle array -> pointer impl conversions well
takesConstPointer([0.0, 1.0, 2.0]) // expected-error{{cannot convert value of type 'Double' to expected element type 'Int'}}
// We don't allow these conversions outside of function arguments.
var x: UnsafePointer<Int> = &i // expected-error{{cannot pass immutable value of type 'Int' as inout argument}}
x = ii // expected-error{{cannot assign value of type '[Int]' to type 'UnsafePointer<Int>'}}
x = p // expected-error{{cannot assign value of type 'UnsafeMutablePointer<Int>' to type 'UnsafePointer<Int>'}}
x = ap // expected-error{{cannot assign value of type 'AutoreleasingUnsafeMutablePointer<Int>' to type 'UnsafePointer<Int>'}}
}
func constVoidPointerArguments(p: UnsafeMutablePointer<Int>,
fp: UnsafeMutablePointer<Float>,
cp: UnsafePointer<Int>,
cfp: UnsafePointer<Float>,
ap: AutoreleasingUnsafeMutablePointer<Int>,
afp: AutoreleasingUnsafeMutablePointer<Float>) {
takesConstVoidPointer(nil)
takesConstVoidPointer(p)
takesConstVoidPointer(fp)
takesConstVoidPointer(cp)
takesConstVoidPointer(cfp)
takesConstVoidPointer(ap)
takesConstVoidPointer(afp)
var i: Int = 0
var f: Float = 0
takesConstVoidPointer(&i)
takesConstVoidPointer(&f)
var ii: [Int] = [0, 1, 2]
var ff: [Float] = [0, 1, 2]
takesConstVoidPointer(&ii)
takesConstVoidPointer(&ff)
takesConstVoidPointer(ii)
takesConstVoidPointer(ff)
// TODO: These two should be accepted, tracked by rdar://17444930.
takesConstVoidPointer([0, 1, 2]) // expected-error {{cannot convert value of type 'Int' to expected element type '()'}}
takesConstVoidPointer([0.0, 1.0, 2.0]) // expected-error {{cannot convert value of type 'Double' to expected element type '()'}}
// We don't allow these conversions outside of function arguments.
var x: UnsafePointer<Void> = &i // expected-error{{cannot convert value of type 'inout Int' to specified type 'UnsafePointer<Void>' (aka 'UnsafePointer<()>')}}
x = ii // expected-error{{cannot assign value of type '[Int]' to type 'UnsafePointer<Void>' (aka 'UnsafePointer<()>')}}
x = p // expected-error{{cannot assign value of type 'UnsafeMutablePointer<Int>' to type 'UnsafePointer<Void>' (aka 'UnsafePointer<()>')}}
x = fp // expected-error{{cannot assign value of type 'UnsafeMutablePointer<Float>' to type 'UnsafePointer<Void>' (aka 'UnsafePointer<()>')}}
x = cp // expected-error{{cannot assign value of type 'UnsafePointer<Int>' to type 'UnsafePointer<Void>' (aka 'UnsafePointer<()>')}}
x = cfp // expected-error{{cannot assign value of type 'UnsafePointer<Float>' to type 'UnsafePointer<Void>' (aka 'UnsafePointer<()>')}}
x = ap // expected-error{{cannot assign value of type 'AutoreleasingUnsafeMutablePointer<Int>' to type 'UnsafePointer<Void>' (aka 'UnsafePointer<()>')}}
x = afp // expected-error{{cannot assign value of type 'AutoreleasingUnsafeMutablePointer<Float>' to type 'UnsafePointer<Void>' (aka 'UnsafePointer<()>')}}
_ = x
}
func stringArguments(s: String) {
var s = s
takesConstVoidPointer(s)
takesConstInt8Pointer(s)
takesConstUInt8Pointer(s)
takesConstPointer(s) // expected-error{{cannot convert value of type 'String' to expected argument type 'UnsafePointer<Int>'}}
takesMutableVoidPointer(s) // expected-error{{cannot convert value of type 'String' to expected argument type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>')}}
takesMutableInt8Pointer(s) // expected-error{{cannot convert value of type 'String' to expected argument type 'UnsafeMutablePointer<Int8>'}}
takesMutableInt8Pointer(&s) // expected-error{{cannot convert value of type 'String' to expected argument type 'Int8'}}
takesMutablePointer(s) // expected-error{{cannot convert value of type 'String' to expected argument type 'UnsafeMutablePointer<Int>'}}
takesMutablePointer(&s) // expected-error{{cannot convert value of type 'String' to expected argument type 'Int'}}
}
func autoreleasingPointerArguments(p: UnsafeMutablePointer<Int>,
cp: UnsafePointer<Int>,
ap: AutoreleasingUnsafeMutablePointer<C>) {
takesAutoreleasingPointer(nil)
takesAutoreleasingPointer(p) // expected-error{{cannot convert value of type 'UnsafeMutablePointer<Int>' to expected argument type 'AutoreleasingUnsafeMutablePointer<C>'}}
takesAutoreleasingPointer(cp) // expected-error{{cannot convert value of type 'UnsafePointer<Int>' to expected argument type 'AutoreleasingUnsafeMutablePointer<C>'}}
takesAutoreleasingPointer(ap)
var c: C = C()
takesAutoreleasingPointer(&c)
takesAutoreleasingPointer(c) // expected-error{{cannot convert value of type 'C' to expected argument type 'AutoreleasingUnsafeMutablePointer<C>'}}
var d: D = D()
takesAutoreleasingPointer(&d) // expected-error{{cannot convert value of type 'D' to expected argument type 'C'}}
takesAutoreleasingPointer(d) // expected-error{{cannot convert value of type 'D' to expected argument type 'AutoreleasingUnsafeMutablePointer<C>'}}
var cc: [C] = [C(), C()]
var dd: [D] = [D(), D()]
takesAutoreleasingPointer(&cc) // expected-error{{cannot convert value of type '[C]' to expected argument type 'C'}}
takesAutoreleasingPointer(&dd) // expected-error{{cannot convert value of type '[D]' to expected argument type 'C'}}
let _: AutoreleasingUnsafeMutablePointer<C> = &c // expected-error{{cannot pass immutable value of type 'C' as inout argument}}
}
func pointerConstructor(x: UnsafeMutablePointer<Int>) -> UnsafeMutablePointer<Float> {
return UnsafeMutablePointer(x)
}
func pointerArithmetic(x: UnsafeMutablePointer<Int>, y: UnsafeMutablePointer<Int>,
i: Int) {
_ = x + i
_ = x - y
}
func genericPointerArithmetic<T>(x: UnsafeMutablePointer<T>, i: Int, t: T) -> UnsafeMutablePointer<T> {
let p = x + i
p.initialize(t)
}
func passPointerToClosure(f: UnsafeMutablePointer<Float> -> Int) -> Int { }
func pointerInClosure(f: UnsafeMutablePointer<Int> -> Int) -> Int {
return passPointerToClosure { f(UnsafeMutablePointer($0)) }
}
struct NotEquatable {}
func arrayComparison(x: [NotEquatable], y: [NotEquatable], p: UnsafeMutablePointer<NotEquatable>) {
var x = x
// Don't allow implicit array-to-pointer conversions in operators.
let a: Bool = x == y // expected-error{{binary operator '==' cannot be applied to two '[NotEquatable]' operands}}
// expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists:}}
let _: Bool = p == &x // Allowed!
}
func addressConversion(p: UnsafeMutablePointer<Int>, x: Int) {
var x = x
let _: Bool = p == &x
}
// <rdar://problem/19478919> QoI: poor error: '&' used with non-inout argument of type 'UnsafeMutablePointer<Int32>'
func f19478919() {
var viewport: Int = 1 // intentionally incorrect type, not Int32
func GLKProject(a : UnsafeMutablePointer<Int32>) {}
GLKProject(&viewport) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Int32'}}
func GLKProjectUP(a : UnsafePointer<Int32>) {}
func UP_Void(a : UnsafePointer<Void>) {}
func UMP_Void(a : UnsafeMutablePointer<Void>) {}
UP_Void(&viewport)
UMP_Void(&viewport)
let cst = 42 // expected-note 2 {{change 'let' to 'var' to make it mutable}}
UP_Void(&cst) // expected-error {{cannot pass immutable value as inout argument: 'cst' is a 'let' constant}}
UMP_Void(&cst) // expected-error {{cannot pass immutable value as inout argument: 'cst' is a 'let' constant}}
}
// <rdar://problem/23202128> QoI: Poor diagnostic with let vs. var passed to C function
func f23202128() {
func UP(p: UnsafePointer<Int32>) {}
func UMP(p: UnsafeMutablePointer<Int32>) {}
let pipe: [Int32] = [0, 0] // expected-note {{change 'let' to 'var' to make it mutable}}}}
UMP(&pipe) // expected-error {{cannot pass immutable value as inout argument: 'pipe' is a 'let' constant}}
var pipe2: [Int] = [0, 0]
UMP(&pipe2) // expected-error {{cannot convert value of type '[Int]' to expected argument type 'Int32'}}
UP(pipe) // ok
UP(&pipe) // expected-error {{'&' is not allowed passing array value as 'UnsafePointer<Int32>' argument}} {{6-7=}}
}
| apache-2.0 | 9ec21eb35db1c92f830d7cd7fa2897fa | 54.388235 | 208 | 0.707661 | 4.46115 | false | false | false | false |
loiclec/Apodimark | Sources/Apodimark/BlockParsing/LineLexer.swift | 1 | 19894 | //
// LineLexer.swift
// Apodimark
//
/*
HOW TO READ THE COMMENTS:
Example:
Lorem Ipsum blah blah
|_<---
Means that scanner points to “s”
Therefore:
- “p” has already been read
- scanner.startIndex is the index of “s”
- the next scanner.peek() will return “s”
*/
/// Error type used for parsing a List line
fileprivate enum ListParsingError: Error {
case notAListMarker
case emptyListItem(ListKind)
}
extension MarkdownParser {
/// Advances the scanner to the end of the valid marker, or throws an error and leaves the scanner intact
/// if the list marker is invalid.
/// - parameter scanner: a scanner whose `startIndex` points to the first token of the list marker
/// (e.g. a hyphen, an asterisk, a digit)
/// - throws: `ListParsingError.notAListMarker` if the list marker is invalid
/// - returns: the kind of the list marker
fileprivate static func readListMarker(_ scanner: inout Scanner<View>) throws -> ListKind {
guard case let firstToken? = scanner.pop() else {
preconditionFailure()
}
var value: Int
switch firstToken {
case Codec.hyphen : return .bullet(.hyphen)
case Codec.asterisk : return .bullet(.star)
case Codec.plus : return .bullet(.plus)
case Codec.zero...Codec.nine: value = Codec.digit(representedByToken: firstToken)
case _ : preconditionFailure()
}
// 1234)
// |_<---
var length = 1
try scanner.popWhile { token in
guard case let token? = token, token != Codec.linefeed else {
throw ListParsingError.notAListMarker // e.g. 1234 followed by end of line / end of string
}
switch token {
case Codec.fullstop, Codec.rightparen:
return .stop // e.g. 1234|)| -> hurray! confirm and stop now
case Codec.zero...Codec.nine:
guard length < 9 else {
throw ListParsingError.notAListMarker // e.g. 123456789|0| -> too long
}
length += 1
value = value * 10 + Codec.digit(representedByToken: token)
return .pop // e.g. 12|3| -> ok, keep reading
case _:
throw ListParsingError.notAListMarker // e.g. 12|a| -> not a list marker
}
}
// will not crash because popWhile threw an error if lastToken is not fullstop or rightparen
let lastToken = scanner.pop()!
switch lastToken {
case Codec.fullstop : return .number(.dot, value)
case Codec.rightparen: return .number(.parenthesis, value)
default : fatalError()
}
}
/// Tries to parse a List. Advances the scanner to the end of the line and return the parsed line.
/// - parameter scanner: a scanner whose `startIndex` points to the start of potential List line
/// - parameter indent: the indent of the line being parsed
/// - return: the parsed Line
fileprivate static func parseList(_ scanner: inout Scanner<View>, indent: Indent, context: LineLexerContext<Codec>) -> Line {
let indexBeforeList = scanner.startIndex
// let initialSubView = scanner
// 1234)
// |_<---
do {
let kind = try MarkdownParser.readListMarker(&scanner)
// 1234)
// |_<---
guard case let token? = scanner.pop(ifNot: Codec.linefeed) else {
throw ListParsingError.emptyListItem(kind)
}
guard token == Codec.space else {
throw ListParsingError.notAListMarker
}
// 1234)
// |_<---
let rest = parseLine(&scanner, context: context)
return Line(.list(kind, rest), indent, indexBeforeList ..< scanner.startIndex)
}
catch ListParsingError.notAListMarker {
// xxxxx…
// |_<--- scanner could point anywhere but not past the end of the line
scanner.popUntil(Codec.linefeed)
return Line(.text, indent, indexBeforeList ..< scanner.startIndex)
}
catch ListParsingError.emptyListItem(let kind) {
// 1234)\n
// |__<---
let finalIndices = indexBeforeList ..< scanner.startIndex
let rest = Line(.empty, indent, finalIndices)
return Line(.list(kind, rest), indent, finalIndices)
}
catch {
fatalError()
}
}
}
/// State used for read the content of a Header line
fileprivate enum HeaderTextReadingState { // e.g. for # Hello World #### \n
case text // # He|_
case textSpaces // # Hello |_
case hashes // # Hello World #|_
case endSpaces // # Hello World #### |_
}
extension MarkdownParser {
/// Reads the content of a Header line
/// - parameter scanner: a scanner whose `startIndex` points to to the start of the text in a Header line
/// - returns: the index pointing to the end of the text in the header
fileprivate static func readHeaderText(_ scanner: inout Scanner<View>) -> View.Index {
var state = HeaderTextReadingState.textSpaces
var end = scanner.startIndex
while case let token? = scanner.pop(ifNot: Codec.linefeed) {
switch state {
case .text:
if token == Codec.space { state = .textSpaces }
else { end = scanner.startIndex }
case .textSpaces:
if token == Codec.space { break }
else if token == Codec.hash { state = .hashes }
else { (state, end) = (.text, scanner.startIndex) }
case .hashes:
if token == Codec.hash { state = .hashes }
else if token == Codec.space { state = .endSpaces }
else { (state, end) = (.text, scanner.startIndex) }
case .endSpaces:
if token == Codec.space { break }
else if token == Codec.hash { (state, end) = (.hashes, scanner.data.index(before: scanner.startIndex)) }
else { (state, end) = (.text, scanner.startIndex) }
}
}
return end
}
}
/// Error type used for parsing a header line
fileprivate enum HeaderParsingError: Error {
case notAHeader
case emptyHeader(Int32)
}
extension MarkdownParser {
/// Tries to parse a Header. Advances the scanner to the end of the line.
/// - parameter scanner: a scanner whose `startIndex` points the start of a potential Header line
/// - parameter indent: the indent of the line being parsed
/// - return: the parsed Line
fileprivate static func parseHeader(_ scanner: inout Scanner<View>, indent: Indent) -> Line {
let indexBeforeHeader = scanner.startIndex
// xxxxxx
// |_<--- (start of line)
do {
var level: Int32 = 0
try scanner.popWhile { token in
guard case let token? = token else {
throw HeaderParsingError.emptyHeader(level)
}
switch token {
case Codec.hash where level < 6:
level = level + 1
return .pop
case Codec.space:
return .stop
case Codec.linefeed:
throw HeaderParsingError.emptyHeader(level)
default:
throw HeaderParsingError.notAHeader
}
}
// ## Hello
// |_<---
scanner.popWhile(Codec.space)
// ## Hello
// |_<---
let start = scanner.startIndex
let end = readHeaderText(&scanner)
// ## Hello World ####\n
// | | |__<---
// |_ |_
// start end
let headerkind = LineKind.header(start ..< end, level)
return Line(headerkind, indent, indexBeforeHeader ..< scanner.startIndex)
}
catch HeaderParsingError.notAHeader {
// scanner could point anywhere but not past end of line
scanner.popUntil(Codec.linefeed)
return Line(.text, indent, indexBeforeHeader ..< scanner.startIndex)
}
catch HeaderParsingError.emptyHeader(let level) {
// scanner could point anywhere but not past end of line
scanner.popUntil(Codec.linefeed)
let lineKind = LineKind.header(scanner.startIndex ..< scanner.startIndex, level)
return Line(lineKind, indent, indexBeforeHeader ..< scanner.startIndex)
}
catch {
fatalError()
}
}
}
/// Error type used for a parsing a Fence
fileprivate enum FenceParsingError: Error {
case notAFence
case emptyFence(FenceKind, Int32)
}
extension MarkdownParser {
/// Tries to read the name of Fence line.
///
/// Advances the scanner to the end of the line if it succeeded, throws an error otherwise.
///
/// - parameter scanner: a scanner pointing to the first letter of a potential Fence’s name
/// - throws: `FenceParsingError.notAFence` if the line is not a Fence line
/// - returns: the index pointing to the end of the name
fileprivate static func readFenceName(_ scanner: inout Scanner<View>) throws -> View.Index {
// ``` name
// |_<---
var end = scanner.startIndex
while case let token? = scanner.pop(ifNot: Codec.linefeed) {
switch token {
case Codec.space:
break
case Codec.backtick:
throw FenceParsingError.notAFence
case _:
end = scanner.startIndex
}
}
// ``` name \n
// |_ |__<---
// end
return end
}
}
extension MarkdownParser {
/// Tries to parse a Fence line.
///
/// Advances the scanner to the end of the line.
///
/// - parameter scanner: a scanner whose pointing to the start of what might be a Fence line
/// - parameter indent: the indent of the line being parsed
/// - returns: the parsed line
fileprivate static func parseFence(_ scanner: inout Scanner<View>, indent: Indent) -> Line {
let indexBeforeFence = scanner.startIndex
guard let firstLetter = scanner.pop() else { preconditionFailure() }
let kind: FenceKind = firstLetter == Codec.backtick ? .backtick : .tilde
// ``` name
// |_<---
do {
var level: Int32 = 1
try scanner.popWhile { token in
guard case let token? = token else {
throw FenceParsingError.emptyFence(kind, level)
}
switch token {
case firstLetter:
level = level + 1
return .pop
case Codec.linefeed:
guard level >= 3 else {
throw FenceParsingError.notAFence
}
throw FenceParsingError.emptyFence(kind, level)
case _:
guard level >= 3 else {
throw FenceParsingError.notAFence
}
return .stop
}
}
// ``` name
// |_<---
scanner.popWhile(Codec.space)
// ``` name
// |_<---
let start = scanner.startIndex
let end = try readFenceName(&scanner)
// ``` name \n
// | | |__<---
// |_ |_
// start end
let linekind = LineKind.fence(kind, start ..< end, level)
return Line(linekind, indent, indexBeforeFence ..< scanner.startIndex)
}
catch FenceParsingError.notAFence {
// scanner could point anywhere but not past end of line
scanner.popUntil(Codec.linefeed)
return Line(.text, indent, indexBeforeFence ..< scanner.startIndex)
}
catch FenceParsingError.emptyFence(let kind, let level) {
// scanner could point anywhere but not past end of line
scanner.popUntil(Codec.linefeed)
let linekind = LineKind.fence(kind, scanner.startIndex ..< scanner.startIndex, level)
return Line(linekind, indent, indexBeforeFence ..< scanner.startIndex)
}
catch {
fatalError()
}
}
}
/// Error type used for parsing a ThematicBreak line
fileprivate struct NotAThematicBreakError: Error {}
extension MarkdownParser {
/// Tries to read a ThematicBreak line.
///
/// Advances the scanner to the end of the line if it succeeded, throws an error otherwise.
///
/// - precondition: `firstToken == scanner.pop()`
///
/// (not checked at runtime)
///
/// - parameter scanner: a scanner pointing to the start of what might be a ThematicBreak line
/// - parameter firstToken: the first token of the potential ThematicBreak line
/// - throws: `NotAThematicBreakError()` if the line is not a ThematicBreak line
fileprivate static func readThematicBreak(_ scanner: inout Scanner<View>, firstToken: Codec.CodeUnit) throws {
// * * *
// |_<--- (start of line)
var level = 0
try scanner.popWhile { token in
guard case let token? = token, token != Codec.linefeed else {
guard level >= 3 else {
throw NotAThematicBreakError() // e.g. * * -> not enough stars -> not a thematic break
}
return .stop // e.g. * * * * -> hurray! confirm and stop now
}
switch token {
case firstToken: // e.g. * * |*| -> ok, keep reading
level += 1
return .pop
case Codec.space, Codec.tab: // e.g. * * | | -> ok, keep reading
return .pop
default:
throw NotAThematicBreakError() // e.g. * * |g| -> not a thematic break!
}
}
}
}
/// Error type used when parsing a ReferenceDefinition line
fileprivate struct NotAReferenceDefinitionError: Error {}
extension MarkdownParser {
/// Tries to parse a ReferenceDefinition line.
///
/// Advances the scanner to the end of line if it succeeded, throws an error otherwise.
///
/// - parameter scanner: a scanner pointing to the first token of what might be a ReferenceDefinition line
/// - parameter indent: the indent of the line being parsed
/// - throws: `NotAReferenceDefinitionError()` if the line is not a ReferenceDefinition line
/// - returns: the parsed line
fileprivate static func parseReferenceDefinition(_ scanner: inout Scanner<View>, indent: Indent) throws -> Line {
// [hello]: world
// |_<---
let indexBeforeRefDef = scanner.startIndex
_ = scanner.pop()
// [hello]: world
// |_<---
let idxBeforeTitle = scanner.startIndex
var escapeNext = false
try scanner.popWhile { (token: Codec.CodeUnit?) throws -> PopOrStop in
guard case let token? = token, token != Codec.linefeed else {
throw NotAReferenceDefinitionError()
}
guard !escapeNext else {
escapeNext = false
return .pop
}
guard token != Codec.leftsqbck else {
throw NotAReferenceDefinitionError()
}
guard token != Codec.rightsqbck else {
return .stop
}
escapeNext = (token == Codec.backslash)
return .pop
}
let idxAfterTitle = scanner.startIndex
guard idxAfterTitle > scanner.data.index(after: idxBeforeTitle) else {
throw NotAReferenceDefinitionError()
}
_ = scanner.pop(Codec.rightsqbck)
// [hello]: world
// |_<---
guard scanner.pop(Codec.colon) else { throw NotAReferenceDefinitionError() }
scanner.popWhile(Codec.space)
let idxBeforeDefinition = scanner.startIndex
// [hello]: world
// |_<---
scanner.popUntil(Codec.linefeed)
let idxAfterDefinition = scanner.startIndex
guard idxBeforeDefinition < idxAfterDefinition else {
throw NotAReferenceDefinitionError()
}
let definition = idxBeforeDefinition ..< idxAfterDefinition
let title = idxBeforeTitle ..< idxAfterTitle
return Line(.reference(title, definition), indent, indexBeforeRefDef ..< scanner.startIndex)
}
}
struct LineLexerContext <C: MarkdownParserCodec> {
var listKindBeingRead: C.CodeUnit?
static var `default`: LineLexerContext {
return .init(listKindBeingRead: nil)
}
}
extension MarkdownParser {
static func parseLine(_ scanner: inout Scanner<View>, context: LineLexerContext<Codec>) -> Line {
// xxxxx
// |_<--- (start of line)
var indent = Indent()
scanner.popWhile { (token: Codec.CodeUnit?) -> PopOrStop in
guard case let token? = token else {
return .stop
}
guard case let indentKind? = IndentKind(token, codec: Codec.self) else {
return .stop
}
indent.add(indentKind)
return .pop
}
let indexAfterIndent = scanner.startIndex
// xxxx
// |_<--- (after indent)
guard case let firstToken? = scanner.peek() else {
return Line(.empty, Indent(), scanner.indices)
}
switch firstToken {
case Codec.quote:
_ = scanner.pop()!
let rest = parseLine(&scanner, context: .default)
return Line(.quote(rest), indent, indexAfterIndent ..< scanner.startIndex)
case Codec.underscore:
guard case .some = try? readThematicBreak(&scanner, firstToken: firstToken) else {
scanner.popUntil(Codec.linefeed)
return Line(.text, indent, indexAfterIndent ..< scanner.startIndex)
}
return Line(.thematicBreak, indent, indexAfterIndent ..< scanner.startIndex)
case Codec.hyphen, Codec.asterisk:
if firstToken != context.listKindBeingRead, case .some = try? readThematicBreak(&scanner, firstToken: firstToken) {
return Line(.thematicBreak, indent, indexAfterIndent ..< scanner.startIndex)
} else {
var context = context
context.listKindBeingRead = firstToken
return parseList(&scanner, indent: indent, context: context)
}
case Codec.plus, Codec.zero...Codec.nine:
return parseList(&scanner, indent: indent, context: context)
case Codec.hash:
return parseHeader(&scanner, indent: indent)
case Codec.linefeed:
return Line(.empty, indent, indexAfterIndent ..< scanner.startIndex)
case Codec.backtick, Codec.tilde:
return parseFence(&scanner, indent: indent)
case Codec.leftsqbck:
guard case let line? = try? parseReferenceDefinition(&scanner, indent: indent) else {
scanner.popUntil(Codec.linefeed)
return Line(.text, indent, indexAfterIndent ..< scanner.startIndex)
}
return line
case _:
scanner.popUntil(Codec.linefeed)
return Line(.text, indent, indexAfterIndent ..< scanner.startIndex)
}
}
}
| mit | 551a99978f9a60b9e5dc55c5e4e67472 | 32.570946 | 129 | 0.560481 | 4.9847 | false | false | false | false |
thomasvl/swift-protobuf | Sources/SwiftProtobufCore/JSONEncoder.swift | 2 | 14274 | // Sources/SwiftProtobuf/JSONEncoder.swift - JSON Encoding support
//
// Copyright (c) 2014 - 2019 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// JSON serialization engine.
///
// -----------------------------------------------------------------------------
import Foundation
private let asciiZero = UInt8(ascii: "0")
private let asciiOne = UInt8(ascii: "1")
private let asciiTwo = UInt8(ascii: "2")
private let asciiThree = UInt8(ascii: "3")
private let asciiFour = UInt8(ascii: "4")
private let asciiFive = UInt8(ascii: "5")
private let asciiSix = UInt8(ascii: "6")
private let asciiSeven = UInt8(ascii: "7")
private let asciiEight = UInt8(ascii: "8")
private let asciiNine = UInt8(ascii: "9")
private let asciiMinus = UInt8(ascii: "-")
private let asciiPlus = UInt8(ascii: "+")
private let asciiEquals = UInt8(ascii: "=")
private let asciiColon = UInt8(ascii: ":")
private let asciiComma = UInt8(ascii: ",")
private let asciiDoubleQuote = UInt8(ascii: "\"")
private let asciiBackslash = UInt8(ascii: "\\")
private let asciiForwardSlash = UInt8(ascii: "/")
private let asciiOpenSquareBracket = UInt8(ascii: "[")
private let asciiCloseSquareBracket = UInt8(ascii: "]")
private let asciiOpenCurlyBracket = UInt8(ascii: "{")
private let asciiCloseCurlyBracket = UInt8(ascii: "}")
private let asciiUpperA = UInt8(ascii: "A")
private let asciiUpperB = UInt8(ascii: "B")
private let asciiUpperC = UInt8(ascii: "C")
private let asciiUpperD = UInt8(ascii: "D")
private let asciiUpperE = UInt8(ascii: "E")
private let asciiUpperF = UInt8(ascii: "F")
private let asciiUpperZ = UInt8(ascii: "Z")
private let asciiLowerA = UInt8(ascii: "a")
private let asciiLowerZ = UInt8(ascii: "z")
private let base64Digits: [UInt8] = {
var digits = [UInt8]()
digits.append(contentsOf: asciiUpperA...asciiUpperZ)
digits.append(contentsOf: asciiLowerA...asciiLowerZ)
digits.append(contentsOf: asciiZero...asciiNine)
digits.append(asciiPlus)
digits.append(asciiForwardSlash)
return digits
}()
private let hexDigits: [UInt8] = {
var digits = [UInt8]()
digits.append(contentsOf: asciiZero...asciiNine)
digits.append(contentsOf: asciiUpperA...asciiUpperF)
return digits
}()
internal struct JSONEncoder {
private var data = [UInt8]()
private var separator: UInt8?
internal init() {}
internal var dataResult: Data { return Data(data) }
internal var stringResult: String {
get {
return String(bytes: data, encoding: String.Encoding.utf8)!
}
}
internal var bytesResult: [UInt8] { return data }
/// Append a `StaticString` to the JSON text. Because
/// `StaticString` is already UTF8 internally, this is faster
/// than appending a regular `String`.
internal mutating func append(staticText: StaticString) {
let buff = UnsafeBufferPointer(start: staticText.utf8Start, count: staticText.utf8CodeUnitCount)
data.append(contentsOf: buff)
}
/// Append a `_NameMap.Name` to the JSON text surrounded by quotes.
/// As with StaticString above, a `_NameMap.Name` provides pre-converted
/// UTF8 bytes, so this is much faster than appending a regular
/// `String`.
internal mutating func appendQuoted(name: _NameMap.Name) {
data.append(asciiDoubleQuote)
data.append(contentsOf: name.utf8Buffer)
data.append(asciiDoubleQuote)
}
/// Append a `String` to the JSON text.
internal mutating func append(text: String) {
data.append(contentsOf: text.utf8)
}
internal mutating func append(bytes: [UInt8]) {
data.append(contentsOf: bytes)
}
/// Append a raw utf8 in a `Data` to the JSON text.
internal mutating func append(utf8Data: Data) {
data.append(contentsOf: utf8Data)
}
/// Append a raw utf8 in a `[UInt8]` to the JSON text.
internal mutating func append(utf8Data: [UInt8]) {
data.append(contentsOf: utf8Data)
}
/// Begin a new field whose name is given as a `_NameMap.Name`
internal mutating func startField(name: _NameMap.Name) {
if let s = separator {
data.append(s)
}
appendQuoted(name: name)
data.append(asciiColon)
separator = asciiComma
}
/// Begin a new field whose name is given as a `String`.
internal mutating func startField(name: String) {
if let s = separator {
data.append(s)
}
data.append(asciiDoubleQuote)
// Can avoid overhead of putStringValue, since
// the JSON field names are always clean ASCII.
data.append(contentsOf: name.utf8)
append(staticText: "\":")
separator = asciiComma
}
/// Begin a new extension field
internal mutating func startExtensionField(name: String) {
if let s = separator {
data.append(s)
}
append(staticText: "\"[")
data.append(contentsOf: name.utf8)
append(staticText: "]\":")
separator = asciiComma
}
/// Append an open square bracket `[` to the JSON.
internal mutating func startArray() {
data.append(asciiOpenSquareBracket)
separator = nil
}
/// Append a close square bracket `]` to the JSON.
internal mutating func endArray() {
data.append(asciiCloseSquareBracket)
separator = asciiComma
}
/// Append a comma `,` to the JSON.
internal mutating func comma() {
data.append(asciiComma)
}
/// Append an open curly brace `{` to the JSON.
/// Assumes this object is part of an array of objects.
internal mutating func startArrayObject() {
if let s = separator {
data.append(s)
}
data.append(asciiOpenCurlyBracket)
separator = nil
}
/// Append an open curly brace `{` to the JSON.
internal mutating func startObject() {
data.append(asciiOpenCurlyBracket)
separator = nil
}
/// Append a close curly brace `}` to the JSON.
internal mutating func endObject() {
data.append(asciiCloseCurlyBracket)
separator = asciiComma
}
/// Write a JSON `null` token to the output.
internal mutating func putNullValue() {
append(staticText: "null")
}
/// Append a float value to the output.
/// This handles Nan and infinite values by
/// writing well-known string values.
internal mutating func putFloatValue(value: Float) {
if value.isNaN {
append(staticText: "\"NaN\"")
} else if !value.isFinite {
if value < 0 {
append(staticText: "\"-Infinity\"")
} else {
append(staticText: "\"Infinity\"")
}
} else {
data.append(contentsOf: value.debugDescription.utf8)
}
}
/// Append a double value to the output.
/// This handles Nan and infinite values by
/// writing well-known string values.
internal mutating func putDoubleValue(value: Double) {
if value.isNaN {
append(staticText: "\"NaN\"")
} else if !value.isFinite {
if value < 0 {
append(staticText: "\"-Infinity\"")
} else {
append(staticText: "\"Infinity\"")
}
} else {
data.append(contentsOf: value.debugDescription.utf8)
}
}
/// Append a UInt64 to the output (without quoting).
private mutating func appendUInt(value: UInt64) {
if value >= 10 {
appendUInt(value: value / 10)
}
data.append(asciiZero + UInt8(value % 10))
}
/// Append an Int64 to the output (without quoting).
private mutating func appendInt(value: Int64) {
if value < 0 {
data.append(asciiMinus)
// This is the twos-complement negation of value,
// computed in a way that won't overflow a 64-bit
// signed integer.
appendUInt(value: 1 + ~UInt64(bitPattern: value))
} else {
appendUInt(value: UInt64(bitPattern: value))
}
}
/// Write an Enum as an int.
internal mutating func putEnumInt(value: Int) {
appendInt(value: Int64(value))
}
/// Write an `Int64` using protobuf JSON quoting conventions.
internal mutating func putQuotedInt64(value: Int64) {
data.append(asciiDoubleQuote)
appendInt(value: value)
data.append(asciiDoubleQuote)
}
internal mutating func putNonQuotedInt64(value: Int64) {
appendInt(value: value)
}
/// Write an `Int32` with quoting suitable for
/// using the value as a map key.
internal mutating func putQuotedInt32(value: Int32) {
data.append(asciiDoubleQuote)
appendInt(value: Int64(value))
data.append(asciiDoubleQuote)
}
/// Write an `Int32` in the default format.
internal mutating func putNonQuotedInt32(value: Int32) {
appendInt(value: Int64(value))
}
/// Write a `UInt64` using protobuf JSON quoting conventions.
internal mutating func putQuotedUInt64(value: UInt64) {
data.append(asciiDoubleQuote)
appendUInt(value: value)
data.append(asciiDoubleQuote)
}
internal mutating func putNonQuotedUInt64(value: UInt64) {
appendUInt(value: value)
}
/// Write a `UInt32` with quoting suitable for
/// using the value as a map key.
internal mutating func putQuotedUInt32(value: UInt32) {
data.append(asciiDoubleQuote)
appendUInt(value: UInt64(value))
data.append(asciiDoubleQuote)
}
/// Write a `UInt32` in the default format.
internal mutating func putNonQuotedUInt32(value: UInt32) {
appendUInt(value: UInt64(value))
}
/// Write a `Bool` with quoting suitable for
/// using the value as a map key.
internal mutating func putQuotedBoolValue(value: Bool) {
data.append(asciiDoubleQuote)
putNonQuotedBoolValue(value: value)
data.append(asciiDoubleQuote)
}
/// Write a `Bool` in the default format.
internal mutating func putNonQuotedBoolValue(value: Bool) {
if value {
append(staticText: "true")
} else {
append(staticText: "false")
}
}
/// Append a string value escaping special characters as needed.
internal mutating func putStringValue(value: String) {
data.append(asciiDoubleQuote)
for c in value.unicodeScalars {
switch c.value {
// Special two-byte escapes
case 8: append(staticText: "\\b")
case 9: append(staticText: "\\t")
case 10: append(staticText: "\\n")
case 12: append(staticText: "\\f")
case 13: append(staticText: "\\r")
case 34: append(staticText: "\\\"")
case 92: append(staticText: "\\\\")
case 0...31, 127...159: // Hex form for C0 control chars
append(staticText: "\\u00")
data.append(hexDigits[Int(c.value / 16)])
data.append(hexDigits[Int(c.value & 15)])
case 23...126:
data.append(UInt8(truncatingIfNeeded: c.value))
case 0x80...0x7ff:
data.append(0xc0 + UInt8(truncatingIfNeeded: c.value >> 6))
data.append(0x80 + UInt8(truncatingIfNeeded: c.value & 0x3f))
case 0x800...0xffff:
data.append(0xe0 + UInt8(truncatingIfNeeded: c.value >> 12))
data.append(0x80 + UInt8(truncatingIfNeeded: (c.value >> 6) & 0x3f))
data.append(0x80 + UInt8(truncatingIfNeeded: c.value & 0x3f))
default:
data.append(0xf0 + UInt8(truncatingIfNeeded: c.value >> 18))
data.append(0x80 + UInt8(truncatingIfNeeded: (c.value >> 12) & 0x3f))
data.append(0x80 + UInt8(truncatingIfNeeded: (c.value >> 6) & 0x3f))
data.append(0x80 + UInt8(truncatingIfNeeded: c.value & 0x3f))
}
}
data.append(asciiDoubleQuote)
}
/// Append a bytes value using protobuf JSON Base-64 encoding.
internal mutating func putBytesValue(value: Data) {
data.append(asciiDoubleQuote)
if value.count > 0 {
value.withUnsafeBytes { (body: UnsafeRawBufferPointer) in
if let p = body.baseAddress, body.count > 0 {
var t: Int = 0
var bytesInGroup: Int = 0
for i in 0..<body.count {
if bytesInGroup == 3 {
data.append(base64Digits[(t >> 18) & 63])
data.append(base64Digits[(t >> 12) & 63])
data.append(base64Digits[(t >> 6) & 63])
data.append(base64Digits[t & 63])
t = 0
bytesInGroup = 0
}
t = (t << 8) + Int(p[i])
bytesInGroup += 1
}
switch bytesInGroup {
case 3:
data.append(base64Digits[(t >> 18) & 63])
data.append(base64Digits[(t >> 12) & 63])
data.append(base64Digits[(t >> 6) & 63])
data.append(base64Digits[t & 63])
case 2:
t <<= 8
data.append(base64Digits[(t >> 18) & 63])
data.append(base64Digits[(t >> 12) & 63])
data.append(base64Digits[(t >> 6) & 63])
data.append(asciiEquals)
case 1:
t <<= 16
data.append(base64Digits[(t >> 18) & 63])
data.append(base64Digits[(t >> 12) & 63])
data.append(asciiEquals)
data.append(asciiEquals)
default:
break
}
}
}
}
data.append(asciiDoubleQuote)
}
}
| apache-2.0 | 16c9d2c866950c8be3a28aca30c7b64b | 34.244444 | 104 | 0.58589 | 4.38795 | false | false | false | false |
avito-tech/Marshroute | Marshroute/Sources/Transitions/TransitionAnimations/ModalEndpointNavigation/ModalEndpointNavigationTransitionsAnimator.swift | 1 | 1886 | import UIKit
/// Аниматор, выполняющий модальный переход на конечный UINavigationController,
/// например MFMailComposeViewController, UIImagePickerController.
/// Также выполняет обратный переход
open class ModalEndpointNavigationTransitionsAnimator: TransitionsAnimator
{
open var shouldAnimate = true
open var targetModalTransitionStyle: UIModalTransitionStyle
open var targetModalPresentationStyle: UIModalPresentationStyle
// MARK: - Init
public init(
targetModalTransitionStyle: UIModalTransitionStyle?,
targetModalPresentationStyle: UIModalPresentationStyle?)
{
self.targetModalTransitionStyle = targetModalTransitionStyle ?? .coverVertical
self.targetModalPresentationStyle = targetModalPresentationStyle ?? .fullScreen
}
public init()
{
self.targetModalTransitionStyle = .coverVertical
self.targetModalPresentationStyle = .fullScreen
}
// MARK: - TransitionsAnimator
open func animatePerformingTransition(animationContext context: ModalEndpointNavigationPresentationAnimationContext)
{
context.targetNavigationController.modalTransitionStyle = targetModalTransitionStyle
context.targetNavigationController.modalPresentationStyle = targetModalPresentationStyle
context.sourceViewController.present(
context.targetNavigationController,
animated: shouldAnimate,
completion: nil
)
shouldAnimate = true
}
open func animateUndoingTransition(animationContext context: ModalEndpointNavigationDismissalAnimationContext)
{
context.targetViewController.dismiss(
animated: shouldAnimate,
completion: nil
)
shouldAnimate = true
}
}
| mit | e3b73b024499ab69626b282b2f01b369 | 35.08 | 120 | 0.734479 | 6.731343 | false | false | false | false |
ReiVerdugo/uikit-fundamentals | step5.5-bondVillains/BondVillains/ViewController.swift | 1 | 1955 | //
// ViewController.swift
// BondVillains
//
// Created by Jason on 11/19/14.
// Copyright (c) 2014 Udacity. All rights reserved.
//
import UIKit
// MARK: - ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: Properties
// Get ahold of some villains, for the table
// This is an array of Villain instances
let allVillains = Villain.allVillains
// MARK: Table View Data Source
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.allVillains.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("VillainCell")!
let villain = self.allVillains[indexPath.row]
// Set the name and image
cell.textLabel?.text = villain.name
cell.imageView?.image = UIImage(named: villain.imageName)
// If the cell has a detail label, we will put the evil scheme in.
if let detailTextLabel = cell.detailTextLabel {
detailTextLabel.text = "Scheme: \(villain.evilScheme)"
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let villain = self.allVillains[indexPath.row]
let nextController = self.storyboard?.instantiateViewControllerWithIdentifier("detailView") as! VillanDetailViewController
nextController.villain = villain
if let navigationController = self.navigationController {
navigationController.pushViewController(nextController, animated: true)
}
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
}
| mit | b53d7c85d78a9cf5a1b0f07d4cd94971 | 33.910714 | 130 | 0.687468 | 5.445682 | false | false | false | false |
alexvye/greywraith | GreyWraith/GreyWraith/MenuScene.swift | 1 | 3679 | //
// GameStartScene.swift
// GreyWraith
//
// Created by Alex Vye on 2016-04-25.
// Copyright © 2016 Alex Vye. All rights reserved.
//
import Foundation
import SpriteKit
import UIKit
class MenuScene: SKScene,UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
var playButton: SKNode! = nil
var quitButton: SKNode! = nil
//
// for stats (unused currently)
//
@IBOutlet
var tableView: UITableView!
var items: [String] = ["Viper", "X", "Games"]
//
// config
//
@IBOutlet
var playerNameTextField: UITextField!
override func didMove(to view: SKView) {
//
// state
//
DataManager.loadData()
//
// screen
//
configureScreen()
}
fileprivate func configureScreen() {
let bgImage = SKSpriteNode(imageNamed: "gwmain")
bgImage.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
bgImage.zPosition = 1
bgImage.size = CGSize(width: size.width, height: size.height)
self.addChild(bgImage)
backgroundColor = SKColor.white
addButtons();
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
// Loop over all the touches in this event
for touch: AnyObject in touches {
// Get the location of the touch in this scene
let location = touch.location(in: self)
// Check if the location of the touch is within the button's bounds
if self.playButton.contains(location) {
startGame()
} else if self.quitButton.contains(location) {
loadStats()
}
}
}
fileprivate func addButtons() {
self.playButton = SKSpriteNode(imageNamed: "playbutton.png")
self.playButton.name = "nextButton"
playButton.position = CGPoint(x:self.frame.maxX-100, y:self.frame.minY+300);
playButton.zPosition = 2;
self.addChild(playButton)
self.quitButton = SKSpriteNode(imageNamed: "quitbutton.png")
self.quitButton.name = "nextButton"
quitButton.position = CGPoint(x:self.frame.maxX-100, y:self.frame.minY+200);
quitButton.zPosition = 2;
self.addChild(quitButton)
}
fileprivate func startGame() {
//self.tableView.hidden = true
let gameScene = GameScene(size: view!.bounds.size)
let transition = SKTransition.fade(withDuration: 0.15)
view!.presentScene(gameScene, transition: transition)
}
fileprivate func loadStats() {
tableView = UITableView()
tableView?.delegate = self;
tableView?.dataSource = self;
let navRect = CGRect(x: self.frame.midX, y: 25, width: size.width/4, height: size.height*(0.85))
tableView.frame = navRect
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view!.addSubview(tableView)
}
//
// For stats
//
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
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
| apache-2.0 | 43d3dcb348f35df6e9a4437f8ddd5353 | 27.734375 | 108 | 0.600326 | 4.715385 | false | false | false | false |
ja-mes/experiments | iOS/Navigation Bar/Navigation Bar/ViewController.swift | 1 | 1106 | //
// ViewController.swift
// Navigation Bar
//
// Created by James Brown on 8/3/16.
// Copyright © 2016 James Brown. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var time = 0
var timer = NSTimer()
@IBOutlet var tickerLabel: UILabel!
@IBAction func resetButtonDidTouch(sender: AnyObject) {
time = 0
timer.invalidate()
tickerLabel.text = "0"
}
@IBAction func playButtonDidTouch(sender: AnyObject) {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.result), userInfo: nil, repeats: true)
}
@IBAction func stopButtonDidTouch(sender: AnyObject) {
timer.invalidate()
tickerLabel.text = String(time)
}
func result() {
time += 1
tickerLabel.text = String(time)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 283168a92af8819457c8a479ad4cb308 | 21.55102 | 145 | 0.632579 | 4.585062 | false | false | false | false |
miller-ms/MMSCropView | Pod/Classes/UIImage+Cropping.swift | 1 | 11655 | //
// UIImage+Cropping.swift
// Pods
//
// Created by William Miller on 3/10/16.
//
// Copyright (c) 2016 William Miller <[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 UIKit
public extension UIImage {
/**
Calculates a return size by aspect scaling the fromSize to fit within the destination size while giving priority to the width or height depending on which preference will maintain both the return width and height within the destination ie the return size will return a new size where both width and height are less than or equal to the destinations.
- parameter fromSize: Size to scale
- parameter toSize: Destination size
- returns: Scaled size
*/
class func scaleSize(_ fromSize: CGSize, toSize:CGSize) -> CGSize {
var scaleSize = CGSize.zero
if toSize.width < toSize.height {
if fromSize.width >= toSize.width { // give priority to width if it is larger than the destination width
scaleSize.width = round(toSize.width)
scaleSize.height = round(scaleSize.width * fromSize.height / fromSize.width)
} else if fromSize.height >= toSize.height { // then give priority to height if it is larger than destination height
scaleSize.height = round(toSize.height)
scaleSize.width = round(scaleSize.height * fromSize.width / fromSize.height)
} else { // otherwise the source size is smaller in all directions. Scale on width
scaleSize.width = round(toSize.width)
scaleSize.height = round(scaleSize.width * fromSize.height / fromSize.width)
if scaleSize.height > toSize.height { // but if the new height is larger than the destination then scale height
scaleSize.height = round(toSize.height)
scaleSize.width = round(scaleSize.height * fromSize.width / fromSize.height)
}
}
} else { // else height is the shorter dimension
if fromSize.height >= toSize.height { // then give priority to height if it is larger than destination height
scaleSize.height = round(toSize.height);
scaleSize.width = round(scaleSize.height * fromSize.width / fromSize.height);
} else if fromSize.width >= toSize.width { // give priority to width if it is larger than the destination width
scaleSize.width = round(toSize.width);
scaleSize.height = round(scaleSize.width * fromSize.height / fromSize.width);
} else { // otherwise the source size is smaller in all directions. Scale on width
scaleSize.width = round(toSize.width);
scaleSize.height = round(scaleSize.width * fromSize.height / fromSize.width);
if (scaleSize.height > toSize.height) { // but if the new height is larger than the destination then scale height
scaleSize.height = round(toSize.height);
scaleSize.width = round(scaleSize.height * fromSize.width / fromSize.height);
}
}
}
return scaleSize
}
/**
Returns an UIImage scaled to the input dimensions. Oftentimes the underlining CGImage does not match the orientation of the UIImage. This routing scales the UIImage dimensions not the CGImage's, and so it swaps the height and width of the scale size when it detects the UIImage is oriented differently.
- parameter scaleSize the dimensions to scale the bitmap to.
- returns: A reference to a uimage created from the scaled bitmap
*/
func scaleBitmapToSize(_ scaleSize:CGSize) -> UIImage {
/* round the size of the underlying CGImage and the input size.
*/
var scaleSize = CGSize(width: round(scaleSize.width), height: round(scaleSize.height))
/* if the underlying CGImage is oriented differently than the UIImage then swap the width and height of the scale size. This method assumes the size passed is a request on the UIImage's orientation.
*/
if imageOrientation == UIImageOrientation.left || imageOrientation == UIImageOrientation.right {
scaleSize = CGSize(width: round(scaleSize.height), height: round(scaleSize.width))
}
let context = CGContext(data: nil, width: Int(scaleSize.width), height: Int(scaleSize.height), bitsPerComponent: cgImage!.bitsPerComponent, bytesPerRow: 0, space: cgImage!.colorSpace!, bitmapInfo: cgImage!.bitmapInfo.rawValue)
var returnImg = UIImage(cgImage:cgImage!)
if context != nil {
context!.draw(cgImage!, in: CGRect(x: 0, y: 0, width: scaleSize.width, height: scaleSize.height))
/* realize the CGImage from the context.
*/
let imgRef = context!.makeImage()
/* realize the CGImage into a UIImage.
*/
returnImg = UIImage(cgImage: imgRef!)
} else {
/* context creation failed, so return a copy of the image, and log the error.
*/
NSLog ("NULL Bitmap Context in scaleBitmapToSize")
}
return returnImg
}
/**
Scales the cropRectangle from the source dimensions to the destination dimensions of the underlying image.
- parameter cropRect: Crop Rectangle
- parameter fromRect: Rectangle of the source image. Crop rectangle is with respect to this rectangle.
- parameter toRect: Rectangle of the desitination image.
- returns: A rectangle scaled from the source to the destination dimensions.
*/
func transposeCropRect(_ cropRect:CGRect, fromBound fromRect: CGRect, toBound toRect: CGRect) -> CGRect {
let scale = toRect.size.width / fromRect.size.width
return CGRect(x: round(cropRect.origin.x * scale), y: round(cropRect.origin.y*scale), width: round(cropRect.size.width*scale), height: round(cropRect.size.height*scale))
}
/**
transposes the origin of the crop rectangle to match the orientation of the underlying CGImage. For some orientations, the height and width are swaped.
- parameter cropRect: Rectangle of the region to crop
- parameter dimension: Size and Width of the source image
- parameter orientation: Orientation of the source image
- returns: A rectangle recalculated to orient with the source image.
*/
func transposeCropRect(_ cropRect:CGRect, inDimension dimension:CGSize, forOrientation orientation: UIImageOrientation) -> CGRect {
var transposedRect = cropRect
switch (orientation) {
case UIImageOrientation.left:
transposedRect.origin.x = dimension.height - (cropRect.size.height + cropRect.origin.y)
transposedRect.origin.y = cropRect.origin.x
transposedRect.size = CGSize(width: cropRect.size.height, height: cropRect.size.width)
case UIImageOrientation.right:
transposedRect.origin.x = cropRect.origin.y
transposedRect.origin.y = dimension.width - (cropRect.size.width + cropRect.origin.x)
transposedRect.size = CGSize(width: cropRect.size.height, height: cropRect.size.width)
case UIImageOrientation.down:
transposedRect.origin.x = dimension.width - (cropRect.size.width + cropRect.origin.x)
transposedRect.origin.y = dimension.height - (cropRect.size.height + cropRect.origin.y)
case UIImageOrientation.downMirrored:
transposedRect.origin.x = cropRect.origin.x
transposedRect.origin.y = dimension.height - (cropRect.size.height + cropRect.origin.y)
case UIImageOrientation.leftMirrored:
transposedRect.origin.x = cropRect.origin.y
transposedRect.origin.y = cropRect.origin.x
transposedRect.size = CGSize(width: cropRect.size.height, height: cropRect.size.width)
case UIImageOrientation.rightMirrored:
transposedRect.origin.x = dimension.height - (cropRect.size.height + cropRect.origin.y)
transposedRect.origin.y = dimension.width - (cropRect.size.width + cropRect.origin.x)
transposedRect.size = CGSize(width: cropRect.size.height, height: cropRect.size.width)
case UIImageOrientation.upMirrored:
transposedRect.origin.x = dimension.width - (cropRect.size.width + cropRect.origin.x)
transposedRect.origin.y = cropRect.origin.y
case UIImageOrientation.up:
break
}
return transposedRect
}
/**
Returns a new UIImage cut from the cropArea of the underlying image. It first scales the underlying image to the scale size before cutting the crop area from it. The returned CGImage is in the dimensions of the cropArea and it is oriented the same as the underlying CGImage as is the imageOrientation.
- parameter cropRect: The rectangular area over the image to crop.
- parameter frameSize: The view dimensions of the image
- returns: A UIImage cut from the image having the crop rect dimensions and origin.
*/
public func cropRectangle(_ cropRect: CGRect, inFrame frameSize: CGSize) -> UIImage {
let rndFrameSize = CGSize(width: round(frameSize.width), height: round(frameSize.height))
/* resize the image to match the zoomed content size
*/
let img = scaleBitmapToSize(rndFrameSize)
/* crop the resized image to the crop rectangel.
*/
let cropCGImage = img.cgImage!.cropping(to: transposeCropRect(cropRect, inDimension: rndFrameSize, forOrientation: imageOrientation))
let croppedImg = UIImage(cgImage: cropCGImage!, scale: 1.0, orientation: imageOrientation)
return croppedImg
}
}
| mit | 3c1cc2b738892279b1895836ef376ff9 | 42.815789 | 353 | 0.633634 | 5.224115 | false | false | false | false |
edx/edx-app-ios | Source/CourseCardView.swift | 1 | 9428 | //
// CourseCardView.swift
// edX
//
// Created by Jianfeng Qiu on 13/05/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
let StandardImageAspectRatio: CGFloat = 0.533
@IBDesignable
class CourseCardView: UIView, UIGestureRecognizerDelegate {
private let arrowHeight = 15.0
private let verticalMargin = 10
private let coverImageView = UIImageView()
private let container = UIView()
private let titleLabel = UILabel()
private let dateLabel = UILabel()
private let bottomLine = UIView()
private let overlayContainer = UIView()
var course: OEXCourse?
var tapAction: ((CourseCardView) -> ())?
private var titleTextStyle: OEXTextStyle {
return OEXTextStyle(weight: .bold, size: .base, color: OEXStyles.shared().neutralBlack())
}
private var dateTextStyle: OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .small, color: OEXStyles.shared().neutralXXDark())
}
private var coverImageAspectRatio: CGFloat {
// Let the placeholder image aspect ratio determine the course card image aspect ratio.
guard let placeholder = UIImage(named:"placeholderCourseCardImage") else {
return StandardImageAspectRatio
}
return placeholder.size.height / placeholder.size.width
}
private func setupView() {
configureViews()
accessibilityTraits = UIAccessibilityTraits.staticText
accessibilityHint = Strings.accessibilityShowsCourseContent
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
let bundle = Bundle(for: type(of: self))
coverImageView.image = UIImage(named:"placeholderCourseCardImage", in: bundle, compatibleWith: traitCollection)
titleLabel.attributedText = titleTextStyle.attributedString(withText: "Demo Course")
dateLabel.attributedText = dateTextStyle.attributedString(withText: "edx | DemoX")
}
func configureViews() {
backgroundColor = OEXStyles.shared().neutralXLight()
clipsToBounds = true
bottomLine.backgroundColor = OEXStyles.shared().neutralXLight()
container.backgroundColor = OEXStyles.shared().neutralWhite().withAlphaComponent(0.85)
coverImageView.backgroundColor = OEXStyles.shared().neutralWhiteT()
coverImageView.contentMode = UIView.ContentMode.scaleAspectFill
coverImageView.clipsToBounds = true
coverImageView.hidesLoadingSpinner = true
container.addSubview(titleLabel)
container.addSubview(dateLabel)
addSubview(coverImageView)
addSubview(container)
insertSubview(bottomLine, aboveSubview: coverImageView)
addSubview(overlayContainer)
coverImageView.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .horizontal)
coverImageView.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .vertical)
dateLabel.setContentHuggingPriority(UILayoutPriority.defaultLow, for: NSLayoutConstraint.Axis.horizontal)
dateLabel.setContentCompressionResistancePriority(UILayoutPriority.defaultHigh, for: NSLayoutConstraint.Axis.horizontal)
dateLabel.adjustsFontSizeToFitWidth = true
container.snp.makeConstraints { make in
make.leading.equalTo(self)
make.trailing.equalTo(self).priority(.required)
make.bottom.equalTo(self).offset(-OEXStyles.dividerSize())
}
coverImageView.snp.makeConstraints { make in
make.top.equalTo(self)
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.height.equalTo(coverImageView.snp.width).multipliedBy(coverImageAspectRatio).priority(.low)
make.bottom.equalTo(self)
}
dateLabel.snp.makeConstraints { make in
make.leading.equalTo(container).offset(StandardHorizontalMargin)
make.top.equalTo(titleLabel.snp.bottom).offset(StandardVerticalMargin/2)
make.bottom.equalTo(container).offset(-verticalMargin)
make.trailing.equalTo(titleLabel)
}
bottomLine.snp.makeConstraints { make in
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.bottom.equalTo(self)
make.top.equalTo(container.snp.bottom)
}
overlayContainer.snp.makeConstraints { make in
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.top.equalTo(self)
make.bottom.equalTo(container.snp.top)
}
let tapGesture = UITapGestureRecognizer {[weak self] _ in self?.cardTapped() }
tapGesture.delegate = self
addGestureRecognizer(tapGesture)
setAccessibilityIdentifiers()
applyBorderStyle(style: BorderStyle())
}
private func setAccessibilityIdentifiers() {
accessibilityIdentifier = "CourseCardView:view"
container.accessibilityIdentifier = "CourseCardView:container-view"
titleLabel.accessibilityIdentifier = "CourseCardView:title-label"
coverImageView.accessibilityIdentifier = "CourseCardView:cover-image"
dateLabel.accessibilityIdentifier = "CourseCardView:date-label"
bottomLine.accessibilityIdentifier = "CourseCardView:bottom-line"
overlayContainer.accessibilityIdentifier = "CourseCardView:overlay-container"
titleAccessoryView?.accessibilityIdentifier = "CourseCardView:title-accessory-view"
}
override func updateConstraints() {
if let accessory = titleAccessoryView {
accessory.snp.remakeConstraints { make in
make.trailing.equalTo(container).offset(-StandardHorizontalMargin)
make.centerY.equalTo(container)
}
}
titleLabel.snp.remakeConstraints { make in
make.leading.equalTo(container).offset(StandardHorizontalMargin)
if let accessory = titleAccessoryView {
make.trailing.lessThanOrEqualTo(accessory).offset(-StandardHorizontalMargin)
}
else {
make.trailing.equalTo(container).offset(-StandardHorizontalMargin)
}
make.top.equalTo(container).offset(verticalMargin)
}
super.updateConstraints()
}
var titleAccessoryView : UIView? = nil {
willSet {
titleAccessoryView?.removeFromSuperview()
}
didSet {
if let accessory = titleAccessoryView {
container.addSubview(accessory)
}
updateConstraints()
}
}
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return tapAction != nil
}
var titleText : String? {
get {
return titleLabel.text
}
set {
titleLabel.attributedText = titleTextStyle.attributedString(withText: newValue)
updateAcessibilityLabel()
updateConstraints()
}
}
var dateText : String? {
get {
return dateLabel.text
}
set {
dateLabel.attributedText = dateTextStyle.attributedString(withText: newValue)
updateAcessibilityLabel()
}
}
var coverImage : RemoteImage? {
get {
return coverImageView.remoteImage
}
set {
coverImageView.remoteImage = newValue
}
}
private func cardTapped() {
tapAction?(self)
}
func wrapTitleLabel() {
titleLabel.numberOfLines = 3
titleLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
titleLabel.minimumScaleFactor = 0.5
titleLabel.adjustsFontSizeToFitWidth = true
layoutIfNeeded()
}
@discardableResult func updateAcessibilityLabel()-> String {
var accessibilityString = ""
if let title = titleText {
accessibilityString = title
}
if let text = dateText {
let formateddateText = text.replacingOccurrences(of: "|", with: "")
accessibilityString = "\(accessibilityString),\(Strings.accessibilityBy) \(formateddateText)"
}
accessibilityLabel = accessibilityString
return accessibilityString
}
func addCenteredOverlay(view : UIView) {
addSubview(view)
view.snp.makeConstraints { make in
make.center.equalTo(overlayContainer)
}
}
}
extension CourseCardView {
static func cardHeight(leftMargin: CGFloat = 0, rightMargin: CGFloat = 0) -> CGFloat {
let screenWidth = UIScreen.main.bounds.size.width
var height: CGFloat = 0
let screenHeight = UIScreen.main.bounds.size.height
let halfScreenHeight = (screenHeight / 2.0) - (leftMargin + rightMargin)
let ratioedHeight = screenWidth * StandardImageAspectRatio
height = CGFloat(Int(halfScreenHeight > ratioedHeight ? ratioedHeight : halfScreenHeight))
return height
}
}
| apache-2.0 | 97fb9ba13c971e6c28126781cea7b039 | 35.542636 | 128 | 0.653797 | 5.710478 | false | false | false | false |
OscarSwanros/swift | test/SILGen/statements.swift | 3 | 20490 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -enable-sil-ownership -verify %s | %FileCheck %s
class MyClass {
func foo() { }
}
func markUsed<T>(_ t: T) {}
func marker_1() {}
func marker_2() {}
func marker_3() {}
class BaseClass {}
class DerivedClass : BaseClass {}
var global_cond: Bool = false
func bar(_ x: Int) {}
func foo(_ x: Int, _ y: Bool) {}
func abort() -> Never { abort() }
func assignment(_ x: Int, y: Int) {
var x = x
var y = y
x = 42
y = 57
_ = x
_ = y
(x, y) = (1,2)
}
// CHECK-LABEL: sil hidden @{{.*}}assignment
// CHECK: integer_literal $Builtin.Int2048, 42
// CHECK: assign
// CHECK: integer_literal $Builtin.Int2048, 57
// CHECK: assign
func if_test(_ x: Int, y: Bool) {
if (y) {
bar(x);
}
bar(x);
}
// CHECK-LABEL: sil hidden @_T010statements7if_test{{[_0-9a-zA-Z]*}}F
func if_else(_ x: Int, y: Bool) {
if (y) {
bar(x);
} else {
foo(x, y);
}
bar(x);
}
// CHECK-LABEL: sil hidden @_T010statements7if_else{{[_0-9a-zA-Z]*}}F
func nested_if(_ x: Int, y: Bool, z: Bool) {
if (y) {
if (z) {
bar(x);
}
} else {
if (z) {
foo(x, y);
}
}
bar(x);
}
// CHECK-LABEL: sil hidden @_T010statements9nested_if{{[_0-9a-zA-Z]*}}F
func nested_if_merge_noret(_ x: Int, y: Bool, z: Bool) {
if (y) {
if (z) {
bar(x);
}
} else {
if (z) {
foo(x, y);
}
}
}
// CHECK-LABEL: sil hidden @_T010statements21nested_if_merge_noret{{[_0-9a-zA-Z]*}}F
func nested_if_merge_ret(_ x: Int, y: Bool, z: Bool) -> Int {
if (y) {
if (z) {
bar(x);
}
return 1
} else {
if (z) {
foo(x, y);
}
}
return 2
}
// CHECK-LABEL: sil hidden @_T010statements19nested_if_merge_ret{{[_0-9a-zA-Z]*}}F
func else_break(_ x: Int, y: Bool, z: Bool) {
while z {
if y {
} else {
break
}
}
}
// CHECK-LABEL: sil hidden @_T010statements10else_break{{[_0-9a-zA-Z]*}}F
func loop_with_break(_ x: Int, _ y: Bool, _ z: Bool) -> Int {
while (x > 2) {
if (y) {
bar(x);
break
}
}
}
// CHECK-LABEL: sil hidden @_T010statements15loop_with_break{{[_0-9a-zA-Z]*}}F
func loop_with_continue(_ x: Int, y: Bool, z: Bool) -> Int {
while (x > 2) {
if (y) {
bar(x);
continue
}
_ = loop_with_break(x, y, z);
}
bar(x);
}
// CHECK-LABEL: sil hidden @_T010statements18loop_with_continue{{[_0-9a-zA-Z]*}}F
func do_loop_with_continue(_ x: Int, y: Bool, z: Bool) -> Int {
repeat {
if (x < 42) {
bar(x);
continue
}
_ = loop_with_break(x, y, z);
}
while (x > 2);
bar(x);
}
// CHECK-LABEL: sil hidden @_T010statements21do_loop_with_continue{{[_0-9a-zA-Z]*}}F
// CHECK-LABEL: sil hidden @{{.*}}for_loops1
func for_loops1(_ x: Int, c: Bool) {
for i in 1..<100 {
markUsed(i)
}
}
// CHECK-LABEL: sil hidden @{{.*}}for_loops2
func for_loops2() {
// rdar://problem/19316670
// CHECK: [[NEXT:%[0-9]+]] = function_ref @_T0s16IndexingIteratorV4next{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: alloc_stack $Optional<MyClass>
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown]
// CHECK-NEXT: apply [[NEXT]]<[MyClass]>
// CHECK: class_method [[OBJ:%[0-9]+]] : $MyClass, #MyClass.foo!1
let objects = [MyClass(), MyClass() ]
for obj in objects {
obj.foo()
}
return
}
func void_return() {
let b:Bool
if b {
return
}
}
// CHECK-LABEL: sil hidden @_T010statements11void_return{{[_0-9a-zA-Z]*}}F
// CHECK: cond_br {{%[0-9]+}}, [[BB1:bb[0-9]+]], [[BB2:bb[0-9]+]]
// CHECK: [[BB1]]:
// CHECK: br [[EPILOG:bb[0-9]+]]
// CHECK: [[BB2]]:
// CHECK: br [[EPILOG]]
// CHECK: [[EPILOG]]:
// CHECK: [[R:%[0-9]+]] = tuple ()
// CHECK: return [[R]]
func foo() {}
// <rdar://problem/13549626>
// CHECK-LABEL: sil hidden @_T010statements14return_from_if{{[_0-9a-zA-Z]*}}F
func return_from_if(_ a: Bool) -> Int {
// CHECK: bb0(%0 : @trivial $Bool):
// CHECK: cond_br {{.*}}, [[THEN:bb[0-9]+]], [[ELSE:bb[0-9]+]]
if a {
// CHECK: [[THEN]]:
// CHECK: br [[EPILOG:bb[0-9]+]]({{%.*}})
return 1
} else {
// CHECK: [[ELSE]]:
// CHECK: br [[EPILOG]]({{%.*}})
return 0
}
// CHECK-NOT: function_ref @foo
// CHECK: [[EPILOG]]([[RET:%.*]] : @trivial $Int):
// CHECK: return [[RET]]
foo() // expected-warning {{will never be executed}}
}
class C {}
func use(_ c: C) {}
func for_each_loop(_ x: [C]) {
for i in x {
use(i)
}
_ = 0
}
// CHECK-LABEL: sil hidden @{{.*}}test_break
func test_break(_ i : Int) {
switch i {
case (let x) where x != 17:
if x == 42 { break }
markUsed(x)
default:
break
}
}
// <rdar://problem/19150249> Allow labeled "break" from an "if" statement
// CHECK-LABEL: sil hidden @_T010statements13test_if_breakyAA1CCSgF : $@convention(thin) (@owned Optional<C>) -> () {
func test_if_break(_ c : C?) {
// CHECK: bb0([[ARG:%.*]] : @owned $Optional<C>):
label1:
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $Optional<C>, case #Optional.some!enumelt.1: [[TRUE:bb[0-9]+]], case #Optional.none!enumelt: [[FALSE:bb[0-9]+]]
if let x = c {
// CHECK: [[TRUE]]({{.*}} : @owned $C):
// CHECK: apply
foo()
// CHECK: destroy_value
// CHECK: br [[FALSE:bb[0-9]+]]
break label1
use(x) // expected-warning {{will never be executed}}
}
// CHECK: [[FALSE]]:
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T010statements18test_if_else_breakyAA1CCSgF : $@convention(thin) (@owned Optional<C>) -> () {
func test_if_else_break(_ c : C?) {
// CHECK: bb0([[ARG:%.*]] : @owned $Optional<C>):
label2:
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $Optional<C>, case #Optional.some!enumelt.1: [[TRUE:bb[0-9]+]], case #Optional.none!enumelt: [[FALSE:bb[0-9]+]]
// CHECK: [[FALSE]]:
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: br [[AFTER_FALSE:bb[0-9]+]]
if let x = c {
// CHECK: [[TRUE]]({{.*}} : @owned $C):
use(x)
// CHECK: br [[CONT:bb[0-9]+]]
// CHECK: [[CONT]]:
// CHECK: br [[EPILOG:bb[0-9]+]]
} else {
// CHECK: [[AFTER_FALSE]]:
// CHECK: apply
// CHECK: br [[EPILOG]]
foo()
break label2
foo() // expected-warning {{will never be executed}}
}
// CHECK: [[EPILOG]]:
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T010statements23test_if_else_then_breakySb_AA1CCSgtF
func test_if_else_then_break(_ a : Bool, _ c : C?) {
label3:
// CHECK: bb0({{.*}}, [[ARG2:%.*]] : @owned $Optional<C>):
// CHECK: [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG2]]
// CHECK: [[ARG2_COPY:%.*]] = copy_value [[BORROWED_ARG2]]
// CHECK: switch_enum [[ARG2_COPY]] : $Optional<C>, case #Optional.some!enumelt.1: [[TRUE:bb[0-9]+]], case #Optional.none!enumelt: [[FALSE:bb[0-9]+]]
// CHECK: [[FALSE]]:
// CHECK: end_borrow [[BORROWED_ARG2]] from [[ARG2]]
// CHECK: br [[COND2:bb[0-9]+]]
if let x = c {
// CHECK: [[TRUE]]({{.*}} : @owned $C):
use(x)
// CHECK: br [[TRUE_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[TRUE_TRAMPOLINE]]:
// CHECK: br [[EPILOG_BB:bb[0-9]+]]
} else if a {
// CHECK: [[COND2]]:
// CHECK: cond_br {{.*}}, [[TRUE2:bb[0-9]+]], [[FALSE2:bb[0-9]+]]
//
// CHECK: [[TRUE2]]:
// CHECK: apply
// CHECK: br [[EPILOG_BB]]
foo()
break label3
foo() // expected-warning {{will never be executed}}
}
// CHECK: [[FALSE2]]:
// CHECK: br [[EPILOG_BB]]
// CHECK: [[EPILOG_BB]]:
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T010statements13test_if_breakySbF
func test_if_break(_ a : Bool) {
// CHECK: br [[LOOP:bb[0-9]+]]
// CHECK: [[LOOP]]:
// CHECK: function_ref @_T0Sb21_getBuiltinLogicValue{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: apply
// CHECK-NEXT: cond_br {{.*}}, [[LOOPTRUE:bb[0-9]+]], [[OUT:bb[0-9]+]]
while a {
if a {
foo()
break // breaks out of while, not if.
}
foo()
}
// CHECK: [[LOOPTRUE]]:
// CHECK: function_ref @_T0Sb21_getBuiltinLogicValue{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: apply
// CHECK-NEXT: cond_br {{.*}}, [[IFTRUE:bb[0-9]+]], [[IFFALSE:bb[0-9]+]]
// [[IFTRUE]]:
// CHECK: function_ref statements.foo
// CHECK: br [[OUT]]
// CHECK: [[IFFALSE]]:
// CHECK: function_ref statements.foo
// CHECK: br [[LOOP]]
// CHECK: [[OUT]]:
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T010statements7test_doyyF
func test_do() {
// CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
// CHECK: integer_literal $Builtin.Int2048, 0
// CHECK: apply [[BAR]](
bar(0)
// CHECK-NOT: br bb
do {
// CHECK: [[CTOR:%.*]] = function_ref @_T010statements7MyClassC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[OBJ:%.*]] = apply [[CTOR]](
let obj = MyClass()
_ = obj
// CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
// CHECK: integer_literal $Builtin.Int2048, 1
// CHECK: apply [[BAR]](
bar(1)
// CHECK-NOT: br bb
// CHECK: destroy_value [[OBJ]]
// CHECK-NOT: br bb
}
// CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
// CHECK: integer_literal $Builtin.Int2048, 2
// CHECK: apply [[BAR]](
bar(2)
}
// CHECK-LABEL: sil hidden @_T010statements15test_do_labeledyyF
func test_do_labeled() {
// CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
// CHECK: integer_literal $Builtin.Int2048, 0
// CHECK: apply [[BAR]](
bar(0)
// CHECK: br bb1
// CHECK: bb1:
lbl: do {
// CHECK: [[CTOR:%.*]] = function_ref @_T010statements7MyClassC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[OBJ:%.*]] = apply [[CTOR]](
let obj = MyClass()
_ = obj
// CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
// CHECK: integer_literal $Builtin.Int2048, 1
// CHECK: apply [[BAR]](
bar(1)
// CHECK: [[GLOBAL:%.*]] = function_ref @_T010statements11global_condSbvau
// CHECK: cond_br {{%.*}}, bb2, bb3
if (global_cond) {
// CHECK: bb2:
// CHECK: destroy_value [[OBJ]]
// CHECK: br bb1
continue lbl
}
// CHECK: bb3:
// CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
// CHECK: integer_literal $Builtin.Int2048, 2
// CHECK: apply [[BAR]](
bar(2)
// CHECK: [[GLOBAL:%.*]] = function_ref @_T010statements11global_condSbvau
// CHECK: cond_br {{%.*}}, bb4, bb5
if (global_cond) {
// CHECK: bb4:
// CHECK: destroy_value [[OBJ]]
// CHECK: br bb6
break lbl
}
// CHECK: bb5:
// CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
// CHECK: integer_literal $Builtin.Int2048, 3
// CHECK: apply [[BAR]](
bar(3)
// CHECK: destroy_value [[OBJ]]
// CHECK: br bb6
}
// CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
// CHECK: integer_literal $Builtin.Int2048, 4
// CHECK: apply [[BAR]](
bar(4)
}
func callee1() {}
func callee2() {}
func callee3() {}
// CHECK-LABEL: sil hidden @_T010statements11defer_test1yyF
func defer_test1() {
defer { callee1() }
defer { callee2() }
callee3()
// CHECK: [[C3:%.*]] = function_ref @_T010statements7callee3yyF
// CHECK: apply [[C3]]
// CHECK: [[C2:%.*]] = function_ref @_T010statements11defer_test1yyF6
// CHECK: apply [[C2]]
// CHECK: [[C1:%.*]] = function_ref @_T010statements11defer_test1yyF6
// CHECK: apply [[C1]]
}
// CHECK: sil private @_T010statements11defer_test1yyF6
// CHECK: function_ref @{{.*}}callee1yyF
// CHECK: sil private @_T010statements11defer_test1yyF6
// CHECK: function_ref @{{.*}}callee2yyF
// CHECK-LABEL: sil hidden @_T010statements11defer_test2ySbF
func defer_test2(_ cond : Bool) {
// CHECK: [[C3:%.*]] = function_ref @{{.*}}callee3yyF
// CHECK: apply [[C3]]
// CHECK: br [[LOOP:bb[0-9]+]]
callee3()
// CHECK: [[LOOP]]:
// test the condition.
// CHECK: [[CONDTRUE:%.*]] = apply {{.*}}(%0)
// CHECK: cond_br [[CONDTRUE]], [[BODY:bb[0-9]+]], [[EXIT:bb[0-9]+]]
while cond {
// CHECK: [[BODY]]:
// CHECK: [[C2:%.*]] = function_ref @{{.*}}callee2yyF
// CHECK: apply [[C2]]
// CHECK: [[C1:%.*]] = function_ref @_T010statements11defer_test2ySbF6
// CHECK: apply [[C1]]
// CHECK: br [[EXIT]]
defer { callee1() }
callee2()
break
}
// CHECK: [[EXIT]]:
// CHECK: [[C3:%.*]] = function_ref @{{.*}}callee3yyF
// CHECK: apply [[C3]]
callee3()
}
func generic_callee_1<T>(_: T) {}
func generic_callee_2<T>(_: T) {}
func generic_callee_3<T>(_: T) {}
// CHECK-LABEL: sil hidden @_T010statements16defer_in_generic{{[_0-9a-zA-Z]*}}F
func defer_in_generic<T>(_ x: T) {
// CHECK: [[C3:%.*]] = function_ref @_T010statements16generic_callee_3{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[C3]]<T>
// CHECK: [[C2:%.*]] = function_ref @_T010statements16defer_in_genericyxlF6
// CHECK: apply [[C2]]<T>
// CHECK: [[C1:%.*]] = function_ref @_T010statements16defer_in_genericyxlF6
// CHECK: apply [[C1]]<T>
defer { generic_callee_1(x) }
defer { generic_callee_2(x) }
generic_callee_3(x)
}
// CHECK-LABEL: sil hidden @_T010statements017defer_in_closure_C8_genericyxlF : $@convention(thin) <T> (@in T) -> ()
func defer_in_closure_in_generic<T>(_ x: T) {
// CHECK-LABEL: sil private @_T010statements017defer_in_closure_C8_genericyxlFyycfU_ : $@convention(thin) <T> () -> ()
_ = {
// CHECK-LABEL: sil private @_T010statements017defer_in_closure_C8_genericyxlFyycfU_6$deferL_yylF : $@convention(thin) <T> () -> ()
defer { generic_callee_1(T.self) }
}
}
// CHECK-LABEL: sil hidden @_T010statements13defer_mutableySiF
func defer_mutable(_ x: Int) {
var x = x
// CHECK: [[BOX:%.*]] = alloc_box ${ var Int }
// CHECK-NEXT: project_box [[BOX]]
// CHECK-NOT: [[BOX]]
// CHECK: function_ref @_T010statements13defer_mutableySiF6$deferL_yyF : $@convention(thin) (@inout_aliasable Int) -> ()
// CHECK-NOT: [[BOX]]
// CHECK: destroy_value [[BOX]]
defer { _ = x }
}
protocol StaticFooProtocol { static func foo() }
func testDeferOpenExistential(_ b: Bool, type: StaticFooProtocol.Type) {
defer { type.foo() }
if b { return }
return
}
// CHECK-LABEL: sil hidden @_T010statements22testRequireExprPatternySiF
func testRequireExprPattern(_ a : Int) {
marker_1()
// CHECK: [[M1:%[0-9]+]] = function_ref @_T010statements8marker_1yyF : $@convention(thin) () -> ()
// CHECK-NEXT: apply [[M1]]() : $@convention(thin) () -> ()
// CHECK: function_ref Swift.~= infix<A where A: Swift.Equatable>(A, A) -> Swift.Bool
// CHECK: cond_br {{.*}}, bb1, bb2
guard case 4 = a else { marker_2(); return }
// Fall through case comes first.
// CHECK: bb1:
// CHECK: [[M3:%[0-9]+]] = function_ref @_T010statements8marker_3yyF : $@convention(thin) () -> ()
// CHECK-NEXT: apply [[M3]]() : $@convention(thin) () -> ()
// CHECK-NEXT: br bb3
marker_3()
// CHECK: bb2:
// CHECK: [[M2:%[0-9]+]] = function_ref @_T010statements8marker_2yyF : $@convention(thin) () -> ()
// CHECK-NEXT: apply [[M2]]() : $@convention(thin) () -> ()
// CHECK-NEXT: br bb3
// CHECK: bb3:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_T010statements20testRequireOptional1S2iSgF
// CHECK: bb0([[ARG:%.*]] : @trivial $Optional<Int>):
// CHECK-NEXT: debug_value [[ARG]] : $Optional<Int>, let, name "a"
// CHECK-NEXT: switch_enum [[ARG]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME:bb[0-9]+]], case #Optional.none!enumelt: [[NONE:bb[0-9]+]]
func testRequireOptional1(_ a : Int?) -> Int {
// CHECK: [[NONE]]:
// CHECK: br [[ABORT:bb[0-9]+]]
// CHECK: [[SOME]]([[PAYLOAD:%.*]] : @trivial $Int):
// CHECK-NEXT: debug_value [[PAYLOAD]] : $Int, let, name "t"
// CHECK-NEXT: br [[EPILOG:bb[0-9]+]]
//
// CHECK: [[EPILOG]]:
// CHECK-NEXT: return [[PAYLOAD]] : $Int
guard let t = a else { abort() }
// CHECK: [[ABORT]]:
// CHECK-NEXT: // function_ref statements.abort() -> Swift.Never
// CHECK-NEXT: [[FUNC_REF:%.*]] = function_ref @_T010statements5aborts5NeverOyF
// CHECK-NEXT: apply [[FUNC_REF]]() : $@convention(thin) () -> Never
// CHECK-NEXT: unreachable
return t
}
// CHECK-LABEL: sil hidden @_T010statements20testRequireOptional2S2SSgF
// CHECK: bb0([[ARG:%.*]] : @owned $Optional<String>):
// CHECK-NEXT: debug_value [[ARG]] : $Optional<String>, let, name "a"
// CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] : $Optional<String>
// CHECK-NEXT: switch_enum [[ARG_COPY]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
func testRequireOptional2(_ a : String?) -> String {
guard let t = a else { abort() }
// CHECK: [[NONE_BB]]:
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: br [[ABORT_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]([[STR:%.*]] : @owned $String):
// CHECK-NEXT: debug_value [[STR]] : $String, let, name "t"
// CHECK-NEXT: br [[CONT_BB:bb[0-9]+]]
// CHECK: [[CONT_BB]]:
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: [[BORROWED_STR:%.*]] = begin_borrow [[STR]]
// CHECK-NEXT: [[RETURN:%.*]] = copy_value [[BORROWED_STR]]
// CHECK-NEXT: end_borrow [[BORROWED_STR]] from [[STR]]
// CHECK-NEXT: destroy_value [[STR]] : $String
// CHECK-NEXT: destroy_value [[ARG]]
// CHECK-NEXT: return [[RETURN]] : $String
// CHECK: [[ABORT_BB]]:
// CHECK-NEXT: // function_ref statements.abort() -> Swift.Never
// CHECK-NEXT: [[ABORT_FUNC:%.*]] = function_ref @_T010statements5aborts5NeverOyF
// CHECK-NEXT: [[NEVER:%.*]] = apply [[ABORT_FUNC]]()
// CHECK-NEXT: unreachable
return t
}
// CHECK-LABEL: sil hidden @_T010statements19testCleanupEmission{{[_0-9a-zA-Z]*}}F
// <rdar://problem/20563234> let-else problem: cleanups for bound patterns shouldn't be run in the else block
protocol MyProtocol {}
func testCleanupEmission<T>(_ x: T) {
// SILGen shouldn't crash/verify abort on this example.
guard let x2 = x as? MyProtocol else { return }
_ = x2
}
// CHECK-LABEL: sil hidden @_T010statements15test_is_patternyAA9BaseClassCF
func test_is_pattern(_ y : BaseClass) {
// checked_cast_br %0 : $BaseClass to $DerivedClass
guard case is DerivedClass = y else { marker_1(); return }
marker_2()
}
// CHECK-LABEL: sil hidden @_T010statements15test_as_patternAA12DerivedClassCAA04BaseF0CF
func test_as_pattern(_ y : BaseClass) -> DerivedClass {
// CHECK: bb0([[ARG:%.*]] : @owned $BaseClass):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: checked_cast_br [[ARG_COPY]] : $BaseClass to $DerivedClass
guard case let result as DerivedClass = y else { }
// CHECK: bb{{.*}}({{.*}} : @owned $DerivedClass):
// CHECK: bb{{.*}}([[PTR:%[0-9]+]] : @owned $DerivedClass):
// CHECK-NEXT: debug_value [[PTR]] : $DerivedClass, let, name "result"
// CHECK-NEXT: br [[CONT_BB:bb[0-9]+]]
// CHECK: [[CONT_BB]]:
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: [[BORROWED_PTR:%.*]] = begin_borrow [[PTR]]
// CHECK-NEXT: [[RESULT:%.*]] = copy_value [[BORROWED_PTR]]
// CHECK-NEXT: end_borrow [[BORROWED_PTR]] from [[PTR]]
// CHECK-NEXT: destroy_value [[PTR]] : $DerivedClass
// CHECK-NEXT: destroy_value [[ARG]] : $BaseClass
// CHECK-NEXT: return [[RESULT]] : $DerivedClass
return result
}
// CHECK-LABEL: sil hidden @_T010statements22let_else_tuple_bindingS2i_SitSgF
func let_else_tuple_binding(_ a : (Int, Int)?) -> Int {
// CHECK: bb0([[ARG:%.*]] : @trivial $Optional<(Int, Int)>):
// CHECK-NEXT: debug_value [[ARG]] : $Optional<(Int, Int)>, let, name "a"
// CHECK-NEXT: switch_enum [[ARG]] : $Optional<(Int, Int)>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
guard let (x, y) = a else { }
_ = y
return x
// CHECK: [[SOME_BB]]([[PAYLOAD:%.*]] : @trivial $(Int, Int)):
// CHECK-NEXT: [[PAYLOAD_1:%.*]] = tuple_extract [[PAYLOAD]] : $(Int, Int), 0
// CHECK-NEXT: debug_value [[PAYLOAD_1]] : $Int, let, name "x"
// CHECK-NEXT: [[PAYLOAD_2:%.*]] = tuple_extract [[PAYLOAD]] : $(Int, Int), 1
// CHECK-NEXT: debug_value [[PAYLOAD_2]] : $Int, let, name "y"
// CHECK-NEXT: br [[CONT_BB:bb[0-9]+]]
// CHECK: [[CONT_BB]]:
// CHECK-NEXT: return [[PAYLOAD_1]] : $Int
}
| apache-2.0 | 05c5be25bc88dd6de57fad116b65ac3d | 27.940678 | 166 | 0.57184 | 2.995176 | false | true | false | false |
ldjhust/BeautifulPhotos | BeautifulPhotos/BeautifulPhotos/ShowPhotos/Controller/MyCollectionViewController.swift | 1 | 7790 | //
// MyCollectionViewController.swift
// BeautifulPhotos
//
// Created by ldjhust on 15/9/8.
// Copyright (c) 2015年 example. All rights reserved.
//
import UIKit
import MJRefresh
import SDWebImage
let reuseIdentifier = "Cell"
let reuseHeaderIdentifier = "header"
class MyCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
// MARK: - properties
var isRefreshing = false
var myTitleView: MyTitleView!
var detailImageView: ShowBigImageView!
var currentPage: Int = 1
var kingImageString: String = "壁纸" {
didSet {
// 更换显示的壁纸种类
self.currentPage = 1
self.imageDatas = nil
self.collectionView?.header.beginRefreshing()
}
}
var imageDatas: [MyImageDataModel]? {
didSet {
// 获取数据后,刷新collectionView数据
self.collectionView?.reloadData()
self.collectionView?.header.endRefreshing()
self.collectionView?.footer.endRefreshing()
self.isRefreshing = false
}
}
// MARK: - Init Method
override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(collectionViewLayout: layout)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Register header classes
self.collectionView?.registerClass(MyCollectionHeaderReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: reuseHeaderIdentifier)
self.collectionView?.backgroundColor = UIColor.whiteColor()
self.collectionView?.contentInset.top = 44 // 避免header遮住标题栏
myTitleView = MyTitleView()
// Add subviews
self.view.addSubview(myTitleView)
// 设置下拉刷新
collectionView?.header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "pullDownToRefresh")
// 设置上拉加载更多
collectionView?.footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "pullUpToRefresh")
// 程序一开始需先自动进入刷新从网络获取数据
collectionView?.header.beginRefreshing()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
// MARK: - Event Response
func pullDownToRefresh() {
if !isRefreshing {
isRefreshing = true // 设置collectionView正在刷新
// request data from 500px.com,网络不行,有真机时在测试一下
// MyNetworkOperation.requestDataWithURL(self, url: "https://api.500px.com/v1/photos", parameters: ["feature" : "popular", "image_size": "600", "consumer_key" : "dOx1REBdbyI3WSoXTlNqnnE9jDPV1hxExIjVVpQl"])
// 从百度图片获取图片, 刷新永远从第一页开始取
MyNetworkOperation.requestDataWithURL(self, url: self.makeURLString(self.kingImageString, pageNumber: 1), parameters: nil, action: "pullDwon")
}
}
func pullUpToRefresh() {
if !isRefreshing {
isRefreshing = true // 设置collectionView正在刷新
self.currentPage++ // 获取下一页
self.collectionView?.footer.beginRefreshing()
MyNetworkOperation.requestDataWithURL(self, url: self.makeURLString(self.kingImageString, pageNumber: self.currentPage), parameters: nil, action: "pullUp")
}
}
// MARK: - private methods
func makeURLString(kindImageString: String, pageNumber: Int) -> String {
return "http://image.baidu.com/data/imgs?col=\(kindImageString)&tag=全部&pn=\(pageNumber)&p=channel&rn=30&from=1".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
}
// MARK: - UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if self.imageDatas == nil {
return 0
} else {
return self.imageDatas!.count - 1 // 第0张图片我们显示在collectionView的header上面
}
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
// Configure the cell
cell.backgroundColor = UIColor.darkGrayColor()
cell.backgroundImageView!.sd_setImageWithURL(NSURL(string: self.imageDatas![indexPath.row+1].imageURLString)!) //+1是因为第0张图片我们放在了header上面,加个header是因为我觉得会更美观
return cell
}
// MARK: - UICollectionView Delegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell
let locationTap = CGPointMake(cell.center.x, cell.center.y - collectionView.contentOffset.y) // 随着滚动cell的垂直坐标一直在增加,所以要获取准确相对于屏幕上方的y值,需减去滚动的距离
self.detailImageView = nil // 释放之前的值
self.detailImageView = ShowBigImageView()
self.detailImageView.showImageView(cell.backgroundImageView!, startCenter: locationTap)
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(1, 0, 1, 0)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 1.0
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 1.0
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let width = (view.bounds.width - 2) / 3
return CGSizeMake(width, width)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
let width = view.bounds.width
return CGSizeMake(width, width)
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: reuseHeaderIdentifier, forIndexPath: indexPath) as! MyCollectionHeaderReusableView
// config header view
if self.imageDatas != nil {
headerView.backgroundImageView.sd_setImageWithURL(NSURL(string: self.imageDatas![0].imageURLString)!) // 显示第0张图片在header上面
}
return headerView
}
}
| mit | 8cd9a42032b5951a9aab09a5c3928eb9 | 38.827027 | 228 | 0.686211 | 5.378102 | false | false | false | false |
lovehhf/edx-app-ios | Source/CourseOutlineViewController.swift | 1 | 14119 | //
// CourseOutlineViewController.swift
// edX
//
// Created by Akiva Leffert on 4/30/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import UIKit
///Controls the space between the ModeChange icon and the View on Web Icon for CourseOutlineViewController and CourseContentPageViewController. Changing this constant changes the spacing in both places.
public let barButtonFixedSpaceWidth : CGFloat = 20
public class CourseOutlineViewController :
UIViewController,
CourseBlockViewController,
CourseOutlineTableControllerDelegate,
CourseOutlineModeControllerDelegate,
CourseContentPageViewControllerDelegate,
DownloadProgressViewControllerDelegate,
CourseLastAccessedControllerDelegate,
OpenOnWebControllerDelegate,
PullRefreshControllerDelegate
{
public struct Environment {
private let analytics : OEXAnalytics?
private let dataManager : DataManager
private let networkManager : NetworkManager
private let reachability : Reachability
private weak var router : OEXRouter?
private let styles : OEXStyles
public init(analytics : OEXAnalytics?, dataManager : DataManager, networkManager : NetworkManager, reachability : Reachability, router : OEXRouter, styles : OEXStyles) {
self.analytics = analytics
self.dataManager = dataManager
self.networkManager = networkManager
self.reachability = reachability
self.router = router
self.styles = styles
}
}
private var rootID : CourseBlockID?
private var environment : Environment
private let courseQuerier : CourseOutlineQuerier
private let tableController : CourseOutlineTableController
private let blockIDStream = BackedStream<CourseBlockID?>()
private let headersLoader = BackedStream<CourseOutlineQuerier.BlockGroup>()
private let rowsLoader = BackedStream<[CourseOutlineQuerier.BlockGroup]>()
private let loadController : LoadStateViewController
private let insetsController : ContentInsetsController
private let modeController : CourseOutlineModeController
private var lastAccessedController : CourseLastAccessedController
/// Strictly a test variable used as a trigger flag. Not to be used out of the test scope
private var t_hasTriggeredSetLastAccessed = false
public var blockID : CourseBlockID? {
return blockIDStream.value ?? nil
}
public var courseID : String {
return courseQuerier.courseID
}
private lazy var webController : OpenOnWebController = OpenOnWebController(delegate: self)
public init(environment: Environment, courseID : String, rootID : CourseBlockID?) {
self.rootID = rootID
self.environment = environment
courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID)
loadController = LoadStateViewController(styles: environment.styles)
insetsController = ContentInsetsController()
modeController = environment.dataManager.courseDataManager.freshOutlineModeController()
tableController = CourseOutlineTableController(courseID: courseID)
lastAccessedController = CourseLastAccessedController(blockID: rootID , dataManager: environment.dataManager, networkManager: environment.networkManager, courseQuerier: courseQuerier)
super.init(nibName: nil, bundle: nil)
lastAccessedController.delegate = self
modeController.delegate = self
addChildViewController(tableController)
tableController.didMoveToParentViewController(self)
tableController.delegate = self
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
fixedSpace.width = barButtonFixedSpaceWidth
navigationItem.rightBarButtonItems = [webController.barButtonItem,fixedSpace,modeController.barItem]
navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
self.blockIDStream.backWithStream(Stream(value: rootID))
}
public required init(coder aDecoder: NSCoder) {
// required by the compiler because UIViewController implements NSCoding,
// but we don't actually want to serialize these things
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = self.environment.styles.standardBackgroundColor()
view.addSubview(tableController.view)
loadController.setupInController(self, contentView:tableController.view)
tableController.refreshController.setupInScrollView(tableController.tableView)
tableController.refreshController.delegate = self
insetsController.setupInController(self, scrollView : self.tableController.tableView)
insetsController.supportOfflineMode(styles: environment.styles)
insetsController.supportDownloadsProgress(interface : environment.dataManager.interface, styles : environment.styles, delegate : self)
insetsController.addSource(tableController.refreshController)
self.view.setNeedsUpdateConstraints()
addListeners()
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
lastAccessedController.loadLastAccessed(forMode: modeController.currentMode)
lastAccessedController.saveLastAccessed()
}
override public func updateViewConstraints() {
loadController.insets = UIEdgeInsets(top: self.topLayoutGuide.length, left: 0, bottom: self.bottomLayoutGuide.length, right : 0)
tableController.view.snp_updateConstraints {make in
make.edges.equalTo(self.view)
}
super.updateViewConstraints()
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.insetsController.updateInsets()
}
private func setupNavigationItem(block : CourseBlock) {
self.navigationItem.title = block.name
self.webController.info = OpenOnWebController.Info(courseID : courseID, blockID : block.blockID, supported : block.displayType.isUnknown, URL: block.webURL)
}
public func viewControllerForCourseOutlineModeChange() -> UIViewController {
return self
}
public func courseOutlineModeChanged(courseMode: CourseOutlineMode) {
headersLoader.removeBacking()
lastAccessedController.loadLastAccessed(forMode: courseMode)
reload()
}
private func reload() {
self.blockIDStream.backWithStream(Stream(value : self.blockID))
}
private func emptyState() -> LoadState {
switch modeController.currentMode {
case .Full:
return LoadState.failed(error : NSError.oex_courseContentLoadError())
case .Video:
let message = OEXLocalizedString("NO_VIDEOS_TRY_MODE_SWITCHER", nil)
let attributedMessage = loadController.messageStyle.attributedStringWithText(message)
let formattedMessage = attributedMessage.oex_formatWithParameters(["mode_switcher" : Icon.CourseModeVideo.attributedTextWithStyle(loadController.messageStyle , inline : true)])
let accessibilityMessage = message.oex_formatWithParameters(["mode_switcher" : OEXLocalizedString("COURSE_MODE_PICKER_DESCRIPTION", nil)])
return LoadState.empty(icon: Icon.CourseModeFull, attributedMessage : formattedMessage, accessibilityMessage : accessibilityMessage)
}
}
private func showErrorIfNecessary(error : NSError) {
if self.loadController.state.isInitial {
self.loadController.state = LoadState.failed(error : error)
}
}
private func loadedHeaders(headers : CourseOutlineQuerier.BlockGroup) {
self.setupNavigationItem(headers.block)
let children = headers.children.map {header in
return self.courseQuerier.childrenOfBlockWithID(header.blockID, forMode: self.modeController.currentMode)
}
rowsLoader.backWithStream(joinStreams(children))
}
private func addListeners() {
blockIDStream.listen(self,
success: {[weak self] blockID in
self?.backHeadersLoaderWithBlockID(blockID)
},
failure: {[weak self] error in
self?.headersLoader.backWithStream(Stream(error: error))
})
headersLoader.listen(self,
success: {[weak self] headers in
self?.loadedHeaders(headers)
},
failure: {[weak self] error in
self?.rowsLoader.backWithStream(Stream(error: error))
self?.showErrorIfNecessary(error)
}
)
rowsLoader.listen(self,
success : {[weak self] groups in
if let owner = self, nodes = owner.headersLoader.value {
owner.tableController.groups = groups
owner.tableController.tableView.reloadData()
owner.loadController.state = groups.count == 0 ? owner.emptyState() : .Loaded
}
},
failure : {[weak self] error in
self?.showErrorIfNecessary(error)
},
finally: {[weak self] in
self?.tableController.refreshController.endRefreshing()
}
)
}
private func backHeadersLoaderWithBlockID(blockID : CourseBlockID?) {
self.headersLoader.backWithStream(courseQuerier.childrenOfBlockWithID(blockID, forMode: modeController.currentMode))
}
// MARK: Outline Table Delegate
func outlineTableController(controller: CourseOutlineTableController, choseDownloadVideosRootedAtBlock block: CourseBlock) {
let hasWifi = environment.reachability.isReachableViaWiFi() ?? false
let onlyOnWifi = environment.dataManager.interface?.shouldDownloadOnlyOnWifi ?? false
if onlyOnWifi && !hasWifi {
self.loadController.showOverlayError(OEXLocalizedString("NO_WIFI_MESSAGE", nil))
return
}
let courseID = self.courseID
let analytics = environment.analytics
let videoStream = courseQuerier.flatMapRootedAtBlockWithID(block.blockID) { block -> [(String)] in
block.type.asVideo.map { _ in return [block.blockID] } ?? []
}
let parentStream = courseQuerier.parentOfBlockWithID(block.blockID)
let stream = joinStreams(parentStream, videoStream)
stream.listenOnce(self,
success : { [weak self] (parentID, videos) in
let interface = self?.environment.dataManager.interface
interface?.downloadVideosWithIDs(videos, courseID: courseID)
if block.type.asVideo != nil {
analytics?.trackSingleVideoDownload(block.blockID, courseID: courseID, unitURL: block.webURL?.absoluteString)
}
else {
analytics?.trackSubSectionBulkVideoDownload(parentID, subsection: block.blockID, courseID: courseID, videoCount: videos.count)
}
},
failure : {[weak self] error in
self?.loadController.showOverlayError(error.localizedDescription)
}
)
}
func outlineTableController(controller: CourseOutlineTableController, choseBlock block: CourseBlock, withParentID parent : CourseBlockID) {
self.environment.router?.showContainerForBlockWithID(block.blockID, type:block.displayType, parentID: parent, courseID: courseQuerier.courseID, fromController:self)
}
private func expandAccessStream(stream : Stream<CourseLastAccessed>) -> Stream<(CourseBlock, CourseLastAccessed)> {
return stream.transform {[weak self] lastAccessed in
return joinStreams(self?.courseQuerier.blockWithID(lastAccessed.moduleId) ?? Stream<CourseBlock>(), Stream(value: lastAccessed))
}
}
//MARK: PullRefreshControllerDelegate
public func refreshControllerActivated(controller: PullRefreshController) {
courseQuerier.needsRefresh = true
reload()
}
//MARK: DownloadProgressViewControllerDelegate
public func downloadProgressControllerChoseShowDownloads(controller: DownloadProgressViewController) {
self.environment.router?.showDownloadsFromViewController(self)
}
//MARK: CourseContentPageViewControllerDelegate
public func courseContentPageViewController(controller: CourseContentPageViewController, enteredItemInGroup blockID : CourseBlockID) {
self.blockIDStream.backWithStream(courseQuerier.parentOfBlockWithID(blockID))
}
//MARK: LastAccessedControllerDeleagte
public func courseLastAccessedControllerDidFetchLastAccessedItem(item: CourseLastAccessed?) {
if let lastAccessedItem = item {
self.tableController.showLastAccessedWithItem(lastAccessedItem)
}
else {
self.tableController.hideLastAccessed()
}
}
public func presentationControllerForOpenOnWebController(controller: OpenOnWebController) -> UIViewController {
return self
}
}
extension CourseOutlineViewController {
public func t_setup() -> Stream<Void> {
return rowsLoader.map { _ in
}
}
public func t_currentChildCount() -> Int {
return tableController.groups.count
}
public func t_populateLastAccessedItem(item : CourseLastAccessed) -> Bool {
self.tableController.showLastAccessedWithItem(item)
return self.tableController.tableView.tableHeaderView != nil
}
public func t_didTriggerSetLastAccessed() -> Bool {
return t_hasTriggeredSetLastAccessed
}
}
| apache-2.0 | c8baf42e94bc4bbbf14898d1075f168d | 41.020833 | 202 | 0.688363 | 5.791222 | false | false | false | false |
jessesquires/Cartography | CartographyTests/EdgeSpec.swift | 1 | 9394 | import Cartography
import Nimble
import Quick
class EdgeSpec: QuickSpec {
override func spec() {
var superview: View!
var view: View!
beforeEach {
superview = TestView(frame: CGRectMake(0, 0, 400, 400))
view = TestView(frame: CGRectZero)
superview.addSubview(view)
constrain(view) { view in
view.height == 200
view.width == 200
}
}
describe("LayoutProxy.top") {
it("should support relative equalities") {
layout(view) { view in
view.top == view.superview!.top
}
expect(view.frame.minY).to(equal(0))
}
it("should support relative inequalities") {
layout(view) { view in
view.top <= view.superview!.top
view.top >= view.superview!.top
}
expect(view.frame.minY).to(equal(0))
}
it("should support addition") {
layout(view) { view in
view.top == view.superview!.top + 100
}
expect(view.frame.minY).to(equal(100))
}
it("should support subtraction") {
layout(view) { view in
view.top == view.superview!.top - 100
}
expect(view.frame.minY).to(equal(-100))
}
}
describe("LayoutProxy.right") {
it("should support relative equalities") {
layout(view) { view in
view.right == view.superview!.right
}
expect(view.frame.maxX).to(equal(400))
}
it("should support relative inequalities") {
layout(view) { view in
view.right <= view.superview!.right
view.right >= view.superview!.right
}
expect(view.frame.maxX).to(equal(400))
}
it("should support addition") {
layout(view) { view in
view.right == view.superview!.right + 100
}
expect(view.frame.maxX).to(equal(500))
}
it("should support subtraction") {
layout(view) { view in
view.right == view.superview!.right - 100
}
expect(view.frame.maxX).to(equal(300))
}
}
describe("LayoutProxy.bottom") {
it("should support relative equalities") {
layout(view) { view in
view.bottom == view.superview!.bottom
}
expect(view.frame.maxY).to(equal(400))
}
it("should support relative inequalities") {
layout(view) { view in
view.bottom <= view.superview!.bottom
view.bottom >= view.superview!.bottom
}
expect(view.frame.maxY).to(equal(400))
}
it("should support addition") {
layout(view) { view in
view.bottom == view.superview!.bottom + 100
}
expect(view.frame.maxY).to(equal(500))
}
it("should support subtraction") {
layout(view) { view in
view.bottom == view.superview!.bottom - 100
}
expect(view.frame.maxY).to(equal(300))
}
}
describe("LayoutProxy.left") {
it("should support relative equalities") {
layout(view) { view in
view.left == view.superview!.left
}
expect(view.frame.minX).to(equal(0))
}
it("should support relative inequalities") {
layout(view) { view in
view.left <= view.superview!.left
view.left >= view.superview!.left
}
expect(view.frame.minX).to(equal(0))
}
it("should support addition") {
layout(view) { view in
view.left == view.superview!.left + 100
}
expect(view.frame.minX).to(equal(100))
}
it("should support subtraction") {
layout(view) { view in
view.left == view.superview!.left - 100
}
expect(view.frame.minX).to(equal(-100))
}
}
describe("LayoutProxy.centerX") {
it("should support relative equalities") {
layout(view) { view in
view.centerX == view.superview!.centerX
}
expect(view.frame.midX).to(equal(200))
}
it("should support relative inequalities") {
layout(view) { view in
view.centerX <= view.superview!.centerX
view.centerX >= view.superview!.centerX
}
expect(view.frame.midX).to(equal(200))
}
it("should support addition") {
layout(view) { view in
view.centerX == view.superview!.centerX + 100
}
expect(view.frame.midX).to(equal(300))
}
it("should support subtraction") {
layout(view) { view in
view.centerX == view.superview!.centerX - 100
}
expect(view.frame.midX).to(equal(100))
}
it("should support multiplication") {
layout(view) { view in
view.centerX == view.superview!.centerX * 2
}
expect(view.frame.midX).to(equal(400))
}
it("should support division") {
layout(view) { view in
view.centerX == view.superview!.centerX / 2
}
expect(view.frame.midX).to(equal(100))
}
}
describe("LayoutProxy.centerX") {
it("should support relative equalities") {
layout(view) { view in
view.centerX == view.superview!.centerX
}
expect(view.frame.midY).to(equal(200))
}
it("should support relative inequalities") {
layout(view) { view in
view.centerX <= view.superview!.centerX
view.centerX >= view.superview!.centerX
}
expect(view.frame.midY).to(equal(200))
}
it("should support addition") {
layout(view) { view in
view.centerX == view.superview!.centerX + 100
}
expect(view.frame.midY).to(equal(300))
}
it("should support subtraction") {
layout(view) { view in
view.centerX == view.superview!.centerX - 100
}
expect(view.frame.midY).to(equal(100))
}
it("should support multiplication") {
layout(view) { view in
view.centerX == view.superview!.centerX * 2
}
expect(view.frame.midY).to(equal(400))
}
it("should support division") {
layout(view) { view in
view.centerX == view.superview!.centerX / 2
}
expect(view.frame.midY).to(equal(100))
}
}
#if os(iOS)
describe("on iOS only") {
beforeEach {
view.layoutMargins = UIEdgeInsets(top: -10, left: -20, bottom: -30, right: -40)
}
describe("LayoutProxy.topMargin") {
it("should support relative equalities") {
layout(view) { view in
view.topMargin == view.superview!.top
}
expect(view.frame.minY).to(equal(10))
}
}
describe("LayoutProxy.rightMargin") {
it("should support relative equalities") {
layout(view) { view in
view.rightMargin == view.superview!.right
}
expect(view.frame.maxX).to(equal(360))
}
}
describe("LayoutProxy.bottomMargin") {
it("should support relative equalities") {
layout(view) { view in
view.bottomMargin == view.superview!.bottom
}
expect(view.frame.maxY).to(equal(370))
}
}
describe("LayoutProxy.leftMargin") {
it("should support relative equalities") {
layout(view) { view in
view.leftMargin == view.superview!.left
}
expect(view.frame.minX).to(equal(20))
}
}
}
#endif
}
}
| mit | f7eb8af8a815041b958a8d743dd5a0af | 29.01278 | 95 | 0.436129 | 5.215991 | false | false | false | false |
parkera/swift-corelibs-foundation | Foundation/FileManager.swift | 1 | 58684 | // 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 os(Android) // struct stat.st_mode is UInt32
internal func &(left: UInt32, right: mode_t) -> mode_t {
return mode_t(left) & right
}
#endif
import CoreFoundation
open class FileManager : NSObject {
/* Returns the default singleton instance.
*/
private static let _default = FileManager()
open class var `default`: FileManager {
get {
return _default
}
}
/// Returns an array of URLs that identify the mounted volumes available on the device.
open func mountedVolumeURLs(includingResourceValuesForKeys propertyKeys: [URLResourceKey]?, options: VolumeEnumerationOptions = []) -> [URL]? {
return _mountedVolumeURLs(includingResourceValuesForKeys: propertyKeys, options: options)
}
/* Returns an NSArray of NSURLs identifying the the directory entries.
If the directory contains no entries, this method will return the empty array. When an array is specified for the 'keys' parameter, the specified property values will be pre-fetched and cached with each enumerated URL.
This method always does a shallow enumeration of the specified directory (i.e. it always acts as if NSDirectoryEnumerationSkipsSubdirectoryDescendants has been specified). If you need to perform a deep enumeration, use -[NSFileManager enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:].
If you wish to only receive the URLs and no other attributes, then pass '0' for 'options' and an empty NSArray ('[NSArray array]') for 'keys'. If you wish to have the property caches of the vended URLs pre-populated with a default set of attributes, then pass '0' for 'options' and 'nil' for 'keys'.
*/
open func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: DirectoryEnumerationOptions = []) throws -> [URL] {
var error : Error? = nil
let e = self.enumerator(at: url, includingPropertiesForKeys: keys, options: mask.union(.skipsSubdirectoryDescendants)) { (url, err) -> Bool in
error = err
return false
}
var result = [URL]()
if let e = e {
for url in e {
result.append(url as! URL)
}
if let error = error {
throw error
}
}
return result
}
internal enum _SearchPathDomain {
case system
case local
case network
case user
static let correspondingValues: [UInt: _SearchPathDomain] = [
SearchPathDomainMask.systemDomainMask.rawValue: .system,
SearchPathDomainMask.localDomainMask.rawValue: .local,
SearchPathDomainMask.networkDomainMask.rawValue: .network,
SearchPathDomainMask.userDomainMask.rawValue: .user,
]
static let searchOrder: [SearchPathDomainMask] = [
.systemDomainMask,
.localDomainMask,
.networkDomainMask,
.userDomainMask,
]
init?(_ domainMask: SearchPathDomainMask) {
if let value = _SearchPathDomain.correspondingValues[domainMask.rawValue] {
self = value
} else {
return nil
}
}
static func allInSearchOrder(from domainMask: SearchPathDomainMask) -> [_SearchPathDomain] {
var domains: [_SearchPathDomain] = []
for bit in _SearchPathDomain.searchOrder {
if domainMask.contains(bit) {
domains.append(_SearchPathDomain.correspondingValues[bit.rawValue]!)
}
}
return domains
}
}
/* -URLsForDirectory:inDomains: is analogous to NSSearchPathForDirectoriesInDomains(), but returns an array of NSURL instances for use with URL-taking APIs. This API is suitable when you need to search for a file or files which may live in one of a variety of locations in the domains specified.
*/
open func urls(for directory: SearchPathDirectory, in domainMask: SearchPathDomainMask) -> [URL] {
return _urls(for: directory, in: domainMask)
}
internal lazy var xdgHomeDirectory: String = {
let key = "HOME="
if let contents = try? String(contentsOfFile: "/etc/default/useradd", encoding: .utf8) {
for line in contents.components(separatedBy: "\n") {
if line.hasPrefix(key) {
let index = line.index(line.startIndex, offsetBy: key.count)
let str = String(line[index...]) as NSString
let homeDir = str.trimmingCharacters(in: CharacterSet.whitespaces)
if homeDir.count > 0 {
return homeDir
}
}
}
}
return "/home"
}()
private enum URLForDirectoryError: Error {
case directoryUnknown
}
/* -URLForDirectory:inDomain:appropriateForURL:create:error: is a URL-based replacement for FSFindFolder(). It allows for the specification and (optional) creation of a specific directory for a particular purpose (e.g. the replacement of a particular item on disk, or a particular Library directory.
You may pass only one of the values from the NSSearchPathDomainMask enumeration, and you may not pass NSAllDomainsMask.
*/
open func url(for directory: SearchPathDirectory, in domain: SearchPathDomainMask, appropriateFor url: URL?, create shouldCreate: Bool) throws -> URL {
let urls = self.urls(for: directory, in: domain)
guard let url = urls.first else {
// On Apple OSes, this case returns nil without filling in the error parameter; Swift then synthesizes an error rather than trap.
// We simulate that behavior by throwing a private error.
throw URLForDirectoryError.directoryUnknown
}
if shouldCreate {
var attributes: [FileAttributeKey : Any] = [:]
switch _SearchPathDomain(domain) {
case .some(.user):
attributes[.posixPermissions] = 0700
case .some(.system):
attributes[.posixPermissions] = 0755
attributes[.ownerAccountID] = 0 // root
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
attributes[.ownerAccountID] = 80 // on Darwin, the admin group's fixed ID.
#endif
default:
break
}
try createDirectory(at: url, withIntermediateDirectories: true, attributes: attributes)
}
return url
}
/* Sets 'outRelationship' to NSURLRelationshipContains if the directory at 'directoryURL' directly or indirectly contains the item at 'otherURL', meaning 'directoryURL' is found while enumerating parent URLs starting from 'otherURL'. Sets 'outRelationship' to NSURLRelationshipSame if 'directoryURL' and 'otherURL' locate the same item, meaning they have the same NSURLFileResourceIdentifierKey value. If 'directoryURL' is not a directory, or does not contain 'otherURL' and they do not locate the same file, then sets 'outRelationship' to NSURLRelationshipOther. If an error occurs, returns NO and sets 'error'.
*/
open func getRelationship(_ outRelationship: UnsafeMutablePointer<URLRelationship>, ofDirectoryAt directoryURL: URL, toItemAt otherURL: URL) throws {
NSUnimplemented()
}
/* Similar to -[NSFileManager getRelationship:ofDirectoryAtURL:toItemAtURL:error:], except that the directory is instead defined by an NSSearchPathDirectory and NSSearchPathDomainMask. Pass 0 for domainMask to instruct the method to automatically choose the domain appropriate for 'url'. For example, to discover if a file is contained by a Trash directory, call [fileManager getRelationship:&result ofDirectory:NSTrashDirectory inDomain:0 toItemAtURL:url error:&error].
*/
open func getRelationship(_ outRelationship: UnsafeMutablePointer<URLRelationship>, of directory: SearchPathDirectory, in domainMask: SearchPathDomainMask, toItemAt url: URL) throws {
NSUnimplemented()
}
/* createDirectoryAtURL:withIntermediateDirectories:attributes:error: creates a directory at the specified URL. If you pass 'NO' for withIntermediateDirectories, the directory must not exist at the time this call is made. Passing 'YES' for withIntermediateDirectories will create any necessary intermediate directories. This method returns YES if all directories specified in 'url' were created and attributes were set. Directories are created with attributes specified by the dictionary passed to 'attributes'. If no dictionary is supplied, directories are created according to the umask of the process. This method returns NO if a failure occurs at any stage of the operation. If an error parameter was provided, a presentable NSError will be returned by reference.
*/
open func createDirectory(at url: URL, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey : Any]? = [:]) throws {
guard url.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : url])
}
try self.createDirectory(atPath: url.path, withIntermediateDirectories: createIntermediates, attributes: attributes)
}
/* createSymbolicLinkAtURL:withDestinationURL:error: returns YES if the symbolic link that point at 'destURL' was able to be created at the location specified by 'url'. 'destURL' is always resolved against its base URL, if it has one. If 'destURL' has no base URL and it's 'relativePath' is indeed a relative path, then a relative symlink will be created. If this method returns NO, the link was unable to be created and an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink.
*/
open func createSymbolicLink(at url: URL, withDestinationURL destURL: URL) throws {
guard url.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : url])
}
guard destURL.scheme == nil || destURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : destURL])
}
try self.createSymbolicLink(atPath: url.path, withDestinationPath: destURL.path)
}
/* Instances of FileManager may now have delegates. Each instance has one delegate, and the delegate is not retained. In versions of Mac OS X prior to 10.5, the behavior of calling [[NSFileManager alloc] init] was undefined. In Mac OS X 10.5 "Leopard" and later, calling [[NSFileManager alloc] init] returns a new instance of an FileManager.
*/
open weak var delegate: FileManagerDelegate?
/* setAttributes:ofItemAtPath:error: returns YES when the attributes specified in the 'attributes' dictionary are set successfully on the item specified by 'path'. If this method returns NO, a presentable NSError will be provided by-reference in the 'error' parameter. If no error is required, you may pass 'nil' for the error.
This method replaces changeFileAttributes:atPath:.
*/
open func setAttributes(_ attributes: [FileAttributeKey : Any], ofItemAtPath path: String) throws {
try _fileSystemRepresentation(withPath: path, { fsRep in
for attribute in attributes.keys {
if attribute == .posixPermissions {
guard let number = attributes[attribute] as? NSNumber else {
fatalError("Can't set file permissions to \(attributes[attribute] as Any?)")
}
#if os(macOS) || os(iOS)
let modeT = number.uint16Value
#elseif os(Linux) || os(Android) || os(Windows)
let modeT = number.uint32Value
#endif
guard chmod(fsRep, mode_t(modeT)) == 0 else {
throw _NSErrorWithErrno(errno, reading: false, path: path)
}
} else {
fatalError("Attribute type not implemented: \(attribute)")
}
}
})
}
/* createDirectoryAtPath:withIntermediateDirectories:attributes:error: creates a directory at the specified path. If you pass 'NO' for createIntermediates, the directory must not exist at the time this call is made. Passing 'YES' for 'createIntermediates' will create any necessary intermediate directories. This method returns YES if all directories specified in 'path' were created and attributes were set. Directories are created with attributes specified by the dictionary passed to 'attributes'. If no dictionary is supplied, directories are created according to the umask of the process. This method returns NO if a failure occurs at any stage of the operation. If an error parameter was provided, a presentable NSError will be returned by reference.
This method replaces createDirectoryAtPath:attributes:
*/
open func createDirectory(atPath path: String, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey : Any]? = [:]) throws {
return try _createDirectory(atPath: path, withIntermediateDirectories: createIntermediates, attributes: attributes)
}
/**
Performs a shallow search of the specified directory and returns the paths of any contained items.
This method performs a shallow search of the directory and therefore does not traverse symbolic links or return the contents of any subdirectories. This method also does not return URLs for the current directory (“.”), parent directory (“..”) but it does return other hidden files (files that begin with a period character).
The order of the files in the returned array is undefined.
- Parameter path: The path to the directory whose contents you want to enumerate.
- Throws: `NSError` if the directory does not exist, this error is thrown with the associated error code.
- Returns: An array of String each of which identifies a file, directory, or symbolic link contained in `path`. The order of the files returned is undefined.
*/
open func contentsOfDirectory(atPath path: String) throws -> [String] {
var contents: [String] = []
try _contentsOfDir(atPath: path, { (entryName, entryType) throws in
contents.append(entryName)
})
return contents
}
/**
Performs a deep enumeration of the specified directory and returns the paths of all of the contained subdirectories.
This method recurses the specified directory and its subdirectories. The method skips the “.” and “..” directories at each level of the recursion.
Because this method recurses the directory’s contents, you might not want to use it in performance-critical code. Instead, consider using the enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: or enumeratorAtPath: method to enumerate the directory contents yourself. Doing so gives you more control over the retrieval of items and more opportunities to abort the enumeration or perform other tasks at the same time.
- Parameter path: The path of the directory to list.
- Throws: `NSError` if the directory does not exist, this error is thrown with the associated error code.
- Returns: An array of NSString objects, each of which contains the path of an item in the directory specified by path. If path is a symbolic link, this method traverses the link. This method returns nil if it cannot retrieve the device of the linked-to file.
*/
open func subpathsOfDirectory(atPath path: String) throws -> [String] {
return try _subpathsOfDirectory(atPath: path)
}
/* attributesOfItemAtPath:error: returns an NSDictionary of key/value pairs containing the attributes of the item (file, directory, symlink, etc.) at the path in question. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink.
This method replaces fileAttributesAtPath:traverseLink:.
*/
open func attributesOfItem(atPath path: String) throws -> [FileAttributeKey : Any] {
var result: [FileAttributeKey:Any] = [:]
#if os(Linux)
let (s, creationDate) = try _statxFile(atPath: path)
result[.creationDate] = creationDate
#else
let s = try _lstatFile(atPath: path)
#endif
result[.size] = NSNumber(value: UInt64(s.st_size))
#if os(macOS) || os(iOS)
let ti = (TimeInterval(s.st_mtimespec.tv_sec) - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * TimeInterval(s.st_mtimespec.tv_nsec))
#elseif os(Android)
let ti = (TimeInterval(s.st_mtime) - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * TimeInterval(s.st_mtime_nsec))
#elseif os(Windows)
let ti = (TimeInterval(s.st_mtime) - kCFAbsoluteTimeIntervalSince1970)
#else
let ti = (TimeInterval(s.st_mtim.tv_sec) - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * TimeInterval(s.st_mtim.tv_nsec))
#endif
result[.modificationDate] = Date(timeIntervalSinceReferenceDate: ti)
result[.posixPermissions] = NSNumber(value: _filePermissionsMask(mode: UInt32(s.st_mode)))
result[.referenceCount] = NSNumber(value: UInt64(s.st_nlink))
result[.systemNumber] = NSNumber(value: UInt64(s.st_dev))
result[.systemFileNumber] = NSNumber(value: UInt64(s.st_ino))
#if os(Windows)
result[.deviceIdentifier] = NSNumber(value: UInt64(s.st_rdev))
let type = FileAttributeType(attributes: try windowsFileAttributes(atPath: path))
#else
if let pwd = getpwuid(s.st_uid), pwd.pointee.pw_name != nil {
let name = String(cString: pwd.pointee.pw_name)
result[.ownerAccountName] = name
}
if let grd = getgrgid(s.st_gid), grd.pointee.gr_name != nil {
let name = String(cString: grd.pointee.gr_name)
result[.groupOwnerAccountName] = name
}
let type = FileAttributeType(statMode: s.st_mode)
#endif
result[.type] = type
if type == .typeBlockSpecial || type == .typeCharacterSpecial {
result[.deviceIdentifier] = NSNumber(value: UInt64(s.st_rdev))
}
#if os(macOS) || os(iOS)
if (s.st_flags & UInt32(UF_IMMUTABLE | SF_IMMUTABLE)) != 0 {
result[.immutable] = NSNumber(value: true)
}
if (s.st_flags & UInt32(UF_APPEND | SF_APPEND)) != 0 {
result[.appendOnly] = NSNumber(value: true)
}
#endif
result[.ownerAccountID] = NSNumber(value: UInt64(s.st_uid))
result[.groupOwnerAccountID] = NSNumber(value: UInt64(s.st_gid))
return result
}
/* attributesOfFileSystemForPath:error: returns an NSDictionary of key/value pairs containing the attributes of the filesystem containing the provided path. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink.
This method replaces fileSystemAttributesAtPath:.
*/
#if os(Android)
@available(*, unavailable, message: "Unsuppported on this platform")
open func attributesOfFileSystem(forPath path: String) throws -> [FileAttributeKey : Any] {
NSUnsupported()
}
#else
open func attributesOfFileSystem(forPath path: String) throws -> [FileAttributeKey : Any] {
return try _attributesOfFileSystem(forPath: path)
}
#endif
/* createSymbolicLinkAtPath:withDestination:error: returns YES if the symbolic link that point at 'destPath' was able to be created at the location specified by 'path'. If this method returns NO, the link was unable to be created and an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink.
This method replaces createSymbolicLinkAtPath:pathContent:
*/
open func createSymbolicLink(atPath path: String, withDestinationPath destPath: String) throws {
return try _createSymbolicLink(atPath: path, withDestinationPath: destPath)
}
/* destinationOfSymbolicLinkAtPath:error: returns a String containing the path of the item pointed at by the symlink specified by 'path'. If this method returns 'nil', an NSError will be thrown.
This method replaces pathContentOfSymbolicLinkAtPath:
*/
open func destinationOfSymbolicLink(atPath path: String) throws -> String {
return try _destinationOfSymbolicLink(atPath: path)
}
internal func extraErrorInfo(srcPath: String?, dstPath: String?, userVariant: String?) -> [String : Any] {
var result = [String : Any]()
result["NSSourceFilePathErrorKey"] = srcPath
result["NSDestinationFilePath"] = dstPath
result["NSUserStringVariant"] = userVariant.map(NSArray.init(object:))
return result
}
internal func shouldProceedAfterError(_ error: Error, copyingItemAtPath path: String, toPath: String, isURL: Bool) -> Bool {
guard let delegate = self.delegate else { return false }
if isURL {
return delegate.fileManager(self, shouldProceedAfterError: error, copyingItemAt: URL(fileURLWithPath: path), to: URL(fileURLWithPath: toPath))
} else {
return delegate.fileManager(self, shouldProceedAfterError: error, copyingItemAtPath: path, toPath: toPath)
}
}
internal func shouldCopyItemAtPath(_ path: String, toPath: String, isURL: Bool) -> Bool {
guard let delegate = self.delegate else { return true }
if isURL {
return delegate.fileManager(self, shouldCopyItemAt: URL(fileURLWithPath: path), to: URL(fileURLWithPath: toPath))
} else {
return delegate.fileManager(self, shouldCopyItemAtPath: path, toPath: toPath)
}
}
fileprivate func _copyItem(atPath srcPath: String, toPath dstPath: String, isURL: Bool) throws {
try _copyOrLinkDirectoryHelper(atPath: srcPath, toPath: dstPath) { (srcPath, dstPath, fileType) in
guard shouldCopyItemAtPath(srcPath, toPath: dstPath, isURL: isURL) else {
return
}
do {
switch fileType {
case .typeRegular:
try _copyRegularFile(atPath: srcPath, toPath: dstPath)
case .typeSymbolicLink:
try _copySymlink(atPath: srcPath, toPath: dstPath)
default:
break
}
} catch {
if !shouldProceedAfterError(error, copyingItemAtPath: srcPath, toPath: dstPath, isURL: isURL) {
throw error
}
}
}
}
internal func shouldProceedAfterError(_ error: Error, movingItemAtPath path: String, toPath: String, isURL: Bool) -> Bool {
guard let delegate = self.delegate else { return false }
if isURL {
return delegate.fileManager(self, shouldProceedAfterError: error, movingItemAt: URL(fileURLWithPath: path), to: URL(fileURLWithPath: toPath))
} else {
return delegate.fileManager(self, shouldProceedAfterError: error, movingItemAtPath: path, toPath: toPath)
}
}
internal func shouldMoveItemAtPath(_ path: String, toPath: String, isURL: Bool) -> Bool {
guard let delegate = self.delegate else { return true }
if isURL {
return delegate.fileManager(self, shouldMoveItemAt: URL(fileURLWithPath: path), to: URL(fileURLWithPath: toPath))
} else {
return delegate.fileManager(self, shouldMoveItemAtPath: path, toPath: toPath)
}
}
internal func shouldProceedAfterError(_ error: Error, linkingItemAtPath path: String, toPath: String, isURL: Bool) -> Bool {
guard let delegate = self.delegate else { return false }
if isURL {
return delegate.fileManager(self, shouldProceedAfterError: error, linkingItemAt: URL(fileURLWithPath: path), to: URL(fileURLWithPath: toPath))
} else {
return delegate.fileManager(self, shouldProceedAfterError: error, linkingItemAtPath: path, toPath: toPath)
}
}
internal func shouldLinkItemAtPath(_ path: String, toPath: String, isURL: Bool) -> Bool {
guard let delegate = self.delegate else { return true }
if isURL {
return delegate.fileManager(self, shouldLinkItemAt: URL(fileURLWithPath: path), to: URL(fileURLWithPath: toPath))
} else {
return delegate.fileManager(self, shouldLinkItemAtPath: path, toPath: toPath)
}
}
internal func shouldProceedAfterError(_ error: Error, removingItemAtPath path: String, isURL: Bool) -> Bool {
guard let delegate = self.delegate else { return false }
if isURL {
return delegate.fileManager(self, shouldProceedAfterError: error, removingItemAt: URL(fileURLWithPath: path))
} else {
return delegate.fileManager(self, shouldProceedAfterError: error, removingItemAtPath: path)
}
}
internal func shouldRemoveItemAtPath(_ path: String, isURL: Bool) -> Bool {
guard let delegate = self.delegate else { return true }
if isURL {
return delegate.fileManager(self, shouldRemoveItemAt: URL(fileURLWithPath: path))
} else {
return delegate.fileManager(self, shouldRemoveItemAtPath: path)
}
}
open func copyItem(atPath srcPath: String, toPath dstPath: String) throws {
try _copyItem(atPath: srcPath, toPath: dstPath, isURL: false)
}
open func moveItem(atPath srcPath: String, toPath dstPath: String) throws {
try _moveItem(atPath: srcPath, toPath: dstPath, isURL: false)
}
open func linkItem(atPath srcPath: String, toPath dstPath: String) throws {
try _linkItem(atPath: srcPath, toPath: dstPath, isURL: false)
}
open func removeItem(atPath path: String) throws {
try _removeItem(atPath: path, isURL: false)
}
open func copyItem(at srcURL: URL, to dstURL: URL) throws {
guard srcURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : srcURL])
}
guard dstURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : dstURL])
}
try _copyItem(atPath: srcURL.path, toPath: dstURL.path, isURL: true)
}
open func moveItem(at srcURL: URL, to dstURL: URL) throws {
guard srcURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : srcURL])
}
guard dstURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : dstURL])
}
try _moveItem(atPath: srcURL.path, toPath: dstURL.path, isURL: true)
}
open func linkItem(at srcURL: URL, to dstURL: URL) throws {
guard srcURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : srcURL])
}
guard dstURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : dstURL])
}
try _linkItem(atPath: srcURL.path, toPath: dstURL.path, isURL: true)
}
open func removeItem(at url: URL) throws {
guard url.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : url])
}
try _removeItem(atPath: url.path, isURL: true)
}
/* Process working directory management. Despite the fact that these are instance methods on FileManager, these methods report and change (respectively) the working directory for the entire process. Developers are cautioned that doing so is fraught with peril.
*/
open var currentDirectoryPath: String {
return _currentDirectoryPath()
}
@discardableResult
open func changeCurrentDirectoryPath(_ path: String) -> Bool {
return _changeCurrentDirectoryPath(path)
}
/* The following methods are of limited utility. Attempting to predicate behavior based on the current state of the filesystem or a particular file on the filesystem is encouraging odd behavior in the face of filesystem race conditions. It's far better to attempt an operation (like loading a file or creating a directory) and handle the error gracefully than it is to try to figure out ahead of time whether the operation will succeed.
*/
open func fileExists(atPath path: String) -> Bool {
return _fileExists(atPath: path, isDirectory: nil)
}
open func fileExists(atPath path: String, isDirectory: UnsafeMutablePointer<ObjCBool>?) -> Bool {
return _fileExists(atPath: path, isDirectory: isDirectory)
}
open func isReadableFile(atPath path: String) -> Bool {
return _isReadableFile(atPath: path)
}
open func isWritableFile(atPath path: String) -> Bool {
return _isWritableFile(atPath: path)
}
open func isExecutableFile(atPath path: String) -> Bool {
return _isExecutableFile(atPath: path)
}
/**
- parameters:
- path: The path to the file we are trying to determine is deletable.
- returns: `true` if the file is deletable, `false` otherwise.
*/
open func isDeletableFile(atPath path: String) -> Bool {
return _isDeletableFile(atPath: path)
}
internal func _compareDirectories(atPath path1: String, andPath path2: String) -> Bool {
guard let enumerator1 = enumerator(atPath: path1) else {
return false
}
guard let enumerator2 = enumerator(atPath: path2) else {
return false
}
var path1entries = Set<String>()
while let item = enumerator1.nextObject() as? String {
path1entries.insert(item)
}
while let item = enumerator2.nextObject() as? String {
if path1entries.remove(item) == nil {
return false
}
if contentsEqual(atPath: NSString(string: path1).appendingPathComponent(item), andPath: NSString(string: path2).appendingPathComponent(item)) == false {
return false
}
}
return path1entries.isEmpty
}
internal func _filePermissionsMask(mode : UInt32) -> Int {
#if os(Windows)
return Int(mode & ~UInt32(ucrt.S_IFMT))
#elseif canImport(Darwin)
return Int(mode & ~UInt32(S_IFMT))
#else
return Int(mode & ~S_IFMT)
#endif
}
internal func _permissionsOfItem(atPath path: String) throws -> Int {
let fileInfo = try _lstatFile(atPath: path)
return _filePermissionsMask(mode: UInt32(fileInfo.st_mode))
}
#if os(Linux)
// statx() is only supported by Linux kernels >= 4.11.0
internal lazy var supportsStatx: Bool = {
let requiredVersion = OperatingSystemVersion(majorVersion: 4, minorVersion: 11, patchVersion: 0)
return ProcessInfo.processInfo.isOperatingSystemAtLeast(requiredVersion)
}()
#endif
/* -contentsEqualAtPath:andPath: does not take into account data stored in the resource fork or filesystem extended attributes.
*/
@available(Windows, deprecated, message: "Not Yet Implemented")
open func contentsEqual(atPath path1: String, andPath path2: String) -> Bool {
return _contentsEqual(atPath: path1, andPath: path2)
}
/* displayNameAtPath: returns an NSString suitable for presentation to the user. For directories which have localization information, this will return the appropriate localized string. This string is not suitable for passing to anything that must interact with the filesystem.
*/
open func displayName(atPath path: String) -> String {
NSUnimplemented()
}
/* componentsToDisplayForPath: returns an NSArray of display names for the path provided. Localization will occur as in displayNameAtPath: above. This array cannot and should not be reassembled into an usable filesystem path for any kind of access.
*/
open func componentsToDisplay(forPath path: String) -> [String]? {
NSUnimplemented()
}
/* enumeratorAtPath: returns an NSDirectoryEnumerator rooted at the provided path. If the enumerator cannot be created, this returns NULL. Because NSDirectoryEnumerator is a subclass of NSEnumerator, the returned object can be used in the for...in construct.
*/
open func enumerator(atPath path: String) -> DirectoryEnumerator? {
return NSPathDirectoryEnumerator(path: path)
}
/* enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: returns an NSDirectoryEnumerator rooted at the provided directory URL. The NSDirectoryEnumerator returns NSURLs from the -nextObject method. The optional 'includingPropertiesForKeys' parameter indicates which resource properties should be pre-fetched and cached with each enumerated URL. The optional 'errorHandler' block argument is invoked when an error occurs. Parameters to the block are the URL on which an error occurred and the error. When the error handler returns YES, enumeration continues if possible. Enumeration stops immediately when the error handler returns NO.
If you wish to only receive the URLs and no other attributes, then pass '0' for 'options' and an empty NSArray ('[NSArray array]') for 'keys'. If you wish to have the property caches of the vended URLs pre-populated with a default set of attributes, then pass '0' for 'options' and 'nil' for 'keys'.
*/
// Note: Because the error handler is an optional block, the compiler treats it as @escaping by default. If that behavior changes, the @escaping will need to be added back.
open func enumerator(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: DirectoryEnumerationOptions = [], errorHandler handler: (/* @escaping */ (URL, Error) -> Bool)? = nil) -> DirectoryEnumerator? {
return NSURLDirectoryEnumerator(url: url, options: mask, errorHandler: handler)
}
/* subpathsAtPath: returns an NSArray of all contents and subpaths recursively from the provided path. This may be very expensive to compute for deep filesystem hierarchies, and should probably be avoided.
*/
open func subpaths(atPath path: String) -> [String]? {
return try? subpathsOfDirectory(atPath: path)
}
/* These methods are provided here for compatibility. The corresponding methods on NSData which return NSErrors should be regarded as the primary method of creating a file from an NSData or retrieving the contents of a file as an NSData.
*/
open func contents(atPath path: String) -> Data? {
return try? Data(contentsOf: URL(fileURLWithPath: path))
}
@discardableResult
open func createFile(atPath path: String, contents data: Data?, attributes attr: [FileAttributeKey : Any]? = nil) -> Bool {
do {
try (data ?? Data()).write(to: URL(fileURLWithPath: path), options: .atomic)
if let attr = attr {
try self.setAttributes(attr, ofItemAtPath: path)
}
return true
} catch {
return false
}
}
/* fileSystemRepresentationWithPath: returns an array of characters suitable for passing to lower-level POSIX style APIs. The string is provided in the representation most appropriate for the filesystem in question.
*/
open func fileSystemRepresentation(withPath path: String) -> UnsafePointer<Int8> {
precondition(path != "", "Empty path argument")
return try! __fileSystemRepresentation(withPath: path)
}
internal func __fileSystemRepresentation(withPath path: String) throws -> UnsafePointer<Int8> {
let len = CFStringGetMaximumSizeOfFileSystemRepresentation(path._cfObject)
if len != kCFNotFound {
let buf = UnsafeMutablePointer<Int8>.allocate(capacity: len)
buf.initialize(repeating: 0, count: len)
if path._nsObject.getFileSystemRepresentation(buf, maxLength: len) {
return UnsafePointer(buf)
}
buf.deinitialize(count: len)
buf.deallocate()
}
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInvalidFileName.rawValue, userInfo: [NSFilePathErrorKey: path])
}
internal func _fileSystemRepresentation<ResultType>(withPath path: String, _ body: (UnsafePointer<Int8>) throws -> ResultType) throws -> ResultType {
let fsRep = try __fileSystemRepresentation(withPath: path)
defer { fsRep.deallocate() }
return try body(fsRep)
}
internal func _fileSystemRepresentation<ResultType>(withPath path1: String, andPath path2: String, _ body: (UnsafePointer<Int8>, UnsafePointer<Int8>) throws -> ResultType) throws -> ResultType {
let fsRep1 = try __fileSystemRepresentation(withPath: path1)
defer { fsRep1.deallocate() }
let fsRep2 = try __fileSystemRepresentation(withPath: path2)
defer { fsRep2.deallocate() }
return try body(fsRep1, fsRep2)
}
/* stringWithFileSystemRepresentation:length: returns an NSString created from an array of bytes that are in the filesystem representation.
*/
open func string(withFileSystemRepresentation str: UnsafePointer<Int8>, length len: Int) -> String {
return NSString(bytes: str, length: len, encoding: String.Encoding.utf8.rawValue)!._swiftObject
}
/* -replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: is for developers who wish to perform a safe-save without using the full NSDocument machinery that is available in the AppKit.
The `originalItemURL` is the item being replaced.
`newItemURL` is the item which will replace the original item. This item should be placed in a temporary directory as provided by the OS, or in a uniquely named directory placed in the same directory as the original item if the temporary directory is not available.
If `backupItemName` is provided, that name will be used to create a backup of the original item. The backup is placed in the same directory as the original item. If an error occurs during the creation of the backup item, the operation will fail. If there is already an item with the same name as the backup item, that item will be removed. The backup item will be removed in the event of success unless the `NSFileManagerItemReplacementWithoutDeletingBackupItem` option is provided in `options`.
For `options`, pass `0` to get the default behavior, which uses only the metadata from the new item while adjusting some properties using values from the original item. Pass `NSFileManagerItemReplacementUsingNewMetadataOnly` in order to use all possible metadata from the new item.
*/
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func replaceItem(at originalItemURL: URL, withItemAt newItemURL: URL, backupItemName: String?, options: ItemReplacementOptions = []) throws {
NSUnimplemented()
}
internal func _tryToResolveTrailingSymlinkInPath(_ path: String) -> String? {
// destinationOfSymbolicLink(atPath:) will fail if the path is not a symbolic link
guard let destination = try? FileManager.default.destinationOfSymbolicLink(atPath: path) else {
return nil
}
return _appendSymlinkDestination(destination, toPath: path)
}
}
extension FileManager {
public func replaceItemAt(_ originalItemURL: URL, withItemAt newItemURL: URL, backupItemName: String? = nil, options: ItemReplacementOptions = []) throws -> NSURL? {
NSUnimplemented()
}
}
extension FileManager {
open var homeDirectoryForCurrentUser: URL {
return homeDirectory(forUser: NSUserName())!
}
open var temporaryDirectory: URL {
return URL(fileURLWithPath: NSTemporaryDirectory())
}
open func homeDirectory(forUser userName: String) -> URL? {
guard !userName.isEmpty else { return nil }
guard let url = CFCopyHomeDirectoryURLForUser(userName._cfObject) else { return nil }
return url.takeRetainedValue()._swiftObject
}
}
extension FileManager {
public struct VolumeEnumerationOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
/* The mounted volume enumeration will skip hidden volumes.
*/
public static let skipHiddenVolumes = VolumeEnumerationOptions(rawValue: 1 << 1)
/* The mounted volume enumeration will produce file reference URLs rather than path-based URLs.
*/
public static let produceFileReferenceURLs = VolumeEnumerationOptions(rawValue: 1 << 2)
}
public struct DirectoryEnumerationOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
/* NSDirectoryEnumerationSkipsSubdirectoryDescendants causes the NSDirectoryEnumerator to perform a shallow enumeration and not descend into directories it encounters.
*/
public static let skipsSubdirectoryDescendants = DirectoryEnumerationOptions(rawValue: 1 << 0)
/* NSDirectoryEnumerationSkipsPackageDescendants will cause the NSDirectoryEnumerator to not descend into packages.
*/
public static let skipsPackageDescendants = DirectoryEnumerationOptions(rawValue: 1 << 1)
/* NSDirectoryEnumerationSkipsHiddenFiles causes the NSDirectoryEnumerator to not enumerate hidden files.
*/
public static let skipsHiddenFiles = DirectoryEnumerationOptions(rawValue: 1 << 2)
}
public struct ItemReplacementOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
/* Causes -replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: to use metadata from the new item only and not to attempt to preserve metadata from the original item.
*/
public static let usingNewMetadataOnly = ItemReplacementOptions(rawValue: 1 << 0)
/* Causes -replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: to leave the backup item in place after a successful replacement. The default behavior is to remove the item.
*/
public static let withoutDeletingBackupItem = ItemReplacementOptions(rawValue: 1 << 1)
}
public enum URLRelationship : Int {
case contains
case same
case other
}
}
public struct FileAttributeKey : RawRepresentable, Equatable, Hashable {
public let rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return self.rawValue.hashValue
}
public static func ==(_ lhs: FileAttributeKey, _ rhs: FileAttributeKey) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static let type = FileAttributeKey(rawValue: "NSFileType")
public static let size = FileAttributeKey(rawValue: "NSFileSize")
public static let modificationDate = FileAttributeKey(rawValue: "NSFileModificationDate")
public static let referenceCount = FileAttributeKey(rawValue: "NSFileReferenceCount")
public static let deviceIdentifier = FileAttributeKey(rawValue: "NSFileDeviceIdentifier")
public static let ownerAccountName = FileAttributeKey(rawValue: "NSFileOwnerAccountName")
public static let groupOwnerAccountName = FileAttributeKey(rawValue: "NSFileGroupOwnerAccountName")
public static let posixPermissions = FileAttributeKey(rawValue: "NSFilePosixPermissions")
public static let systemNumber = FileAttributeKey(rawValue: "NSFileSystemNumber")
public static let systemFileNumber = FileAttributeKey(rawValue: "NSFileSystemFileNumber")
public static let extensionHidden = FileAttributeKey(rawValue: "NSFileExtensionHidden")
public static let hfsCreatorCode = FileAttributeKey(rawValue: "NSFileHFSCreatorCode")
public static let hfsTypeCode = FileAttributeKey(rawValue: "NSFileHFSTypeCode")
public static let immutable = FileAttributeKey(rawValue: "NSFileImmutable")
public static let appendOnly = FileAttributeKey(rawValue: "NSFileAppendOnly")
public static let creationDate = FileAttributeKey(rawValue: "NSFileCreationDate")
public static let ownerAccountID = FileAttributeKey(rawValue: "NSFileOwnerAccountID")
public static let groupOwnerAccountID = FileAttributeKey(rawValue: "NSFileGroupOwnerAccountID")
public static let busy = FileAttributeKey(rawValue: "NSFileBusy")
public static let systemSize = FileAttributeKey(rawValue: "NSFileSystemSize")
public static let systemFreeSize = FileAttributeKey(rawValue: "NSFileSystemFreeSize")
public static let systemNodes = FileAttributeKey(rawValue: "NSFileSystemNodes")
public static let systemFreeNodes = FileAttributeKey(rawValue: "NSFileSystemFreeNodes")
}
public struct FileAttributeType : RawRepresentable, Equatable, Hashable {
public let rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return self.rawValue.hashValue
}
public static func ==(_ lhs: FileAttributeType, _ rhs: FileAttributeType) -> Bool {
return lhs.rawValue == rhs.rawValue
}
#if os(Windows)
internal init(attributes: WIN32_FILE_ATTRIBUTE_DATA) {
if attributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) == DWORD(FILE_ATTRIBUTE_DIRECTORY) {
self = .typeDirectory
} else if attributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DEVICE) == DWORD(FILE_ATTRIBUTE_DEVICE) {
self = .typeCharacterSpecial
} else if attributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_REPARSE_POINT) == DWORD(FILE_ATTRIBUTE_REPARSE_POINT) {
// FIXME(compnerd) this is a lie! It may be a junction or a hard link
self = .typeSymbolicLink
} else if attributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_NORMAL) == DWORD(FILE_ATTRIBUTE_NORMAL) {
self = .typeRegular
} else {
self = .typeUnknown
}
}
#else
internal init(statMode: mode_t) {
switch statMode & S_IFMT {
case S_IFCHR: self = .typeCharacterSpecial
case S_IFDIR: self = .typeDirectory
case S_IFBLK: self = .typeBlockSpecial
case S_IFREG: self = .typeRegular
case S_IFLNK: self = .typeSymbolicLink
case S_IFSOCK: self = .typeSocket
default: self = .typeUnknown
}
}
#endif
public static let typeDirectory = FileAttributeType(rawValue: "NSFileTypeDirectory")
public static let typeRegular = FileAttributeType(rawValue: "NSFileTypeRegular")
public static let typeSymbolicLink = FileAttributeType(rawValue: "NSFileTypeSymbolicLink")
public static let typeSocket = FileAttributeType(rawValue: "NSFileTypeSocket")
public static let typeCharacterSpecial = FileAttributeType(rawValue: "NSFileTypeCharacterSpecial")
public static let typeBlockSpecial = FileAttributeType(rawValue: "NSFileTypeBlockSpecial")
public static let typeUnknown = FileAttributeType(rawValue: "NSFileTypeUnknown")
}
public protocol FileManagerDelegate : NSObjectProtocol {
/* fileManager:shouldCopyItemAtPath:toPath: gives the delegate an opportunity to filter the resulting copy. Returning YES from this method will allow the copy to happen. Returning NO from this method causes the item in question to be skipped. If the item skipped was a directory, no children of that directory will be copied, nor will the delegate be notified of those children.
*/
func fileManager(_ fileManager: FileManager, shouldCopyItemAtPath srcPath: String, toPath dstPath: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldCopyItemAt srcURL: URL, to dstURL: URL) -> Bool
/* fileManager:shouldProceedAfterError:copyingItemAtPath:toPath: gives the delegate an opportunity to recover from or continue copying after an error. If an error occurs, the error object will contain an NSError indicating the problem. The source path and destination paths are also provided. If this method returns YES, the FileManager instance will continue as if the error had not occurred. If this method returns NO, the FileManager instance will stop copying, return NO from copyItemAtPath:toPath:error: and the error will be provided there.
*/
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, copyingItemAtPath srcPath: String, toPath dstPath: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, copyingItemAt srcURL: URL, to dstURL: URL) -> Bool
/* fileManager:shouldMoveItemAtPath:toPath: gives the delegate an opportunity to not move the item at the specified path. If the source path and the destination path are not on the same device, a copy is performed to the destination path and the original is removed. If the copy does not succeed, an error is returned and the incomplete copy is removed, leaving the original in place.
*/
func fileManager(_ fileManager: FileManager, shouldMoveItemAtPath srcPath: String, toPath dstPath: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldMoveItemAt srcURL: URL, to dstURL: URL) -> Bool
/* fileManager:shouldProceedAfterError:movingItemAtPath:toPath: functions much like fileManager:shouldProceedAfterError:copyingItemAtPath:toPath: above. The delegate has the opportunity to remedy the error condition and allow the move to continue.
*/
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, movingItemAtPath srcPath: String, toPath dstPath: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, movingItemAt srcURL: URL, to dstURL: URL) -> Bool
/* fileManager:shouldLinkItemAtPath:toPath: acts as the other "should" methods, but this applies to the file manager creating hard links to the files in question.
*/
func fileManager(_ fileManager: FileManager, shouldLinkItemAtPath srcPath: String, toPath dstPath: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldLinkItemAt srcURL: URL, to dstURL: URL) -> Bool
/* fileManager:shouldProceedAfterError:linkingItemAtPath:toPath: allows the delegate an opportunity to remedy the error which occurred in linking srcPath to dstPath. If the delegate returns YES from this method, the linking will continue. If the delegate returns NO from this method, the linking operation will stop and the error will be returned via linkItemAtPath:toPath:error:.
*/
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, linkingItemAtPath srcPath: String, toPath dstPath: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, linkingItemAt srcURL: URL, to dstURL: URL) -> Bool
/* fileManager:shouldRemoveItemAtPath: allows the delegate the opportunity to not remove the item at path. If the delegate returns YES from this method, the FileManager instance will attempt to remove the item. If the delegate returns NO from this method, the remove skips the item. If the item is a directory, no children of that item will be visited.
*/
func fileManager(_ fileManager: FileManager, shouldRemoveItemAtPath path: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldRemoveItemAt URL: URL) -> Bool
/* fileManager:shouldProceedAfterError:removingItemAtPath: allows the delegate an opportunity to remedy the error which occurred in removing the item at the path provided. If the delegate returns YES from this method, the removal operation will continue. If the delegate returns NO from this method, the removal operation will stop and the error will be returned via linkItemAtPath:toPath:error:.
*/
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, removingItemAtPath path: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, removingItemAt URL: URL) -> Bool
}
extension FileManagerDelegate {
func fileManager(_ fileManager: FileManager, shouldCopyItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldCopyItemAt srcURL: URL, to dstURL: URL) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, copyingItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, copyingItemAt srcURL: URL, to dstURL: URL) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldMoveItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldMoveItemAt srcURL: URL, to dstURL: URL) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, movingItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, movingItemAt srcURL: URL, to dstURL: URL) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldLinkItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldLinkItemAt srcURL: URL, to dstURL: URL) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, linkingItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, linkingItemAt srcURL: URL, to dstURL: URL) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldRemoveItemAtPath path: String) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldRemoveItemAt URL: URL) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, removingItemAtPath path: String) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, removingItemAt URL: URL) -> Bool { return false }
}
extension FileManager {
open class DirectoryEnumerator : NSEnumerator {
/* For NSDirectoryEnumerators created with -enumeratorAtPath:, the -fileAttributes and -directoryAttributes methods return an NSDictionary containing the keys listed below. For NSDirectoryEnumerators created with -enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:, these two methods return nil.
*/
open var fileAttributes: [FileAttributeKey : Any]? {
NSRequiresConcreteImplementation()
}
open var directoryAttributes: [FileAttributeKey : Any]? {
NSRequiresConcreteImplementation()
}
/* This method returns the number of levels deep the current object is in the directory hierarchy being enumerated. The directory passed to -enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: is considered to be level 0.
*/
open var level: Int {
NSRequiresConcreteImplementation()
}
open func skipDescendants() {
NSRequiresConcreteImplementation()
}
}
internal class NSPathDirectoryEnumerator: DirectoryEnumerator {
let baseURL: URL
let innerEnumerator : DirectoryEnumerator
internal var _currentItemPath: String?
override var fileAttributes: [FileAttributeKey : Any]? {
guard let currentItemPath = _currentItemPath else {
return nil
}
return try? FileManager.default.attributesOfItem(atPath: baseURL.appendingPathComponent(currentItemPath).path)
}
override var directoryAttributes: [FileAttributeKey : Any]? {
return try? FileManager.default.attributesOfItem(atPath: baseURL.path)
}
override var level: Int {
return innerEnumerator.level
}
override func skipDescendants() {
innerEnumerator.skipDescendants()
}
init?(path: String) {
guard path != "" else { return nil }
let url = URL(fileURLWithPath: path)
self.baseURL = url
guard let ie = FileManager.default.enumerator(at: url, includingPropertiesForKeys: nil, options: [], errorHandler: nil) else {
return nil
}
self.innerEnumerator = ie
}
override func nextObject() -> Any? {
return _nextObject()
}
}
}
| apache-2.0 | bb6f9d286613ca69c8cef0e1378b45cf | 54.7132 | 771 | 0.698786 | 5.120985 | false | false | false | false |
frootloops/swift | validation-test/stdlib/Set.swift | 1 | 115344 | // RUN: %empty-directory(%t)
//
// RUN: %gyb %s -o %t/main.swift
// RUN: if [ %target-runtime == "objc" ]; then \
// RUN: %target-clang -fobjc-arc %S/Inputs/SlurpFastEnumeration/SlurpFastEnumeration.m -c -o %t/SlurpFastEnumeration.o; \
// RUN: %line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %S/Inputs/DictionaryKeyValueTypesObjC.swift %t/main.swift -I %S/Inputs/SlurpFastEnumeration/ -Xlinker %t/SlurpFastEnumeration.o -o %t/Set -Xfrontend -disable-access-control; \
// RUN: else \
// RUN: %line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %t/main.swift -o %t/Set -Xfrontend -disable-access-control; \
// RUN: fi
//
// RUN: %line-directive %t/main.swift -- %target-run %t/Set
// REQUIRES: executable_test
import StdlibUnittest
import StdlibCollectionUnittest
// For rand32
import SwiftPrivate
#if _runtime(_ObjC)
import Foundation
#else
// for random, srandom
import Glibc
#endif
extension Set {
func _rawIdentifier() -> Int {
return unsafeBitCast(self, to: Int.self)
}
}
// Check that the generic parameter is called 'Element'.
protocol TestProtocol1 {}
extension Set where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension SetIndex where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension SetIterator where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
let hugeNumberArray = Array(0..<500)
var SetTestSuite = TestSuite("Set")
SetTestSuite.setUp {
resetLeaksOfDictionaryKeysValues()
#if _runtime(_ObjC)
resetLeaksOfObjCDictionaryKeysValues()
#endif
}
SetTestSuite.tearDown {
expectNoLeaksOfDictionaryKeysValues()
#if _runtime(_ObjC)
expectNoLeaksOfObjCDictionaryKeysValues()
#endif
}
func getCOWFastSet(_ members: [Int] = [1010, 2020, 3030]) -> Set<Int> {
var s = Set<Int>(minimumCapacity: 10)
for member in members {
s.insert(member)
}
expectTrue(isNativeSet(s))
return s
}
func getCOWSlowSet(_ members: [Int] = [1010, 2020, 3030]) -> Set<TestKeyTy> {
var s = Set<TestKeyTy>(minimumCapacity: 10)
for member in members {
s.insert(TestKeyTy(member))
}
expectTrue(isNativeSet(s))
return s
}
func helperDeleteThree(_ k1: TestKeyTy, _ k2: TestKeyTy, _ k3: TestKeyTy) {
var s1 = Set<TestKeyTy>(minimumCapacity: 10)
s1.insert(k1)
s1.insert(k2)
s1.insert(k3)
expectTrue(s1.contains(k1))
expectTrue(s1.contains(k2))
expectTrue(s1.contains(k3))
s1.remove(k1)
expectTrue(s1.contains(k2))
expectTrue(s1.contains(k3))
s1.remove(k2)
expectTrue(s1.contains(k3))
s1.remove(k3)
expectEqual(0, s1.count)
}
func uniformRandom(_ max: Int) -> Int {
return Int(rand32(exclusiveUpperBound: UInt32(max)))
}
func pickRandom<T>(_ a: [T]) -> T {
return a[uniformRandom(a.count)]
}
func equalsUnordered(_ lhs: Set<Int>, _ rhs: Set<Int>) -> Bool {
return lhs.sorted().elementsEqual(rhs.sorted()) {
$0 == $1
}
}
func isNativeSet<T : Hashable>(_ s: Set<T>) -> Bool {
switch s._variantBuffer {
case .native:
return true
#if _runtime(_ObjC)
case .cocoa:
return false
#endif
}
}
#if _runtime(_ObjC)
func isNativeNSSet(_ s: NSSet) -> Bool {
let className: NSString = NSStringFromClass(type(of: s)) as NSString
return ["_SwiftDeferredNSSet", "NativeSetStorage"].contains {
className.range(of: $0).length > 0
}
}
func isCocoaNSSet(_ s: NSSet) -> Bool {
let className: NSString = NSStringFromClass(type(of: s)) as NSString
return className.range(of: "NSSet").length > 0 ||
className.range(of: "NSCFSet").length > 0
}
func getBridgedEmptyNSSet() -> NSSet {
let s = Set<TestObjCKeyTy>()
let bridged = unsafeBitCast(convertSetToNSSet(s), to: NSSet.self)
expectTrue(isNativeNSSet(bridged))
return bridged
}
func isCocoaSet<T : Hashable>(_ s: Set<T>) -> Bool {
return !isNativeSet(s)
}
/// Get an NSSet of TestObjCKeyTy values
func getAsNSSet(_ members: [Int] = [1010, 2020, 3030]) -> NSSet {
let nsArray = NSMutableArray()
for member in members {
nsArray.add(TestObjCKeyTy(member))
}
return NSMutableSet(array: nsArray as [AnyObject])
}
/// Get an NSMutableSet of TestObjCKeyTy values
func getAsNSMutableSet(_ members: [Int] = [1010, 2020, 3030]) -> NSMutableSet {
let nsArray = NSMutableArray()
for member in members {
nsArray.add(TestObjCKeyTy(member))
}
return NSMutableSet(array: nsArray as [AnyObject])
}
public func convertSetToNSSet<T>(_ s: Set<T>) -> NSSet {
return s._bridgeToObjectiveC()
}
public func convertNSSetToSet<T : Hashable>(_ s: NSSet?) -> Set<T> {
if _slowPath(s == nil) { return [] }
var result: Set<T>?
Set._forceBridgeFromObjectiveC(s!, result: &result)
return result!
}
/// Get a Set<NSObject> (Set<TestObjCKeyTy>) backed by Cocoa storage
func getBridgedVerbatimSet(_ members: [Int] = [1010, 2020, 3030])
-> Set<NSObject> {
let nss = getAsNSSet(members)
let result: Set<NSObject> = convertNSSetToSet(nss)
expectTrue(isCocoaSet(result))
return result
}
/// Get a Set<NSObject> (Set<TestObjCKeyTy>) backed by native storage
func getNativeBridgedVerbatimSet(_ members: [Int] = [1010, 2020, 3030]) ->
Set<NSObject> {
let result: Set<NSObject> = Set(members.map({ TestObjCKeyTy($0) }))
expectTrue(isNativeSet(result))
return result
}
/// Get a Set<NSObject> (Set<TestObjCKeyTy>) backed by Cocoa storage
func getHugeBridgedVerbatimSet() -> Set<NSObject> {
let nss = getAsNSSet(hugeNumberArray)
let result: Set<NSObject> = convertNSSetToSet(nss)
expectTrue(isCocoaSet(result))
return result
}
/// Get a Set<TestBridgedKeyTy> backed by native storage
func getBridgedNonverbatimSet(_ members: [Int] = [1010, 2020, 3030]) ->
Set<TestBridgedKeyTy> {
let nss = getAsNSSet(members)
let _ = unsafeBitCast(nss, to: Int.self)
let result: Set<TestBridgedKeyTy> =
Swift._forceBridgeFromObjectiveC(nss, Set.self)
expectTrue(isNativeSet(result))
return result
}
/// Get a larger Set<TestBridgedKeyTy> backed by native storage
func getHugeBridgedNonverbatimSet() -> Set<TestBridgedKeyTy> {
let nss = getAsNSSet(hugeNumberArray)
let _ = unsafeBitCast(nss, to: Int.self)
let result: Set<TestBridgedKeyTy> =
Swift._forceBridgeFromObjectiveC(nss, Set.self)
expectTrue(isNativeSet(result))
return result
}
func getBridgedVerbatimSetAndNSMutableSet() -> (Set<NSObject>, NSMutableSet) {
let nss = getAsNSMutableSet()
return (convertNSSetToSet(nss), nss)
}
func getBridgedNonverbatimSetAndNSMutableSet()
-> (Set<TestBridgedKeyTy>, NSMutableSet) {
let nss = getAsNSMutableSet()
return (Swift._forceBridgeFromObjectiveC(nss, Set.self), nss)
}
func getBridgedNSSetOfRefTypesBridgedVerbatim() -> NSSet {
expectTrue(_isBridgedVerbatimToObjectiveC(TestObjCKeyTy.self))
var s = Set<TestObjCKeyTy>(minimumCapacity: 32)
s.insert(TestObjCKeyTy(1010))
s.insert(TestObjCKeyTy(2020))
s.insert(TestObjCKeyTy(3030))
let bridged =
unsafeBitCast(convertSetToNSSet(s), to: NSSet.self)
expectTrue(isNativeNSSet(bridged))
return bridged
}
func getBridgedNSSet_ValueTypesCustomBridged(
numElements: Int = 3
) -> NSSet {
expectTrue(!_isBridgedVerbatimToObjectiveC(TestBridgedKeyTy.self))
var s = Set<TestBridgedKeyTy>()
for i in 1..<(numElements + 1) {
s.insert(TestBridgedKeyTy(i * 1000 + i * 10))
}
let bridged = convertSetToNSSet(s)
expectTrue(isNativeNSSet(bridged))
return bridged
}
func getRoundtripBridgedNSSet() -> NSSet {
let items = NSMutableArray()
items.add(TestObjCKeyTy(1010))
items.add(TestObjCKeyTy(2020))
items.add(TestObjCKeyTy(3030))
let nss = NSSet(array: items as [AnyObject])
let s: Set<NSObject> = convertNSSetToSet(nss)
let bridgedBack = convertSetToNSSet(s)
expectTrue(isCocoaNSSet(bridgedBack))
// FIXME: this should be true.
//expectTrue(unsafeBitCast(nsd, to: Int.self) == unsafeBitCast(bridgedBack, to: Int.self))
return bridgedBack
}
func getBridgedNSSet_MemberTypesCustomBridged() -> NSSet {
expectFalse(_isBridgedVerbatimToObjectiveC(TestBridgedKeyTy.self))
var s = Set<TestBridgedKeyTy>()
s.insert(TestBridgedKeyTy(1010))
s.insert(TestBridgedKeyTy(2020))
s.insert(TestBridgedKeyTy(3030))
let bridged = convertSetToNSSet(s)
expectTrue(isNativeNSSet(bridged))
return bridged
}
#endif // _runtime(_ObjC)
SetTestSuite.test("AssociatedTypes") {
typealias Collection = Set<MinimalHashableValue>
expectCollectionAssociatedTypes(
collectionType: Collection.self,
iteratorType: SetIterator<MinimalHashableValue>.self,
subSequenceType: Slice<Collection>.self,
indexType: SetIndex<MinimalHashableValue>.self,
indicesType: DefaultIndices<Collection>.self)
}
SetTestSuite.test("sizeof") {
var s = Set(["Hello", "world"])
#if arch(i386) || arch(arm)
expectEqual(4, MemoryLayout.size(ofValue: s))
#else
expectEqual(8, MemoryLayout.size(ofValue: s))
#endif
}
SetTestSuite.test("Index.Hashable") {
let s: Set = [1, 2, 3, 4, 5]
let t = Set(s.indices)
expectEqual(s.count, t.count)
expectTrue(t.contains(s.startIndex))
}
SetTestSuite.test("COW.Smoke") {
var s1 = Set<TestKeyTy>(minimumCapacity: 10)
for i in [1010, 2020, 3030]{ s1.insert(TestKeyTy(i)) }
var identity1 = s1._rawIdentifier()
var s2 = s1
_fixLifetime(s2)
expectEqual(identity1, s2._rawIdentifier())
s2.insert(TestKeyTy(4040))
expectNotEqual(identity1, s2._rawIdentifier())
s2.insert(TestKeyTy(5050))
expectEqual(identity1, s1._rawIdentifier())
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
SetTestSuite.test("COW.Fast.IndexesDontAffectUniquenessCheck") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
var startIndex = s.startIndex
var endIndex = s.endIndex
expectNotEqual(startIndex, endIndex)
expectTrue(startIndex < endIndex)
expectTrue(startIndex <= endIndex)
expectFalse(startIndex >= endIndex)
expectFalse(startIndex > endIndex)
expectEqual(identity1, s._rawIdentifier())
s.insert(4040)
expectEqual(identity1, s._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
SetTestSuite.test("COW.Slow.IndexesDontAffectUniquenessCheck") {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
var startIndex = s.startIndex
var endIndex = s.endIndex
expectNotEqual(startIndex, endIndex)
expectTrue(startIndex < endIndex)
expectTrue(startIndex <= endIndex)
expectFalse(startIndex >= endIndex)
expectFalse(startIndex > endIndex)
expectEqual(identity1, s._rawIdentifier())
s.insert(TestKeyTy(4040))
expectEqual(identity1, s._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
SetTestSuite.test("COW.Fast.SubscriptWithIndexDoesNotReallocate") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
var startIndex = s.startIndex
let empty = startIndex == s.endIndex
expectNotEqual(empty, (s.startIndex < s.endIndex))
expectTrue(s.startIndex <= s.endIndex)
expectEqual(empty, (s.startIndex >= s.endIndex))
expectFalse(s.startIndex > s.endIndex)
expectEqual(identity1, s._rawIdentifier())
expectNotEqual(0, s[startIndex])
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Slow.SubscriptWithIndexDoesNotReallocate") {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
var startIndex = s.startIndex
let empty = startIndex == s.endIndex
expectNotEqual(empty, (s.startIndex < s.endIndex))
expectTrue(s.startIndex <= s.endIndex)
expectEqual(empty, (s.startIndex >= s.endIndex))
expectFalse(s.startIndex > s.endIndex)
expectEqual(identity1, s._rawIdentifier())
expectNotEqual(TestKeyTy(0), s[startIndex])
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Fast.ContainsDoesNotReallocate") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
expectTrue(s.contains(1010))
expectEqual(identity1, s._rawIdentifier())
do {
var s2: Set<MinimalHashableValue> = []
MinimalHashableValue.timesEqualEqualWasCalled = 0
MinimalHashableValue.timesHashValueWasCalled = 0
expectFalse(s2.contains(MinimalHashableValue(42)))
// If the set is empty, we shouldn't be computing the hash value of the
// provided key.
expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableValue.timesHashValueWasCalled)
}
}
SetTestSuite.test("COW.Slow.ContainsDoesNotReallocate")
.code {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
expectTrue(s.contains(TestKeyTy(1010)))
expectEqual(identity1, s._rawIdentifier())
// Insert a new key-value pair.
s.insert(TestKeyTy(4040))
expectEqual(identity1, s._rawIdentifier())
expectEqual(4, s.count)
expectTrue(s.contains(TestKeyTy(1010)))
expectTrue(s.contains(TestKeyTy(2020)))
expectTrue(s.contains(TestKeyTy(3030)))
expectTrue(s.contains(TestKeyTy(4040)))
// Delete an existing key.
s.remove(TestKeyTy(1010))
expectEqual(identity1, s._rawIdentifier())
expectEqual(3, s.count)
expectTrue(s.contains(TestKeyTy(2020)))
expectTrue(s.contains(TestKeyTy(3030)))
expectTrue(s.contains(TestKeyTy(4040)))
// Try to delete a key that does not exist.
s.remove(TestKeyTy(777))
expectEqual(identity1, s._rawIdentifier())
expectEqual(3, s.count)
expectTrue(s.contains(TestKeyTy(2020)))
expectTrue(s.contains(TestKeyTy(3030)))
expectTrue(s.contains(TestKeyTy(4040)))
do {
var s2: Set<MinimalHashableClass> = []
MinimalHashableClass.timesEqualEqualWasCalled = 0
MinimalHashableClass.timesHashValueWasCalled = 0
expectFalse(s2.contains(MinimalHashableClass(42)))
// If the set is empty, we shouldn't be computing the hash value of the
// provided key.
expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableClass.timesHashValueWasCalled)
}
}
SetTestSuite.test("COW.Fast.InsertDoesNotReallocate") {
var s1 = getCOWFastSet()
let identity1 = s1._rawIdentifier()
let count1 = s1.count
// Inserting a redundant element should not create new storage
s1.insert(2020)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(count1, s1.count)
s1.insert(4040)
s1.insert(5050)
s1.insert(6060)
expectEqual(count1 + 3, s1.count)
expectEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("COW.Slow.InsertDoesNotReallocate") {
do {
var s1 = getCOWSlowSet()
let identity1 = s1._rawIdentifier()
let count1 = s1.count
// Inserting a redundant element should not create new storage
s1.insert(TestKeyTy(2020))
expectEqual(identity1, s1._rawIdentifier())
expectEqual(count1, s1.count)
s1.insert(TestKeyTy(4040))
s1.insert(TestKeyTy(5050))
s1.insert(TestKeyTy(6060))
expectEqual(count1 + 3, s1.count)
expectEqual(identity1, s1._rawIdentifier())
}
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
s2.insert(TestKeyTy(2040))
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s2._rawIdentifier())
expectEqual(3, s1.count)
expectTrue(s1.contains(TestKeyTy(1010)))
expectTrue(s1.contains(TestKeyTy(2020)))
expectTrue(s1.contains(TestKeyTy(3030)))
expectFalse(s1.contains(TestKeyTy(2040)))
expectEqual(4, s2.count)
expectTrue(s2.contains(TestKeyTy(1010)))
expectTrue(s2.contains(TestKeyTy(2020)))
expectTrue(s2.contains(TestKeyTy(3030)))
expectTrue(s2.contains(TestKeyTy(2040)))
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
// Replace a redundant element.
s2.update(with: TestKeyTy(2020))
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s2._rawIdentifier())
expectEqual(3, s1.count)
expectTrue(s1.contains(TestKeyTy(1010)))
expectTrue(s1.contains(TestKeyTy(2020)))
expectTrue(s1.contains(TestKeyTy(3030)))
expectEqual(3, s2.count)
expectTrue(s2.contains(TestKeyTy(1010)))
expectTrue(s2.contains(TestKeyTy(2020)))
expectTrue(s2.contains(TestKeyTy(3030)))
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
}
SetTestSuite.test("COW.Fast.IndexForMemberDoesNotReallocate") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
// Find an existing key.
do {
var foundIndex1 = s.index(of: 1010)!
expectEqual(identity1, s._rawIdentifier())
var foundIndex2 = s.index(of: 1010)!
expectEqual(foundIndex1, foundIndex2)
expectEqual(1010, s[foundIndex1])
expectEqual(identity1, s._rawIdentifier())
}
// Try to find a key that is not present.
do {
var foundIndex1 = s.index(of: 1111)
expectNil(foundIndex1)
expectEqual(identity1, s._rawIdentifier())
}
do {
var s2: Set<MinimalHashableValue> = []
MinimalHashableValue.timesEqualEqualWasCalled = 0
MinimalHashableValue.timesHashValueWasCalled = 0
expectNil(s2.index(of: MinimalHashableValue(42)))
// If the set is empty, we shouldn't be computing the hash value of the
// provided key.
expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableValue.timesHashValueWasCalled)
}
}
SetTestSuite.test("COW.Slow.IndexForMemberDoesNotReallocate") {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
// Find an existing key.
do {
var foundIndex1 = s.index(of: TestKeyTy(1010))!
expectEqual(identity1, s._rawIdentifier())
var foundIndex2 = s.index(of: TestKeyTy(1010))!
expectEqual(foundIndex1, foundIndex2)
expectEqual(TestKeyTy(1010), s[foundIndex1])
expectEqual(identity1, s._rawIdentifier())
}
// Try to find a key that is not present.
do {
var foundIndex1 = s.index(of: TestKeyTy(1111))
expectNil(foundIndex1)
expectEqual(identity1, s._rawIdentifier())
}
do {
var s2: Set<MinimalHashableClass> = []
MinimalHashableClass.timesEqualEqualWasCalled = 0
MinimalHashableClass.timesHashValueWasCalled = 0
expectNil(s2.index(of: MinimalHashableClass(42)))
// If the set is empty, we shouldn't be computing the hash value of the
// provided key.
expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableClass.timesHashValueWasCalled)
}
}
SetTestSuite.test("COW.Fast.RemoveAtDoesNotReallocate")
.code {
do {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
let foundIndex1 = s.index(of: 1010)!
expectEqual(identity1, s._rawIdentifier())
expectEqual(1010, s[foundIndex1])
let removed = s.remove(at: foundIndex1)
expectEqual(1010, removed)
expectEqual(identity1, s._rawIdentifier())
expectNil(s.index(of: 1010))
}
do {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
var foundIndex1 = s2.index(of: 1010)!
expectEqual(1010, s2[foundIndex1])
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
let removed = s2.remove(at: foundIndex1)
expectEqual(1010, removed)
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s2._rawIdentifier())
expectNil(s2.index(of: 1010))
}
}
SetTestSuite.test("COW.Slow.RemoveAtDoesNotReallocate")
.code {
do {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
let foundIndex1 = s.index(of: TestKeyTy(1010))!
expectEqual(identity1, s._rawIdentifier())
expectEqual(TestKeyTy(1010), s[foundIndex1])
let removed = s.remove(at: foundIndex1)
expectEqual(TestKeyTy(1010), removed)
expectEqual(identity1, s._rawIdentifier())
expectNil(s.index(of: TestKeyTy(1010)))
}
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
var foundIndex1 = s2.index(of: TestKeyTy(1010))!
expectEqual(TestKeyTy(1010), s2[foundIndex1])
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
let removed = s2.remove(at: foundIndex1)
expectEqual(TestKeyTy(1010), removed)
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s2._rawIdentifier())
expectNil(s2.index(of: TestKeyTy(1010)))
}
}
SetTestSuite.test("COW.Fast.RemoveDoesNotReallocate")
.code {
do {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
var deleted = s1.remove(0)
expectNil(deleted)
expectEqual(identity1, s1._rawIdentifier())
deleted = s1.remove(1010)
expectOptionalEqual(1010, deleted)
expectEqual(identity1, s1._rawIdentifier())
// Keep variables alive.
_fixLifetime(s1)
}
do {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
var deleted = s2.remove(0)
expectNil(deleted)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
deleted = s2.remove(1010)
expectOptionalEqual(1010, deleted)
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s2._rawIdentifier())
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
}
SetTestSuite.test("COW.Slow.RemoveDoesNotReallocate")
.code {
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
var deleted = s1.remove(TestKeyTy(0))
expectNil(deleted)
expectEqual(identity1, s1._rawIdentifier())
deleted = s1.remove(TestKeyTy(1010))
expectOptionalEqual(TestKeyTy(1010), deleted)
expectEqual(identity1, s1._rawIdentifier())
// Keep variables alive.
_fixLifetime(s1)
}
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
var deleted = s2.remove(TestKeyTy(0))
expectNil(deleted)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
deleted = s2.remove(TestKeyTy(1010))
expectOptionalEqual(TestKeyTy(1010), deleted)
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s2._rawIdentifier())
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
}
SetTestSuite.test("COW.Fast.UnionInPlaceSmallSetDoesNotReallocate") {
var s1 = getCOWFastSet()
let s2 = Set([4040, 5050, 6060])
let s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let identity1 = s1._rawIdentifier()
// Adding the empty set should obviously not allocate
s1.formUnion(Set<Int>())
expectEqual(identity1, s1._rawIdentifier())
// adding a small set shouldn't cause a reallocation
s1.formUnion(s2)
expectEqual(s1, s3)
expectEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("COW.Fast.RemoveAllDoesNotReallocate") {
do {
var s = getCOWFastSet()
let originalCapacity = s._variantBuffer.asNative.capacity
expectEqual(3, s.count)
expectTrue(s.contains(1010))
s.removeAll()
// We cannot expectTrue that identity changed, since the new buffer of
// smaller size can be allocated at the same address as the old one.
var identity1 = s._rawIdentifier()
expectTrue(s._variantBuffer.asNative.capacity < originalCapacity)
expectEqual(0, s.count)
expectFalse(s.contains(1010))
s.removeAll()
expectEqual(identity1, s._rawIdentifier())
expectEqual(0, s.count)
expectFalse(s.contains(1010))
}
do {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
let originalCapacity = s._variantBuffer.asNative.capacity
expectEqual(3, s.count)
expectTrue(s.contains(1010))
s.removeAll(keepingCapacity: true)
expectEqual(identity1, s._rawIdentifier())
expectEqual(originalCapacity, s._variantBuffer.asNative.capacity)
expectEqual(0, s.count)
expectFalse(s.contains(1010))
s.removeAll(keepingCapacity: true)
expectEqual(identity1, s._rawIdentifier())
expectEqual(originalCapacity, s._variantBuffer.asNative.capacity)
expectEqual(0, s.count)
expectFalse(s.contains(1010))
}
do {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
expectEqual(3, s1.count)
expectTrue(s1.contains(1010))
var s2 = s1
s2.removeAll()
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, identity2)
expectEqual(3, s1.count)
expectTrue(s1.contains(1010))
expectEqual(0, s2.count)
expectFalse(s2.contains(1010))
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
do {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
let originalCapacity = s1._variantBuffer.asNative.capacity
expectEqual(3, s1.count)
expectTrue(s1.contains(1010))
var s2 = s1
s2.removeAll(keepingCapacity: true)
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, identity2)
expectEqual(3, s1.count)
expectTrue(s1.contains(1010))
expectEqual(originalCapacity, s2._variantBuffer.asNative.capacity)
expectEqual(0, s2.count)
expectFalse(s2.contains(1010))
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
}
SetTestSuite.test("COW.Slow.RemoveAllDoesNotReallocate") {
do {
var s = getCOWSlowSet()
let originalCapacity = s._variantBuffer.asNative.capacity
expectEqual(3, s.count)
expectTrue(s.contains(TestKeyTy(1010)))
s.removeAll()
// We cannot expectTrue that identity changed, since the new buffer of
// smaller size can be allocated at the same address as the old one.
var identity1 = s._rawIdentifier()
expectTrue(s._variantBuffer.asNative.capacity < originalCapacity)
expectEqual(0, s.count)
expectFalse(s.contains(TestKeyTy(1010)))
s.removeAll()
expectEqual(identity1, s._rawIdentifier())
expectEqual(0, s.count)
expectFalse(s.contains(TestKeyTy(1010)))
}
do {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
let originalCapacity = s._variantBuffer.asNative.capacity
expectEqual(3, s.count)
expectTrue(s.contains(TestKeyTy(1010)))
s.removeAll(keepingCapacity: true)
expectEqual(identity1, s._rawIdentifier())
expectEqual(originalCapacity, s._variantBuffer.asNative.capacity)
expectEqual(0, s.count)
expectFalse(s.contains(TestKeyTy(1010)))
s.removeAll(keepingCapacity: true)
expectEqual(identity1, s._rawIdentifier())
expectEqual(originalCapacity, s._variantBuffer.asNative.capacity)
expectEqual(0, s.count)
expectFalse(s.contains(TestKeyTy(1010)))
}
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
expectEqual(3, s1.count)
expectTrue(s1.contains(TestKeyTy(1010)))
var s2 = s1
s2.removeAll()
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, identity2)
expectEqual(3, s1.count)
expectTrue(s1.contains(TestKeyTy(1010)))
expectEqual(0, s2.count)
expectFalse(s2.contains(TestKeyTy(1010)))
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
let originalCapacity = s1._variantBuffer.asNative.capacity
expectEqual(3, s1.count)
expectTrue(s1.contains(TestKeyTy(1010)))
var s2 = s1
s2.removeAll(keepingCapacity: true)
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, identity2)
expectEqual(3, s1.count)
expectTrue(s1.contains(TestKeyTy(1010)))
expectEqual(originalCapacity, s2._variantBuffer.asNative.capacity)
expectEqual(0, s2.count)
expectFalse(s2.contains(TestKeyTy(1010)))
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
}
SetTestSuite.test("COW.Fast.FirstDoesNotReallocate") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
expectNotNil(s.first)
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Fast.CountDoesNotReallocate") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
expectEqual(3, s.count)
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Slow.FirstDoesNotReallocate") {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
expectNotNil(s.first)
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Slow.CountDoesNotReallocate") {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
expectEqual(3, s.count)
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Fast.GenerateDoesNotReallocate") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
var iter = s.makeIterator()
var items: [Int] = []
while let value = iter.next() {
items += [value]
}
expectTrue(equalsUnordered(items, [ 1010, 2020, 3030 ]))
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Slow.GenerateDoesNotReallocate") {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
var iter = s.makeIterator()
var items: [Int] = []
while let value = iter.next() {
items.append(value.value)
}
expectTrue(equalsUnordered(items, [ 1010, 2020, 3030 ]))
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Fast.EqualityTestDoesNotReallocate") {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
var s2 = getCOWFastSet()
var identity2 = s2._rawIdentifier()
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
}
SetTestSuite.test("COW.Slow.EqualityTestDoesNotReallocate") {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
var s2 = getCOWFastSet()
var identity2 = s2._rawIdentifier()
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
}
//===---
// Native set tests.
//===---
SetTestSuite.test("deleteChainCollision") {
var k1 = TestKeyTy(value: 1010, hashValue: 0)
var k2 = TestKeyTy(value: 2020, hashValue: 0)
var k3 = TestKeyTy(value: 3030, hashValue: 0)
helperDeleteThree(k1, k2, k3)
}
SetTestSuite.test("deleteChainNoCollision") {
var k1 = TestKeyTy(value: 1010, hashValue: 0)
var k2 = TestKeyTy(value: 2020, hashValue: 1)
var k3 = TestKeyTy(value: 3030, hashValue: 2)
helperDeleteThree(k1, k2, k3)
}
SetTestSuite.test("deleteChainCollision2") {
var k1_0 = TestKeyTy(value: 1010, hashValue: 0)
var k2_0 = TestKeyTy(value: 2020, hashValue: 0)
var k3_2 = TestKeyTy(value: 3030, hashValue: 2)
var k4_0 = TestKeyTy(value: 4040, hashValue: 0)
var k5_2 = TestKeyTy(value: 5050, hashValue: 2)
var k6_0 = TestKeyTy(value: 6060, hashValue: 0)
var s = Set<TestKeyTy>(minimumCapacity: 10)
s.insert(k1_0) // in bucket 0
s.insert(k2_0) // in bucket 1
s.insert(k3_2) // in bucket 2
s.insert(k4_0) // in bucket 3
s.insert(k5_2) // in bucket 4
s.insert(k6_0) // in bucket 5
s.remove(k3_2)
expectTrue(s.contains(k1_0))
expectTrue(s.contains(k2_0))
expectFalse(s.contains(k3_2))
expectTrue(s.contains(k4_0))
expectTrue(s.contains(k5_2))
expectTrue(s.contains(k6_0))
}
SetTestSuite.test("deleteChainCollisionRandomized") {
let timeNow = CUnsignedInt(time(nil))
print("time is \(timeNow)")
srandom(timeNow)
func check(_ s: Set<TestKeyTy>) {
var keys = Array(s)
for i in 0..<keys.count {
for j in 0..<i {
expectNotEqual(keys[i], keys[j])
}
}
for k in keys {
expectTrue(s.contains(k))
}
}
var collisionChainsChoices = Array(1...8)
var chainOverlapChoices = Array(0...5)
var collisionChains = pickRandom(collisionChainsChoices)
var chainOverlap = pickRandom(chainOverlapChoices)
print("chose parameters: collisionChains=\(collisionChains) chainLength=\(chainOverlap)")
let chainLength = 7
var knownKeys: [TestKeyTy] = []
func getKey(_ value: Int) -> TestKeyTy {
for k in knownKeys {
if k.value == value {
return k
}
}
let hashValue = uniformRandom(chainLength - chainOverlap) * collisionChains
let k = TestKeyTy(value: value, hashValue: hashValue)
knownKeys += [k]
return k
}
var s = Set<TestKeyTy>(minimumCapacity: 30)
for i in 1..<300 {
let key = getKey(uniformRandom(collisionChains * chainLength))
if uniformRandom(chainLength * 2) == 0 {
s.remove(key)
} else {
s.insert(TestKeyTy(key.value))
}
check(s)
}
}
#if _runtime(_ObjC)
@objc
class CustomImmutableNSSet : NSSet {
init(_privateInit: ()) {
super.init()
}
override init() {
expectUnreachable()
super.init()
}
override init(objects: UnsafePointer<AnyObject>?, count: Int) {
expectUnreachable()
super.init(objects: objects, count: count)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) not implemented by CustomImmutableNSSet")
}
@objc(copyWithZone:)
override func copy(with zone: NSZone?) -> Any {
CustomImmutableNSSet.timesCopyWithZoneWasCalled += 1
return self
}
override func member(_ object: Any) -> Any? {
CustomImmutableNSSet.timesMemberWasCalled += 1
return getAsNSSet([ 1010, 1020, 1030 ]).member(object)
}
override func objectEnumerator() -> NSEnumerator {
CustomImmutableNSSet.timesObjectEnumeratorWasCalled += 1
return getAsNSSet([ 1010, 1020, 1030 ]).objectEnumerator()
}
override var count: Int {
CustomImmutableNSSet.timesCountWasCalled += 1
return 3
}
static var timesCopyWithZoneWasCalled = 0
static var timesMemberWasCalled = 0
static var timesObjectEnumeratorWasCalled = 0
static var timesCountWasCalled = 0
}
SetTestSuite.test("BridgedFromObjC.Verbatim.SetIsCopied") {
var (s, nss) = getBridgedVerbatimSetAndNSMutableSet()
expectTrue(isCocoaSet(s))
expectTrue(s.contains(TestObjCKeyTy(1010)))
expectNotNil(nss.member(TestObjCKeyTy(1010)))
nss.remove(TestObjCKeyTy(1010))
expectNil(nss.member(TestObjCKeyTy(1010)))
expectTrue(s.contains(TestObjCKeyTy(1010)))
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.SetIsCopied") {
var (s, nss) = getBridgedNonverbatimSetAndNSMutableSet()
expectTrue(isNativeSet(s))
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectNotNil(nss.member(TestBridgedKeyTy(1010) as AnyObject))
nss.remove(TestBridgedKeyTy(1010) as AnyObject)
expectNil(nss.member(TestBridgedKeyTy(1010) as AnyObject))
expectTrue(s.contains(TestBridgedKeyTy(1010)))
}
SetTestSuite.test("BridgedFromObjC.Verbatim.NSSetIsRetained") {
var nss: NSSet = NSSet(set: getAsNSSet([ 1010, 1020, 1030 ]))
var s: Set<NSObject> = convertNSSetToSet(nss)
var bridgedBack: NSSet = convertSetToNSSet(s)
expectEqual(
unsafeBitCast(nss, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nss)
_fixLifetime(s)
_fixLifetime(bridgedBack)
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.NSSetIsCopied") {
var nss: NSSet = NSSet(set: getAsNSSet([ 1010, 1020, 1030 ]))
var s: Set<TestBridgedKeyTy> = convertNSSetToSet(nss)
var bridgedBack: NSSet = convertSetToNSSet(s)
expectNotEqual(
unsafeBitCast(nss, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nss)
_fixLifetime(s)
_fixLifetime(bridgedBack)
}
SetTestSuite.test("BridgedFromObjC.Verbatim.ImmutableSetIsRetained") {
var nss: NSSet = CustomImmutableNSSet(_privateInit: ())
CustomImmutableNSSet.timesCopyWithZoneWasCalled = 0
CustomImmutableNSSet.timesMemberWasCalled = 0
CustomImmutableNSSet.timesObjectEnumeratorWasCalled = 0
CustomImmutableNSSet.timesCountWasCalled = 0
var s: Set<NSObject> = convertNSSetToSet(nss)
expectEqual(1, CustomImmutableNSSet.timesCopyWithZoneWasCalled)
expectEqual(0, CustomImmutableNSSet.timesMemberWasCalled)
expectEqual(0, CustomImmutableNSSet.timesObjectEnumeratorWasCalled)
expectEqual(0, CustomImmutableNSSet.timesCountWasCalled)
var bridgedBack: NSSet = convertSetToNSSet(s)
expectEqual(
unsafeBitCast(nss, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nss)
_fixLifetime(s)
_fixLifetime(bridgedBack)
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.ImmutableSetIsCopied") {
var nss: NSSet = CustomImmutableNSSet(_privateInit: ())
CustomImmutableNSSet.timesCopyWithZoneWasCalled = 0
CustomImmutableNSSet.timesMemberWasCalled = 0
CustomImmutableNSSet.timesObjectEnumeratorWasCalled = 0
CustomImmutableNSSet.timesCountWasCalled = 0
var s: Set<TestBridgedKeyTy> = convertNSSetToSet(nss)
expectEqual(0, CustomImmutableNSSet.timesCopyWithZoneWasCalled)
expectEqual(0, CustomImmutableNSSet.timesMemberWasCalled)
expectEqual(1, CustomImmutableNSSet.timesObjectEnumeratorWasCalled)
expectNotEqual(0, CustomImmutableNSSet.timesCountWasCalled)
var bridgedBack: NSSet = convertSetToNSSet(s)
expectNotEqual(
unsafeBitCast(nss, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nss)
_fixLifetime(s)
_fixLifetime(bridgedBack)
}
SetTestSuite.test("BridgedFromObjC.Verbatim.IndexForMember") {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
// Find an existing key.
var member = s[s.index(of: TestObjCKeyTy(1010))!]
expectEqual(TestObjCKeyTy(1010), member)
member = s[s.index(of: TestObjCKeyTy(2020))!]
expectEqual(TestObjCKeyTy(2020), member)
member = s[s.index(of: TestObjCKeyTy(3030))!]
expectEqual(TestObjCKeyTy(3030), member)
// Try to find a key that does not exist.
expectNil(s.index(of: TestObjCKeyTy(4040)))
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.IndexForMember") {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
do {
var member = s[s.index(of: TestBridgedKeyTy(1010))!]
expectEqual(TestBridgedKeyTy(1010), member)
member = s[s.index(of: TestBridgedKeyTy(2020))!]
expectEqual(TestBridgedKeyTy(2020), member)
member = s[s.index(of: TestBridgedKeyTy(3030))!]
expectEqual(TestBridgedKeyTy(3030), member)
}
expectNil(s.index(of: TestBridgedKeyTy(4040)))
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Insert") {
do {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
expectFalse(s.contains(TestObjCKeyTy(2040)))
s.insert(TestObjCKeyTy(2040))
var identity2 = s._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
expectTrue(s.contains(TestObjCKeyTy(1010)))
expectTrue(s.contains(TestObjCKeyTy(2020)))
expectTrue(s.contains(TestObjCKeyTy(3030)))
expectTrue(s.contains(TestObjCKeyTy(2040)))
}
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Insert") {
do {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectFalse(s.contains(TestBridgedKeyTy(2040)))
s.insert(TestObjCKeyTy(2040) as TestBridgedKeyTy)
var identity2 = s._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectTrue(s.contains(TestBridgedKeyTy(2040)))
}
}
SetTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex") {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
var startIndex = s.startIndex
var endIndex = s.endIndex
expectNotEqual(startIndex, endIndex)
expectTrue(startIndex < endIndex)
expectTrue(startIndex <= endIndex)
expectFalse(startIndex >= endIndex)
expectFalse(startIndex > endIndex)
expectEqual(identity1, s._rawIdentifier())
var members = [Int]()
for i in s.indices {
var foundMember: AnyObject = s[i]
let member = foundMember as! TestObjCKeyTy
members.append(member.value)
}
expectTrue(equalsUnordered(members, [1010, 2020, 3030]))
expectEqual(identity1, s._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex") {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
var startIndex = s.startIndex
var endIndex = s.endIndex
expectNotEqual(startIndex, endIndex)
expectTrue(startIndex < endIndex)
expectTrue(startIndex <= endIndex)
expectFalse(startIndex >= endIndex)
expectFalse(startIndex > endIndex)
expectEqual(identity1, s._rawIdentifier())
var members = [Int]()
for i in s.indices {
var foundMember: AnyObject = s[i] as NSObject
let member = foundMember as! TestObjCKeyTy
members.append(member.value)
}
expectTrue(equalsUnordered(members, [1010, 2020, 3030]))
expectEqual(identity1, s._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
SetTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex_Empty") {
var s = getBridgedVerbatimSet([])
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
var startIndex = s.startIndex
var endIndex = s.endIndex
expectEqual(startIndex, endIndex)
expectFalse(startIndex < endIndex)
expectTrue(startIndex <= endIndex)
expectTrue(startIndex >= endIndex)
expectFalse(startIndex > endIndex)
expectEqual(identity1, s._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex_Empty") {
var s = getBridgedNonverbatimSet([])
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
var startIndex = s.startIndex
var endIndex = s.endIndex
expectEqual(startIndex, endIndex)
expectFalse(startIndex < endIndex)
expectTrue(startIndex <= endIndex)
expectTrue(startIndex >= endIndex)
expectFalse(startIndex > endIndex)
expectEqual(identity1, s._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Contains") {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
expectTrue(s.contains(TestObjCKeyTy(1010)))
expectTrue(s.contains(TestObjCKeyTy(2020)))
expectTrue(s.contains(TestObjCKeyTy(3030)))
expectEqual(identity1, s._rawIdentifier())
// Inserting an item should now create storage unique from the bridged set.
s.insert(TestObjCKeyTy(4040))
var identity2 = s._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
// Verify items are still present.
expectTrue(s.contains(TestObjCKeyTy(1010)))
expectTrue(s.contains(TestObjCKeyTy(2020)))
expectTrue(s.contains(TestObjCKeyTy(3030)))
expectTrue(s.contains(TestObjCKeyTy(4040)))
// Insert a redundant item to the set.
// A copy should *not* occur here.
s.insert(TestObjCKeyTy(1010))
expectEqual(identity2, s._rawIdentifier())
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
// Again, verify items are still present.
expectTrue(s.contains(TestObjCKeyTy(1010)))
expectTrue(s.contains(TestObjCKeyTy(2020)))
expectTrue(s.contains(TestObjCKeyTy(3030)))
expectTrue(s.contains(TestObjCKeyTy(4040)))
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Contains") {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectEqual(identity1, s._rawIdentifier())
// Inserting an item should now create storage unique from the bridged set.
s.insert(TestBridgedKeyTy(4040))
var identity2 = s._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
// Verify items are still present.
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectTrue(s.contains(TestBridgedKeyTy(4040)))
// Insert a redundant item to the set.
// A copy should *not* occur here.
s.insert(TestBridgedKeyTy(1010))
expectEqual(identity2, s._rawIdentifier())
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
// Again, verify items are still present.
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectTrue(s.contains(TestBridgedKeyTy(4040)))
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithMember") {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectEqual(identity1, s._rawIdentifier())
// Insert a new member.
// This should trigger a copy.
s.insert(TestBridgedKeyTy(4040))
var identity2 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
// Verify all items in place.
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectTrue(s.contains(TestBridgedKeyTy(4040)))
// Insert a redundant member.
// This should *not* trigger a copy.
s.insert(TestBridgedKeyTy(1010))
expectEqual(identity2, s._rawIdentifier())
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
// Again, verify all items in place.
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectTrue(s.contains(TestBridgedKeyTy(4040)))
}
SetTestSuite.test("BridgedFromObjC.Verbatim.RemoveAt") {
var s = getBridgedVerbatimSet()
let identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
let foundIndex1 = s.index(of: TestObjCKeyTy(1010))!
expectEqual(TestObjCKeyTy(1010), s[foundIndex1])
expectEqual(identity1, s._rawIdentifier())
let removedElement = s.remove(at: foundIndex1)
expectNotEqual(identity1, s._rawIdentifier())
expectTrue(isNativeSet(s))
expectEqual(2, s.count)
expectEqual(TestObjCKeyTy(1010), removedElement)
expectNil(s.index(of: TestObjCKeyTy(1010)))
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAt")
.code {
var s = getBridgedNonverbatimSet()
let identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
let foundIndex1 = s.index(of: TestBridgedKeyTy(1010))!
expectEqual(1010, s[foundIndex1].value)
expectEqual(identity1, s._rawIdentifier())
let removedElement = s.remove(at: foundIndex1)
expectEqual(identity1, s._rawIdentifier())
expectTrue(isNativeSet(s))
expectEqual(1010, removedElement.value)
expectEqual(2, s.count)
expectNil(s.index(of: TestBridgedKeyTy(1010)))
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Remove") {
do {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
var deleted: AnyObject? = s.remove(TestObjCKeyTy(0))
expectNil(deleted)
expectEqual(identity1, s._rawIdentifier())
expectTrue(isCocoaSet(s))
deleted = s.remove(TestObjCKeyTy(1010))
expectEqual(1010, deleted!.value)
var identity2 = s._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isNativeSet(s))
expectEqual(2, s.count)
expectFalse(s.contains(TestObjCKeyTy(1010)))
expectTrue(s.contains(TestObjCKeyTy(2020)))
expectTrue(s.contains(TestObjCKeyTy(3030)))
expectEqual(identity2, s._rawIdentifier())
}
do {
var s1 = getBridgedVerbatimSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
expectTrue(isCocoaSet(s1))
expectTrue(isCocoaSet(s2))
var deleted: AnyObject? = s2.remove(TestObjCKeyTy(0))
expectNil(deleted)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
expectTrue(isCocoaSet(s1))
expectTrue(isCocoaSet(s2))
deleted = s2.remove(TestObjCKeyTy(1010))
expectEqual(1010, deleted!.value)
var identity2 = s2._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isCocoaSet(s1))
expectTrue(isNativeSet(s2))
expectEqual(2, s2.count)
expectTrue(s1.contains(TestObjCKeyTy(1010)))
expectTrue(s1.contains(TestObjCKeyTy(2020)))
expectTrue(s1.contains(TestObjCKeyTy(3030)))
expectEqual(identity1, s1._rawIdentifier())
expectFalse(s2.contains(TestObjCKeyTy(1010)))
expectTrue(s2.contains(TestObjCKeyTy(2020)))
expectTrue(s2.contains(TestObjCKeyTy(3030)))
expectEqual(identity2, s2._rawIdentifier())
}
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Remove")
.code {
do {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
// Trying to remove something not in the set should
// leave it completely unchanged.
var deleted = s.remove(TestBridgedKeyTy(0))
expectNil(deleted)
expectEqual(identity1, s._rawIdentifier())
expectTrue(isNativeSet(s))
// Now remove an item that is in the set. This should
// not create a new set altogether, however.
deleted = s.remove(TestBridgedKeyTy(1010))
expectEqual(1010, deleted!.value)
var identity2 = s._rawIdentifier()
expectEqual(identity1, identity2)
expectTrue(isNativeSet(s))
expectEqual(2, s.count)
// Double-check - the removed member should not be found.
expectFalse(s.contains(TestBridgedKeyTy(1010)))
// ... but others not removed should be found.
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
// Triple-check - we should still be working with the same object.
expectEqual(identity2, s._rawIdentifier())
}
do {
var s1 = getBridgedNonverbatimSet()
let identity1 = s1._rawIdentifier()
var s2 = s1
expectTrue(isNativeSet(s1))
expectTrue(isNativeSet(s2))
var deleted = s2.remove(TestBridgedKeyTy(0))
expectNil(deleted)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
expectTrue(isNativeSet(s1))
expectTrue(isNativeSet(s2))
deleted = s2.remove(TestBridgedKeyTy(1010))
expectEqual(1010, deleted!.value)
let identity2 = s2._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isNativeSet(s1))
expectTrue(isNativeSet(s2))
expectEqual(2, s2.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010)))
expectTrue(s1.contains(TestBridgedKeyTy(2020)))
expectTrue(s1.contains(TestBridgedKeyTy(3030)))
expectEqual(identity1, s1._rawIdentifier())
expectFalse(s2.contains(TestBridgedKeyTy(1010)))
expectTrue(s2.contains(TestBridgedKeyTy(2020)))
expectTrue(s2.contains(TestBridgedKeyTy(3030)))
expectEqual(identity2, s2._rawIdentifier())
}
}
SetTestSuite.test("BridgedFromObjC.Verbatim.RemoveAll") {
do {
var s = getBridgedVerbatimSet([])
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
expectEqual(0, s.count)
s.removeAll()
expectEqual(identity1, s._rawIdentifier())
expectEqual(0, s.count)
}
do {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
expectEqual(3, s.count)
expectTrue(s.contains(TestBridgedKeyTy(1010) as NSObject))
s.removeAll()
expectEqual(0, s.count)
expectFalse(s.contains(TestBridgedKeyTy(1010) as NSObject))
}
do {
var s1 = getBridgedVerbatimSet()
var identity1 = s1._rawIdentifier()
expectTrue(isCocoaSet(s1))
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010) as NSObject))
var s2 = s1
s2.removeAll()
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity2, identity1)
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010) as NSObject))
expectEqual(0, s2.count)
expectFalse(s2.contains(TestBridgedKeyTy(1010) as NSObject))
}
do {
var s1 = getBridgedVerbatimSet()
var identity1 = s1._rawIdentifier()
expectTrue(isCocoaSet(s1))
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010) as NSObject))
var s2 = s1
s2.removeAll(keepingCapacity: true)
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity2, identity1)
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010) as NSObject))
expectEqual(0 , s2.count)
expectFalse(s2.contains(TestBridgedKeyTy(1010) as NSObject))
}
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAll") {
do {
var s = getBridgedNonverbatimSet([])
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectEqual(0, s.count)
s.removeAll()
expectEqual(identity1, s._rawIdentifier())
expectEqual(0, s.count)
}
do {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectEqual(3, s.count)
expectTrue(s.contains(TestBridgedKeyTy(1010)))
s.removeAll()
expectEqual(0, s.count)
expectFalse(s.contains(TestBridgedKeyTy(1010)))
}
do {
var s1 = getBridgedNonverbatimSet()
var identity1 = s1._rawIdentifier()
expectTrue(isNativeSet(s1))
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010)))
var s2 = s1
s2.removeAll()
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity2, identity1)
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010)))
expectEqual(0, s2.count)
expectFalse(s2.contains(TestBridgedKeyTy(1010)))
}
do {
var s1 = getBridgedNonverbatimSet()
var identity1 = s1._rawIdentifier()
expectTrue(isNativeSet(s1))
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010)))
var s2 = s1
s2.removeAll(keepingCapacity: true)
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity2, identity1)
expectEqual(3, s1.count)
expectTrue(s1.contains(TestObjCKeyTy(1010) as TestBridgedKeyTy))
expectEqual(0, s2.count)
expectFalse(s2.contains(TestObjCKeyTy(1010) as TestBridgedKeyTy))
}
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Count") {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
expectEqual(3, s.count)
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Count") {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectEqual(3, s.count)
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Generate") {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
var iter = s.makeIterator()
var members: [Int] = []
while let member = iter.next() {
members.append((member as! TestObjCKeyTy).value)
}
expectTrue(equalsUnordered(members, [1010, 2020, 3030]))
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Generate") {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
var iter = s.makeIterator()
var members: [Int] = []
while let member = iter.next() {
members.append(member.value)
}
expectTrue(equalsUnordered(members, [1010, 2020, 3030]))
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Generate_Empty") {
var s = getBridgedVerbatimSet([])
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
var iter = s.makeIterator()
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Empty") {
var s = getBridgedNonverbatimSet([])
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
var iter = s.makeIterator()
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Generate_Huge") {
var s = getHugeBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
var iter = s.makeIterator()
var members = [Int]()
while let member = iter.next() {
members.append((member as! TestObjCKeyTy).value)
}
expectTrue(equalsUnordered(members, hugeNumberArray))
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Huge") {
var s = getHugeBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
var iter = s.makeIterator()
var members = [Int]()
while let member = iter.next() as AnyObject? {
members.append((member as! TestBridgedKeyTy).value)
}
expectTrue(equalsUnordered(members, hugeNumberArray))
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Empty") {
var s1 = getBridgedVerbatimSet([])
expectTrue(isCocoaSet(s1))
var s2 = getBridgedVerbatimSet([])
expectTrue(isCocoaSet(s2))
expectEqual(s1, s2)
s2.insert(TestObjCKeyTy(4040))
expectTrue(isNativeSet(s2))
expectNotEqual(s1, s2)
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.EqualityTest_Empty") {
var s1 = getBridgedNonverbatimSet([])
var identity1 = s1._rawIdentifier()
expectTrue(isNativeSet(s1))
var s2 = getBridgedNonverbatimSet([])
var identity2 = s2._rawIdentifier()
expectTrue(isNativeSet(s2))
expectNotEqual(identity1, identity2)
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
s2.insert(TestObjCKeyTy(4040) as TestBridgedKeyTy)
expectTrue(isNativeSet(s2))
expectEqual(identity2, s2._rawIdentifier())
expectNotEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Small") {
var s1 = getBridgedVerbatimSet()
let identity1 = s1._rawIdentifier()
expectTrue(isCocoaSet(s1))
var s2 = getBridgedVerbatimSet()
let identity2 = s2._rawIdentifier()
expectTrue(isCocoaSet(s2))
expectNotEqual(identity1, identity2)
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.EqualityTest_Small") {
var s1 = getBridgedNonverbatimSet()
let identity1 = s1._rawIdentifier()
expectTrue(isNativeSet(s1))
var s2 = getBridgedNonverbatimSet()
let identity2 = s2._rawIdentifier()
expectTrue(isNativeSet(s2))
expectNotEqual(identity1, identity2)
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.ArrayOfSets") {
var nsa = NSMutableArray()
for i in 0..<3 {
nsa.add(
getAsNSSet([1 + i, 2 + i, 3 + i]))
}
var a = nsa as [AnyObject] as! [Set<NSObject>]
for i in 0..<3 {
var s = a[i]
var iter = s.makeIterator()
var items: [Int] = []
while let value = iter.next() {
let v = (value as! TestObjCKeyTy).value
items.append(v)
}
var expectedItems = [1 + i, 2 + i, 3 + i]
expectTrue(equalsUnordered(items, expectedItems))
}
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.ArrayOfSets") {
var nsa = NSMutableArray()
for i in 0..<3 {
nsa.add(
getAsNSSet([1 + i, 2 + i, 3 + i]))
}
var a = nsa as [AnyObject] as! [Set<TestBridgedKeyTy>]
for i in 0..<3 {
var d = a[i]
var iter = d.makeIterator()
var items: [Int] = []
while let value = iter.next() {
items.append(value.value)
}
var expectedItems = [1 + i, 2 + i, 3 + i]
expectTrue(equalsUnordered(items, expectedItems))
}
}
//===---
// Dictionary -> NSDictionary bridging tests.
//
// Value is bridged verbatim.
//===---
SetTestSuite.test("BridgedToObjC.Verbatim.Count") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
expectEqual(3, s.count)
}
SetTestSuite.test("BridgedToObjC.Verbatim.Contains") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
var v: AnyObject? = s.member(TestObjCKeyTy(1010)).map { $0 as AnyObject }
expectEqual(1010, (v as! TestObjCKeyTy).value)
let idValue10 = unsafeBitCast(v, to: UInt.self)
v = s.member(TestObjCKeyTy(2020)).map { $0 as AnyObject }
expectEqual(2020, (v as! TestObjCKeyTy).value)
let idValue20 = unsafeBitCast(v, to: UInt.self)
v = s.member(TestObjCKeyTy(3030)).map { $0 as AnyObject }
expectEqual(3030, (v as! TestObjCKeyTy).value)
let idValue30 = unsafeBitCast(v, to: UInt.self)
expectNil(s.member(TestObjCKeyTy(4040)))
// NSSet can store mixed key types. Swift's Set is typed, but when bridged
// to NSSet, it should behave like one, and allow queries for mismatched key
// types.
expectNil(s.member(TestObjCInvalidKeyTy()))
for i in 0..<3 {
expectEqual(idValue10,
unsafeBitCast(s.member(TestObjCKeyTy(1010)).map { $0 as AnyObject }, to: UInt.self))
expectEqual(idValue20,
unsafeBitCast(s.member(TestObjCKeyTy(2020)).map { $0 as AnyObject }, to: UInt.self))
expectEqual(idValue30,
unsafeBitCast(s.member(TestObjCKeyTy(3030)).map { $0 as AnyObject }, to: UInt.self))
}
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("BridgingRoundtrip") {
let s = getRoundtripBridgedNSSet()
let enumerator = s.objectEnumerator()
var items: [Int] = []
while let value = enumerator.nextObject() {
let v = (value as! TestObjCKeyTy).value
items.append(v)
}
expectTrue(equalsUnordered([1010, 2020, 3030], items))
}
SetTestSuite.test("BridgedToObjC.Verbatim.ObjectEnumerator.FastEnumeration.UseFromSwift") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
checkSetFastEnumerationFromSwift(
[ 1010, 2020, 3030 ],
s, { s.objectEnumerator() },
{ ($0 as! TestObjCKeyTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("BridgedToObjC.Verbatim.ObjectEnumerator.FastEnumeration.UseFromObjC") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
checkSetFastEnumerationFromObjC(
[ 1010, 2020, 3030 ],
s, { s.objectEnumerator() },
{ ($0 as! TestObjCKeyTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("BridgedToObjC.Verbatim.ObjectEnumerator.FastEnumeration_Empty") {
let s = getBridgedEmptyNSSet()
checkSetFastEnumerationFromSwift(
[], s, { s.objectEnumerator() },
{ ($0 as! TestObjCKeyTy).value })
checkSetFastEnumerationFromObjC(
[], s, { s.objectEnumerator() },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Custom.ObjectEnumerator.FastEnumeration.UseFromObjC") {
let s = getBridgedNSSet_MemberTypesCustomBridged()
checkSetFastEnumerationFromObjC(
[ 1010, 2020, 3030 ],
s, { s.objectEnumerator() },
{ ($0 as! TestObjCKeyTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("BridgedToObjC.Custom.ObjectEnumerator.FastEnumeration.UseFromSwift") {
let s = getBridgedNSSet_MemberTypesCustomBridged()
checkSetFastEnumerationFromSwift(
[ 1010, 2020, 3030 ],
s, { s.objectEnumerator() },
{ ($0 as! TestObjCKeyTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromSwift") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
checkSetFastEnumerationFromSwift(
[ 1010, 2020, 3030 ],
s, { s },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromObjC") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
checkSetFastEnumerationFromObjC(
[ 1010, 2020, 3030 ],
s, { s },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration_Empty") {
let s = getBridgedEmptyNSSet()
checkSetFastEnumerationFromSwift(
[], s, { s },
{ ($0 as! TestObjCKeyTy).value })
checkSetFastEnumerationFromObjC(
[], s, { s },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromSwift") {
let s = getBridgedNSSet_ValueTypesCustomBridged()
checkSetFastEnumerationFromSwift(
[ 1010, 2020, 3030 ],
s, { s },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromObjC") {
let s = getBridgedNSSet_ValueTypesCustomBridged()
checkSetFastEnumerationFromObjC(
[ 1010, 2020, 3030 ],
s, { s },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Custom.FastEnumeration_Empty") {
let s = getBridgedNSSet_ValueTypesCustomBridged(
numElements: 0)
checkSetFastEnumerationFromSwift(
[], s, { s },
{ ($0 as! TestObjCKeyTy).value })
checkSetFastEnumerationFromObjC(
[], s, { s },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Count") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
expectEqual(3, s.count)
}
SetTestSuite.test("BridgedToObjC.ObjectEnumerator.NextObject") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
let enumerator = s.objectEnumerator()
var members = [Int]()
while let nextObject = enumerator.nextObject() {
members.append((nextObject as! TestObjCKeyTy).value)
}
expectTrue(equalsUnordered([1010, 2020, 3030], members))
expectNil(enumerator.nextObject())
expectNil(enumerator.nextObject())
expectNil(enumerator.nextObject())
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("BridgedToObjC.ObjectEnumerator.NextObject.Empty") {
let s = getBridgedEmptyNSSet()
let enumerator = s.objectEnumerator()
expectNil(enumerator.nextObject())
expectNil(enumerator.nextObject())
expectNil(enumerator.nextObject())
}
//
// Set -> NSSet Bridging
//
SetTestSuite.test("BridgedToObjC.MemberTypesCustomBridged") {
let s = getBridgedNSSet_MemberTypesCustomBridged()
let enumerator = s.objectEnumerator()
var members = [Int]()
while let nextObject = enumerator.nextObject() {
members.append((nextObject as! TestObjCKeyTy).value)
}
expectTrue(equalsUnordered([1010, 2020, 3030], members))
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
//
// NSSet -> Set -> NSSet Round trip bridging
//
SetTestSuite.test("BridgingRoundTrip") {
let s = getRoundtripBridgedNSSet()
let enumerator = s.objectEnumerator()
var members = [Int]()
while let nextObject = enumerator.nextObject() {
members.append((nextObject as! TestObjCKeyTy).value)
}
expectTrue(equalsUnordered([1010, 2020, 3030] ,members))
}
//
// NSSet -> Set implicit conversion
//
SetTestSuite.test("NSSetToSetConversion") {
let nsArray = NSMutableArray()
for i in [1010, 2020, 3030] {
nsArray.add(TestObjCKeyTy(i))
}
let nss = NSSet(array: nsArray as [AnyObject])
let s = nss as Set
var members = [Int]()
for member: AnyObject in s {
members.append((member as! TestObjCKeyTy).value)
}
expectTrue(equalsUnordered(members, [1010, 2020, 3030]))
}
SetTestSuite.test("SetToNSSetConversion") {
var s = Set<TestObjCKeyTy>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
let nss: NSSet = s as NSSet
expectTrue(equalsUnordered(Array(s).map { $0.value }, [1010, 2020, 3030]))
}
//
// Set Casts
//
SetTestSuite.test("SetUpcastEntryPoint") {
var s = Set<TestObjCKeyTy>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
var sAsAnyObject: Set<NSObject> = _setUpCast(s)
expectEqual(3, sAsAnyObject.count)
expectTrue(sAsAnyObject.contains(TestObjCKeyTy(1010)))
expectTrue(sAsAnyObject.contains(TestObjCKeyTy(2020)))
expectTrue(sAsAnyObject.contains(TestObjCKeyTy(3030)))
}
SetTestSuite.test("SetUpcast") {
var s = Set<TestObjCKeyTy>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
var sAsAnyObject: Set<NSObject> = s
expectEqual(3, sAsAnyObject.count)
expectTrue(sAsAnyObject.contains(TestObjCKeyTy(1010)))
expectTrue(sAsAnyObject.contains(TestObjCKeyTy(2020)))
expectTrue(sAsAnyObject.contains(TestObjCKeyTy(3030)))
}
SetTestSuite.test("SetUpcastBridgedEntryPoint") {
var s = Set<TestBridgedKeyTy>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestBridgedKeyTy(i))
}
do {
var s: Set<NSObject> = _setBridgeToObjectiveC(s)
expectTrue(s.contains(TestBridgedKeyTy(1010) as NSObject))
expectTrue(s.contains(TestBridgedKeyTy(2020) as NSObject))
expectTrue(s.contains(TestBridgedKeyTy(3030) as NSObject))
}
do {
var s: Set<TestObjCKeyTy> = _setBridgeToObjectiveC(s)
expectEqual(3, s.count)
expectTrue(s.contains(TestBridgedKeyTy(1010) as TestObjCKeyTy))
expectTrue(s.contains(TestBridgedKeyTy(2020) as TestObjCKeyTy))
expectTrue(s.contains(TestBridgedKeyTy(3030) as TestObjCKeyTy))
}
}
SetTestSuite.test("SetUpcastBridged") {
var s = Set<TestBridgedKeyTy>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestBridgedKeyTy(i))
}
do {
var s = s as! Set<NSObject>
expectEqual(3, s.count)
expectTrue(s.contains(TestBridgedKeyTy(1010) as NSObject))
expectTrue(s.contains(TestBridgedKeyTy(2020) as NSObject))
expectTrue(s.contains(TestBridgedKeyTy(3030) as NSObject))
}
do {
var s = s as Set<TestObjCKeyTy>
expectEqual(3, s.count)
expectTrue(s.contains(TestBridgedKeyTy(1010) as TestObjCKeyTy))
expectTrue(s.contains(TestBridgedKeyTy(2020) as TestObjCKeyTy))
expectTrue(s.contains(TestBridgedKeyTy(3030) as TestObjCKeyTy))
}
}
//
// Set downcasts
//
SetTestSuite.test("SetDowncastEntryPoint") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
let sCC: Set<TestObjCKeyTy> = _setDownCast(s)
expectEqual(3, sCC.count)
expectTrue(sCC.contains(TestObjCKeyTy(1010)))
expectTrue(sCC.contains(TestObjCKeyTy(2020)))
expectTrue(sCC.contains(TestObjCKeyTy(3030)))
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("SetDowncast") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
let sCC = s as! Set<TestObjCKeyTy>
expectEqual(3, sCC.count)
expectTrue(sCC.contains(TestObjCKeyTy(1010)))
expectTrue(sCC.contains(TestObjCKeyTy(2020)))
expectTrue(sCC.contains(TestObjCKeyTy(3030)))
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("SetDowncastConditionalEntryPoint") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
if let sCC = _setDownCastConditional(s) as Set<TestObjCKeyTy>? {
expectEqual(3, sCC.count)
expectTrue(sCC.contains(TestObjCKeyTy(1010)))
expectTrue(sCC.contains(TestObjCKeyTy(2020)))
expectTrue(sCC.contains(TestObjCKeyTy(3030)))
} else {
expectTrue(false)
}
// Unsuccessful downcast
s.insert("Hello, world" as NSString)
if let sCC = _setDownCastConditional(s) as Set<TestObjCKeyTy>? {
expectTrue(false)
}
}
SetTestSuite.test("SetDowncastConditional") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
if let sCC = s as? Set<TestObjCKeyTy> {
expectEqual(3, sCC.count)
expectTrue(sCC.contains(TestObjCKeyTy(1010)))
expectTrue(sCC.contains(TestObjCKeyTy(2020)))
expectTrue(sCC.contains(TestObjCKeyTy(3030)))
} else {
expectTrue(false)
}
// Unsuccessful downcast
s.insert("Hello, world, I'm your wild girl. I'm your ch-ch-ch-ch-ch-ch cherry bomb" as NSString)
if let sCC = s as? Set<TestObjCKeyTy> {
expectTrue(false)
}
}
SetTestSuite.test("SetBridgeFromObjectiveCEntryPoint") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
let sCV: Set<TestBridgedKeyTy> = _setBridgeFromObjectiveC(s)
do {
expectEqual(3, sCV.count)
expectTrue(sCV.contains(TestBridgedKeyTy(1010)))
expectTrue(sCV.contains(TestBridgedKeyTy(2020)))
expectTrue(sCV.contains(TestBridgedKeyTy(3030)))
}
}
SetTestSuite.test("SetBridgeFromObjectiveC") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
let sCV = s as! Set<TestObjCKeyTy>
do {
expectEqual(3, sCV.count)
expectTrue(sCV.contains(TestObjCKeyTy(1010)))
expectTrue(sCV.contains(TestObjCKeyTy(2020)))
expectTrue(sCV.contains(TestObjCKeyTy(3030)))
}
// Successful downcast.
let sVC = s as! Set<TestBridgedKeyTy>
do {
expectEqual(3, sVC.count)
expectTrue(sVC.contains(TestBridgedKeyTy(1010)))
expectTrue(sVC.contains(TestBridgedKeyTy(2020)))
expectTrue(sVC.contains(TestBridgedKeyTy(3030)))
}
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("SetBridgeFromObjectiveCConditionalEntryPoint") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
if let sVC = _setBridgeFromObjectiveCConditional(s) as Set<TestBridgedKeyTy>? {
expectEqual(3, sVC.count)
expectTrue(sVC.contains(TestBridgedKeyTy(1010)))
expectTrue(sVC.contains(TestBridgedKeyTy(2020)))
expectTrue(sVC.contains(TestBridgedKeyTy(3030)))
} else {
expectTrue(false)
}
// Unsuccessful downcasts
s.insert("Hello, world, I'm your wild girl. I'm your ch-ch-ch-ch-ch-ch cherry bomb" as NSString)
if let sVC = _setBridgeFromObjectiveCConditional(s) as Set<TestBridgedKeyTy>? {
expectTrue(false)
}
}
SetTestSuite.test("SetBridgeFromObjectiveCConditional") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
if let sCV = s as? Set<TestObjCKeyTy> {
expectEqual(3, sCV.count)
expectTrue(sCV.contains(TestObjCKeyTy(1010)))
expectTrue(sCV.contains(TestObjCKeyTy(2020)))
expectTrue(sCV.contains(TestObjCKeyTy(3030)))
} else {
expectTrue(false)
}
// Successful downcast.
if let sVC = s as? Set<TestBridgedKeyTy> {
expectEqual(3, sVC.count)
expectTrue(sVC.contains(TestBridgedKeyTy(1010)))
expectTrue(sVC.contains(TestBridgedKeyTy(2020)))
expectTrue(sVC.contains(TestBridgedKeyTy(3030)))
} else {
expectTrue(false)
}
// Unsuccessful downcasts
s.insert("Hello, world, I'm your wild girl. I'm your ch-ch-ch-ch-ch-ch cherry bomb" as NSString)
if let sCm = s as? Set<TestObjCKeyTy> {
expectTrue(false)
}
if let sVC = s as? Set<TestBridgedKeyTy> {
expectTrue(false)
}
if let sVm = s as? Set<TestBridgedKeyTy> {
expectTrue(false)
}
}
#endif // _runtime(_ObjC)
// Public API
SetTestSuite.test("init(Sequence:)") {
let s1 = Set([1010, 2020, 3030])
var s2 = Set<Int>()
s2.insert(1010)
s2.insert(2020)
s2.insert(3030)
expectEqual(s1, s2)
// Test the uniquing capabilities of a set
let s3 = Set([
1010, 1010, 1010, 1010, 1010, 1010,
1010, 1010, 1010, 1010, 1010, 1010,
2020, 2020, 2020, 3030, 3030, 3030
])
expectEqual(s1, s3)
}
SetTestSuite.test("init(arrayLiteral:)") {
let s1: Set<Int> = [1010, 2020, 3030, 1010, 2020, 3030]
let s2 = Set([1010, 2020, 3030])
var s3 = Set<Int>()
s3.insert(1010)
s3.insert(2020)
s3.insert(3030)
expectEqual(s1, s2)
expectEqual(s2, s3)
}
SetTestSuite.test("isSubsetOf.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectTrue(Set<Int>().isSubset(of: s1))
expectFalse(s1.isSubset(of: Set<Int>()))
expectTrue(s1.isSubset(of: s1))
expectTrue(s2.isSubset(of: s1))
}
SetTestSuite.test("isSubsetOf.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectTrue(Set<Int>().isSubset(of: s1))
expectFalse(s1.isSubset(of: Set<Int>()))
expectTrue(s1.isSubset(of: s1))
}
SetTestSuite.test("isStrictSubsetOf.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectTrue(Set<Int>().isStrictSubset(of: s1))
expectFalse(s1.isStrictSubset(of: Set<Int>()))
expectFalse(s1.isStrictSubset(of: s1))
}
SetTestSuite.test("isStrictSubsetOf.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectTrue(Set<Int>().isStrictSubset(of: s1))
expectFalse(s1.isStrictSubset(of: Set<Int>()))
expectFalse(s1.isStrictSubset(of: s1))
}
SetTestSuite.test("isSupersetOf.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectTrue(s1.isSuperset(of: Set<Int>()))
expectFalse(Set<Int>().isSuperset(of: s1))
expectTrue(s1.isSuperset(of: s1))
expectTrue(s1.isSuperset(of: s2))
expectFalse(Set<Int>().isSuperset(of: s1))
}
SetTestSuite.test("isSupersetOf.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectTrue(s1.isSuperset(of: Set<Int>()))
expectFalse(Set<Int>().isSuperset(of: s1))
expectTrue(s1.isSuperset(of: s1))
expectTrue(s1.isSuperset(of: s2))
expectFalse(Set<Int>().isSuperset(of: s1))
}
SetTestSuite.test("strictSuperset.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectTrue(s1.isStrictSuperset(of: Set<Int>()))
expectFalse(Set<Int>().isStrictSuperset(of: s1))
expectFalse(s1.isStrictSuperset(of: s1))
expectTrue(s1.isStrictSuperset(of: s2))
}
SetTestSuite.test("strictSuperset.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectTrue(s1.isStrictSuperset(of: Set<Int>()))
expectFalse(Set<Int>().isStrictSuperset(of: s1))
expectFalse(s1.isStrictSuperset(of: s1))
expectTrue(s1.isStrictSuperset(of: s2))
}
SetTestSuite.test("Equatable.Native.Native") {
let s1 = getCOWFastSet()
let s2 = getCOWFastSet([1010, 2020, 3030, 4040, 5050, 6060])
checkEquatable(true, s1, s1)
checkEquatable(false, s1, Set<Int>())
checkEquatable(true, Set<Int>(), Set<Int>())
checkEquatable(false, s1, s2)
}
#if _runtime(_ObjC)
SetTestSuite.test("Equatable.Native.BridgedVerbatim") {
let s1 = getNativeBridgedVerbatimSet()
let bvs1 = getBridgedVerbatimSet()
let bvs2 = getBridgedVerbatimSet([1010, 2020, 3030, 4040, 5050, 6060])
let bvsEmpty = getBridgedVerbatimSet([])
checkEquatable(true, s1, bvs1)
checkEquatable(false, s1, bvs2)
checkEquatable(false, s1, bvsEmpty)
}
SetTestSuite.test("Equatable.BridgedVerbatim.BridgedVerbatim") {
let bvs1 = getBridgedVerbatimSet()
let bvs2 = getBridgedVerbatimSet([1010, 2020, 3030, 4040, 5050, 6060])
let bvsEmpty = getBridgedVerbatimSet([])
checkEquatable(true, bvs1, bvs1)
checkEquatable(false, bvs1, bvs2)
checkEquatable(false, bvs1, bvsEmpty)
}
SetTestSuite.test("Equatable.BridgedNonverbatim.BridgedNonverbatim") {
let bnvs1 = getBridgedNonverbatimSet()
let bnvs2 = getBridgedNonverbatimSet([1010, 2020, 3030, 4040, 5050, 6060])
let bnvsEmpty = getBridgedNonverbatimSet([])
checkEquatable(true, bnvs1, bnvs1)
checkEquatable(false, bnvs1, bnvs2)
checkEquatable(false, bnvs1, bnvsEmpty)
checkEquatable(false, bnvs2, bnvsEmpty)
}
#endif // _runtime(_ObjC)
SetTestSuite.test("isDisjointWith.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
let s3 = Set([7070, 8080, 9090])
expectTrue(s1.isDisjoint(with: s3))
expectFalse(s1.isDisjoint(with: s2))
expectTrue(Set<Int>().isDisjoint(with: s1))
expectTrue(Set<Int>().isDisjoint(with: Set<Int>()))
}
SetTestSuite.test("isDisjointWith.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
let s3 = AnySequence([7070, 8080, 9090])
expectTrue(s1.isDisjoint(with: s3))
expectFalse(s1.isDisjoint(with: s2))
expectTrue(Set<Int>().isDisjoint(with: s1))
expectTrue(Set<Int>().isDisjoint(with: Set<Int>()))
}
SetTestSuite.test("insert") {
// These are anagrams - they should amount to the same sets.
var s1 = Set<TestKeyTy>([1010, 2020, 3030])
let fortyForty: TestKeyTy = 4040
do {
// Inserting an element that isn't present
let (inserted, currentMember) = s1.insert(fortyForty)
expectTrue(inserted)
expectTrue(currentMember === fortyForty)
}
do {
// Inserting an element that is already present
let (inserted, currentMember) = s1.insert(4040)
expectFalse(inserted)
expectTrue(currentMember === fortyForty)
}
expectEqual(4, s1.count)
expectTrue(s1.contains(1010))
expectTrue(s1.contains(2020))
expectTrue(s1.contains(3030))
expectTrue(s1.contains(4040))
}
SetTestSuite.test("replace") {
// These are anagrams - they should amount to the same sets.
var s1 = Set<TestKeyTy>([1010, 2020, 3030])
let fortyForty: TestKeyTy = 4040
do {
// Replacing an element that isn't present
let oldMember = s1.update(with: fortyForty)
expectNil(oldMember)
}
do {
// Replacing an element that is already present
let oldMember = s1.update(with: 4040)
expectTrue(oldMember === fortyForty)
}
expectEqual(4, s1.count)
expectTrue(s1.contains(1010))
expectTrue(s1.contains(2020))
expectTrue(s1.contains(3030))
expectTrue(s1.contains(4040))
}
SetTestSuite.test("union") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
let s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let identity1 = s1._rawIdentifier()
let s4 = s1.union(s2)
expectEqual(s4, s3)
// s1 should be unchanged
expectEqual(identity1, s1._rawIdentifier())
expectEqual(Set([1010, 2020, 3030]), s1)
// s4 should be a fresh set
expectNotEqual(identity1, s4._rawIdentifier())
expectEqual(s4, s3)
let s5 = s1.union(s1)
expectEqual(s5, s1)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, s1.union(Set<Int>()))
expectEqual(s1, Set<Int>().union(s1))
}
SetTestSuite.test("formUnion") {
// These are anagrams - they should amount to the same sets.
var s1 = Set("the morse code".characters)
let s2 = Set("here come dots".characters)
let s3 = Set("and then dashes".characters)
let identity1 = s1._rawIdentifier()
s1.formUnion("".characters)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, s2)
s1.formUnion(s2)
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
s1.formUnion(s3)
expectNotEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("subtract")
.code {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
let s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let identity1 = s1._rawIdentifier()
// Subtracting a disjoint set should not create a
// unique reference
let s4 = s1.subtracting(s2)
expectEqual(s1, s4)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s4._rawIdentifier())
// Subtracting a superset will leave the set empty
let s5 = s1.subtracting(s3)
expectTrue(s5.isEmpty)
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s5._rawIdentifier())
// Subtracting the empty set does nothing
expectEqual(s1, s1.subtracting(Set<Int>()))
expectEqual(Set<Int>(), Set<Int>().subtracting(s1))
expectEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("subtract")
.code {
var s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
let s3 = Set([4040, 5050, 6060])
let identity1 = s1._rawIdentifier()
s1.subtract(Set<Int>())
expectEqual(identity1, s1._rawIdentifier())
s1.subtract(s3)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("intersect") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
var s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
var s4 = Set([1010, 2020, 3030])
let identity1 = s1._rawIdentifier()
expectEqual(Set([1010, 2020, 3030]),
Set([1010, 2020, 3030]).intersection(Set([1010, 2020, 3030])) as Set<Int>)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, s1.intersection(s3))
expectEqual(identity1, s1._rawIdentifier())
expectEqual(Set<Int>(), Set<Int>().intersection(Set<Int>()))
expectEqual(Set<Int>(), s1.intersection(Set<Int>()))
expectEqual(Set<Int>(), Set<Int>().intersection(s1))
}
SetTestSuite.test("formIntersection") {
var s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
var s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
var s4 = Set([1010, 2020, 3030])
let identity1 = s1._rawIdentifier()
s1.formIntersection(s4)
expectEqual(s1, s4)
expectEqual(identity1, s1._rawIdentifier())
s4.formIntersection(s2)
expectEqual(Set<Int>(), s4)
let identity2 = s3._rawIdentifier()
s3.formIntersection(s2)
expectEqual(s3, s2)
expectTrue(s1.isDisjoint(with: s3))
expectNotEqual(identity1, s3._rawIdentifier())
var s5 = Set<Int>()
s5.formIntersection(s5)
expectEqual(s5, Set<Int>())
s5.formIntersection(s1)
expectEqual(s5, Set<Int>())
}
SetTestSuite.test("symmetricDifference") {
// Overlap with 4040, 5050, 6060
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([4040, 5050, 6060, 7070, 8080, 9090])
let result = Set([1010, 2020, 3030, 7070, 8080, 9090])
let universe = Set([1010, 2020, 3030, 4040, 5050, 6060,
7070, 8080, 9090])
let identity1 = s1._rawIdentifier()
let s3 = s1.symmetricDifference(s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s3, result)
expectEqual(s1.symmetricDifference(s2),
s1.union(s2).intersection(universe.subtracting(s1.intersection(s2))))
expectEqual(s1.symmetricDifference(s2),
s1.intersection(universe.subtracting(s2)).union(universe.subtracting(s1).intersection(s2)))
expectTrue(s1.symmetricDifference(s1).isEmpty)
}
SetTestSuite.test("formSymmetricDifference")
.code {
// Overlap with 4040, 5050, 6060
var s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010])
let result = Set([2020, 3030, 4040, 5050, 6060])
// s1 ⨁ s2 == result
let identity1 = s1._rawIdentifier()
s1.formSymmetricDifference(s2)
// Removing just one element shouldn't cause an identity change
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, result)
// A ⨁ A == {}
s1.formSymmetricDifference(s1)
expectTrue(s1.isEmpty)
// Removing all elements should cause an identity change
expectNotEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("removeFirst") {
var s1 = Set([1010, 2020, 3030])
let s2 = s1
let empty = Set<Int>()
let a1 = s1.removeFirst()
expectFalse(s1.contains(a1))
expectTrue(s2.contains(a1))
expectNotEqual(s1._rawIdentifier(), s2._rawIdentifier())
expectTrue(s1.isSubset(of: s2))
expectNil(empty.first)
}
SetTestSuite.test("remove(member)")
.code {
let s1 : Set<TestKeyTy> = [1010, 2020, 3030]
var s2 = Set<TestKeyTy>(minimumCapacity: 10)
for i in [1010, 2020, 3030] {
s2.insert(TestKeyTy(i))
}
let identity1 = s2._rawIdentifier()
// remove something that's not there.
let fortyForty = s2.remove(4040)
expectEqual(s2, s1)
expectNil(fortyForty)
expectEqual(identity1, s2._rawIdentifier())
// Remove things that are there.
let thirtyThirty = s2.remove(3030)
expectEqual(3030, thirtyThirty)
expectEqual(identity1, s2._rawIdentifier())
s2.remove(2020)
expectEqual(identity1, s2._rawIdentifier())
s2.remove(1010)
expectEqual(identity1, s2._rawIdentifier())
expectEqual(Set(), s2)
expectTrue(s2.isEmpty)
}
SetTestSuite.test("contains") {
let s1 = Set([1010, 2020, 3030])
expectTrue(s1.contains(1010))
expectFalse(s1.contains(999))
}
SetTestSuite.test("memberAtIndex") {
let s1 = Set([1010, 2020, 3030])
let foundIndex = s1.index(of: 1010)!
expectEqual(1010, s1[foundIndex])
}
SetTestSuite.test("first") {
let s1 = Set([1010, 2020, 3030])
let emptySet = Set<Int>()
expectTrue(s1.contains(s1.first!))
expectNil(emptySet.first)
}
SetTestSuite.test("capacity/reserveCapacity(_:)") {
var s1: Set = [10, 20, 30]
expectEqual(3, s1.capacity)
s1.insert(40)
expectEqual(6, s1.capacity)
// Reserving new capacity jumps up to next limit.
s1.reserveCapacity(7)
expectEqual(12, s1.capacity)
// Can reserve right up to a limit.
s1.reserveCapacity(24)
expectEqual(24, s1.capacity)
// Fill up to the limit, no reallocation.
s1.formUnion(stride(from: 50, through: 240, by: 10))
expectEqual(24, s1.count)
expectEqual(24, s1.capacity)
s1.insert(250)
expectEqual(48, s1.capacity)
}
SetTestSuite.test("isEmpty") {
let s1 = Set([1010, 2020, 3030])
expectFalse(s1.isEmpty)
let emptySet = Set<Int>()
expectTrue(emptySet.isEmpty)
}
#if _runtime(_ObjC)
@objc
class MockSetWithCustomCount : NSSet {
init(count: Int) {
self._count = count
super.init()
}
override init() {
expectUnreachable()
super.init()
}
override init(objects: UnsafePointer<AnyObject>?, count: Int) {
expectUnreachable()
super.init(objects: objects, count: count)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) not implemented by MockSetWithCustomCount")
}
@objc(copyWithZone:)
override func copy(with zone: NSZone?) -> Any {
// Ensure that copying this set produces an object of the same
// dynamic type.
return self
}
override func member(_ object: Any) -> Any? {
expectUnreachable()
return object
}
override func objectEnumerator() -> NSEnumerator {
expectUnreachable()
return getAsNSSet([1010, 1020, 1030]).objectEnumerator()
}
override var count: Int {
MockSetWithCustomCount.timesCountWasCalled += 1
return _count
}
var _count: Int = 0
static var timesCountWasCalled = 0
}
func getMockSetWithCustomCount(count: Int)
-> Set<NSObject> {
return MockSetWithCustomCount(count: count) as Set
}
func callGenericIsEmpty<C : Collection>(_ collection: C) -> Bool {
return collection.isEmpty
}
SetTestSuite.test("isEmpty/ImplementationIsCustomized") {
do {
var d = getMockSetWithCustomCount(count: 0)
MockSetWithCustomCount.timesCountWasCalled = 0
expectTrue(d.isEmpty)
expectEqual(1, MockSetWithCustomCount.timesCountWasCalled)
}
do {
var d = getMockSetWithCustomCount(count: 0)
MockSetWithCustomCount.timesCountWasCalled = 0
expectTrue(callGenericIsEmpty(d))
expectEqual(1, MockSetWithCustomCount.timesCountWasCalled)
}
do {
var d = getMockSetWithCustomCount(count: 4)
MockSetWithCustomCount.timesCountWasCalled = 0
expectFalse(d.isEmpty)
expectEqual(1, MockSetWithCustomCount.timesCountWasCalled)
}
do {
var d = getMockSetWithCustomCount(count: 4)
MockSetWithCustomCount.timesCountWasCalled = 0
expectFalse(callGenericIsEmpty(d))
expectEqual(1, MockSetWithCustomCount.timesCountWasCalled)
}
}
#endif // _runtime(_ObjC)
SetTestSuite.test("count") {
let s1 = Set([1010, 2020, 3030])
var s2 = Set([4040, 5050, 6060])
expectEqual(0, Set<Int>().count)
expectEqual(3, s1.count)
}
SetTestSuite.test("contains") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
expectTrue(s1.contains(1010))
expectFalse(s1.contains(999))
expectFalse(Set<Int>().contains(1010))
}
SetTestSuite.test("_customContainsEquatableElement") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
expectTrue(s1._customContainsEquatableElement(1010)!)
expectFalse(s1._customContainsEquatableElement(999)!)
expectFalse(Set<Int>()._customContainsEquatableElement(1010)!)
}
SetTestSuite.test("index(of:)") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let foundIndex1 = s1.index(of: 1010)!
expectEqual(1010, s1[foundIndex1])
expectNil(s1.index(of: 999))
}
SetTestSuite.test("popFirst") {
// Empty
do {
var s = Set<Int>()
let popped = s.popFirst()
expectNil(popped)
expectTrue(s.isEmpty)
}
do {
var popped = [Int]()
var s = Set([1010, 2020, 3030])
let expected = Array(s)
while let element = s.popFirst() {
popped.append(element)
}
expectEqualSequence(expected, Array(popped))
expectTrue(s.isEmpty)
}
}
SetTestSuite.test("removeAt") {
// Test removing from the startIndex, the middle, and the end of a set.
for i in 1...3 {
var s = Set<Int>([1010, 2020, 3030])
let removed = s.remove(at: s.index(of: i*1010)!)
expectEqual(i*1010, removed)
expectEqual(2, s.count)
expectNil(s.index(of: i*1010))
let origKeys: [Int] = [1010, 2020, 3030]
expectEqual(origKeys.filter { $0 != (i*1010) }, [Int](s).sorted())
}
}
SetTestSuite.test("_customIndexOfEquatableElement") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let foundIndex1 = s1._customIndexOfEquatableElement(1010)!!
expectEqual(1010, s1[foundIndex1])
expectNil(s1._customIndexOfEquatableElement(999)!)
}
SetTestSuite.test("commutative") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([2020, 3030])
expectTrue(equalsUnordered(s1.intersection(s2), s2.intersection(s1)))
expectTrue(equalsUnordered(s1.union(s2), s2.union(s1)))
}
SetTestSuite.test("associative") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([2020, 3030])
let s3 = Set([1010, 2020, 3030])
let s4 = Set([2020, 3030])
let s5 = Set([7070, 8080, 9090])
expectTrue(equalsUnordered(s1.intersection(s2).intersection(s3),
s1.intersection(s2.intersection(s3))))
expectTrue(equalsUnordered(s3.union(s4).union(s5), s3.union(s4.union(s5))))
}
SetTestSuite.test("distributive") {
let s1 = Set([1010])
let s2 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s3 = Set([2020, 3030])
expectTrue(equalsUnordered(s1.union(s2.intersection(s3)),
s1.union(s2).intersection(s1.union(s3))))
let s4 = Set([2020, 3030])
expectTrue(equalsUnordered(s4.intersection(s1.union(s3)),
s4.intersection(s1).union(s4.intersection(s3))))
}
SetTestSuite.test("idempotent") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
expectTrue(equalsUnordered(s1, s1.intersection(s1)))
expectTrue(equalsUnordered(s1, s1.union(s1)))
}
SetTestSuite.test("absorption") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
let s3 = Set([2020, 3030])
expectTrue(equalsUnordered(s1, s1.union(s1.intersection(s2))))
expectTrue(equalsUnordered(s1, s1.intersection(s1.union(s3))))
}
SetTestSuite.test("misc") {
// Set with other types
do {
var s = Set([1.1, 2.2, 3.3])
s.insert(4.4)
expectTrue(s.contains(1.1))
expectTrue(s.contains(2.2))
expectTrue(s.contains(3.3))
}
do {
var s = Set(["Hello", "world"])
expectTrue(s.contains("Hello"))
expectTrue(s.contains("world"))
}
}
SetTestSuite.test("Hashable") {
let s1 = Set([1010])
let s2 = Set([2020])
checkHashable([s1, s2], equalityOracle: { $0 == $1 })
// Explicit types help the type checker quite a bit.
let ss1 = Set([Set([1010] as [Int]), Set([2020] as [Int]), Set([3030] as [Int])])
let ss11 = Set([Set([2020] as [Int]), Set([3030] as [Int]), Set([2020] as [Int])])
let ss2 = Set([Set([9090] as [Int])])
checkHashable([ss1, ss11, ss2], equalityOracle: { $0 == $1 })
}
//===---
// Check that iterators traverse a snapshot of the collection.
//===---
SetTestSuite.test("mutationDoesNotAffectIterator/remove,1") {
var set = Set([1010, 1020, 1030])
var iter = set.makeIterator()
expectOptionalEqual(1010, set.remove(1010))
expectEqualsUnordered([1010, 1020, 1030], Array(IteratorSequence(iter)))
}
SetTestSuite.test("mutationDoesNotAffectIterator/remove,all") {
var set = Set([1010, 1020, 1030])
var iter = set.makeIterator()
expectOptionalEqual(1010, set.remove(1010))
expectOptionalEqual(1020, set.remove(1020))
expectOptionalEqual(1030, set.remove(1030))
expectEqualsUnordered([1010, 1020, 1030], Array(IteratorSequence(iter)))
}
SetTestSuite.test("mutationDoesNotAffectIterator/removeAll,keepingCapacity=false") {
var set = Set([1010, 1020, 1030])
var iter = set.makeIterator()
set.removeAll(keepingCapacity: false)
expectEqualsUnordered([1010, 1020, 1030], Array(IteratorSequence(iter)))
}
SetTestSuite.test("mutationDoesNotAffectIterator/removeAll,keepingCapacity=true") {
var set = Set([1010, 1020, 1030])
var iter = set.makeIterator()
set.removeAll(keepingCapacity: true)
expectEqualsUnordered([1010, 1020, 1030], Array(IteratorSequence(iter)))
}
//===---
// Check SetAlgebra conformance
//===---
// Make sure Set conforms to the SetAlgebra protocol
SetTestSuite.test("SetAlgebra.conformance") {
func ensureConformance<T: SetAlgebra>(_ s: T) {
expectFalse(s.isEmpty)
}
let s: Set<Int> = [1,2,3,4,5]
ensureConformance(s)
}
// Test isEmpty
SetTestSuite.test("SetAlgebra.IsEmpty.SingleEntry") {
let s = Set<Int>([1050])
expectFalse(s.isEmpty)
}
SetTestSuite.test("SetAlgebra.IsEmpty.MultipleEntries") {
let s: Set<Int> = [1010, 1020, 1030, 1040, 1050]
expectFalse(s.isEmpty)
}
SetTestSuite.test("SetAlgebra.IsEmpty.EmptySet") {
var s: Set<Int> = []
expectTrue(s.isEmpty)
s.insert(1010)
expectFalse(s.isEmpty)
}
// Test equality operator
SetTestSuite.test("SetAlgebra.==.SingleEntry") {
let s1 = Set<Int>([1010])
let s2 = Set<Int>([1010])
let s3: Set<Int> = [1010, 1020, 1030]
expectEqual(s1, s2)
expectNotEqual(s1, s3)
}
SetTestSuite.test("SetAlgebra.==.MultipleEntries") {
let s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1010, 1020, 1030]
let s3: Set<Int> = [1030, 1040, 1050]
expectEqual(s1, s2)
expectNotEqual(s1, s3)
}
SetTestSuite.test("SetAlgebra.==.EmptySet") {
let s1: Set<Int> = []
let s2: Set<Int> = []
let s3: Set<Int> = [1010, 1020, 1030]
expectEqual(s1, s2)
expectNotEqual(s1, s3)
}
// Test contains()
SetTestSuite.test("SetAlgebra.Contains.SingleEntry") {
let s = Set<Int>([1050])
expectFalse(s.contains(1010))
expectTrue(s.contains(1050))
}
SetTestSuite.test("SetAlgebra.Contains.MultipleEntries") {
let s: Set<Int> = [1010, 1020, 1030, 1040, 1050]
expectFalse(s.contains(1060))
expectFalse(s.contains(1070))
expectTrue(s.contains(1010))
expectTrue(s.contains(1020))
expectTrue(s.contains(1030))
expectTrue(s.contains(1040))
expectTrue(s.contains(1050))
}
SetTestSuite.test("SetAlgebra.Contains.EmptySet") {
let s: Set<Int> = []
expectFalse(s.contains(1010))
expectFalse(s.contains(1020))
expectFalse(s.contains(1030))
expectFalse(s.contains(1040))
expectFalse(s.contains(1050))
expectFalse(s.contains(1060))
expectFalse(s.contains(1070))
}
// Test formItersection()
SetTestSuite.test("SetAlgebra.FormIntersection.SingleEntry") {
do {
var s1 = Set<Int>([1010])
let s2: Set<Int> = [1010, 1020, 1030]
s1.formIntersection(s2)
expectTrue(s1.contains(1010))
expectFalse(s1.contains(1020))
expectFalse(s1.contains(1070))
}
do {
var s1 = Set<Int>([1010])
let s2: Set<Int> = [1020, 1030, 1050]
s1.formIntersection(s2)
expectFalse(s1.contains(1010))
expectFalse(s1.contains(1020))
expectFalse(s1.contains(1070))
}
}
SetTestSuite.test("SetAlgebra.FormIntersection.MultipleEntries") {
do {
var s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1030, 1040, 1050]
s1.formIntersection(s2)
expectTrue(s1.contains(1030))
expectFalse(s1.contains(1020))
expectFalse(s1.contains(1070))
}
do {
var s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1040, 1050, 1060]
s1.formIntersection(s2)
expectFalse(s1.contains(1030))
expectFalse(s1.contains(1040))
expectFalse(s1.contains(1070))
}
}
SetTestSuite.test("SetAlgebra.FormIntersection.EmptySet") {
var s1: Set<Int> = []
let s2: Set<Int> = [1010, 1020, 1030]
s1.formIntersection(s2)
expectFalse(s1.contains(1030))
expectFalse(s1.contains(1040))
}
// Test formSymmetricDifference()
SetTestSuite.test("SetAlgebra.FormSymmetricDifference.SingleEntry") {
do {
var s1 = Set<Int>([1010])
let s2: Set<Int> = [1010, 1020, 1030]
s1.formSymmetricDifference(s2)
expectTrue(s1.contains(1020))
expectFalse(s1.contains(1010))
expectFalse(s1.contains(1070))
}
do {
var s1 = Set<Int>([1010])
let s2: Set<Int> = [1020, 1030, 1050]
s1.formSymmetricDifference(s2)
expectTrue(s1.contains(1010))
expectTrue(s1.contains(1020))
expectFalse(s1.contains(1070))
}
}
SetTestSuite.test("SetAlgebra.FormSymmetricDifference.MultipleEntries") {
do {
var s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1030, 1040, 1050]
s1.formSymmetricDifference(s2)
expectTrue(s1.contains(1020))
expectFalse(s1.contains(1030))
expectFalse(s1.contains(1070))
}
do {
var s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1040, 1050, 1060]
s1.formSymmetricDifference(s2)
expectTrue(s1.contains(1030))
expectTrue(s1.contains(1040))
expectFalse(s1.contains(1070))
}
}
SetTestSuite.test("SetAlgebra.FormSymmetricDifference.EmptySet") {
var s1: Set<Int> = []
let s2: Set<Int> = [1010, 1020, 1030]
s1.formSymmetricDifference(s2)
expectTrue(s1.contains(1030))
expectFalse(s1.contains(1040))
}
// Test formUnion()
SetTestSuite.test("SetAlgebra.FormUnion.SingleEntry") {
do {
var s1 = Set<Int>([1010])
let s2: Set<Int> = [1010, 1020, 1030]
s1.formUnion(s2)
expectTrue(s1.contains(1010))
expectTrue(s1.contains(1020))
expectFalse(s1.contains(1070))
}
do {
var s1 = Set<Int>([1010])
let s2: Set<Int> = [1020, 1030, 1050]
s1.formUnion(s2)
expectTrue(s1.contains(1010))
expectTrue(s1.contains(1020))
expectFalse(s1.contains(1070))
}
}
SetTestSuite.test("SetAlgebra.FormUnion.MultipleEntries") {
do {
var s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1030, 1040, 1050]
s1.formUnion(s2)
expectTrue(s1.contains(1030))
expectTrue(s1.contains(1020))
expectFalse(s1.contains(1070))
}
do {
var s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1040, 1050, 1060]
s1.formUnion(s2)
expectTrue(s1.contains(1030))
expectTrue(s1.contains(1040))
expectFalse(s1.contains(1070))
}
}
SetTestSuite.test("SetAlgebra.FormUnion.EmptySet") {
var s1: Set<Int> = []
let s2: Set<Int> = [1010, 1020, 1030]
s1.formUnion(s2)
expectTrue(s1.contains(1030))
expectFalse(s1.contains(1040))
}
// Test insert()
SetTestSuite.test("SetAlgebra.Insert.SingleEntry") {
var s = Set<Int>([1010])
expectFalse(s.contains(1020))
let (inserted1, member1) = s.insert(1020)
expectTrue(s.contains(1010))
expectTrue(s.contains(1020))
expectFalse(s.contains(1070))
expectTrue(inserted1)
expectEqual(1020, member1)
let (inserted2, member2) = s.insert(1020)
expectFalse(inserted2)
expectEqual(1020, member2)
}
SetTestSuite.test("SetAlgebra.Insert.MultipleEntries") {
var s: Set<Int> = [1010, 1020, 1030]
expectFalse(s.contains(1050))
let (inserted1, member1) = s.insert(1050)
expectTrue(s.contains(1010))
expectTrue(s.contains(1050))
expectFalse(s.contains(1070))
expectTrue(inserted1)
expectEqual(1050, member1)
let (inserted2, member2) = s.insert(1050)
expectFalse(inserted2)
expectEqual(1050, member2)
}
SetTestSuite.test("SetAlgebra.Insert.EmptySet") {
var s: Set<Int> = []
expectFalse(s.contains(1010))
let (inserted1, member1) = s.insert(1010)
expectTrue(s.contains(1010))
expectTrue(inserted1)
expectEqual(1010, member1)
let (inserted2, member2) = s.insert(1010)
expectFalse(inserted2)
expectEqual(1010, member2)
}
// Test intersection()
SetTestSuite.test("SetAlgebra.Intersection.SingleEntry") {
do {
let s1 = Set<Int>([1010])
let s2: Set<Int> = [1010, 1020, 1030]
let intersection = s1.intersection(s2)
expectTrue(intersection.contains(1010))
expectFalse(intersection.contains(1020))
expectFalse(intersection.contains(1070))
}
do {
let s1 = Set<Int>([1010])
let s2: Set<Int> = [1020, 1030, 1050]
let intersection = s1.intersection(s2)
expectFalse(intersection.contains(1010))
expectFalse(intersection.contains(1020))
expectFalse(intersection.contains(1070))
}
}
SetTestSuite.test("SetAlgebra.Intersection.MultipleEntries") {
do {
let s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1030, 1040, 1050]
let intersection = s1.intersection(s2)
expectTrue(intersection.contains(1030))
expectFalse(intersection.contains(1020))
expectFalse(intersection.contains(1070))
}
do {
let s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1040, 1050, 1060]
let intersection = s1.intersection(s2)
expectFalse(intersection.contains(1030))
expectFalse(intersection.contains(1040))
expectFalse(intersection.contains(1070))
}
}
SetTestSuite.test("SetAlgebra.Intersection.EmptySet") {
let s1: Set<Int> = []
let s2: Set<Int> = [1010, 1020, 1030]
let intersection = s1.intersection(s2)
expectFalse(intersection.contains(1030))
expectFalse(intersection.contains(1040))
}
// Test isDisjointUnion(with:)
SetTestSuite.test("SetAlgebra.IsDisjointWith.SingleEntry") {
let s1 = Set<Int>([1010])
let s2: Set<Int> = [1010, 1020, 1030]
let s3: Set<Int> = [1020, 1030]
expectFalse(s1.isDisjoint(with: s2))
expectTrue(s1.isDisjoint(with: s3))
}
SetTestSuite.test("SetAlgebra.IsDisjointWith.MultipleEntries") {
let s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1020, 1030]
let s3: Set<Int> = [1040, 1050, 1060]
expectFalse(s1.isDisjoint(with: s2))
expectTrue(s1.isDisjoint(with: s3))
}
SetTestSuite.test("SetAlgebra.IsDisjointWith.EmptySet") {
let s1: Set<Int> = []
let s2: Set<Int> = [1020, 1030]
expectTrue(s1.isDisjoint(with: s2))
}
// Test isSubset(of:)
SetTestSuite.test("SetAlgebra.IsSubsetOf.SingleEntry") {
let s1 = Set<Int>([1010])
let s2: Set<Int> = [1010, 1020, 1030]
let s3: Set<Int> = [1020, 1030]
expectTrue(s1.isSubset(of: s2))
expectFalse(s1.isSubset(of: s3))
}
SetTestSuite.test("SetAlgebra.IsSubsetOf.MultipleEntries") {
let s1: Set<Int> = [1010, 1020]
let s2: Set<Int> = [1010, 1020, 1030]
let s3: Set<Int> = [1040, 1050, 1060]
expectTrue(s1.isSubset(of: s2))
expectFalse(s1.isSubset(of: s3))
}
SetTestSuite.test("SetAlgebra.IsSubsetOf.EmptySet") {
let s1: Set<Int> = []
let s2: Set<Int> = [1020, 1030]
expectTrue(s1.isSubset(of: s2))
}
// Test isSuperset(of:)
SetTestSuite.test("SetAlgebra.IsSupersetOf.SingleEntry") {
let s1 = Set<Int>([1010])
let s2: Set<Int> = [1010]
let s3: Set<Int> = [1020, 1030]
let s4: Set<Int> = []
expectTrue(s1.isSuperset(of: s2))
expectFalse(s1.isSuperset(of: s3))
expectTrue(s1.isSuperset(of: s4))
}
SetTestSuite.test("SetAlgebra.IsSupersetOf.MultipleEntries") {
let s1: Set<Int> = [1010, 1020]
let s2: Set<Int> = [1010, 1020]
let s3: Set<Int> = [1010]
let s4: Set<Int> = [1040, 1050, 1060]
expectTrue(s1.isSuperset(of: s2))
expectTrue(s1.isSuperset(of: s3))
expectFalse(s1.isSuperset(of: s4))
}
SetTestSuite.test("SetAlgebra.IsSupersetOf.EmptySet") {
let s1: Set<Int> = []
let s2: Set<Int> = [1020, 1030]
let s3: Set<Int> = []
expectFalse(s1.isSuperset(of: s2))
expectTrue(s1.isSuperset(of: s3))
}
// Test remove()
SetTestSuite.test("SetAlgebra.Remove.SingleEntry") {
var s = Set<Int>([1010])
expectTrue(s.contains(1010))
let removed = s.remove(1010)
expectFalse(s.contains(1010))
expectFalse(s.contains(1070))
expectEqual(1010, removed)
}
SetTestSuite.test("SetAlgebra.Remove.MultipleEntries") {
var s: Set<Int> = [1010, 1020, 1030]
expectTrue(s.contains(1020))
let removed = s.remove(1020)
expectTrue(s.contains(1010))
expectFalse(s.contains(1020))
expectFalse(s.contains(1070))
expectEqual(1020, removed)
}
SetTestSuite.test("SetAlgebra.Remove.EmptySet") {
var s: Set<Int> = []
expectFalse(s.contains(1010))
let removed = s.remove(1010)
expectFalse(s.contains(1010))
expectNil(removed)
}
// Test subtract()
SetTestSuite.test("SetAlgebra.Subtract.SingleEntry") {
do {
var s = Set<Int>([1010])
s.subtract([1010])
expectFalse(s.contains(1010))
}
do {
var s = Set<Int>([1010])
s.subtract([1020])
expectTrue(s.contains(1010))
}
}
SetTestSuite.test("SetAlgebra.Subtract.MultipleEntries") {
do {
var s: Set<Int> = [1010, 1020, 1030]
s.subtract([1010])
expectFalse(s.contains(1010))
expectTrue(s.contains(1020))
}
do {
var s: Set<Int> = [1010, 1020, 1030]
s.subtract([1050])
expectTrue(s.contains(1010))
expectFalse(s.contains(1050))
}
}
SetTestSuite.test("SetAlgebra.Subtract.EmptySet") {
var s: Set<Int> = []
s.subtract([1010])
expectFalse(s.contains(1010))
expectFalse(s.contains(1020))
}
// Test subtracting()
SetTestSuite.test("SetAlgebra.Subtracting.SingleEntry") {
do {
let s = Set<Int>([1010])
let difference = s.subtracting([1010])
expectFalse(difference.contains(1010))
}
do {
let s = Set<Int>([1010])
let difference = s.subtracting([1020])
expectTrue(difference.contains(1010))
}
}
SetTestSuite.test("SetAlgebra.Subtracting.MultipleEntries") {
do {
let s: Set<Int> = [1010, 1020, 1030]
let difference = s.subtracting([1010])
expectFalse(difference.contains(1010))
expectTrue(difference.contains(1020))
}
do {
let s: Set<Int> = [1010, 1020, 1030]
let difference = s.subtracting([1050])
expectTrue(difference.contains(1010))
expectFalse(difference.contains(1050))
}
}
SetTestSuite.test("SetAlgebra.Subtracting.EmptySet") {
let s: Set<Int> = []
let difference = s.subtracting([1010])
expectFalse(difference.contains(1010))
expectFalse(difference.contains(1020))
}
// Test symmetricDifference()
SetTestSuite.test("SetAlgebra.SymmetricDifference.SingleEntry") {
do {
let s1 = Set<Int>([1010])
let s2: Set<Int> = [1010, 1020, 1030]
let difference = s1.symmetricDifference(s2)
expectFalse(difference.contains(1010))
expectTrue(difference.contains(1020))
expectFalse(difference.contains(1070))
}
do {
let s1 = Set<Int>([1010])
let s2: Set<Int> = [1020, 1030, 1050]
let difference = s1.symmetricDifference(s2)
expectTrue(difference.contains(1010))
expectTrue(difference.contains(1020))
expectFalse(difference.contains(1070))
}
}
SetTestSuite.test("SetAlgebra.SymmetricDifference.MultipleEntries") {
do {
let s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1030, 1040, 1050]
let difference = s1.symmetricDifference(s2)
expectFalse(difference.contains(1030))
expectTrue(difference.contains(1020))
expectFalse(difference.contains(1070))
}
do {
let s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1040, 1050, 1060]
let difference = s1.symmetricDifference(s2)
expectTrue(difference.contains(1030))
expectTrue(difference.contains(1040))
expectFalse(difference.contains(1070))
}
}
SetTestSuite.test("SetAlgebra.SymmetricDifference.EmptySet") {
let s1: Set<Int> = []
let s2: Set<Int> = [1010, 1020, 1030]
let difference = s1.symmetricDifference(s2)
expectTrue(difference.contains(1030))
expectFalse(difference.contains(1040))
}
// Test union()
SetTestSuite.test("SetAlgebra.Union.SingleEntry") {
do {
let s1 = Set<Int>([1010])
let s2: Set<Int> = [1010, 1020, 1030]
let union = s1.union(s2)
expectTrue(union.contains(1010))
expectTrue(union.contains(1020))
expectFalse(union.contains(1070))
}
do {
let s1 = Set<Int>([1010])
let s2: Set<Int> = [1020, 1030, 1050]
let union = s1.union(s2)
expectTrue(union.contains(1010))
expectTrue(union.contains(1020))
expectFalse(union.contains(1070))
}
}
SetTestSuite.test("SetAlgebra.Union.MultipleEntries") {
do {
let s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1030, 1040, 1050]
let union = s1.union(s2)
expectTrue(union.contains(1030))
expectTrue(union.contains(1020))
expectFalse(union.contains(1070))
}
do {
let s1: Set<Int> = [1010, 1020, 1030]
let s2: Set<Int> = [1040, 1050, 1060]
let union = s1.union(s2)
expectTrue(union.contains(1030))
expectTrue(union.contains(1040))
expectFalse(union.contains(1070))
}
}
SetTestSuite.test("SetAlgebra.Union.EmptySet") {
let s1: Set<Int> = []
let s2: Set<Int> = [1010, 1020, 1030]
let union = s1.union(s2)
expectTrue(union.contains(1030))
expectFalse(union.contains(1040))
}
// Test update(with:)
SetTestSuite.test("SetAlgebra.UpdateWith.SingleEntry") {
var s = Set<Int>([1010])
expectFalse(s.contains(1020))
let member1 = s.update(with: 1020)
expectTrue(s.contains(1010))
expectTrue(s.contains(1020))
expectFalse(s.contains(1070))
expectNil(member1)
let member2 = s.update(with: 1020)
expectOptionalEqual(1020, member2)
}
SetTestSuite.test("SetAlgebra.UpdateWith.MultipleEntries") {
var s: Set<Int> = [1010, 1020, 1030]
expectFalse(s.contains(1050))
let member1 = s.update(with: 1050)
expectTrue(s.contains(1010))
expectTrue(s.contains(1050))
expectFalse(s.contains(1070))
expectNil(member1)
let member2 = s.update(with: 1050)
expectOptionalEqual(1050, member2)
}
SetTestSuite.test("SetAlgebra.UpdateWith.EmptySet") {
var s: Set<Int> = []
expectFalse(s.contains(1010))
let member1 = s.update(with: 1010)
expectTrue(s.contains(1010))
expectNil(member1)
let member2 = s.update(with: 1010)
expectOptionalEqual(1010, member2)
}
runAllTests()
| apache-2.0 | ca3ddd4c24dfc38354ff517e2403671a | 26.416211 | 278 | 0.70202 | 3.791086 | false | true | false | false |
grimcoder/fourthstep | FourthStep/FourthStep/FileManagement.swift | 1 | 19853 | //
// Created by Anthony Levings on 25/06/2014.
//
import Foundation
import Foundation
//pragma mark - strip slashes
public class FileHelper {
public static func stripSlashIfNeeded(stringWithPossibleSlash:String) -> String {
var stringWithoutSlash:String = stringWithPossibleSlash
// If the file name contains a slash at the beginning then we remove so that we don't end up with two
if stringWithPossibleSlash.hasPrefix("/") {
stringWithoutSlash = stringWithPossibleSlash.substringFromIndex(stringWithoutSlash.startIndex.advancedBy(1))
}
// Return the string with no slash at the beginning
return stringWithoutSlash
}
public static func createSubDirectory(subdirectoryPath:String) -> Bool {
var error:NSError?
var isDir:ObjCBool=false;
let exists:Bool = NSFileManager.defaultManager().fileExistsAtPath(subdirectoryPath, isDirectory:&isDir)
if (exists) {
/* a file of the same name exists, we don't care about this so won't do anything */
if isDir {
/* subdirectory already exists, don't create it again */
return true;
}
}
var success:Bool
do {
try NSFileManager.defaultManager().createDirectoryAtPath(subdirectoryPath, withIntermediateDirectories:true, attributes:nil)
success = true
} catch let error1 as NSError {
error = error1
success = false
}
if (error != nil) { print(error) }
return success;
}
}
import Foundation
public struct FileDirectory {
public static func applicationDirectory(directory:NSSearchPathDirectory) -> NSURL? {
var appDirectory:String?
var paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(directory, NSSearchPathDomainMask.UserDomainMask, true);
if paths.count > 0 {
if let pathString = paths[0] as? String {
appDirectory = pathString
}
}
if let dD = appDirectory {
return NSURL(string:dD)
}
return nil
}
public static func applicationTemporaryDirectory() -> NSURL? {
return NSURL(string: NSTemporaryDirectory())
}
}
import Foundation
// see here for Apple's ObjC Code https://developer.apple.com/library/mac/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html
public class FileList {
public static func allFilesAndFolders(inDirectory directory:NSSearchPathDirectory, subdirectory:String?) -> [NSURL]? {
// Create load path
if let loadPath = buildPathToDirectory(directory, subdirectory: subdirectory) {
let url = NSURL(fileURLWithPath: loadPath)
var array:[NSURL]? = nil
let properties = [NSURLLocalizedNameKey,
NSURLCreationDateKey, NSURLLocalizedTypeDescriptionKey]
do {
array = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(url, includingPropertiesForKeys: properties, options:NSDirectoryEnumerationOptions.SkipsHiddenFiles)
} catch let error1 as NSError {
print(error1.description)
}
return array
}
return nil
}
public static func allFilesAndFoldersInTemporaryDirectory(subdirectory:String?) -> [NSURL]? {
// Create load path
let loadPath = buildPathToTemporaryDirectory(subdirectory)
let url = NSURL(fileURLWithPath: loadPath)
var array:[NSURL]? = nil
let properties = [NSURLLocalizedNameKey,
NSURLCreationDateKey, NSURLLocalizedTypeDescriptionKey]
do {
array = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(url, includingPropertiesForKeys: properties, options:NSDirectoryEnumerationOptions.SkipsHiddenFiles) as [NSURL] }
catch let error1 as NSError {
print(error1.description)
}
return array
}
// private methods
private static func buildPathToDirectory(directory:NSSearchPathDirectory, subdirectory:String?) -> String? {
// Remove unnecessary slash if need
// Remove unnecessary slash if need
var subDir = ""
if let sub = subdirectory {
subDir = FileHelper.stripSlashIfNeeded(sub)
}
// Create generic beginning to file delete path
var buildPath = ""
if let direct = FileDirectory.applicationDirectory(directory),
path = direct.path {
buildPath = path + "/"
}
buildPath += subDir
buildPath += "/"
var dir:ObjCBool = true
let dirExists = NSFileManager.defaultManager().fileExistsAtPath(buildPath, isDirectory:&dir)
if dir.boolValue == false {
return nil
}
if dirExists == false {
return nil
}
return buildPath
}
public static func buildPathToTemporaryDirectory(subdirectory:String?) -> String {
// Remove unnecessary slash if need
var subDir:String?
if let sub = subdirectory {
subDir = FileHelper.stripSlashIfNeeded(sub)
}
// Create generic beginning to file load path
var loadPath = ""
if let direct = FileDirectory.applicationTemporaryDirectory(),
path = direct.path {
loadPath = path + "/"
}
if let sub = subDir {
loadPath += sub
loadPath += "/"
}
// Add requested save path
return loadPath
}
}
import Foundation
public struct FileLoad {
public static func loadData(path:String, directory:NSSearchPathDirectory, subdirectory:String?) -> NSData?
{
let loadPath = buildPath(path, inDirectory: directory, subdirectory: subdirectory)
// load the file and see if it was successful
let data = NSFileManager.defaultManager().contentsAtPath(loadPath)
// Return data
return data
}
public static func loadDataFromTemporaryDirectory(path:String, subdirectory:String?) -> NSData?
{
let loadPath = buildPathToTemporaryDirectory(path, subdirectory: subdirectory)
// Save the file and see if it was successful
let data = NSFileManager.defaultManager().contentsAtPath(loadPath)
// Return status of file save
return data
}
// string methods
public static func loadString(path:String, directory:NSSearchPathDirectory, subdirectory:String?, encoding enc:NSStringEncoding = NSUTF8StringEncoding) -> String?
{
let loadPath = buildPath(path, inDirectory: directory, subdirectory: subdirectory)
var error:NSError?
print(loadPath)
// Save the file and see if it was successful
let text:String?
do {
text = try String(contentsOfFile:loadPath, encoding:enc)
} catch let error1 as NSError {
error = error1
text = nil
}
return text
}
public static func loadStringFromTemporaryDirectory(path:String, subdirectory:String?, encoding enc:NSStringEncoding = NSUTF8StringEncoding) -> String? {
let loadPath = buildPathToTemporaryDirectory(path, subdirectory: subdirectory)
var error:NSError?
print(loadPath)
// Save the file and see if it was successful
var text:String?
do {
text = try String(contentsOfFile:loadPath, encoding:enc)
} catch let error1 as NSError {
error = error1
text = nil
}
return text
}
// private methods
private static func buildPath(path:String, inDirectory directory:NSSearchPathDirectory, subdirectory:String?) -> String {
// Remove unnecessary slash if need
let newPath = FileHelper.stripSlashIfNeeded(path)
var subDir:String?
if let sub = subdirectory {
subDir = FileHelper.stripSlashIfNeeded(sub)
}
// Create generic beginning to file load path
var loadPath = ""
if let direct = FileDirectory.applicationDirectory(directory),
path = direct.path {
loadPath = path + "/"
}
if let sub = subDir {
loadPath += sub
loadPath += "/"
}
// Add requested load path
loadPath += newPath
return loadPath
}
public static func buildPathToTemporaryDirectory(path:String, subdirectory:String?) -> String {
// Remove unnecessary slash if need
let newPath = FileHelper.stripSlashIfNeeded(path)
var subDir:String?
if let sub = subdirectory {
subDir = FileHelper.stripSlashIfNeeded(sub)
}
// Create generic beginning to file load path
var loadPath = ""
if let direct = FileDirectory.applicationTemporaryDirectory(),
path = direct.path {
loadPath = path + "/"
}
if let sub = subDir {
loadPath += sub
loadPath += "/"
}
// Add requested save path
loadPath += newPath
return loadPath
}
}
import Foundation
public struct FileSave {
public static func saveData(fileData:NSData, directory:NSSearchPathDirectory, path:String, subdirectory:String?) -> Bool
{
let savePath = buildPath(path, inDirectory: directory, subdirectory: subdirectory)
// Save the file and see if it was successful
let ok:Bool = NSFileManager.defaultManager().createFileAtPath(savePath,contents:fileData, attributes:nil)
// Return status of file save
return ok
}
public static func saveDataToTemporaryDirectory(fileData:NSData, path:String, subdirectory:String?) -> Bool
{
let savePath = buildPathToTemporaryDirectory(path, subdirectory: subdirectory)
// Save the file and see if it was successful
let ok:Bool = NSFileManager.defaultManager().createFileAtPath(savePath,contents:fileData, attributes:nil)
// Return status of file save
return ok
}
// string methods
public static func saveString(fileString:String, directory:NSSearchPathDirectory, path:String, subdirectory:String) -> Bool {
let savePath = buildPath(path, inDirectory: directory, subdirectory: subdirectory)
var error:NSError?
// Save the file and see if it was successful
let ok:Bool
do {
try fileString.writeToFile(savePath, atomically:false, encoding:NSUTF8StringEncoding)
ok = true
} catch let error1 as NSError {
error = error1
ok = false
}
if (error != nil) {print(error)}
// Return status of file save
return ok
}
public static func saveStringToTemporaryDirectory(fileString:String, path:String, subdirectory:String) -> Bool {
let savePath = buildPathToTemporaryDirectory(path, subdirectory: subdirectory)
var error:NSError?
// Save the file and see if it was successful
var ok:Bool
do {
try fileString.writeToFile(savePath, atomically:false, encoding:NSUTF8StringEncoding)
ok = true
} catch let error1 as NSError {
error = error1
ok = false
}
if (error != nil) {
print(error)
}
// Return status of file save
return ok;
}
// private methods
public static func buildPath(path:String, inDirectory directory:NSSearchPathDirectory, subdirectory:String?) -> String {
// Remove unnecessary slash if need
let newPath = FileHelper.stripSlashIfNeeded(path)
var newSubdirectory:String?
if let sub = subdirectory {
newSubdirectory = FileHelper.stripSlashIfNeeded(sub)
}
// Create generic beginning to file save path
var savePath = ""
if let direct = FileDirectory.applicationDirectory(directory),
path = direct.path {
savePath = path + "/"
}
if (newSubdirectory != nil) {
savePath.appendContentsOf(newSubdirectory!)
FileHelper.createSubDirectory(savePath)
savePath += "/"
}
// Add requested save path
savePath += newPath
return savePath
}
public static func buildPathToTemporaryDirectory(path:String, subdirectory:String?) -> String {
// Remove unnecessary slash if need
let newPath = FileHelper.stripSlashIfNeeded(path)
var newSubdirectory:String?
if let sub = subdirectory {
newSubdirectory = FileHelper.stripSlashIfNeeded(sub)
}
// Create generic beginning to file save path
var savePath = ""
if let direct = FileDirectory.applicationTemporaryDirectory(),
path = direct.path {
savePath = path + "/"
}
if let sub = newSubdirectory {
savePath += sub
FileHelper.createSubDirectory(savePath)
savePath += "/"
}
// Add requested save path
savePath += newPath
return savePath
}
}
public struct FileDelete {
public static func deleteFile(path:String, directory:NSSearchPathDirectory, subdirectory:String?) -> Bool
{
let deletePath = buildPath(path, inDirectory: directory, subdirectory: subdirectory)
// Delete the file and see if it was successful
var error:NSError?
let ok:Bool
do {
try NSFileManager.defaultManager().removeItemAtPath(deletePath)
ok = true
} catch let error1 as NSError {
error = error1
ok = false
}
if error != nil {
print(error)
}
// Return status of file delete
return ok;
}
public static func deleteFileFromTemporaryDirectory(path:String, subdirectory:String?) -> Bool
{
let deletePath = buildPathToTemporaryDirectory(path, subdirectory: subdirectory)
// Delete the file and see if it was successful
var error:NSError?
let ok:Bool
do {
try NSFileManager.defaultManager().removeItemAtPath(deletePath)
ok = true
} catch let error1 as NSError {
error = error1
ok = false
}
if error != nil {
print(error)
}
// Return status of file delete
return ok
}
// Delete folders
public static func deleteSubDirectory(directory:NSSearchPathDirectory, subdirectory:String) -> Bool
{
// Remove unnecessary slash if need
let subDir = FileHelper.stripSlashIfNeeded(subdirectory)
// Create generic beginning to file delete path
var deletePath = ""
if let direct = FileDirectory.applicationDirectory(directory),
path = direct.path {
deletePath = path + "/"
}
deletePath += subDir
deletePath += "/"
var dir:ObjCBool = true
let dirExists = NSFileManager.defaultManager().fileExistsAtPath(deletePath, isDirectory:&dir)
if dir.boolValue == false {
return false
}
if dirExists == false {
return false
}
// Delete the file and see if it was successful
var error:NSError?
let ok:Bool
do {
try NSFileManager.defaultManager().removeItemAtPath(deletePath)
ok = true
} catch let error1 as NSError {
error = error1
ok = false
}
if error != nil {
print(error)
}
// Return status of file delete
return ok
}
public static func deleteSubDirectoryFromTemporaryDirectory(subdirectory:String) -> Bool
{
// Remove unnecessary slash if need
let subDir = FileHelper.stripSlashIfNeeded(subdirectory)
// Create generic beginning to file delete path
var deletePath = ""
if let direct = FileDirectory.applicationTemporaryDirectory(),
path = direct.path {
deletePath = path + "/"
}
deletePath += subDir
deletePath += "/"
var dir:ObjCBool = true
let dirExists = NSFileManager.defaultManager().fileExistsAtPath(deletePath, isDirectory:&dir)
if dir.boolValue == false {
return false
}
if dirExists == false {
return false
}
// Delete the file and see if it was successful
var error:NSError?
let ok:Bool
do {
try NSFileManager.defaultManager().removeItemAtPath(deletePath)
ok = true
} catch let error1 as NSError {
error = error1
ok = false
}
if error != nil {
print(error)
}
// Return status of file delete
return ok
}
// private methods
// private methods
private static func buildPath(path:String, inDirectory directory:NSSearchPathDirectory, subdirectory:String?) -> String {
// Remove unnecessary slash if need
let newPath = FileHelper.stripSlashIfNeeded(path)
var subDir:String?
if let sub = subdirectory {
subDir = FileHelper.stripSlashIfNeeded(sub)
}
// Create generic beginning to file load path
var loadPath = ""
if let direct = FileDirectory.applicationDirectory(directory),
path = direct.path {
loadPath = path + "/"
}
if let sub = subDir {
loadPath += sub
loadPath += "/"
}
// Add requested load path
loadPath += newPath
return loadPath
}
public static func buildPathToTemporaryDirectory(path:String, subdirectory:String?) -> String {
// Remove unnecessary slash if need
let newPath = FileHelper.stripSlashIfNeeded(path)
var subDir:String?
if let sub = subdirectory {
subDir = FileHelper.stripSlashIfNeeded(sub)
}
// Create generic beginning to file load path
var loadPath = ""
if let direct = FileDirectory.applicationTemporaryDirectory(),
path = direct.path {
loadPath = path + "/"
}
if let sub = subDir {
loadPath += sub
loadPath += "/"
}
// Add requested save path
loadPath += newPath
return loadPath
}
} | mit | ce9700a79d07479d9a22e838995ef7da | 28.810811 | 203 | 0.575127 | 5.940455 | false | false | false | false |
insidegui/WWDC | WWDC/LiveObserver.swift | 1 | 10815 | //
// LiveObserver.swift
// WWDC
//
// Created by Guilherme Rambo on 13/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
import ConfCore
import RealmSwift
import CloudKit
import os.log
final class LiveObserver: NSObject {
private let log = OSLog(subsystem: "WWDC", category: "LiveObserver")
private let dateProvider: DateProvider
private let storage: Storage
private let syncEngine: SyncEngine
private var refreshTimer: Timer?
var isRunning = false
private let specialEventsObserver: CloudKitLiveObserver
init(dateProvider: @escaping DateProvider, storage: Storage, syncEngine: SyncEngine) {
self.dateProvider = dateProvider
self.storage = storage
self.syncEngine = syncEngine
specialEventsObserver = CloudKitLiveObserver(storage: storage)
}
var isWWDCWeek: Bool {
return storage.realm.objects(Event.self).filter("startDate <= %@ AND endDate > %@ ", dateProvider(), dateProvider()).count > 0
}
func start() {
guard !isRunning else { return }
os_log("start()", log: log, type: .debug)
clearLiveSessions()
specialEventsObserver.fetch()
guard isWWDCWeek else {
os_log("Not starting the live event observer because WWDC is not this week",
log: log,
type: .debug)
isRunning = false
return
}
isRunning = true
refreshTimer = Timer.scheduledTimer(withTimeInterval: Constants.liveSessionCheckInterval, repeats: true, block: { [weak self] _ in
self?.checkForLiveSessions()
})
refreshTimer?.tolerance = Constants.liveSessionCheckTolerance
}
/// Clears the live flag for all live sessions
private func clearLiveSessions() {
storage.modify(allLiveInstances.toArray()) { instances in
instances.forEach { instance in
instance.isCurrentlyLive = false
instance.isForcedLive = false
}
}
}
func refresh() {
NSObject.cancelPreviousPerformRequests(withTarget: self)
perform(#selector(checkForLiveSessions), with: nil, afterDelay: 0)
}
private var allLiveInstances: Results<SessionInstance> {
return storage.realm.objects(SessionInstance.self).filter("isCurrentlyLive == true")
}
@objc private func checkForLiveSessions() {
os_log("checkForLiveSessions()", log: log, type: .debug)
specialEventsObserver.fetch()
syncEngine.syncLiveVideos { [weak self] in
self?.updateLiveFlags()
}
}
private func updateLiveFlags() {
guard let startTime = Calendar.current.date(byAdding: DateComponents(minute: Constants.liveSessionStartTimeTolerance), to: dateProvider()) else {
os_log("Could not compute a start time to check for live sessions!", log: log, type: .fault)
return
}
guard let endTime = Calendar.current.date(byAdding: DateComponents(minute: Constants.liveSessionEndTimeTolerance), to: dateProvider()) else {
os_log("Could not compute an end time to check for live sessions!", log: log, type: .fault)
return
}
let previouslyLiveInstances = allLiveInstances.toArray()
var notLiveAnymore: [SessionInstance] = []
os_log("Looking for live instances with startTime <= %{public}@ and endTime >= %{public}@", log: log, type: .debug, String(describing: startTime), String(describing: endTime))
let liveInstances = storage.realm.objects(SessionInstance.self).filter("startTime <= %@ AND endTime >= %@ AND SUBQUERY(session.assets, $asset, $asset.rawAssetType == %@ AND $asset.actualEndDate == nil).@count > 0", startTime, endTime, SessionAssetType.liveStreamVideo.rawValue)
previouslyLiveInstances.forEach { instance in
if !liveInstances.contains(instance) {
notLiveAnymore.append(instance)
}
}
setLiveFlag(false, for: notLiveAnymore)
setLiveFlag(true, for: liveInstances.toArray())
os_log("There are %{public}d live instances. %{public}d instances are not live anymore",
log: log,
type: .debug,
liveInstances.count,
notLiveAnymore.count)
let liveIdentifiers: [String] = liveInstances.map({ $0.identifier })
let notLiveAnymoreIdentifiers: [String] = notLiveAnymore.map({ $0.identifier })
if liveIdentifiers.count > 0 {
os_log("The following sessions are currently live: %{public}@", log: log, type: .debug, liveIdentifiers.joined(separator: ","))
} else {
os_log("There are no live sessions at the moment", log: log, type: .debug)
}
if notLiveAnymoreIdentifiers.count > 0 {
os_log("The following sessions are NOT live anymore: %{public}@", log: log, type: .debug, notLiveAnymoreIdentifiers.joined(separator: ","))
} else {
os_log("There are no sessions that were live and are not live anymore", log: log, type: .debug)
}
}
private func setLiveFlag(_ value: Bool, for instances: [SessionInstance]) {
os_log("Setting live flag to %{public}@ for %{public}d instances",
log: log,
type: .info,
String(describing: value), instances.count)
storage.modify(instances) { bgInstances in
bgInstances.forEach { instance in
guard !instance.isForcedLive else { return }
instance.isCurrentlyLive = value
}
}
}
func processSubscriptionNotification(with userInfo: [String: Any]) -> Bool {
return specialEventsObserver.processSubscriptionNotification(with: userInfo)
}
}
private extension SessionAsset {
static var recordType: String {
return "LiveSession"
}
convenience init?(record: CKRecord) {
guard let sessionIdentifier = record["sessionIdentifier"] as? String else { return nil }
guard let hls = record["hls"] as? String else { return nil }
self.init()
assetType = .liveStreamVideo
year = Calendar.current.component(.year, from: today())
sessionId = sessionIdentifier
remoteURL = hls
identifier = generateIdentifier()
}
}
private final class CloudKitLiveObserver {
private let log = OSLog(subsystem: "WWDC", category: "CloudKitLiveObserver")
private let storage: Storage
private lazy var database: CKDatabase = CKContainer.default().publicCloudDatabase
init(storage: Storage) {
self.storage = storage
createSubscriptionIfNeeded()
}
func fetch() {
#if ICLOUD
let query = CKQuery(recordType: SessionAsset.recordType, predicate: NSPredicate(value: true))
let operation = CKQueryOperation(query: query)
var fetchedRecords: [CKRecord] = []
operation.recordFetchedBlock = { record in
fetchedRecords.append(record)
}
operation.queryCompletionBlock = { [unowned self] _, error in
if let error = error {
os_log("Error fetching special live records: %{public}@",
log: self.log,
type: .error,
String(describing: error))
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
self.fetch()
}
} else {
DispatchQueue.main.async { self.store(fetchedRecords) }
}
}
database.add(operation)
#endif
}
private func createSubscriptionIfNeeded() {
#if ICLOUD
CloudKitHelper.subscriptionExists(with: specialLiveEventsSubscriptionID, in: database) { [unowned self] exists in
if !exists {
self.doCreateSubscription()
}
}
#endif
}
private func doCreateSubscription() {
#if ICLOUD
let options: CKQuerySubscription.Options = [.firesOnRecordCreation, .firesOnRecordUpdate, .firesOnRecordDeletion]
let subscription = CKQuerySubscription(recordType: SessionAsset.recordType,
predicate: NSPredicate(value: true),
subscriptionID: specialLiveEventsSubscriptionID,
options: options)
database.save(subscription) { _, error in
if let error = error {
os_log("Error creating subscriptions: %{public}@",
log: self.log,
type: .error,
String(describing: error))
} else {
os_log("Subscriptions created", log: self.log, type: .info)
}
}
#endif
}
private let specialLiveEventsSubscriptionID: String = "SPECIAL-LIVE-EVENTS"
func processSubscriptionNotification(with userInfo: [String: Any]) -> Bool {
#if ICLOUD
let notification = CKNotification(fromRemoteNotificationDictionary: userInfo)
// check if the remote notification is for us, if not, tell the caller that we haven't handled it
guard notification?.subscriptionID == specialLiveEventsSubscriptionID else { return false }
// notification for special live events, just fetch everything again
fetch()
return true
#else
return false
#endif
}
private func store(_ records: [CKRecord]) {
os_log("Storing live records", log: log, type: .debug)
storage.backgroundUpdate { realm in
records.forEach { record in
guard let asset = SessionAsset(record: record) else { return }
guard let session = realm.object(ofType: Session.self, forPrimaryKey: asset.sessionId) else { return }
guard let instance = session.instances.first else { return }
if let existingAsset = realm.object(ofType: SessionAsset.self, forPrimaryKey: asset.identifier) {
// update existing asset hls URL if appropriate
existingAsset.remoteURL = asset.remoteURL
} else {
// add new live asset to corresponding session
session.assets.append(asset)
}
instance.isForcedLive = (record["isLive"] as? Int == 1)
instance.isCurrentlyLive = instance.isForcedLive
}
}
}
}
| bsd-2-clause | 349c459648257b11c5e528a3bd2cd0ff | 35.046667 | 285 | 0.601073 | 5.191551 | false | false | false | false |
Estimote/iOS-SDK | Examples/swift/Loyalty/Loyalty/Models/LocationsManager.swift | 1 | 3274 | //
// Please report any problems with this app template to [email protected]
//
import Foundation
import FirebaseDatabase
protocol LocationsManagerDelegate {
func didEnterLocation(_ location:Location)
func didExitLocation(_ location:Location)
}
class LocationsManager: NSObject, ESTMonitoringV2ManagerDelegate {
@objc var monitoringManager : ESTMonitoringV2Manager!
var delegate : LocationsManagerDelegate?
@objc var locationIdentifierProvider: LocationIdentifierProvider!
override init() {
super.init()
let id = ESTConfig.appID()
let token = ESTConfig.appToken()
self.monitoringManager = ESTMonitoringV2Manager(desiredMeanTriggerDistance: 1.0, delegate: self)
self.locationIdentifierProvider = LocationIdentifierProvider.init(appId: id!, appToken: token!)
}
@objc func startMonitoring() {
// init devices ref
let dbRef = Database.database().reference()
let devicesRef = dbRef.child("devices")
// fetch devices
devicesRef.observeSingleEvent(of: .value, with: { snapshot in
var identifiers = [String]()
for device in snapshot.children {
guard let device_info = (device as! DataSnapshot).value as? NSDictionary, let identifier = device_info.object(forKey: "device_identifier") as? String else {
continue
}
identifiers.append(identifier)
}
self.monitoringManager.startMonitoring(forIdentifiers: identifiers)
})
}
@objc func stopMonitoring() {
self.monitoringManager.stopMonitoring()
}
// MARK: Handle Enter & Exit
@objc func handleInsideRegion(_ identifier:String) {
guard let locationIdentifier = self.locationIdentifierProvider.locationIdentifierPerDeviceIdentifier[identifier] else { return }
let location = Location(identifier: locationIdentifier)
_ = location.initCustomers().then{_ in
self.delegate?.didEnterLocation(location)
}
}
@objc func handleOutsideRegion(_ identifier:String) {
guard let locationIdentifier = self.locationIdentifierProvider.locationIdentifierPerDeviceIdentifier[identifier] else { return }
let location = Location(identifier: locationIdentifier)
self.delegate?.didExitLocation(location)
}
// MARK: ESTBeaconManagerDelegate
func monitoringManager(_ manager: ESTMonitoringV2Manager, didFailWithError error: Error) {
print(error.localizedDescription)
}
func monitoringManager(_ manager: ESTMonitoringV2Manager, didEnterDesiredRangeOfBeaconWithIdentifier identifier: String) {
handleInsideRegion(identifier)
}
func monitoringManager(_ manager: ESTMonitoringV2Manager, didExitDesiredRangeOfBeaconWithIdentifier identifier: String) {
handleOutsideRegion(identifier)
}
func monitoringManager(_ manager: ESTMonitoringV2Manager, didDetermineInitialState state: ESTMonitoringState, forBeaconWithIdentifier identifier: String) {
switch state {
case .insideZone : handleInsideRegion(identifier)
default : return
}
}
}
| mit | ed78c6ab252e20eb162448ed938118f0 | 35.786517 | 169 | 0.684484 | 5.376026 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/CollectionKit-master/Examples/ExampleView.swift | 2 | 1874 | //
// ExampleView.swift
// CollectionKitExample
//
// Created by Luke Zhao on 2017-09-04.
// Copyright © 2017 lkzhao. All rights reserved.
//
import UIKit
import CollectionKit
class ExampleView: UIView {
let titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = .boldSystemFont(ofSize: 24)
return titleLabel
}()
let cardView: UIView = {
let cardView = UIView()
cardView.backgroundColor = .white
cardView.layer.cornerRadius = 8
cardView.layer.shadowColor = UIColor.black.cgColor
cardView.layer.shadowOffset = CGSize(width: 0, height: 12)
cardView.layer.shadowRadius = 10
cardView.layer.shadowOpacity = 0.1
cardView.layer.borderColor = UIColor(white: 0, alpha: 0.1).cgColor
cardView.layer.borderWidth = 0.5
return cardView
}()
private var contentVC: UIViewController?
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(titleLabel)
addSubview(cardView)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let size = titleLabel.sizeThatFits(bounds.size)
titleLabel.frame = CGRect(origin: CGPoint(x: 0, y: 10), size: size)
let labelHeight = titleLabel.frame.maxY + 10
cardView.frame = CGRect(x: 0, y: labelHeight, width: bounds.width, height: bounds.height - labelHeight)
contentVC?.view.frame = cardView.bounds
}
func populate(title: String,
contentViewControllerType: UIViewController.Type) {
titleLabel.text = title
contentVC?.view.removeFromSuperview()
contentVC = contentViewControllerType.init()
let contentView = contentVC!.view!
contentView.clipsToBounds = true
contentView.layer.cornerRadius = 8
cardView.addSubview(contentView)
setNeedsLayout()
}
}
| mit | 853c4b00762f91519908d066565bc1fa | 27.815385 | 107 | 0.703684 | 4.345708 | false | false | false | false |
optimizely/swift-sdk | Sources/Utils/ThreadSafeLogger.swift | 1 | 1442 | //
// Copyright 2022, 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
class ThreadSafeLogger {
// thread-safe lazy logger (after HandlerRegisterService ready)
// - "lazy var" is not thread-safe
// - call this thread-safe version when required to be lazy-init. logger should be initialized before (for customiziation) or at the same time with OptimizelyClient (so HandlerRegisterService is not ready yet).
// - [DefaultDatafileHandler, DefaultEventDispatcher, DefaultDecisionService, DefaultBucketer]
private var instance: OPTLogger?
private let lock = DispatchQueue(label: "logger")
var logger: OPTLogger {
var result: OPTLogger?
lock.sync {
if instance == nil {
instance = OPTLoggerFactory.getLogger()
}
result = instance
}
return result!
}
}
| apache-2.0 | 132fa2ae7793dbfe9bc2832dd377c7ad | 35.05 | 214 | 0.692788 | 4.592357 | false | false | false | false |
zhuxietong/Eelay | Sources/Eelay/object/Array+extention.swift | 1 | 2759 | //
// File.swift
//
//
// Created by zhu xietong on 2020/3/21.
//
import Foundation
#if canImport(UIKit)
import UIKit
#endif
public class EeArrayGenerator<T>:IteratorProtocol
{
public typealias Element = T
var list:NSArray
var validate_list = NSMutableArray()
var count:Int = 0
init(list:NSArray)
{
self.list = list
validate_list.removeAllObjects()
for obj in self.list
{
if let _ = obj as? T
{
validate_list.add(obj)
}
}
self.count = 0
}
public func next() -> Element? {
if self.count < self.validate_list.count
{
let one = self.validate_list[count] as? Element
count += 1
return one
}
self.count = 0
return nil
}
}
open class Each<T> :Sequence{
public typealias Iterator = EeArrayGenerator<T>
public var list:NSArray
open func makeIterator() -> Iterator {
return EeArrayGenerator(list: list)
}
public init(_ list:NSArray)
{
self.list = list
}
}
extension NSArray
{
public func reverse_list<T>(_ block:(T,Int)->Void) {
let list = self.reversed()
var index:Int = 0
for one in Each<T>(list as NSArray)
{
block(one,index)
index += 1
}
}
public typealias Finish = ()->Void
public func forEach<T>(_ body: (T,Int,Finish) throws -> Void) rethrows {
var index:Int = 0
var finish = false
for one in Each<T>(self)
{
let finishBlock = {() in
finish = true
}
try body(one,index,finishBlock)
if (finish){
return
}
index += 1
}
}
public func list<T>(_ block:(T,Int)->Void)
{
var index:Int = 0
for one in Each<T>(self)
{
block(one,index)
index += 1
}
}
public func listObj<T>(_ block:(T)->Void)
{
for one in Each<T>(self)
{
block(one)
}
}
}
extension Array{
public func new<T,Obj>(_ creator:(Int,Obj)throws->T) ->[T]{
var new_list = [T]()
for (index,one) in self.enumerated()
{
if let o = one as? Obj
{
do {
let one = try creator(index,o)
new_list.append(one)
} catch {
print(error)
}
}
}
return new_list
}
}
| mit | 2b5f94d5208e093061a8a496ff4042ba | 17.641892 | 76 | 0.446176 | 4.317684 | false | false | false | false |
lfaoro/Cast | Carthage/Checkouts/RxSwift/RxSwift/Observables/Observable+Single.swift | 1 | 2614 | //
// Observable+Single.swift
// Rx
//
// Created by Krunoslav Zaher on 2/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// distinct until changed
extension ObservableType where E: Equatable {
public func distinctUntilChanged()
-> Observable<E> {
return self.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) })
}
}
extension ObservableType {
public func distinctUntilChanged<K: Equatable>(keySelector: (E) throws -> K)
-> Observable<E> {
return self.distinctUntilChanged(keySelector, comparer: { $0 == $1 })
}
public func distinctUntilChanged(comparer: (lhs: E, rhs: E) throws -> Bool)
-> Observable<E> {
return self.distinctUntilChanged({ $0 }, comparer: comparer)
}
public func distinctUntilChanged<K>(keySelector: (E) throws -> K, comparer: (lhs: K, rhs: K) throws -> Bool)
-> Observable<E> {
return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer)
}
}
// do
extension ObservableType {
public func doOn(eventHandler: (Event<E>) throws -> Void)
-> Observable<E> {
return Do(source: self.asObservable(), eventHandler: eventHandler)
}
public func doOn(next next: (E throws -> Void)? = nil, error: (ErrorType throws -> Void)? = nil, completed: (() throws -> Void)? = nil, disposed: (() throws -> Void)? = nil)
-> Observable<E> {
return Do(source: self.asObservable()) { e in
switch e {
case .Next(let element):
try next?(element)
case .Error(let e):
try error?(e)
try disposed?()
case .Completed:
try completed?()
try disposed?()
}
}
}
}
// startWith
extension ObservableType {
public func startWith(elements: E ...)
-> Observable<E> {
return StartWith(source: self.asObservable(), elements: elements)
}
}
// retry
extension ObservableType {
public func retry() -> Observable<E> {
return CatchSequence(sources: InifiniteSequence(repeatedValue: self.asObservable()))
}
public func retry(retryCount: Int)
-> Observable<E> {
return CatchSequence(sources: Repeat(count: retryCount, repeatedValue: self.asObservable()))
}
}
// scan
extension ObservableType {
public func scan<A>(seed: A, accumulator: (A, E) throws -> A)
-> Observable<A> {
return Scan(source: self.asObservable(), seed: seed, accumulator: accumulator)
}
} | mit | dc32e21e75ea8925f8b25ea7f74e0839 | 27.11828 | 177 | 0.60329 | 4.292282 | false | false | false | false |
ReactiveCocoa/ReactiveSwift | Sources/SignalProducer.swift | 1 | 138301 | import Dispatch
import Foundation
/// A SignalProducer creates Signals that can produce values of type `Value`
/// and/or fail with errors of type `Error`. If no failure should be possible,
/// `Never` can be specified for `Error`.
///
/// SignalProducers can be used to represent operations or tasks, like network
/// requests, where each invocation of `start()` will create a new underlying
/// operation. This ensures that consumers will receive the results, versus a
/// plain Signal, where the results might be sent before any observers are
/// attached.
///
/// Because of the behavior of `start()`, different Signals created from the
/// producer may see a different version of Events. The Events may arrive in a
/// different order between Signals, or the stream might be completely
/// different!
public struct SignalProducer<Value, Error: Swift.Error> {
public typealias ProducedSignal = Signal<Value, Error>
/// `core` is the actual implementation for this `SignalProducer`. It is responsible
/// of:
///
/// 1. handling the single-observer `start`; and
/// 2. building `Signal`s on demand via its `makeInstance()` method, which produces a
/// `Signal` with the associated side effect and interrupt handle.
fileprivate let core: SignalProducerCore<Value, Error>
/// Convert an entity into its equivalent representation as `SignalProducer`.
///
/// - parameters:
/// - base: The entity to convert from.
public init<T: SignalProducerConvertible>(_ base: T) where T.Value == Value, T.Error == Error {
self = base.producer
}
/// Initializes a `SignalProducer` that will emit the same events as the
/// given signal.
///
/// If the Disposable returned from `start()` is disposed or a terminating
/// event is sent to the observer, the given signal will be disposed.
///
/// - parameters:
/// - signal: A signal to observe after starting the producer.
public init(_ signal: Signal<Value, Error>) {
self.init { observer, lifetime in
lifetime += signal.observe(observer)
}
}
/// Initialize a `SignalProducer` which invokes the supplied starting side
/// effect once upon the creation of every produced `Signal`, or in other
/// words, for every invocation of `startWithSignal(_:)`, `start(_:)` and
/// their convenience shorthands.
///
/// The supplied starting side effect would be given (1) an input `Observer`
/// to emit events to the produced `Signal`; and (2) a `Lifetime` to bind
/// resources to the lifetime of the produced `Signal`.
///
/// The `Lifetime` of a produced `Signal` ends when: (1) a terminal event is
/// sent to the input `Observer`; or (2) when the produced `Signal` is
/// interrupted via the disposable yielded at the starting call.
///
/// - note: The provided input observer is thread safe.
///
/// - parameters:
/// - startHandler: The starting side effect.
public init(_ startHandler: @escaping (Signal<Value, Error>.Observer, Lifetime) -> Void) {
self.init(SignalCore {
let disposable = CompositeDisposable()
let (signal, observer) = Signal<Value, Error>.pipe(disposable: disposable)
let observerDidSetup = { startHandler(observer, Lifetime(disposable)) }
let interruptHandle = AnyDisposable(observer.sendInterrupted)
return SignalProducerCore.Instance(signal: signal,
observerDidSetup: observerDidSetup,
interruptHandle: interruptHandle)
})
}
/// Initialize a `SignalProducer` which invokes the supplied starting side
/// effect once upon the creation of every produced `Signal`, or in other
/// words, for every invocation of `startWithSignal(_:)`, `start(_:)` and
/// their convenience shorthands.
///
/// The supplied starting side effect would be given (1) an input `Observer`
/// to emit events to the produced `Signal`; and (2) a `Lifetime` to bind
/// resources to the lifetime of the produced `Signal`.
///
/// The `Lifetime` of a produced `Signal` ends when: (1) a terminal event is
/// sent to the input `Observer`; or (2) when the produced `Signal` is
/// interrupted via the disposable yielded at the starting call.
///
/// - warning: Like `Signal.unserialized(_:)`, the provided input observer **is not thread safe**.
/// Mutual exclusion is assumed to be enforced among the callers.
///
/// - parameters:
/// - startHandler: The starting side effect.
public static func unserialized(
_ startHandler: @escaping (Signal<Value, Error>.Observer, Lifetime) -> Void
) -> SignalProducer<Value, Error> {
return self.init(SignalCore {
let disposable = CompositeDisposable()
let (signal, observer) = Signal<Value, Error>.unserializedPipe(disposable: disposable)
let observerDidSetup = { startHandler(observer, Lifetime(disposable)) }
let interruptHandle = AnyDisposable(observer.sendInterrupted)
return SignalProducerCore.Instance(signal: signal,
observerDidSetup: observerDidSetup,
interruptHandle: interruptHandle)
})
}
/// Create a SignalProducer.
///
/// - parameters:
/// - core: The `SignalProducer` core.
internal init(_ core: SignalProducerCore<Value, Error>) {
self.core = core
}
/// Creates a producer for a `Signal` that will immediately send one value
/// then complete.
///
/// - parameters:
/// - value: A value that should be sent by the `Signal` in a `value`
/// event.
public init(value: Value) {
self.init(GeneratorCore { observer, _ in
observer.send(value: value)
observer.sendCompleted()
})
}
/// Creates a producer for a `Signal` that immediately sends one value, then
/// completes.
///
/// This initializer differs from `init(value:)` in that its sole `value`
/// event is constructed lazily by invoking the supplied `action` when
/// the `SignalProducer` is started.
///
/// - parameters:
/// - action: A action that yields a value to be sent by the `Signal` as
/// a `value` event.
public init(_ action: @escaping () -> Value) {
self.init(GeneratorCore { observer, _ in
observer.send(value: action())
observer.sendCompleted()
})
}
/// Create a `SignalProducer` that will attempt the given operation once for
/// each invocation of `start()`.
///
/// Upon success, the started signal will send the resulting value then
/// complete. Upon failure, the started signal will fail with the error that
/// occurred.
///
/// - parameters:
/// - action: A closure that returns instance of `Result`.
public init(_ action: @escaping () -> Result<Value, Error>) {
self.init(GeneratorCore { observer, _ in
switch action() {
case let .success(value):
observer.send(value: value)
observer.sendCompleted()
case let .failure(error):
observer.send(error: error)
}
})
}
/// Creates a producer for a `Signal` that will immediately fail with the
/// given error.
///
/// - parameters:
/// - error: An error that should be sent by the `Signal` in a `failed`
/// event.
public init(error: Error) {
self.init(GeneratorCore { observer, _ in observer.send(error: error) })
}
/// Creates a producer for a Signal that will immediately send one value
/// then complete, or immediately fail, depending on the given Result.
///
/// - parameters:
/// - result: A `Result` instance that will send either `value` event if
/// `result` is `success`ful or `failed` event if `result` is a
/// `failure`.
public init(result: Result<Value, Error>) {
switch result {
case let .success(value):
self.init(value: value)
case let .failure(error):
self.init(error: error)
}
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - values: A sequence of values that a `Signal` will send as separate
/// `value` events and then complete.
public init<S: Sequence>(_ values: S) where S.Iterator.Element == Value {
self.init(GeneratorCore(isDisposable: true) { observer, disposable in
for value in values {
observer.send(value: value)
if disposable.isDisposed {
break
}
}
observer.sendCompleted()
})
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - first: First value for the `Signal` to send.
/// - second: Second value for the `Signal` to send.
/// - tail: Rest of the values to be sent by the `Signal`.
public init(values first: Value, _ second: Value, _ tail: Value...) {
self.init([ first, second ] + tail)
}
/// A producer for a Signal that immediately completes without sending any values.
public static var empty: SignalProducer {
return SignalProducer(GeneratorCore { observer, _ in observer.sendCompleted() })
}
/// A producer for a Signal that immediately interrupts when started, without
/// sending any values.
internal static var interrupted: SignalProducer {
return SignalProducer(GeneratorCore { observer, _ in observer.sendInterrupted() })
}
/// A producer for a Signal that never sends any events to its observers.
public static var never: SignalProducer {
return self.init { observer, lifetime in
lifetime.observeEnded { _ = observer }
}
}
/// Create a `Signal` from `self`, pass it into the given closure, and start the
/// associated work on the produced `Signal` as the closure returns.
///
/// - parameters:
/// - setup: A closure to be invoked before the work associated with the produced
/// `Signal` commences. Both the produced `Signal` and an interrupt handle
/// of the signal would be passed to the closure.
/// - returns: The return value of the given setup closure.
@discardableResult
public func startWithSignal<Result>(_ setup: (_ signal: Signal<Value, Error>, _ interruptHandle: Disposable) -> Result) -> Result {
let instance = core.makeInstance()
let result = setup(instance.signal, instance.interruptHandle)
if !instance.interruptHandle.isDisposed {
instance.observerDidSetup()
}
return result
}
}
/// `SignalProducerCore` is the actual implementation of a `SignalProducer`.
///
/// While `SignalProducerCore` still requires all subclasses to be able to produce
/// instances of `Signal`s, the abstraction enables room of optimization for common
/// compositional and single-observer use cases.
internal class SignalProducerCore<Value, Error: Swift.Error> {
/// `Instance` represents an instance of `Signal` created from a
/// `SignalProducer`. In addition to the `Signal` itself, it includes also the
/// starting side effect and an interrupt handle for this particular instance.
///
/// It is the responsibility of the `Instance` consumer to ensure the
/// starting side effect is invoked exactly once, and is invoked after observations
/// has properly setup.
struct Instance {
let signal: Signal<Value, Error>
let observerDidSetup: () -> Void
let interruptHandle: Disposable
}
func makeInstance() -> Instance {
fatalError()
}
/// Start the producer with an observer created by the given generator.
///
/// The created observer **must** manaully dispose of the given upstream interrupt
/// handle iff it performs any event transformation that might result in a terminal
/// event.
///
/// - parameters:
/// - generator: The closure to generate an observer.
///
/// - returns: A disposable to interrupt the started producer instance.
@discardableResult
func start(_ generator: (_ upstreamInterruptHandle: Disposable) -> Signal<Value, Error>.Observer) -> Disposable {
fatalError()
}
/// Perform an action upon every event from `self`. The action may generate zero or
/// more events.
///
/// - precondition: The action must be synchronous.
///
/// - parameters:
/// - transform: A closure that creates the said action from the given event
/// closure.
///
/// - returns: A producer that forwards events yielded by the action.
internal func flatMapEvent<U, E>(_ transform: @escaping Signal<Value, Error>.Event.Transformation<U, E>) -> SignalProducer<U, E> {
return SignalProducer<U, E>(TransformerCore(source: self, transform: transform))
}
}
private final class SignalCore<Value, Error: Swift.Error>: SignalProducerCore<Value, Error> {
private let _make: () -> Instance
init(_ action: @escaping () -> Instance) {
self._make = action
}
@discardableResult
override func start(_ generator: (Disposable) -> Signal<Value, Error>.Observer) -> Disposable {
let instance = makeInstance()
instance.signal.observe(generator(instance.interruptHandle))
instance.observerDidSetup()
return instance.interruptHandle
}
override func makeInstance() -> Instance {
return _make()
}
}
/// `TransformerCore` composes event transforms, and is intended to back synchronous
/// `SignalProducer` operators in general via the core-level operator `Core.flatMapEvent`.
///
/// It takes advantage of the deferred, single-observer nature of SignalProducer. For
/// example, when we do:
///
/// ```
/// upstream.map(transform).compactMap(filteringTransform).start()
/// ```
///
/// It is contractually guaranteed that these operators would always end up producing a
/// chain of streams, each with a _single and persistent_ observer to its upstream. The
/// multicasting & detaching capabilities of Signal is useless in these scenarios.
///
/// So TransformerCore builds on top of this very fact, and composes directly at the
/// level of event transforms, without any `Signal` in between.
///
/// - note: This core does not use `Signal` unless it is requested via `makeInstance()`.
private final class TransformerCore<Value, Error: Swift.Error, SourceValue, SourceError: Swift.Error>: SignalProducerCore<Value, Error> {
private let source: SignalProducerCore<SourceValue, SourceError>
private let transform: Signal<SourceValue, SourceError>.Event.Transformation<Value, Error>
init(source: SignalProducerCore<SourceValue, SourceError>, transform: @escaping Signal<SourceValue, SourceError>.Event.Transformation<Value, Error>) {
self.source = source
self.transform = transform
}
@discardableResult
internal override func start(_ generator: (Disposable) -> Signal<Value, Error>.Observer) -> Disposable {
// Collect all resources related to this transformed producer instance.
let disposables = CompositeDisposable()
source.start { upstreamInterrupter in
// Backpropagate the terminal event, if any, to the upstream.
disposables += upstreamInterrupter
var hasDeliveredTerminalEvent = false
// Generate the output sink that receives transformed output.
let output = generator(disposables)
// Wrap the output sink to enforce the "no event beyond the terminal
// event" contract, and the disposal upon termination.
let wrappedOutput = Signal<Value, Error>.Observer { event in
if !hasDeliveredTerminalEvent {
output.send(event)
if event.isTerminating {
// Mark that a terminal event has already been
// delivered.
hasDeliveredTerminalEvent = true
// Disposed of all associated resources, and notify
// the upstream too.
disposables.dispose()
}
}
}
// Create an input sink whose events would go through the given
// event transformation, and have the resulting events propagated
// to the output sink above.
let input = transform(wrappedOutput, Lifetime(disposables))
// Return the input sink to the source producer core.
return input.assumeUnboundDemand()
}
// Manual interruption disposes of `disposables`, which in turn notifies
// the event transformation side effects, and the upstream instance.
return disposables
}
internal override func flatMapEvent<U, E>(_ transform: @escaping Signal<Value, Error>.Event.Transformation<U, E>) -> SignalProducer<U, E> {
return SignalProducer<U, E>(TransformerCore<U, E, SourceValue, SourceError>(source: source) { [innerTransform = self.transform] action, lifetime in
return innerTransform(transform(action, lifetime), lifetime)
})
}
internal override func makeInstance() -> Instance {
let disposable = SerialDisposable()
// The Event contract requires that event is serial, which `SignalProducer` adheres to. So it is unnecessary for
// us to add another level of serialization, since we would have "inherited" serialization as an observer.
let (signal, observer) = Signal<Value, Error>.unserializedPipe(disposable: disposable)
func observerDidSetup() {
start { interrupter in
disposable.inner = interrupter
return observer
}
}
return Instance(signal: signal,
observerDidSetup: observerDidSetup,
interruptHandle: disposable)
}
}
/// `GeneratorCore` wraps a generator closure that would be invoked upon a produced
/// `Signal` when started. The generator closure is passed only the input observer and the
/// cancel disposable.
///
/// It is intended for constant `SignalProducers`s that synchronously emits all events
/// without escaping the `Observer`.
///
/// - note: This core does not use `Signal` unless it is requested via `makeInstance()`.
private final class GeneratorCore<Value, Error: Swift.Error>: SignalProducerCore<Value, Error> {
private let isDisposable: Bool
private let generator: (Signal<Value, Error>.Observer, Disposable) -> Void
init(isDisposable: Bool = false, _ generator: @escaping (Signal<Value, Error>.Observer, Disposable) -> Void) {
self.isDisposable = isDisposable
self.generator = generator
}
@discardableResult
internal override func start(_ observerGenerator: (Disposable) -> Signal<Value, Error>.Observer) -> Disposable {
// Object allocation is a considerable overhead. So unless the core is configured
// to be disposable, we would reuse the already-disposed, shared `NopDisposable`.
let d: Disposable = isDisposable ? _SimpleDisposable() : NopDisposable.shared
generator(observerGenerator(d), d)
return d
}
internal override func makeInstance() -> Instance {
let (signal, observer) = Signal<Value, Error>.pipe()
let d = AnyDisposable(observer.sendInterrupted)
return Instance(signal: signal,
observerDidSetup: { self.generator(observer, d) },
interruptHandle: d)
}
}
extension SignalProducer where Error == Never {
/// Creates a producer for a `Signal` that will immediately send one value
/// then complete.
///
/// - parameters:
/// - value: A value that should be sent by the `Signal` in a `value`
/// event.
public init(value: Value) {
self.init(GeneratorCore { observer, _ in
observer.send(value: value)
observer.sendCompleted()
})
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - values: A sequence of values that a `Signal` will send as separate
/// `value` events and then complete.
public init<S: Sequence>(_ values: S) where S.Iterator.Element == Value {
self.init(GeneratorCore(isDisposable: true) { observer, disposable in
for value in values {
observer.send(value: value)
if disposable.isDisposed {
break
}
}
observer.sendCompleted()
})
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - first: First value for the `Signal` to send.
/// - second: Second value for the `Signal` to send.
/// - tail: Rest of the values to be sent by the `Signal`.
public init(values first: Value, _ second: Value, _ tail: Value...) {
self.init([ first, second ] + tail)
}
}
extension SignalProducer where Error == Swift.Error {
/// Create a `SignalProducer` that will attempt the given failable operation once for
/// each invocation of `start()`.
///
/// Upon success, the started producer will send the resulting value then
/// complete. Upon failure, the started signal will fail with the error that
/// occurred.
///
/// - parameters:
/// - operation: A failable closure.
public init(_ action: @escaping () throws -> Value) {
self.init {
return Result {
return try action()
}
}
}
}
#if swift(>=5.7)
/// Represents reactive primitives that can be represented by `SignalProducer`.
public protocol SignalProducerConvertible<Value, Error> {
/// The type of values being sent by `self`.
associatedtype Value
/// The type of error that can occur on `self`.
associatedtype Error: Swift.Error
/// The `SignalProducer` representation of `self`.
var producer: SignalProducer<Value, Error> { get }
}
#else
/// Represents reactive primitives that can be represented by `SignalProducer`.
public protocol SignalProducerConvertible {
/// The type of values being sent by `self`.
associatedtype Value
/// The type of error that can occur on `self`.
associatedtype Error: Swift.Error
/// The `SignalProducer` representation of `self`.
var producer: SignalProducer<Value, Error> { get }
}
#endif
#if swift(>=5.7)
/// A protocol for constraining associated types to `SignalProducer`.
public protocol SignalProducerProtocol<Value, Error> {
/// The type of values being sent by `self`.
associatedtype Value
/// The type of error that can occur on `self`.
associatedtype Error: Swift.Error
/// The materialized `self`.
var producer: SignalProducer<Value, Error> { get }
}
#else
/// A protocol for constraining associated types to `SignalProducer`.
public protocol SignalProducerProtocol {
/// The type of values being sent by `self`.
associatedtype Value
/// The type of error that can occur on `self`.
associatedtype Error: Swift.Error
/// The materialized `self`.
var producer: SignalProducer<Value, Error> { get }
}
#endif
extension SignalProducer: SignalProducerConvertible, SignalProducerProtocol {
public var producer: SignalProducer {
return self
}
}
extension SignalProducer {
/// Create a `Signal` from `self`, and observe it with the given observer.
///
/// - parameters:
/// - observer: An observer to attach to the produced `Signal`.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func start(_ observer: Signal<Value, Error>.Observer = .init()) -> Disposable {
return core.start { _ in observer }
}
/// Create a `Signal` from `self`, and observe the `Signal` for all events
/// being emitted.
///
/// - parameters:
/// - action: A closure to be invoked with every event from `self`.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func start(_ action: @escaping Signal<Value, Error>.Observer.Action) -> Disposable {
return start(Signal.Observer(action))
}
/// Create a `Signal` from `self`, and observe the `Signal` for all values being
/// emitted, and if any, its failure.
///
/// - parameters:
/// - action: A closure to be invoked with values from `self`, or the propagated
/// error should any `failed` event is emitted.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithResult(_ action: @escaping (Result<Value, Error>) -> Void) -> Disposable {
return start(
Signal.Observer(
value: { action(.success($0)) },
failed: { action(.failure($0)) }
)
)
}
/// Create a `Signal` from `self`, and observe its completion.
///
/// - parameters:
/// - action: A closure to be invoked when a `completed` event is emitted.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithCompleted(_ action: @escaping () -> Void) -> Disposable {
return start(Signal.Observer(completed: action))
}
/// Create a `Signal` from `self`, and observe its failure.
///
/// - parameters:
/// - action: A closure to be invoked with the propagated error, should any
/// `failed` event is emitted.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithFailed(_ action: @escaping (Error) -> Void) -> Disposable {
return start(Signal.Observer(failed: action))
}
/// Create a `Signal` from `self`, and observe its interruption.
///
/// - parameters:
/// - action: A closure to be invoked when an `interrupted` event is emitted.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithInterrupted(_ action: @escaping () -> Void) -> Disposable {
return start(Signal.Observer(interrupted: action))
}
/// Creates a `Signal` from the producer.
///
/// This is equivalent to `SignalProducer.startWithSignal`, but it has
/// the downside that any values emitted synchronously upon starting will
/// be missed by the observer, because it won't be able to subscribe in time.
/// That's why we don't want this method to be exposed as `public`,
/// but it's useful internally.
internal func startAndRetrieveSignal() -> Signal<Value, Error> {
var result: Signal<Value, Error>!
self.startWithSignal { signal, _ in
result = signal
}
return result
}
/// Create a `Signal` from `self` in the manner described by `startWithSignal`, and
/// put the interrupt handle into the given `CompositeDisposable`.
///
/// - parameters:
/// - lifetime: The `Lifetime` the interrupt handle to be added to.
/// - setup: A closure that accepts the produced `Signal`.
fileprivate func startWithSignal(during lifetime: Lifetime, setup: (Signal<Value, Error>) -> Void) {
startWithSignal { signal, interruptHandle in
lifetime += interruptHandle
setup(signal)
}
}
}
extension SignalProducer where Error == Never {
/// Create a `Signal` from `self`, and observe the `Signal` for all values being
/// emitted.
///
/// - parameters:
/// - action: A closure to be invoked with values from the produced `Signal`.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithValues(_ action: @escaping (Value) -> Void) -> Disposable {
return start(Signal.Observer(value: action))
}
}
extension SignalProducer {
/// Lift an unary Signal operator to operate upon SignalProducers instead.
///
/// In other words, this will create a new `SignalProducer` which will apply
/// the given `Signal` operator to _every_ created `Signal`, just as if the
/// operator had been applied to each `Signal` yielded from `start()`.
///
/// - parameters:
/// - transform: An unary operator to lift.
///
/// - returns: A signal producer that applies signal's operator to every
/// created signal.
public func lift<U, F>(_ transform: @escaping (Signal<Value, Error>) -> Signal<U, F>) -> SignalProducer<U, F> {
// The Event contract requires that event is serial, which `Signal` adheres to. So it is unnecessary for us to
// add another level of serialization, since we would have "inherited" serialization as an observer.
return SignalProducer<U, F>.unserialized { observer, lifetime in
self.startWithSignal { signal, interrupter in
lifetime += interrupter
lifetime += transform(signal).observe(observer)
}
}
}
/// Lift a binary Signal operator to operate upon SignalProducers.
///
/// The left producer would first be started. When both producers are synchronous this
/// order can be important depending on the operator to generate correct results.
///
/// - returns: A factory that creates a SignalProducer with the given operator
/// applied. `self` would be the LHS, and the factory input would
/// be the RHS.
internal func liftLeft<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return { right in
return SignalProducer<V, G> { observer, lifetime in
right.startWithSignal { rightSignal, rightInterrupter in
lifetime += rightInterrupter
self.startWithSignal { leftSignal, leftInterrupter in
lifetime += leftInterrupter
lifetime += transform(leftSignal)(rightSignal).observe(observer)
}
}
}
}
}
/// Lift a binary Signal operator to operate upon SignalProducers.
///
/// The right producer would first be started. When both producers are synchronous
/// this order can be important depending on the operator to generate correct results.
///
/// - returns: A factory that creates a SignalProducer with the given operator
/// applied. `self` would be the LHS, and the factory input would
/// be the RHS.
internal func liftRight<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return { right in
return SignalProducer<V, G> { observer, lifetime in
self.startWithSignal { leftSignal, leftInterrupter in
lifetime += leftInterrupter
right.startWithSignal { rightSignal, rightInterrupter in
lifetime += rightInterrupter
lifetime += transform(leftSignal)(rightSignal).observe(observer)
}
}
}
}
}
/// Lift a binary Signal operator to operate upon SignalProducers instead.
///
/// In other words, this will create a new `SignalProducer` which will apply
/// the given `Signal` operator to _every_ `Signal` created from the two
/// producers, just as if the operator had been applied to each `Signal`
/// yielded from `start()`.
///
/// - note: starting the returned producer will start the receiver of the
/// operator, which may not be adviseable for some operators.
///
/// - parameters:
/// - transform: A binary operator to lift.
///
/// - returns: A binary operator that operates on two signal producers.
public func lift<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return liftRight(transform)
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>) -> Void) {
b.startWithSignal(during: lifetime) { b in
a.startWithSignal(during: lifetime) { setup($0, b) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>) -> Void) {
c.startWithSignal(during: lifetime) { c in
flattenStart(lifetime, a, b) { setup($0, $1, c) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>) -> Void) {
d.startWithSignal(during: lifetime) { d in
flattenStart(lifetime, a, b, c) { setup($0, $1, $2, d) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>) -> Void) {
e.startWithSignal(during: lifetime) { e in
flattenStart(lifetime, a, b, c, d) { setup($0, $1, $2, $3, e) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>) -> Void) {
f.startWithSignal(during: lifetime) { f in
flattenStart(lifetime, a, b, c, d, e) { setup($0, $1, $2, $3, $4, f) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, G, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>, Signal<G, Error>) -> Void) {
g.startWithSignal(during: lifetime) { g in
flattenStart(lifetime, a, b, c, d, e, f) { setup($0, $1, $2, $3, $4, $5, g) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, G, H, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>, Signal<G, Error>, Signal<H, Error>) -> Void) {
h.startWithSignal(during: lifetime) { h in
flattenStart(lifetime, a, b, c, d, e, f, g) { setup($0, $1, $2, $3, $4, $5, $6, h) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, G, H, I, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>, Signal<G, Error>, Signal<H, Error>, Signal<I, Error>) -> Void) {
i.startWithSignal(during: lifetime) { i in
flattenStart(lifetime, a, b, c, d, e, f, g, h) { setup($0, $1, $2, $3, $4, $5, $6, $7, i) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, G, H, I, J, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ j: SignalProducer<J, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>, Signal<G, Error>, Signal<H, Error>, Signal<I, Error>, Signal<J, Error>) -> Void) {
j.startWithSignal(during: lifetime) { j in
flattenStart(lifetime, a, b, c, d, e, f, g, h, i) { setup($0, $1, $2, $3, $4, $5, $6, $7, $8, j) }
}
}
extension SignalProducer {
/// Map each value in the producer to a new value.
///
/// - parameters:
/// - transform: A closure that accepts a value and returns a different
/// value.
///
/// - returns: A signal producer that, when started, will send a mapped
/// value of `self.`
public func map<U>(_ transform: @escaping (Value) -> U) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.map(transform))
}
/// Map each value in the producer to a new constant value.
///
/// - parameters:
/// - value: A new value.
///
/// - returns: A signal producer that, when started, will send a mapped
/// value of `self`.
public func map<U>(value: U) -> SignalProducer<U, Error> {
return lift { $0.map(value: value) }
}
/// Map each value in the producer to a new value by applying a key path.
///
/// - parameters:
/// - keyPath: A key path relative to the producer's `Value` type.
///
/// - returns: A producer that will send new values.
public func map<U>(_ keyPath: KeyPath<Value, U>) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.compactMap { $0[keyPath: keyPath] })
}
/// Map errors in the producer to a new error.
///
/// - parameters:
/// - transform: A closure that accepts an error object and returns a
/// different error.
///
/// - returns: A producer that emits errors of new type.
public func mapError<F>(_ transform: @escaping (Error) -> F) -> SignalProducer<Value, F> {
return core.flatMapEvent(Signal.Event.mapError(transform))
}
/// Maps each value in the producer to a new value, lazily evaluating the
/// supplied transformation on the specified scheduler.
///
/// - important: Unlike `map`, there is not a 1-1 mapping between incoming
/// values, and values sent on the returned producer. If
/// `scheduler` has not yet scheduled `transform` for
/// execution, then each new value will replace the last one as
/// the parameter to `transform` once it is finally executed.
///
/// - parameters:
/// - transform: The closure used to obtain the returned value from this
/// producer's underlying value.
///
/// - returns: A producer that, when started, sends values obtained using
/// `transform` as this producer sends values.
public func lazyMap<U>(on scheduler: Scheduler, transform: @escaping (Value) -> U) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.lazyMap(on: scheduler, transform: transform))
}
/// Preserve only values which pass the given closure.
///
/// - parameters:
/// - isIncluded: A closure to determine whether a value from `self` should be
/// included in the produced `Signal`.
///
/// - returns: A producer that, when started, forwards the values passing the given
/// closure.
public func filter(_ isIncluded: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.filter(isIncluded))
}
/// Applies `transform` to values from the producer and forwards values with non `nil` results unwrapped.
/// - parameters:
/// - transform: A closure that accepts a value from the `value` event and
/// returns a new optional value.
///
/// - returns: A producer that will send new values, that are non `nil` after the transformation.
public func compactMap<U>(_ transform: @escaping (Value) -> U?) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.compactMap(transform))
}
/// Applies `transform` to values from the producer and forwards values with non `nil` results unwrapped.
/// - parameters:
/// - transform: A closure that accepts a value from the `value` event and
/// returns a new optional value.
///
/// - returns: A producer that will send new values, that are non `nil` after the transformation.
@available(*, deprecated, renamed: "compactMap")
public func filterMap<U>(_ transform: @escaping (Value) -> U?) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.compactMap(transform))
}
/// Yield the first `count` values from the input producer.
///
/// - precondition: `count` must be non-negative number.
///
/// - parameters:
/// - count: A number of values to take from the signal.
///
/// - returns: A producer that, when started, will yield the first `count`
/// values from `self`.
public func take(first count: Int) -> SignalProducer<Value, Error> {
guard count >= 1 else { return .interrupted }
return core.flatMapEvent(Signal.Event.take(first: count))
}
/// Yield an array of values when `self` completes.
///
/// - note: When `self` completes without collecting any value, it will send
/// an empty array of values.
///
/// - returns: A producer that, when started, will yield an array of values
/// when `self` completes.
public func collect() -> SignalProducer<[Value], Error> {
return core.flatMapEvent(Signal.Event.collect)
}
/// Yield an array of values until it reaches a certain count.
///
/// - precondition: `count` must be greater than zero.
///
/// - note: When the count is reached the array is sent and the signal
/// starts over yielding a new array of values.
///
/// - note: When `self` completes any remaining values will be sent, the
/// last array may not have `count` values. Alternatively, if were
/// not collected any values will sent an empty array of values.
///
/// - returns: A producer that, when started, collects at most `count`
/// values from `self`, forwards them as a single array and
/// completes.
public func collect(count: Int) -> SignalProducer<[Value], Error> {
return core.flatMapEvent(Signal.Event.collect(count: count))
}
/// Collect values from `self`, and emit them if the predicate passes.
///
/// When `self` completes any remaining values will be sent, regardless of the
/// collected values matching `shouldEmit` or not.
///
/// If `self` completes without having emitted any value, an empty array would be
/// emitted, followed by the completion of the produced `Signal`.
///
/// ````
/// let (producer, observer) = SignalProducer<Int, Never>.buffer(1)
///
/// producer
/// .collect { values in values.reduce(0, combine: +) == 8 }
/// .startWithValues { print($0) }
///
/// observer.send(value: 1)
/// observer.send(value: 3)
/// observer.send(value: 4)
/// observer.send(value: 7)
/// observer.send(value: 1)
/// observer.send(value: 5)
/// observer.send(value: 6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 3, 4]
/// // [7, 1]
/// // [5, 6]
/// ````
///
/// - parameters:
/// - shouldEmit: A closure to determine, when every time a new value is received,
/// whether the collected values should be emitted.
///
/// - returns: A producer of arrays of values, as instructed by the `shouldEmit`
/// closure.
public func collect(_ shouldEmit: @escaping (_ values: [Value]) -> Bool) -> SignalProducer<[Value], Error> {
return core.flatMapEvent(Signal.Event.collect(shouldEmit))
}
/// Collect values from `self`, and emit them if the predicate passes.
///
/// When `self` completes any remaining values will be sent, regardless of the
/// collected values matching `shouldEmit` or not.
///
/// If `self` completes without having emitted any value, an empty array would be
/// emitted, followed by the completion of the produced `Signal`.
///
/// ````
/// let (producer, observer) = SignalProducer<Int, Never>.buffer(1)
///
/// producer
/// .collect { values, value in value == 7 }
/// .startWithValues { print($0) }
///
/// observer.send(value: 1)
/// observer.send(value: 1)
/// observer.send(value: 7)
/// observer.send(value: 7)
/// observer.send(value: 5)
/// observer.send(value: 6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 1]
/// // [7]
/// // [7, 5, 6]
/// ````
///
/// - parameters:
/// - shouldEmit: A closure to determine, when every time a new value is received,
/// whether the collected values should be emitted. The new value
/// is **not** included in the collected values, and is included when
/// the next value is received.
///
/// - returns: A producer of arrays of values, as instructed by the `shouldEmit`
/// closure.
public func collect(_ shouldEmit: @escaping (_ collected: [Value], _ latest: Value) -> Bool) -> SignalProducer<[Value], Error> {
return core.flatMapEvent(Signal.Event.collect(shouldEmit))
}
/// Forward the latest values on `scheduler` every `interval`.
///
/// - note: If `self` terminates while values are being accumulated,
/// the behaviour will be determined by `discardWhenCompleted`.
/// If `true`, the values will be discarded and the returned producer
/// will terminate immediately.
/// If `false`, that values will be delivered at the next interval.
///
/// - parameters:
/// - interval: A repetition interval.
/// - scheduler: A scheduler to send values on.
/// - skipEmpty: Whether empty arrays should be sent if no values were
/// accumulated during the interval.
/// - discardWhenCompleted: A boolean to indicate if the latest unsent
/// values should be discarded on completion.
///
/// - returns: A producer that sends all values that are sent from `self`
/// at `interval` seconds apart.
public func collect(every interval: DispatchTimeInterval, on scheduler: DateScheduler, skipEmpty: Bool = false, discardWhenCompleted: Bool = true) -> SignalProducer<[Value], Error> {
return core.flatMapEvent(Signal.Event.collect(every: interval, on: scheduler, skipEmpty: skipEmpty, discardWhenCompleted: discardWhenCompleted))
}
/// Forward all events onto the given scheduler, instead of whichever
/// scheduler they originally arrived upon.
///
/// - parameters:
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that, when started, will yield `self` values on
/// provided scheduler.
public func observe(on scheduler: Scheduler) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.observe(on: scheduler))
}
/// Combine the latest value of the receiver with the latest value from the
/// given producer.
///
/// - note: The returned producer will not send a value until both inputs
/// have sent at least one value each.
///
/// - note: If either producer is interrupted, the returned producer will
/// also be interrupted.
///
/// - note: The returned producer will not complete until both inputs
/// complete.
///
/// - parameters:
/// - other: A producer to combine `self`'s value with.
///
/// - returns: A producer that, when started, will yield a tuple containing
/// values of `self` and given producer.
public func combineLatest<U>(with other: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> {
return SignalProducer.combineLatest(self, other)
}
/// Combine the latest value of the receiver with the latest value from the
/// given producer.
///
/// - note: The returned producer will not send a value until both inputs
/// have sent at least one value each.
///
/// - note: If either producer is interrupted, the returned producer will
/// also be interrupted.
///
/// - note: The returned producer will not complete until both inputs
/// complete.
///
/// - parameters:
/// - other: A producer to combine `self`'s value with.
///
/// - returns: A producer that, when started, will yield a tuple containing
/// values of `self` and given producer.
public func combineLatest<Other: SignalProducerConvertible>(with other: Other) -> SignalProducer<(Value, Other.Value), Error> where Other.Error == Error {
return combineLatest(with: other.producer)
}
/// Merge the given producer into a single `SignalProducer` that will emit all
/// values from both of them, and complete when all of them have completed.
///
/// - parameters:
/// - other: A producer to merge `self`'s value with.
///
/// - returns: A producer that sends all values of `self` and given producer.
public func merge(with other: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return SignalProducer.merge(self, other)
}
/// Merge the given producer into a single `SignalProducer` that will emit all
/// values from both of them, and complete when all of them have completed.
///
/// - parameters:
/// - other: A producer to merge `self`'s value with.
///
/// - returns: A producer that sends all values of `self` and given producer.
public func merge<Other: SignalProducerConvertible>(with other: Other) -> SignalProducer<Value, Error> where Other.Value == Value, Other.Error == Error {
return merge(with: other.producer)
}
/// Delay `value` and `completed` events by the given interval, forwarding
/// them on the given scheduler.
///
/// - note: `failed` and `interrupted` events are always scheduled
/// immediately.
///
/// - parameters:
/// - interval: Interval to delay `value` and `completed` events by.
/// - scheduler: A scheduler to deliver delayed events on.
///
/// - returns: A producer that, when started, will delay `value` and
/// `completed` events and will yield them on given scheduler.
public func delay(_ interval: TimeInterval, on scheduler: DateScheduler) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.delay(interval, on: scheduler))
}
/// Skip the first `count` values, then forward everything afterward.
///
/// - parameters:
/// - count: A number of values to skip.
///
/// - returns: A producer that, when started, will skip the first `count`
/// values, then forward everything afterward.
public func skip(first count: Int) -> SignalProducer<Value, Error> {
guard count != 0 else { return self }
return core.flatMapEvent(Signal.Event.skip(first: count))
}
/// Treats all Events from the input producer as plain values, allowing them
/// to be manipulated just like any other value.
///
/// In other words, this brings Events “into the monad.”
///
/// - note: When a Completed or Failed event is received, the resulting
/// producer will send the Event itself and then complete. When an
/// `interrupted` event is received, the resulting producer will
/// send the `Event` itself and then interrupt.
///
/// - returns: A producer that sends events as its values.
public func materialize() -> SignalProducer<ProducedSignal.Event, Never> {
return core.flatMapEvent(Signal.Event.materialize)
}
/// Treats all Results from the input producer as plain values, allowing them
/// to be manipulated just like any other value.
///
/// In other words, this brings Results “into the monad.”
///
/// - note: When a Failed event is received, the resulting producer will
/// send the `Result.failure` itself and then complete.
///
/// - returns: A producer that sends results as its values.
public func materializeResults() -> SignalProducer<Result<Value, Error>, Never> {
return core.flatMapEvent(Signal.Event.materializeResults)
}
/// Forward the latest value from `self` with the value from `sampler` as a
/// tuple, only when `sampler` sends a `value` event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A producer that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A producer that will send values from `self` and `sampler`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input producers have completed, or interrupt if
/// either input producer is interrupted.
public func sample<U>(with sampler: SignalProducer<U, Never>) -> SignalProducer<(Value, U), Error> {
return liftLeft(Signal.sample(with:))(sampler)
}
/// Forward the latest value from `self` with the value from `sampler` as a
/// tuple, only when `sampler` sends a `value` event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A producer that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A producer that will send values from `self` and `sampler`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input producers have completed, or interrupt if
/// either input producer is interrupted.
public func sample<Sampler: SignalProducerConvertible>(with sampler: Sampler) -> SignalProducer<(Value, Sampler.Value), Error> where Sampler.Error == Never {
return sample(with: sampler.producer)
}
/// Forward the latest value from `self` whenever `sampler` sends a `value`
/// event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A producer that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A producer that, when started, will send values from `self`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input producers have completed, or interrupt if
/// either input producer is interrupted.
public func sample(on sampler: SignalProducer<(), Never>) -> SignalProducer<Value, Error> {
return liftLeft(Signal.sample(on:))(sampler)
}
/// Forward the latest value from `self` whenever `sampler` sends a `value`
/// event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A producer that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A producer that, when started, will send values from `self`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input producers have completed, or interrupt if
/// either input producer is interrupted.
public func sample<Sampler: SignalProducerConvertible>(on sampler: Sampler) -> SignalProducer<Value, Error> where Sampler.Value == (), Sampler.Error == Never {
return sample(on: sampler.producer)
}
/// Forward the latest value from `samplee` with the value from `self` as a
/// tuple, only when `self` sends a `value` event.
/// This is like a flipped version of `sample(with:)`, but `samplee`'s
/// terminal events are completely ignored.
///
/// - note: If `self` fires before a value has been observed on `samplee`,
/// nothing happens.
///
/// - parameters:
/// - samplee: A producer whose latest value is sampled by `self`.
///
/// - returns: A producer that will send values from `self` and `samplee`,
/// sampled (possibly multiple times) by `self`, then terminate
/// once `self` has terminated. **`samplee`'s terminated events
/// are ignored**.
public func withLatest<U>(from samplee: SignalProducer<U, Never>) -> SignalProducer<(Value, U), Error> {
return liftRight(Signal.withLatest)(samplee.producer)
}
/// Forward the latest value from `samplee` with the value from `self` as a
/// tuple, only when `self` sends a `value` event.
/// This is like a flipped version of `sample(with:)`, but `samplee`'s
/// terminal events are completely ignored.
///
/// - note: If `self` fires before a value has been observed on `samplee`,
/// nothing happens.
///
/// - parameters:
/// - samplee: A producer whose latest value is sampled by `self`.
///
/// - returns: A producer that will send values from `self` and `samplee`,
/// sampled (possibly multiple times) by `self`, then terminate
/// once `self` has terminated. **`samplee`'s terminated events
/// are ignored**.
public func withLatest<Samplee: SignalProducerConvertible>(from samplee: Samplee) -> SignalProducer<(Value, Samplee.Value), Error> where Samplee.Error == Never {
return withLatest(from: samplee.producer)
}
/// Forwards events from `self` until `lifetime` ends, at which point the
/// returned producer will complete.
///
/// - parameters:
/// - lifetime: A lifetime whose `ended` signal will cause the returned
/// producer to complete.
///
/// - returns: A producer that will deliver events until `lifetime` ends.
public func take(during lifetime: Lifetime) -> SignalProducer<Value, Error> {
return lift { $0.take(during: lifetime) }
}
/// Forward events from `self` until `trigger` sends a `value` or `completed`
/// event, at which point the returned producer will complete.
///
/// - parameters:
/// - trigger: A producer whose `value` or `completed` events will stop the
/// delivery of `value` events from `self`.
///
/// - returns: A producer that will deliver events until `trigger` sends
/// `value` or `completed` events.
public func take(until trigger: SignalProducer<(), Never>) -> SignalProducer<Value, Error> {
return liftRight(Signal.take(until:))(trigger)
}
/// Forward events from `self` until `trigger` sends a `value` or `completed`
/// event, at which point the returned producer will complete.
///
/// - parameters:
/// - trigger: A producer whose `value` or `completed` events will stop the
/// delivery of `value` events from `self`.
///
/// - returns: A producer that will deliver events until `trigger` sends
/// `value` or `completed` events.
public func take<Trigger: SignalProducerConvertible>(until trigger: Trigger) -> SignalProducer<Value, Error> where Trigger.Value == (), Trigger.Error == Never {
return take(until: trigger.producer)
}
/// Do not forward any values from `self` until `trigger` sends a `value`
/// or `completed`, at which point the returned producer behaves exactly
/// like `producer`.
///
/// - parameters:
/// - trigger: A producer whose `value` or `completed` events will start
/// the deliver of events on `self`.
///
/// - returns: A producer that will deliver events once the `trigger` sends
/// `value` or `completed` events.
public func skip(until trigger: SignalProducer<(), Never>) -> SignalProducer<Value, Error> {
return liftRight(Signal.skip(until:))(trigger)
}
/// Do not forward any values from `self` until `trigger` sends a `value`
/// or `completed`, at which point the returned producer behaves exactly
/// like `producer`.
///
/// - parameters:
/// - trigger: A producer whose `value` or `completed` events will start
/// the deliver of events on `self`.
///
/// - returns: A producer that will deliver events once the `trigger` sends
/// `value` or `completed` events.
public func skip<Trigger: SignalProducerConvertible>(until trigger: Trigger) -> SignalProducer<Value, Error> where Trigger.Value == (), Trigger.Error == Never {
return skip(until: trigger.producer)
}
/// Forward events from `self` with history: values of the returned producer
/// are a tuples whose first member is the previous value and whose second member
/// is the current value. `initial` is supplied as the first member when `self`
/// sends its first value.
///
/// - parameters:
/// - initial: A value that will be combined with the first value sent by
/// `self`.
///
/// - returns: A producer that sends tuples that contain previous and current
/// sent values of `self`.
public func combinePrevious(_ initial: Value) -> SignalProducer<(Value, Value), Error> {
return core.flatMapEvent(Signal.Event.combinePrevious(initial: initial))
}
/// Forward events from `self` with history: values of the produced signal
/// are a tuples whose first member is the previous value and whose second member
/// is the current value.
///
/// The produced `Signal` would not emit any tuple until it has received at least two
/// values.
///
/// - returns: A producer that sends tuples that contain previous and current
/// sent values of `self`.
public func combinePrevious() -> SignalProducer<(Value, Value), Error> {
return core.flatMapEvent(Signal.Event.combinePrevious(initial: nil))
}
/// Combine all values from `self`, and forward the final result.
///
/// See `scan(_:_:)` if the resulting producer needs to forward also the partial
/// results.
///
/// - parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - nextPartialResult: A closure that combines the accumulating value and the
/// latest value from `self`. The result would be used in the
/// next call of `nextPartialResult`, or emit to the returned
/// `Signal` when `self` completes.
///
/// - returns: A producer that sends the final result as `self` completes.
public func reduce<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.reduce(initialResult, nextPartialResult))
}
/// Combine all values from `self`, and forward the final result.
///
/// See `scan(into:_:)` if the resulting producer needs to forward also the partial
/// results.
///
/// - parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - nextPartialResult: A closure that combines the accumulating value and the
/// latest value from `self`. The result would be used in the
/// next call of `nextPartialResult`, or emit to the returned
/// `Signal` when `self` completes.
///
/// - returns: A producer that sends the final value as `self` completes.
public func reduce<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.reduce(into: initialResult, nextPartialResult))
}
/// Combine all values from `self`, and forward the partial results and the final
/// result.
///
/// See `reduce(_:_:)` if the resulting producer needs to forward only the final
/// result.
///
/// - parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - nextPartialResult: A closure that combines the accumulating value and the
/// latest value from `self`. The result would be forwarded,
/// and would be used in the next call of `nextPartialResult`.
///
/// - returns: A producer that sends the partial results of the accumuation, and the
/// final result as `self` completes.
public func scan<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.scan(initialResult, nextPartialResult))
}
/// Combine all values from `self`, and forward the partial results and the final
/// result.
///
/// See `reduce(into:_:)` if the resulting producer needs to forward only the final
/// result.
///
/// - parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - nextPartialResult: A closure that combines the accumulating value and the
/// latest value from `self`. The result would be forwarded,
/// and would be used in the next call of `nextPartialResult`.
///
/// - returns: A producer that sends the partial results of the accumuation, and the
/// final result as `self` completes.
public func scan<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.scan(into: initialResult, nextPartialResult))
}
/// Accumulate all values from `self` as `State`, and send the value as `U`.
///
/// - parameters:
/// - initialState: The state to use as the initial accumulating state.
/// - next: A closure that combines the accumulating state and the latest value
/// from `self`. The result would be "next state" and "output" where
/// "output" would be forwarded and "next state" would be used in the
/// next call of `next`.
///
/// - returns: A producer that sends the output that is computed from the accumuation.
public func scanMap<State, U>(_ initialState: State, _ next: @escaping (State, Value) -> (State, U)) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.scanMap(initialState, next))
}
/// Accumulate all values from `self` as `State`, and send the value as `U`.
///
/// - parameters:
/// - initialState: The state to use as the initial accumulating state.
/// - next: A closure that combines the accumulating state and the latest value
/// from `self`. The result would be "next state" and "output" where
/// "output" would be forwarded and "next state" would be used in the
/// next call of `next`.
///
/// - returns: A producer that sends the output that is computed from the accumuation.
public func scanMap<State, U>(into initialState: State, _ next: @escaping (inout State, Value) -> U) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.scanMap(into: initialState, next))
}
/// Forward only values from `self` that are not considered equivalent to its
/// immediately preceding value.
///
/// - note: The first value is always forwarded.
///
/// - parameters:
/// - isEquivalent: A closure to determine whether two values are equivalent.
///
/// - returns: A producer which conditionally forwards values from `self`
public func skipRepeats(_ isEquivalent: @escaping (Value, Value) -> Bool) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.skipRepeats(isEquivalent))
}
/// Do not forward any value from `self` until `shouldContinue` returns `false`, at
/// which point the returned signal starts to forward values from `self`, including
/// the one leading to the toggling.
///
/// - parameters:
/// - shouldContinue: A closure to determine whether the skipping should continue.
///
/// - returns: A producer which conditionally forwards values from `self`.
public func skip(while shouldContinue: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.skip(while: shouldContinue))
}
/// Forwards events from `self` until `replacement` begins sending events.
///
/// - parameters:
/// - replacement: A producer to wait to wait for values from and start
/// sending them as a replacement to `self`'s values.
///
/// - returns: A producer which passes through `value`, `failed`, and
/// `interrupted` events from `self` until `replacement` sends an
/// event, at which point the returned producer will send that
/// event and switch to passing through events from `replacement`
/// instead, regardless of whether `self` has sent events
/// already.
public func take(untilReplacement replacement: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return liftRight(Signal.take(untilReplacement:))(replacement)
}
/// Forwards events from `self` until `replacement` begins sending events.
///
/// - parameters:
/// - replacement: A producer to wait to wait for values from and start
/// sending them as a replacement to `self`'s values.
///
/// - returns: A producer which passes through `value`, `failed`, and
/// `interrupted` events from `self` until `replacement` sends an
/// event, at which point the returned producer will send that
/// event and switch to passing through events from `replacement`
/// instead, regardless of whether `self` has sent events
/// already.
public func take<Replacement: SignalProducerConvertible>(untilReplacement replacement: Replacement) -> SignalProducer<Value, Error> where Replacement.Value == Value, Replacement.Error == Error {
return take(untilReplacement: replacement.producer)
}
/// Wait until `self` completes and then forward the final `count` values
/// on the returned producer.
///
/// - parameters:
/// - count: Number of last events to send after `self` completes.
///
/// - returns: A producer that receives up to `count` values from `self`
/// after `self` completes.
public func take(last count: Int) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.take(last: count))
}
/// Forward any values from `self` until `shouldContinue` returns `false`, at which
/// point the returned signal forwards the last value and then it completes.
/// This is equivalent to `take(while:)`, except it also forwards the last value that failed the check.
///
/// - parameters:
/// - shouldContinue: A closure to determine whether the forwarding of values should
/// continue.
///
/// - returns: A signal which conditionally forwards values from `self`.
public func take(until shouldContinue: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.take(until: shouldContinue))
}
/// Forward any values from `self` until `shouldContinue` returns `false`, at which
/// point the produced `Signal` would complete.
///
/// - parameters:
/// - shouldContinue: A closure to determine whether the forwarding of values should
/// continue.
///
/// - returns: A producer which conditionally forwards values from `self`.
public func take(while shouldContinue: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.take(while: shouldContinue))
}
/// Zip elements of two producers into pairs. The elements of any Nth pair
/// are the Nth elements of the two input producers.
///
/// - parameters:
/// - other: A producer to zip values with.
///
/// - returns: A producer that sends tuples of `self` and `otherProducer`.
public func zip<U>(with other: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> {
return SignalProducer.zip(self, other)
}
/// Zip elements of two producers into pairs. The elements of any Nth pair
/// are the Nth elements of the two input producers.
///
/// - parameters:
/// - other: A producer to zip values with.
///
/// - returns: A producer that sends tuples of `self` and `otherProducer`.
public func zip<Other: SignalProducerConvertible>(with other: Other) -> SignalProducer<(Value, Other.Value), Error> where Other.Error == Error {
return zip(with: other.producer)
}
/// Apply an action to every value from `self`, and forward the value if the action
/// succeeds. If the action fails with an error, the produced `Signal` would propagate
/// the failure and terminate.
///
/// - parameters:
/// - action: An action which yields a `Result`.
///
/// - returns: A producer which forwards the values from `self` until the given action
/// fails.
public func attempt(_ action: @escaping (Value) -> Result<(), Error>) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.attempt(action))
}
/// Apply a transform to every value from `self`, and forward the transformed value
/// if the action succeeds. If the action fails with an error, the produced `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - action: A transform which yields a `Result` of the transformed value or the
/// error.
///
/// - returns: A producer which forwards the transformed values.
public func attemptMap<U>(_ action: @escaping (Value) -> Result<U, Error>) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.attemptMap(action))
}
/// Forward the latest value on `scheduler` after at least `interval`
/// seconds have passed since *the returned signal* last sent a value.
///
/// If `self` always sends values more frequently than `interval` seconds,
/// then the returned signal will send a value every `interval` seconds.
///
/// To measure from when `self` last sent a value, see `debounce`.
///
/// - seealso: `debounce`
///
/// - note: If multiple values are received before the interval has elapsed,
/// the latest value is the one that will be passed on.
///
/// - note: If `self` terminates while a value is being throttled, that
/// value will be discarded and the returned producer will terminate
/// immediately.
///
/// - note: If the device time changed backwards before previous date while
/// a value is being throttled, and if there is a new value sent,
/// the new value will be passed anyway.
///
/// - parameters:
/// - interval: Number of seconds to wait between sent values.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that sends values at least `interval` seconds
/// appart on a given scheduler.
public func throttle(_ interval: TimeInterval, on scheduler: DateScheduler) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.throttle(interval, on: scheduler))
}
/// Conditionally throttles values sent on the receiver whenever
/// `shouldThrottle` is true, forwarding values on the given scheduler.
///
/// - note: While `shouldThrottle` remains false, values are forwarded on the
/// given scheduler. If multiple values are received while
/// `shouldThrottle` is true, the latest value is the one that will
/// be passed on.
///
/// - note: If the input signal terminates while a value is being throttled,
/// that value will be discarded and the returned signal will
/// terminate immediately.
///
/// - note: If `shouldThrottle` completes before the receiver, and its last
/// value is `true`, the returned signal will remain in the throttled
/// state, emitting no further values until it terminates.
///
/// - parameters:
/// - shouldThrottle: A boolean property that controls whether values
/// should be throttled.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that sends values only while `shouldThrottle` is false.
public func throttle<P: PropertyProtocol>(while shouldThrottle: P, on scheduler: Scheduler) -> SignalProducer<Value, Error>
where P.Value == Bool
{
// Using `Property.init(_:)` avoids capturing a strong reference
// to `shouldThrottle`, so that we don't extend its lifetime.
let shouldThrottle = Property(shouldThrottle)
return lift { $0.throttle(while: shouldThrottle, on: scheduler) }
}
/// Forward the latest value on `scheduler` after at least `interval`
/// seconds have passed since `self` last sent a value.
///
/// If `self` always sends values more frequently than `interval` seconds,
/// then the returned signal will never send any values.
///
/// To measure from when the *returned signal* last sent a value, see
/// `throttle`.
///
/// - seealso: `throttle`
///
/// - note: If multiple values are received before the interval has elapsed,
/// the latest value is the one that will be passed on.
///
/// - note: If `self` terminates while a value is being debounced,
/// the behaviour will be determined by `discardWhenCompleted`.
/// If `true`, that value will be discarded and the returned producer
/// will terminate immediately.
/// If `false`, that value will be delivered at the next debounce
/// interval.
///
/// - parameters:
/// - interval: A number of seconds to wait before sending a value.
/// - scheduler: A scheduler to send values on.
/// - discardWhenCompleted: A boolean to indicate if the latest value
/// should be discarded on completion.
///
/// - returns: A producer that sends values that are sent from `self` at
/// least `interval` seconds apart.
public func debounce(_ interval: TimeInterval, on scheduler: DateScheduler, discardWhenCompleted: Bool = true) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.debounce(interval, on: scheduler, discardWhenCompleted: discardWhenCompleted))
}
/// Forward events from `self` until `interval`. Then if producer isn't
/// completed yet, fails with `error` on `scheduler`.
///
/// - note: If the interval is 0, the timeout will be scheduled immediately.
/// The producer must complete synchronously (or on a faster
/// scheduler) to avoid the timeout.
///
/// - parameters:
/// - interval: Number of seconds to wait for `self` to complete.
/// - error: Error to send with `failed` event if `self` is not completed
/// when `interval` passes.
/// - scheduler: A scheduler to deliver error on.
///
/// - returns: A producer that sends events for at most `interval` seconds,
/// then, if not `completed` - sends `error` with `failed` event
/// on `scheduler`.
public func timeout(after interval: TimeInterval, raising error: Error, on scheduler: DateScheduler) -> SignalProducer<Value, Error> {
return lift { $0.timeout(after: interval, raising: error, on: scheduler) }
}
}
extension SignalProducer where Value: OptionalProtocol {
/// Unwraps non-`nil` values and forwards them on the returned signal, `nil`
/// values are dropped.
///
/// - returns: A producer that sends only non-nil values.
public func skipNil() -> SignalProducer<Value.Wrapped, Error> {
return core.flatMapEvent(Signal.Event.skipNil)
}
}
extension SignalProducer where Value: EventProtocol, Error == Never {
/// The inverse of materialize(), this will translate a producer of `Event`
/// _values_ into a producer of those events themselves.
///
/// - returns: A producer that sends values carried by `self` events.
public func dematerialize() -> SignalProducer<Value.Value, Value.Error> {
return core.flatMapEvent(Signal.Event.dematerialize)
}
}
extension SignalProducer where Error == Never {
/// The inverse of materializeResults(), this will translate a producer of `Result`
/// _values_ into a producer of those events themselves.
///
/// - returns: A producer that sends values carried by `self` results.
public func dematerializeResults<Success, Failure>() -> SignalProducer<Success, Failure> where Value == Result<Success, Failure> {
return core.flatMapEvent(Signal.Event.dematerializeResults)
}
}
extension SignalProducer where Error == Never {
/// Promote a producer that does not generate failures into one that can.
///
/// - note: This does not actually cause failers to be generated for the
/// given producer, but makes it easier to combine with other
/// producers that may fail; for example, with operators like
/// `combineLatestWith`, `zipWith`, `flatten`, etc.
///
/// - parameters:
/// - _ An `ErrorType`.
///
/// - returns: A producer that has an instantiatable `ErrorType`.
public func promoteError<F>(_: F.Type = F.self) -> SignalProducer<Value, F> {
return core.flatMapEvent(Signal.Event.promoteError(F.self))
}
/// Promote a producer that does not generate failures into one that can.
///
/// - note: This does not actually cause failers to be generated for the
/// given producer, but makes it easier to combine with other
/// producers that may fail; for example, with operators like
/// `combineLatestWith`, `zipWith`, `flatten`, etc.
///
/// - parameters:
/// - _ An `ErrorType`.
///
/// - returns: A producer that has an instantiatable `ErrorType`.
public func promoteError(_: Error.Type = Error.self) -> SignalProducer<Value, Error> {
return self
}
/// Forward events from `self` until `interval`. Then if producer isn't
/// completed yet, fails with `error` on `scheduler`.
///
/// - note: If the interval is 0, the timeout will be scheduled immediately.
/// The producer must complete synchronously (or on a faster
/// scheduler) to avoid the timeout.
///
/// - parameters:
/// - interval: Number of seconds to wait for `self` to complete.
/// - error: Error to send with `failed` event if `self` is not completed
/// when `interval` passes.
/// - scheudler: A scheduler to deliver error on.
///
/// - returns: A producer that sends events for at most `interval` seconds,
/// then, if not `completed` - sends `error` with `failed` event
/// on `scheduler`.
public func timeout<NewError>(
after interval: TimeInterval,
raising error: NewError,
on scheduler: DateScheduler
) -> SignalProducer<Value, NewError> {
return lift { $0.timeout(after: interval, raising: error, on: scheduler) }
}
/// Apply a throwable action to every value from `self`, and forward the values
/// if the action succeeds. If the action throws an error, the produced `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - action: A throwable closure to perform an arbitrary action on the value.
///
/// - returns: A producer which forwards the successful values of the given action.
public func attempt(_ action: @escaping (Value) throws -> Void) -> SignalProducer<Value, Swift.Error> {
return self
.promoteError(Swift.Error.self)
.attempt(action)
}
/// Apply a throwable action to every value from `self`, and forward the results
/// if the action succeeds. If the action throws an error, the produced `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - action: A throwable closure to perform an arbitrary action on the value, and
/// yield a result.
///
/// - returns: A producer which forwards the successful results of the given action.
public func attemptMap<U>(_ action: @escaping (Value) throws -> U) -> SignalProducer<U, Swift.Error> {
return self
.promoteError(Swift.Error.self)
.attemptMap(action)
}
}
extension SignalProducer where Error == Swift.Error {
/// Apply a throwable action to every value from `self`, and forward the values
/// if the action succeeds. If the action throws an error, the produced `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - action: A throwable closure to perform an arbitrary action on the value.
///
/// - returns: A producer which forwards the successful values of the given action.
public func attempt(_ action: @escaping (Value) throws -> Void) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.attempt(action))
}
/// Apply a throwable transform to every value from `self`, and forward the results
/// if the action succeeds. If the transform throws an error, the produced `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - transform: A throwable transform.
///
/// - returns: A producer which forwards the successfully transformed values.
public func attemptMap<U>(_ transform: @escaping (Value) throws -> U) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.attemptMap(transform))
}
}
extension SignalProducer where Value == Never {
/// Promote a producer that does not generate values, as indicated by `Never`,
/// to be a producer of the given type of value.
///
/// - note: The promotion does not result in any value being generated.
///
/// - parameters:
/// - _ The type of value to promote to.
///
/// - returns: A producer that forwards all terminal events from `self`.
public func promoteValue<U>(_: U.Type = U.self) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.promoteValue(U.self))
}
/// Promote a producer that does not generate values, as indicated by `Never`,
/// to be a producer of the given type of value.
///
/// - note: The promotion does not result in any value being generated.
///
/// - parameters:
/// - _ The type of value to promote to.
///
/// - returns: A producer that forwards all terminal events from `self`.
public func promoteValue(_: Value.Type = Value.self) -> SignalProducer<Value, Error> {
return self
}
}
extension SignalProducer where Value: Equatable {
/// Forward only values from `self` that are not equal to its immediately preceding
/// value.
///
/// - note: The first value is always forwarded.
///
/// - returns: A producer which conditionally forwards values from `self`.
public func skipRepeats() -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.skipRepeats(==))
}
}
extension SignalProducer {
/// Forward only those values from `self` that have unique identities across
/// the set of all values that have been seen.
///
/// - note: This causes the identities to be retained to check for
/// uniqueness.
///
/// - parameters:
/// - transform: A closure that accepts a value and returns identity
/// value.
///
/// - returns: A producer that sends unique values during its lifetime.
public func uniqueValues<Identity: Hashable>(_ transform: @escaping (Value) -> Identity) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.uniqueValues(transform))
}
}
extension SignalProducer where Value: Hashable {
/// Forward only those values from `self` that are unique across the set of
/// all values that have been seen.
///
/// - note: This causes the values to be retained to check for uniqueness.
/// Providing a function that returns a unique value for each sent
/// value can help you reduce the memory footprint.
///
/// - returns: A producer that sends unique values during its lifetime.
public func uniqueValues() -> SignalProducer<Value, Error> {
return uniqueValues { $0 }
}
}
extension SignalProducer {
/// Injects side effects to be performed upon the specified producer events.
///
/// - note: In a composed producer, `starting` is invoked in the reverse
/// direction of the flow of events.
///
/// - parameters:
/// - starting: A closure that is invoked before the producer is started.
/// - started: A closure that is invoked after the producer is started.
/// - event: A closure that accepts an event and is invoked on every
/// received event.
/// - failed: A closure that accepts error object and is invoked for
/// `failed` event.
/// - completed: A closure that is invoked for `completed` event.
/// - interrupted: A closure that is invoked for `interrupted` event.
/// - terminated: A closure that is invoked for any terminating event.
/// - disposed: A closure added as disposable when signal completes.
/// - value: A closure that accepts a value from `value` event.
///
/// - returns: A producer with attached side-effects for given event cases.
public func on(
starting: (() -> Void)? = nil,
started: (() -> Void)? = nil,
event: ((ProducedSignal.Event) -> Void)? = nil,
failed: ((Error) -> Void)? = nil,
completed: (() -> Void)? = nil,
interrupted: (() -> Void)? = nil,
terminated: (() -> Void)? = nil,
disposed: (() -> Void)? = nil,
value: ((Value) -> Void)? = nil
) -> SignalProducer<Value, Error> {
return SignalProducer(SignalCore {
let instance = self.core.makeInstance()
let signal = instance.signal.on(event: event,
failed: failed,
completed: completed,
interrupted: interrupted,
terminated: terminated,
disposed: disposed,
value: value)
return .init(signal: signal,
observerDidSetup: { starting?(); instance.observerDidSetup(); started?() },
interruptHandle: instance.interruptHandle)
})
}
/// Start the returned producer on the given `Scheduler`.
///
/// - note: This implies that any side effects embedded in the producer will
/// be performed on the given scheduler as well.
///
/// - note: Events may still be sent upon other schedulers — this merely
/// affects where the `start()` method is run.
///
/// - parameters:
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that will deliver events on given `scheduler` when
/// started.
public func start(on scheduler: Scheduler) -> SignalProducer<Value, Error> {
return SignalProducer { observer, lifetime in
lifetime += scheduler.schedule {
self.startWithSignal { signal, signalDisposable in
lifetime += signalDisposable
signal.observe(observer)
}
}
}
}
}
extension SignalProducer {
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible>(_ a: A, _ b: B) -> SignalProducer<(Value, B.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer) { Signal.combineLatest($0, $1).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C) -> SignalProducer<(Value, B.Value, C.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer) { Signal.combineLatest($0, $1, $2).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D) -> SignalProducer<(Value, B.Value, C.Value, D.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer) { Signal.combineLatest($0, $1, $2, $3).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer) { Signal.combineLatest($0, $1, $2, $3, $4).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer) { Signal.combineLatest($0, $1, $2, $3, $4, $5).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer) { Signal.combineLatest($0, $1, $2, $3, $4, $5, $6).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error, H.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer) { Signal.combineLatest($0, $1, $2, $3, $4, $5, $6, $7).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible, I: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error, H.Error == Error, I.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer, i.producer) { Signal.combineLatest($0, $1, $2, $3, $4, $5, $6, $7, $8).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible, I: SignalProducerConvertible, J: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value, J.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error, H.Error == Error, I.Error == Error, J.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer, i.producer, j.producer) { Signal.combineLatest($0, $1, $2, $3, $4, $5, $6, $7, $8, $9).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`. Will return an empty `SignalProducer` if the sequence is empty.
public static func combineLatest<S: Sequence>(_ producers: S) -> SignalProducer<[Value], Error> where S.Iterator.Element: SignalProducerConvertible, S.Iterator.Element.Value == Value, S.Iterator.Element.Error == Error {
return start(producers, Signal.combineLatest)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`. If no producer is given, the resulting producer will constantly return `emptySentinel`.
public static func combineLatest<S: Sequence>(_ producers: S, emptySentinel: [S.Iterator.Element.Value]) -> SignalProducer<[Value], Error> where S.Iterator.Element: SignalProducerConvertible, S.Iterator.Element.Value == Value, S.Iterator.Element.Error == Error {
return start(producers, emptySentinel: emptySentinel, Signal.combineLatest)
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible>(_ a: A, _ b: B) -> SignalProducer<(Value, B.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer) { Signal.zip($0, $1).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C) -> SignalProducer<(Value, B.Value, C.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer) { Signal.zip($0, $1, $2).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D) -> SignalProducer<(Value, B.Value, C.Value, D.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer) { Signal.zip($0, $1, $2, $3).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer) { Signal.zip($0, $1, $2, $3, $4).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer) { Signal.zip($0, $1, $2, $3, $4, $5).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer) { Signal.zip($0, $1, $2, $3, $4, $5, $6).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error, H.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer) { Signal.zip($0, $1, $2, $3, $4, $5, $6, $7).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible, I: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error, H.Error == Error, I.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer, i.producer) { Signal.zip($0, $1, $2, $3, $4, $5, $6, $7, $8).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible, I: SignalProducerConvertible, J: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value, J.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error, H.Error == Error, I.Error == Error, J.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer, i.producer, j.producer) { Signal.zip($0, $1, $2, $3, $4, $5, $6, $7, $8, $9).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`. Will return an empty `SignalProducer` if the sequence is empty.
public static func zip<S: Sequence>(_ producers: S) -> SignalProducer<[Value], Error> where S.Iterator.Element: SignalProducerConvertible, S.Iterator.Element.Value == Value, S.Iterator.Element.Error == Error {
return start(producers, Signal.zip)
}
/// Combines the values of all the given producers, in the manner described by
/// `zip(with:)`. If no producer is given, the resulting producer will constantly return `emptySentinel`.
public static func zip<S: Sequence>(_ producers: S, emptySentinel: [S.Iterator.Element.Value]) -> SignalProducer<[Value], Error> where S.Iterator.Element: SignalProducerConvertible, S.Iterator.Element.Value == Value, S.Iterator.Element.Error == Error {
return start(producers, emptySentinel: emptySentinel, Signal.zip)
}
private static func start<S: Sequence>(
_ producers: S,
emptySentinel: [S.Iterator.Element.Value]? = nil,
_ transform: @escaping (AnySequence<Signal<Value, Error>>) -> Signal<[Value], Error>
) -> SignalProducer<[Value], Error>
where S.Iterator.Element: SignalProducerConvertible, S.Iterator.Element.Value == Value, S.Iterator.Element.Error == Error
{
return SignalProducer<[Value], Error> { observer, lifetime in
let setup = producers.map {
(producer: $0.producer, pipe: Signal<Value, Error>.pipe())
}
guard !setup.isEmpty else {
if let emptySentinel = emptySentinel {
observer.send(value: emptySentinel)
}
observer.sendCompleted()
return
}
lifetime += transform(AnySequence(setup.lazy.map { $0.pipe.output })).observe(observer)
for (producer, pipe) in setup {
lifetime += producer.start(pipe.input)
}
}
}
}
extension SignalProducer {
/// Repeat `self` a total of `count` times. In other words, start producer
/// `count` number of times, each one after previously started producer
/// completes.
///
/// - note: Repeating `1` time results in an equivalent signal producer.
///
/// - note: Repeating `0` times results in a producer that instantly
/// completes.
///
/// - precondition: `count` must be non-negative integer.
///
/// - parameters:
/// - count: Number of repetitions.
///
/// - returns: A signal producer start sequentially starts `self` after
/// previously started producer completes.
public func `repeat`(_ count: Int) -> SignalProducer<Value, Error> {
precondition(count >= 0)
if count == 0 {
return .empty
} else if count == 1 {
return producer
}
return SignalProducer { observer, lifetime in
let serialDisposable = SerialDisposable()
lifetime += serialDisposable
func iterate(_ current: Int) {
self.startWithSignal { signal, signalDisposable in
serialDisposable.inner = signalDisposable
signal.observe { event in
if case .completed = event {
let remainingTimes = current - 1
if remainingTimes > 0 {
iterate(remainingTimes)
} else {
observer.sendCompleted()
}
} else {
observer.send(event)
}
}
}
}
iterate(count)
}
}
/// Ignore failures up to `count` times.
///
/// - precondition: `count` must be non-negative integer.
///
/// - parameters:
/// - count: Number of retries.
///
/// - returns: A signal producer that restarts up to `count` times.
public func retry(upTo count: Int) -> SignalProducer<Value, Error> {
precondition(count >= 0)
if count == 0 {
return producer
} else {
return flatMapError { _ in
self.retry(upTo: count - 1)
}
}
}
/// Delays retrying on failure by `interval` up to `count` attempts.
///
/// - precondition: `count` must be non-negative integer.
///
/// - parameters:
/// - count: Number of retries.
/// - interval: An interval between invocations.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A signal producer that restarts up to `count` times.
public func retry(upTo count: Int, interval: TimeInterval, on scheduler: DateScheduler) -> SignalProducer<Value, Error> {
precondition(count >= 0)
if count == 0 {
return producer
}
return SignalProducer { observer, lifetime in
var retries = count
lifetime += self.flatMapError { error -> SignalProducer<Value, Error> in
// The final attempt shouldn't defer the error if it fails
var producer = SignalProducer<Value, Error>(error: error)
if retries > 0 {
producer = SignalProducer.empty
.delay(interval, on: scheduler)
.concat(producer)
}
retries -= 1
return producer
}
.retry(upTo: count)
.start(observer)
}
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<U>(_ replacement: SignalProducer<U, Never>) -> SignalProducer<U, Error> {
return _then(replacement.promoteError(Error.self))
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Replacement.Value, Error> where Replacement.Error == Never {
return then(replacement.producer)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<U>(_ replacement: SignalProducer<U, Error>) -> SignalProducer<U, Error> {
return _then(replacement)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Replacement.Value, Error> where Replacement.Error == Error {
return then(replacement.producer)
}
// NOTE: The overload below is added to disambiguate compile-time selection of
// `then(_:)`.
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then(_ replacement: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return _then(replacement)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Value, Error> where Replacement.Value == Value, Replacement.Error == Error {
return then(replacement.producer)
}
// NOTE: The method below is the shared implementation of `then(_:)`. The underscore
// prefix is added to avoid self referencing in `then(_:)` overloads with
// regard to the most specific rule of overload selection in Swift.
internal func _then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Replacement.Value, Error> where Replacement.Error == Error {
return SignalProducer<Replacement.Value, Error> { observer, lifetime in
self.startWithSignal { signal, signalDisposable in
lifetime += signalDisposable
signal.observe { event in
switch event {
case let .failed(error):
observer.send(error: error)
case .completed:
lifetime += replacement.producer.start(observer)
case .interrupted:
observer.sendInterrupted()
case .value:
break
}
}
}
}
}
}
extension SignalProducer where Error == Never {
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<U, F>(_ replacement: SignalProducer<U, F>) -> SignalProducer<U, F> {
return promoteError(F.self)._then(replacement)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Replacement.Value, Replacement.Error> {
return then(replacement.producer)
}
// NOTE: The overload below is added to disambiguate compile-time selection of
// `then(_:)`.
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<U>(_ replacement: SignalProducer<U, Never>) -> SignalProducer<U, Never> {
return _then(replacement)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Replacement.Value, Never> where Replacement.Error == Never {
return then(replacement.producer)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then(_ replacement: SignalProducer<Value, Never>) -> SignalProducer<Value, Never> {
return _then(replacement)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Value, Never> where Replacement.Value == Value, Replacement.Error == Never {
return then(replacement.producer)
}
}
extension SignalProducer {
/// Start the producer, then block, waiting for the first value.
///
/// When a single value or error is sent, the returned `Result` will
/// represent those cases. However, when no values are sent, `nil` will be
/// returned.
///
/// - returns: Result when single `value` or `failed` event is received.
/// `nil` when no events are received.
public func first() -> Result<Value, Error>? {
return take(first: 1).single()
}
/// Start the producer, then block, waiting for events: `value` and
/// `completed`.
///
/// When a single value or error is sent, the returned `Result` will
/// represent those cases. However, when no values are sent, or when more
/// than one value is sent, `nil` will be returned.
///
/// - returns: Result when single `value` or `failed` event is received.
/// `nil` when 0 or more than 1 events are received.
public func single() -> Result<Value, Error>? {
let semaphore = DispatchSemaphore(value: 0)
var result: Result<Value, Error>?
take(first: 2).start { event in
switch event {
case let .value(value):
if result != nil {
// Move into failure state after recieving another value.
result = nil
return
}
result = .success(value)
case let .failed(error):
result = .failure(error)
semaphore.signal()
case .completed, .interrupted:
semaphore.signal()
}
}
semaphore.wait()
return result
}
/// Start the producer, then block, waiting for the last value.
///
/// When a single value or error is sent, the returned `Result` will
/// represent those cases. However, when no values are sent, `nil` will be
/// returned.
///
/// - returns: Result when single `value` or `failed` event is received.
/// `nil` when no events are received.
public func last() -> Result<Value, Error>? {
return take(last: 1).single()
}
/// Starts the producer, then blocks, waiting for completion.
///
/// When a completion or error is sent, the returned `Result` will represent
/// those cases.
///
/// - returns: Result when single `completion` or `failed` event is
/// received.
public func wait() -> Result<(), Error> {
return then(SignalProducer<(), Error>(value: ())).last() ?? .success(())
}
/// Creates a new `SignalProducer` that will multicast values emitted by
/// the underlying producer, up to `capacity`.
/// This means that all clients of this `SignalProducer` will see the same
/// version of the emitted values/errors.
///
/// The underlying `SignalProducer` will not be started until `self` is
/// started for the first time. When subscribing to this producer, all
/// previous values (up to `capacity`) will be emitted, followed by any new
/// values.
///
/// If you find yourself needing *the current value* (the last buffered
/// value) you should consider using `PropertyType` instead, which, unlike
/// this operator, will guarantee at compile time that there's always a
/// buffered value. This operator is not recommended in most cases, as it
/// will introduce an implicit relationship between the original client and
/// the rest, so consider alternatives like `PropertyType`, or representing
/// your stream using a `Signal` instead.
///
/// This operator is only recommended when you absolutely need to introduce
/// a layer of caching in front of another `SignalProducer`.
///
/// - precondition: `capacity` must be non-negative integer.
///
/// - parameters:
/// - capacity: Number of values to hold.
///
/// - returns: A caching producer that will hold up to last `capacity`
/// values.
public func replayLazily(upTo capacity: Int) -> SignalProducer<Value, Error> {
precondition(capacity >= 0, "Invalid capacity: \(capacity)")
// This will go "out of scope" when the returned `SignalProducer` goes
// out of scope. This lets us know when we're supposed to dispose the
// underlying producer. This is necessary because `struct`s don't have
// `deinit`.
let lifetimeToken = Lifetime.Token()
let lifetime = Lifetime(lifetimeToken)
let state = Atomic(ReplayState<Value, Error>(upTo: capacity))
let start: Atomic<(() -> Void)?> = Atomic {
// Start the underlying producer.
self
.take(during: lifetime)
.start { event in
let observers: Bag<Signal<Value, Error>.Observer>? = state.modify { state in
defer { state.enqueue(event) }
return state.observers
}
observers?.forEach { $0.send(event) }
}
}
return SignalProducer { observer, lifetime in
// Don't dispose of the original producer until all observers
// have terminated.
lifetime.observeEnded { _ = lifetimeToken }
while true {
var result: Result<Bag<Signal<Value, Error>.Observer>.Token?, ReplayError<Value>>!
state.modify {
result = $0.observe(observer)
}
switch result! {
case let .success(token):
if let token = token {
lifetime.observeEnded {
state.modify {
$0.removeObserver(using: token)
}
}
}
// Start the underlying producer if it has never been started.
start.swap(nil)?()
// Terminate the replay loop.
return
case let .failure(error):
error.values.forEach(observer.send(value:))
}
}
}
}
}
extension SignalProducer where Value == Bool {
/// Create a producer that computes a logical NOT in the latest values of `self`.
///
/// - returns: A producer that emits the logical NOT results.
public func negate() -> SignalProducer<Value, Error> {
return map(!)
}
/// Create a producer that computes a logical AND between the latest values of `self`
/// and `producer`.
///
/// - parameters:
/// - booleans: A producer of booleans to be combined with `self`.
///
/// - returns: A producer that emits the logical AND results.
public func and(_ booleans: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return type(of: self).all([self, booleans])
}
/// Create a producer that computes a logical AND between the latest values of `self`
/// and `producer`.
///
/// - parameters:
/// - booleans: A producer of booleans to be combined with `self`.
///
/// - returns: A producer that emits the logical AND results.
public func and<Booleans: SignalProducerConvertible>(_ booleans: Booleans) -> SignalProducer<Value, Error> where Booleans.Value == Value, Booleans.Error == Error {
return and(booleans.producer)
}
/// Create a producer that computes a logical AND between the latest values of `booleans`.
///
/// If no producer is given in `booleans`, the resulting producer constantly emits `true`.
///
/// - parameters:
/// - booleans: A collection of boolean producers to be combined.
///
/// - returns: A producer that emits the logical AND results.
public static func all<BooleansCollection: Collection>(_ booleans: BooleansCollection) -> SignalProducer<Value, Error> where BooleansCollection.Element == SignalProducer<Value, Error> {
return combineLatest(booleans, emptySentinel: []).map { $0.reduce(true) { $0 && $1 } }
}
/// Create a producer that computes a logical AND between the latest values of `booleans`.
///
/// If no producer is given in `booleans`, the resulting producer constantly emits `true`.
///
/// - parameters:
/// - booleans: Boolean producers to be combined.
///
/// - returns: A producer that emits the logical AND results.
public static func all(_ booleans: SignalProducer<Value, Error>...) -> SignalProducer<Value, Error> {
return .all(booleans)
}
/// Create a producer that computes a logical AND between the latest values of `booleans`.
///
/// If no producer is given in `booleans`, the resulting producer constantly emits `true`.
///
/// - parameters:
/// - booleans: A collection of boolean producers to be combined.
///
/// - returns: A producer that emits the logical AND results.
public static func all<Booleans: SignalProducerConvertible, BooleansCollection: Collection>(_ booleans: BooleansCollection) -> SignalProducer<Value, Error> where Booleans.Value == Value, Booleans.Error == Error, BooleansCollection.Element == Booleans {
return all(booleans.map { $0.producer })
}
/// Create a producer that computes a logical OR between the latest values of `self`
/// and `producer`.
///
/// - parameters:
/// - booleans: A producer of booleans to be combined with `self`.
///
/// - returns: A producer that emits the logical OR results.
public func or(_ booleans: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return type(of: self).any([self, booleans])
}
/// Create a producer that computes a logical OR between the latest values of `self`
/// and `producer`.
///
/// - parameters:
/// - booleans: A producer of booleans to be combined with `self`.
///
/// - returns: A producer that emits the logical OR results.
public func or<Booleans: SignalProducerConvertible>(_ booleans: Booleans) -> SignalProducer<Value, Error> where Booleans.Value == Value, Booleans.Error == Error {
return or(booleans.producer)
}
/// Create a producer that computes a logical OR between the latest values of `booleans`.
///
/// If no producer is given in `booleans`, the resulting producer constantly emits `false`.
///
/// - parameters:
/// - booleans: A collection of boolean producers to be combined.
///
/// - returns: A producer that emits the logical OR results.
public static func any<BooleansCollection: Collection>(_ booleans: BooleansCollection) -> SignalProducer<Value, Error> where BooleansCollection.Element == SignalProducer<Value, Error> {
return combineLatest(booleans, emptySentinel: []).map { $0.reduce(false) { $0 || $1 } }
}
/// Create a producer that computes a logical OR between the latest values of `booleans`.
///
/// If no producer is given in `booleans`, the resulting producer constantly emits `false`.
///
/// - parameters:
/// - booleans: Boolean producers to be combined.
///
/// - returns: A producer that emits the logical OR results.
public static func any(_ booleans: SignalProducer<Value, Error>...) -> SignalProducer<Value, Error> {
return .any(booleans)
}
/// Create a producer that computes a logical OR between the latest values of `booleans`.
///
/// If no producer is given in `booleans`, the resulting producer constantly emits `false`.
///
/// - parameters:
/// - booleans: A collection of boolean producers to be combined.
///
/// - returns: A producer that emits the logical OR results.
public static func any<Booleans: SignalProducerConvertible, BooleansCollection: Collection>(_ booleans: BooleansCollection) -> SignalProducer<Value, Error> where Booleans.Value == Value, Booleans.Error == Error, BooleansCollection.Element == Booleans {
return any(booleans.map { $0.producer })
}
}
/// Represents a recoverable error of an observer not being ready for an
/// attachment to a `ReplayState`, and the observer should replay the supplied
/// values before attempting to observe again.
private struct ReplayError<Value>: Error {
/// The values that should be replayed by the observer.
let values: [Value]
}
private struct ReplayState<Value, Error: Swift.Error> {
let capacity: Int
/// All cached values.
var values: [Value] = []
/// A termination event emitted by the underlying producer.
///
/// This will be nil if termination has not occurred.
var terminationEvent: Signal<Value, Error>.Event?
/// The observers currently attached to the caching producer, or `nil` if the
/// caching producer was terminated.
var observers: Bag<Signal<Value, Error>.Observer>? = Bag()
/// The set of in-flight replay buffers.
var replayBuffers: [ObjectIdentifier: [Value]] = [:]
/// Initialize the replay state.
///
/// - parameters:
/// - capacity: The maximum amount of values which can be cached by the
/// replay state.
init(upTo capacity: Int) {
self.capacity = capacity
}
/// Attempt to observe the replay state.
///
/// - warning: Repeatedly observing the replay state with the same observer
/// should be avoided.
///
/// - parameters:
/// - observer: The observer to be registered.
///
/// - returns: If the observer is successfully attached, a `Result.success`
/// with the corresponding removal token would be returned.
/// Otherwise, a `Result.failure` with a `ReplayError` would be
/// returned.
mutating func observe(_ observer: Signal<Value, Error>.Observer) -> Result<Bag<Signal<Value, Error>.Observer>.Token?, ReplayError<Value>> {
// Since the only use case is `replayLazily`, which always creates a unique
// `Observer` for every produced signal, we can use the ObjectIdentifier of
// the `Observer` to track them directly.
let id = ObjectIdentifier(observer)
switch replayBuffers[id] {
case .none where !values.isEmpty:
// No in-flight replay buffers was found, but the `ReplayState` has one or
// more cached values in the `ReplayState`. The observer should replay
// them before attempting to observe again.
replayBuffers[id] = []
return .failure(ReplayError(values: values))
case let .some(buffer) where !buffer.isEmpty:
// An in-flight replay buffer was found with one or more buffered values.
// The observer should replay them before attempting to observe again.
defer { replayBuffers[id] = [] }
return .failure(ReplayError(values: buffer))
case let .some(buffer) where buffer.isEmpty:
// Since an in-flight but empty replay buffer was found, the observer is
// ready to be attached to the `ReplayState`.
replayBuffers.removeValue(forKey: id)
default:
// No values has to be replayed. The observer is ready to be attached to
// the `ReplayState`.
break
}
if let event = terminationEvent {
observer.send(event)
}
return .success(observers?.insert(observer))
}
/// Enqueue the supplied event to the replay state.
///
/// - parameter:
/// - event: The event to be cached.
mutating func enqueue(_ event: Signal<Value, Error>.Event) {
switch event {
case let .value(value):
for key in replayBuffers.keys {
replayBuffers[key]!.append(value)
}
switch capacity {
case 0:
// With a capacity of zero, `state.values` can never be filled.
break
case 1:
values = [value]
default:
values.append(value)
let overflow = values.count - capacity
if overflow > 0 {
values.removeFirst(overflow)
}
}
case .completed, .failed, .interrupted:
// Disconnect all observers and prevent future attachments.
terminationEvent = event
observers = nil
}
}
/// Remove the observer represented by the supplied token.
///
/// - parameters:
/// - token: The token of the observer to be removed.
mutating func removeObserver(using token: Bag<Signal<Value, Error>.Observer>.Token) {
observers?.remove(using: token)
}
}
extension SignalProducer where Value == Date, Error == Never {
/// Create a repeating timer of the given interval, with a reasonable default
/// leeway, sending updates on the given scheduler.
///
/// - note: This timer will never complete naturally, so all invocations of
/// `start()` must be disposed to avoid leaks.
///
/// - precondition: `interval` must be non-negative number.
///
/// - note: If you plan to specify an `interval` value greater than 200,000
/// seconds, use `timer(interval:on:leeway:)` instead
/// and specify your own `leeway` value to avoid potential overflow.
///
/// - parameters:
/// - interval: An interval between invocations.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that sends `Date` values every `interval` seconds.
public static func timer(interval: DispatchTimeInterval, on scheduler: DateScheduler) -> SignalProducer<Value, Error> {
// Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of
// at least 10% of the timer interval.
return timer(interval: interval, on: scheduler, leeway: interval * 0.1)
}
/// Creates a repeating timer of the given interval, sending updates on the
/// given scheduler.
///
/// - note: This timer will never complete naturally, so all invocations of
/// `start()` must be disposed to avoid leaks.
///
/// - precondition: `interval` must be non-negative number.
///
/// - precondition: `leeway` must be non-negative number.
///
/// - parameters:
/// - interval: An interval between invocations.
/// - scheduler: A scheduler to deliver events on.
/// - leeway: Interval leeway. Apple's "Power Efficiency Guide for Mac Apps"
/// recommends a leeway of at least 10% of the timer interval.
///
/// - returns: A producer that sends `Date` values every `interval` seconds.
public static func timer(interval: DispatchTimeInterval, on scheduler: DateScheduler, leeway: DispatchTimeInterval) -> SignalProducer<Value, Error> {
precondition(interval.timeInterval >= 0)
precondition(leeway.timeInterval >= 0)
return SignalProducer { observer, lifetime in
lifetime += scheduler.schedule(
after: scheduler.currentDate.addingTimeInterval(interval),
interval: interval,
leeway: leeway,
action: { observer.send(value: scheduler.currentDate) }
)
}
}
}
extension SignalProducer where Error == Never {
/// Creates a producer that will send the values from the given sequence
/// separated by the given time interval.
///
/// - note: If `values` is an infinite sequeence this `SignalProducer` will never complete naturally,
/// so all invocations of `start()` must be disposed to avoid leaks.
///
/// - precondition: `interval` must be non-negative number.
///
/// - parameters:
/// - values: A sequence of values that will be sent as separate
/// `value` events and then complete.
/// - interval: An interval between value events.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that sends the next value from the sequence every `interval` seconds.
public static func interval<S: Sequence>(
_ values: S,
interval: DispatchTimeInterval,
on scheduler: DateScheduler
) -> SignalProducer<S.Element, Error> where S.Iterator.Element == Value {
return SignalProducer { observer, lifetime in
var iterator = values.makeIterator()
lifetime += scheduler.schedule(
after: scheduler.currentDate.addingTimeInterval(interval),
interval: interval,
// Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of
// at least 10% of the timer interval.
leeway: interval * 0.1,
action: {
switch iterator.next() {
case let .some(value):
observer.send(value: value)
case .none:
observer.sendCompleted()
}
}
)
}
}
}
extension SignalProducer where Error == Never, Value == Int {
/// Creates a producer that will send the sequence of all integers
/// from 0 to infinity, or until disposed.
///
/// - note: This timer will never complete naturally, so all invocations of
/// `start()` must be disposed to avoid leaks.
///
/// - precondition: `interval` must be non-negative number.
///
/// - parameters:
/// - interval: An interval between value events.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that sends a sequential `Int` value every `interval` seconds.
public static func interval(
_ interval: DispatchTimeInterval,
on scheduler: DateScheduler
) -> SignalProducer {
.interval(0..., interval: interval, on: scheduler)
}
}
| mit | 7af2240d0a50d88d77909f03fd797c92 | 42.351411 | 733 | 0.676732 | 3.863309 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.