repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1234224576/WheelSlider
|
WheelSlider/WheelSlider.swift
|
1
|
8183
|
//
// WheelSlider.swift
// WheelSliderSample
//
// Created by 曽和修平 on 2015/10/31.
// Copyright © 2015年 deeptoneworks. All rights reserved.
//
import UIKit
protocol WheelSliderDelegate{
func updateSliderValue(value:Double,sender:WheelSlider) -> ()
}
public enum WSKnobLineCap{
case WSLineCapButt
case WSLineCapRound
case WSLineCapSquare
var getLineCapValue:String{
switch self{
case .WSLineCapButt:
return kCALineCapButt
case .WSLineCapRound:
return kCALineCapRound
case .WSLineCapSquare:
return kCALineCapSquare
}
}
}
@IBDesignable
public class WheelSlider: UIView {
private let wheelView:UIView
private var beforePoint:Double = 0
private var currentPoint:Double = 0{
didSet{
wheelView.layer.removeAllAnimations()
wheelView.layer.addAnimation(nextAnimation(), forKey: "rotateAnimation")
valueTextLayer?.string = "\(Int(calcCurrentValue()))"
delegate?.updateSliderValue(calcCurrentValue(),sender: self)
callback?(calcCurrentValue())
}
}
private var beganTouchPosition = CGPointMake(0, 0)
private var moveTouchPosition = CGPointMake(0, 0){
didSet{
calcCurrentPoint()
}
}
private var valueTextLayer:CATextLayer?
var delegate : WheelSliderDelegate?
public var callback : ((Double) -> ())?
//backgroundCircleParameter
@IBInspectable public var backStrokeColor : UIColor = UIColor.darkGrayColor()
@IBInspectable public var backFillColor : UIColor = UIColor.darkGrayColor()
@IBInspectable public var backWidth : CGFloat = 10.0
//knobParameter
@IBInspectable public var knobStrokeColor : UIColor = UIColor.whiteColor()
@IBInspectable public var knobWidth : CGFloat = 30.0
@IBInspectable public var knobLength : CGFloat = 0.025
public var knobLineCap = WSKnobLineCap.WSLineCapRound
@IBInspectable public var minVal:Int = 0
@IBInspectable public var maxVal:Int = 10
@IBInspectable public var speed:Int = 40
@IBInspectable public var isLimited:Bool = false
@IBInspectable public var allowNegativeNumber:Bool = true
@IBInspectable public var isValueText:Bool = true
@IBInspectable public var valueTextColor:UIColor = UIColor.whiteColor()
@IBInspectable public var valueTextFontSize:CGFloat = 20.0
public lazy var font:UIFont = UIFont.systemFontOfSize(self.valueTextFontSize)
override init(frame: CGRect) {
wheelView = UIView(frame: CGRectMake(0, 0, frame.width, frame.height))
super.init(frame: frame)
addSubview(wheelView)
wheelView.layer.addSublayer(drawBackgroundCicle())
wheelView.layer.addSublayer(drawPointerCircle())
if let layer = drawValueText(){
valueTextLayer = layer
self.layer.addSublayer(layer)
}
}
required public init?(coder aDecoder: NSCoder) {
wheelView = UIView();
super.init(coder: aDecoder)
wheelView.frame = bounds
addSubview(wheelView)
wheelView.layer.addSublayer(drawBackgroundCicle())
wheelView.layer.addSublayer(drawPointerCircle())
if let layer = drawValueText(){
valueTextLayer = layer
self.layer.addSublayer(layer)
}
}
private func drawValueText()->CATextLayer?{
guard(isValueText)else{
return nil
}
let textLayer = CATextLayer()
textLayer.string = "\(0)"
textLayer.font = font
textLayer.fontSize = font.pointSize
textLayer.frame = CGRectMake(frame.origin.x/2 - bounds.width/2, frame.origin.y/2, bounds.width, bounds.height)
textLayer.foregroundColor = valueTextColor.CGColor
textLayer.alignmentMode = kCAAlignmentCenter
textLayer.contentsScale = UIScreen.mainScreen().scale
return textLayer
}
private func drawBackgroundCicle() -> CAShapeLayer{
let ovalShapeLayer = CAShapeLayer()
ovalShapeLayer.strokeColor = backStrokeColor.CGColor
ovalShapeLayer.fillColor = backFillColor.CGColor
ovalShapeLayer.lineWidth = backWidth
let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
let start = CGFloat(0)
let end = CGFloat(2.0 * M_PI)
ovalShapeLayer.path = UIBezierPath(arcCenter: center, radius: max(bounds.width, bounds.height) / 2, startAngle:start, endAngle: end ,clockwise: true).CGPath
return ovalShapeLayer
}
private func drawPointerCircle() -> CAShapeLayer{
let ovalShapeLayer = CAShapeLayer()
ovalShapeLayer.strokeColor = knobStrokeColor.CGColor
ovalShapeLayer.fillColor = UIColor.clearColor().CGColor
ovalShapeLayer.lineWidth = knobWidth
ovalShapeLayer.lineCap = knobLineCap.getLineCapValue
let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
let start = CGFloat(M_PI * 3.0/2.0)
let end = CGFloat(M_PI * 3.0/2.0) + knobLength
ovalShapeLayer.path = UIBezierPath(arcCenter: center, radius: max(bounds.width, bounds.height) / 2, startAngle:start, endAngle: end ,clockwise: true).CGPath
return ovalShapeLayer
}
private func nextAnimation()->CABasicAnimation{
let start = CGFloat(beforePoint/Double(speed) * M_PI)
let end = CGFloat(currentPoint/Double(speed) * M_PI)
let anim = CABasicAnimation(keyPath: "transform.rotation.z")
anim.duration = 0
anim.repeatCount = 0
anim.fromValue = start
anim.toValue = end
anim.removedOnCompletion = false;
anim.fillMode = kCAFillModeForwards;
anim.removedOnCompletion = false
return anim
}
private func calcCurrentValue() -> Double{
let normalization = Double(maxVal) / Double(speed)
let val = currentPoint*normalization/2.0
if(isLimited && val > Double(maxVal)){
beforePoint = 0
currentPoint = 0
}
return val
}
private func calcCurrentPoint(){
let displacementY = abs(beganTouchPosition.y - moveTouchPosition.y)
let displacementX = abs(beganTouchPosition.x - moveTouchPosition.x)
guard(max(displacementX,displacementY) > 1.0)else{
return
}
guard(allowNegativeNumber || calcCurrentValue() > 0)else{
currentPoint++
return
}
let centerX = bounds.size.width/2.0
let centerY = bounds.size.height/2.0
beforePoint = currentPoint
if(displacementX > displacementY){
if(centerY > beganTouchPosition.y){
if(moveTouchPosition.x >= beganTouchPosition.x){
currentPoint++
}else{
currentPoint--
}
}else{
if(moveTouchPosition.x > beganTouchPosition.x){
currentPoint--
}else{
currentPoint++
}
}
}else{
if(centerX <= beganTouchPosition.x){
if(moveTouchPosition.y >= beganTouchPosition.y){
currentPoint++
}else{
currentPoint--
}
}else{
if(moveTouchPosition.y > beganTouchPosition.y){
currentPoint--
}else{
currentPoint++
}
}
}
}
override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first as UITouch?
if let t = touch{
let pos = t.locationInView(self)
beganTouchPosition = moveTouchPosition
moveTouchPosition = pos
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
|
mit
|
684d2b10c904c9e466b70406981f4275
| 33.481013 | 164 | 0.619677 | 4.931804 | false | false | false | false |
cfraz89/ObjectMapper
|
ObjectMapperTests/MapContextTests.swift
|
5
|
1324
|
//
// MapContextTests.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2016-05-10.
// Copyright © 2016 hearst. All rights reserved.
//
import XCTest
import ObjectMapper
class MapContextTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testMappingWithContext() {
let JSON = ["name":"Tristan"]
let context = Context(shouldMap: true)
let person = Mapper<Person>(context: context).map(JSON)
XCTAssertNotNil(person)
XCTAssertNotNil(person?.name)
}
func testMappingWithoutContext() {
let JSON = ["name" : "Tristan"]
let person = Mapper<Person>().map(JSON)
XCTAssertNotNil(person)
XCTAssertNil(person?.name)
}
struct Context: MapContext {
var shouldMap = false
init(shouldMap: Bool){
self.shouldMap = shouldMap
}
}
class Person: Mappable {
var name: String?
required init?(_ map: Map){
}
func mapping(map: Map) {
if (map.context as? Context)?.shouldMap == true {
name <- map["name"]
}
}
}
}
|
mit
|
e16e98fa5cbfe2f9b2a83b624716c513
| 19.671875 | 111 | 0.645503 | 3.801724 | false | true | false | false |
Pluto-Y/SwiftyEcharts
|
SwiftyEchartsTest_iOS/AxisTickSpec.swift
|
1
|
2277
|
//
// AxisTickSpec.swift
// SwiftyEcharts
//
// Created by Pluto Y on 26/06/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
import Quick
import Nimble
import SwiftyEcharts
class AxisTickSpec: QuickSpec {
override func spec() {
describe("For AxisTick") {
let showValue = false
let alignWithLabelValue = true
let intervalValue = 12
let insideValue = false
let lengthValue: Float = 3.45
let lineStyleValue = LineStyle(
.color(Color.red),
.width(12.0),
.type(.dashed),
.opacity(0.5),
.curveness(12.55)
)
let splitNumberValue: UInt8 = 20
let axisTick = AxisTick()
axisTick.show = showValue
axisTick.alignWithLabel = alignWithLabelValue
axisTick.interval = intervalValue
axisTick.inside = insideValue
axisTick.length = lengthValue
axisTick.lineStyle = lineStyleValue
axisTick.splitNumber = splitNumberValue
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"show": showValue,
"alignWithLabel": alignWithLabelValue,
"interval": intervalValue,
"inside": insideValue,
"length": lengthValue,
"lineStyle": lineStyleValue,
"splitNumber": splitNumberValue
]
expect(axisTick.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let axisTickByEnums = AxisTick(
.show(showValue),
.alignWithLabel(alignWithLabelValue),
.interval(intervalValue),
.inside(insideValue),
.length(lengthValue),
.lineStyle(lineStyleValue),
.splitNumber(splitNumberValue)
)
expect(axisTickByEnums.jsonString).to(equal(axisTick.jsonString))
}
}
}
}
|
mit
|
6c800af7c9400ac6e48d710b191f78a7
| 32.470588 | 81 | 0.501757 | 5.393365 | false | false | false | false |
SamirTalwar/advent-of-code
|
2018/AOC_18_2.swift
|
1
|
3269
|
let iterations = 1_000_000_000
enum Acre: CustomStringConvertible {
case openGround
case trees
case lumberyard
var description: String {
switch self {
case .openGround:
return "."
case .trees:
return "|"
case .lumberyard:
return "#"
}
}
func convert(adjacentCounts: [Acre: Int]) -> Acre {
switch self {
case .openGround:
return (adjacentCounts[.trees] ?? 0) >= 3 ? .trees : self
case .trees:
return (adjacentCounts[.lumberyard] ?? 0) >= 3 ? .lumberyard : self
case .lumberyard:
return (adjacentCounts[.lumberyard] ?? 0) >= 1 && (adjacentCounts[.trees] ?? 0) >= 1 ? self : .openGround
}
}
}
struct Grid: Equatable, CustomStringConvertible {
let values: [[Acre]]
let xRange: Range<Int>
let yRange: Range<Int>
init(_ values: [[Acre]]) {
self.values = values
xRange = 0 ..< values[0].count
yRange = 0 ..< values.count
}
var description: String {
return values.map { row in row.map { acre in acre.description }.joined() + "\n" }.joined()
}
func count(of acreType: Acre) -> Int {
return values.flatMap { row in row.filter { acre in acre == acreType } }.count
}
func iterate() -> Grid {
return Grid(yRange.map { y in
xRange.map { x in
values[y][x].convert(adjacentCounts: adjacentValueCounts(x: x, y: y))
}
})
}
private func adjacentValueCounts(x: Int, y: Int) -> [Acre: Int] {
let adjacentPositions = [
(x - 1, y - 1),
(x, y - 1),
(x + 1, y - 1),
(x - 1, y),
(x + 1, y),
(x - 1, y + 1),
(x, y + 1),
(x + 1, y + 1),
]
let adjacentValues = adjacentPositions
.filter { x, y in xRange.contains(x) && yRange.contains(y) }
.map { x, y in values[y][x] }
var counts: [Acre: Int] = [:]
for value in adjacentValues {
if let count = counts[value] {
counts[value] = count + 1
} else {
counts[value] = 1
}
}
return counts
}
}
func main() {
var past: [Grid] = []
var grid = Grid(StdIn().map { line in line.map(parseInputCharacter) })
for i in 0 ..< iterations {
grid = grid.iterate()
if let cycle = findCycle(startingWith: grid, inPast: past) {
grid = cycle[(iterations - i - 1) % cycle.count]
break
}
past.append(grid)
}
print(grid)
print(grid.count(of: .trees) * grid.count(of: .lumberyard))
}
func findCycle(startingWith grid: Grid, inPast past: [Grid]) -> [Grid]? {
for (offset, element) in past.enumerated().reversed() {
if grid == element {
return Array(past[offset ..< past.count])
}
}
return nil
}
func parseInputCharacter(_ character: Character) -> Acre {
switch character {
case ".":
return .openGround
case "|":
return .trees
case "#":
return .lumberyard
default:
fatalError("Could not parse \"\(character)\".")
}
}
|
mit
|
5713c97e64fe4839825dd9424e85b09a
| 26.016529 | 117 | 0.507801 | 3.810023 | false | false | false | false |
nixzhu/Baby
|
Sources/BabyBrain/Meta.swift
|
1
|
4559
|
/*
* @nixzhu (zhuhongxu@gmail.com)
*/
public struct Meta {
let isPublic: Bool
let modelType: String
let codable: Bool
let declareVariableProperties: Bool
let jsonDictionaryName: String
let useSnakeCaseKeyDecodingStrategy: Bool
let propertyMap: [String: String]
let arrayObjectMap: [String: String]
let propertyTypeMap: [String: String]
public struct EnumProperty {
public let name: String
public struct Case {
public let name: String
public let rawValue: String?
public init(name: String, rawValue: String?) {
self.name = name
self.rawValue = rawValue
}
public var string: String {
if let rawValue = rawValue {
return "\(name): \(rawValue)"
} else {
return name
}
}
}
public let cases: [Case]?
public init(name: String, cases: [(String, String?)]?) {
self.name = name
if let cases = cases {
self.cases = cases.map({ .init(name: $0, rawValue: $1) })
} else {
self.cases = nil
}
}
public var string: String {
var string = name
if let cases = cases, !cases.isEmpty {
string += "["
string += cases.map({ $0.string }).joined(separator: ", ")
string += "]"
}
return string
}
}
let enumProperties: [EnumProperty]
func contains(enumPropertyKey: String ) -> Bool {
for enumProperty in enumProperties {
if enumProperty.name == enumPropertyKey {
return true
}
}
return false
}
func enumCases(key: String) -> [EnumProperty.Case]? {
for enumProperty in enumProperties {
if enumProperty.name == key {
return enumProperty.cases
}
}
return nil
}
public init(isPublic: Bool, modelType: String, codable: Bool, declareVariableProperties: Bool, jsonDictionaryName: String, useSnakeCaseKeyDecodingStrategy: Bool, propertyMap: [String: String], arrayObjectMap: [String: String], propertyTypeMap: [String: String], enumProperties: [EnumProperty]) {
self.isPublic = isPublic
self.modelType = modelType
self.codable = codable
self.declareVariableProperties = declareVariableProperties
self.jsonDictionaryName = jsonDictionaryName
self.useSnakeCaseKeyDecodingStrategy = useSnakeCaseKeyDecodingStrategy
self.propertyMap = propertyMap
self.arrayObjectMap = arrayObjectMap
self.propertyTypeMap = propertyTypeMap
self.enumProperties = enumProperties
}
public static var `default`: Meta {
return Meta(
isPublic: false,
modelType: "struct",
codable: false,
declareVariableProperties: false,
jsonDictionaryName: "[String: Any]",
useSnakeCaseKeyDecodingStrategy: false,
propertyMap: [:],
arrayObjectMap: [:],
propertyTypeMap: [:],
enumProperties: []
)
}
var publicCode: String {
return isPublic ? "public " : ""
}
var declareKeyword: String {
return declareVariableProperties ? "var" : "let"
}
}
extension Meta {
static let swiftKeywords: Set<String> = [
"Any",
"as",
"associatedtype",
"break",
"case",
"catch",
"class",
"continue",
"default",
"defer",
"deinit",
"do",
"else",
"enum",
"extension",
"fallthrough",
"false",
"fileprivate",
"for",
"func",
"guard",
"if",
"import",
"in",
"init",
"inout",
"internal",
"is",
"let",
"nil",
"open",
"operator",
"private",
"protocol",
"public",
"repeat",
"rethrows",
"return",
"Self",
"self",
"static",
"struct",
"subscript",
"super",
"switch",
"Type",
"throw",
"throws",
"true",
"try",
"typealias",
"var",
"where",
"while"
]
}
extension Meta {
public static var enumRawValueSeparator: String = "<@_@>"
}
|
mit
|
2d9912895ad6ad757addf2a67d3369f9
| 25.201149 | 299 | 0.511735 | 4.875936 | false | false | false | false |
billfromannarbor/pitchperfect
|
PitchPerfect/RecordSoundsViewController.swift
|
1
|
2384
|
//
// RecordSoundsViewController.swift
// PitchPerfect
//
// Created by Heitzeg, William on 12/14/16.
//
import UIKit
import AVFoundation
class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate {
var audioRecorder: AVAudioRecorder!
@IBOutlet weak var RecordingLabel: UILabel!
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var stopRecordingButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
stopRecordingButton.isEnabled=false
}
@IBAction func recordAudio(_ sender: AnyObject) {
RecordingLabel.text = "Recording in Progress"
recordButton.isEnabled=false
stopRecordingButton.isEnabled=true
let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0] as String
let recordingName = "recordedVoice.wav"
let pathArray = [dirPath, recordingName]
let filePath = URL(string: pathArray.joined(separator: "/"))
let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayAndRecord, with:AVAudioSessionCategoryOptions.defaultToSpeaker)
try! audioRecorder = AVAudioRecorder(url: filePath!, settings: [:])
audioRecorder.delegate=self
audioRecorder.isMeteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record()
}
@IBAction func stopRecording(_ sender: AnyObject) {
recordButton.isEnabled=true
stopRecordingButton.isEnabled=false
RecordingLabel.text = "Tap to Record"
audioRecorder.stop()
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setActive(false)
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
if flag {
performSegue(withIdentifier: "stopRecording", sender: audioRecorder.url)
}
else {
print("recording was not successful")
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "stopRecording" {
let playSoundsVC = segue.destination as! PlaySoundsViewController
let recordedAudioURL = sender as! URL
playSoundsVC.recordedAudioURL = recordedAudioURL as NSURL!
}
}
}
|
apache-2.0
|
78da92a06dda445bd0fc36502c557e1c
| 33.550725 | 122 | 0.685403 | 5.570093 | false | false | false | false |
HTWDD/HTWDresden-iOS
|
HTWDD/Components/Schedule/Main/ScheduleBaseVC.swift
|
1
|
5078
|
//
// ScheduleBaseVC.swift
// HTWDD
//
// Created by Benjamin Herzog on 31.10.17.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import UIKit
import SideMenu
class ScheduleBaseVC: CollectionViewController {
let dataSource: ScheduleDataSource
private var lastSelectedIndexPath: IndexPath?
var auth: ScheduleService.Auth? {
didSet {
self.dataSource.auth = self.auth
}
}
init(configuration: ScheduleDataSource.Configuration, layout: UICollectionViewLayout) {
self.dataSource = ScheduleDataSource(configuration: configuration)
super.init(layout: layout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func initialSetup() {
super.initialSetup()
// DataSource
self.dataSource.collectionView = self.collectionView
}
// MARK: - ViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let todayButton = UIBarButtonItem(title: Loca.Schedule.today, style: .plain, target: self, action: #selector(self.handleJumpToToday))
self.navigationItem.rightBarButtonItem = todayButton
self.dataSource.load()
DispatchQueue.main.async {
self.register3DTouch()
}
NotificationCenter.default.rx
.notification(UIApplication.willEnterForegroundNotification)
.subscribe(onNext: { [weak self] _ in
self?.dataSource.invalidate()
})
.disposed(by: self.rx_disposeBag)
}
override func noResultsViewConfiguration() -> NoResultsView.Configuration? {
return .init(title: Loca.Schedule.noResults.title, message: Loca.Schedule.noResults.message, image: nil)
}
// MARK: - Private
private func register3DTouch() {
guard self.traitCollection.forceTouchCapability == .available else {
return
}
self.registerForPreviewing(with: self, sourceView: self.collectionView)
}
fileprivate func presentDetail(_ controller: UIViewController, animated: Bool) {
if UIDevice.current.userInterfaceIdiom == .pad {
let nc = controller.inNavigationController()
nc.modalPresentationStyle = .formSheet
self.present(nc, animated: animated, completion: nil)
} else {
self.navigationController?.pushViewController(controller, animated: animated)
}
}
@objc
func handleJumpToToday() {
self.jumpToToday(animated: true)
}
@objc
func jumpToToday(animated: Bool = true) {
let left = CGPoint(x: -self.collectionView.contentInset.left, y: self.collectionView.contentOffset.y)
self.collectionView.setContentOffset(left, animated: true)
}
}
// MARK: - CollectionViewDelegate
extension ScheduleBaseVC {
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let item = self.dataSource.lecture(at: indexPath) else {
// might be a free day
if let cell = collectionView.cellForItem(at: indexPath) as? FreeDayListCell {
if cell.label.text == Loca.Schedule.freeDay || cell.label.text == Loca.Schedule.holiday {
self.tabBarController?.view.emitConfetti(duration: 4)
}
}
return
}
self.lastSelectedIndexPath = indexPath
let detail = ScheduleDetailVC(lecture: item)
detail.onStatusChange = { [weak self, weak detail] in
// not working
// item.hidden = !item.hidden
PersistenceService().save([item.lecture.fullHash(): !item.hidden])
self?.dataSource.load()
detail?.update(viewModel: LectureViewModel(model: item))
}
self.presentDetail(detail, animated: true)
}
}
// MARK: - UIViewControllerPreviewingDelegate
extension ScheduleBaseVC: UIViewControllerPreviewingDelegate, HasSideBarItem {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard
let indexPath = self.collectionView.indexPathForItem(at: location),
let item = self.dataSource.lecture(at: indexPath)
else {
return nil
}
if let cell = self.collectionView.cellForItem(at: indexPath) {
cell.transform = .identity
previewingContext.sourceRect = cell.frame
}
self.lastSelectedIndexPath = indexPath
return ScheduleDetailVC(lecture: item)
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
self.presentDetail(viewControllerToCommit, animated: false)
}
}
// MARK: - AnimatedViewControllerTransitionDataSource
extension ScheduleBaseVC: AnimatedViewControllerTransitionDataSource {
func viewForTransition(_ transition: AnimatedViewControllerTransition) -> UIView? {
return self.lastSelectedIndexPath.flatMap(self.collectionView.cellForItem(at:))
}
}
|
gpl-2.0
|
eb31d9939d481919e0c784b3a676d48a
| 32.183007 | 143 | 0.681899 | 4.919574 | false | false | false | false |
phanviet/AppState
|
Example/AppState/SignInViewController.swift
|
1
|
2288
|
//
// SignInViewController.swift
// AppState
//
// Created by Phan Hong Viet on 11/30/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import UIKit
import AppState
class SignInViewController: UIViewController {
var isClearInput = false
@IBOutlet weak var userNameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let barBtnItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "back")
self.navigationItem.leftBarButtonItem = barBtnItem
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if isClearInput {
resetInput()
}
}
func back() {
AppWorkflow.sharedInstance.transitTo("backLandingPage")
}
private func resetInput() {
print("@signIn: Reset Input")
userNameTextField.text = ""
}
private func showSignInPage(context: StateContext?) {
// Reset input
if let context = context, isClearInput = context["isClearInput"] as? Bool {
self.isClearInput = isClearInput
} else {
self.isClearInput = false
}
AppWorkflow.currentViewControllerPushOrPopController(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func signInDidTouch(sender: AnyObject) {
var context = [String: AnyObject]()
context["username"] = userNameTextField.text
AppWorkflow.sharedInstance.transitTo("showWelcomePage", context: context)
}
}
extension SignInViewController: AppStateDelegate {
func onEnterState(eventName: String, currentState: String, from: String, to: String, context: StateContext?) {
switch eventName {
case "showSignInPage":
showSignInPage(context)
break
default:
break
}
}
}
|
mit
|
e9267b6d98a0218427bc4467fc63be5b
| 25.593023 | 116 | 0.698732 | 4.657841 | false | false | false | false |
Sega-Zero/Cereal
|
Cereal/CerealDecoder.swift
|
1
|
92476
|
//
// CerealDecoder.swift
// Cereal
//
// Created by James Richard on 8/3/15.
// Copyright © 2015 Weebly. All rights reserved.
//
import Foundation
private struct TypeIndexMap {
let type: Any.Type
let map: [String: Int]
}
private class TypeIndexMapHolder: SyncHolder<TypeIndexMap> {
func typeMap(forType type: Any.Type) -> [String: Int]? {
var result: [String: Int]? = nil
self.sync {
for item in self.values where item.type == type {
result = item.map
break
}
}
return result
}
func save(map: [String: Int], for type: Any.Type) {
self.appendData(TypeIndexMap(type: type, map: map))
}
}
private let typesHolder = TypeIndexMapHolder()
/**
A CerealDecoder handles decoding items that were encoded by a `CerealEncoder`.
*/
public struct CerealDecoder {
private var items: [CoderTreeValue]
private let reverseRange: StrideThrough<Int>
private let indexMap: [String: Int]?
fileprivate func item(forKey key: String) -> CoderTreeValue? {
if items.count > 100 { // it appears that on small amount of items, a simmple array enumeration is faster than a dictionary lookup
if let index = indexMap?[key], case let .pair(_, value) = items[index] {
return value
}
}
for index in reverseRange {
guard case let .pair(keyValue, value) = items[index], case let .string(itemKey) = keyValue else { continue }
if itemKey == key {
return value
}
}
return nil
}
/**
Initializes a `CerealDecoder` with the data contained in data.
- parameter data: The encoded data to decode from.
*/
public init(data: Data) throws {
guard let tree = CoderTreeValue(data: data) else { throw CerealError.invalidDataContent }
guard case .subTree(_) = tree else { throw CerealError.invalidDataContent }
self.init(tree: tree)
}
private init(tree: CoderTreeValue) {
switch tree {
case let .subTree(array):
items = array
let count = array.count - 1
reverseRange = stride(from: count, through: 0, by: -1)
case let .identifyingTree(_, array):
items = array
let count = array.count - 1
reverseRange = stride(from: count, through: 0, by: -1)
default:
items = []
reverseRange = stride(from: 0, through: 0, by: -1)
break
}
indexMap = nil
}
private init(items: [CoderTreeValue], map: [String: Int]) {
self.items = items
let count = items.count - 1
reverseRange = stride(from: count, through: 0, by: -1)
indexMap = map
}
// MARK: - Decoding
/**
Decodes the object contained in key.
This method can decode any of the structs conforming to `CerealRepresentable` or
any type that conforms to `IdentifyingCerealType`. If the type conforms to
`IdentifyingCerealType` it must be registered with Cereal before calling
this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedType: CerealRepresentable>(key: String) throws -> DecodedType? {
guard let data = item(forKey: key) else {
return nil
}
let result: DecodedType = try CerealDecoder.instantiate(value: data)
return result
}
/**
Decodes the object contained in key.
This method can decode any type that conforms to `CerealType`.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCereal<DecodedType: CerealType>(key: String) throws -> DecodedType? {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.instantiateCereal(value: data) as DecodedType
}
/**
Decodes the object contained in key.
This method can decode any type that conforms to `IdentifyingCerealType`.
Use this method if you want to decode an object into a protocol.
You must register the type with Cereal before it can be decoded properly.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeIdentifyingCereal(key: String) throws -> IdentifyingCerealType? {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.instantiateIdentifyingCereal(value: data)
}
// MARK: Arrays
/**
Decodes homogeneous arrays of type `DecodedType`, where `DecodedType`
conforms to `CerealRepresentable`.
This method does not support decoding `CerealType` objects, but
can decode `IndentifyingCerealType` objects.
If you are decoding a `IdentifyingCerealType` it must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedType: CerealRepresentable>(key: String) throws -> [DecodedType]? {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parse(array: data)
}
/**
Decodes heterogeneous arrays conforming to `CerealRepresentable`.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
If you are decoding a `IdentifyingCerealType` it must be registered
before calling this method.
- parameter key The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode(key: String) throws -> [CerealRepresentable]? {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parse(array: data)
}
/**
Decodes homogenous arrays of type `DecodedType`, where `DecodedType`
conforms to `CerealType`.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCereal<DecodedType: CerealType>(key: String) throws -> [DecodedType]? {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parseCereal(array: data)
}
/**
Decodes heterogeneous arrays conforming to `IdentifyingCerealType`.
You must register the type with Cereal before it can be decoded properly.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeIdentifyingCerealArray(key: String) throws -> [IdentifyingCerealType]? {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parseIdentifyingCereal(array: data)
}
// MARK: Arrays of Dictionaries
/**
Decodes homogenous arrays containing dictionaries that have a key conforming to `CerealRepresentable`
and a value conforming to `CerealRepresentable`.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
If you are decoding a `IdentifyingCerealType` it must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedKeyType: CerealRepresentable & Hashable, DecodedValueType: CerealRepresentable>(key: String) throws -> [[DecodedKeyType: DecodedValueType]]? {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = [[DecodedKeyType: DecodedValueType]]()
decodedItems.reserveCapacity(items.count)
for item in items {
decodedItems.append(try CerealDecoder.parse(dictionary: item))
}
return decodedItems
}
/**
Decodes homogenous arrays containing dictionaries that have a key conforming to `CerealRepresentable`
and a value conforming to `CerealType`.
This method does not support decoding `CerealType` objects for its key, but
can decode `IdentifyingCerealType` objects.
If you are decoding a `IdentifyingCerealType` for the key it must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCereal<DecodedKeyType: CerealRepresentable & Hashable, DecodedValueType: CerealType>(key: String) throws -> [[DecodedKeyType: DecodedValueType]]? {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = [[DecodedKeyType: DecodedValueType]]()
decodedItems.reserveCapacity(items.count)
for item in items {
let value: [DecodedKeyType: DecodedValueType] = try CerealDecoder.parseCereal(dictionary: item)
decodedItems.append(value)
}
return decodedItems
}
/**
Decodes homogenous arrays containing dictionaries that have a key conforming to `CerealType`
and a value conforming to `CerealRepresentable`.
This method does not support decoding `CerealType` objects for its value, but
can decode `IdentifyingCerealType` objects.
If you are decoding a `IdentifyingCerealType` it must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCereal<DecodedKeyType: CerealType & Hashable, DecodedValueType: CerealRepresentable>(key: String) throws -> [[DecodedKeyType: DecodedValueType]]? {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = [[DecodedKeyType: DecodedValueType]]()
decodedItems.reserveCapacity(items.count)
for item in items {
decodedItems.append(try CerealDecoder.parseCereal(dictionary: item))
}
return decodedItems
}
/**
Decodes homogenous arrays containing dictionaries that have a key conforming to `CerealType`
and a value conforming to `CerealType`.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCerealPair<DecodedKeyType: CerealType & Hashable, DecodedValueType: CerealType>(key: String) throws -> [[DecodedKeyType: DecodedValueType]]? {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = [[DecodedKeyType: DecodedValueType]]()
decodedItems.reserveCapacity(items.count)
for item in items {
decodedItems.append(try CerealDecoder.parseCerealPair(dictionary: item))
}
return decodedItems
}
/**
Decodes heterogenous arrays containing dictionaries that have a key conforming to `CerealRepresentable`
and a value conforming to `IdentifyingCerealType`.
This method does not support decoding `CerealType` objects for its key, but
can decode `IdentifyingCerealType` objects.
If you are decoding a `IdentifyingCerealType` for the key it must be registered
before calling this method. The `IdentifyingCerealType` must be registered
for the value before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeIdentifyingCerealArray<DecodedKeyType: CerealRepresentable & Hashable>(key: String) throws -> [[DecodedKeyType: IdentifyingCerealType]]? {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = [[DecodedKeyType: IdentifyingCerealType]]()
decodedItems.reserveCapacity(items.count)
for item in items {
decodedItems.append(try CerealDecoder.parseIdentifyingCereal(dictionary: item))
}
return decodedItems
}
/**
Decodes heterogenous arrays containing dictionaries that have a key conforming to `CerealType`
and a value conforming to `IdentifyingCerealType`.
The `IdentifyingCerealType` for the value must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCerealToIdentifyingCerealArray<DecodedKeyType: CerealType & Hashable>(key: String) throws -> [[DecodedKeyType: IdentifyingCerealType]]? {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = [[DecodedKeyType: IdentifyingCerealType]]()
decodedItems.reserveCapacity(items.count)
for item in items {
decodedItems.append(try CerealDecoder.parseCerealToIdentifyingCereal(dictionary: item))
}
return decodedItems
}
// MARK: Dictionaries
/**
Decodes homogeneous dictoinaries conforming to `CerealRepresentable` for both the key
and value.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedKeyType: CerealRepresentable & Hashable, DecodedValueType: CerealRepresentable>(key: String) throws -> [DecodedKeyType: DecodedValueType]? {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parse(dictionary: data)
}
/**
Decodes heterogeneous values conforming to `CerealRepresentable`.
They key must be homogeneous.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedKeyType: CerealRepresentable & Hashable>(key: String) throws -> [DecodedKeyType: CerealRepresentable]? {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parse(dictionary: data)
}
/**
Decodes homogenous values conforming to `CerealType` and keys conforming to
`CerealRepresentable`.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
The `IdentifyingCerealType` for the value must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCereal<DecodedKeyType: CerealRepresentable & Hashable, DecodedValueType: CerealType>(key: String) throws -> [DecodedKeyType: DecodedValueType]? {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parseCereal(dictionary: data)
}
/**
Decodes homogenous values conforming to `CerealRepresentable` and keys conforming to
`CerealType`.
This method does not support decoding `CerealType` for its value objects, but
can decode `IdentifyingCerealType` objects.
The `IdentifyingCerealType` for the value must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCereal<DecodedKeyType: CerealType & Hashable, DecodedValueType: CerealRepresentable>(key: String) throws -> [DecodedKeyType: DecodedValueType]? {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parseCereal(dictionary: data)
}
/**
Decodes homogenous values conforming to `CerealRepresentable` and keys conforming to
`IdentifyingCerealType`.
The `IdentifyingCerealType` for the value must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeIdentifyingCerealDictionary<DecodedKeyType: CerealRepresentable & Hashable>(key: String) throws -> [DecodedKeyType: IdentifyingCerealType]? {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parseIdentifyingCereal(dictionary: data)
}
/**
Decodes homogenous keys and values conforming to `CerealType`.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCerealPair<DecodedKeyType: CerealType & Hashable, DecodedValueType: CerealType>(key: String) throws -> [DecodedKeyType: DecodedValueType]? {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parseCerealPair(dictionary: data)
}
/**
Decodes homogenous values conforming to `IdentifyingCerealType` and keys conforming to
`CerealType`.
The `IdentifyingCerealType` for the value must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCerealToIdentifyingCerealDictionary<DecodedKeyType: CerealType & Hashable>(key: String) throws -> [DecodedKeyType: IdentifyingCerealType]? {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parseCerealToIdentifyingCereal(dictionary: data)
}
// MARK: Dictionaries of Arrays
/**
Decodes a homogenous dictionary of arrays conforming to `CerealRepresentable`. The key
must be a `CerealRepresentable`.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
The `IdentifyingCerealType` for the value must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedKeyType: CerealRepresentable & Hashable, DecodedValueType: CerealRepresentable>(key: String) throws -> [DecodedKeyType: [DecodedValueType]]? {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = Dictionary<DecodedKeyType, [DecodedValueType]>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
decodedItems[decodedKey] = try CerealDecoder.parse(array: value)
}
return decodedItems
}
/**
Decodes a homogenous dictionary of arrays conforming to `CerealType`. The key
must be a `CerealRepresentable`.
This method does not support decoding `CerealType` keys, but
can decode `IdentifyingCerealType` keys.
The `IdentifyingCerealType` for the key must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCereal<DecodedKeyType: CerealRepresentable & Hashable, DecodedValueType: CerealType>(key: String) throws -> [DecodedKeyType: [DecodedValueType]]? {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = Dictionary<DecodedKeyType, [DecodedValueType]>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
decodedItems[decodedKey] = try CerealDecoder.parseCereal(array: value)
}
return decodedItems
}
/**
Decodes a homogenous dictionary of arrays conforming to `CerealRepresentable`. The key
must be a `CerealType`.
This method does not support decoding `CerealType` values, but
can decode `IdentifyingCerealType` values.
The `IdentifyingCerealType` for the value must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCereal<DecodedKeyType: CerealType & Hashable, DecodedValueType: CerealRepresentable>(key: String) throws -> [DecodedKeyType: [DecodedValueType]]? {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = Dictionary<DecodedKeyType, [DecodedValueType]>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiateCereal(value: key)
decodedItems[decodedKey] = try CerealDecoder.parse(array: value)
}
return decodedItems
}
/**
Decodes a homogenous dictionary of arrays conforming to `CerealType`. The key
must be a `CerealType`.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCerealPair<DecodedKeyType: CerealType & Hashable, DecodedValueType: CerealType>(key: String) throws -> [DecodedKeyType: [DecodedValueType]]? {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = Dictionary<DecodedKeyType, [DecodedValueType]>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiateCereal(value: key)
decodedItems[decodedKey] = try CerealDecoder.parseCereal(array: value)
}
return decodedItems
}
/**
Decodes a heterogenous dictionary of arrays conforming to `IdentifyingCerealType`. The key
must be a `CerealRepresentable`.
This method does not support decoding `CerealType` keys, but
can decode `IdentifyingCerealType` keys.
The `IdentifyingCerealType` for the value must be registered
before calling this method. If using an `IdentifyingCerealType` for the
key it must also be registered before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeIdentifyingCerealDictionary<DecodedKeyType: CerealRepresentable & Hashable>(key: String) throws -> [DecodedKeyType: [IdentifyingCerealType]]? {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = Dictionary<DecodedKeyType, [IdentifyingCerealType]>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
decodedItems[decodedKey] = try CerealDecoder.parseIdentifyingCereal(array: value)
}
return decodedItems
}
/**
Decodes a heterogeneous dictionary of arrays conforming to `IdentifyingCerealType`. The key
must be a `CerealType`.
The `IdentifyingCerealType` for the value must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCerealToIdentifyingCerealDictionary<DecodedKeyType: CerealType & Hashable>(key: String) throws -> [DecodedKeyType: [IdentifyingCerealType]]? {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = Dictionary<DecodedKeyType, [IdentifyingCerealType]>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiateCereal(value: key)
decodedItems[decodedKey] = try CerealDecoder.parseIdentifyingCereal(array: value)
}
return decodedItems
}
// MARK: - Root Decoding
// These methods are convenience methods that allow users to quickly decode their object.
// MARK: Basic items
/**
Decodes objects encoded with `CerealEncoder.data<ItemType: CerealRepresentable>(with rootItem: ItemType)`.
If you encoded custom objects conforming to `CerealType`, use `CerealDecoder.rootCerealItem(with:)` instead.
- parameter data: The data returned by `CerealEncoder.data(withRoot: ItemType)`.
- returns: The instantiated object.
*/
public static func rootItem<ItemType: CerealRepresentable>(with data: Data) throws -> ItemType {
let decoder = try CerealDecoder(data: data)
guard let item: ItemType = try decoder.decode(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemType: CerealRepresentable>(withRoot: ItemType)`.
This method will instantiate your custom `CerealType` objects.
- parameter data: The data returned by `CerealEncoder.data<ItemType: CerealRepresentable>(withRoot: ItemType)`.
- returns: The instantiated object.
*/
public static func rootCerealItem<ItemType: CerealType>(with data: Data) throws -> ItemType {
let decoder = try CerealDecoder(data: data)
guard let item: ItemType = try decoder.decodeCereal(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data(withRoot: IdentifyingCerealType)`.
The `IdentifyingCerealType` for the returned object must be registered
before calling this method.
- parameter data: The data returned by `CerealEncoder.data(withRoot: IdentifyingCerealType)`.
- returns: The instantiated object.
*/
public static func rootIdentifyingCerealItem(with data: Data) throws -> IdentifyingCerealType {
let decoder = try CerealDecoder(data: data)
guard let item: IdentifyingCerealType = try decoder.decodeIdentifyingCereal(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
// MARK: Arrays
/**
Decodes objects encoded with `CerealEncoder.data<ItemType: CerealRepresentable>(withRoot: [ItemType])`.
If you encoded custom objects conforming to `CerealType`, use `CerealDecoder.rootCerealItems(with:)` instead.
- parameter data: The data returned by `CerealEncoder.data<ItemType: CerealRepresentable>(withRoot: [ItemType])`.
- returns: The instantiated object.
*/
public static func rootItems<ItemType: CerealRepresentable>(with data: Data) throws -> [ItemType] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemType] = try decoder.decode(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemType: CerealRepresentable>(withRoot: [ItemType])`.
This method will instantiate your custom `CerealType` objects.
- param data: The data returned by `CerealEncoder.data<ItemType: CerealRepresentable>(withRoot: [ItemType])`.
- returns: The instantiated object.
*/
public static func rootCerealItems<ItemType: CerealType>(with data: Data) throws -> [ItemType] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemType] = try decoder.decodeCereal(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data(withRoot: [IdentifyingCerealType])`.
The `IdentifyingCerealType` for the returned object must be registered
before calling this method.
- parameter data: The data returned by `CerealEncoder.data(withRoot: [IdentifyingCerealType])`.
- returns: The instantiated object.
*/
public static func rootIdentifyingCerealItems(with data: Data) throws -> [IdentifyingCerealType] {
let decoder = try CerealDecoder(data: data)
guard let item: [IdentifyingCerealType] = try decoder.decodeIdentifyingCerealArray(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
// MARK: Arrays of Dictionaries
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [[ItemKeyType: ItemValueType]])`.
If you encoded custom objects conforming to `CerealType`, use `CerealDecoder.rootCerealItems` instead.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [[ItemKeyType: ItemValueType]])`.
- returns: The instantiated object.
*/
public static func rootItems<ItemKeyType: CerealRepresentable & Hashable, ItemValueType: CerealRepresentable>(with data: Data) throws -> [[ItemKeyType: ItemValueType]] {
let decoder = try CerealDecoder(data: data)
guard let item: [[ItemKeyType: ItemValueType]] = try decoder.decode(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [[ItemKeyType: ItemValueType]])`.
This method will instantiate your custom `CerealType` objects.
If you encoded custom objects for the ItemKeyType conforming to `CerealType`, use `CerealDecoder.rootCerealPairItems(with:)` instead.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [[ItemKeyType: ItemValueType]])`.
- returns: The instantiated object.
*/
public static func rootCerealItems<ItemKeyType: CerealRepresentable & Hashable, ItemValueType: CerealType>(with data: Data) throws -> [[ItemKeyType: ItemValueType]] {
let decoder = try CerealDecoder(data: data)
guard let item: [[ItemKeyType: ItemValueType]] = try decoder.decodeCereal(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [[ItemKeyType: ItemValueType]])`.
This method will instantiate your custom `CerealType` objects.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [[ItemKeyType: ItemValueType]])`.
- returns: The instantiated object.
*/
public static func rootCerealPairItems<ItemKeyType: CerealType & Hashable, ItemValueType: CerealType>(with data: Data) throws -> [[ItemKeyType: ItemValueType]] {
let decoder = try CerealDecoder(data: data)
guard let item: [[ItemKeyType: ItemValueType]] = try decoder.decodeCerealPair(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [[ItemKeyType: IdentifyingCerealType]])`.
If you encoded custom objects for the ItemKeyType conforming to `CerealType`, use `CerealDecoder.rootCerealToIdentifyingCerealItems(with:)` instead.
The `IdentifyingCerealType` for the returned object must be registered
before calling this method.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [[ItemKeyType: IdentifyingCerealType]])`.
- returns: The instantiated object.
*/
public static func rootIdentifyingCerealItems<ItemKeyType: CerealRepresentable & Hashable>(with data: Data) throws -> [[ItemKeyType: IdentifyingCerealType]] {
let decoder = try CerealDecoder(data: data)
guard let item: [[ItemKeyType: IdentifyingCerealType]] = try decoder.decodeIdentifyingCerealArray(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [[ItemKeyType: IdentifyingCerealType]])`.
If you encoded custom objects for the ItemKeyType conforming to `CerealType`, use `CerealDecoder.rootCerealToIdentifyingCerealItems(with:)` instead.
The `IdentifyingCerealType` for the returned object must be registered
before calling this method.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [[ItemKeyType: IdentifyingCerealType]])`.
- returns: The instantiated object.
*/
public static func rootCerealToIdentifyingCerealItems<ItemKeyType: CerealType & Hashable>(with data: Data) throws -> [[ItemKeyType: IdentifyingCerealType]] {
let decoder = try CerealDecoder(data: data)
guard let item: [[ItemKeyType: IdentifyingCerealType]] = try decoder.decodeCerealToIdentifyingCerealArray(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
// MARK: Dictionaries
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: ItemValueType])`.
If you encoded custom objects for your values or keys conforming to `CerealType`, use `CerealDecoder.rootCerealItems(with:)` instead.
If you encoded custom objects for your values and keys conforming to `CerealType`, use `CerealDecoder.rootCerealPairItems(with:)` instead.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: ItemValueType])`.
- returns: The instantiated object.
*/
public static func rootItems<ItemKeyType: CerealRepresentable & Hashable, ItemValueType: CerealRepresentable>(with data: Data) throws -> [ItemKeyType: ItemValueType] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: ItemValueType] = try decoder.decode(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: ItemValueType])`.
If you encoded custom objects for your keys conforming to `CerealType`, use `CerealDecoder.rootCerealPairItems(with:)` instead.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: ItemValueType])`.
- returns: The instantiated object.
*/
public static func rootCerealItems<ItemKeyType: CerealRepresentable & Hashable, ItemValueType: CerealType>(with data: Data) throws -> [ItemKeyType: ItemValueType] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: ItemValueType] = try decoder.decodeCereal(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: ItemValueType])`.
If you encoded custom objects for your values conforming to `CerealType`, use `CerealDecoder.rootCerealPairItems(with:)` instead.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: ItemValueType])`.
- returns: The instantiated object.
*/
public static func rootCerealItems<ItemKeyType: CerealType & Hashable, ItemValueType: CerealRepresentable>(with data: Data) throws -> [ItemKeyType: ItemValueType] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: ItemValueType] = try decoder.decodeCereal(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: ItemValueType])`.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: ItemValueType])`.
- returns: The instantiated object.
*/
public static func rootCerealPairItems<ItemKeyType: CerealType & Hashable, ItemValueType: CerealType>(with data: Data) throws -> [ItemKeyType: ItemValueType] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: ItemValueType] = try decoder.decodeCerealPair(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [ItemKeyType: IdentifyingCerealType])`.
If you encoded custom objects for your keys conforming to `CerealType`, use `CerealDecoder.rootCerealToIdentifyingCerealItems(with:)` instead.
The `IdentifyingCerealType` for the returned object must be registered
before calling this method.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [ItemKeyType: IdentifyingCerealType])`.
- returns: The instantiated object.
*/
public static func rootIdentifyingCerealItems<ItemKeyType: CerealRepresentable & Hashable>(with data: Data) throws -> [ItemKeyType: IdentifyingCerealType] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: IdentifyingCerealType] = try decoder.decodeIdentifyingCerealDictionary(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [ItemKeyType: IdentifyingCerealType])`.
The `IdentifyingCerealType` for the returned object must be registered
before calling this method.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [ItemKeyType: IdentifyingCerealType])`.
- returns: The instantiated object.
*/
public static func rootCerealToIdentifyingCerealItems<ItemKeyType: CerealType & Hashable>(with data: Data) throws -> [ItemKeyType: IdentifyingCerealType] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: IdentifyingCerealType] = try decoder.decodeCerealToIdentifyingCerealDictionary(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
// MARK: Dictionaries of Arrays
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
If you encoded custom objects for your values or keys conforming to `CerealType`, use `CerealDecoder.rootCerealItems(with:)` instead.
If you encoded custom objects for your values and keys conforming to `CerealType`, use `CerealDecoder.rootCerealPairItems(with:)` instead.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
- returns: The instantiated object.
*/
public static func rootItems<ItemKeyType: CerealRepresentable & Hashable, ItemValueType: CerealRepresentable>(with data: Data) throws -> [ItemKeyType: [ItemValueType]] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: [ItemValueType]] = try decoder.decode(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
If you encoded custom objects for your keys conforming to `CerealType`, use `CerealDecoder.rootCerealPairItems(with:)` instead.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
- returns: The instantiated object.
*/
public static func rootCerealItems<ItemKeyType: CerealRepresentable & Hashable, ItemValueType: CerealType>(with data: Data) throws -> [ItemKeyType: [ItemValueType]] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: [ItemValueType]] = try decoder.decodeCereal(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
If you encoded custom objects for your values conforming to `CerealType`, use `CerealDecoder.rootCerealPairItems(with:)` instead.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
- returns: The instantiated object.
*/
public static func rootCerealItems<ItemKeyType: CerealType & Hashable, ItemValueType: CerealRepresentable>(with data: Data) throws -> [ItemKeyType: [ItemValueType]] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: [ItemValueType]] = try decoder.decodeCereal(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
- returns: The instantiated object.
*/
public static func rootCerealPairItems<ItemKeyType: CerealType & Hashable, ItemValueType: CerealType>(with data: Data) throws -> [ItemKeyType: [ItemValueType]] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: [ItemValueType]] = try decoder.decodeCerealPair(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [ItemKeyType: [IdentifyingCerealType]])`.
If you encoded custom objects for your keys conforming to `CerealType`, use `CerealDecoder.rootCerealToIdentifyingCerealItems(with:)` instead.
The `IdentifyingCerealType` for the returned object must be registered
before calling this method.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [ItemKeyType: [IdentifyingCerealType]])`.
- returns: The instantiated object.
*/
public static func rootIdentifyingCerealItems<ItemKeyType: CerealRepresentable & Hashable>(with data: Data) throws -> [ItemKeyType: [IdentifyingCerealType]] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: [IdentifyingCerealType]] = try decoder.decodeIdentifyingCerealDictionary(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [ItemKeyType: [IdentifyingCerealType]])`.
The `IdentifyingCerealType` for the returned object must be registered
before calling this method.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [ItemKeyType: [IdentifyingCerealType]])`.
- returns: The instantiated object.
*/
public static func rootCerealToIdentifyingCerealItems<ItemKeyType: CerealType & Hashable>(with data: Data) throws -> [ItemKeyType: [IdentifyingCerealType]] {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: [IdentifyingCerealType]] = try decoder.decodeCerealToIdentifyingCerealDictionary(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
// MARK: - Instantiators
// Instantiators take a CoderTreeValue, optionally through a Generic, and instantiate the object
// being asked for
/// Used for primitive or identifying cereal values
fileprivate static func instantiate(value: CoderTreeValue) throws -> CerealRepresentable {
switch value {
case let .string(val): return val
case let .int(val): return val
case let .int64(val): return val
case let .double(val): return val
case let .float(val): return val
case let .bool(val): return val
case let .date(val): return val
case let .url(val): return val
case let .data(val): return val
case .pair, .array, .subTree:
throw CerealError.invalidEncoding(".Array / .Cereal / .Dictionary not expected")
case .identifyingTree:
return try instantiateIdentifyingCereal(value: value)
}
}
fileprivate static func instantiate<DecodedType: CerealRepresentable>(value: CoderTreeValue) throws -> DecodedType {
guard let decodedResult: DecodedType = try CerealDecoder.instantiate(value: value) as? DecodedType else {
throw CerealError.invalidEncoding("Failed to decode value \(value)")
}
return decodedResult
}
/// Helper method to improve decoding speed for large objects:
/// method returns index map to read value for key without enumerating through all the items
fileprivate static func propertiesIndexMap(for type: Any.Type, value: CoderTreeValue) -> [String: Int] {
if let map = typesHolder.typeMap(forType: type) {
return map
}
func buildIndexMap(items: [CoderTreeValue]) -> [String: Int] {
// assuming the array of decoded values always contains constant number of entries
var indexMap = [String: Int]()
for (index,item) in items.enumerated() {
guard case let .pair(keyValue, _) = item, case let .string(itemKey) = keyValue else { continue }
indexMap[itemKey] = index
}
return indexMap
}
switch value {
case let .identifyingTree(_, items):
let map = buildIndexMap(items: items)
typesHolder.save(map: map, for: type)
return map
case let .subTree(items):
let map = buildIndexMap(items: items)
typesHolder.save(map: map, for: type)
return map
default:
return [:]
}
}
/// Used for CerealType where we have type data from the compiler
fileprivate static func instantiateCereal<DecodedType: CerealType>(value: CoderTreeValue) throws -> DecodedType {
let map = CerealDecoder.propertiesIndexMap(for: DecodedType.self, value: value)
let cereal: CerealDecoder
switch value {
case let .identifyingTree(_, items):
cereal = CerealDecoder(items: items, map: map)
case let .subTree(items):
cereal = CerealDecoder(items: items, map: map)
default:
throw CerealError.invalidEncoding("Invalid type found: \(value)")
}
return try DecodedType.init(decoder: cereal)
}
fileprivate static func instantiateIdentifyingCereal(value: CoderTreeValue) throws -> IdentifyingCerealType {
guard case let .identifyingTree(identifier, items) = value else {
throw CerealError.rootItemNotFound
}
let type = try identifyingCerealType(withIdentifier: identifier)
let map = CerealDecoder.propertiesIndexMap(for: type.self, value: value)
let cereal = CerealDecoder(items: items, map: map)
return try type.init(decoder: cereal)
}
// MARK: - Parsers
// Parsers are to DRY up some of the decoding code. For example, [CerealType] and [CerealRepresentable: [CerealType]] can reuse a parser for decoding
// the array of CerealType.
fileprivate static func parse(array: CoderTreeValue) throws -> [CerealRepresentable] {
guard case let .array(items) = array else { throw CerealError.typeMismatch("\(array) should be of type Array (line \(#line))") }
var decodedItems = [CerealRepresentable]()
decodedItems.reserveCapacity(items.count)
for item in items {
decodedItems.append(try CerealDecoder.instantiate(value: item))
}
return decodedItems
}
fileprivate static func parse<DecodedType: CerealRepresentable>(array: CoderTreeValue) throws -> [DecodedType] {
guard case let .array(items) = array else { throw CerealError.typeMismatch("\(array) should be of type Array (line \(#line))") }
var decodedItems = [DecodedType]()
decodedItems.reserveCapacity(items.count)
for item in items {
let decodedValue: DecodedType = try CerealDecoder.instantiate(value: item)
decodedItems.append(decodedValue)
}
return decodedItems
}
fileprivate static func parseCereal<DecodedType: CerealType>(array: CoderTreeValue) throws -> [DecodedType] {
guard case let .array(items) = array else { throw CerealError.typeMismatch("\(array) should be of type Array (line \(#line))") }
var decodedItems = [DecodedType]()
decodedItems.reserveCapacity(items.count)
for item in items {
decodedItems.append(try CerealDecoder.instantiateCereal(value: item))
}
return decodedItems
}
fileprivate static func parseIdentifyingCereal(array: CoderTreeValue) throws -> [IdentifyingCerealType] {
guard case let .array(items) = array else { throw CerealError.typeMismatch("\(array) should be of type Array (line \(#line))") }
var decodedItems = [IdentifyingCerealType]()
decodedItems.reserveCapacity(items.count)
for item in items {
decodedItems.append(try CerealDecoder.instantiateIdentifyingCereal(value: item))
}
return decodedItems
}
fileprivate static func parse<DecodedKeyType: Hashable & CerealRepresentable>(dictionary: CoderTreeValue) throws -> [DecodedKeyType: CerealRepresentable] {
guard case let .array(items) = dictionary else { throw CerealError.rootItemNotFound }
var decodedItems = Dictionary<DecodedKeyType, CerealRepresentable>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
decodedItems[decodedKey] = try CerealDecoder.instantiate(value: value)
}
return decodedItems
}
fileprivate static func parse<DecodedKeyType: Hashable & CerealRepresentable, DecodedValueType: CerealRepresentable>(dictionary: CoderTreeValue) throws -> [DecodedKeyType: DecodedValueType] {
guard case let .array(items) = dictionary else { throw CerealError.typeMismatch("\(dictionary) should be an Array of pairs (line \(#line))") }
var decodedItems = Dictionary<DecodedKeyType, DecodedValueType>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.rootItemNotFound }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
let decodedValue: DecodedValueType = try CerealDecoder.instantiate(value: value)
decodedItems[decodedKey] = decodedValue
}
return decodedItems
}
fileprivate static func parseCereal<DecodedKeyType: Hashable & CerealRepresentable, DecodedValueType: CerealType>(dictionary: CoderTreeValue) throws -> [DecodedKeyType: DecodedValueType] {
guard case let .array(items) = dictionary else { throw CerealError.typeMismatch("\(dictionary) should be an Array of pairs (line \(#line))") }
var decodedItems = Dictionary<DecodedKeyType, DecodedValueType>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
decodedItems[decodedKey] = try CerealDecoder.instantiateCereal(value: value) as DecodedValueType
}
return decodedItems
}
fileprivate static func parseCereal<DecodedKeyType: Hashable & CerealType, DecodedValueType: CerealRepresentable>(dictionary: CoderTreeValue) throws -> [DecodedKeyType: DecodedValueType] {
guard case let .array(items) = dictionary else { throw CerealError.typeMismatch("\(dictionary) should be an Array of pairs (line \(#line))") }
var decodedItems = Dictionary<DecodedKeyType, DecodedValueType>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.rootItemNotFound }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiateCereal(value: key)
let decodedValue: DecodedValueType = try CerealDecoder.instantiate(value: value)
decodedItems[decodedKey] = decodedValue
}
return decodedItems
}
fileprivate static func parseCerealPair<DecodedKeyType: Hashable & CerealType, DecodedValueType: CerealType>(dictionary: CoderTreeValue) throws -> [DecodedKeyType: DecodedValueType] {
guard case let .array(items) = dictionary else { throw CerealError.typeMismatch("\(dictionary) should be an Array of pairs (line \(#line))") }
var decodedItems = Dictionary<DecodedKeyType, DecodedValueType>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiateCereal(value: key)
let decodedValue: DecodedValueType = try CerealDecoder.instantiateCereal(value: value)
decodedItems[decodedKey] = decodedValue
}
return decodedItems
}
fileprivate static func parseIdentifyingCereal<DecodedKeyType: Hashable & CerealRepresentable>(dictionary: CoderTreeValue) throws -> [DecodedKeyType: IdentifyingCerealType] {
guard case let .array(items) = dictionary else { throw CerealError.typeMismatch("\(dictionary) should be an Array of pairs (line \(#line))") }
var decodedItems = Dictionary<DecodedKeyType, IdentifyingCerealType>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
decodedItems[decodedKey] = try CerealDecoder.instantiateIdentifyingCereal(value: value)
}
return decodedItems
}
fileprivate static func parseCerealToIdentifyingCereal<DecodedKeyType: Hashable & CerealType>(dictionary: CoderTreeValue) throws -> [DecodedKeyType: IdentifyingCerealType] {
guard case let .array(items) = dictionary else { throw CerealError.typeMismatch("\(dictionary) should be an Array of pairs (line \(#line))") }
var decodedItems = Dictionary<DecodedKeyType, IdentifyingCerealType>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiateCereal(value: key)
decodedItems[decodedKey] = try CerealDecoder.instantiateIdentifyingCereal(value: value)
}
return decodedItems
}
}
// MARK: - RawRepresentable overrides -
public extension CerealDecoder {
// MARK: - Decoding
/**
Decodes the object contained in key.
This method can decode any of the structs conforming to `CerealRepresentable` or
any type that conforms to `IdentifyingCerealType`. If the type conforms to
`IdentifyingCerealType` it must be registered with Cereal before calling
this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedType: RawRepresentable & CerealRepresentable>(key: String) throws -> DecodedType? where DecodedType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
let decodedResult: DecodedType = try CerealDecoder.instantiate(value: data)
return decodedResult
}
// MARK: Arrays
/**
Decodes homogeneous arrays of type `DecodedType`, where `DecodedType`
conforms to `CerealRepresentable`.
This method does not support decoding `CerealType` objects, but
can decode `IndentifyingCerealType` objects.
If you are decoding a `IdentifyingCerealType` it must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedType: RawRepresentable & CerealRepresentable>(key: String) throws -> [DecodedType]? where DecodedType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parse(array: data)
}
// MARK: Arrays of Dictionaries
/**
Decodes homogenous arrays containing dictionaries that have a key conforming to `CerealRepresentable`
and a value conforming to `CerealRepresentable`.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
If you are decoding a `IdentifyingCerealType` it must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedKeyType: RawRepresentable & CerealRepresentable & Hashable, DecodedValueType: CerealRepresentable>(key: String) throws -> [[DecodedKeyType: DecodedValueType]]? where DecodedKeyType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = [[DecodedKeyType: DecodedValueType]]()
decodedItems.reserveCapacity(items.count)
for item in items {
decodedItems.append(try CerealDecoder.parse(dictionary: item))
}
return decodedItems
}
/**
Decodes homogenous arrays containing dictionaries that have a key conforming to `CerealRepresentable`
and a value conforming to `CerealRepresentable`.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
If you are decoding a `IdentifyingCerealType` it must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedKeyType: RawRepresentable & CerealRepresentable & Hashable, DecodedValueType: RawRepresentable & CerealRepresentable>(key: String) throws -> [[DecodedKeyType: DecodedValueType]]? where DecodedKeyType.RawValue: CerealRepresentable, DecodedValueType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = [[DecodedKeyType: DecodedValueType]]()
decodedItems.reserveCapacity(items.count)
for item in items {
decodedItems.append(try CerealDecoder.parse(dictionary: item))
}
return decodedItems
}
/**
Decodes homogenous arrays containing dictionaries that have a key conforming to `CerealRepresentable`
and a value conforming to `CerealType`.
This method does not support decoding `CerealType` objects for its key, but
can decode `IdentifyingCerealType` objects.
If you are decoding a `IdentifyingCerealType` for the key it must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCereal<DecodedKeyType: RawRepresentable & CerealRepresentable & Hashable, DecodedValueType: CerealType>(key: String) throws -> [[DecodedKeyType: DecodedValueType]]? where DecodedKeyType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = [[DecodedKeyType: DecodedValueType]]()
decodedItems.reserveCapacity(items.count)
for item in items {
decodedItems.append(try CerealDecoder.parseCereal(dictionary: item))
}
return decodedItems
}
/**
Decodes homogenous arrays containing dictionaries that have a key conforming to `CerealType`
and a value conforming to `CerealRepresentable`.
This method does not support decoding `CerealType` objects for its value, but
can decode `IdentifyingCerealType` objects.
If you are decoding a `IdentifyingCerealType` it must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCereal<DecodedKeyType: CerealType & Hashable, DecodedValueType: RawRepresentable & CerealRepresentable>(key: String) throws -> [[DecodedKeyType: DecodedValueType]]? where DecodedValueType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = [[DecodedKeyType: DecodedValueType]]()
decodedItems.reserveCapacity(items.count)
for item in items {
decodedItems.append(try CerealDecoder.parseCereal(dictionary: item))
}
return decodedItems
}
// MARK: Dictionaries
/**
Decodes homogeneous dictoinaries conforming to `CerealRepresentable` for both the key
and value.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedKeyType: RawRepresentable & CerealRepresentable & Hashable, DecodedValueType: CerealRepresentable>(key: String) throws -> [DecodedKeyType: DecodedValueType]? where DecodedKeyType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parse(dictionary: data)
}
/**
Decodes homogeneous dictoinaries conforming to `CerealRepresentable` for both the key
and value.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedKeyType: RawRepresentable & CerealRepresentable & Hashable, DecodedValueType: RawRepresentable & CerealRepresentable>(key: String) throws -> [DecodedKeyType: DecodedValueType]? where DecodedKeyType.RawValue: CerealRepresentable, DecodedValueType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parse(dictionary: data)
}
/**
Decodes heterogeneous values conforming to `CerealRepresentable`.
They key must be homogeneous.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedKeyType: RawRepresentable & CerealRepresentable & Hashable>(key: String) throws -> [DecodedKeyType: CerealRepresentable]? where DecodedKeyType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parse(dictionary: data)
}
/**
Decodes homogenous values conforming to `CerealType` and keys conforming to
`CerealRepresentable`.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
The `IdentifyingCerealType` for the value must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCereal<DecodedKeyType: RawRepresentable & CerealRepresentable & Hashable, DecodedValueType: CerealType>(key: String) throws -> [DecodedKeyType: DecodedValueType]? where DecodedKeyType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parseCereal(dictionary: data)
}
/**
Decodes homogenous values conforming to `CerealRepresentable` and keys conforming to
`IdentifyingCerealType`.
The `IdentifyingCerealType` for the value must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeIdentifyingCerealDictionary<DecodedKeyType: RawRepresentable & CerealRepresentable & Hashable>(key: String) throws -> [DecodedKeyType: IdentifyingCerealType]? where DecodedKeyType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
return try CerealDecoder.parseIdentifyingCereal(dictionary: data)
}
// MARK: Dictionaries of Arrays
/**
Decodes a homogenous dictionary of arrays conforming to `CerealRepresentable`. The key
must be a `CerealRepresentable`.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
The `IdentifyingCerealType` for the value must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedKeyType: RawRepresentable & CerealRepresentable & Hashable, DecodedValueType: CerealRepresentable>(key: String) throws -> [DecodedKeyType: [DecodedValueType]]? where DecodedKeyType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = Dictionary<DecodedKeyType, [DecodedValueType]>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.rootItemNotFound }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
decodedItems[decodedKey] = try CerealDecoder.parse(array: value)
}
return decodedItems
}
/**
Decodes a homogenous dictionary of arrays conforming to `CerealRepresentable`. The key
must be a `CerealRepresentable`.
This method does not support decoding `CerealType` objects, but
can decode `IdentifyingCerealType` objects.
The `IdentifyingCerealType` for the value must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decode<DecodedKeyType: RawRepresentable & CerealRepresentable & Hashable, DecodedValueType: RawRepresentable & CerealRepresentable>(key: String) throws -> [DecodedKeyType: [DecodedValueType]]? where DecodedKeyType.RawValue: CerealRepresentable, DecodedValueType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = Dictionary<DecodedKeyType, [DecodedValueType]>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
decodedItems[decodedKey] = try CerealDecoder.parse(array: value)
}
return decodedItems
}
/**
Decodes a homogenous dictionary of arrays conforming to `CerealType`. The key
must be a `CerealRepresentable`.
This method does not support decoding `CerealType` keys, but
can decode `IdentifyingCerealType` keys.
The `IdentifyingCerealType` for the key must be registered
before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeCereal<DecodedKeyType: RawRepresentable & CerealRepresentable & Hashable, DecodedValueType: CerealType>(key: String) throws -> [DecodedKeyType: [DecodedValueType]]? where DecodedKeyType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = Dictionary<DecodedKeyType, [DecodedValueType]>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
decodedItems[decodedKey] = try CerealDecoder.parseCereal(array: value)
}
return decodedItems
}
/**
Decodes a heterogenous dictionary of arrays conforming to `IdentifyingCerealType`. The key
must be a `CerealRepresentable`.
This method does not support decoding `CerealType` keys, but
can decode `IdentifyingCerealType` keys.
The `IdentifyingCerealType` for the value must be registered
before calling this method. If using an `IdentifyingCerealType` for the
key it must also be registered before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeIdentifyingCerealDictionary<DecodedKeyType: RawRepresentable & CerealRepresentable & Hashable>(key: String) throws -> [DecodedKeyType: [IdentifyingCerealType]]? where DecodedKeyType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("Expected array but \(data) found")
}
var decodedItems = Dictionary<DecodedKeyType, [IdentifyingCerealType]>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
decodedItems[decodedKey] = try CerealDecoder.parseIdentifyingCereal(array: value)
}
return decodedItems
}
// MARK: - Root Decoding
// These methods are convenience methods that allow users to quickly decode their object.
// MARK: Arrays of Dictionaries
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
If you encoded custom objects for your values or keys conforming to `CerealType`, use `CerealDecoder.rootCerealItems(with:)` instead.
If you encoded custom objects for your values and keys conforming to `CerealType`, use `CerealDecoder.rootCerealPairItems(with:)` instead.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
- returns: The instantiated object.
*/
public static func rootItems<ItemKeyType: RawRepresentable & CerealRepresentable & Hashable, ItemValueType: CerealRepresentable>(with data: Data) throws -> [ItemKeyType: [ItemValueType]] where ItemKeyType.RawValue: CerealRepresentable {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: [ItemValueType]] = try decoder.decode(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
If you encoded custom objects for your values or keys conforming to `CerealType`, use `CerealDecoder.rootCerealItems(with:)` instead.
If you encoded custom objects for your values and keys conforming to `CerealType`, use `CerealDecoder.rootCerealPairItems(with:)` instead.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
- returns: The instantiated object.
*/
public static func rootItems<ItemKeyType: RawRepresentable & CerealRepresentable & Hashable, ItemValueType: RawRepresentable & CerealRepresentable>(with data: Data) throws -> [ItemKeyType: [ItemValueType]] where ItemKeyType.RawValue: CerealRepresentable, ItemValueType.RawValue: CerealRepresentable {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: [ItemValueType]] = try decoder.decode(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
If you encoded custom objects for your keys conforming to `CerealType`, use `CerealDecoder.rootCerealPairItems(with:)` instead.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>, ItemValueType: CerealRepresentable>(withRoot: [ItemKeyType: [ItemValueType]])`.
- returns: The instantiated object.
*/
public static func rootCerealItems<ItemKeyType: RawRepresentable & CerealRepresentable & Hashable, ItemValueType: CerealType>(with data: Data) throws -> [ItemKeyType: [ItemValueType]] where ItemKeyType.RawValue: CerealRepresentable {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: [ItemValueType]] = try decoder.decodeCereal(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
// MARK: Dictionaries of Arrays
/**
Decodes objects encoded with `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [ItemKeyType: [IdentifyingCerealType]])`.
If you encoded custom objects for your keys conforming to `CerealType`, use `CerealDecoder.rootCerealToIdentifyingCerealItems(with:)` instead.
The `IdentifyingCerealType` for the returned object must be registered
before calling this method.
- parameter data: The data returned by `CerealEncoder.data<ItemKeyType: protocol<CerealRepresentable, Hashable>>(withRoot: [ItemKeyType: [IdentifyingCerealType]])`.
- returns: The instantiated object.
*/
public static func rootIdentifyingCerealItems<ItemKeyType: RawRepresentable & CerealRepresentable & Hashable>(with data: Data) throws -> [ItemKeyType: [IdentifyingCerealType]] where ItemKeyType.RawValue: CerealRepresentable {
let decoder = try CerealDecoder(data: data)
guard let item: [ItemKeyType: [IdentifyingCerealType]] = try decoder.decodeIdentifyingCerealDictionary(key: rootKey) else { throw CerealError.rootItemNotFound }
return item
}
// MARK: Arrays of Dictionaries
/**
Decodes heterogenous arrays containing dictionaries that have a key conforming to `CerealRepresentable`
and a value conforming to `IdentifyingCerealType`.
This method does not support decoding `CerealType` objects for its key, but
can decode `IdentifyingCerealType` objects.
If you are decoding a `IdentifyingCerealType` for the key it must be registered
before calling this method. The `IdentifyingCerealType` must be registered
for the value before calling this method.
- parameter key: The key that the object being decoded resides at.
- returns: The instantiated object, or nil if no object was at the specified key.
*/
public func decodeIdentifyingCerealArray<DecodedKeyType: RawRepresentable & CerealRepresentable & Hashable>(key: String) throws -> [[DecodedKeyType: IdentifyingCerealType]]? where DecodedKeyType.RawValue: CerealRepresentable {
guard let data = item(forKey: key) else {
return nil
}
guard case let .array(items) = data else {
throw CerealError.typeMismatch("\(data) should be an array (line \(#line))")
}
var decodedItems = [[DecodedKeyType: IdentifyingCerealType]]()
decodedItems.reserveCapacity(items.count)
for item in items {
decodedItems.append(try CerealDecoder.parseIdentifyingCereal(dictionary: item))
}
return decodedItems
}
}
// MARK: - RawRepresentable private functions overrides -
fileprivate extension CerealDecoder {
// MARK: - Instantiators
// Instantiators take a CoderTreeValue, optionally through a Generic, and instantiate the object
// being asked for
/// Used for primitive or identifying cereal values
fileprivate static func instantiate<DecodedType: RawRepresentable>(value: CoderTreeValue) throws -> DecodedType where DecodedType: CerealRepresentable, DecodedType.RawValue: CerealRepresentable {
guard let rawValue = try CerealDecoder.instantiate(value: value) as? DecodedType.RawValue, let decodedResult = DecodedType(rawValue: rawValue) else {
throw CerealError.typeMismatch("Failed to decode value \(value)")
}
return decodedResult
}
// MARK: - Parsers
fileprivate static func parse<DecodedType: RawRepresentable>(array: CoderTreeValue) throws -> [DecodedType] where DecodedType: CerealRepresentable, DecodedType.RawValue: CerealRepresentable {
guard case let .array(items) = array else { throw CerealError.typeMismatch("\(array) should be of type Array (line \(#line))") }
var decodedItems = [DecodedType]()
decodedItems.reserveCapacity(items.count)
for item in items {
let decodedValue: DecodedType = try CerealDecoder.instantiate(value: item)
decodedItems.append(decodedValue)
}
return decodedItems
}
fileprivate static func parse<DecodedKeyType: RawRepresentable & Hashable & CerealRepresentable>(dictionary: CoderTreeValue) throws -> [DecodedKeyType: CerealRepresentable] where DecodedKeyType.RawValue: CerealRepresentable {
guard case let .array(items) = dictionary else { throw CerealError.typeMismatch("\(dictionary) should be an Array of pairs (line \(#line))") }
var decodedItems = Dictionary<DecodedKeyType, CerealRepresentable>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
decodedItems[decodedKey] = try CerealDecoder.instantiate(value: value)
}
return decodedItems
}
fileprivate static func parse<DecodedKeyType: RawRepresentable & Hashable & CerealRepresentable, DecodedValueType: CerealRepresentable>(dictionary: CoderTreeValue) throws -> [DecodedKeyType: DecodedValueType] where DecodedKeyType.RawValue: CerealRepresentable {
guard case let .array(items) = dictionary else { throw CerealError.typeMismatch("\(dictionary) should be an Array of pairs (line \(#line))") }
var decodedItems = Dictionary<DecodedKeyType, DecodedValueType>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
let decodedValue: DecodedValueType = try CerealDecoder.instantiate(value: value)
decodedItems[decodedKey] = decodedValue
}
return decodedItems
}
fileprivate static func parse<DecodedKeyType: RawRepresentable & Hashable & CerealRepresentable, DecodedValueType: RawRepresentable & CerealRepresentable>(dictionary: CoderTreeValue) throws -> [DecodedKeyType: DecodedValueType] where DecodedKeyType.RawValue: CerealRepresentable, DecodedValueType.RawValue: CerealRepresentable {
guard case let .array(items) = dictionary else { throw CerealError.typeMismatch("\(dictionary) should be an Array of pairs (line \(#line))") }
var decodedItems = Dictionary<DecodedKeyType, DecodedValueType>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
let decodedValue: DecodedValueType = try CerealDecoder.instantiate(value: value)
decodedItems[decodedKey] = decodedValue
}
return decodedItems
}
fileprivate static func parseCereal<DecodedKeyType: RawRepresentable & Hashable & CerealRepresentable, DecodedValueType: CerealType>(dictionary: CoderTreeValue) throws -> [DecodedKeyType: DecodedValueType] where DecodedKeyType.RawValue: CerealRepresentable {
guard case let .array(items) = dictionary else { throw CerealError.typeMismatch("\(dictionary) should be an Array of pairs (line \(#line))") }
var decodedItems = Dictionary<DecodedKeyType, DecodedValueType>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
decodedItems[decodedKey] = try CerealDecoder.instantiateCereal(value: value) as DecodedValueType
}
return decodedItems
}
fileprivate static func parseCereal<DecodedKeyType: Hashable & CerealType, DecodedValueType: RawRepresentable & CerealRepresentable>(dictionary: CoderTreeValue) throws -> [DecodedKeyType: DecodedValueType] where DecodedValueType.RawValue: CerealRepresentable {
guard case let .array(items) = dictionary else { throw CerealError.typeMismatch("\(dictionary) should be an Array of pairs (line \(#line))") }
var decodedItems = Dictionary<DecodedKeyType, DecodedValueType>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiateCereal(value: key)
let decodedValue: DecodedValueType = try CerealDecoder.instantiate(value: value)
decodedItems[decodedKey] = decodedValue
}
return decodedItems
}
fileprivate static func parseIdentifyingCereal<DecodedKeyType: RawRepresentable & Hashable & CerealRepresentable>(dictionary: CoderTreeValue) throws -> [DecodedKeyType: IdentifyingCerealType] where DecodedKeyType.RawValue: CerealRepresentable {
guard case let .array(items) = dictionary else { throw CerealError.typeMismatch("\(dictionary) should be an Array of pairs (line \(#line))") }
var decodedItems = Dictionary<DecodedKeyType, IdentifyingCerealType>(minimumCapacity: items.count)
for item in items {
guard case let .pair(key, value) = item else { throw CerealError.typeMismatch("\(item) not expected (line \(#line))") }
let decodedKey: DecodedKeyType = try CerealDecoder.instantiate(value: key)
decodedItems[decodedKey] = try CerealDecoder.instantiateIdentifyingCereal(value: value)
}
return decodedItems
}
}
|
bsd-3-clause
|
e65203f0cbc011aaab0cf1d403ccebcf
| 46.618435 | 332 | 0.695496 | 4.825706 | false | false | false | false |
lucianomarisi/LoadIt
|
Sources/LoadIt/Protocols/ResourceOperationType.swift
|
1
|
1708
|
//
// ResourceOperation.swift
// LoadIt
//
// Created by Luciano Marisi on 26/06/2016.
// Copyright © 2016 Luciano Marisi. All rights reserved.
//
import Foundation
/// Define a type that is cancellable
public protocol Cancellable: class {
/// Returns whether or not the type has been cancelled
var cancelled: Bool { get }
}
public protocol Finishable: class {
/**
Method to be called when the type finished all it's work
- parameter errors: Any error from the work done
*/
func finish(errors: [NSError])
}
public protocol ResourceOperationType: Cancellable, Finishable {
associatedtype Resource: ResourceType
/**
Fetches a resource using the provided service
- parameter resource: The resource to fetch
- parameter service: The service to be used for fetching the resource
*/
func fetch<Service: ResourceServiceType where Service.Resource == Resource>(resource resource: Resource, usingService service: Service)
/**
Called when the operation has finished, called on Main thread
- parameter result: The result of the operation
*/
func didFinishFetchingResource(result result: Result<Resource.Model>)
}
public extension ResourceOperationType {
public func fetch<Service: ResourceServiceType where Service.Resource == Resource>(resource resource: Resource, usingService service: Service) {
if cancelled { return }
service.fetch(resource: resource) { [weak self] (result) in
NSThread.li_executeOnMain { [weak self] in
guard let strongSelf = self where !strongSelf.cancelled else { return }
strongSelf.finish([])
strongSelf.didFinishFetchingResource(result: result)
}
}
}
}
|
mit
|
5f5f3b6dd69514b96b975b0f19d6706d
| 27.932203 | 146 | 0.716462 | 4.626016 | false | false | false | false |
benlangmuir/swift
|
stdlib/public/core/Sort.swift
|
5
|
27366
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// sorted()/sort()
//===----------------------------------------------------------------------===//
extension Sequence where Element: Comparable {
/// Returns the elements of the sequence, sorted.
///
/// You can sort any sequence of elements that conform to the `Comparable`
/// protocol by calling this method. Elements are sorted in ascending order.
///
/// Here's an example of sorting a list of students' names. Strings in Swift
/// conform to the `Comparable` protocol, so the names are sorted in
/// ascending order according to the less-than operator (`<`).
///
/// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// let sortedStudents = students.sorted()
/// print(sortedStudents)
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
///
/// To sort the elements of your sequence in descending order, pass the
/// greater-than operator (`>`) to the `sorted(by:)` method.
///
/// let descendingStudents = students.sorted(by: >)
/// print(descendingStudents)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// The sorting algorithm is not guaranteed to be stable. A stable sort
/// preserves the relative order of elements that compare equal.
///
/// - Returns: A sorted array of the sequence's elements.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of the sequence.
@inlinable
public func sorted() -> [Element] {
return sorted(by: <)
}
}
extension Sequence {
/// Returns the elements of the sequence, sorted using the given predicate as
/// the comparison between elements.
///
/// When you want to sort a sequence of elements that don't conform to the
/// `Comparable` protocol, pass a predicate to this method that returns
/// `true` when the first element should be ordered before the second. The
/// elements of the resulting array are ordered according to the given
/// predicate.
///
/// In the following example, the predicate provides an ordering for an array
/// of a custom `HTTPResponse` type. The predicate orders errors before
/// successes and sorts the error responses by their error code.
///
/// enum HTTPResponse {
/// case ok
/// case error(Int)
/// }
///
/// let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
/// let sortedResponses = responses.sorted {
/// switch ($0, $1) {
/// // Order errors by code
/// case let (.error(aCode), .error(bCode)):
/// return aCode < bCode
///
/// // All successes are equivalent, so none is before any other
/// case (.ok, .ok): return false
///
/// // Order errors before successes
/// case (.error, .ok): return true
/// case (.ok, .error): return false
/// }
/// }
/// print(sortedResponses)
/// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]"
///
/// You also use this method to sort elements that conform to the
/// `Comparable` protocol in descending order. To sort your sequence in
/// descending order, pass the greater-than operator (`>`) as the
/// `areInIncreasingOrder` parameter.
///
/// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// let descendingStudents = students.sorted(by: >)
/// print(descendingStudents)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// Calling the related `sorted()` method is equivalent to calling this
/// method and passing the less-than operator (`<`) as the predicate.
///
/// print(students.sorted())
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
/// print(students.sorted(by: <))
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also `true`.
/// (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// The sorting algorithm is not guaranteed to be stable. A stable sort
/// preserves the relative order of elements for which
/// `areInIncreasingOrder` does not establish an order.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`.
/// - Returns: A sorted array of the sequence's elements.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of the sequence.
@inlinable
public func sorted(
by areInIncreasingOrder:
(Element, Element) throws -> Bool
) rethrows -> [Element] {
var result = ContiguousArray(self)
try result.sort(by: areInIncreasingOrder)
return Array(result)
}
}
extension MutableCollection
where Self: RandomAccessCollection, Element: Comparable {
/// Sorts the collection in place.
///
/// You can sort any mutable collection of elements that conform to the
/// `Comparable` protocol by calling this method. Elements are sorted in
/// ascending order.
///
/// Here's an example of sorting a list of students' names. Strings in Swift
/// conform to the `Comparable` protocol, so the names are sorted in
/// ascending order according to the less-than operator (`<`).
///
/// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// students.sort()
/// print(students)
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
///
/// To sort the elements of your collection in descending order, pass the
/// greater-than operator (`>`) to the `sort(by:)` method.
///
/// students.sort(by: >)
/// print(students)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// The sorting algorithm is not guaranteed to be stable. A stable sort
/// preserves the relative order of elements that compare equal.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of the collection.
@inlinable
public mutating func sort() {
sort(by: <)
}
}
extension MutableCollection where Self: RandomAccessCollection {
/// Sorts the collection in place, using the given predicate as the
/// comparison between elements.
///
/// When you want to sort a collection of elements that don't conform to
/// the `Comparable` protocol, pass a closure to this method that returns
/// `true` when the first element should be ordered before the second.
///
/// In the following example, the closure provides an ordering for an array
/// of a custom enumeration that describes an HTTP response. The predicate
/// orders errors before successes and sorts the error responses by their
/// error code.
///
/// enum HTTPResponse {
/// case ok
/// case error(Int)
/// }
///
/// var responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
/// responses.sort {
/// switch ($0, $1) {
/// // Order errors by code
/// case let (.error(aCode), .error(bCode)):
/// return aCode < bCode
///
/// // All successes are equivalent, so none is before any other
/// case (.ok, .ok): return false
///
/// // Order errors before successes
/// case (.error, .ok): return true
/// case (.ok, .error): return false
/// }
/// }
/// print(responses)
/// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]"
///
/// Alternatively, use this method to sort a collection of elements that do
/// conform to `Comparable` when you want the sort to be descending instead
/// of ascending. Pass the greater-than operator (`>`) operator as the
/// predicate.
///
/// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// students.sort(by: >)
/// print(students)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// `areInIncreasingOrder` must be a *strict weak ordering* over the
/// elements. That is, for any elements `a`, `b`, and `c`, the following
/// conditions must hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also `true`.
/// (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// The sorting algorithm is not guaranteed to be stable. A stable sort
/// preserves the relative order of elements for which
/// `areInIncreasingOrder` does not establish an order.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`. If `areInIncreasingOrder` throws an error during
/// the sort, the elements may be in a different order, but none will be
/// lost.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of the collection.
@inlinable
public mutating func sort(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
let didSortUnsafeBuffer: Void? =
try withContiguousMutableStorageIfAvailable { buffer in
try buffer._stableSortImpl(by: areInIncreasingOrder)
}
if didSortUnsafeBuffer == nil {
// Fallback since we can't use an unsafe buffer: sort into an outside
// array, then copy elements back in.
let sortedElements = try sorted(by: areInIncreasingOrder)
for (i, j) in zip(indices, sortedElements.indices) {
self[i] = sortedElements[j]
}
}
}
}
extension MutableCollection where Self: BidirectionalCollection {
/// Sorts `self[range]` according to `areInIncreasingOrder`. Stable.
///
/// - Precondition: `sortedEnd != range.lowerBound`
/// - Precondition: `elements[..<sortedEnd]` are already in order.
@inlinable
internal mutating func _insertionSort(
within range: Range<Index>,
sortedEnd: Index,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
var sortedEnd = sortedEnd
// Continue sorting until the sorted elements cover the whole sequence.
while sortedEnd != range.upperBound {
var i = sortedEnd
// Look backwards for `self[i]`'s position in the sorted sequence,
// moving each element forward to make room.
repeat {
let j = index(before: i)
// If `self[i]` doesn't belong before `self[j]`, we've found
// its position.
if try !areInIncreasingOrder(self[i], self[j]) {
break
}
swapAt(i, j)
i = j
} while i != range.lowerBound
formIndex(after: &sortedEnd)
}
}
/// Sorts `self[range]` according to `areInIncreasingOrder`. Stable.
@inlinable
public // @testable
mutating func _insertionSort(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
if range.isEmpty {
return
}
// One element is trivially already-sorted, so the actual sort can
// start on the second element.
let sortedEnd = index(after: range.lowerBound)
try _insertionSort(
within: range, sortedEnd: sortedEnd, by: areInIncreasingOrder)
}
/// Reverses the elements in the given range.
@inlinable
internal mutating func _reverse(
within range: Range<Index>
) {
var f = range.lowerBound
var l = range.upperBound
while f < l {
formIndex(before: &l)
swapAt(f, l)
formIndex(after: &f)
}
}
}
// FIXME(ABI): unused return value
/// Merges the elements in the ranges `lo..<mid` and `mid..<hi` using `buffer`
/// as out-of-place storage. Stable.
///
/// The unused return value is legacy ABI. It was originally added as a
/// workaround for a compiler bug (now fixed). See SR-14750 (rdar://45044610).
///
/// - Precondition: `lo..<mid` and `mid..<hi` must already be sorted according
/// to `areInIncreasingOrder`.
/// - Precondition: `buffer` must point to a region of memory at least as large
/// as `min(mid - lo, hi - mid)`.
/// - Postcondition: `lo..<hi` is sorted according to `areInIncreasingOrder`.
@discardableResult
@inlinable
internal func _merge<Element>(
low: UnsafeMutablePointer<Element>,
mid: UnsafeMutablePointer<Element>,
high: UnsafeMutablePointer<Element>,
buffer: UnsafeMutablePointer<Element>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Bool {
let lowCount = mid - low
let highCount = high - mid
var destLow = low // Lower bound of uninitialized storage
var bufferLow = buffer // Lower bound of the initialized buffer
var bufferHigh = buffer // Upper bound of the initialized buffer
// When we exit the merge, move any remaining elements from the buffer back
// into `destLow` (aka the collection we're sorting). The buffer can have
// remaining elements if `areIncreasingOrder` throws, or more likely if the
// merge runs out of elements from the array before exhausting the buffer.
defer {
destLow.moveInitialize(from: bufferLow, count: bufferHigh - bufferLow)
}
if lowCount < highCount {
// Move the lower group of elements into the buffer, then traverse from
// low to high in both the buffer and the higher group of elements.
//
// After moving elements, the storage and buffer look like this, where
// `x` is uninitialized memory:
//
// Storage: [x, x, x, x, x, 6, 8, 8, 10, 12, 15]
// ^ ^
// destLow srcLow
//
// Buffer: [4, 4, 7, 8, 9, x, ...]
// ^ ^
// bufferLow bufferHigh
buffer.moveInitialize(from: low, count: lowCount)
bufferHigh = bufferLow + lowCount
var srcLow = mid
// Each iteration moves the element that compares lower into `destLow`,
// preferring the buffer when equal to maintain stability. Elements are
// moved from either `bufferLow` or `srcLow`, with those pointers
// incrementing as elements are moved.
while bufferLow < bufferHigh && srcLow < high {
if try areInIncreasingOrder(srcLow.pointee, bufferLow.pointee) {
destLow.moveInitialize(from: srcLow, count: 1)
srcLow += 1
} else {
destLow.moveInitialize(from: bufferLow, count: 1)
bufferLow += 1
}
destLow += 1
}
} else {
// Move the higher group of elements into the buffer, then traverse from
// high to low in both the buffer and the lower group of elements.
//
// After moving elements, the storage and buffer look like this, where
// `x` is uninitialized memory:
//
// Storage: [4, 4, 7, 8, 9, 16, x, x, x, x, x]
// ^ ^
// srcHigh/destLow destHigh (past the end)
//
// Buffer: [8, 8, 10, 12, 15, x, ...]
// ^ ^
// bufferLow bufferHigh
buffer.moveInitialize(from: mid, count: highCount)
bufferHigh = bufferLow + highCount
var destHigh = high
var srcHigh = mid
destLow = mid
// Each iteration moves the element that compares higher into `destHigh`,
// preferring the buffer when equal to maintain stability. Elements are
// moved from either `bufferHigh - 1` or `srcHigh - 1`, with those
// pointers decrementing as elements are moved.
//
// Note: At the start of each iteration, each `...High` pointer points one
// past the element they're referring to.
while bufferHigh > bufferLow && srcHigh > low {
destHigh -= 1
if try areInIncreasingOrder(
(bufferHigh - 1).pointee, (srcHigh - 1).pointee
) {
srcHigh -= 1
destHigh.moveInitialize(from: srcHigh, count: 1)
// Moved an element from the lower initialized portion to the upper,
// sorted, initialized portion, so `destLow` moves down one.
destLow -= 1
} else {
bufferHigh -= 1
destHigh.moveInitialize(from: bufferHigh, count: 1)
}
}
}
return true
}
/// Calculates an optimal minimum run length for sorting a collection.
///
/// "... pick a minrun in range(32, 65) such that N/minrun is exactly a power
/// of 2, or if that isn't possible, is close to, but strictly less than, a
/// power of 2. This is easier to do than it may sound: take the first 6 bits
/// of N, and add 1 if any of the remaining bits are set."
/// - From the Timsort introduction, at
/// https://svn.python.org/projects/python/trunk/Objects/listsort.txt
///
/// - Parameter c: The number of elements in a collection.
/// - Returns: If `c <= 64`, returns `c`. Otherwise, returns a value in
/// `32...64`.
@inlinable
internal func _minimumMergeRunLength(_ c: Int) -> Int {
// Max out at `2^6 == 64` elements
let bitsToUse = 6
if c < 1 << bitsToUse {
return c
}
let offset = (Int.bitWidth - bitsToUse) - c.leadingZeroBitCount
let mask = (1 << offset) - 1
return c >> offset + (c & mask == 0 ? 0 : 1)
}
/// Returns the end of the next in-order run along with a Boolean value
/// indicating whether the elements in `start..<end` are in descending order.
///
/// - Precondition: `start < elements.endIndex`
@inlinable
internal func _findNextRun<C: RandomAccessCollection>(
in elements: C,
from start: C.Index,
by areInIncreasingOrder: (C.Element, C.Element) throws -> Bool
) rethrows -> (end: C.Index, descending: Bool) {
_internalInvariant(start < elements.endIndex)
var previous = start
var current = elements.index(after: start)
guard current < elements.endIndex else {
// This is a one-element run, so treating it as ascending saves a
// meaningless call to `reverse()`.
return (current, false)
}
// Check whether the run beginning at `start` is ascending or descending.
// An ascending run can include consecutive equal elements, but because a
// descending run will be reversed, it must be strictly descending.
let isDescending =
try areInIncreasingOrder(elements[current], elements[previous])
// Advance `current` until there's a break in the ascending / descending
// pattern.
repeat {
previous = current
elements.formIndex(after: ¤t)
} while try current < elements.endIndex &&
isDescending == areInIncreasingOrder(elements[current], elements[previous])
return(current, isDescending)
}
extension UnsafeMutableBufferPointer {
// FIXME(ABI): unused return value
/// Merges the elements at `runs[i]` and `runs[i - 1]`, using `buffer` as
/// out-of-place storage.
///
/// The unused return value is legacy ABI. It was originally added as a
/// workaround for a compiler bug (now fixed). See SR-14750 (rdar://45044610).
///
/// - Precondition: `runs.count > 1` and `i > 0`
/// - Precondition: `buffer` must have at least
/// `min(runs[i].count, runs[i - 1].count)` uninitialized elements.
@discardableResult
@inlinable
internal mutating func _mergeRuns(
_ runs: inout [Range<Index>],
at i: Int,
buffer: UnsafeMutablePointer<Element>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Bool {
_internalInvariant(runs[i - 1].upperBound == runs[i].lowerBound)
let low = runs[i - 1].lowerBound
let middle = runs[i].lowerBound
let high = runs[i].upperBound
try _merge(
low: baseAddress! + low,
mid: baseAddress! + middle,
high: baseAddress! + high,
buffer: buffer,
by: areInIncreasingOrder)
runs[i - 1] = low..<high
runs.remove(at: i)
return true
}
// FIXME(ABI): unused return value
/// Merges upper elements of `runs` until the required invariants are
/// satisfied.
///
/// The unused return value is legacy ABI. It was originally added as a
/// workaround for a compiler bug (now fixed). See SR-14750 (rdar://45044610).
///
/// - Precondition: `buffer` must have at least
/// `min(runs[i].count, runs[i - 1].count)` uninitialized elements.
/// - Precondition: The ranges in `runs` must be consecutive, such that for
/// any i, `runs[i].upperBound == runs[i + 1].lowerBound`.
@discardableResult
@inlinable
internal mutating func _mergeTopRuns(
_ runs: inout [Range<Index>],
buffer: UnsafeMutablePointer<Element>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Bool {
// The invariants for the `runs` array are:
// (a) - for all i in 2..<runs.count:
// - runs[i - 2].count > runs[i - 1].count + runs[i].count
// (b) - for c = runs.count - 1:
// - runs[c - 1].count > runs[c].count
//
// Loop until the invariant is satisfied for the top four elements of
// `runs`. Because this method is called for every added run, and only
// the top three runs are ever merged, this guarantees the invariant holds
// for the whole array.
//
// At all times, `runs` is one of the following, where W, X, Y, and Z are
// the counts of their respective ranges:
// - [ ...?, W, X, Y, Z ]
// - [ X, Y, Z ]
// - [ Y, Z ]
//
// If W > X + Y, X > Y + Z, and Y > Z, then the invariants are satisfied
// for the entirety of `runs`.
// The invariant is always in place for a single element.
while runs.count > 1 {
var lastIndex = runs.count - 1
// Check for the three invariant-breaking conditions, and break out of
// the while loop if none are met.
if lastIndex >= 3 &&
(runs[lastIndex - 3].count <=
runs[lastIndex - 2].count + runs[lastIndex - 1].count)
{
// Second-to-last three runs do not follow W > X + Y.
// Always merge Y with the smaller of X or Z.
if runs[lastIndex - 2].count < runs[lastIndex].count {
lastIndex -= 1
}
} else if lastIndex >= 2 &&
(runs[lastIndex - 2].count <=
runs[lastIndex - 1].count + runs[lastIndex].count)
{
// Last three runs do not follow X > Y + Z.
// Always merge Y with the smaller of X or Z.
if runs[lastIndex - 2].count < runs[lastIndex].count {
lastIndex -= 1
}
} else if runs[lastIndex - 1].count <= runs[lastIndex].count {
// Last two runs do not follow Y > Z, so merge Y and Z.
// This block is intentionally blank--the merge happens below.
} else {
// All invariants satisfied!
break
}
// Merge the runs at `i` and `i - 1`.
try _mergeRuns(
&runs, at: lastIndex, buffer: buffer, by: areInIncreasingOrder)
}
return true
}
// FIXME(ABI): unused return value
/// Merges elements of `runs` until only one run remains.
///
/// The unused return value is legacy ABI. It was originally added as a
/// workaround for a compiler bug (now fixed). See SR-14750 (rdar://45044610).
///
/// - Precondition: `buffer` must have at least
/// `min(runs[i].count, runs[i - 1].count)` uninitialized elements.
/// - Precondition: The ranges in `runs` must be consecutive, such that for
/// any i, `runs[i].upperBound == runs[i + 1].lowerBound`.
@discardableResult
@inlinable
internal mutating func _finalizeRuns(
_ runs: inout [Range<Index>],
buffer: UnsafeMutablePointer<Element>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Bool {
while runs.count > 1 {
try _mergeRuns(
&runs, at: runs.count - 1, buffer: buffer, by: areInIncreasingOrder)
}
return true
}
/// Sorts the elements of this buffer according to `areInIncreasingOrder`,
/// using a stable, adaptive merge sort.
///
/// The adaptive algorithm used is Timsort, modified to perform a straight
/// merge of the elements using a temporary buffer.
@inlinable
public mutating func _stableSortImpl(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
let minimumRunLength = _minimumMergeRunLength(count)
if count <= minimumRunLength {
try _insertionSort(
within: startIndex..<endIndex, by: areInIncreasingOrder)
return
}
// Use array's allocating initializer to create a temporary buffer---this
// keeps the buffer allocation going through the same tail-allocated path
// as other allocating methods.
//
// There's no need to set the initialized count within the initializing
// closure, since the buffer is guaranteed to be uninitialized at exit.
_ = try Array<Element>(_unsafeUninitializedCapacity: count / 2) {
buffer, _ in
var runs: [Range<Index>] = []
var start = startIndex
while start < endIndex {
// Find the next consecutive run, reversing it if necessary.
var (end, descending) =
try _findNextRun(in: self, from: start, by: areInIncreasingOrder)
if descending {
_reverse(within: start..<end)
}
// If the current run is shorter than the minimum length, use the
// insertion sort to extend it.
if end < endIndex && end - start < minimumRunLength {
let newEnd = Swift.min(endIndex, start + minimumRunLength)
try _insertionSort(
within: start..<newEnd, sortedEnd: end, by: areInIncreasingOrder)
end = newEnd
}
// Append this run and merge down as needed to maintain the `runs`
// invariants.
runs.append(start..<end)
try _mergeTopRuns(
&runs, buffer: buffer.baseAddress!, by: areInIncreasingOrder)
start = end
}
try _finalizeRuns(
&runs, buffer: buffer.baseAddress!, by: areInIncreasingOrder)
_internalInvariant(runs.count == 1, "Didn't complete final merge")
}
}
}
|
apache-2.0
|
80bbeee637df025dee908831737bbdd0
| 37.598025 | 91 | 0.619638 | 4.134461 | false | false | false | false |
Constructor-io/constructorio-client-swift
|
AutocompleteClient/FW/Logic/Result/CIOCollectionData.swift
|
1
|
954
|
//
// CIOCollectionData.swift
// Constructor.io
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import Foundation
/**
Struct encapsulating a collection
*/
public class CIOCollectionData: NSObject {
/**
Id of the collection
*/
public let id: String
/**
Display name of the collection
*/
public let display_name: String
/**
Additional metadata for the collection
*/
public let data: [String: Any]
/**
Create a collection object
- Parameters:
- json: JSON data from server reponse
*/
init?(json: JSONObject?) {
guard let json = json, let id = json["id"] as? String, let display_name = json["display_name"] as? String else {
return nil
}
let data = json["data"] as? [String: Any] ?? [:]
self.id = id
self.display_name = display_name
self.data = data
}
}
|
mit
|
5a7688358a95aa541c8222730ea52b28
| 19.717391 | 120 | 0.579224 | 4.161572 | false | false | false | false |
nolili/iOS-9-Sampler
|
iOS9Sampler/SampleViewControllers/AudioUnitComponentManagerViewController.swift
|
110
|
9075
|
//
// AudioUnitComponentManagerViewController.swift
// iOS9Sampler
//
// Created by Shuichi Tsutsumi on 2015/06/21.
// Copyright © 2015 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
import AVFoundation
import CoreAudioKit
class AudioUnitComponentManagerViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var viewBtn: UIBarButtonItem!
private var items = [AVAudioUnitComponent]()
private let engine = AVAudioEngine()
private let player = AVAudioPlayerNode()
private var file: AVAudioFile?
/// The currently selected `AUAudioUnit` effect, if any.
var audioUnit: AUAudioUnit?
/// The audio unit's presets.
var presetList = [AUAudioUnitPreset]()
/// Engine's effect node.
private var effect: AVAudioUnit?
override func viewDidLoad() {
super.viewDidLoad()
viewBtn = UIBarButtonItem(
title: "ShowAUVC",
style: UIBarButtonItemStyle.Plain,
target: self, action: "viewBtnTapped:")
self.navigationItem.setRightBarButtonItem(viewBtn, animated: false)
viewBtn.enabled = false
// setup engine and player
engine.attachNode(player)
guard let fileURL = NSBundle.mainBundle().URLForResource("drumLoop", withExtension: "caf") else {
fatalError("\"drumLoop.caf\" file not found.")
}
do {
let file = try AVAudioFile(forReading: fileURL)
self.file = file
engine.connect(player, to: engine.mainMixerNode, format: file.processingFormat)
}
catch {
fatalError("Could not create AVAudioFile instance. error: \(error).")
}
// extract available effects
var anyEffectDescription = AudioComponentDescription()
anyEffectDescription.componentType = kAudioUnitType_Effect
anyEffectDescription.componentSubType = 0
anyEffectDescription.componentManufacturer = 0
anyEffectDescription.componentFlags = 0
anyEffectDescription.componentFlagsMask = 0
items = AVAudioUnitComponentManager.sharedAudioUnitComponentManager()
.componentsMatchingDescription(anyEffectDescription)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Schedule buffers on the player.
self.scheduleLoop()
// Start the engine.
do {
try self.engine.start()
}
catch {
fatalError("Could not start engine. error: \(error).")
}
self.player.play()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.player.stop()
self.engine.stop()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
private func scheduleLoop() {
guard let file = file else {
fatalError("`file` must not be nil in \(__FUNCTION__).")
}
player.scheduleFile(file, atTime: nil) {
self.scheduleLoop()
}
}
private func selectEffectWithComponentDescription(componentDescription: AudioComponentDescription?, completionHandler: (Void -> Void) = {}) {
// Internal function to resume playing and call the completion handler.
func done() {
player.play()
completionHandler()
}
/*
Pause the player before re-wiring it. (It is not simple to keep it
playing across an effect insertion or deletion.)
*/
player.pause()
// Destroy any pre-existing effect.
if effect != nil {
// We have player -> effect -> mixer. Break both connections.
engine.disconnectNodeInput(effect!)
engine.disconnectNodeInput(engine.mainMixerNode)
// Connect player -> mixer.
engine.connect(player, to: engine.mainMixerNode, format: file!.processingFormat)
// We're done with the effect; release all references.
engine.detachNode(effect!)
effect = nil
audioUnit = nil
presetList = [AUAudioUnitPreset]()
}
// Insert the new effect, if any.
if let componentDescription = componentDescription {
AVAudioUnit.instantiateWithComponentDescription(componentDescription, options: []) { avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.effect = avAudioUnitEffect
self.engine.attachNode(avAudioUnitEffect)
// Disconnect player -> mixer.
self.engine.disconnectNodeInput(self.engine.mainMixerNode)
// Connect player -> effect -> mixer.
self.engine.connect(self.player, to: avAudioUnitEffect, format: self.file!.processingFormat)
self.engine.connect(avAudioUnitEffect, to: self.engine.mainMixerNode, format: self.file!.processingFormat)
self.audioUnit = avAudioUnitEffect.AUAudioUnit
self.presetList = avAudioUnitEffect.AUAudioUnit.factoryPresets ?? []
self.audioUnit?.requestViewControllerWithCompletionHandler { [weak self] viewController in
guard let strongSelf = self else { return }
strongSelf.viewBtn.enabled = viewController != nil ? true : false
}
done()
}
}
else {
done()
}
}
// =========================================================================
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count + 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
if indexPath.row == 0 {
cell.textLabel!.text = "No Effect"
cell.detailTextLabel!.text = ""
}
else {
let auComponent = items[indexPath.row - 1]
cell.textLabel!.text = auComponent.name
cell.detailTextLabel!.text = auComponent.manufacturerName
}
return cell
}
// =========================================================================
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let auComponent: AVAudioUnitComponent?
if indexPath.row == 0 {
// no effect
auComponent = nil
}
else {
auComponent = items[indexPath.row - 1]
}
self.selectEffectWithComponentDescription(
auComponent?.audioComponentDescription) { () -> Void in
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// =========================================================================
// MARK: - Actions
func viewBtnTapped(sender: AnyObject) {
// close
if self.childViewControllers.count > 0 {
let childViewController = childViewControllers.first!
childViewController.willMoveToParentViewController(nil)
childViewController.view.removeFromSuperview()
childViewController.removeFromParentViewController()
viewBtn.title = "ShowAUVC"
return
}
// open
self.audioUnit?.requestViewControllerWithCompletionHandler { [weak self] viewController in
guard let strongSelf = self else { return }
guard let viewController = viewController, view = viewController.view else { return }
strongSelf.addChildViewController(viewController)
let parentRect = strongSelf.view.bounds
view.frame = CGRectMake(
0,
parentRect.size.height / 2,
parentRect.size.width,
parentRect.size.height / 2)
strongSelf.view.addSubview(view)
viewController.didMoveToParentViewController(self)
strongSelf.viewBtn.title = "CloseAUVC"
}
}
}
|
mit
|
0a596180c21cfa9d1575b9e310f35ff6
| 32.985019 | 145 | 0.589046 | 5.824134 | false | false | false | false |
thomasvl/swift-protobuf
|
Sources/SwiftProtobufPluginLibrary/Descriptor.swift
|
2
|
36859
|
// Sources/SwiftProtobufPluginLibrary/Descriptor.swift - Descriptor wrappers
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// This is like Descriptor.{h,cc} in the google/protobuf C++ code, it provides
/// wrappers around the protos to make a more usable object graph for generation
/// and also provides some SwiftProtobuf specific additions that would be useful
/// to anyone generating something that uses SwiftProtobufs (like support the
/// `service` messages). It is *not* the intent for these to eventually be used
/// as part of some reflection or generate message api.
///
/// Unlike the C++ Descriptors, the intent is for these to *only* be used within
/// the context of a protoc plugin, meaning, the
/// `Google_Protobuf_FileDescriptorSet` used to create these will be *always*
/// be well formed by protoc and the guarentees it provides.
///
// -----------------------------------------------------------------------------
import Foundation
import SwiftProtobuf
/// The front interface for building/getting descriptors. The objects
/// vended from the here are different from the raw
/// `Google_Protobuf_*Proto` types in that they have all the cross object
/// references resolved or wired up, making for an easier to use object
/// model.
///
/// This is like the `DescriptorPool` class in the C++ protobuf library.
public final class DescriptorSet {
/// The list of `FileDescriptor`s in this set.
public let files: [FileDescriptor]
private let registry = Registry()
// Consturct out of a `Google_Protobuf_FileDescriptorSet` likely
// created by protoc.
public convenience init(proto: Google_Protobuf_FileDescriptorSet) {
self.init(protos: proto.file)
}
/// Consturct out of a ordered list of
/// `Google_Protobuf_FileDescriptorProto`s likely created by protoc. Since
/// .proto files can import other .proto files, the imports have to be
/// listed before the things that use them so the graph can be
/// reconstructed.
public init(protos: [Google_Protobuf_FileDescriptorProto]) {
let registry = self.registry
self.files = protos.map { return FileDescriptor(proto: $0, registry: registry) }
}
/// Lookup a specific file. The names for files are what was captured in
/// the `Google_Protobuf_FileDescriptorProto` when it was created, protoc
/// uses the path name for how the file was found.
///
/// This is a legacy api since it requires the file to be found or it aborts.
/// Mainly kept for grpc-swift compatibility.
@available(*, deprecated, renamed: "fileDescriptor(named:)")
public func lookupFileDescriptor(protoName name: String) -> FileDescriptor {
return registry.fileDescriptor(named: name)!
}
/// Find a specific file. The names for files are what was captured in
/// the `Google_Protobuf_FileDescriptorProto` when it was created, protoc
/// uses the path name for how the file was found.
public func fileDescriptor(named name: String) -> FileDescriptor? {
return registry.fileDescriptor(named: name)
}
/// Find the `Descriptor` for a named proto message.
public func descriptor(named fullName: String) -> Descriptor? {
return registry.descriptor(named: ".\(fullName)")
}
/// Find the `EnumDescriptor` for a named proto enum.
public func enumDescriptor(named fullName: String) -> EnumDescriptor? {
return registry.enumDescriptor(named: ".\(fullName)")
}
/// Find the `ServiceDescriptor` for a named proto service.
public func serviceDescriptor(named fullName: String) -> ServiceDescriptor? {
return registry.serviceDescriptor(named: ".\(fullName)")
}
}
/// Models a .proto file. `FileDescriptor`s are not directly created,
/// instead they are constructed/fetched via the `DescriptorSet` or
/// they are directly accessed via a `file` property on all the other
/// types of descriptors.
public final class FileDescriptor {
/// Syntax of this file.
public enum Syntax: RawRepresentable {
case proto2
case proto3
case unknown(String)
public init?(rawValue: String) {
switch rawValue {
case "proto2", "":
self = .proto2
case "proto3":
self = .proto3
default:
self = .unknown(rawValue)
}
}
public var rawValue: String {
switch self {
case .proto2:
return "proto2"
case .proto3:
return "proto3"
case .unknown(let value):
return value
}
}
/// The string form of the syntax.
public var name: String { return rawValue }
}
/// The filename used with protoc.
public let name: String
/// The proto package.
public let package: String
/// Syntax of this file.
public let syntax: Syntax
/// The imports for this file.
public let dependencies: [FileDescriptor]
/// The subset of the imports that were declared `public`.
public let publicDependencies: [FileDescriptor]
/// The subset of the imports that were declared `weak`.
public let weakDependencies: [FileDescriptor]
/// The enum defintions at the file scope level.
public let enums: [EnumDescriptor]
/// The message defintions at the file scope level.
public let messages: [Descriptor]
/// The extension field defintions at the file scope level.
public let extensions: [FieldDescriptor]
/// The service defintions at the file scope level.
public let services: [ServiceDescriptor]
/// The `Google_Protobuf_FileOptions` set on this file.
public let options: Google_Protobuf_FileOptions
private let sourceCodeInfo: Google_Protobuf_SourceCodeInfo
fileprivate init(proto: Google_Protobuf_FileDescriptorProto, registry: Registry) {
self.name = proto.name
self.package = proto.package
self.syntax = Syntax(rawValue: proto.syntax)!
self.options = proto.options
let protoPackage = proto.package
self.enums = proto.enumType.enumeratedMap {
return EnumDescriptor(proto: $1, index: $0, registry: registry, scope: protoPackage)
}
self.messages = proto.messageType.enumeratedMap {
return Descriptor(proto: $1, index: $0, registry: registry, scope: protoPackage)
}
self.extensions = proto.extension.enumeratedMap {
return FieldDescriptor(proto: $1, index: $0, registry: registry, isExtension: true)
}
self.services = proto.service.enumeratedMap {
return ServiceDescriptor(proto: $1, index: $0, registry: registry, scope: protoPackage)
}
// The compiler ensures there aren't cycles between a file and dependencies, so
// this doesn't run the risk of creating any retain cycles that would force these
// to have to be weak.
let dependencies = proto.dependency.map { return registry.fileDescriptor(named: $0)! }
self.dependencies = dependencies
self.publicDependencies = proto.publicDependency.map { dependencies[Int($0)] }
self.weakDependencies = proto.weakDependency.map { dependencies[Int($0)] }
self.sourceCodeInfo = proto.sourceCodeInfo
// Done initializing, register ourselves.
registry.register(file: self)
// descriptor.proto documents the files will be in deps order. That means we
// any external reference will have been in the previous files in the set.
self.enums.forEach { $0.bind(file: self, registry: registry, containingType: nil) }
self.messages.forEach { $0.bind(file: self, registry: registry, containingType: nil) }
self.extensions.forEach { $0.bind(file: self, registry: registry, containingType: nil) }
self.services.forEach { $0.bind(file: self, registry: registry) }
}
/// Fetch the source information for a give path. For more details on the paths
/// and what this information is, see `Google_Protobuf_SourceCodeInfo`.
///
/// For simpler access to the comments for give message, fields, enums; see
/// `Descriptor+Extensions.swift` and the `ProvidesLocationPath` and
/// `ProvidesSourceCodeLocation` protocols.
public func sourceCodeInfoLocation(path: IndexPath) -> Google_Protobuf_SourceCodeInfo.Location? {
guard let location = locationMap[path] else {
return nil
}
return location
}
// Lazy so this can be computed on demand, as the imported files won't need
// comments during generation.
private lazy var locationMap: [IndexPath:Google_Protobuf_SourceCodeInfo.Location] = {
var result: [IndexPath:Google_Protobuf_SourceCodeInfo.Location] = [:]
for loc in sourceCodeInfo.location {
let intList = loc.path.map { return Int($0) }
result[IndexPath(indexes: intList)] = loc
}
return result
}()
}
/// Describes a type of protocol message, or a particular group within a
/// message. `Descriptor`s are not directly created, instead they are
/// constructed/fetched via the `DescriptorSet` or they are directly accessed
/// via a `messageType` property on `FieldDescriptor`s, etc.
public final class Descriptor {
/// The type of this Message.
public enum WellKnownType: String {
/// An instance of google.protobuf.DoubleValue.
case doubleValue = "google.protobuf.DoubleValue"
/// An instance of google.protobuf.FloatValue.
case floatValue = "google.protobuf.FloatValue"
/// An instance of google.protobuf.Int64Value.
case int64Value = "google.protobuf.Int64Value"
/// An instance of google.protobuf.UInt64Value.
case uint64Value = "google.protobuf.UInt64Value"
/// An instance of google.protobuf.Int32Value.
case int32Value = "google.protobuf.Int32Value"
/// An instance of google.protobuf.UInt32Value.
case uint32Value = "google.protobuf.UInt32Value"
/// An instance of google.protobuf.StringValue.
case stringValue = "google.protobuf.StringValue"
/// An instance of google.protobuf.BytesValue.
case bytesValue = "google.protobuf.BytesValue"
/// An instance of google.protobuf.BoolValue.
case boolValue = "google.protobuf.BoolValue"
/// An instance of google.protobuf.Any.
case any = "google.protobuf.Any"
/// An instance of google.protobuf.FieldMask.
case fieldMask = "google.protobuf.FieldMask"
/// An instance of google.protobuf.Duration.
case duration = "google.protobuf.Duration"
/// An instance of google.protobuf.Timestamp.
case timestamp = "google.protobuf.Timestamp"
/// An instance of google.protobuf.Value.
case value = "google.protobuf.Value"
/// An instance of google.protobuf.ListValue.
case listValue = "google.protobuf.ListValue"
/// An instance of google.protobuf.Struct.
case `struct` = "google.protobuf.Struct"
}
/// The name of the message type, not including its scope.
public let name: String
/// The fully-qualified name of the message type, scope delimited by
/// periods. For example, message type "Foo" which is declared in package
/// "bar" has full name "bar.Foo". If a type "Baz" is nested within
/// Foo, Baz's `fullName` is "bar.Foo.Baz". To get only the part that
/// comes after the last '.', use name().
public let fullName: String
/// Index of this descriptor within the file or containing type's message
/// type array.
public let index: Int
/// The .proto file in which this message type was defined.
public var file: FileDescriptor { return _file! }
/// If this Descriptor describes a nested type, this returns the type
/// in which it is nested.
public private(set) unowned var containingType: Descriptor?
/// The `Google_Protobuf_MessageOptions` set on this Message.
public let options: Google_Protobuf_MessageOptions
// If this descriptor represents a well known type, which type it is.
public let wellKnownType: WellKnownType?
/// The enum defintions under this message.
public let enums: [EnumDescriptor]
/// The message defintions under this message. In the C++ Descriptor this
/// is `nested_type`.
public let messages: [Descriptor]
/// The fields of this message.
public let fields: [FieldDescriptor]
/// The oneofs in this message. This can include synthetic oneofs.
public let oneofs: [OneofDescriptor]
/// Non synthetic oneofs.
///
/// These always come first (enforced by the C++ Descriptor code). So this is always a
/// leading subset of `oneofs` (or the same if there are no synthetic entries).
public private(set) lazy var realOneofs: [OneofDescriptor] = {
// Lazy because `isSynthetic` can't be called until after `bind()`.
return self.oneofs.filter { !$0.isSynthetic }
}()
/// The extension field defintions under this message.
public let extensions: [FieldDescriptor]
/// The extension ranges declared for this message. They are returned in
/// the order they are defined in the .proto file.
public let extensionRanges: [Google_Protobuf_DescriptorProto.ExtensionRange]
/// The reserved field number ranges for this message. These are returned
/// in the order they are defined in the .proto file.
public let reservedRanges: [Range<Int32>]
/// The reserved field names for this message. These are returned in the
/// order they are defined in the .proto file.
public let reservedNames: [String]
/// Returns the `FieldDescriptor`s for the "key" and "value" fields. If
/// this isn't a map entry field, returns nil.
///
/// This is like the C++ Descriptor `map_key()` and `map_value()` methods.
public var mapKeyAndValue: (key: FieldDescriptor, value: FieldDescriptor)? {
guard options.mapEntry else { return nil }
assert(fields.count == 2)
return (key: fields[0], value: fields[1])
}
// Storage for `file`, will be set by bind()
private unowned var _file: FileDescriptor?
fileprivate init(proto: Google_Protobuf_DescriptorProto,
index: Int,
registry: Registry,
scope: String) {
self.name = proto.name
let fullName = scope.isEmpty ? proto.name : "\(scope).\(proto.name)"
self.fullName = fullName
self.index = index
self.options = proto.options
self.wellKnownType = WellKnownType(rawValue: fullName)
self.extensionRanges = proto.extensionRange
self.reservedRanges = proto.reservedRange.map { return $0.start ..< $0.end }
self.reservedNames = proto.reservedName
self.enums = proto.enumType.enumeratedMap {
return EnumDescriptor(proto: $1, index: $0, registry: registry, scope: fullName)
}
self.messages = proto.nestedType.enumeratedMap {
return Descriptor(proto: $1, index: $0, registry: registry, scope: fullName)
}
self.fields = proto.field.enumeratedMap {
return FieldDescriptor(proto: $1, index: $0, registry: registry)
}
self.oneofs = proto.oneofDecl.enumeratedMap {
return OneofDescriptor(proto: $1, index: $0, registry: registry)
}
self.extensions = proto.extension.enumeratedMap {
return FieldDescriptor(proto: $1, index: $0, registry: registry, isExtension: true)
}
// Done initializing, register ourselves.
registry.register(message: self)
}
fileprivate func bind(file: FileDescriptor, registry: Registry, containingType: Descriptor?) {
_file = file
self.containingType = containingType
enums.forEach { $0.bind(file: file, registry: registry, containingType: self) }
messages.forEach { $0.bind(file: file, registry: registry, containingType: self) }
fields.forEach { $0.bind(file: file, registry: registry, containingType: self) }
oneofs.forEach { $0.bind(registry: registry, containingType: self) }
extensions.forEach { $0.bind(file: file, registry: registry, containingType: self) }
// Synthetic oneofs come after normal oneofs. The C++ Descriptor enforces this, only
// here as a secondary validation because other code can rely on it.
var seenSynthetic = false
for o in oneofs {
if o.isSynthetic {
seenSynthetic = true
} else {
assert(!seenSynthetic)
}
}
}
}
/// Describes a type of protocol enum. `EnumDescriptor`s are not directly
/// created, instead they are constructed/fetched via the `DescriptorSet` or
/// they are directly accessed via a `EnumType` property on `FieldDescriptor`s,
/// etc.
public final class EnumDescriptor {
/// The name of this enum type in the containing scope.
public let name: String
/// The fully-qualified name of the enum type, scope delimited by periods.
public let fullName: String
/// Index of this enum within the file or containing message's enums.
public let index: Int
/// The .proto file in which this message type was defined.
public var file: FileDescriptor { return _file! }
/// If this Descriptor describes a nested type, this returns the type
/// in which it is nested.
public private(set) unowned var containingType: Descriptor?
/// The values defined for this enum. Guaranteed (by protoc) to be atleast
/// one item. These are returned in the order they were defined in the .proto
/// file.
public let values: [EnumValueDescriptor]
/// The `Google_Protobuf_MessageOptions` set on this enum.
public let options: Google_Protobuf_EnumOptions
/// The reserved value ranges for this enum. These are returned in the order
/// they are defined in the .proto file.
public let reservedRanges: [ClosedRange<Int32>]
/// The reserved value names for this enum. These are returned in the order
/// they are defined in the .proto file.
public let reservedNames: [String]
/// Returns true whether this is a "closed" enum, meaning that it:
/// - Has a fixed set of named values.
/// - Encountering values not in this set causes them to be treated as unknown
/// fields.
/// - The first value (i.e., the default) may be nonzero.
public var isClosed: Bool {
// Implementation comes from C++ EnumDescriptor::is_closed().
return file.syntax != .proto3
}
// Storage for `file`, will be set by bind()
private unowned var _file: FileDescriptor?
fileprivate init(proto: Google_Protobuf_EnumDescriptorProto,
index: Int,
registry: Registry,
scope: String) {
self.name = proto.name
self.fullName = scope.isEmpty ? proto.name : "\(scope).\(proto.name)"
self.index = index
self.options = proto.options
self.reservedRanges = proto.reservedRange.map { return $0.start ... $0.end }
self.reservedNames = proto.reservedName
self.values = proto.value.enumeratedMap {
return EnumValueDescriptor(proto: $1, index: $0, scope: scope)
}
// Done initializing, register ourselves.
registry.register(enum: self)
values.forEach { $0.bind(enumType: self) }
}
fileprivate func bind(file: FileDescriptor, registry: Registry, containingType: Descriptor?) {
_file = file
self.containingType = containingType
}
}
/// Describes an individual enum constant of a particular type. To get the
/// `EnumValueDescriptor` for a given enum value, first get the `EnumDescriptor`
/// for its type.
public final class EnumValueDescriptor {
/// Name of this enum constant.
public let name: String
/// The full_name of an enum value is a sibling symbol of the enum type.
/// e.g. the full name of FieldDescriptorProto::TYPE_INT32 is actually
/// "google.protobuf.FieldDescriptorProto.TYPE_INT32", NOT
/// "google.protobuf.FieldDescriptorProto.Type.TYPE_INT32". This is to conform
/// with C++ scoping rules for enums.
public let fullName: String
/// Index within the enums's `EnumDescriptor`.
public let index: Int
/// Numeric value of this enum constant.
public let number: Int32
/// The .proto file in which this message type was defined.
public var file: FileDescriptor { return enumType.file }
/// The type of this value.
public var enumType: EnumDescriptor { return _enumType! }
/// The `Google_Protobuf_EnumValueOptions` set on this value.
public let options: Google_Protobuf_EnumValueOptions
// Storage for `service`, will be set by bind()
private unowned var _enumType: EnumDescriptor?
fileprivate init(proto: Google_Protobuf_EnumValueDescriptorProto,
index: Int,
scope: String) {
self.name = proto.name
self.fullName = scope.isEmpty ? proto.name : "\(scope).\(proto.name)"
self.index = index
self.number = proto.number
self.options = proto.options
}
fileprivate func bind(enumType: EnumDescriptor) {
self._enumType = enumType
}
}
/// Describes a oneof defined in a message type.
public final class OneofDescriptor {
/// Name of this oneof.
public let name: String
/// Fully-qualified name of the oneof.
public var fullName: String { return "\(containingType.fullName).\(name)" }
/// Index of this oneof within the message's oneofs.
public let index: Int
/// Returns whether this oneof was inserted by the compiler to wrap a proto3
/// optional field. If this returns true, code generators should *not* emit it.
public var isSynthetic: Bool {
return fields.count == 1 && fields.first!.proto3Optional
}
/// The .proto file in which this oneof type was defined.
public var file: FileDescriptor { return containingType.file }
/// The Descriptor of the message that defines this oneof.
public var containingType: Descriptor { return _containingType! }
/// The `Google_Protobuf_OneofOptions` set on this oneof.
public let options: Google_Protobuf_OneofOptions
/// The members of this oneof, in the order in which they were declared in the
/// .proto file.
public private(set) lazy var fields: [FieldDescriptor] = {
let myIndex = Int32(self.index)
return containingType.fields.filter { $0.oneofIndex == myIndex }
}()
// Storage for `containingType`, will be set by bind()
private unowned var _containingType: Descriptor?
fileprivate init(proto: Google_Protobuf_OneofDescriptorProto,
index: Int,
registry: Registry) {
self.name = proto.name
self.index = index
self.options = proto.options
}
fileprivate func bind(registry: Registry, containingType: Descriptor) {
_containingType = containingType
}
}
/// Describes a single field of a message. To get the descriptor for a given
/// field, first get the `Descriptor` for the message in which it is defined,
/// then find the field. To get a `FieldDescriptor` for an extension, get the
/// `Descriptor` or `FileDescriptor` for its containing scope, find the
/// extension.
public final class FieldDescriptor {
/// Name of this field within the message.
public let name: String
/// Fully-qualified name of the field.
public var fullName: String {
// Since the fullName isn't needed on fields that often, compute it on demand.
guard isExtension else {
// Normal field on a message.
return "\(containingType.fullName).\(name)"
}
if let extensionScope = extensionScope {
return "\(extensionScope.fullName).\(name)"
}
let package = file.package
return package.isEmpty ? name : "\(package).\(name)"
}
/// JSON name of this field.
public let jsonName: String
/// File in which this field was defined.
public var file: FileDescriptor { return _file! }
/// If this is an extension field.
public let isExtension: Bool
/// The field number.
public let number: Int32
/// Valid field numbers are positive integers up to kMaxNumber.
static let kMaxNumber: Int = (1 << 29) - 1
/// First field number reserved for the protocol buffer library
/// implementation. Users may not declare fields that use reserved numbers.
static let kFirstReservedNumber: Int = 19000
/// Last field number reserved for the protocol buffer library implementation.
/// Users may not declare fields that use reserved numbers.
static let kLastReservedNumber: Int = 19999
/// Declared type of this field.
public let type: Google_Protobuf_FieldDescriptorProto.TypeEnum
/// optional/required/repeated
public let label: Google_Protobuf_FieldDescriptorProto.Label
/// Shorthand for `label` == `.required`.
///
/// NOTE: This could also be a map as the are also repeated fields.
public var isRequired: Bool { return label == .required }
/// Shorthand for `label` == `.optional`
public var isOptional: Bool { return label == .optional }
/// Shorthand for `label` == `.repeated`
public var isRepeated: Bool { return label == .repeated }
/// Is this field packable.
public var isPackable: Bool {
// This logic comes from the C++ FieldDescriptor::is_packable() impl.
return label == .repeated && FieldDescriptor.isPackable(type: type)
}
/// Should this field be packed format.
public var isPacked: Bool {
// This logic comes from the C++ FieldDescriptor::is_packed() impl.
// NOTE: It does not match what is in the C++ header for is_packed().
guard isPackable else { return false }
// The C++ imp also checks if the `options_` are null, but that is only for
// their placeholder descriptor support, as once the FieldDescriptor is
// fully wired it gets a default FileOptions instance, rendering nullptr
// meaningless.
if file.syntax == .proto2 {
return options.packed
} else {
return !options.hasPacked || options.packed
}
}
/// True if this field is a map.
public var isMap: Bool {
// This logic comes from the C++ FieldDescriptor::is_map() impl.
return type == .message && messageType!.options.mapEntry
}
/// Returns true if this field was syntactically written with "optional" in the
/// .proto file. Excludes singular proto3 fields that do not have a label.
public var hasOptionalKeyword: Bool {
// This logic comes from the C++ FieldDescriptor::has_optional_keyword()
// impl.
return proto3Optional ||
(file.syntax == .proto2 && label == .optional && oneofIndex == nil)
}
/// Returns true if this field tracks presence, ie. does the field
/// distinguish between "unset" and "present with default value."
/// This includes required, optional, and oneof fields. It excludes maps,
/// repeated fields, and singular proto3 fields without "optional".
public var hasPresence: Bool {
// This logic comes from the C++ FieldDescriptor::has_presence() impl.
guard label != .repeated else { return false }
switch type {
case .group, .message:
// Groups/messages always get field presence.
return true
default:
return file.syntax == .proto2 || oneofIndex != nil
}
}
/// Returns true if this is a string field and should do UTF-8 validation.
///
/// This api is for completeness, but it likely should never be used. The
/// concept comes from the C++ FieldDescriptory::requires_utf8_validation(),
/// but doesn't make a lot of sense for Swift Protobuf because `string` fields
/// are modeled as Swift `String` objects, and thus they always have to be
/// valid UTF-8. If something were to try putting something else in the field,
/// the library won't be able to parse it. While that sounds bad, other
/// languages have similar issues with their _string_ types and thus have the
/// same issues.
public var requiresUTF8Validation: Bool {
return type == .string && file.syntax == .proto3
}
/// Index of this field within the message's fields, or the file or
/// extension scope's extensions.
public let index: Int
/// The explicitly declared default value for this field.
///
/// This is the *raw* string value from the .proto file that was listed as
/// the default, it is up to the consumer to convert it correctly for the
/// type of this field. The C++ FieldDescriptor does offer some apis to
/// help with that, but at this time, that is not provided here.
public let defaultValue: String?
/// The `Descriptor` of the message which this is a field of. For extensions,
/// this is the extended type.
public var containingType: Descriptor { return _containingType! }
/// The oneof this field is a member of.
public var containingOneof: OneofDescriptor? {
guard let oneofIndex = oneofIndex else { return nil }
assert(!isExtension)
return containingType.oneofs[Int(oneofIndex)]
}
/// The non synthetic oneof this field is a member of.
public var realContainingOneof: OneofDescriptor? {
guard let oneof = containingOneof, !oneof.isSynthetic else { return nil }
return oneof
}
/// The index in a oneof this field is in.
public let oneofIndex: Int32?
/// Extensions can be declared within the scope of another message. If this
/// is an extension field, then this will be the scope it was declared in
/// nil if was declared at a global scope.
public private(set) unowned var extensionScope: Descriptor?
/// When this is a message/group field, that message's `Desciptor`.
public private(set) unowned var messageType: Descriptor?
/// When this is a enum field, that enum's `EnumDesciptor`.
public private(set) unowned var enumType: EnumDescriptor?
/// The FieldOptions for this field.
public var options: Google_Protobuf_FieldOptions
let proto3Optional: Bool
// These next two cache values until bind().
var extendee: String?
var typeName: String?
// Storage for `containingType`, will be set by bind()
private unowned var _containingType: Descriptor?
// Storage for `file`, will be set by bind()
private unowned var _file: FileDescriptor?
fileprivate init(proto: Google_Protobuf_FieldDescriptorProto,
index: Int,
registry: Registry,
isExtension: Bool = false) {
self.name = proto.name
self.index = index
self.defaultValue = proto.hasDefaultValue ? proto.defaultValue : nil
assert(proto.hasJsonName) // protoc should always set the name
self.jsonName = proto.jsonName
assert(isExtension == !proto.extendee.isEmpty)
self.isExtension = isExtension
self.number = proto.number
self.type = proto.type
self.label = proto.label
self.options = proto.options
if proto.hasOneofIndex {
assert(!isExtension)
oneofIndex = proto.oneofIndex
} else {
oneofIndex = nil
// FieldDescriptorProto is used for fields or extensions, generally
// .proto3Optional only makes sense on fields if it is in a oneof. But
// It is allowed on extensions. For information on that, see
// https://github.com/protocolbuffers/protobuf/issues/8234#issuecomment-774224376
// The C++ Descriptor code encorces the field/oneof part, but nothing
// is checked on the oneof side.
assert(!proto.proto3Optional || isExtension)
}
self.proto3Optional = proto.proto3Optional
self.extendee = isExtension ? proto.extendee : nil
switch type {
case .group, .message, .enum:
typeName = proto.typeName
default:
typeName = nil
}
}
fileprivate func bind(file: FileDescriptor, registry: Registry, containingType: Descriptor?) {
_file = file
if let extendee = extendee {
assert(isExtension)
extensionScope = containingType
_containingType = registry.descriptor(named: extendee)!
} else {
_containingType = containingType
}
extendee = nil
if let typeName = typeName {
if type == .enum {
enumType = registry.enumDescriptor(named: typeName)!
} else {
messageType = registry.descriptor(named: typeName)!
}
}
typeName = nil
}
}
/// Describes an RPC service.
///
/// SwiftProtobuf does *not* generate anything for these (or methods), but
/// they are here to support things that generate based off RPCs defined in
/// .proto file (gRPC, etc.).
public final class ServiceDescriptor {
/// The name of the service, not including its containing scope.
public let name: String
/// The fully-qualified name of the service, scope delimited by periods.
public let fullName: String
/// Index of this service within the file's services.
public let index: Int
/// The .proto file in which this service was defined
public var file: FileDescriptor { return _file! }
/// Get `Google_Protobuf_ServiceOptions` for this service.
public let options: Google_Protobuf_ServiceOptions
/// The methods defined on this service. These are returned in the order they
/// were defined in the .proto file.
public let methods: [MethodDescriptor]
// Storage for `file`, will be set by bind()
private unowned var _file: FileDescriptor?
fileprivate init(proto: Google_Protobuf_ServiceDescriptorProto,
index: Int,
registry: Registry,
scope: String) {
self.name = proto.name
self.fullName = scope.isEmpty ? proto.name : "\(scope).\(proto.name)"
self.index = index
self.options = proto.options
self.methods = proto.method.enumeratedMap {
return MethodDescriptor(proto: $1, index: $0, registry: registry)
}
// Done initializing, register ourselves.
registry.register(service: self)
}
fileprivate func bind(file: FileDescriptor, registry: Registry) {
_file = file
methods.forEach { $0.bind(service: self, registry: registry) }
}
}
/// Describes an individual service method.
///
/// SwiftProtobuf does *not* generate anything for these (or services), but
/// they are here to support things that generate based off RPCs defined in
/// .proto file (gRPC, etc.).
public final class MethodDescriptor {
/// The name of the method, not including its containing scope.
public let name: String
/// The fully-qualified name of the method, scope delimited by periods.
public var fullName: String { return "\(service.fullName).\(name)" }
/// Index of this service within the file's services.
public let index: Int
/// The .proto file in which this service was defined
public var file: FileDescriptor { return service.file }
/// The service tha defines this method.
public var service: ServiceDescriptor { return _service! }
/// The type of protocol message which this method accepts as input.
public private(set) var inputType: Descriptor
/// The type of protocol message which this message produces as output.
public private(set) var outputType: Descriptor
/// Whether the client streams multiple requests.
public let clientStreaming: Bool
// Whether the server streams multiple responses.
public let serverStreaming: Bool
/// The proto version of the descriptor that defines this method.
@available(*, deprecated,
message: "Use the properties directly or open a GitHub issue for something missing")
public var proto: Google_Protobuf_MethodDescriptorProto { return _proto }
private let _proto: Google_Protobuf_MethodDescriptorProto
// Storage for `service`, will be set by bind()
private unowned var _service: ServiceDescriptor?
fileprivate init(proto: Google_Protobuf_MethodDescriptorProto,
index: Int,
registry: Registry) {
self.name = proto.name
self.index = index
self.clientStreaming = proto.clientStreaming
self.serverStreaming = proto.serverStreaming
// Can look these up because all the Descriptors are already registered
self.inputType = registry.descriptor(named: proto.inputType)!
self.outputType = registry.descriptor(named: proto.outputType)!
self._proto = proto
}
fileprivate func bind(service: ServiceDescriptor, registry: Registry) {
self._service = service
}
}
/// Helper used under the hood to build the mapping tables and look things up.
///
/// All fullNames are like defined in descriptor.proto, they start with a
/// leading '.'. This simplifies the string ops when assembling the message
/// graph.
fileprivate final class Registry {
private var fileMap = [String:FileDescriptor]()
// These three are all keyed by the full_name prefixed with a '.'.
private var messageMap = [String:Descriptor]()
private var enumMap = [String:EnumDescriptor]()
private var serviceMap = [String:ServiceDescriptor]()
init() {}
func register(file: FileDescriptor) {
fileMap[file.name] = file
}
func register(message: Descriptor) {
messageMap[".\(message.fullName)"] = message
}
func register(enum e: EnumDescriptor) {
enumMap[".\(e.fullName)"] = e
}
func register(service: ServiceDescriptor) {
serviceMap[".\(service.fullName)"] = service
}
func fileDescriptor(named name: String) -> FileDescriptor? {
return fileMap[name]
}
func descriptor(named fullName: String) -> Descriptor? {
return messageMap[fullName]
}
func enumDescriptor(named fullName: String) -> EnumDescriptor? {
return enumMap[fullName]
}
func serviceDescriptor(named fullName: String) -> ServiceDescriptor? {
return serviceMap[fullName]
}
}
|
apache-2.0
|
acdc05e3b7d675a70f25397ccdf0de48
| 38.71875 | 99 | 0.698825 | 4.379114 | false | false | false | false |
AlexLombry/SwiftMastery-iOS10
|
PlayGround/Tuples.playground/Contents.swift
|
1
|
1465
|
//: Playground - noun: a place where people can play
import UIKit
var meeting = (meetingType: "Board Meeting", date: (NSDate()), presentation: true)
var currency = ("US Dollar", 350.00)
meeting.0
meeting.1
meeting.2
meeting.date
meeting.meetingType
meeting.2
let workItinerary = meeting.meetingType
let teamPresentation = meeting.presentation
let (currencyType, _) = currency
currencyType
let businessTrips = ["San Francisco" : 650.00, "Japan" : 1800.00, "London" : 1200.00, "Brazil" : 2200.00, "New York" : 450.00]
for (location, tripExpense) in businessTrips {
print("The business trip to \(location) has a budgeted expense of \(tripExpense)")
}
func smallesetAndLargest(arrayOfInts: [Int]) -> (small: Int, Large: Int)? {
if arrayOfInts.isEmpty { return nil }
var smallest = arrayOfInts[0]
var largest = arrayOfInts[0]
for value in arrayOfInts[1..<arrayOfInts.count] {
if value < smallest {
smallest = value
} else if value > largest {
largest = value
}
}
return (smallest, largest)
}
let results = smallesetAndLargest(arrayOfInts: [8, 45, 2, -7, 32, 71])
let emptyArray = [Int]()
//smallesetAndLargest(arrayOfInts: emptyArray)
if let optionalResults = smallesetAndLargest(arrayOfInts: emptyArray) {
print("The smallest number in the array is \(optionalResults.small) and the largest is \(optionalResults.Large)")
}
|
apache-2.0
|
0bb78c6e556f58760327177127236b48
| 22.253968 | 126 | 0.666894 | 3.766067 | false | false | false | false |
SwiftKit/Lipstick
|
Source/UIEdgeInsets+Init.swift
|
1
|
1361
|
//
// UIEdgeInsets+Init.swift
// Lipstick
//
// Created by Filip Dolnik on 16.10.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import UIKit
extension UIEdgeInsets {
public init(left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) {
self.init(top: 0, left: left, bottom: bottom, right: right)
}
public init(top: CGFloat, bottom: CGFloat = 0, right: CGFloat = 0) {
self.init(top: top, left: 0, bottom: bottom, right: right)
}
public init(top: CGFloat, left: CGFloat, right: CGFloat = 0) {
self.init(top: top, left: left, bottom: 0, right: right)
}
public init(top: CGFloat, left: CGFloat, bottom: CGFloat) {
self.init(top: top, left: left, bottom: bottom, right: 0)
}
public init(_ all: CGFloat) {
self.init(horizontal: all, vertical: all)
}
public init(horizontal: CGFloat, vertical: CGFloat) {
self.init(top: vertical, left: horizontal, bottom: vertical, right: horizontal)
}
public init(horizontal: CGFloat, top: CGFloat = 0, bottom: CGFloat = 0) {
self.init(top: top, left: horizontal, bottom: bottom, right: horizontal)
}
public init(vertical: CGFloat, left: CGFloat = 0, right: CGFloat = 0) {
self.init(top: vertical, left: left, bottom: vertical, right: right)
}
}
|
mit
|
ff744cbc2fa5a8f939def1b282d44ea6
| 29.909091 | 87 | 0.616176 | 3.617021 | false | false | false | false |
OscarSwanros/swift
|
tools/SwiftSyntax/Syntax.swift
|
3
|
7700
|
//===-------------------- Syntax.swift - Syntax Protocol ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
/// A Syntax node represents a tree of nodes with tokens at the leaves.
/// Each node has accessors for its known children, and allows efficient
/// iteration over the children through its `children` property.
public class Syntax: CustomStringConvertible {
/// The type of sequence containing the indices of present children.
internal typealias PresentChildIndicesSequence =
LazyFilterSequence<CountableRange<Int>>
/// The root of the tree this node is currently in.
internal let _root: SyntaxData
/// The data backing this node.
/// - note: This is unowned, because the reference to the root data keeps it
/// alive. This means there is an implicit relationship -- the data
/// property must be a descendent of the root. This relationship must
/// be preserved in all circumstances where Syntax nodes are created.
internal unowned var data: SyntaxData
#if DEBUG
func validate() {
// This is for subclasses to override to perform structural validation.
}
#endif
/// Creates a Syntax node from the provided root and data.
internal init(root: SyntaxData, data: SyntaxData) {
self._root = root
self.data = data
#if DEBUG
validate()
#endif
}
/// Access the raw syntax assuming the node is a Syntax.
var raw: RawSyntax {
return data.raw
}
/// An iterator over children of this node.
public var children: SyntaxChildren {
return SyntaxChildren(node: self)
}
/// Whether or not this node it marked as `present`.
public var isPresent: Bool {
return raw.presence == .present
}
/// Whether or not this node it marked as `missing`.
public var isMissing: Bool {
return raw.presence == .missing
}
/// Whether or not this node represents an Expression.
public var isExpr: Bool {
return raw.kind.isExpr
}
/// Whether or not this node represents a Declaration.
public var isDecl: Bool {
return raw.kind.isDecl
}
/// Whether or not this node represents a Statement.
public var isStmt: Bool {
return raw.kind.isStmt
}
/// Whether or not this node represents a Type.
public var isType: Bool {
return raw.kind.isType
}
/// Whether or not this node represents a Pattern.
public var isPattern: Bool {
return raw.kind.isPattern
}
/// The parent of this syntax node, or `nil` if this node is the root.
public var parent: Syntax? {
guard let parentData = data.parent else { return nil }
return Syntax.make(root: _root, data: parentData)
}
/// The index of this node in the parent's children.
public var indexInParent: Int {
return data.indexInParent
}
/// The root of the tree in which this node resides.
public var root: Syntax {
return Syntax.make(root: _root, data: _root)
}
/// The sequence of indices that correspond to child nodes that are not
/// missing.
///
/// This property is an implementation detail of `SyntaxChildren`.
internal var presentChildIndices: PresentChildIndicesSequence {
return raw.layout.indices.lazy.filter { self.raw.layout[$0].isPresent }
}
/// Gets the child at the provided index in this node's children.
/// - Parameter index: The index of the child node you're looking for.
/// - Returns: A Syntax node for the provided child, or `nil` if there
/// is not a child at that index in the node.
public func child(at index: Int) -> Syntax? {
guard raw.layout.indices.contains(index) else { return nil }
if raw.layout[index].isMissing { return nil }
return Syntax.make(root: _root, data: data.cachedChild(at: index))
}
/// A source-accurate description of this node.
public var description: String {
var s = ""
self.write(to: &s)
return s
}
}
extension Syntax: TextOutputStreamable {
/// Prints the raw value of this node to the provided stream.
/// - Parameter stream: The stream to which to print the raw tree.
public func write<Target>(to target: inout Target)
where Target: TextOutputStream {
data.raw.write(to: &target)
}
}
extension Syntax: Equatable {
/// Determines if two nodes are equal to each other.
public static func ==(lhs: Syntax, rhs: Syntax) -> Bool {
return lhs.data === rhs.data
}
}
/// MARK: - Nodes
/// A Syntax node representing a single token.
public class TokenSyntax: Syntax {
/// The text of the token as written in the source code.
public var text: String {
return tokenKind.text
}
public func withKind(_ tokenKind: TokenKind) -> TokenSyntax {
guard case let .token(_, leadingTrivia, trailingTrivia, presence) = raw else {
fatalError("TokenSyntax must have token as its raw")
}
let (root, newData) = data.replacingSelf(.token(tokenKind, leadingTrivia,
trailingTrivia, presence))
return TokenSyntax(root: root, data: newData)
}
/// Returns a new TokenSyntax with its leading trivia replaced
/// by the provided trivia.
public func withLeadingTrivia(_ leadingTrivia: Trivia) -> TokenSyntax {
guard case let .token(kind, _, trailingTrivia, presence) = raw else {
fatalError("TokenSyntax must have token as its raw")
}
let (root, newData) = data.replacingSelf(.token(kind, leadingTrivia,
trailingTrivia, presence))
return TokenSyntax(root: root, data: newData)
}
/// Returns a new TokenSyntax with its trailing trivia replaced
/// by the provided trivia.
public func withTrailingTrivia(_ trailingTrivia: Trivia) -> TokenSyntax {
guard case let .token(kind, leadingTrivia, _, presence) = raw else {
fatalError("TokenSyntax must have token as its raw")
}
let (root, newData) = data.replacingSelf(.token(kind, leadingTrivia,
trailingTrivia, presence))
return TokenSyntax(root: root, data: newData)
}
/// Returns a new TokenSyntax with its leading trivia removed.
public func withoutLeadingTrivia() -> TokenSyntax {
return withLeadingTrivia([])
}
/// Returns a new TokenSyntax with its trailing trivia removed.
public func withoutTrailingTrivia() -> TokenSyntax {
return withTrailingTrivia([])
}
/// Returns a new TokenSyntax with all trivia removed.
public func withoutTrivia() -> TokenSyntax {
return withoutLeadingTrivia().withoutTrailingTrivia()
}
/// The leading trivia (spaces, newlines, etc.) associated with this token.
public var leadingTrivia: Trivia {
guard case .token(_, let leadingTrivia, _, _) = raw else {
fatalError("TokenSyntax must have token as its raw")
}
return leadingTrivia
}
/// The trailing trivia (spaces, newlines, etc.) associated with this token.
public var trailingTrivia: Trivia {
guard case .token(_, _, let trailingTrivia, _) = raw else {
fatalError("TokenSyntax must have token as its raw")
}
return trailingTrivia
}
/// The kind of token this node represents.
public var tokenKind: TokenKind {
guard case .token(let kind, _, _, _) = raw else {
fatalError("TokenSyntax must have token as its raw")
}
return kind
}
}
|
apache-2.0
|
8be130d0c94679c6e9fb577827def5ff
| 32.624454 | 82 | 0.668961 | 4.513482 | false | false | false | false |
gkaimakas/SwiftValidatorsReactiveExtensions
|
Example/SwiftValidatorsReactiveExtensions/Extensions/UIImageView.swift
|
1
|
552
|
//
// UIImageView.swift
// SwiftValidatorsReactiveExtensions
//
// Created by George Kaimakas on 05/04/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
func bordered(width: CGFloat, color: UIColor = UIColor.clear) {
self.layoutIfNeeded()
self.layer.cornerRadius = min(self.bounds.height, bounds.width)/2
self.layer.borderWidth = width
self.layer.borderColor = color.cgColor
self.clipsToBounds = true
self.layoutIfNeeded()
}
}
|
mit
|
4ad8bdaac43430d6ab39874948e30027
| 24.045455 | 73 | 0.684211 | 4.11194 | false | false | false | false |
Fenrikur/ef-app_ios
|
Eurofurence/Modules/Knowledge Groups/View/UIKit/KnowledgeListViewController.swift
|
1
|
3113
|
import UIKit
class KnowledgeListViewController: UIViewController, KnowledgeListScene {
// MARK: IBOutlets
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var activityIndicator: UIActivityIndicatorView!
// MARK: KnowledgeListScene
private var delegate: KnowledgeListSceneDelegate?
func setDelegate(_ delegate: KnowledgeListSceneDelegate) {
self.delegate = delegate
}
func setKnowledgeListTitle(_ title: String) {
navigationItem.title = title
}
func setKnowledgeListShortTitle(_ shortTitle: String) {
tabBarItem.title = shortTitle
}
func showLoadingIndicator() {
activityIndicator.startAnimating()
}
func hideLoadingIndicator() {
activityIndicator.stopAnimating()
}
private lazy var tableViewRenderer = TableViewDataSource()
func prepareToDisplayKnowledgeGroups(numberOfGroups: Int, binder: KnowledgeListBinder) {
tableViewRenderer.entryCounts = numberOfGroups
tableViewRenderer.binder = binder
tableView.reloadData()
}
func deselectKnowledgeEntry(at indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: Overrides
override func viewDidLoad() {
super.viewDidLoad()
tableViewRenderer.onDidSelectRowAtIndexPath = didSelectRow
tableView.dataSource = tableViewRenderer
tableView.delegate = tableViewRenderer
tableView.estimatedSectionHeaderHeight = 64
tableView.rowHeight = UITableView.automaticDimension
tableView.sectionHeaderHeight = UITableView.automaticDimension
delegate?.knowledgeListSceneDidLoad()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView?.adjustScrollIndicatorInsetsForSafeAreaCompensation()
}
// MARK: Private
private func didSelectRow(at indexPath: IndexPath) {
delegate?.knowledgeListSceneDidSelectKnowledgeGroup(at: indexPath.row)
}
private class TableViewDataSource: NSObject, UITableViewDataSource, UITableViewDelegate {
var entryCounts = 0
var binder: KnowledgeListBinder?
var onDidSelectRowAtIndexPath: ((IndexPath) -> Void)?
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return entryCounts
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue(KnowledgeListSectionHeaderTableViewCell.self)
binder?.bind(cell, toGroupAt: indexPath.row)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
onDidSelectRowAtIndexPath?(indexPath)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView()
}
}
}
|
mit
|
548475528cc432623de9e8a93d579fa7
| 29.821782 | 104 | 0.694186 | 5.952199 | false | false | false | false |
ubclaunchpad/RocketCast
|
RocketCast/PlayerView.swift
|
1
|
4707
|
//
// PlayerView.swift
// RocketCast
//
// Created by Odin and QuantumSpark on 2016-08-31.
// Copyright © 2016 UBCLaunchPad. All rights reserved.
//
import UIKit
class PlayerView: UIView {
var viewDelegate: PlayerViewDelegate?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var podcastTitleLabel: UILabel!
@IBOutlet weak var descriptionView: UITextView!
@IBOutlet weak var coverPhotoView: UIView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var speedButton: UIButton!
@IBOutlet weak var playButton: UIButton!
@IBAction func playButton(_ sender: AnyObject) {
isPlaying = !isPlaying
}
@IBOutlet weak var slider: UISlider!
var sliderIsMoving = false
var isPlaying = true {
didSet {
if isPlaying {
playButton.setImage(#imageLiteral(resourceName: "Pause"), for: .normal)
viewDelegate?.playPodcast()
statusLabel.text = "Playing at \(Int(AudioEpisodeTracker.currentRate))x"
} else {
playButton.setImage(#imageLiteral(resourceName: "Play"), for: .normal)
viewDelegate?.pausePodcast()
statusLabel.text = "Pause"
}
}
}
@IBAction func backButton(_ sender: AnyObject) {
viewDelegate?.goBack()
}
@IBAction func skipButton(_ sender: AnyObject) {
viewDelegate?.goForward()
}
@IBAction func changeAudio(_ sender: AnyObject) {
// Smooths slider by reducing logic performed during each continuous slide
if sliderIsMoving {
// Once slider is let go
sliderIsMoving = false
slider.isContinuous = true
guard slider.value != slider.maximumValue else {
viewDelegate?.playNextEpisode()
return
}
AudioEpisodeTracker.audioPlayer.stop()
AudioEpisodeTracker.audioPlayer.currentTime = TimeInterval(slider.value)
AudioEpisodeTracker.audioPlayer.prepareToPlay()
AudioEpisodeTracker.audioPlayer.play()
} else {
// Initial slide value
sliderIsMoving = true
slider.isContinuous = false
}
}
@IBAction func changeSpeed(_ sender: UIButton) {
let speed = viewDelegate?.changeSpeed()
speedButton.setTitle("\(speed!)x", for: .normal)
statusLabel.text = "Playing at \(speed!)x"
}
class func instancefromNib(_ frame: CGRect) -> PlayerView {
let view = UINib(nibName: "PlayerView", bundle: nil).instantiate(withOwner: nil, options: nil)[0]
as! PlayerView
view.frame = frame
return view
}
func setStyling() {
let effectsLayer = coverPhotoView.layer
effectsLayer.cornerRadius = 14
effectsLayer.shadowColor = UIColor.black.cgColor
effectsLayer.shadowOffset = CGSize(width: 0, height: 0)
effectsLayer.shadowRadius = 4
effectsLayer.shadowOpacity = 0.4
effectsLayer.shadowPath = UIBezierPath(roundedRect: coverPhotoView.bounds, cornerRadius: coverPhotoView.layer.cornerRadius).cgPath
}
func setTitles (title: String) {
titleLabel.text = title
descriptionView.text = "Test Description"
}
func updateUI (episode: Episode) {
speedButton.setTitle("\(Int(AudioEpisodeTracker.currentRate))x", for: .normal)
isPlaying = AudioEpisodeTracker.isPlaying
self.titleLabel.text = episode.title!
self.podcastTitleLabel.text = episode.podcastTitle
self.descriptionView.text = "Simple description of Podcast"
let url = URL(string: episode.imageURL!)
DispatchQueue.global().async {
do {
let data = try Data(contentsOf: url!)
let coverPhoto = UIImageView()
coverPhoto.frame = self.coverPhotoView.bounds
coverPhoto.layer.cornerRadius = 14
coverPhoto.layer.masksToBounds = true
DispatchQueue.main.async {
coverPhoto.image = UIImage(data: data)
self.coverPhotoView.addSubview(coverPhoto)
}
} catch let error as NSError{
Log.error("Error: " + error.debugDescription)
}
}
}
}
class MediaSlider: UISlider {
override func trackRect(forBounds bounds: CGRect) -> CGRect {
let customBounds = CGRect(origin: bounds.origin, size: CGSize(width: bounds.size.width, height: 5.0))
super.trackRect(forBounds: customBounds)
return customBounds
}
}
|
mit
|
9d26298b0b65a99ef9d55a02dd95a907
| 34.383459 | 138 | 0.611985 | 5.05478 | false | false | false | false |
vgorloff/AUHost
|
Vendor/mc/mcxAppKitMedia/Sources/MediaObjectPasteboardUtility.swift
|
1
|
2150
|
//
// MediaObjectPasteboardUtility.swift
// MCA-OSS-AUH
//
// Created by Vlad Gorlov on 26.01.16.
// Copyright © 2016 Vlad Gorlov. All rights reserved.
//
import AppKit
public struct MediaObjectPasteboardUtility {
public enum PasteboardObjects {
case mediaObjects(NSDictionary)
case filePaths([String])
case none
}
private let mediaLibraryPasteboardType
= NSPasteboard.PasteboardType("com.apple.MediaLibrary.PBoardType.MediaObjectIdentifiersPlist")
// FIXME: Workaround. Replace after getting answer on SO question:
// https://stackoverflow.com/questions/44537356/swift-4-nsfilenamespboardtype-not-available-what-to-use-instead-for-registerfo
private let fileNamesPasteboardType = NSPasteboard.PasteboardType("NSFilenamesPboardType")
public let draggedTypes: [NSPasteboard.PasteboardType]
public init() {
draggedTypes = [mediaLibraryPasteboardType, fileNamesPasteboardType]
}
public func objectsFromPasteboard(pasteboard: NSPasteboard) -> PasteboardObjects {
guard let pasteboardTypes = pasteboard.types else {
return .none
}
if pasteboardTypes.contains(mediaLibraryPasteboardType),
let dict = pasteboard.propertyList(forType: mediaLibraryPasteboardType) as? NSDictionary
{
return .mediaObjects(dict)
} else if pasteboardTypes.contains(fileNamesPasteboardType),
let filePaths = pasteboard.propertyList(forType: fileNamesPasteboardType) as? [String]
{
let acceptedFilePaths = filteredFilePaths(pasteboardFilePaths: filePaths)
return acceptedFilePaths.count > 0 ? .filePaths(acceptedFilePaths) : .none
} else {
return .none
}
}
private func filteredFilePaths(pasteboardFilePaths: [String]) -> [String] {
let ws = NSWorkspace.shared
let result = pasteboardFilePaths.filter { element in
do {
let fileType = try ws.type(ofFile: element)
return UTTypeConformsTo(fileType as CFString, kUTTypeAudio)
} catch {
print("\(error)")
}
return false
}
return result
}
}
|
mit
|
8aca8251acaed337533c0f5b38bd9d4e
| 34.229508 | 129 | 0.697999 | 4.906393 | false | false | false | false |
vincent-cheny/DailyRecord
|
DailyRecord/Utils.swift
|
1
|
13914
|
//
// Utils.swift
// DailyRecord
//
// Created by ChenYong on 16/4/4.
// Copyright © 2016年 LazyPanda. All rights reserved.
//
class Utils {
static let isInitialized: String = "isInitialized"
static let needBlackCheck: String = "needBlackCheck"
static let needWhiteCheck: String = "needWhiteCheck"
static let needDailySummary: String = "needDailySummary"
static let summaryTime: String = "summaryTime"
static let remindCategory: String = "remindCategory"
static let dailySummaryCategory: String = "dailySummaryCategory"
static let timeSetting1: String = "timeSetting1"
static let timeSetting2: String = "timeSetting2"
static let timeSetting3: String = "timeSetting3"
static let timeSetting4: String = "timeSetting4"
static let timeSetting5: String = "timeSetting5"
static let timeSetting6: String = "timeSetting6"
static func descriptionFromTime(date: NSDate) -> String {
let defaults = NSUserDefaults.standardUserDefaults()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.Hour, fromDate: date)
let hour = components.hour
switch hour {
case defaults.integerForKey(timeSetting1)...defaults.integerForKey(timeSetting2) - 1:
return "晨起"
case defaults.integerForKey(timeSetting2)...defaults.integerForKey(timeSetting3) - 1:
return "早饭后"
case defaults.integerForKey(timeSetting3)...defaults.integerForKey(timeSetting4) - 1:
return "午饭前"
case defaults.integerForKey(timeSetting4)...defaults.integerForKey(timeSetting5) - 1:
return "下午"
case defaults.integerForKey(timeSetting5)...defaults.integerForKey(timeSetting6) - 1:
return "晚殿"
default:
return "睡前"
}
}
static func allInfoFromTime(date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy.M.d HH:mm"
let todayDate = dateFormatter.stringFromDate(date)
let todayDescription = descriptionFromTime(date);
return todayDate + " " + todayDescription;
}
static func getYear(date: NSDate) -> String {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.Year, fromDate: date)
return String(components.year) + "年"
}
static func getYearMonth(date: NSDate) -> String {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month], fromDate: date)
return String(components.year) + "年" + String(components.month) + "月"
}
static func getDay(date: NSDate) -> String {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day], fromDate: date)
return String(components.year) + "年" + String(components.month) + "月" + String(components.day) + "日"
}
static func getShortDay(date: NSDate) -> String {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day], fromDate: date)
return String(components.year) + "." + String(components.month) + "." + String(components.day)
}
static func getWeek(dateFormatter: NSDateFormatter, date: NSDate) -> String {
let calendar = NSCalendar.currentCalendar()
calendar.firstWeekday = 2
var startOfWeek : NSDate?;
calendar.rangeOfUnit(.WeekOfYear, startDate: &startOfWeek, interval: nil, forDate: date)
let weekComponet = NSDateComponents()
weekComponet.day = 7
let endOfWeek = calendar.dateByAddingComponents(weekComponet, toDate: startOfWeek!, options: NSCalendarOptions())?.dateByAddingTimeInterval(-1)
return dateFormatter.stringFromDate(startOfWeek!) + "-" + dateFormatter.stringFromDate(endOfWeek!)
}
static func getMonth(dateFormatter: NSDateFormatter, date: NSDate) -> String {
let calendar = NSCalendar.currentCalendar()
var startOfMonth : NSDate?
calendar.rangeOfUnit(.Month, startDate: &startOfMonth, interval: nil, forDate: date)
let monthComponent = NSDateComponents()
monthComponent.month = 1;
let endOfMonth = calendar.dateByAddingComponents(monthComponent, toDate: startOfMonth!, options: NSCalendarOptions())?.dateByAddingTimeInterval(-1)
return dateFormatter.stringFromDate(startOfMonth!) + "-" + dateFormatter.stringFromDate(endOfMonth!)
}
static func getDayRange(date: NSDate) -> [NSTimeInterval] {
let calendar = NSCalendar.currentCalendar()
var startOfDay : NSDate?
calendar.rangeOfUnit(.Day, startDate: &startOfDay, interval: nil, forDate: date)
let dayComponet = NSDateComponents()
dayComponet.day = 1
let endOfDay = calendar.dateByAddingComponents(dayComponet, toDate: startOfDay!, options: NSCalendarOptions())?.dateByAddingTimeInterval(-1)
return [startOfDay!.timeIntervalSince1970, endOfDay!.timeIntervalSince1970]
}
static func getWeekRange(date: NSDate) -> [NSTimeInterval] {
let calendar = NSCalendar.currentCalendar()
calendar.firstWeekday = 2
var startOfWeek : NSDate?;
calendar.rangeOfUnit(.WeekOfYear, startDate: &startOfWeek, interval: nil, forDate: date)
let weekComponet = NSDateComponents()
weekComponet.day = 7
let endOfWeek = calendar.dateByAddingComponents(weekComponet, toDate: startOfWeek!, options: NSCalendarOptions())?.dateByAddingTimeInterval(-1)
return [startOfWeek!.timeIntervalSince1970, endOfWeek!.timeIntervalSince1970]
}
static func getMonthRange(date: NSDate) -> [NSTimeInterval] {
let calendar = NSCalendar.currentCalendar()
var startOfMonth : NSDate?
calendar.rangeOfUnit(.Month, startDate: &startOfMonth, interval: nil, forDate: date)
let monthComponent = NSDateComponents()
monthComponent.month = 1;
let endOfMonth = calendar.dateByAddingComponents(monthComponent, toDate: startOfMonth!, options: NSCalendarOptions())?.dateByAddingTimeInterval(-1)
return [startOfMonth!.timeIntervalSince1970, endOfMonth!.timeIntervalSince1970]
}
static func getYearRange(date: NSDate) -> [NSTimeInterval] {
let calendar = NSCalendar.currentCalendar()
var startOfYear : NSDate?
calendar.rangeOfUnit(.Year, startDate: &startOfYear, interval: nil, forDate: date)
let yearComponent = NSDateComponents()
yearComponent.year = 1;
let endOfYear = calendar.dateByAddingComponents(yearComponent, toDate: startOfYear!, options: NSCalendarOptions())?.dateByAddingTimeInterval(-1)
return [startOfYear!.timeIntervalSince1970, endOfYear!.timeIntervalSince1970]
}
static func firstWeekdayInMonth(date: NSDate) -> Int {
let calendar = NSCalendar.currentCalendar()
calendar.firstWeekday = 2
var startOfMonth : NSDate?
calendar.rangeOfUnit(.Month, startDate: &startOfMonth, interval: nil, forDate: date)
return calendar.ordinalityOfUnit(.Weekday, inUnit: .WeekOfMonth, forDate: startOfMonth!)
}
static func totalDaysInMonth(date: NSDate) -> Int {
return NSCalendar.currentCalendar().rangeOfUnit(.Day, inUnit: .Month, forDate: date).length
}
static func lastMonth(date: NSDate) -> NSDate {
let monthComponent = NSDateComponents()
monthComponent.month = -1;
return NSCalendar.currentCalendar().dateByAddingComponents(monthComponent, toDate: date, options: NSCalendarOptions())!
}
static func nextMonth(date: NSDate) -> NSDate {
let monthComponent = NSDateComponents()
monthComponent.month = 1;
return NSCalendar.currentCalendar().dateByAddingComponents(monthComponent, toDate: date, options: NSCalendarOptions())!
}
static func lastDay(date: NSDate) -> NSDate {
let dayComponent = NSDateComponents()
dayComponent.day = -1;
return NSCalendar.currentCalendar().dateByAddingComponents(dayComponent, toDate: date, options: NSCalendarOptions())!
}
static func nextDay(date: NSDate) -> NSDate {
let dayComponent = NSDateComponents()
dayComponent.day = 1;
return NSCalendar.currentCalendar().dateByAddingComponents(dayComponent, toDate: date, options: NSCalendarOptions())!
}
static func getHourAndMinute(components: NSDateComponents) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
return dateFormatter.stringFromDate(NSCalendar.currentCalendar().dateFromComponents(components)!)
}
static func getWeekday(date: NSDate) -> Int {
let calendar = NSCalendar.currentCalendar()
calendar.firstWeekday = 2
return calendar.ordinalityOfUnit(.Weekday, inUnit: .WeekOfMonth, forDate: date)
}
static func getFireDate(components: NSDateComponents) -> NSDate {
let today = NSDate()
let fireDateMinutes = components.hour * 60 + components.minute
let calendar = NSCalendar.currentCalendar()
let todayComponents = calendar.components([.Hour, .Minute], fromDate: today)
let todayMinutes = todayComponents.hour * 60 + todayComponents.minute
if fireDateMinutes > todayMinutes {
return calendar.dateBySettingHour(components.hour, minute: components.minute, second: 0, ofDate: today, options: NSCalendarOptions())!
} else {
return calendar.dateBySettingHour(components.hour, minute: components.minute, second: 0, ofDate: nextDay(today), options: NSCalendarOptions())!
}
}
static func getRepeatsDescription(repeats: [Bool]) -> String {
var description = ""
if repeats[0] {
description += "周一 "
}
if repeats[1] {
description += "周二 "
}
if repeats[2] {
description += "周三 "
}
if repeats[3] {
description += "周四 "
}
if repeats[4] {
description += "周五 "
}
if repeats[5] {
description += "周六 "
}
if repeats[6] {
description += "周日 "
}
if description == "" {
return "不重复"
} else {
return description
}
}
static func openRemindNotification(remind: Remind) {
if remind.monday || remind.tuesday || remind.wednesday || remind.thursday || remind.friday || remind.saturday || remind.sunday {
if remind.monday {
openRemindNotification(remind, weekday: 1)
}
if remind.tuesday {
openRemindNotification(remind, weekday: 2)
}
if remind.wednesday {
openRemindNotification(remind, weekday: 3)
}
if remind.thursday {
openRemindNotification(remind, weekday: 4)
}
if remind.friday {
openRemindNotification(remind, weekday: 5)
}
if remind.saturday {
openRemindNotification(remind, weekday: 6)
}
if remind.sunday {
openRemindNotification(remind, weekday: 7)
}
}
}
static func openRemindNotification(remind: Remind, weekday: Int) {
let calendar = NSCalendar.currentCalendar()
let notification = UILocalNotification()
notification.alertBody = remind.content
notification.soundName = UILocalNotificationDefaultSoundName
notification.category = remindCategory
notification.repeatInterval = .Weekday
notification.userInfo = ["id": remind.id]
let remindComponents = NSDateComponents()
remindComponents.hour = remind.hour
remindComponents.minute = remind.minute
let today = NSDate()
let todayWeekday = getWeekday(today)
if todayWeekday == weekday {
notification.fireDate = getFireDate(remindComponents)
} else if todayWeekday < weekday {
let diffComponets = NSDateComponents()
diffComponets.day = weekday - todayWeekday
notification.fireDate = calendar.dateBySettingHour(remindComponents.hour, minute: remindComponents.minute, second: 0, ofDate: calendar.dateByAddingComponents(diffComponets, toDate: today, options: NSCalendarOptions())!, options: NSCalendarOptions())!
} else {
let diffComponets = NSDateComponents()
diffComponets.day = weekday - todayWeekday + 7
notification.fireDate = calendar.dateBySettingHour(remindComponents.hour, minute: remindComponents.minute, second: 0, ofDate: calendar.dateByAddingComponents(diffComponets, toDate: today, options: NSCalendarOptions())!, options: NSCalendarOptions())!
}
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
static func cancelRemindNotification(remind: Remind) {
if remind.monday || remind.tuesday || remind.wednesday || remind.thursday || remind.friday || remind.saturday || remind.sunday {
let application = UIApplication.sharedApplication()
let notifications = application.scheduledLocalNotifications!
for notification in notifications {
var userInfo = notification.userInfo
if userInfo != nil {
let id = userInfo!["id"] as! Int
if remind.id == id {
//Cancelling local notification
application.cancelLocalNotification(notification)
}
}
}
}
}
}
|
gpl-2.0
|
cea3dd04347da3b36b26be7257deb871
| 44.973422 | 262 | 0.654983 | 5.059232 | false | false | false | false |
huangboju/AsyncDisplay_Study
|
AsyncDisplay/Nodes/SupplementaryNode.swift
|
1
|
1089
|
//
// SupplementaryNode.swift
// AsyncDisplay
//
// Created by 伯驹 黄 on 2017/4/19.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
let kInsets: CGFloat = 15.0
import AsyncDisplayKit
class SupplementaryNode: ASCellNode {
var textNode: ASTextNode!
init(text: String) {
super.init()
textNode = ASTextNode()
textNode.attributedText = NSAttributedString(string: text, attributes: textAttributes)
addSubnode(textNode)
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let center = ASCenterLayoutSpec()
center.centeringOptions = ASCenterLayoutSpecCenteringOptions.XY
center.child = textNode
let insets = UIEdgeInsets(top: kInsets, left: kInsets, bottom: kInsets, right: kInsets);
return ASInsetLayoutSpec(insets: insets, child: center)
}
var textAttributes: [NSAttributedString.Key: Any] {
return [
.font: UIFont.systemFont(ofSize:18.0),
.foregroundColor: UIColor.white,
]
}
}
|
mit
|
2904fcf03b7a5e4a825c40d392aed52f
| 27.263158 | 96 | 0.655493 | 4.493724 | false | false | false | false |
iOkay/MiaoWuWu
|
Pods/RAMAnimatedTabBarController/RAMAnimatedTabBarController/RAMAnimatedTabBarController.swift
|
2
|
16296
|
// AnimationTabBarController.swift
//
// Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
// MARK: Custom Badge
extension RAMAnimatedTabBarItem {
/// The current badge value
override open var badgeValue: String? {
get {
return badge?.text
}
set(newValue) {
if newValue == nil {
badge?.removeFromSuperview()
badge = nil;
return
}
if let iconView = iconView, let contanerView = iconView.icon.superview , badge == nil {
badge = RAMBadge.badge()
badge!.addBadgeOnView(contanerView)
}
badge?.text = newValue
}
}
}
/// UITabBarItem with animation
open class RAMAnimatedTabBarItem: UITabBarItem {
@IBInspectable open var yOffSet: CGFloat = 0
open override var isEnabled: Bool {
didSet {
iconView?.icon.alpha = isEnabled == true ? 1 : 0.5
iconView?.textLabel.alpha = isEnabled == true ? 1 : 0.5
}
}
/// animation for UITabBarItem. use RAMFumeAnimation, RAMBounceAnimation, RAMRotationAnimation, RAMFrameItemAnimation, RAMTransitionAnimation
/// or create custom anmation inherit RAMItemAnimation
@IBOutlet open var animation: RAMItemAnimation!
/// The font used to render the UITabBarItem text.
open var textFont: UIFont = UIFont.systemFont(ofSize: 10)
/// The color of the UITabBarItem text.
@IBInspectable open var textColor: UIColor = UIColor.black
/// The tint color of the UITabBarItem icon.
@IBInspectable open var iconColor: UIColor = UIColor.clear // if alpha color is 0 color ignoring
var bgDefaultColor: UIColor = UIColor.clear // background color
var bgSelectedColor: UIColor = UIColor.clear
// The current badge value
open var badge: RAMBadge? // use badgeValue to show badge
// Container for icon and text in UITableItem.
open var iconView: (icon: UIImageView, textLabel: UILabel)?
/**
Start selected animation
*/
open func playAnimation() {
assert(animation != nil, "add animation in UITabBarItem")
guard animation != nil && iconView != nil else {
return
}
animation.playAnimation(iconView!.icon, textLabel: iconView!.textLabel)
}
/**
Start unselected animation
*/
open func deselectAnimation() {
guard animation != nil && iconView != nil else {
return
}
animation.deselectAnimation(
iconView!.icon,
textLabel: iconView!.textLabel,
defaultTextColor: textColor,
defaultIconColor: iconColor)
}
/**
Set selected state without animation
*/
open func selectedState() {
guard animation != nil && iconView != nil else {
return
}
animation.selectedState(iconView!.icon, textLabel: iconView!.textLabel)
}
}
extension RAMAnimatedTabBarController {
/**
Change selected color for each UITabBarItem
- parameter textSelectedColor: set new color for text
- parameter iconSelectedColor: set new color for icon
*/
public func changeSelectedColor(_ textSelectedColor:UIColor, iconSelectedColor:UIColor) {
let items = tabBar.items as! [RAMAnimatedTabBarItem]
for index in 0..<items.count {
let item = items[index]
item.animation.textSelectedColor = textSelectedColor
item.animation.iconSelectedColor = iconSelectedColor
if item == self.tabBar.selectedItem {
item.selectedState()
}
}
}
/**
Hide UITabBarController
- parameter isHidden: A Boolean indicating whether the UITabBarController is displayed
*/
public func animationTabBarHidden(_ isHidden:Bool) {
guard let items = tabBar.items as? [RAMAnimatedTabBarItem] else {
fatalError("items must inherit RAMAnimatedTabBarItem")
}
for item in items {
if let iconView = item.iconView {
iconView.icon.superview?.isHidden = isHidden
}
}
self.tabBar.isHidden = isHidden;
}
/**
Selected UITabBarItem with animaton
- parameter from: Index for unselected animation
- parameter to: Index for selected animation
*/
public func setSelectIndex(from: Int, to: Int) {
selectedIndex = to
guard let items = tabBar.items as? [RAMAnimatedTabBarItem] else {
fatalError("items must inherit RAMAnimatedTabBarItem")
}
let containerFrom = items[from].iconView?.icon.superview
containerFrom?.backgroundColor = items[from].bgDefaultColor
items[from].deselectAnimation()
let containerTo = items[to].iconView?.icon.superview
containerTo?.backgroundColor = items[to].bgSelectedColor
items[to].playAnimation()
}
}
/// UITabBarController with item animations
open class RAMAnimatedTabBarController: UITabBarController {
fileprivate var didInit: Bool = false
fileprivate var didLoadView: Bool = false
// MARK: life circle
/**
Returns a newly initialized view controller with the nib file in the specified bundle.
- parameter nibNameOrNil: The name of the nib file to associate with the view controller. The nib file name should
not contain any leading path information. If you specify nil, the nibName property is set to nil.
- parameter nibBundleOrNil: The bundle in which to search for the nib file. This method looks for the nib file in the
bundle's language-specific project directories first, followed by the Resources directory. If this parameter is nil,
the method uses the heuristics described below to locate the nib file.
- returns: A newly initialized RAMAnimatedTabBarController object.
*/
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.didInit = true
self.initializeContainers()
}
/**
Returns a newly initialized view controller with the nib file in the specified bundle.
- parameter viewControllers: Sets the root view controllers of the tab bar controller.
- returns: A newly initialized RAMAnimatedTabBarController object.
*/
public init(viewControllers: [UIViewController]) {
super.init(nibName: nil, bundle: nil)
self.didInit = true
// Set initial items
self.setViewControllers(viewControllers, animated: false)
self.initializeContainers()
}
/**
Returns a newly initialized view controller with the nib file in the specified bundle.
- parameter coder: An unarchiver object.
- returns: A newly initialized RAMAnimatedTabBarController object.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.didInit = true
self.initializeContainers()
}
override open func viewDidLoad() {
super.viewDidLoad()
self.didLoadView = true
self.initializeContainers()
}
fileprivate func initializeContainers() {
if !self.didInit || !self.didLoadView {
return
}
let containers = self.createViewContainers()
self.createCustomIcons(containers)
}
// MARK: create methods
fileprivate func createCustomIcons(_ containers : NSDictionary) {
guard let items = tabBar.items as? [RAMAnimatedTabBarItem] else {
fatalError("items must inherit RAMAnimatedTabBarItem")
}
var index = 0
for item in items {
guard let itemImage = item.image else {
fatalError("add image icon in UITabBarItem")
}
guard let container = containers["container\(items.count - 1 - index)"] as? UIView else {
fatalError()
}
container.tag = index
let renderMode = item.iconColor.cgColor.alpha == 0 ? UIImageRenderingMode.alwaysOriginal :
UIImageRenderingMode.alwaysTemplate
let icon = UIImageView(image: item.image?.withRenderingMode(renderMode))
icon.translatesAutoresizingMaskIntoConstraints = false
icon.tintColor = item.iconColor
// text
let textLabel = UILabel()
textLabel.text = item.title
textLabel.backgroundColor = UIColor.clear
textLabel.textColor = item.textColor
textLabel.font = item.textFont
textLabel.textAlignment = NSTextAlignment.center
textLabel.translatesAutoresizingMaskIntoConstraints = false
container.backgroundColor = (items as [RAMAnimatedTabBarItem])[index].bgDefaultColor
container.addSubview(icon)
createConstraints(icon, container: container, size: itemImage.size, yOffset: -5 - item.yOffSet)
container.addSubview(textLabel)
let textLabelWidth = tabBar.frame.size.width / CGFloat(items.count) - 5.0
createConstraints(textLabel, container: container, size: CGSize(width: textLabelWidth , height: 10), yOffset: 16 - item.yOffSet)
if item.isEnabled == false {
icon.alpha = 0.5
textLabel.alpha = 0.5
}
item.iconView = (icon:icon, textLabel:textLabel)
if 0 == index { // selected first elemet
item.selectedState()
container.backgroundColor = (items as [RAMAnimatedTabBarItem])[index].bgSelectedColor
}
item.image = nil
item.title = ""
index += 1
}
}
fileprivate func createConstraints(_ view:UIView, container:UIView, size:CGSize, yOffset:CGFloat) {
let constX = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal,
toItem: container,
attribute: NSLayoutAttribute.centerX,
multiplier: 1,
constant: 0)
container.addConstraint(constX)
let constY = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: container,
attribute: NSLayoutAttribute.centerY,
multiplier: 1,
constant: yOffset)
container.addConstraint(constY)
let constW = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: size.width)
view.addConstraint(constW)
let constH = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: size.height)
view.addConstraint(constH)
}
fileprivate func createViewContainers() -> NSDictionary {
guard let items = tabBar.items else {
fatalError("add items in tabBar")
}
var containersDict = [String: AnyObject]()
for index in 0..<items.count {
let viewContainer = createViewContainer()
containersDict["container\(index)"] = viewContainer
}
var formatString = "H:|-(0)-[container0]"
for index in 1..<items.count {
formatString += "-(0)-[container\(index)(==container0)]"
}
formatString += "-(0)-|"
let constranints = NSLayoutConstraint.constraints(withVisualFormat: formatString,
options:NSLayoutFormatOptions.directionRightToLeft,
metrics: nil,
views: (containersDict as [String : AnyObject]))
view.addConstraints(constranints)
return containersDict as NSDictionary
}
fileprivate func createViewContainer() -> UIView {
let viewContainer = UIView();
viewContainer.backgroundColor = UIColor.clear // for test
viewContainer.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(viewContainer)
// add gesture
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(RAMAnimatedTabBarController.tapHandler(_:)))
tapGesture.numberOfTouchesRequired = 1
viewContainer.addGestureRecognizer(tapGesture)
// add constrains
let constY = NSLayoutConstraint(item: viewContainer,
attribute: NSLayoutAttribute.bottom,
relatedBy: NSLayoutRelation.equal,
toItem: view,
attribute: NSLayoutAttribute.bottom,
multiplier: 1,
constant: 0)
view.addConstraint(constY)
let constH = NSLayoutConstraint(item: viewContainer,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: tabBar.frame.size.height)
viewContainer.addConstraint(constH)
return viewContainer
}
// MARK: actions
func tapHandler(_ gesture:UIGestureRecognizer) {
guard let items = tabBar.items as? [RAMAnimatedTabBarItem],
let gestureView = gesture.view else {
fatalError("items must inherit RAMAnimatedTabBarItem")
}
let currentIndex = gestureView.tag
if items[currentIndex].isEnabled == false { return }
let controller = self.childViewControllers[currentIndex]
if let shouldSelect = delegate?.tabBarController?(self, shouldSelect: controller)
, !shouldSelect {
return
}
if selectedIndex != currentIndex {
let animationItem : RAMAnimatedTabBarItem = items[currentIndex]
animationItem.playAnimation()
let deselectItem = items[selectedIndex]
let containerPrevious : UIView = deselectItem.iconView!.icon.superview!
containerPrevious.backgroundColor = items[currentIndex].bgDefaultColor
deselectItem.deselectAnimation()
let container : UIView = animationItem.iconView!.icon.superview!
container.backgroundColor = items[currentIndex].bgSelectedColor
selectedIndex = gestureView.tag
delegate?.tabBarController?(self, didSelect: controller)
} else if selectedIndex == currentIndex {
if let navVC = self.viewControllers![selectedIndex] as? UINavigationController {
navVC.popToRootViewController(animated: true)
}
}
}
}
|
gpl-3.0
|
3d96329a2c2263d07d978a0780d85686
| 33.452431 | 143 | 0.634205 | 5.539089 | false | false | false | false |
aldoram5/Swifty-Way
|
SwiftyWay/AppDelegate.swift
|
1
|
3324
|
//
// AppDelegate.swift
// SwiftyWay
//
// Created by Aldo Rangel on 11/2/15.
// Copyright © 2015 crimsonrgames. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
|
mit
|
d1609644f3b041332170aeca8a8c7aa1
| 53.47541 | 285 | 0.761059 | 6.142329 | false | false | false | false |
BurntIcing/IcingForMac
|
BurntIcingModel/Content.swift
|
1
|
2808
|
//
// Content.swift
// BurntIcing
//
// Created by Patrick Smith on 14/02/2015.
// Copyright (c) 2015 Burnt Caramel. All rights reserved.
//
import Foundation
public struct Content {
let JSONData: NSData
}
public struct Section {
//let UUID: NSUUID
var identifier: String
let content: Content
}
public class Document {
//let UUID: NSUUID
var identifier: String
var sections: [Section]
init(identifier: String) {
self.identifier = identifier
self.sections = []
}
func addSection(section: Section) {
sections.append(section)
}
}
@objc public protocol DocumentContentEditor {
func useLatestDocumentJSONDataOnMainQueue(callback: (NSData?) -> Void)
func usePreviewHTMLStringOnMainQueue(callback: (String?) -> Void)
func usePageSourceHTMLStringOnMainQueue(callback: (String?) -> Void) // For debugging
}
public class DocumentContentController {
internal var JSONData: NSData!
public weak var editor: DocumentContentEditor?
public init(JSONData: NSData?) {
if JSONData != nil {
self.JSONData = JSONData!.copy() as! NSData
}
}
public convenience init() {
self.init(JSONData: nil)
}
public func useLatestJSONDataOnMainQueue(callback: (NSData?) -> Void) {
#if DEBUG
println("DocumentContentController useLatestJSONDataOnMainQueue \(self.JSONData?.length)")
#endif
if let editor = editor {
NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in
editor.useLatestDocumentJSONDataOnMainQueue { (latestData) -> Void in
callback(latestData)
}
}
}
else {
NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in
callback(self.JSONData)
}
}
}
public func usePreviewHTMLStringOnMainQueue(callback: (String?) -> Void) {
var block: () -> Void
if let editor = editor {
block = {
editor.usePreviewHTMLStringOnMainQueue { (previewHTMLString) -> Void in
callback(previewHTMLString)
}
}
}
else {
block = {
callback(nil)
}
}
// Make sure it is always asynchronous.
NSOperationQueue.mainQueue().addOperationWithBlock(block)
}
public func usePageSourceHTMLStringOnMainQueue(callback: (String?) -> Void) {
var block: () -> Void
if let editor = editor {
block = {
editor.usePageSourceHTMLStringOnMainQueue { (sourceHTMLString) -> Void in
callback(sourceHTMLString)
}
}
}
else {
block = {
callback(nil)
}
}
// Make sure it is always asynchronous.
NSOperationQueue.mainQueue().addOperationWithBlock(block)
}
public func wrapNakedHTMLString(nakedHTMLString: String, pageTitle: String) -> String {
let template = HTMLTemplate(name: "wrapped-content-template")
return template.copyHTMLStringWithPlaceholderValues(
[
"__TITLE__": pageTitle,
"__BODY_CONTENT__": nakedHTMLString
]
);
}
}
|
apache-2.0
|
f147b5b45c030dbc7f03e08a6a7213d8
| 21.110236 | 93 | 0.696581 | 3.689882 | false | false | false | false |
gabrielvieira/TFStepProgress
|
TFStepProgress/Classes/TFStepProgress.swift
|
1
|
5749
|
//
// StepProgress.swift
// step
//
// Created by Gabriel Tomaz on 28/08/17.
// Copyright © 2017 Gabriel Tomaz. All rights reserved.
//
import UIKit
extension UIImage {
public class func bundledImage(named: String) -> UIImage? {
let image = UIImage(named: named)
if image == nil {
return UIImage(named: named, in: Bundle.init(for: TFStepProgress.classForCoder()), compatibleWith: nil)
} // Replace MyBasePodClass with yours
return image
}
}
public enum TFStepProgressDirection {
case next
case back
}
public class TFStepProgress: UIView {
private var stepItems: [TFStepItemView] = []
private var _currentIndex = 0
private var lockAnimation:Bool = false
private var defaultAnimationDuration = 0.5
private var noneAnimationDuration = 0.0
public var currentIndex: Int {
return _currentIndex
}
override public init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//TODO DEIXAR BONITO
public func setupItems(items: [TFStepItemConfig]) {
for (index,item) in items.enumerated() {
let xPos = 0 + CGFloat(index) * (self.frame.width / CGFloat(items.count) )
let step = TFStepItemView(frame: CGRect(x: xPos, y: 0, width: self.frame.width / CGFloat(items.count), height: self.frame.height))
let fontSize = self.calculateFontSize(items: items, maxHeight: step.titleHeight)
step.configure(config: item, fontSize: CGFloat(fontSize))
self.stepItems.append(step)
self.addSubview(step)
}
self.stepItems.first?.hideLeftBar()
self.lockAnimation = true
self.stepItems.first?.setActive(animationDuration: self.defaultAnimationDuration, firstAnimation: {}, completionHandler: {
self.lockAnimation = false
})
self.stepItems.last?.hideRightBar()
}
public func setStep(direction: TFStepProgressDirection) {
if lockAnimation { return }
lockAnimation = true
if direction == .next {
_currentIndex += 1
if _currentIndex == self.stepItems.count {
_currentIndex = self.stepItems.count - 1
self.lockAnimation = false
return
}
let stepItem = self.stepItems[_currentIndex]
let prev = self.stepItems[self._currentIndex - 1]
if currentIndex == self.stepItems.count - 1 {
stepItem.setActive(animationDuration: self.defaultAnimationDuration, firstAnimation: {}, completionHandler: {
stepItem.setComplete(animationDuration: self.defaultAnimationDuration, completionHandler: {
self.lockAnimation = false
})
})
}
stepItem.setActive(animationDuration: self.defaultAnimationDuration, firstAnimation: {
prev.setComplete(animationDuration: self.defaultAnimationDuration, completionHandler: {})
}, completionHandler: {
self.lockAnimation = false
})
} else {
let stepItem = self.stepItems[_currentIndex]
if _currentIndex > 0 {
stepItem.setDisabled(animationDuration: self.defaultAnimationDuration, completionHandler: {
self.lockAnimation = false
})
_currentIndex -= 1
let prev = self.stepItems[_currentIndex]
prev.setActive(animationDuration: self.noneAnimationDuration, firstAnimation: {}, completionHandler: {
self.lockAnimation = false
})
}
else{
stepItem.setActive(animationDuration: self.noneAnimationDuration, firstAnimation: {}, completionHandler: {
self.lockAnimation = false
})
}
if _currentIndex < 0 {
_currentIndex = 0
}
if _currentIndex == 0 {
self.lockAnimation = false
}
}
}
public func setStep(index: Int) {
if index < 0 || index > self.stepItems.count - 1 {
return
}
self.clearAllSteps()
for num in 0...index {
let stepItem = self.stepItems[num]
stepItem.setActive(animationDuration: self.noneAnimationDuration, firstAnimation: {}, completionHandler: {})
}
}
public func clearAllSteps () {
for num in 0...self.stepItems.count - 1 {
let stepItem = self.stepItems[num]
stepItem.setDisabled(animationDuration: self.noneAnimationDuration, completionHandler: {})
}
}
public func calculateFontSize(items: [TFStepItemConfig], maxHeight:CGFloat) -> CGFloat {
var fontSize = 0.0
var continueSearch = true
var x = 100
while continueSearch {
let sum = items.compactMap {$0.title.count}.reduce(0, +)
if (sum * x) > (Int(self.frame.width * 0.8)/items.count) && x > Int(maxHeight * 0.8) {
x-=1
} else {
fontSize = Double(x)
continueSearch = false
}
}
return CGFloat(fontSize)
}
}
|
mit
|
71d4dfe820df82e315cfd81a7c0ed4f7
| 32.034483 | 142 | 0.549235 | 5.095745 | false | false | false | false |
icapps/ios-delirium
|
Example/Example for Delirium/Modules/Dynamic Type/FontFamilyHeader.swift
|
1
|
1278
|
//
// FontFamilyHeader.swift
// Delirium
//
// Created by Nikki Vergracht on 31/05/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
class FontFamilyHeader: UITableViewHeaderFooterView {
let label = UILabel()
class var reuseIdentifier: String {
return String(describing: self)
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.backgroundColor = .clear
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.thin)
contentView.addSubview(label)
label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20).isActive = true
label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20).isActive = true
label.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 20).isActive = true
label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -20).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
1c8a13935acaa6c943771404e173e3ad
| 33.513514 | 107 | 0.696946 | 4.800752 | false | false | false | false |
mcxiaoke/learning-ios
|
ios_programming_4th/Hypnosister-ch5/Hypnosister/UIColorEx.swift
|
1
|
2250
|
//
// UIColorEx.swift
// Hypnosister
//
// Created by Xiaoke Zhang on 2017/8/15.
// Copyright © 2017年 Xiaoke Zhang. All rights reserved.
//
import UIKit
// from https://cocoacasts.com/from-hex-to-uicolor-and-back-in-swift/
extension UIColor {
// MARK: - Initialization
convenience init?(hex: String) {
var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines)
hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")
var rgb: UInt32 = 0
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 1.0
let length = hexSanitized.characters.count
guard Scanner(string: hexSanitized).scanHexInt32(&rgb) else { return nil }
if length == 6 {
r = CGFloat((rgb & 0xFF0000) >> 16) / 255.0
g = CGFloat((rgb & 0x00FF00) >> 8) / 255.0
b = CGFloat(rgb & 0x0000FF) / 255.0
} else if length == 8 {
r = CGFloat((rgb & 0xFF000000) >> 24) / 255.0
g = CGFloat((rgb & 0x00FF0000) >> 16) / 255.0
b = CGFloat((rgb & 0x0000FF00) >> 8) / 255.0
a = CGFloat(rgb & 0x000000FF) / 255.0
} else {
return nil
}
self.init(red: r, green: g, blue: b, alpha: a)
}
// MARK: - Computed Properties
var toHex: String {
return toHex() ?? ""
}
// MARK: - From UIColor to String
func toHex(alpha: Bool = false) -> String? {
guard let components = cgColor.components, components.count >= 3 else {
return nil
}
let r = Float(components[0])
let g = Float(components[1])
let b = Float(components[2])
var a = Float(1.0)
if components.count >= 4 {
a = Float(components[3])
}
if alpha {
return String(format: "%02lX%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255), lroundf(a * 255))
} else {
return String(format: "%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255))
}
}
}
|
apache-2.0
|
1919b6b960b9d68c9512ce5da14750eb
| 27.443038 | 129 | 0.510903 | 3.834471 | false | false | false | false |
Pursuit92/antlr4
|
runtime/Swift/Antlr4/org/antlr/v4/runtime/misc/extension/ArrayExtension.swift
|
3
|
2882
|
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
import Foundation
//https://github.com/pNre/ExSwift/blob/master/ExSwift/Array.swift
extension Array {
@discardableResult
mutating func concat(_ addArray: [Element]) -> [Element] {
return self + addArray
}
mutating func removeObject<T:Equatable>(_ object: T) {
var index: Int?
for (idx, objectToCompare) in self.enumerated() {
if let to = objectToCompare as? T {
if object == to {
index = idx
}
}
}
if index != nil {
self.remove(at: index!)
}
}
/**
Removes the last element from self and returns it.
:returns: The removed element
*/
mutating func pop() -> Element {
return removeLast()
}
/**
Same as append.
:param: newElement Element to append
*/
mutating func push(_ newElement: Element) {
return append(newElement)
}
func all(_ test: (Element) -> Bool) -> Bool {
for item in self {
if !test(item) {
return false
}
}
return true
}
/**
Checks if test returns true for all the elements in self
:param: test Function to call for each element
:returns: True if test returns true for all the elements in self
*/
func every(_ test: (Element) -> Bool) -> Bool {
for item in self {
if !test(item) {
return false
}
}
return true
}
/**
Checks if test returns true for any element of self.
:param: test Function to call for each element
:returns: true if test returns true for any element of self
*/
func any(_ test: (Element) -> Bool) -> Bool {
for item in self {
if test(item) {
return true
}
}
return false
}
/* slice array
:param: index slice index
:param: isClose is close array
:param: first First array
:param: second Second array
*/
//func slice(startIndex startIndex:Int, endIndex:Int) -> Slice<Element> {
func slice(startIndex: Int, endIndex: Int) -> ArraySlice<Element> {
return self[startIndex ... endIndex]
}
// func slice(index:Int,isClose:Bool = false) ->(first:Slice<Element> ,second:Slice<Element>){
func slice(_ index: Int, isClose: Bool = false) -> (first:ArraySlice<Element>, second:ArraySlice<Element>) {
var first = self[0 ... index]
var second = self[index ..< count]
if isClose {
first = second + first
second = []
}
return (first, second)
}
}
|
bsd-3-clause
|
86fbd7ddafc3b37726fb3ea3fa2f488d
| 22.056 | 112 | 0.553782 | 4.386606 | false | true | false | false |
CesarValiente/CursoSwiftUniMonterrey
|
week4/week4_classes_vs_structures.playground/Contents.swift
|
1
|
1056
|
//: Week 4 - Classes vs Structures
import UIKit
class ProductClass {
var brand : String
var price : Double = 0.0
init (brand: String, price : Double) {
self.brand = brand
self.price = price
}
func calculateDisccountPrice (percentageDiscount : Double) -> Double {
return price - (price * percentageDiscount / 100)
}
}
var telephoneClass = ProductClass(brand : "Iphone", price : 150.00)
var telephone = telephoneClass
telephone.brand = "Iphone6+"
telephoneClass.brand
telephone.brand
struct ProductStruct {
var brand : String
var price : Double = 0.0
init (brand : String, price : Double) {
self.brand = brand
self.price = price
}
func calculateDisccountPrice (percentageDosccount : Double) -> Double {
return price - (price * percentageDosccount / 100)
}
}
var telephoneStruct = ProductStruct(brand: "Samsung", price : 50.0)
var telephoneMini = telephoneStruct
telephoneMini.brand = "Sony"
telephoneStruct.brand
telephoneMini.brand
|
mit
|
13e6ca91502368357f683684120f1348
| 21.956522 | 75 | 0.663826 | 4.015209 | false | false | false | false |
UncleJoke/Spiral
|
Spiral/GameKitHelper.swift
|
1
|
5420
|
//
// GameKitHelper.swift
// Spiral
//
// Created by 杨萧玉 on 15/9/13.
// Copyright © 2015年 杨萧玉. All rights reserved.
//
import Foundation
import GameKit
let kHighScoreLeaderboardIdentifier = "com.yulingtianxia.Spiral.HighScores"
let kClean100KillerAchievementID = "com.yulingtianxia.Spiral.clean100Killer"
let kCatch500ScoreAchievementID = "com.yulingtianxia.Spiral.catch500Score"
let kCatch500ShieldAchievementID = "com.yulingtianxia.Spiral.catch500Shield"
let kget50PointsAchievementID = "com.yulingtianxia.Spiral.get50"
let kget100PointsAchievementID = "com.yulingtianxia.Spiral.get100"
let kget200PointsAchievementID = "com.yulingtianxia.Spiral.get200"
let WantGamePauseNotification = "gamepause"
protocol GameKitHelperProtocol: NSObjectProtocol {
func onScoresSubmitted(success:Bool)
}
class GameKitHelper: NSObject, GKGameCenterControllerDelegate {
var delegate : GameKitHelperProtocol?
var lastError : NSError? {
willSet(newError) {
if newError != nil {
print("GameKitHelper ERROR: \(newError!.userInfo.description)")
}
}
}
var achievementsDictionary: [String:GKAchievement]
var submitScoreWithCompletionHandler: ((success: Bool)->Void)?
private var gameCenterFeaturesEnabled: Bool = false
private static let sharedInstance = GameKitHelper()
class var sharedGameKitHelper: GameKitHelper {
return sharedInstance
}
override init() {
achievementsDictionary = [String:GKAchievement]()
super.init()
}
//MARK: - Player Authentication
func authenticateLocalPlayer() {
let localPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler = { [unowned localPlayer] (viewController, error) in
self.lastError = error
if localPlayer.authenticated {
self.gameCenterFeaturesEnabled = true
self.submitScoreWithCompletionHandler?(success: true)
self.loadAchievements()
}
else if let vc = viewController {
self.pause()
self.presentViewController(vc)
}
else {
self.gameCenterFeaturesEnabled = false
self.submitScoreWithCompletionHandler?(success: false)
}
}
}
//MARK: - UIViewController stuff
func getRootViewController() -> UIViewController? {
return UIApplication.sharedApplication().keyWindow?.rootViewController;
}
func presentViewController(vc: UIViewController) {
let rootVC = self.getRootViewController()
rootVC?.presentViewController(vc, animated: true, completion: nil)
}
// MARK: - GameKitHelperProtocol
func submitScore(score: Int64, identifier: String) {
//1: Check if Game Center features are enabled
guard gameCenterFeaturesEnabled else {
submitScoreWithCompletionHandler?(success: false)
return
}
//2: Create a GKScore object
let gkScore = GKScore(leaderboardIdentifier: identifier)
//3: Set the score value
gkScore.value = score
//4: Send the score to Game Center
GKScore.reportScores([gkScore]) { (error) -> Void in
self.lastError = error
let success = (error == nil)
self.submitScoreWithCompletionHandler?(success: success)
self.delegate?.onScoresSubmitted(success)
}
}
func pause() {
NSNotificationCenter.defaultCenter().postNotificationName(WantGamePauseNotification, object: nil)
}
//MARK: - Achievements Methods
func loadAchievements() {
GKAchievement.loadAchievementsWithCompletionHandler { (achievements, error) -> Void in
if let achievements = achievements where error == nil {
for achievement in achievements {
self.achievementsDictionary[achievement.identifier!] = achievement
}
}
}
}
func getAchievementForIdentifier(identifier: String) -> GKAchievement {
guard let achievement = achievementsDictionary[identifier] else {
let achievement = GKAchievement(identifier: identifier)
achievementsDictionary[achievement.identifier!] = achievement
return achievement;
}
return achievement;
}
func updateAchievement(achievement: GKAchievement, identifier: String) {
achievementsDictionary[identifier] = achievement
}
func reportMultipleAchievements() {
GKAchievement.reportAchievements(Array(achievementsDictionary.values)) { (error) -> Void in
if error != nil {
fatalError("Error in reporting achievements:\(error)")
}
}
}
func showLeaderboard() {
let gameCenterController = GKGameCenterViewController()
pause()
gameCenterController.gameCenterDelegate = self
gameCenterController.viewState = .Achievements
presentViewController(gameCenterController)
}
//MARK: - GKGameCenterControllerDelegate
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) {
getRootViewController()?.dismissViewControllerAnimated(true, completion: nil)
}
}
|
mit
|
a1ae03420872ee941b91ca2ceafb50f5
| 33.433121 | 105 | 0.658834 | 5.051402 | false | false | false | false |
RobinFalko/Ubergang
|
Ubergang/Tween/BezierPathTween.swift
|
1
|
9665
|
//
// BezierPathTween.swift
// Ubergang
//
// Created by Robin Frielingsdorf on 14/01/16.
// Copyright © 2016 Robin Falko. All rights reserved.
//
import Foundation
import UIKit
import GLKit
open class BezierPathTween: UTweenBase {
var offset: Double?
var current: (() -> UIBezierPath)!
var updateValue: ((_ value: CGPoint) -> Void)!
var updateValueAndProgress: ((_ value: CGPoint, _ progress: Double) -> Void)!
var updateValueAndProgressAndOrientation: ((_ value: CGPoint, _ progress: Double, _ orientation: CGPoint) -> Void)!
var pathInfo: ([Float], Float)?
var elements: [(type: CGPathElementType, points: [CGPoint])]!
/**
Initialize a generic `UTween` with a random id.
Tweens any value with type T from start to end.
This object needs to know how to compute interpolations from start to end, that for
`func compute(value: Double) -> T` must be overriden.
*/
public convenience init() {
let id = "\(#file)_\(arc4random())_update"
self.init(id: id)
}
/**
Initialize a generic `UTween`.
Tweens any value with type T from start to end.
This object needs to know how to compute interpolations from start to end, that for
`func compute(value: Double) -> T` must be overriden.
- Parameter id: The unique id of the Tween
*/
public override init(id: String) {
super.init(id: id)
}
override open var progress: Double {
set {
time = newValue * duration
easeValue = ease.function(time, 0.0, 1.0, duration)
//if an offset is set, add it to the current ease value
if let offset = offset {
easeValue = fmod(easeValue + offset, 1.0)
}
let computedValue = compute(easeValue)
//call update closures if set
updateValue?( computedValue )
updateValueAndProgress?( computedValue, newValue )
updateValueAndProgressAndOrientation?( computedValue, newValue, orientation ?? CGPoint.zero )
super.progress = newValue
}
get {
return time / duration
}
}
var previousPoint: CGPoint?
var orientation: CGPoint?
func compute(_ value: Double) -> CGPoint {
var currentSegmentIndex = 0
var currentDistance: Double = 0
var lower: Double = 0
var upper: Double = 0
for i in 0..<elements.count {
currentDistance = value * Double(pathInfo!.1)
upper = (Double(pathInfo!.0[i]))
if currentDistance <= lower + upper {
currentSegmentIndex = i
break
}
lower += (Double(pathInfo!.0[i]))
}
let element = elements[currentSegmentIndex]
let mapped = Math.mapValueInRange(currentDistance,
fromLower: lower, fromUpper: lower + upper,
toLower: 0.0, toUpper: 1.0)
var newPoint:CGPoint!
switch element.type {
case .moveToPoint:
newPoint = element.points[0]
case .addLineToPoint:
newPoint = Bezier.linear(t: CGFloat(mapped),
p0: element.points[0],
p1: element.points[1])
case .addQuadCurveToPoint:
newPoint = Bezier.quad(t: CGFloat(mapped),
p0: element.points[0],
p1: element.points[1],
p2: element.points[2])
case .addCurveToPoint:
newPoint = Bezier.cubic(t: CGFloat(mapped),
p0: element.points[0],
p1: element.points[1],
p2: element.points[2],
p3: element.points[3])
case .closeSubpath:
newPoint = Bezier.linear(t: CGFloat(mapped),
p0: element.points[0],
p1: element.points[1])
@unknown default:
break
}
//calculate the orientation vector from one vector to the other,
//but only if these vectors are not equal
if let previousPoint = previousPoint , previousPoint != newPoint {
let v0 = GLKVector2(v: (Float(newPoint.x), Float(newPoint.y)))
let v1 = GLKVector2(v: (Float(previousPoint.x), Float(previousPoint.y)))
var vDirection = GLKVector2Subtract(v0, v1)
vDirection = GLKVector2Normalize(vDirection)
orientation = CGPoint(x: CGFloat(vDirection.x), y: CGFloat(vDirection.y))
}
previousPoint = newPoint
return newPoint
}
var path: UIBezierPath!
/**
Build a 'BezierPathTween'.
Tweens the value along a `UIBezierPath` from start to end.
- Parameter path: The bezier path
- Parameter update: A closure containing the value on update
- Parameter duration: The duration of the Tween
- Parameter id: The unique id of the Tween
- Returns: The built Tween
*/
open func along(_ path: UIBezierPath) -> Self {
self.path = path
elements = path.cgPath.getElements()
pathInfo = computeDistances(elements)
return self
}
/**
Build a 'BezierPathTween'.
Tweens the value along a `UIBezierPath` from start to end. The path will go curve through the given points.
- Parameter points: The points where the path will curve through
- Parameter update: A closure containing the value on update
- Parameter duration: The duration of the Tween
- Parameter id: The unique id of the Tween
- Returns: The built Tween
*/
open func along(_ points: [CGPoint], closed: Bool = false) -> Self {
let numbers = points.map { NSValue(cgPoint: $0) }
self.path = UIBezierPath.interpolateCGPoints(withCatmullRom: numbers, closed: closed, alpha: 1.0)!
elements = path.cgPath.getElements()
pathInfo = computeDistances(elements)
return self
}
open func update(_ value: @escaping (CGPoint) -> Void) -> Self {
updateValue = value
return self
}
open func update(_ value: @escaping (CGPoint, Double) -> Void) -> Self {
updateValueAndProgress = value
return self
}
open func update(_ value: @escaping (CGPoint, Double, CGPoint) -> Void) -> Self {
updateValueAndProgressAndOrientation = value
return self
}
open func ease(_ ease: Ease) -> Self {
self.ease = ease
return self
}
open func offset(_ value: Double) -> Self {
self.offset = value
return self
}
func computeDistances(_ elements: [(type: CGPathElementType, points: [CGPoint])]) -> (distanceElements: [Float], distanceSum: Float) {
var pr = CGPoint.zero
var currentV = GLKVector2(v: (0, 0))
var previousV = GLKVector2(v: (0, 0))
var distanceSum: Float = 0
var distanceElements = [Float]()
let interval = 10000
for element in elements {
var distanceElement: Float = 0
for i in 0..<interval {
let t = Float(i) / Float(interval)
switch element.type {
case .moveToPoint:
let p = element.points[0]
previousV = GLKVector2(v: (Float(p.x), Float(p.y)))
case .addLineToPoint:
pr = Bezier.linear(t: CGFloat(t),
p0: element.points[0],
p1: element.points[1])
case .addQuadCurveToPoint:
pr = Bezier.quad(t: CGFloat(t),
p0: element.points[0],
p1: element.points[1],
p2: element.points[2])
case .addCurveToPoint:
pr = Bezier.cubic(t: CGFloat(t),
p0: element.points[0],
p1: element.points[1],
p2: element.points[2],
p3: element.points[3])
case .closeSubpath:
pr = Bezier.linear(t: CGFloat(t),
p0: element.points[0],
p1: element.points[1])
@unknown default:
break
}
if GLKVector2Length(previousV) == 0 {
let p = element.points[0]
previousV = GLKVector2(v: (Float(p.x), Float(p.y)))
}
currentV = GLKVector2(v: (Float(pr.x), Float(pr.y)))
distanceElement += GLKVector2Distance(currentV, previousV)
previousV = currentV
}
distanceElements.append(distanceElement)
distanceSum += distanceElement
}
return (distanceElements, distanceSum)
}
}
|
apache-2.0
|
fe36d3dd57404afb24d573ed85b77c96
| 33.76259 | 138 | 0.510348 | 4.989158 | false | false | false | false |
coderZsq/coderZsq.target.swift
|
StudyNotes/Foundation/Algorithm4Swift/Algorithm4Swift/Algorithm/Raywenderlich/Big-O notation.swift
|
1
|
2131
|
//
// Big-O notation.swift
// Algorithm
//
// Created by 朱双泉 on 2018/5/22.
// Copyright © 2018 Castie!. All rights reserved.
//
import Foundation
struct Big_O {
static let array = [1, 2, 3, 4, 5, 6]
static func _1() {
let value = array[5]
print(value)
}
static func _log_n(_ n: Int) {
var j = 1
while j < n {
j *= 2
print(j)
}
}
static func _n(_ n: Int) {
for i in stride(from: 0, to: n, by: 1) {
print(array[i])
}
}
static func _n_log_n(_ n: Int) {
if n % 2 == 0 {
for i in stride(from: 0, to: n, by: 1) {
var j = 1
while j < n {
j *= 2
print(i * j)
}
}
} else {
for i in stride(from: 0, to: n, by: 1) {
func index(after i: Int) -> Int? {
return i < n ? i * 2 : nil
}
for j in sequence(first: 1, next: index(after:)) {
print(i * j)
}
}
}
}
//n^2
static func _n_2(_ n: Int) {
for i in stride(from: 0, to: n, by: 1) {
for j in stride(from: 1, to: n, by: 1) {
print(i * j)
}
}
}
//n^3
static func _n_3(_ n: Int) {
for i in stride(from: 0, to: n, by: 1) {
for j in stride(from: 1, to: n, by: 1) {
for k in stride(from: 1, to: n, by: 1) {
print(i * j * k)
}
}
}
}
//2^n
static func _2_n(_ n: Int, from: String, to: String, spare: String) {
guard n >= 1 else { return }
if n > 1 {
_2_n(n - 1, from: from, to: spare, spare: to)
} else {
_2_n(n - 1, from: spare, to: to, spare: from)
}
}
//n!
static func _n_fact(_ n: Int) {
for i in stride(from: 0, to: n, by: 1) {
print(i)
_n_fact(n - 1)
}
}
}
|
mit
|
10e3fd17a4fe07dff35a7d28c0d2bf1e
| 22.086957 | 73 | 0.361111 | 3.33438 | false | false | false | false |
khizkhiz/swift
|
test/IRGen/protocol_metadata.swift
|
2
|
3866
|
// RUN: %target-swift-frontend -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
protocol A { func a() }
protocol B { func b() }
protocol C : class { func c() }
@objc protocol O { func o() }
@objc protocol OPT {
optional func opt()
optional static func static_opt()
optional var prop: O { get }
optional subscript (x: O) -> O { get }
}
protocol AB : A, B { func ab() }
protocol ABO : A, B, O { func abo() }
// CHECK: @_TMp17protocol_metadata1A = {{(protected )?}}constant %swift.protocol {
// -- size 72
// -- flags: 1 = Swift | 2 = Not Class-Constrained | 4 = Needs Witness Table
// CHECK: i32 72, i32 7,
// CHECK: i16 0, i16 0
// CHECK: }
// CHECK: @_TMp17protocol_metadata1B = {{(protected )?}}constant %swift.protocol {
// CHECK: i32 72, i32 7,
// CHECK: i16 0, i16 0
// CHECK: }
// CHECK: @_TMp17protocol_metadata1C = {{(protected )?}}constant %swift.protocol {
// -- flags: 1 = Swift | 4 = Needs Witness Table
// CHECK: i32 72, i32 5,
// CHECK: i16 0, i16 0
// CHECK: }
// -- @objc protocol O uses ObjC symbol mangling and layout
// CHECK: @_PROTOCOL__TtP17protocol_metadata1O_ = private constant { {{.*}} i32, { [1 x i8*] }* } {
// CHECK: @_PROTOCOL_INSTANCE_METHODS__TtP17protocol_metadata1O_,
// -- flags: 1 = Swift
// CHECK: i32 80, i32 1
// CHECK: }
// CHECK: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata1O_
// CHECK: }
// -- @objc protocol OPT uses ObjC symbol mangling and layout
// CHECK: @_PROTOCOL__TtP17protocol_metadata3OPT_ = private constant { {{.*}} i32, { [4 x i8*] }* } {
// CHECK: @_PROTOCOL_INSTANCE_METHODS_OPT__TtP17protocol_metadata3OPT_,
// CHECK: @_PROTOCOL_CLASS_METHODS_OPT__TtP17protocol_metadata3OPT_,
// -- flags: 1 = Swift
// CHECK: i32 80, i32 1
// CHECK: }
// CHECK: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata3OPT_
// CHECK: }
// -- inheritance lists for refined protocols
// CHECK: [[AB_INHERITED:@.*]] = private constant { {{.*}}* } {
// CHECK: i64 2,
// CHECK: %swift.protocol* @_TMp17protocol_metadata1A,
// CHECK: %swift.protocol* @_TMp17protocol_metadata1B
// CHECK: }
// CHECK: @_TMp17protocol_metadata2AB = {{(protected )?}}constant %swift.protocol {
// CHECK: [[AB_INHERITED]]
// CHECK: i32 72, i32 7,
// CHECK: i16 0, i16 0
// CHECK: }
// CHECK: [[ABO_INHERITED:@.*]] = private constant { {{.*}}* } {
// CHECK: i64 3,
// CHECK: %swift.protocol* @_TMp17protocol_metadata1A,
// CHECK: %swift.protocol* @_TMp17protocol_metadata1B,
// CHECK: {{.*}}* @_PROTOCOL__TtP17protocol_metadata1O_
// CHECK: }
func reify_metadata<T>(x: T) {}
// CHECK: define hidden void @_TF17protocol_metadata14protocol_types
func protocol_types(a: A,
abc: protocol<A, B, C>,
abco: protocol<A, B, C, O>) {
// CHECK: store %swift.protocol* @_TMp17protocol_metadata1A
// CHECK: call %swift.type* @rt_swift_getExistentialTypeMetadata(i64 1, %swift.protocol** {{%.*}})
reify_metadata(a)
// CHECK: store %swift.protocol* @_TMp17protocol_metadata1A
// CHECK: store %swift.protocol* @_TMp17protocol_metadata1B
// CHECK: store %swift.protocol* @_TMp17protocol_metadata1C
// CHECK: call %swift.type* @rt_swift_getExistentialTypeMetadata(i64 3, %swift.protocol** {{%.*}})
reify_metadata(abc)
// CHECK: store %swift.protocol* @_TMp17protocol_metadata1A
// CHECK: store %swift.protocol* @_TMp17protocol_metadata1B
// CHECK: store %swift.protocol* @_TMp17protocol_metadata1C
// CHECK: [[O_REF:%.*]] = load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP17protocol_metadata1O_"
// CHECK: [[O_REF_BITCAST:%.*]] = bitcast i8* [[O_REF]] to %swift.protocol*
// CHECK: store %swift.protocol* [[O_REF_BITCAST]]
// CHECK: call %swift.type* @rt_swift_getExistentialTypeMetadata(i64 4, %swift.protocol** {{%.*}})
reify_metadata(abco)
}
|
apache-2.0
|
b2ffe538f138d76a5be531ffb12a3d72
| 37.277228 | 117 | 0.643559 | 3.125303 | false | false | false | false |
barbrobmich/linkbase
|
LinkBase/LinkBase/CreateAccountViewController.swift
|
1
|
3928
|
//
// CreateAccountViewController.swift
// LinkBase
//
// Created by Michael Leung on 3/30/17.
// Copyright © 2017 barbrobmich. All rights reserved.
//
import UIKit
import Parse
class CreateAccountViewController: UIViewController {
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var confirmPasswordTextField: UITextField!
var currentUser: User?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - USER SET UP METHODS
func createUser(completion: (_ success: Bool) -> Void) {
currentUser = User(_email: emailTextField.text!, _password: passwordTextField.text!, _firstname: firstNameTextField.text!, _lastname: lastNameTextField.text!)
completion (true)
}
@IBAction func exit(_ sender: Any) {
navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
}
@IBAction func createAccount(_ sender: Any) {
// MOVE THIS TO A VALIDATION FUNCTION. IF VALIDATE IS SUCCESSFUL THEN WE CAN DO THE SUBSEQUENT STEPS
// if passwordTextField.text != confirmPasswordTextField.text {
// alert(message: "Passwords do not match")
// }
createUser{ (success) -> Void in
if success {
currentUser!.signUpInBackground { (succeeded: Bool, error: Error?) in
if let error = error {
print("error: \(error)")
// self.alert(message: "Username already taken")
// // Show the errorString somewhere and let the user try again.
} else {
print("user created!")
self.setUpDefaultAffiliation()
self.alert(message: "User created!")
}
}
}
}
}
//This feature assumes that the user is a CodePath student. Default affiliation with CodePath is created so that the affiliations array is not empty when the user accesses this view controller (AddAffiliations).
func setUpDefaultAffiliation(){
let defaultAffiliation = Affiliation()
defaultAffiliation.name = "CodePath"
defaultAffiliation.user = User.current()
Affiliation.postAffiliationToParse(affiliation: defaultAffiliation) { (success: Bool, error: Error?) -> Void in
if success {
print("Successful Post to Parse")
}
else {
print("Can't post to parse")
}
}
}
func alert(message: String) {
let alert = UIAlertController(title: "Alert", message: "\(message)", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Now let's set up your profile", style: UIAlertActionStyle.default, handler: {_ in self.goToProfile(currUser: self.currentUser!)
}))
self.present(alert, animated: true, completion: nil)
}
func goToProfile(currUser: PFUser){
NotificationCenter.default.post(name: NSNotification.Name(rawValue: User.userDidSignUp), object: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
1b08d81925be0877289aa6966d3ac3af
| 32.564103 | 216 | 0.628215 | 4.921053 | false | false | false | false |
EmuxEvans/CocoaMQTT
|
CocoaMQTT/CocoaMQTTFrame.swift
|
2
|
8643
|
//
// CocoaMQTTFrame.swift
// CocoaMQTT
//
// Created by Feng Lee<feng@eqmtt.io> on 14/8/3.
// Copyright (c) 2015 emqtt.io. All rights reserved.
//
import Foundation
/**
* Encode and Decode big-endian UInt16
*/
extension UInt16 {
//Most Significant Byte (MSB)
var highByte: UInt8 { return UInt8( (self & 0xFF00) >> 8) }
//Least Significant Byte (LSB)
var lowByte: UInt8 { return UInt8(self & 0x00FF) }
var hlBytes: [UInt8] { return [highByte, lowByte] }
}
/**
* String with two bytes length
*/
extension String {
//ok?
var bytesWithLength: [UInt8] { return UInt16(utf8.count).hlBytes + utf8 }
}
/**
* Bool to bit
*/
extension Bool {
var bit: UInt8 { return self ? 1 : 0}
init(bit: UInt8) {
self = (bit == 0) ? false : true
}
}
/**
* read bit
*/
extension UInt8 {
func bitAt(offset: UInt8) -> UInt8 {
return (self >> offset) & 0x01
}
}
/**
* MQTT Frame Type
*/
enum CocoaMQTTFrameType: UInt8 {
case RESERVED = 0x00
case CONNECT = 0x10
case CONNACK = 0x20
case PUBLISH = 0x30
case PUBACK = 0x40
case PUBREC = 0x50
case PUBREL = 0x60
case PUBCOMP = 0x70
case SUBSCRIBE = 0x80
case SUBACK = 0x90
case UNSUBSCRIBE = 0xA0
case UNSUBACK = 0xB0
case PINGREQ = 0xC0
case PINGRESP = 0xD0
case DISCONNECT = 0xE0
}
/**
* MQTT Frame
*/
class CocoaMQTTFrame {
/**
* |--------------------------------------
* | 7 6 5 4 | 3 | 2 1 | 0 |
* | Type | DUP flag | QoS | RETAIN |
* |--------------------------------------
*/
var header: UInt8 = 0
var type: UInt8 { return UInt8(header & 0xF0) }
var dup: Bool {
get { return ((header & 0x08) >> 3) == 0 ? false : true }
set { header |= (newValue.bit << 3) }
}
var qos: UInt8 {
//#define GETQOS(HDR) ((HDR & 0x06) >> 1)
get { return (header & 0x06) >> 1 }
//#define SETQOS(HDR, Q) (HDR | ((Q) << 1))
set { header |= (newValue << 1) }
}
var retain: Bool {
get { return (header & 0x01) == 0 ? false : true }
set { header |= newValue.bit }
}
/*
* Variable Header
*/
var variableHeader: [UInt8] = []
/*
* Payload
*/
var payload: [UInt8] = []
init(header: UInt8) {
self.header = header
}
init(type: CocoaMQTTFrameType, payload: [UInt8] = []) {
self.header = type.rawValue
self.payload = payload
}
func data() -> [UInt8] {
self.pack()
return [UInt8]([header]) + encodeLength() + variableHeader + payload
}
func encodeLength() -> [UInt8] {
var bytes: [UInt8] = []
var digit: UInt8 = 0
var len: UInt32 = UInt32(variableHeader.count+payload.count)
repeat {
digit = UInt8(len % 128)
len = len / 128
// if there are more digits to encode, set the top bit of this digit
if len > 0 { digit = digit | 0x80 }
bytes.append(digit)
} while len > 0
return bytes
}
func pack() { return; } //do nothing
}
/**
* MQTT CONNECT Frame
*/
class CocoaMQTTFrameConnect: CocoaMQTTFrame {
let PROTOCOL_LEVEL = UInt8(4)
let PROTOCOL_VERSION: String = "MQTT/3.1.1"
let PROTOCOL_MAGIC: String = "MQTT"
/**
* |----------------------------------------------------------------------------------
* | 7 | 6 | 5 | 4 3 | 2 | 1 | 0 |
* | username | password | willretain | willqos | willflag | cleansession | reserved |
* |----------------------------------------------------------------------------------
*/
var flags: UInt8 = 0
var flagUsername: Bool {
//#define FLAG_USERNAME(F, U) (F | ((U) << 7))
get { return Bool(bit: (flags >> 7) & 0x01) }
set { flags |= (newValue.bit << 7) }
}
var flagPasswd: Bool {
//#define FLAG_PASSWD(F, P) (F | ((P) << 6))
get { return Bool(bit:(flags >> 6) & 0x01) }
set { flags |= (newValue.bit << 6) }
}
var flagWillRetain: Bool {
//#define FLAG_WILLRETAIN(F, R) (F | ((R) << 5))
get { return Bool(bit: (flags >> 5) & 0x01) }
set { flags |= (newValue.bit << 5) }
}
var flagWillQOS: UInt8 {
//#define FLAG_WILLQOS(F, Q) (F | ((Q) << 3))
get { return (flags >> 3) & 0x03 }
set { flags |= (newValue << 3) }
}
var flagWill: Bool {
//#define FLAG_WILL(F, W) (F | ((W) << 2))
get { return Bool(bit:(flags >> 2) & 0x01) }
set { flags |= ((newValue.bit) << 2) }
}
var flagCleanSess: Bool {
//#define FLAG_CLEANSESS(F, C) (F | ((C) << 1))
get { return Bool(bit: (flags >> 1) & 0x01) }
set { flags |= ((newValue.bit) << 1) }
}
var client: CocoaMQTTClient
init(client: CocoaMQTT) {
self.client = client
super.init(type: CocoaMQTTFrameType.CONNECT)
}
override func pack() {
//variable header
variableHeader += PROTOCOL_MAGIC.bytesWithLength
variableHeader.append(PROTOCOL_LEVEL)
//payload
payload += client.clientId.bytesWithLength
if let will = client.willMessage {
flagWill = true
flagWillQOS = will.qos.rawValue
flagWillRetain = will.retain
payload += will.topic.bytesWithLength
payload += will.payload
}
if let username = client.username {
flagUsername = true
payload += username.bytesWithLength
}
if let password = client.password {
flagPasswd = true
payload += password.bytesWithLength
}
//flags
flagCleanSess = client.cleanSess
variableHeader.append(flags)
variableHeader += client.keepAlive.hlBytes
}
}
/**
* MQTT PUBLISH Frame
*/
class CocoaMQTTFramePublish: CocoaMQTTFrame {
var msgid: UInt16?
var topic: String?
var data: [UInt8]?
init(msgid: UInt16, topic: String, payload: [UInt8]) {
super.init(type: CocoaMQTTFrameType.PUBLISH, payload: payload)
self.msgid = msgid
self.topic = topic
}
init(header: UInt8, data: [UInt8]) {
super.init(header: header)
self.data = data
}
func unpack() {
//topic
var msb = data![0], lsb = data![1]
let len = UInt16(msb) << 8 + UInt16(lsb)
var pos: Int = 2 + Int(len)
topic = NSString(bytes: [UInt8](data![2...(pos-1)]), length: Int(len), encoding: NSUTF8StringEncoding) as? String
//msgid
if qos == 0 {
msgid = 0
} else {
msb = data![pos]; lsb = data![pos+1]
msgid = UInt16(msb) << 8 + UInt16(lsb)
pos += 2
}
//payload
let end = data!.count - 1
payload = [UInt8](data![pos...end])
}
override func pack() {
variableHeader += topic!.bytesWithLength
if qos > 0 {
variableHeader += msgid!.hlBytes
}
}
}
/**
* MQTT PUBACK Frame
*/
class CocoaMQTTFramePubAck: CocoaMQTTFrame {
var msgid: UInt16?
init(type: CocoaMQTTFrameType, msgid: UInt16) {
super.init(type: type)
if type == CocoaMQTTFrameType.PUBREL {
qos = CocoaMQTTQOS.QOS1.rawValue
}
self.msgid = msgid
}
override func pack() {
variableHeader += msgid!.hlBytes
}
}
/**
* MQTT SUBSCRIBE Frame
*/
class CocoaMQTTFrameSubscribe: CocoaMQTTFrame {
var msgid: UInt16?
var topic: String?
var reqos: UInt8 = CocoaMQTTQOS.QOS0.rawValue
init(msgid: UInt16, topic: String, reqos: UInt8) {
super.init(type: CocoaMQTTFrameType.SUBSCRIBE)
self.msgid = msgid
self.topic = topic
self.reqos = reqos
self.qos = CocoaMQTTQOS.QOS1.rawValue
}
override func pack() {
variableHeader += msgid!.hlBytes
payload += topic!.bytesWithLength
payload.append(reqos)
}
}
/**
* MQTT UNSUBSCRIBE Frame
*/
class CocoaMQTTFrameUnsubscribe: CocoaMQTTFrame {
var msgid: UInt16?
var topic: String?
init(msgid: UInt16, topic: String) {
super.init(type: CocoaMQTTFrameType.UNSUBSCRIBE)
self.msgid = msgid
self.topic = topic
qos = CocoaMQTTQOS.QOS1.rawValue
}
override func pack() {
variableHeader += msgid!.hlBytes
payload += topic!.bytesWithLength
}
}
|
mit
|
cfe80f84ac04a00fe6391b15e6440946
| 20.340741 | 121 | 0.519727 | 3.611784 | false | false | false | false |
glbuyer/GbKit
|
GbKit/Models/GBCurrencyExchange.swift
|
1
|
1172
|
//
// GBCurrencyExchange.swift
// GbKit
//
// Created by Ye Gu on 1/9/17.
// Copyright © 2017 glbuyer. All rights reserved.
//
import Foundation
import ObjectMapper
enum GBCurrencyType : String {
//澳元
case AUD = "AUD"
//人民币
case CNY = "CNY"
//美元
case USD = "USD"
//日元
case JPY = "JPY"
//其他
case OTHER = "OTHER"
}
enum GBCurrencySymbol : String {
//澳元
case AUD = "$"
//人民币
case CNY = "¥"
//美元
case USD = "$#USD"
//日元
case JPY = "¥#JPY"
//其他
case OTHER = "$#OTHER"
}
class GBCurrencyExchange:GBBaseModel {
//主货币单位
var fromCurrency = GBCurrencyType.OTHER
//转换后货币单位
var toCurrency = GBCurrencyType.OTHER
//主货币单位符号
var fromCurrencySymbol = GBCurrencySymbol.OTHER
//转换后货币单位符号
var toCurrencySymbol = GBCurrencySymbol.OTHER
//汇兑比率
var rate:Double = 1
// Mappable
override func mapping(map: Map) {
super.mapping(map: map)
}
}
|
mit
|
634ad25ff4055140359a3a0af698c597
| 13.915493 | 51 | 0.539188 | 3.340694 | false | false | false | false |
TakuSemba/DribbbleSwiftApp
|
Carthage/Checkouts/RxSwift/Rx.playground/Pages/Mathematical_and_Aggregate_Operators.xcplaygroundpage/Contents.swift
|
1
|
2551
|
/*:
> # IMPORTANT: To use **Rx.playground**:
1. Open **Rx.xcworkspace**.
1. Build the **RxSwift-OSX** scheme (**Product** → **Build**).
1. Open **Rx** playground in the **Project navigator**.
1. Show the Debug Area (**View** → **Debug Area** → **Show Debug Area**).
----
[Previous](@previous) - [Table of Contents](Table_of_Contents)
*/
import RxSwift
/*:
# Mathematical and Aggregate Operators
Operators that operate on the entire sequence of items emitted by an `Observable`.
## `toArray`
Converts an `Observable` sequence into an array, emits that array as a new single-element `Observable` sequence, and then terminates. [More info](http://reactivex.io/documentation/operators/to.html)

*/
example("toArray") {
let disposeBag = DisposeBag()
Observable.range(start: 1, count: 10)
.toArray()
.subscribe { print($0) }
.addDisposableTo(disposeBag)
}
/*:
----
## `reduce`
Begins with an initial seed value, and then applies an accumulator closure to all elements emitted by an `Observable` sequence, and returns the aggregate result as a single-element `Observable` sequence. [More info](http://reactivex.io/documentation/operators/reduce.html)

*/
example("reduce") {
let disposeBag = DisposeBag()
Observable.of(10, 100, 1000)
.reduce(1, accumulator: +)
.subscribeNext { print($0) }
.addDisposableTo(disposeBag)
}
/*:
----
## `concat`
Joins elements from inner `Observable` sequences of an `Observable` sequence in a sequential manner, waiting for each sequence to terminate successfully before emitting elements from the next sequence. [More info](http://reactivex.io/documentation/operators/concat.html)

*/
example("concat") {
let disposeBag = DisposeBag()
let subject1 = BehaviorSubject(value: "🍎")
let subject2 = BehaviorSubject(value: "🐶")
let variable = Variable(subject1)
variable.asObservable()
.concat()
.subscribe { print($0) }
.addDisposableTo(disposeBag)
subject1.onNext("🍐")
subject1.onNext("🍊")
variable.value = subject2
subject2.onNext("🐱")
subject1.onCompleted()
subject2.onNext("🐭")
}
//: [Next](@next) - [Table of Contents](Table_of_Contents)
|
apache-2.0
|
64d8ec157fadee204df797c8f80f049c
| 34.591549 | 273 | 0.675505 | 4.197674 | false | false | false | false |
devpunk/velvet_room
|
Source/Model/Vita/MVitaPtpMessageInEventHandlesFactory.swift
|
1
|
678
|
import Foundation
extension MVitaPtpMessageInEventHandles
{
private static let kTotalHandles:Int = 2
//MARK: internal
static func factoryHandles(
event:MVitaPtpMessageInEvent) -> MVitaPtpMessageInEventHandles?
{
guard
event.parameters.count == kTotalHandles,
let item:UInt32 = event.parameters.first,
let parent:UInt32 = event.parameters.last
else
{
return nil
}
let handles:MVitaPtpMessageInEventHandles = MVitaPtpMessageInEventHandles(
item:item,
parent:parent)
return handles
}
}
|
mit
|
a24da1f9d25583f31697e9f6fefe980c
| 22.37931 | 82 | 0.587021 | 4.612245 | false | false | false | false |
alvivi/BadType
|
BadTypeTests/Specs/FontStylesCatalogSpec.swift
|
1
|
7781
|
// Copyright 2015 Alvaro Vilanova Vidal. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
import Quick
import Nimble
@testable import BadType
class FontStylesCatalogSpec: QuickSpec {
override func spec() {
describe("FontStylesCatalog") {
it("should throw an error when catalog file do not exists") {
}
it("should throw an error when catalog file root element is not an array") {
}
it("should throw an error when a catalog root entry is not a dictionary") {
expect {
try FontStylesCatalog(fromArray: [
[
"Style Name": "Foo",
"Size Categories": [
"Medium": [
"Size": 14,
],
],
],
"To The Moon!",
])
}.to(throwError())
}
}
describe("Default FontStylesCatalog") {
it("should find the default catalog") {
expect{ try FontStylesCatalog() }.toNot(throwError())
}
it("should have 10 entries") {
expect { () -> Void in
let catalog = try FontStylesCatalog()
expect(catalog.fontStyles.count).to(equal(10))
}.toNot(throwError())
}
}
describe("FontStyle") {
it("should initialize with minimal contents") {
expect {
try FontStyle(fromDictionary: [
"Style Name": "Foo",
"Size Categories": [
"Medium": [
"Size": 14,
],
],
])
}.toNot(throwError())
}
it("should initialize with a single trait") {
expect {
try FontStyle(fromDictionary: [
"Style Name": "Foo",
"Size Categories": [
"Medium": [
"Size": 14,
"Traits": "Bold",
],
],
])
}.toNot(throwError())
}
it("should initialize with multiple trait") {
expect {
try FontStyle(fromDictionary: [
"Style Name": "Foo",
"Size Categories": [
"Medium": [
"Size": 14,
"Traits": ["Bold", "Italic"],
],
],
])
}.toNot(throwError())
}
it("should throw an error when style name entry is not present") {
expect {
try FontStyle(fromDictionary: [
"style name": "Foo", // Note lower case
"Size Categories": [
"Medium": [
"Size": 14,
],
],
])
}.to(throwError())
}
it("should throw an error when style name entry is not a string") {
expect {
try FontStyle(fromDictionary: [
"Style Name": 42,
"Size Categories": [
"Medium": [
"Size": 14,
],
],
])
}.to(throwError())
}
it("should throw an error when size categories entry is not present") {
expect {
try FontStyle(fromDictionary: [
"Style Name": "Foo",
"size categories": [ // Note lower case
"Medium": [
"Size": 14,
],
],
])
}.to(throwError())
}
it("should throw an error when size categories entry is not a dictionary") {
expect {
try FontStyle(fromDictionary: [
"Style Name": "Foo",
"Size Categories": [
"Medium": "To The Moon!",
],
])
}.to(throwError())
}
it("should throw an error when a size category has an invalid name") {
expect {
try FontStyle(fromDictionary: [
"Style Name": "Foo",
"Size Categories": [
"medium": [ // Note lower case
"Size": 14,
],
],
])
}.to(throwError())
}
it("should throw an error when a size category value is not present") {
expect {
try FontStyle(fromDictionary: [
"Style Name": "Foo",
"Size Categories": [
"Medium": [
],
],
])
}.to(throwError())
}
it("should throw an error when a size category has an invalid value") {
expect {
try FontStyle(fromDictionary: [
"Style Name": "Foo",
"Size Categories": [
"Medium": [
"Size": -42,
],
],
])
}.to(throwError())
}
it("should throw an error when a trait category value is invalid") {
expect {
try FontStyle(fromDictionary: [
"Style Name": "Foo",
"Size Categories": [
"Medium": [
"Size": 14,
"Traits": "To the Moon",
],
],
])
}.to(throwError())
}
}
describe("FontStylesCatalog.fontWithStyleName") {
it("should return the default font when style name is not valid") {
expect { () -> Void in
let catalog = try FontStylesCatalog()
BadType.contentSizeCategory = UIContentSizeCategoryMedium
let font = catalog.fontWithStyleName("TO THE MOON!")
expect(font.fontName).to(match(UIFont.systemFontOfSize(0).fontName))
expect(font.pointSize).to(equal(UIFont.systemFontSize()))
}.toNot(throwError())
}
it("should trim style name") {
expect { () -> Void in
let catalog = try FontStylesCatalog()
BadType.contentSizeCategory = UIContentSizeCategoryMedium
let font = catalog.fontWithStyleName(" Headline ")
expect(font.pointSize).to(equal(19))
}.toNot(throwError())
}
it("should works with no font override and no default font") {
expect { () -> Void in
let catalog = try FontStylesCatalog()
BadType.contentSizeCategory = UIContentSizeCategoryMedium
let font = catalog.fontWithStyleName("Headline")
expect(font.fontName).to(match(UIFont.systemFontOfSize(0).fontName))
expect(font.pointSize).to(equal(19))
}.toNot(throwError())
}
it("should override fonts") {
expect { () -> Void in
let catalog = try FontStylesCatalog(fromArray: [
[
"Style Name": "Foo",
"Size Categories": [
"Medium": [
"Font Name": "Arial",
"Size": 14,
],
],
],
])
BadType.contentSizeCategory = UIContentSizeCategoryMedium
let defaultFont = UIFont(name: "Avenir", size: 20)!
let font = catalog.fontWithStyleName("Foo", defaultFont: defaultFont)
expect(font.fontName).to(match("Arial"))
expect(font.pointSize).to(equal(14))
}.toNot(throwError())
}
it("should set font name") {
expect { () -> Void in
let catalog = try FontStylesCatalog(fromArray: [
[
"Style Name": "Foo",
"Size Categories": [
"Medium": [
"Font Name": "Arial",
"Size": 14,
],
],
],
])
BadType.contentSizeCategory = UIContentSizeCategoryMedium
expect(catalog.fontWithStyleName("Foo").fontName).to(match("Arial"))
}.toNot(throwError())
}
}
}
}
|
bsd-3-clause
|
8579ed9e3dd4fb58b01fc10f075e48e2
| 28.362264 | 82 | 0.470505 | 5.010303 | false | false | false | false |
jf-rce/SwiftEasingFunctions
|
Easing/Elastic/ElasticEaseInOut.swift
|
1
|
982
|
//
// ElasticEaseInOut.swift
// Easing
//
// Created by Justin Forsyth on 10/21/15.
// Copyright © 2015 jforce. All rights reserved.
//
import Foundation
import UIKit
public class ElasticEaseInOut : EasingFunction {
override public func calculate(var t: Float, var b: Float, var c: Float, var d: Float)->Float{
if (t==0){
return b;
}
t = t / (d / 2);
if (t==2){
return b+c;
}
var p = d * (0.3 * 1.5);
var a = c;
var s = p / 4;
if (t < 1){
t = t - 1;
return -0.5*(a*Float(pow(2,10*t)) * Float(sin( Float(t*d-s)*Float(2*CGFloat(M_PI))/p ))) + b;
}
t = t - 1;
return a*Float(pow(2,-10*t)) * Float(sin(Float(t*d-s)*Float(2*CGFloat(M_PI))/p )) * 0.5 + c + b;
}
}
|
bsd-3-clause
|
612b4385511c1701e565ad5b6ca26325
| 18.254902 | 105 | 0.404689 | 3.503571 | false | false | false | false |
XLabKC/Badger
|
Badger/Badger/UserProfileHeaderCell.swift
|
1
|
1507
|
import UIKit
import Haneke
class UserProfileHeaderCell: UITableViewCell {
private var hasAwakened = false
private var user: User?
@IBOutlet weak var profileCircle: ProfileCircle!
@IBOutlet weak var backgroundImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
override func awakeFromNib() {
self.hasAwakened = true
self.updateView()
}
func setUser(user: User) {
self.user = user
self.updateView()
}
@IBAction func logout(sender: AnyObject) {
Firebase(url: Global.FirebaseUrl).unauth()
}
private func updateView() {
if self.hasAwakened {
// 656x448
if let user = self.user {
self.nameLabel.text = user.fullName
self.profileCircle.setUid(user.uid)
self.statusLabel.text = user.statusText
self.statusLabel.textColor = Helpers.statusToColor(user.status)
// Set the header background image.
let placeholder = UIImage(named: "DefaultBackground")
if user.headerImage != "" {
let url = Helpers.getHeaderImageUrl(user.headerImage)
self.backgroundImage.hnk_setImageFromURL(url, placeholder: placeholder, format: nil, failure: nil, success: nil)
} else {
self.backgroundImage.image = placeholder
}
}
}
}
}
|
gpl-2.0
|
e960265fd34a1c6db8e324f2337a7a11
| 30.395833 | 132 | 0.592568 | 4.924837 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/Utility/Blogging Prompts/ReminderScheduleCoordinator.swift
|
1
|
6774
|
import UserNotifications
/// Bridges the logic between Blogging Reminders and Blogging Prompts.
///
/// Users can switch between receiving Blogging Reminders or Blogging Prompts based on the switch toggle in the reminder sheet. They are both delivered
/// through local notifications, but the mechanism between the two is differentiated due to technical limitations. Blogging Prompts requires the content
/// of each notification to be different, and this is not possible if we want to use a repeating `UNCalendarNotificationTrigger`.
///
class ReminderScheduleCoordinator {
// MARK: Dependencies
private let bloggingRemindersScheduler: BloggingRemindersScheduler
private let promptRemindersScheduler: PromptRemindersScheduler
private let bloggingPromptsServiceFactory: BloggingPromptsServiceFactory
// MARK: Public Methods
init(bloggingRemindersScheduler: BloggingRemindersScheduler,
promptRemindersScheduler: PromptRemindersScheduler,
bloggingPromptsServiceFactory: BloggingPromptsServiceFactory = .init()) {
self.bloggingRemindersScheduler = bloggingRemindersScheduler
self.promptRemindersScheduler = promptRemindersScheduler
self.bloggingPromptsServiceFactory = bloggingPromptsServiceFactory
}
convenience init(notificationScheduler: NotificationScheduler = UNUserNotificationCenter.current(),
pushNotificationAuthorizer: PushNotificationAuthorizer = InteractiveNotificationsManager.shared,
bloggingPromptsServiceFactory: BloggingPromptsServiceFactory = .init()) throws {
let bloggingRemindersScheduler = try BloggingRemindersScheduler(notificationCenter: notificationScheduler,
pushNotificationAuthorizer: pushNotificationAuthorizer)
let promptRemindersScheduler = PromptRemindersScheduler(bloggingPromptsServiceFactory: bloggingPromptsServiceFactory,
notificationScheduler: notificationScheduler,
pushAuthorizer: pushNotificationAuthorizer)
self.init(bloggingRemindersScheduler: bloggingRemindersScheduler,
promptRemindersScheduler: promptRemindersScheduler,
bloggingPromptsServiceFactory: bloggingPromptsServiceFactory)
}
/// Returns the user's reminder schedule for the given `blog`, based on the current reminder type.
///
/// - Parameter blog: The blog associated with the reminders.
/// - Returns: The user's preferred reminder schedule.
func schedule(for blog: Blog) -> BloggingRemindersScheduler.Schedule {
switch reminderType(for: blog) {
case .bloggingReminders:
return bloggingRemindersScheduler.schedule(for: blog)
case .bloggingPrompts:
guard let settings = promptReminderSettings(for: blog),
let reminderDays = settings.reminderDays,
!reminderDays.getActiveWeekdays().isEmpty else {
return .none
}
return .weekdays(reminderDays.getActiveWeekdays())
}
}
/// Returns the user's preferred time for the given `blog`, based on the current reminder type.
///
/// - Parameter blog: The blog associated with the reminders.
/// - Returns: The user's preferred time returned in `Date`.
func scheduledTime(for blog: Blog) -> Date {
switch reminderType(for: blog) {
case .bloggingReminders:
return bloggingRemindersScheduler.scheduledTime(for: blog)
case .bloggingPrompts:
guard let settings = promptReminderSettings(for: blog),
let dateForTime = settings.reminderTimeDate() else {
return Constants.defaultTime
}
return dateForTime
}
}
/// Schedules a reminder notification for the given `blog` based on the current reminder type.
///
/// - Note: Calling this method will trigger the push notification authorization flow.
///
/// - Parameters:
/// - schedule: The preferred notification schedule.
/// - blog: The blog that will upload the user's post.
/// - time: The user's preferred time to be notified.
/// - completion: Closure called after the process completes.
func schedule(_ schedule: BloggingRemindersScheduler.Schedule,
for blog: Blog,
time: Date? = nil,
completion: @escaping (Result<Void, Swift.Error>) -> ()) {
switch reminderType(for: blog) {
case .bloggingReminders:
bloggingRemindersScheduler.schedule(schedule, for: blog, time: time) { [weak self] result in
// always unschedule prompt reminders in case the user toggled the switch.
self?.promptRemindersScheduler.unschedule(for: blog)
completion(result)
}
case .bloggingPrompts:
promptRemindersScheduler.schedule(schedule, for: blog, time: time) { [weak self] result in
// always unschedule blogging reminders in case the user toggled the switch.
self?.bloggingRemindersScheduler.unschedule(for: blog)
completion(result)
}
}
}
/// Unschedules all future reminders from the given `blog`.
/// This applies to both Blogging Reminders and Blogging Prompts.
///
/// - Parameter blog: The blog associated with the reminders.
func unschedule(for blog: Blog) {
bloggingRemindersScheduler.unschedule(for: blog)
promptRemindersScheduler.unschedule(for: blog)
}
}
// MARK: - Private Helpers
private extension ReminderScheduleCoordinator {
enum ReminderType {
case bloggingReminders
case bloggingPrompts
}
enum Constants {
static let defaultHour = 10
static let defaultMinute = 0
static var defaultTime: Date {
let calendar = Calendar.current
return calendar.date(from: DateComponents(calendar: calendar, hour: defaultHour, minute: defaultMinute)) ?? Date()
}
}
func promptReminderSettings(for blog: Blog) -> BloggingPromptSettings? {
guard let service = bloggingPromptsServiceFactory.makeService(for: blog) else {
return nil
}
return service.localSettings
}
func reminderType(for blog: Blog) -> ReminderType {
if Feature.enabled(.bloggingPrompts),
let settings = promptReminderSettings(for: blog),
settings.promptRemindersEnabled {
return .bloggingPrompts
}
return .bloggingReminders
}
}
|
gpl-2.0
|
acbd6dfb5ea4f43826eb9be0b8e6d382
| 41.873418 | 152 | 0.665633 | 5.552459 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios
|
Frameworks/TBAData/Sources/Event/EventInsights.swift
|
1
|
2481
|
import CoreData
import Foundation
import TBAKit
extension EventInsights {
public var playoff: [String: Any]? {
return getValue(\EventInsights.playoffRaw)
}
public var qual: [String: Any]? {
return getValue(\EventInsights.qualRaw)
}
public var event: Event {
guard let event = getValue(\EventInsights.eventRaw) else {
fatalError("Save EventInsights before accessing event")
}
return event
}
}
@objc(EventInsights)
public class EventInsights: NSManagedObject {
@nonobjc public class func fetchRequest() -> NSFetchRequest<EventInsights> {
return NSFetchRequest<EventInsights>(entityName: EventInsights.entityName)
}
@NSManaged var playoffRaw: [String: Any]?
@NSManaged var qualRaw: [String: Any]?
@NSManaged var eventRaw: Event?
}
extension EventInsights: Managed {
/**
Insert an EventInsights with values from a TBAKit EventInsights model in to the managed object context.
- Important: This method does not manage setting up a relationship between an Event and EventInsights.
- Parameter model: The TBAKit EventInsights representation to set values from.
- Parameter eventKey: The key for the Event the EventInsights belongs to.
- Parameter context: The NSManagedContext to insert the EventInsights in to.
- Returns: The inserted Event.
*/
@discardableResult
public static func insert(_ model: TBAEventInsights, eventKey: String, in context: NSManagedObjectContext) -> EventInsights {
let predicate = NSPredicate(format: "%K == %@",
#keyPath(EventInsights.eventRaw.keyRaw), eventKey)
return findOrCreate(in: context, matching: predicate) { (insights) in
// TODO: Handle NSNull? At least write a test
insights.qualRaw = model.qual
insights.playoffRaw = model.playoff
}
}
}
extension EventInsights {
public var insightsDictionary: [String: Any] {
var insights: [String: [String: Any]] = [:]
if let qual = qual {
insights["qual"] = qual
}
if let playoff = playoff {
insights["playoff"] = playoff
}
return insights
}
}
extension EventInsights: Orphanable {
public var isOrphaned: Bool {
// EventInsights should never be orphaned because they'll cascade with an Event's deletion
return eventRaw == nil
}
}
|
mit
|
4ef960e6dfe19d047855aa1ca22b0f63
| 26.263736 | 129 | 0.655784 | 4.743786 | false | false | false | false |
RuiAAPeres/Nuke
|
Nuke/Source/Core/ImageMemoryCache.swift
|
1
|
2668
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Alexander Grebenyuk (github.com/kean).
import Foundation
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
public protocol ImageMemoryCaching {
func cachedResponseForKey(key: ImageRequestKey) -> ImageCachedResponse?
func storeResponse(response: ImageCachedResponse, forKey key: ImageRequestKey)
func removeAllCachedImages()
}
public class ImageCachedResponse {
public let image: Image
public let userInfo: Any?
public init(image: Image, userInfo: Any?) {
self.image = image
self.userInfo = userInfo
}
}
/** Auto purging memory caches.
*/
public class ImageMemoryCache: ImageMemoryCaching {
public let cache: NSCache
deinit {
#if os(iOS)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
#endif
}
public init(cache: NSCache) {
self.cache = cache
#if os(iOS)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didReceiveMemoryWarning:"), name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
#endif
}
public convenience init() {
let cache = NSCache()
cache.totalCostLimit = ImageMemoryCache.recommendedCacheTotalLimit()
#if os(OSX)
cache.countLimit = 100
#endif
self.init(cache: cache)
}
public func cachedResponseForKey(key: ImageRequestKey) -> ImageCachedResponse? {
return self.cache.objectForKey(key) as? ImageCachedResponse
}
public func storeResponse(response: ImageCachedResponse, forKey key: ImageRequestKey) {
self.cache.setObject(response, forKey: key, cost: self.costForImage(response.image))
}
public func costForImage(image: Image) -> Int {
#if os(OSX)
return 1
#else
let imageRef = image.CGImage
let bits = CGImageGetWidth(imageRef) * CGImageGetHeight(imageRef) * CGImageGetBitsPerPixel(imageRef)
return bits / 8
#endif
}
public class func recommendedCacheTotalLimit() -> Int {
let physicalMemory = Double(NSProcessInfo.processInfo().physicalMemory)
let ratio = physicalMemory <= (1024 * 1024 * 512 /* 512 Mb */) ? 0.1 : 0.2
let limit = physicalMemory * ratio
return limit > Double(Int.max) ? Int.max : Int(limit)
}
public func removeAllCachedImages() {
self.cache.removeAllObjects()
}
@objc private func didReceiveMemoryWarning(notification: NSNotification) {
self.cache.removeAllObjects()
}
}
|
mit
|
b4157434c7a0c5c32893f9e82a4e7d82
| 29.666667 | 183 | 0.66979 | 4.764286 | false | false | false | false |
acrocat/EverLayout
|
Source/Model/ELConstraintModel.swift
|
1
|
6064
|
// EverLayout
//
// Copyright (c) 2017 Dale Webster
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public class ELConstraintModel: ELRawData
{
public var constraintParser : LayoutConstraintParser!
public var leftSideAttributes : [NSLayoutAttribute?]? {
return self.constraintParser.leftSideAttributes(source: self.rawData)
}
public var rightSideAttribute : NSLayoutAttribute? {
return self.constraintParser.rightSideAttribute(source: self.rawData)
}
public var constant : ELConstraintConstant {
return self.constraintParser.constant(source: self.rawData) ?? ELConstraintConstant(value: 0, sign: .positive)
}
public var multiplier : ELConstraintMultiplier {
return self.constraintParser.multiplier(source: self.rawData) ?? ELConstraintMultiplier(value: 1, sign: .multiply)
}
public var priority : CGFloat? {
return self.constraintParser.priority(source: self.rawData)
}
public var relation : NSLayoutRelation {
return self.constraintParser.relation(source: self.rawData) ?? .equal
}
public var comparableViewReference : String? {
return self.constraintParser.comparableViewReference(source: self.rawData)
}
public var identifier : String? {
return self.constraintParser.identifier(source: self.rawData)
}
public var verticalSizeClass : UIUserInterfaceSizeClass? {
return self.constraintParser.verticalSizeClass(source: self.rawData) ?? .unspecified
}
public var horizontalSizeClass : UIUserInterfaceSizeClass? {
return self.constraintParser.horizontalSizeClass(source: self.rawData) ?? .unspecified
}
public init (rawData : Any , parser : LayoutConstraintParser)
{
super.init(rawData: rawData)
self.constraintParser = parser
}
public func establishConstraints (onView view : ELViewModel , withViewIndex viewIndex : ViewIndex , viewEnvironment : NSObject? = nil) {
guard let target = view.target else { return }
for attr in self.leftSideAttributes ?? [] {
guard let attr = attr else { continue }
// Properties of the constraints can be changed or inferred to make writing them easier. For this we
// will use a EverLayoutConstraintContext
let context = ELConstraintContext(
_target: target,
_leftSideAttribute: attr,
_relation: self.relation,
_comparableView: (self.comparableViewReference == "super") ? target.superview : viewIndex.view(forKey: self.comparableViewReference ?? "") ?? viewEnvironment?.property(forKey: self.comparableViewReference ?? "") as? UIView,
_rightSideAttribute: self.rightSideAttribute,
_constant: self.constant,
_multiplier: self.multiplier)
// Create the constraint from the context
let constraint : ELConstraint = ELConstraint(item: context.target, attribute: context.leftSideAttribute, relatedBy: context.relation, toItem: context.comparableView, attribute: context.rightSideAttribute ?? context.leftSideAttribute, multiplier: context.multiplier.value, constant: context.constant.value)
// Constraint priority
if let priority = self.priority {
constraint.priority = UILayoutPriority(Float(priority))
}
// SizeClasses
constraint.horizontalSizeClass = self.horizontalSizeClass
constraint.verticalSizeClass = self.verticalSizeClass
// Set active / inactive
constraint.setActiveForTraitCollection(target.traitCollection)
// Add an identifier to the constraint
constraint.identifier = self.identifier
// Add the constraint to the root view
let constraintTarget = viewIndex.rootView() ?? target.superview ?? target
// Check that these the view and comparable view are in the same hierarchy before
// adding the constraint as this will cause a crash
if target.sharesAncestry(withView: context.comparableView ?? target) {
// Add this constraint to the applied constraints of the ELView
view.appliedConstraints.append(constraint)
constraintTarget.addConstraint(constraint)
} else {
if let identifier = self.identifier {
ELReporter.default.error(message: "Some views do not share a view ancestry and so this constraint cannot be made. Constraint: \(identifier)")
} else {
ELReporter.default.error(message: "Some views do not share a view ancestry and so this constraint cannot be made. Use constraint identifiers to determine which constraint is causing the problem.")
}
}
}
}
}
|
mit
|
0341dae5c24ac54832939eadbdce365b
| 47.126984 | 317 | 0.673318 | 5.20515 | false | false | false | false |
YoungGary/30daysSwiftDemo
|
day14/day14/day14/ViewController.swift
|
1
|
3913
|
//
// ViewController.swift
// day14
//
// Created by YOUNG on 2016/10/10.
// Copyright © 2016年 Young. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
//IB
@IBOutlet weak var emojiPickerView: UIPickerView!
@IBOutlet weak var goButton: UIButton!
@IBAction func didClickGoButton(sender: AnyObject) {
//变图案 动画
let row = arc4random()%90 + 3
emojiPickerView.selectRow(Int(row), inComponent: 0, animated: true)
emojiPickerView.selectRow(Int(row), inComponent: 1, animated: true)
emojiPickerView.selectRow(Int(row), inComponent: 2, animated: true)
if dataArray1[emojiPickerView.selectedRowInComponent(0)] == dataArray2[emojiPickerView.selectedRowInComponent(1)] && dataArray2[emojiPickerView.selectedRowInComponent(1)] == dataArray3[emojiPickerView.selectedRowInComponent(2)] {
bingoLabel.text = "bingo"
}else{
bingoLabel.text = "no bingo"
}
//animation
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.1, initialSpringVelocity: 1, options: .CurveLinear, animations: {
self.goButton.bounds = CGRect(x: self.buttonBounds.origin.x, y: self.buttonBounds.origin.y, width: self.buttonBounds.size.width + 20, height: self.buttonBounds.size.height)
}, completion: { (compelete: Bool) in
UIView.animateWithDuration(0.1, delay: 0.0, options: .CurveEaseInOut, animations: {
self.goButton.bounds = CGRect(x: self.buttonBounds.origin.x, y: self.buttonBounds.origin.y, width: self.buttonBounds.size.width, height: self.buttonBounds.size.height)
}, completion: nil)
})
}
@IBOutlet weak var bingoLabel: UILabel!
var imageArray : [String] = ["👻","👸","💩","😘","🍔","🤖","🍟","🐼","🚖","🐷"]
var dataArray1 = [Int]()
var dataArray2 = [Int]()
var dataArray3 = [Int]()
var buttonBounds : CGRect = CGRectZero
override func viewDidLoad() {
super.viewDidLoad()
for _ in 0..<100 {
dataArray1.append((Int)(arc4random() % 10 ))
dataArray2.append((Int)(arc4random() % 10 ))
dataArray3.append((Int)(arc4random() % 10 ))
}
bingoLabel.text = ""
buttonBounds = goButton.bounds
emojiPickerView.delegate = self
emojiPickerView.dataSource = self
goButton.layer.cornerRadius = 6
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 100
}
func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return 100.0
}
func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 100.0
}
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
let pickerLabel = UILabel()
if component == 0 {
pickerLabel.text = imageArray[(Int)(dataArray1[row])]
} else if component == 1 {
pickerLabel.text = imageArray[(Int)(dataArray2[row])]
} else {
pickerLabel.text = imageArray[(Int)(dataArray3[row])]
}
pickerLabel.font = UIFont(name: "Apple Color Emoji", size: 80)
pickerLabel.textAlignment = NSTextAlignment.Center
return pickerLabel
}
}
|
mit
|
6421c27d104ed88ffd9c58fdb49ec7e7
| 30.463415 | 238 | 0.594574 | 4.668275 | false | false | false | false |
docileninja/Calvin-and-Hobbes-Viewer
|
Viewer/Calvin and Hobbes/Controllers/FavoritesViewController.swift
|
1
|
2053
|
//
// FavoritesViewController.swift
// Calvin and Hobbes
//
// Created by Adam Van Prooyen on 4/14/16.
// Copyright © 2016 Adam Van Prooyen. All rights reserved.
//
import UIKit
class FavoritesViewController: UIViewController {
let defaults = UserDefaults.standard
var favorites: [Date]!
var comicManager: ComicManager!
@IBOutlet weak var tableView: UITableView!
func initialize(_ comicManager: ComicManager) {
self.comicManager = comicManager
}
override func viewWillAppear(_ animated: Bool) {
if let favorites = defaults.object(forKey: "favorites") as? [Date] {
self.favorites = favorites.sorted(by: { $0.compare($1) == .orderedAscending })
}
tableView.reloadData()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "ShowComic") {
let date = favorites[(tableView.indexPathForSelectedRow! as NSIndexPath).row]
let vc = segue.destination as! ComicPageViewController
vc.initialize(comicManager, date: date)
}
}
}
extension FavoritesViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return favorites.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Favorite", for: indexPath)
cell.textLabel?.text = favorites[(indexPath as NSIndexPath).row].stringFromFormat("EEEE d MMMM YYYY")
return cell
}
}
extension FavoritesViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "ShowComic", sender: self)
tableView.deselectRow(at: indexPath, animated: true)
}
}
|
mit
|
a60f8a505b0c520baf6ddfc23003fcde
| 29.626866 | 109 | 0.665692 | 4.932692 | false | false | false | false |
y0ke/actor-platform
|
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Group/AAInviteLinkViewController.swift
|
2
|
2843
|
//
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
public class AAInviteLinkViewController: AAContentTableController {
// Data
public var currentUrl: String?
// Rows
public var urlRow: AACommonRow!
public init(gid: Int) {
super.init(style: AAContentTableStyle.SettingsGrouped)
self.gid = gid
self.title = AALocalized("GroupInviteLinkPageTitle")
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func tableDidLoad() {
tableView.hidden = true
section { (s) -> () in
s.headerText = AALocalized("GroupInviteLinkTitle")
s.footerText = AALocalized("GroupInviteLinkHint")
self.urlRow = s.common { (r) -> () in
r.bindAction = { (r) -> () in
r.content = self.currentUrl
}
}
}
section { (s) -> () in
s.action("ActionCopyLink") { (r) -> () in
r.selectAction = { () -> Bool in
UIPasteboard.generalPasteboard().string = self.currentUrl
self.alertUser("AlertLinkCopied")
return true
}
}
s.action("ActionShareLink") { (r) -> () in
r.selectAction = { () -> Bool in
var sharingItems = [AnyObject]()
sharingItems.append(self.currentUrl!)
let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil)
self.presentViewController(activityViewController, animated: true, completion: nil)
return true
}
}
}
section { (s) -> () in
s.danger("ActionRevokeLink") { (r) -> () in
r.selectAction = { () -> Bool in
self.confirmDestructive(AALocalized("GroupInviteLinkRevokeMessage"), action: AALocalized("GroupInviteLinkRevokeAction"), yes: { () -> () in
self.reloadLink()
})
return true
}
}
}
executeSafe(Actor.requestInviteLinkCommandWithGid(jint(gid))!) { (val) -> Void in
self.currentUrl = val as? String
self.urlRow.reload()
self.tableView.hidden = false
}
}
public func reloadLink() {
executeSafe(Actor.requestRevokeLinkCommandWithGid(jint(gid))!) { (val) -> Void in
self.currentUrl = val as? String
self.urlRow.reload()
self.tableView.hidden = false
}
}
}
|
agpl-3.0
|
cbb090170bad6330c22a716506adcc84
| 31.318182 | 159 | 0.51108 | 5.094982 | false | false | false | false |
SteveRohrlack/CitySimCore
|
examples/Contentobjects/Powerplant.swift
|
1
|
839
|
//
// Powerplant.swift
// CitySimCore
//
// Created by Steve Rohrlack on 15.06.16.
// Copyright © 2016 Steve Rohrlack. All rights reserved.
//
import Foundation
struct PowerplantPlopp: Ploppable, Conditionable, MapStatistical, Budgetable, PlaceNearStreet, RessourceProducing {
let origin: (Int, Int)
let height: Int = 4
let width: Int = 4
var name = "Powerplant"
let description = "just a small powerplant"
let cost: Int? = 1000
let runningCost: Int? = 200
let type: TileType = .Ploppable(.Powerplant)
let statistics: MapStatisticContainer = MapStatisticContainer(mapStatistics: .Noise(radius: 3, value: 4))
var conditions: ConditionContainer = ConditionContainer()
let ressource: RessourceType = .Electricity(100)
init(origin: (Int, Int)) {
self.origin = origin
}
}
|
mit
|
9daa3d197c449ee7e450a3e9d1529c54
| 28.964286 | 115 | 0.692124 | 3.791855 | false | false | false | false |
lulee007/GankMeizi
|
GankMeizi/MainTabBarViewController.swift
|
1
|
3852
|
//
// MainTabBarViewController.swift
// GankMeizi
//
// Created by 卢小辉 on 16/5/26.
// Copyright © 2016年 lulee007. All rights reserved.
//
import UIKit
import SwiftyUserDefaults
import RxSwift
import RxCocoa
class MainTabBarViewController: UITabBarController {
var searchText: Driver<String>?
var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
Defaults[.launchCount] += 1
self.tabBar.tintColor = ThemeUtil.colorWithHexString(ThemeUtil.ACCENT_COLOR)
// 1、设置导航栏标题属性:设置标题颜色
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
// 2、设置导航栏前景色:设置item指示色
self.navigationController?.navigationBar.barTintColor = ThemeUtil.colorWithHexString(ThemeUtil.DARK_PRIMARY_COLOR)
// 3、设置导航栏前景色:设置item指示色
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
let caption = UILabel()
let frame = self.navigationController?.navigationBar.bounds
caption.frame = CGRectMake((frame?.origin.x)!, (frame?.origin.y)!, 20, (frame?.size.height)!)
caption.text = "GANK.IO"
caption.textColor = UIColor.whiteColor()
caption.font = UIFont(name: "GillSans-Bold", size: 18)
caption.sizeToFit()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: caption)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: #selector(showSearchView))
self.title = "最新"
launchAnimation()
}
//MARK: tabbar
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
self.title = item.title
if item.title == "关于"{
self.navigationItem.rightBarButtonItem?.enabled = false
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.clearColor()
}else{
self.navigationItem.rightBarButtonItem?.enabled = true
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.whiteColor()
}
}
// MARK: 启动画面过渡效果
func launchAnimation() {
if !Defaults[.splashAnimated] {
Defaults[.splashAnimated] = true
let toAnimVC = ControllerUtil.loadViewControllerWithName("LaunchScreen", sbName: "LaunchScreen")
let launchView = toAnimVC.view
let mainWindow = UIApplication .sharedApplication().keyWindow
launchView.frame = (mainWindow?.frame)!
mainWindow?.addSubview(launchView)
UIView.animateWithDuration(1.0, delay: 0.5, options: UIViewAnimationOptions.BeginFromCurrentState, animations: {
launchView.alpha = 0.0
launchView.layer.transform = CATransform3DScale(CATransform3DIdentity, 2.0, 2.0, 1.0)
}) { (finished) in
launchView.removeFromSuperview()
}
}
}
var model: SearchModel!
func showSearchView() {
model = SearchModel()
let searchController = ControllerUtil.loadViewControllerWithName("SearchResults", sbName: "Main")
self.navigationController?.pushViewController(searchController, animated: true)
}
//MARK: 对外接口
static func buildController() -> MainTabBarViewController{
let controller = ControllerUtil.loadViewControllerWithName("MainTabBar", sbName: "Main") as! MainTabBarViewController
// does not need anim
Defaults[.splashAnimated] = true
return controller
}
}
|
mit
|
1671057b52e534efbca93a3abb886186
| 35.087379 | 143 | 0.645682 | 5.084815 | false | false | false | false |
hgani/ganilib-ios
|
glib/Classes/JsonUi/Views/Button.swift
|
1
|
569
|
class JsonView_ButtonV1: JsonView {
#if INCLUDE_UILIBS
private let view = MButton()
#else
private let view = GButton()
.color(bg: nil, text: .darkGray)
.border(color: .darkGray)
.font(nil, size: 12)
#endif
override func initView() -> UIView {
if let text = spec["text"].string {
_ = view.title(text)
}
_ = view.onClick { _ in
JsonAction.execute(spec: self.spec["onClick"], screen: self.screen, creator: self.view)
}
return view
}
}
|
mit
|
2a9c256315d110e555803c2ce7c0b9d9
| 27.45 | 99 | 0.528998 | 3.818792 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
BlockchainTests/DelegatedCustody/DelegatedCustodySigningServiceTests.swift
|
1
|
1724
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
@testable import BlockchainApp
import Combine
import DelegatedSelfCustodyDomain
import XCTest
final class DelegatedCustodySigningServiceTests: XCTestCase {
var subject: DelegatedCustodySigningService!
override func setUp() {
subject = DelegatedCustodySigningService()
super.setUp()
}
func testSecp256k1Derivation1() throws {
try runTestSecp256k1Derivation(
data: "fd09c5d898ca107a3cbc535065c66345d929e34a77beb687e8caf4a7a3683098",
privateKey: "0d371300cd074054ef8248f5640a6dcbe60bdd1fad900be94e0d62fd9168caae",
expectedResult: "bae592f9d4bcd845e8929cb753478f00350381dfd0cffa27876ed812564a8cc142ba9afa2f631b757eed4580948650c5fbd16644f294ba9b664fd1d646b3993800"
)
}
func testSecp256k1Derivation2() throws {
try runTestSecp256k1Derivation(
data: "fd09c5d898ca107a3cbc535065c66345d929e34a77beb687e8caf4a7a3683098",
privateKey: "320dc1afd9ffa43b98a541e58f0d464a1d0983921eb8878cab975f3aadc02653",
expectedResult: "79dd15512c741ef7de052587e08d62b3603de6e928e8f3df47145d8f1404880a39d3dd9ee4ebbc84e0e946c0d1b4f3d340570101a98b7f8990addcca73ae96ac00"
)
}
func runTestSecp256k1Derivation(
data: String,
privateKey: String,
expectedResult: String
) throws {
let data = Data(hexValue: data)
let privateKey = Data(hexValue: privateKey)
let signed = subject.sign(
data: data,
privateKey: privateKey,
algorithm: .secp256k1
)
let result = try signed.get()
XCTAssertEqual(result.hex, expectedResult)
}
}
|
lgpl-3.0
|
53bc89f85c1d5563442c086c78cef0b0
| 34.895833 | 160 | 0.72722 | 3.144161 | false | true | false | false |
vamsirajendra/firefox-ios
|
Storage/SQL/BrowserTable.swift
|
2
|
21627
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
let BookmarksFolderTitleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let BookmarksFolderTitleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let BookmarksFolderTitleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let BookmarksFolderTitleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let TableBookmarks = "bookmarks"
let TableBookmarksMirror = "bookmarksMirror" // Added in v9.
let TableBookmarksMirrorStructure = "bookmarksMirrorStructure" // Added in v10.
let TableFavicons = "favicons"
let TableHistory = "history"
let TableDomains = "domains"
let TableVisits = "visits"
let TableFaviconSites = "favicon_sites"
let TableQueuedTabs = "queue"
let ViewWidestFaviconsForSites = "view_favicons_widest"
let ViewHistoryIDsWithWidestFavicons = "view_history_id_favicon"
let ViewIconForURL = "view_icon_for_url"
let IndexHistoryShouldUpload = "idx_history_should_upload"
let IndexVisitsSiteIDDate = "idx_visits_siteID_date" // Removed in v6.
let IndexVisitsSiteIDIsLocalDate = "idx_visits_siteID_is_local_date" // Added in v6.
let IndexBookmarksMirrorStructureParentIdx = "idx_bookmarksMirrorStructure_parent_idx" // Added in v10.
private let AllTables: Args = [
TableDomains,
TableFavicons,
TableFaviconSites,
TableHistory,
TableVisits,
TableBookmarks,
TableBookmarksMirror,
TableBookmarksMirrorStructure,
TableQueuedTabs,
]
private let AllViews: Args = [
ViewHistoryIDsWithWidestFavicons,
ViewWidestFaviconsForSites,
ViewIconForURL,
]
private let AllIndices: Args = [
IndexHistoryShouldUpload,
IndexVisitsSiteIDIsLocalDate,
IndexBookmarksMirrorStructureParentIdx,
]
private let AllTablesIndicesAndViews: Args = AllViews + AllIndices + AllTables
private let log = Logger.syncLogger
/**
* The monolithic class that manages the inter-related history etc. tables.
* We rely on SQLiteHistory having initialized the favicon table first.
*/
public class BrowserTable: Table {
static let DefaultVersion = 10
let version: Int
var name: String { return "BROWSER" }
let sqliteVersion: Int32
let supportsPartialIndices: Bool
public init(version: Int = DefaultVersion) {
self.version = version
let v = sqlite3_libversion_number()
self.sqliteVersion = v
self.supportsPartialIndices = v >= 3008000 // 3.8.0.
let ver = String.fromCString(sqlite3_libversion())!
log.info("SQLite version: \(ver) (\(v)).")
}
func run(db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool {
let err = db.executeChange(sql, withArgs: args)
if err != nil {
log.error("Error running SQL in BrowserTable. \(err?.localizedDescription)")
log.error("SQL was \(sql)")
}
return err == nil
}
// TODO: transaction.
func run(db: SQLiteDBConnection, queries: [(String, Args?)]) -> Bool {
for (sql, args) in queries {
if !run(db, sql: sql, args: args) {
return false
}
}
return true
}
func runValidQueries(db: SQLiteDBConnection, queries: [(String?, Args?)]) -> Bool {
for (sql, args) in queries {
if let sql = sql {
if !run(db, sql: sql, args: args) {
return false
}
}
}
return true
}
func prepopulateRootFolders(db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.Folder.rawValue
let root = BookmarkRoots.RootID
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, BookmarksFolderTitleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, BookmarksFolderTitleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, BookmarksFolderTitleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, BookmarksFolderTitleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString(forVersion version: Int = BrowserTable.DefaultVersion) -> String? {
return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
(version > 5 ? "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " : "") +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func getDomainsTableCreationString(forVersion version: Int = BrowserTable.DefaultVersion) -> String? {
if version <= 5 {
return nil
}
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func getQueueTableCreationString(forVersion version: Int = BrowserTable.DefaultVersion) -> String? {
if version <= 4 {
return nil
}
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
func getBookmarksMirrorTableCreationString(forVersion version: Int = BrowserTable.DefaultVersion) -> String? {
if version < 9 {
return nil
}
// The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry.
// For now we have the simplest possible schema: everything in one.
let sql =
"CREATE TABLE IF NOT EXISTS \(TableBookmarksMirror) " +
// Shared fields.
"( id INTEGER PRIMARY KEY AUTOINCREMENT" +
", guid TEXT NOT NULL UNIQUE" +
", type TINYINT NOT NULL" + // Type enum. TODO: BookmarkNodeType needs to be extended.
// Record/envelope metadata that'll allow us to do merges.
", server_modified INTEGER NOT NULL" + // Milliseconds.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean
", hasDupe TINYINT NOT NULL DEFAULT 0" + // Boolean, 0 (false) if deleted.
", parentid TEXT" + // GUID
", parentName TEXT" +
// Type-specific fields. These should be NOT NULL in many cases, but we're going
// for a sparse schema, so this'll do for now. Enforce these in the application code.
", feedUri TEXT, siteUri TEXT" + // LIVEMARKS
", pos INT" + // SEPARATORS
", title TEXT, description TEXT" + // FOLDERS, BOOKMARKS, QUERIES
", bmkUri TEXT, tags TEXT, keyword TEXT" + // BOOKMARKS, QUERIES
", folderName TEXT, queryId TEXT" + // QUERIES
", CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)" +
", CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)" +
")"
return sql
}
/**
* We need to explicitly store what's provided by the server, because we can't rely on
* referenced child nodes to exist yet!
*/
func getBookmarksMirrorStructureTableCreationString(forVersion version: Int = BrowserTable.DefaultVersion) -> String? {
if version < 10 {
return nil
}
// TODO: index me.
let sql =
"CREATE TABLE IF NOT EXISTS \(TableBookmarksMirrorStructure) " +
"( parent TEXT NOT NULL REFERENCES \(TableBookmarksMirror)(guid) ON DELETE CASCADE" +
", child TEXT NOT NULL" + // Should be the GUID of a child.
", idx INTEGER NOT NULL" + // Should advance from 0.
")"
return sql
}
func create(db: SQLiteDBConnection, version: Int) -> Bool {
let favicons =
"CREATE TABLE IF NOT EXISTS \(TableFavicons) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS \(TableVisits) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"\(TableFavicons).id AS iconID, " +
"\(TableFavicons).url AS iconURL, " +
"\(TableFavicons).date AS iconDate, " +
"\(TableFavicons).type AS iconType, " +
"MAX(\(TableFavicons).width) AS iconWidth " +
"FROM \(TableFaviconSites), \(TableFavicons) WHERE " +
"\(TableFaviconSites).faviconID = \(TableFavicons).id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT \(TableHistory).id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM \(TableHistory) " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " +
"\(TableHistory).id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS \(TableBookmarks) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES \(TableBookmarks)(id) NOT NULL, " +
"faviconID INTEGER REFERENCES \(TableFavicons)(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let bookmarksMirror = getBookmarksMirrorTableCreationString()
let bookmarksMirrorStructure = getBookmarksMirrorStructureTableCreationString()
let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " +
"ON \(TableBookmarksMirrorStructure) (parent, idx)"
let queries: [(String?, Args?)] = [
(getDomainsTableCreationString(forVersion: version), nil),
(getHistoryTableCreationString(forVersion: version), nil),
(favicons, nil),
(visits, nil),
(bookmarks, nil),
(bookmarksMirror, nil),
(bookmarksMirrorStructure, nil),
(indexStructureParentIdx, nil),
(faviconSites, nil),
(indexShouldUpload, nil),
(indexSiteIDDate, nil),
(widestFavicons, nil),
(historyIDsWithIcon, nil),
(iconForURL, nil),
(getQueueTableCreationString(forVersion: version), nil)
]
assert(queries.count == AllTablesIndicesAndViews.count, "Did you forget to add your table, index, or view to the list?")
log.debug("Creating \(queries.count) tables, views, and indices.")
return self.runValidQueries(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool {
if from == to {
log.debug("Skipping update from \(from) to \(to).")
return true
}
if from == 0 {
// This is likely an upgrade from before Bug 1160399.
log.debug("Updating browser tables from zero. Assuming drop and recreate.")
return drop(db) && create(db, version: to)
}
if from > to {
// This is likely an upgrade from before Bug 1160399.
log.debug("Downgrading browser tables. Assuming drop and recreate.")
return drop(db) && create(db, version: to)
}
if from < 4 && to >= 4 {
return drop(db) && create(db, version: to)
}
if from < 5 && to >= 5 {
let queries: [(String?, Args?)] = [(getQueueTableCreationString(forVersion: to), nil)]
if !self.runValidQueries(db, queries: queries) {
return false
}
}
if from < 6 && to >= 6 {
if !self.run(db, queries: [
("DROP INDEX IF EXISTS \(IndexVisitsSiteIDDate)", nil),
("CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) ON \(TableVisits) (siteID, is_local, date)", nil)
]) {
return false
}
}
if from < 7 && to >= 7 {
let queries: [(String?, Args?)] = [
(getDomainsTableCreationString(forVersion: to), nil),
("ALTER TABLE \(TableHistory) ADD COLUMN domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE", nil)
]
if !self.runValidQueries(db, queries: queries) {
return false
}
let urls = db.executeQuery("SELECT DISTINCT url FROM \(TableHistory) WHERE url IS NOT NULL",
factory: { $0["url"] as! String })
if !fillDomainNamesFromCursor(urls, db: db) {
return false
}
}
if from < 8 && to == 8 {
// Nothing to do: we're just shifting the favicon table to be owned by this class.
return true
}
if from < 9 && to >= 9 {
if !self.run(db, sql: getBookmarksMirrorTableCreationString(forVersion: to)!) {
return false
}
}
if from < 10 && to >= 10 {
if !self.run(db, sql: getBookmarksMirrorStructureTableCreationString(forVersion: to)!) {
return false
}
let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " +
"ON \(TableBookmarksMirrorStructure) (parent, idx)"
if !self.run(db, sql: indexStructureParentIdx) {
return false
}
}
return true
}
private func fillDomainNamesFromCursor(cursor: Cursor<String>, db: SQLiteDBConnection) -> Bool {
if cursor.count == 0 {
return true
}
// URL -> hostname, flattened to make args.
var pairs = Args()
pairs.reserveCapacity(cursor.count * 2)
for url in cursor {
if let url = url, host = url.asURL?.normalizedHost() {
pairs.append(url)
pairs.append(host)
}
}
cursor.close()
let tmpTable = "tmp_hostnames"
let table = "CREATE TEMP TABLE \(tmpTable) (url TEXT NOT NULL UNIQUE, domain TEXT NOT NULL, domain_id INT)"
if !self.run(db, sql: table, args: nil) {
log.error("Can't create temporary table. Unable to migrate domain names. Top Sites is likely to be broken.")
return false
}
// Now insert these into the temporary table. Chunk by an even number, for obvious reasons.
let chunks = chunk(pairs, by: BrowserDB.MaxVariableNumber - (BrowserDB.MaxVariableNumber % 2))
for chunk in chunks {
let ins = "INSERT INTO \(tmpTable) (url, domain) VALUES " +
Array<String>(count: chunk.count / 2, repeatedValue: "(?, ?)").joinWithSeparator(", ")
if !self.run(db, sql: ins, args: Array(chunk)) {
log.error("Couldn't insert domains into temporary table. Aborting migration.")
return false
}
}
// Now make those into domains.
let domains = "INSERT OR IGNORE INTO \(TableDomains) (domain) SELECT DISTINCT domain FROM \(tmpTable)"
// … and fill that temporary column.
let domainIDs = "UPDATE \(tmpTable) SET domain_id = (SELECT id FROM \(TableDomains) WHERE \(TableDomains).domain = \(tmpTable).domain)"
// Update the history table from the temporary table.
let updateHistory = "UPDATE \(TableHistory) SET domain_id = (SELECT domain_id FROM \(tmpTable) WHERE \(tmpTable).url = \(TableHistory).url)"
// Clean up.
let dropTemp = "DROP TABLE \(tmpTable)"
// Now run these.
if !self.run(db, queries: [(domains, nil),
(domainIDs, nil),
(updateHistory, nil),
(dropTemp, nil)]) {
log.error("Unable to migrate domains.")
return false
}
return true
}
/**
* The Table mechanism expects to be able to check if a 'table' exists. In our (ab)use
* of Table, that means making sure that any of our tables and views exist.
* We do that by fetching all tables from sqlite_master with matching names, and verifying
* that we get back more than one.
* Note that we don't check for views -- trust to luck.
*/
func exists(db: SQLiteDBConnection) -> Bool {
return db.tablesExist(AllTables)
}
func drop(db: SQLiteDBConnection) -> Bool {
log.debug("Dropping all browser tables.")
let additional: [(String, Args?)] = [
("DROP TABLE IF EXISTS faviconSites", nil) // We renamed it to match naming convention.
]
let queries: [(String, Args?)] = AllViews.map { ("DROP VIEW IF EXISTS \($0!)", nil) } as [(String, Args?)] +
AllIndices.map { ("DROP INDEX IF EXISTS \($0!)", nil) } as [(String, Args?)] +
AllTables.map { ("DROP TABLE IF EXISTS \($0!)", nil) } as [(String, Args?)] +
additional
return self.run(db, queries: queries)
}
}
|
mpl-2.0
|
40517002b8f4cec027e46b11690bacc7
| 40.910853 | 238 | 0.592694 | 4.693944 | false | false | false | false |
spark/photon-tinker-ios
|
Photon-Tinker/Mesh/StepGetNewNetworkPassword.swift
|
1
|
1165
|
//
// Created by Raimundas Sakalauskas on 2019-03-07.
// Copyright (c) 2019 Particle. All rights reserved.
//
import Foundation
class StepGetNewNetworkPassword : Gen3SetupStep {
override func start() {
guard let context = self.context else {
return
}
if (context.newNetworkPassword == nil) {
context.delegate.gen3SetupDidRequestToEnterNewNetworkPassword(self)
} else {
self.stepCompleted()
}
}
func setNewNetworkPassword(password: String) -> Gen3SetupFlowError? {
guard let context = self.context else {
return nil
}
guard Gen3SetupStep.validateNetworkPassword(password) else {
return .PasswordTooShort
}
self.log("set network password with character count: \(password.count)")
context.newNetworkPassword = password
self.stepCompleted()
return nil
}
override func rewindTo(context: Gen3SetupContext) {
super.rewindTo(context: context)
guard let context = self.context else {
return
}
context.newNetworkPassword = nil
}
}
|
apache-2.0
|
ccbaf0dc1a024316c15c3c7009764ca5
| 23.270833 | 80 | 0.621459 | 4.894958 | false | false | false | false |
charmaex/favorite-movies
|
FavoriteMovies/ImdbVC.swift
|
1
|
1325
|
//
// ImdbVC.swift
// FavoriteMovies
//
// Created by Jan Dammshäuser on 18.02.16.
// Copyright © 2016 Jan Dammshäuser. All rights reserved.
//
import UIKit
import WebKit
class ImdbVC: UIViewController {
@IBOutlet weak var webFrame: UIView!
private var _webView: WKWebView!
private var _link: String!
convenience init(link: String) {
self.init(nibName: "ImdbVC", bundle: nil)
_link = link
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
_webView = WKWebView()
webFrame.addSubview(_webView)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
_webView.frame = CGRectMake(0, 0, webFrame.bounds.width, webFrame.bounds.height)
let url = NSURL(string: _link)!
let request = NSURLRequest(URL: url)
_webView.loadRequest(request)
}
@IBAction func doneTapped(sender: UIButton) {
dismissViewControllerAnimated(true, completion: nil)
}
}
|
gpl-3.0
|
827ebd06eb46212c2a41d0367009324c
| 23.036364 | 88 | 0.618003 | 4.436242 | false | false | false | false |
googlearchive/science-journal-ios
|
ScienceJournal/Chart/TimeAxisView.swift
|
1
|
14996
|
/*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
protocol AccessibilityDelegate: class {
/// Inform the delegate adjustable accessibility element did increment its value.
func accessibilityAdjustableViewDidIncrement()
/// Inform the delegate adjustable accessibility element did decrement its value.
func accessibilityAdjustableViewDidDecrement()
}
/// A view that displays a horizontal axis with labels and tick marks corresponding to time values.
/// This corresponds to the Android class ExternalAxisView.
class TimeAxisView: UIScrollView {
// MARK: - Style
/// The style of a TimeAxisView.
enum Style {
/// Used when recording in the observe view.
case observe
/// Used during playback in a trial review.
case review
var height: CGFloat {
switch self {
case .observe: return 41.0
case .review: return 40.0
}
}
}
// MARK: - Constants
weak var accessibilityDelegate: AccessibilityDelegate?
let numberOfTicks = 10
let paddingTop: CGFloat = 8.0
let longTickHeight: CGFloat = 6.0
let shortTickHeight: CGFloat = 3.0
let tickPaddingTop: CGFloat = 2.0
let tickPaddingBottom: CGFloat = 4.0
let tickWidth: CGFloat = 1.0
let topLineWidth: CGFloat = 1.0
let recordingLineWidth: CGFloat = 5.0
let recordingDotRadius: CGFloat = 8.0
let noteDotRadius: CGFloat = 7.0
let noteDotLineWidth: CGFloat = 3.0
// Label size is fixed to avoid the cost of calculating it frequently.
let labelSize = CGSize(width: 50, height: 12)
// MARK: - Properties
var topBackgroundMargin: CGFloat {
switch style {
case .observe: return recordingDotRadius + recordingLineWidth
case .review: return 10
}
}
override var bounds: CGRect {
didSet {
// When the bounds size changes, recalculate the content size and offset based on the visible
// range.
if bounds.size != oldValue.size {
updateContentSizeAndOffset()
}
}
}
/// The display format for time.
let timeFormat = ElapsedTimeFormatter()
/// Timestamps where notes should be displayed.
var noteTimestamps: [Int64] = []
/// The min/max of the entire range of data that can be displayed. This represents the beginning
/// and end of the time axis scroll view.
var dataAxis: ChartAxis<Int64>
/// The currently rendered view axis, used to calculate when a new range should be drawn.
private var renderAxis: ChartAxis<CGFloat> = .zero
/// The min/max of the visible area. This corresponds to the visible bounds of the scroll view.
var visibleAxis: ChartAxis<Int64> {
didSet {
// Need to redraw labels, so reset render axis.
renderAxis = .zero
updateContentSizeAndOffset()
}
}
/// The time that will be labeled as 0:00. All other times are labeled relative to this time.
var zeroTime: DataPoint.Millis = 0
/// The height of the view based on the current style.
var height: CGFloat {
return style.height
}
private var shapeLayers = [CAShapeLayer]()
private var inUseTextLayers = [CATextLayer]()
private var availableTextLayers = [CATextLayer]()
private let style: Style
var recordingStartTime: Int64? {
didSet {
guard style == .observe else { return }
// Hide line if not recording.
if recordingStartTime == nil {
recordingDotLayer.path = nil
recordingLineLayer.path = nil
}
// Force the view to redraw.
renderAxis = .zero
}
}
/// The background, only used in observe style.
private lazy var backgroundLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = UIColor(white: 1, alpha: 0.8).cgColor
self.layer.addSublayer(shapeLayer)
return shapeLayer
}()
/// A thin black line along the top of the axis view, only used in review.
private lazy var topLineLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = self.topLineWidth
shapeLayer.strokeColor = UIColor.black.cgColor
self.layer.addSublayer(shapeLayer)
return shapeLayer
}()
/// A thic red line along the top of the axis view, used in observe style when recording.
private lazy var recordingLineLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = self.recordingLineWidth
shapeLayer.strokeColor = UIColor.red.cgColor
self.layer.addSublayer(shapeLayer)
return shapeLayer
}()
/// A red dot with a white stroke used to show the recording start point.
private lazy var recordingDotLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = self.recordingLineWidth
shapeLayer.strokeColor = UIColor.white.cgColor
shapeLayer.fillColor = UIColor.red.cgColor
self.layer.addSublayer(shapeLayer)
return shapeLayer
}()
// MARK: - Public
init(style: Style, visibleAxis: ChartAxis<Int64>, dataAxis: ChartAxis<Int64>) {
self.style = style
self.visibleAxis = visibleAxis
self.dataAxis = dataAxis
zeroTime = dataAxis.min
super.init(frame: CGRect.zero)
isScrollEnabled = false
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
}
override func accessibilityIncrement() {
accessibilityDelegate?.accessibilityAdjustableViewDidIncrement()
}
override func accessibilityDecrement() {
accessibilityDelegate?.accessibilityAdjustableViewDidDecrement()
}
private override convenience init(frame: CGRect) {
fatalError("init(coder:) is not supported")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not supported")
}
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: style.height)
}
/// Returns a timestamp corresponding to a horizontal view position
///
/// - Parameter viewPosition: The horizontal view position.
/// - Returns: A timestamp.
func timestampForViewPosition(_ viewPosition: CGFloat) -> Int64? {
guard bounds.size.width > 0 else { return nil }
return Int64(viewPosition * CGFloat(visibleAxis.length) / bounds.size.width) + dataAxis.min
}
// MARK: - Private
private func updateContentSizeAndOffset() {
guard visibleAxis.length > 0 else { return }
let contentWidth =
CGFloat(dataAxis.length) * bounds.size.width / CGFloat(visibleAxis.length)
contentSize = CGSize(width: contentWidth, height: bounds.size.height)
guard let offsetX = viewPositionForTime(visibleAxis.min) else { return }
contentOffset = CGPoint(x: offsetX, y: 0)
drawView()
}
private func drawView() {
// Don't do anything if the size of the view is zero. (This happens when the view is first
// created and hasn't been sized yet).
guard bounds.size != .zero else { return }
// Given the current scroll position, determine the desired render range.
let pageBuffer: CGFloat = 1
let pageSize = frame.size
let currentPage = floor(contentOffset.x / pageSize.width)
let firstPage = max(-1, currentPage - pageBuffer)
let lastPage = currentPage + pageBuffer
let startX = firstPage * pageSize.width
let endX = (lastPage + 1) * pageSize.width
let desiredRenderAxis = ChartAxis(min: startX, max: endX)
// Only draw if the desired render axis is different than the current one.
guard desiredRenderAxis != renderAxis else { return }
renderAxis = desiredRenderAxis
// If observe style, draw a background.
if style == .observe {
let bgRect = CGRect(x: startX,
y: topBackgroundMargin,
width: endX - startX,
height: bounds.size.height - topBackgroundMargin)
let backgroundPath = UIBezierPath(rect: bgRect)
backgroundLayer.path = backgroundPath.cgPath
}
// Remove existing layers.
shapeLayers.forEach { $0.removeFromSuperlayer() }
shapeLayers.removeAll()
// Move all existing text layers to available layers in order to reuse them.
availableTextLayers.append(contentsOf: inUseTextLayers)
inUseTextLayers.removeAll()
guard let renderStartTime = timestampForViewPosition(renderAxis.min),
let renderEndTime = timestampForViewPosition(renderAxis.max) else { return }
// Default time between ticks, rounded down to nearest second.
var timeBetweenTicks = visibleAxis.length / Int64(numberOfTicks) / 1000 * 1000
if timeBetweenTicks < 1000 {
// Make sure the minimum time between ticks is half a second.
timeBetweenTicks = 500
}
var tickTime: Int64
var isLabelTick: Bool
// Establish the initial tick time and initial label state.
// When there is no zero time (observing but not recording) tick placement is arbitrary.
// If there is a zero time (recording or reviewing) make ticks relative to zero.
if style == .observe && recordingStartTime == nil {
isLabelTick = true
tickTime = renderStartTime
} else {
// Set first tick relative to the zero time.
let timeFromZero = zeroTime - renderStartTime
let ticksFromZero = timeFromZero / timeBetweenTicks
tickTime = zeroTime - ticksFromZero * timeBetweenTicks
isLabelTick = ticksFromZero % 2 == 0
}
while tickTime < renderEndTime {
guard let tickPosition = viewPositionForTime(tickTime) else { continue }
if isLabelTick {
addLabel(forTime: tickTime, atPosition: tickPosition)
addLongTick(atPosition: tickPosition)
} else {
addShortTick(atPosition: tickPosition)
}
tickTime += timeBetweenTicks
isLabelTick = !isLabelTick
}
// Remove unused layers.
availableTextLayers.forEach { $0.removeFromSuperlayer() }
switch style {
case .review:
let topLinePath = UIBezierPath()
let yPosition = topLineWidth / 2 + topBackgroundMargin
topLinePath.move(to: CGPoint(x: startX, y: yPosition))
topLinePath.addLine(to: CGPoint(x: endX, y: yPosition))
topLineLayer.path = topLinePath.cgPath
case .observe:
guard let recordingStartTime = recordingStartTime,
let recordingStartViewPosition = viewPositionForTime(recordingStartTime) else {
return
}
// Record line.
if recordingStartViewPosition < endX {
let lineStartPosition = max(recordingStartViewPosition, startX)
let recordLinePath = UIBezierPath()
let yPosition = topBackgroundMargin - recordingLineWidth / 2
recordLinePath.move(to: CGPoint(x: lineStartPosition, y: yPosition))
recordLinePath.addLine(to: CGPoint(x: endX, y: yPosition))
recordingLineLayer.path = recordLinePath.cgPath
}
// Record dot.
if startX...endX ~= recordingStartViewPosition {
let recordDotFrame = CGRect(x: recordingStartViewPosition - recordingDotRadius,
y: recordingLineWidth / 2,
width: recordingDotRadius * 2,
height: recordingDotRadius * 2)
let recordDotPath = UIBezierPath(ovalIn: recordDotFrame)
recordingDotLayer.path = recordDotPath.cgPath
}
// Note dots.
for timestamp in noteTimestamps {
guard renderStartTime...renderEndTime ~= timestamp,
let notePosition = viewPositionForTime(timestamp) else { continue }
addNoteDot(atPosition: notePosition)
}
}
}
private func addNoteDot(atPosition position: CGFloat) {
let noteDotFrame = CGRect(x: position - noteDotRadius,
y: topBackgroundMargin - recordingLineWidth / 2 - noteDotRadius,
width: noteDotRadius * 2,
height: noteDotRadius * 2)
let noteDotLayer = CAShapeLayer()
noteDotLayer.lineWidth = noteDotLineWidth
noteDotLayer.strokeColor = UIColor.red.cgColor
noteDotLayer.fillColor = UIColor.yellow.cgColor
noteDotLayer.path = UIBezierPath(ovalIn: noteDotFrame).cgPath
shapeLayers.append(noteDotLayer)
layer.addSublayer(noteDotLayer)
}
private func addLabel(forTime time: DataPoint.Millis, atPosition labelPosition: CGFloat) {
var textLayer: CATextLayer
// Existing text layers are reused as creating new layers is costly.
if !availableTextLayers.isEmpty {
textLayer = availableTextLayers.remove(at: 0)
} else {
textLayer = CATextLayer()
// Disable implicit animations.
textLayer.disableImplicitAnimations()
textLayer.foregroundColor = UIColor.black.cgColor
textLayer.contentsScale = UIScreen.main.scale
textLayer.fontSize = 10
textLayer.alignmentMode = .center
}
textLayer.string = timeFormat.string(fromTimestamp: time - zeroTime)
let yPosition = topBackgroundMargin + tickPaddingTop + longTickHeight + tickPaddingBottom
textLayer.frame = CGRect(x: floor(labelPosition - labelSize.width / 2),
y: yPosition,
width: labelSize.width,
height: labelSize.height)
layer.addSublayer(textLayer)
inUseTextLayers.append(textLayer)
}
private func addLongTick(atPosition position: CGFloat) {
addTick(atPosition: position, height: longTickHeight)
}
private func addShortTick(atPosition position: CGFloat) {
addTick(atPosition: position, height: shortTickHeight)
}
private func addTick(atPosition position: CGFloat, height: CGFloat) {
let newTickLayer = tickLayer(withPath: tickPathForPosition(position, height: height))
layer.addSublayer(newTickLayer)
shapeLayers.append(newTickLayer)
}
private func tickPathForPosition(_ position: CGFloat, height: CGFloat) -> UIBezierPath {
let path = UIBezierPath()
let topPadding = tickPaddingTop + topBackgroundMargin
path.move(to: CGPoint(x: position, y: topPadding))
path.addLine(to: CGPoint(x: position, y: topPadding + height))
return path
}
private func tickLayer(withPath path: UIBezierPath) -> CAShapeLayer {
let layer = CAShapeLayer()
layer.lineWidth = tickWidth
layer.strokeColor = UIColor.black.cgColor
layer.path = path.cgPath
return layer
}
private func viewPositionForTime(_ time: DataPoint.Millis) -> CGFloat? {
guard visibleAxis.length > 0 else { return nil }
return bounds.size.width / CGFloat(visibleAxis.length) * CGFloat(time - dataAxis.min)
}
}
|
apache-2.0
|
cbcc9391c95841e954013217a7441951
| 34.284706 | 99 | 0.692518 | 4.61984 | false | false | false | false |
wikimedia/apps-ios-wikipedia
|
Wikipedia/Code/InsertMediaViewController.swift
|
1
|
16215
|
protocol InsertMediaViewControllerDelegate: AnyObject {
func insertMediaViewController(_ insertMediaViewController: InsertMediaViewController, didTapCloseButton button: UIBarButtonItem)
func insertMediaViewController(_ insertMediaViewController: InsertMediaViewController, didPrepareWikitextToInsert wikitext: String)
}
final class InsertMediaViewController: ViewController {
private let selectedImageViewController = InsertMediaSelectedImageViewController()
private let searchViewController: InsertMediaSearchViewController
private let searchResultsCollectionViewController = InsertMediaSearchResultsCollectionViewController()
weak var delegate: InsertMediaViewControllerDelegate?
init(articleTitle: String?, siteURL: URL?) {
searchViewController = InsertMediaSearchViewController(articleTitle: articleTitle, siteURL: siteURL)
searchResultsCollectionViewController.delegate = selectedImageViewController
super.init()
selectedImageViewController.delegate = self
searchViewController.progressController = FakeProgressController(progress: navigationBar, delegate: navigationBar)
searchViewController.delegate = self
searchViewController.searchBarDelegate = self
searchResultsCollectionViewController.scrollDelegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var closeButton: UIBarButtonItem = {
let closeButton = UIBarButtonItem.wmf_buttonType(.X, target: self, action: #selector(delegateCloseButtonTap(_:)))
closeButton.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
return closeButton
}()
private lazy var nextButton: UIBarButtonItem = {
let nextButton = UIBarButtonItem(title: CommonStrings.nextTitle, style: .done, target: self, action: #selector(goToMediaSettings(_:)))
nextButton.isEnabled = false
return nextButton
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.isNavigationBarHidden = true
title = CommonStrings.insertMediaTitle
navigationItem.leftBarButtonItem = closeButton
navigationItem.rightBarButtonItem = nextButton
navigationItem.backBarButtonItem = UIBarButtonItem(title: CommonStrings.accessibilityBackTitle, style: .plain, target: nil, action: nil)
navigationBar.displayType = .modal
navigationBar.isBarHidingEnabled = false
navigationBar.isUnderBarViewHidingEnabled = true
navigationBar.isExtendedViewHidingEnabled = true
navigationBar.isTopSpacingHidingEnabled = false
addChild(selectedImageViewController)
navigationBar.addUnderNavigationBarView(selectedImageViewController.view)
selectedImageViewController.didMove(toParent: self)
addChild(searchViewController)
navigationBar.addExtendedNavigationBarView(searchViewController.view)
searchViewController.didMove(toParent: self)
wmf_add(childController: searchResultsCollectionViewController, andConstrainToEdgesOfContainerView: view)
additionalSafeAreaInsets = searchResultsCollectionViewController.additionalSafeAreaInsets
scrollView = searchResultsCollectionViewController.collectionView
}
private var selectedImageViewHeightConstraint: NSLayoutConstraint?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if selectedImageViewHeightConstraint == nil {
selectedImageViewHeightConstraint = selectedImageViewController.view.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3)
selectedImageViewHeightConstraint?.isActive = true
}
}
private var isDisappearing = false
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isDisappearing = true
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
isDisappearing = false
}
private var isTransitioningToNewCollection = false
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
isTransitioningToNewCollection = true
super.willTransition(to: newCollection, with: coordinator)
coordinator.animate(alongsideTransition: { _ in
//
}) { _ in
self.isTransitioningToNewCollection = false
}
}
@objc private func goToMediaSettings(_ sender: UIBarButtonItem) {
guard
let navigationController = navigationController,
let selectedSearchResult = selectedImageViewController.searchResult,
let image = selectedImageViewController.image ?? searchResultsCollectionViewController.selectedImage
else {
assertionFailure("Selected image and search result should be set by now")
return
}
let settingsViewController = InsertMediaSettingsViewController(image: image, searchResult: selectedSearchResult)
settingsViewController.title = WMFLocalizedString("insert-media-media-settings-title", value: "Media settings", comment: "Title for media settings view")
let insertButton = UIBarButtonItem(title: WMFLocalizedString("insert-action-title", value: "Insert", comment: "Title for insert action"), style: .done, target: self, action: #selector(insertMedia(_:)))
insertButton.tintColor = theme.colors.link
settingsViewController.navigationItem.rightBarButtonItem = insertButton
settingsViewController.apply(theme: theme)
navigationController.pushViewController(settingsViewController, animated: true)
}
@objc private func insertMedia(_ sender: UIBarButtonItem) {
guard let mediaSettingsTableViewController = navigationController?.topViewController as? InsertMediaSettingsViewController else {
assertionFailure()
return
}
let searchResult = mediaSettingsTableViewController.searchResult
let wikitext: String
switch mediaSettingsTableViewController.settings {
case nil:
wikitext = "[[\(searchResult.fileTitle)]]"
case let mediaSettings?:
switch (mediaSettings.caption, mediaSettings.alternativeText) {
case (let caption?, let alternativeText?):
wikitext = """
[[\(searchResult.fileTitle) | \(mediaSettings.advanced.imageType.rawValue) | \(mediaSettings.advanced.imageSize.rawValue) | \(mediaSettings.advanced.imagePosition.rawValue) | alt= \(alternativeText) |
\(caption)]]
"""
case (let caption?, nil):
wikitext = """
[[\(searchResult.fileTitle) | \(mediaSettings.advanced.imageType.rawValue) | \(mediaSettings.advanced.imageSize.rawValue) | \(mediaSettings.advanced.imagePosition.rawValue) | \(caption)]]
"""
case (nil, let alternativeText?):
wikitext = """
[[\(searchResult.fileTitle) | \(mediaSettings.advanced.imageType.rawValue) | \(mediaSettings.advanced.imageSize.rawValue) | \(mediaSettings.advanced.imagePosition.rawValue) | alt= \(alternativeText)]]
"""
default:
wikitext = """
[[\(searchResult.fileTitle) | \(mediaSettings.advanced.imageType.rawValue) | \(mediaSettings.advanced.imageSize.rawValue) | \(mediaSettings.advanced.imagePosition.rawValue)]]
"""
}
}
delegate?.insertMediaViewController(self, didPrepareWikitextToInsert: wikitext)
}
@objc private func delegateCloseButtonTap(_ sender: UIBarButtonItem) {
delegate?.insertMediaViewController(self, didTapCloseButton: sender)
}
override func apply(theme: Theme) {
super.apply(theme: theme)
selectedImageViewController.apply(theme: theme)
searchViewController.apply(theme: theme)
searchResultsCollectionViewController.apply(theme: theme)
closeButton.tintColor = theme.colors.primaryText
nextButton.tintColor = theme.colors.link
}
override func scrollViewInsetsDidChange() {
super.scrollViewInsetsDidChange()
searchResultsCollectionViewController.scrollViewInsetsDidChange()
}
override func keyboardDidChangeFrame(from oldKeyboardFrame: CGRect?, newKeyboardFrame: CGRect?) {
guard !isAnimatingSearchBarState else {
return
}
super.keyboardDidChangeFrame(from: oldKeyboardFrame, newKeyboardFrame: newKeyboardFrame)
}
override func accessibilityPerformEscape() -> Bool {
delegate?.insertMediaViewController(self, didTapCloseButton: closeButton)
return true
}
var isAnimatingSearchBarState: Bool = false
func focusSearch(_ focus: Bool, animated: Bool = true, additionalAnimations: (() -> Void)? = nil) {
useNavigationBarVisibleHeightForScrollViewInsets = focus
navigationBar.isAdjustingHidingFromContentInsetChangesEnabled = true
let completion = { (finished: Bool) in
self.isAnimatingSearchBarState = false
self.useNavigationBarVisibleHeightForScrollViewInsets = focus
}
let animations = {
let underBarViewPercentHidden: CGFloat
let extendedViewPercentHidden: CGFloat
if let scrollView = self.scrollView, scrollView.wmf_isAtTop, !focus {
underBarViewPercentHidden = 0
extendedViewPercentHidden = 0
} else {
underBarViewPercentHidden = 1
extendedViewPercentHidden = focus ? 0 : 1
}
self.navigationBar.setNavigationBarPercentHidden(0, underBarViewPercentHidden: underBarViewPercentHidden, extendedViewPercentHidden: extendedViewPercentHidden, topSpacingPercentHidden: 0, animated: false)
self.searchViewController.searchBar.setShowsCancelButton(focus, animated: animated)
additionalAnimations?()
self.view.layoutIfNeeded()
self.updateScrollViewInsets(preserveAnimation: true)
}
guard animated else {
animations()
completion(true)
return
}
isAnimatingSearchBarState = true
self.view.layoutIfNeeded()
UIView.animate(withDuration: 0.3, animations: animations, completion: completion)
}
}
extension InsertMediaViewController: InsertMediaSearchViewControllerDelegate {
func insertMediaSearchViewController(_ insertMediaSearchViewController: InsertMediaSearchViewController, didFind searchResults: [InsertMediaSearchResult]) {
searchResultsCollectionViewController.emptyViewType = .noSearchResults
searchResultsCollectionViewController.searchResults = searchResults
}
func insertMediaSearchViewController(_ insertMediaSearchViewController: InsertMediaSearchViewController, didFind imageInfo: MWKImageInfo, for searchResult: InsertMediaSearchResult, at index: Int) {
searchResultsCollectionViewController.setImageInfo(imageInfo, for: searchResult, at: index)
}
func insertMediaSearchViewController(_ insertMediaSearchViewController: InsertMediaSearchViewController, didFailWithError error: Error) {
let emptyViewType: WMFEmptyViewType
let nserror = error as NSError
if nserror.wmf_isNetworkConnectionError() {
emptyViewType = .noInternetConnection
} else if nserror.domain == NSURLErrorDomain, nserror.code == NSURLErrorCancelled {
emptyViewType = .none
} else {
emptyViewType = .noSearchResults
}
searchResultsCollectionViewController.emptyViewType = emptyViewType
searchResultsCollectionViewController.searchResults = []
}
}
extension InsertMediaViewController: InsertMediaSelectedImageViewControllerDelegate {
func insertMediaSelectedImageViewController(_ insertMediaSelectedImageViewController: InsertMediaSelectedImageViewController, willSetSelectedImageFrom searchResult: InsertMediaSearchResult) {
nextButton.isEnabled = false
}
func insertMediaSelectedImageViewController(_ insertMediaSelectedImageViewController: InsertMediaSelectedImageViewController, didSetSelectedImage selectedImage: UIImage?, from searchResult: InsertMediaSearchResult) {
nextButton.isEnabled = true
}
}
extension InsertMediaViewController: InsertMediaSearchResultsCollectionViewControllerScrollDelegate {
func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewDidScroll scrollView: UIScrollView) {
guard !isAnimatingSearchBarState else {
return
}
scrollViewDidScroll(scrollView)
}
func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewWillBeginDragging scrollView: UIScrollView) {
scrollViewWillBeginDragging(scrollView)
}
func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewWillEndDragging scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
scrollViewWillEndDragging(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset)
}
func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewDidEndDecelerating scrollView: UIScrollView) {
scrollViewDidEndDecelerating(scrollView)
}
func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewDidEndScrollingAnimation scrollView: UIScrollView) {
scrollViewDidEndScrollingAnimation(scrollView)
}
func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewShouldScrollToTop scrollView: UIScrollView) -> Bool {
return scrollViewShouldScrollToTop(scrollView)
}
func insertMediaSearchResultsCollectionViewController(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, scrollViewDidScrollToTop scrollView: UIScrollView) {
scrollViewDidScrollToTop(scrollView)
}
}
extension InsertMediaViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchViewController.search(for: searchText)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
unfocusSearch {
searchBar.endEditing(true)
}
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
navigationBar.isUnderBarViewHidingEnabled = false
navigationBar.isExtendedViewHidingEnabled = false
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
guard !isAnimatingSearchBarState else {
return
}
unfocusSearch {
searchBar.endEditing(true)
searchBar.text = nil
}
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
navigationBar.isUnderBarViewHidingEnabled = true
navigationBar.isExtendedViewHidingEnabled = true
}
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
guard !isAnimatingSearchBarState else {
return false
}
focusSearch(true)
return true
}
private func unfocusSearch(additionalAnimations: (() -> Void)? = nil) {
navigationBar.isUnderBarViewHidingEnabled = true
navigationBar.isExtendedViewHidingEnabled = true
focusSearch(false, additionalAnimations: additionalAnimations)
}
}
|
mit
|
4e34c6a5d86126ca1d6f4cb8da4e5c7e
| 47.840361 | 297 | 0.736602 | 6.519903 | false | false | false | false |
RobotsAndPencils/Scythe
|
Dependencies/HarvestKit-Swift/HarvestKit-Shared/AccountController.swift
|
1
|
2206
|
//
// AccountController.swift
// HarvestKit
//
// Created by Matthew Cheetham on 16/01/2016.
// Copyright © 2016 Matt Cheetham. All rights reserved.
//
import Foundation
#if os(iOS)
import ThunderRequest
#elseif os(tvOS)
import ThunderRequestTV
#elseif os (OSX)
import ThunderRequestMac
#endif
/**
Handles loading information about the currently authenticated user
*/
public final class AccountController {
/**
The request controller used to load account information. This is shared with other controllers
*/
let requestController: TSCRequestController
internal init(requestController: TSCRequestController) {
self.requestController = requestController
}
/**
Retrieves a user and a company object for the currently authenticated user.
- parameter completionHandler: The completion handler to call passing a company and user object if available. This may also be passed an error object where appropriate
*/
public func getAccountInformation(_ completionHandler: @escaping (_ currentUser: User?, _ currentCompany: Company?, _ requestError: Error?) -> ()) {
requestController.get("account/who_am_i") { (response: TSCRequestResponse?, requestError: Error?) -> Void in
if let error = requestError {
completionHandler(nil, nil, error)
return;
}
guard let responseDictionary = response?.dictionary as? [String: AnyObject] else {
completionHandler(nil, nil, nil)
return;
}
var responseCompany: Company?
var responseUser: User?
if let companyDictionary = responseDictionary["company"] as? [String: AnyObject] {
responseCompany = Company(dictionary: companyDictionary)
}
if let _ = responseDictionary["user"] as? [String: AnyObject] {
responseUser = User(dictionary: responseDictionary)
}
completionHandler(responseUser, responseCompany, nil)
}
}
}
|
mit
|
f221622d5f2435ec793c33f22ad5e694
| 30.056338 | 171 | 0.617234 | 5.378049 | false | false | false | false |
nerdyc/Squeal
|
Tests/Migrations/TableHelpers.swift
|
1
|
5057
|
import Nimble
import Squeal
// =================================================================================================
// MARK:- Column Matchers
func haveColumns(_ expectedColumnNames:String...) -> Predicate<Table> {
return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
guard let table = try actualExpression.evaluate() else {
return false
}
failureMessage.expected = "expected \(table.name) table"
failureMessage.actualValue = table.columnNames.description
failureMessage.postfixMessage = "have columns <\(expectedColumnNames)>"
return table.columnNames == expectedColumnNames
}
}
func haveColumns(_ expectedColumnNames:String...) -> Predicate<TableInfo> {
return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
guard let table = try actualExpression.evaluate() else {
return false
}
failureMessage.expected = "expected \(table.name) table"
failureMessage.actualValue = table.columnNames.description
failureMessage.postfixMessage = "have columns <\(expectedColumnNames)>"
return table.columnNames == expectedColumnNames
}
}
// =================================================================================================
// MARK:- Table Matchers
func haveTables(_ expectedTableNames:String...) -> Predicate<Database> {
return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
guard let db = try actualExpression.evaluate() else {
return false
}
failureMessage.expected = "expected database"
failureMessage.actualValue = "\(db.schema.tableNames)"
failureMessage.postfixMessage = "have tables <\(expectedTableNames)>"
return db.schema.tableNames == expectedTableNames
}
}
func haveTables(_ expectedTableNames:String...) -> Predicate<Version> {
return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
guard let version = try actualExpression.evaluate() else {
return false
}
failureMessage.expected = "expected schema"
failureMessage.actualValue = "\(version.tableNames)"
failureMessage.postfixMessage = "have tables <\(expectedTableNames)>"
return version.tableNames == expectedTableNames
}
}
// =================================================================================================
// MARK:- Index Matchers
func haveIndex(_ name:String) -> Predicate<Database> {
return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
guard let db = try actualExpression.evaluate() else {
return false
}
let schema = db.schema
failureMessage.expected = "expected database"
failureMessage.actualValue = "\(db.schema.indexNames)"
failureMessage.postfixMessage = "have index <\(name)>"
return schema.indexNames.contains(name)
}
}
func haveIndex(_ name:String) -> Predicate<Version> {
return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
guard let version = try actualExpression.evaluate() else {
return false
}
failureMessage.expected = "expected database"
failureMessage.actualValue = "\(version.indexNames)"
failureMessage.postfixMessage = "have index <\(name)>"
return version.indexNames.contains(name)
}
}
func haveIndex(_ name:String, on tableName:String, columns:[String]) -> Predicate<Database> {
return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
guard let db = try actualExpression.evaluate() else {
return false
}
let schema = db.schema
guard schema.indexNames.contains(name) else {
failureMessage.expected = "expected database"
failureMessage.actualValue = "\(schema.indexNames)"
failureMessage.postfixMessage = "have index <\(name)>"
return false
}
guard let tableInfo = try db.tableInfoForTableNamed(tableName) else {
failureMessage.expected = "expected database"
failureMessage.actualValue = "\(schema.tableNames)"
failureMessage.postfixMessage = "have table <\(tableName)>"
return false
}
guard let indexInfo = tableInfo.indexNamed(name) else {
failureMessage.expected = "expected \(tableName) table"
failureMessage.actualValue = "\(tableInfo.indexNames)"
failureMessage.postfixMessage = "have index <\(name)>"
return false
}
failureMessage.expected = "expected \(name) index"
failureMessage.actualValue = "\(indexInfo.columnNames)"
failureMessage.postfixMessage = "have columns <\(columns)>"
return indexInfo.columnNames == columns
}
}
|
mit
|
109e1954261117bc3dfff1307fbcd978
| 37.603053 | 100 | 0.613012 | 5.80597 | false | false | false | false |
NoryCao/zhuishushenqi
|
zhuishushenqi/RightSide/Topic/Controllers/ThemeTopic/QSThemeTopicRouter.swift
|
1
|
1403
|
//
// QSThemeTopicRouter.swift
// zhuishushenqi
//
// Created Nory Cao on 2017/4/13.
// Copyright © 2017年 QS. All rights reserved.
//
// Template generated by Juanpe Catalán @JuanpeCMiOS
//
import UIKit
class QSThemeTopicRouter: QSThemeTopicWireframeProtocol {
weak var viewController: UIViewController?
static func createModule() -> UIViewController {
// Change to get view from storyboard if not using progammatic UI
let view = QSThemeTopicViewController(nibName: nil, bundle: nil)
let interactor = QSThemeTopicInteractor()
let router = QSThemeTopicRouter()
let presenter = QSThemeTopicPresenter(interface: view, interactor: interactor, router: router)
view.presenter = presenter
interactor.output = presenter
router.viewController = view
return view
}
func presentDetail(indexPath:IndexPath,models:[ThemeTopicModel]){
let model = models[indexPath.row]
viewController?.navigationController?.pushViewController(QSTopicDetailRouter.createModule(id: model._id), animated: true)
}
func presentReading(model:[ResourceModel],booDetail:BookDetail){
let viewController = ZSReaderViewController()
viewController.viewModel.book = booDetail
self.viewController?.present(viewController, animated: true, completion: nil)
}
}
|
mit
|
61e4254f92e1cc277c68825311304366
| 33.121951 | 129 | 0.699071 | 4.710438 | false | false | false | false |
anilkumarbp/ringcentral-swiftv2.0
|
Demo/Pods/ringcentral/src/src/Core/Util.swift
|
1
|
1545
|
//
// Util.swift
// src
//
// Created by Anil Kumar BP on 1/21/16.
// Copyright © 2016 Anil Kumar BP. All rights reserved.
//
import Foundation
import SwiftyJSON
public class Util {
/// func jsonToString()
///
/// @param: json Json Object
/// @response String
static func jsonToString(json: [String: AnyObject]) -> String {
let resultJSON = JSON(json)
let result = resultJSON.rawString()!
// var result = "{"
// var delimiter = ""
// for key in json.keys {
// result += delimiter + "\"" + key + "\":"
// let item: AnyObject? = json[key]
// if let check = item as? String {
// result += "\"" + check + "\""
// } else {
// if let check = item as? [String: AnyObject] {
// result += jsonToString(check)
// } else if let check = item as? [AnyObject] {
// result += "["
// delimiter = ""
// for item in check {
// result += "\n"
// result += delimiter + "\""
// result += item.description + "\""
// delimiter = ","
// }
// result += "]"
// } else {
// result += item!.description
// }
// }
// delimiter = ","
// }
// result = result + "}"
return result
}
}
|
mit
|
563e1fccf4899219dc2ba1d3a5c6d1df
| 28.132075 | 67 | 0.398316 | 4.51462 | false | false | false | false |
mbernson/HomeControl.iOS
|
Pods/Promissum/src/Promissum/Delay+Promise.swift
|
1
|
1879
|
//
// Delay.swift
// Promissum
//
// Created by Tom Lokhorst on 2015-01-12.
// Copyright (c) 2015 Tom Lokhorst. All rights reserved.
//
import Foundation
/// Wrapper around `dispatch_after`, with a seconds parameter.
public func delay(_ seconds: TimeInterval, queue: DispatchQueue! = DispatchQueue.main, execute: @escaping () -> Void) {
let when = DispatchTime.now() + seconds
queue.asyncAfter(deadline: when, execute: execute)
}
/// Create a Promise that resolves with the specified value after the specified number of seconds.
public func delayPromise<Value, Error>(_ seconds: TimeInterval, value: Value, queue: DispatchQueue! = DispatchQueue.main) -> Promise<Value, Error> {
let source = PromiseSource<Value, Error>()
delay(seconds, queue: queue) {
source.resolve(value)
}
return source.promise
}
/// Create a Promise that rejects with the specified error after the specified number of seconds.
public func delayErrorPromise<Value, Error>(_ seconds: TimeInterval, error: Error, queue: DispatchQueue! = DispatchQueue.main) -> Promise<Value, Error> {
let source = PromiseSource<Value, Error>()
delay(seconds, queue: queue) {
source.reject(error)
}
return source.promise
}
/// Create a Promise that resolves after the specified number of seconds.
public func delayPromise<Error>(_ seconds: TimeInterval, queue: DispatchQueue! = DispatchQueue.main) -> Promise<Void, Error> {
return delayPromise(seconds, value: (), queue: queue)
}
extension Promise {
/// Return a Promise with the resolve or reject delayed by the specified number of seconds.
public func delay(_ seconds: TimeInterval) -> Promise<Value, Error> {
return self
.flatMap { value in
return delayPromise(seconds).map { value }
}
.flatMapError { error in
return delayPromise(seconds).flatMap { Promise(error: error) }
}
}
}
|
mit
|
8bf6fd694b7ab496f7a6ed9144c53d2a
| 31.964912 | 153 | 0.713145 | 4.194196 | false | false | false | false |
ohadh123/MuscleUp-
|
Pods/LionheartExtensions/Pod/Classes/Core/Int+LionheartExtensions.swift
|
1
|
2194
|
//
// Copyright 2016 Lionheart Software LLC
//
// 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 UIKit
public extension Int {
/**
Scale a value proportionally to the current screen width. Useful for making designed sizes look proportionally similar on all devices.
For instance, let's say a certain button was meant to take up 30px of an iPhone 6s screen, but you'd like the width to scale proportionally to an iPhone 5s.
```
>>> 30.scaledToDeviceWidth(baseWidth: 375)
25.6
```
- parameter baseWidth: The base width for the provided value.
- returns: A `Float` that represents the proportionally sized value.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- date: February 17, 2016
*/
func scaledToDeviceWidth(_ baseWidth: CGFloat) -> CGFloat {
let screen = UIScreen.main
return (screen.bounds.width / baseWidth) * CGFloat(self)
}
func toRGBA(_ r: inout CGFloat!, _ g: inout CGFloat!, _ b: inout CGFloat!, _ a: inout CGFloat!) {
if self > 0xFFFFFF {
r = CGFloat((self>>24) & 0xFF) / 0xFF
g = CGFloat((self>>16) & 0xFF) / 0xFF
b = CGFloat((self>>8) & 0xFF) / 0xFF
a = CGFloat(self & 0xFF) / 0xFF
} else if self > 0xFFF {
r = CGFloat((self>>16) & 0xFF) / 0xFF
g = CGFloat((self>>8) & 0xFF) / 0xFF
b = CGFloat(self & 0xFF) / 0xFF
a = 1
} else {
r = CGFloat((self>>8) & 0xF) / 0xF
g = CGFloat((self>>4) & 0xF) / 0xF
b = CGFloat(self & 0xF) / 0xF
a = 1
}
}
}
|
apache-2.0
|
5d2a9dfc1dda4e9ad7b822efbd194eb1
| 35.55 | 161 | 0.610123 | 3.902135 | false | false | false | false |
bphun/Calculator
|
Calculator/AppDelegate.swift
|
1
|
2770
|
//
// AppDelegate.swift
// Calculator
//
// Created by Brandon Phan on 7/23/16.
// Copyright © 2016 Brandon Phan. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
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 persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "CoreDataModel")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
mit
|
dfd102043221cba3cae59a9164d695d9
| 36.418919 | 187 | 0.734922 | 4.815652 | false | false | false | false |
debugsquad/nubecero
|
nubecero/Controller/Home/CHomeUpload.swift
|
1
|
11602
|
import UIKit
import Photos
class CHomeUpload:CController, CPhotosAlbumSelectionDelegate
{
let model:MHomeUpload
weak var viewBar:VHomeUploadBar?
weak var album:MPhotosItem?
private weak var viewUpload:VHomeUpload!
private let kBarWidth:CGFloat = 150
override init()
{
album = MPhotos.sharedInstance.defaultAlbum
model = MHomeUpload()
super.init()
}
required init?(coder:NSCoder)
{
fatalError()
}
override func loadView()
{
let viewUpload:VHomeUpload = VHomeUpload(controller:self)
self.viewUpload = viewUpload
view = viewUpload
}
override func viewDidLoad()
{
super.viewDidLoad()
title = NSLocalizedString("CHomeUpload_title", comment:"")
switch PHPhotoLibrary.authorizationStatus()
{
case PHAuthorizationStatus.denied,
PHAuthorizationStatus.restricted:
authDenied()
break
case PHAuthorizationStatus.notDetermined:
PHPhotoLibrary.requestAuthorization()
{ [weak self] (status:PHAuthorizationStatus) in
if status == PHAuthorizationStatus.authorized
{
self?.authorized()
}
else
{
self?.authDenied()
}
}
break
case PHAuthorizationStatus.authorized:
authorized()
break
}
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidAppear(animated)
loadBar()
}
override func viewWillDisappear(_ animated:Bool)
{
super.viewWillDisappear(animated)
viewBar?.removeFromSuperview()
}
//MARK: private
private func loadBar()
{
self.viewBar?.removeFromSuperview()
let mainBar:VBar = parentController.viewParent.bar
let viewBar:VHomeUploadBar = VHomeUploadBar(controller:self)
self.viewBar = viewBar
mainBar.addSubview(viewBar)
let views:[String:UIView] = [
"viewBar":viewBar]
let metrics:[String:CGFloat] = [
"barWidth":kBarWidth]
mainBar.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:[viewBar(barWidth)]-0-|",
options:[],
metrics:metrics,
views:views))
mainBar.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[viewBar]-0-|",
options:[],
metrics:metrics,
views:views))
viewUpload.updateBar()
}
private func showError()
{
DispatchQueue.main.async
{ [weak self] in
self?.viewUpload.showError()
}
}
private func imagesLoaded()
{
DispatchQueue.main.async
{ [weak self] in
self?.viewUpload.imagesLoaded()
}
}
private func authDenied()
{
let errorMessage:String = NSLocalizedString("CHomeUpload_authDenied", comment:"")
VAlert.message(message:errorMessage)
showError()
}
private func errorLoadingCameraRoll()
{
let errorMessage:String = NSLocalizedString("CHomeUpload_noCameraRoll", comment:"")
VAlert.message(message:errorMessage)
showError()
}
private func authorized()
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.loadCameraRoll()
}
}
private func loadCameraRoll()
{
model.items = []
let collectionResult:PHFetchResult = PHAssetCollection.fetchAssetCollections(
with:PHAssetCollectionType.smartAlbum,
subtype:PHAssetCollectionSubtype.smartAlbumUserLibrary,
options:nil)
guard
let cameraRoll:PHAssetCollection = collectionResult.firstObject
else
{
errorLoadingCameraRoll()
return
}
let fetchOptions:PHFetchOptions = PHFetchOptions()
let sortNewest:NSSortDescriptor = NSSortDescriptor(
key:"creationDate",
ascending:false)
let predicateImages:NSPredicate = NSPredicate(
format:"mediaType = %d",
PHAssetMediaType.image.rawValue)
fetchOptions.sortDescriptors = [sortNewest]
fetchOptions.predicate = predicateImages
let assetsResult:PHFetchResult = PHAsset.fetchAssets(
in:cameraRoll,
options:fetchOptions)
let countAssets:Int = assetsResult.count
for indexAsset:Int in 0 ..< countAssets
{
let asset:PHAsset = assetsResult[indexAsset]
let uploadItem:MHomeUploadItem = MHomeUploadItem(asset:asset)
model.items.append(uploadItem)
}
imagesLoaded()
}
private func removePicturesAlert()
{
let alert:UIAlertController = UIAlertController(
title:
NSLocalizedString("CHomeUpload_uploadedTitle", comment:""),
message:nil,
preferredStyle:UIAlertControllerStyle.actionSheet)
let actionDontRemove:UIAlertAction = UIAlertAction(
title:
NSLocalizedString("CHomeUpload_uploadedDontRemove", comment:""),
style:
UIAlertActionStyle.cancel)
let actionRemove:UIAlertAction = UIAlertAction(
title:
NSLocalizedString("CHomeUpload_uploadedRemove", comment:""),
style:
UIAlertActionStyle.destructive)
{ (action:UIAlertAction) in
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.performRemovePictures()
}
}
alert.addAction(actionRemove)
alert.addAction(actionDontRemove)
present(alert, animated:true, completion:nil)
}
private func performRemovePictures()
{
var deletableAssets:[PHAsset] = []
for item:MHomeUploadItem in model.items
{
if item.status.finished
{
deletableAssets.append(item.asset)
}
else
{
guard
let _:MHomeUploadItemStatusClouded = item.status as? MHomeUploadItemStatusClouded
else
{
continue
}
deletableAssets.append(item.asset)
}
}
let deletableEnumeration:NSFastEnumeration = deletableAssets as NSFastEnumeration
PHPhotoLibrary.shared().performChanges(
{
PHAssetChangeRequest.deleteAssets(deletableEnumeration)
})
{ [weak self] (done:Bool, error:Error?) in
if let errorStrong:Error = error
{
VAlert.message(message:errorStrong.localizedDescription)
}
else
{
self?.loadCameraRoll()
}
}
}
private func selectedItems() -> [MHomeUploadItem]?
{
guard
let selectedItems:[IndexPath] = viewUpload.collectionView.indexPathsForSelectedItems
else
{
return nil
}
var uploadItems:[MHomeUploadItem] = []
for indexSelected:IndexPath in selectedItems
{
let itemIndex:Int = indexSelected.item
let uploadItem:MHomeUploadItem = model.items[itemIndex]
uploadItems.append(uploadItem)
}
return uploadItems
}
//MARK: public
func commitUpload()
{
guard
var uploadItems:[MHomeUploadItem] = selectedItems()
else
{
return
}
uploadItems.sort
{ (itemA:MHomeUploadItem, itemB:MHomeUploadItem) -> Bool in
return itemA.creationDate > itemB.creationDate
}
let controllerSync:CHomeUploadSync = CHomeUploadSync(
album:album,
uploadItems:uploadItems,
controllerUpload:self)
parentController.over(
controller:controllerSync,
pop:false,
animate:true)
}
func uploadFinished()
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
guard
let autoDelete:Bool = MSession.sharedInstance.settings.current?.autoDelete
else
{
return
}
if autoDelete
{
self?.performRemovePictures()
}
}
}
func clearAdded()
{
removePicturesAlert()
}
func changeAlbum()
{
let albumSelect:CPhotosAlbumSelection = CPhotosAlbumSelection(
currentAlbum:album,
delegate:self)
parentController.over(
controller:albumSelect,
pop:false,
animate:true)
}
func selectAll(selection:Bool)
{
let collectionView:UICollectionView = viewUpload.collectionView
let count:Int = model.items.count
if selection
{
for indexItem:Int in 0 ..< count
{
let item:MHomeUploadItem = model.items[indexItem]
guard
let _:MHomeUploadItemStatusNone = item.status as? MHomeUploadItemStatusNone
else
{
continue
}
item.statusWaiting()
let indexPath:IndexPath = IndexPath(
item:indexItem,
section:0)
collectionView.selectItem(
at:indexPath,
animated:false,
scrollPosition:UICollectionViewScrollPosition())
}
}
else
{
for indexItem:Int in 0 ..< count
{
let item:MHomeUploadItem = model.items[indexItem]
guard
let _:MHomeUploadItemStatusWaiting = item.status as? MHomeUploadItemStatusWaiting
else
{
continue
}
item.statusClear()
}
collectionView.reloadData()
}
viewUpload.updateBar()
}
//MARK: album selection delegate
func albumSelected(album:MPhotosItem)
{
self.album = album
viewUpload.header?.refresh()
}
}
|
mit
|
da46b01fbef688eb30f71aff61b574bd
| 25.918794 | 101 | 0.509309 | 6.128896 | false | false | false | false |
qasim/CDFLabs
|
CDFLabs/Utils/Constants.swift
|
1
|
393
|
//
// Constants.swift
// CDFLabs
//
// Created by Qasim Iqbal on 12/31/15.
// Copyright © 2015 Qasim Iqbal. All rights reserved.
//
import UIKit
struct CLTable {
static var printerCellHeight: CGFloat = 112.0
static var cellHeight: CGFloat = 80.0
static var cellPadding: CGFloat = 8.0
static var cellCornerRadius: CGFloat = 4.0
static var tagPadding: CGFloat = 4.0
}
|
mit
|
2707b9d9c435cba0e337929bd778c358
| 22.058824 | 54 | 0.686224 | 3.322034 | false | false | false | false |
A752575700/HOMEWORK
|
Day4_1/ProductName/ProductName/GameScene.swift
|
1
|
1551
|
//
// GameScene.swift
// ProductName
//
// Created by Lan on 14/08/2015.
// Copyright (c) 2015 TOPHACKER. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
//SK=SpriteKit
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = "Hello, World!";
myLabel.fontSize = 65;
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
self.addChild(myLabel)
}
//回调
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
//set<>-集合
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
let sprite = SKSpriteNode(imageNamed:"Spaceship")
sprite.xScale = 0.5
sprite.yScale = 0.5
sprite.position = location
let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:10)
let action2 = SKAction.fadeOutWithDuration(10)
let actionmix = SKAction.group([action, action2])
//SKAction 动作
sprite.runAction(actionmix)
//SKAction.repeatAction
self.addChild(sprite)
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
|
mit
|
1862eac77e193a5e912cf8c036554dd9
| 28.037736 | 93 | 0.565952 | 4.720859 | false | false | false | false |
Eflet/Charts
|
ChartsDemo-OSX/ChartsDemo-OSX/Demos/RadarDemoViewController.swift
|
6
|
1533
|
//
// RadarDemoViewController.swift
// ChartsDemo-OSX
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
import Foundation
import Cocoa
import Charts
public class RadarDemoViewController: NSViewController
{
@IBOutlet var radarChartView: RadarChartView!
override public func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
let xs = Array(1..<10).map { return Double($0) }
let ys1 = xs.map { i in return sin(Double(i / 2.0 / 3.141 * 1.5)) }
let ys2 = xs.map { i in return cos(Double(i / 2.0 / 3.141)) }
let yse1 = ys1.enumerate().map { idx, i in return ChartDataEntry(value: i, xIndex: idx) }
let yse2 = ys2.enumerate().map { idx, i in return ChartDataEntry(value: i, xIndex: idx) }
let data = RadarChartData(xVals: xs)
let ds1 = RadarChartDataSet(yVals: yse1, label: "Hello")
ds1.colors = [NSUIColor.redColor()]
data.addDataSet(ds1)
let ds2 = RadarChartDataSet(yVals: yse2, label: "World")
ds2.colors = [NSUIColor.blueColor()]
data.addDataSet(ds2)
self.radarChartView.data = data
self.radarChartView.descriptionText = "Radarchart Demo"
}
override public func viewWillAppear()
{
self.radarChartView.animate(xAxisDuration: 0.0, yAxisDuration: 1.0)
}
}
|
apache-2.0
|
6294653aa7c2b9f27d43a70a8c1987a4
| 30.958333 | 97 | 0.634051 | 3.96124 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new
|
Source/PaginationController.swift
|
3
|
2378
|
//
// TablePaginationController.swift
// edX
//
// Created by Akiva Leffert on 12/16/15.
// Copyright © 2015 edX. All rights reserved.
//
extension UIScrollView {
var scrolledNearBottom : Bool {
// Rough guess for near bottom: One screen's worth of content away or less
return self.bounds.maxY + self.bounds.height >= self.contentSize.height
}
}
protocol ScrollingPaginationViewManipulator {
func setFooter(footer: UIView, visible: Bool)
var scrollView: UIScrollView? { get }
var canPaginate: Bool { get }
}
private let footerHeight = 30
public class PaginationController<A> : NSObject, Paginator {
typealias Element = A
private let paginator : AnyPaginator<A>
private let viewManipulator: ScrollingPaginationViewManipulator
private let footer : UIView = {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: footerHeight))
let activityIndicator = SpinnerView(size: .Large, color: .Primary)
view.addSubview(activityIndicator)
activityIndicator.snp_makeConstraints { make in
make.center.equalTo(view)
}
return view
}()
init<P: Paginator where P.Element == A>(paginator: P, manipulator: ScrollingPaginationViewManipulator) {
self.paginator = AnyPaginator(paginator)
self.viewManipulator = manipulator
super.init()
manipulator.setFooter(self.footer, visible: false)
manipulator.scrollView?.oex_addObserver(self, forKeyPath: "bounds") { (controller, tableView, newValue) -> Void in
controller.viewScrolled()
}
}
var stream : Stream<[A]> {
return paginator.stream
}
func loadMore() {
paginator.loadMore()
}
var hasNext: Bool {
return paginator.hasNext
}
private func updateVisibility() {
viewManipulator.setFooter(self.footer, visible: self.paginator.stream.active)
}
private func viewScrolled() {
if !self.paginator.stream.active && (viewManipulator.scrollView?.scrolledNearBottom ?? false) && viewManipulator.canPaginate && self.paginator.hasNext {
self.paginator.loadMore()
self.updateVisibility()
}
else if !self.paginator.hasNext && (viewManipulator.scrollView?.scrolledNearBottom ?? false){
self.updateVisibility()
}
}
}
|
apache-2.0
|
2c377682e8489f38929cbbcf8570b899
| 28.7125 | 160 | 0.662179 | 4.493384 | false | false | false | false |
LuAndreCast/iOS_WatchProjects
|
watchOS3/HealthKit Workout/HealthStoreMonitor.swift
|
1
|
4218
|
//
// HeartRate.swift
// HealthWatchExample
//
// Created by Luis Castillo on 8/5/16.
// Copyright © 2016 LC. All rights reserved.
//
//import Foundation
import HealthKit
@objc protocol healthStoreMonitorDelegate {
func healthStoreMonitorResults(results:[HKSample])
func healthStoreMonitorError(error:NSError)
}
@objc
class HealthStoreMonitor: NSObject {
var delegate:healthStoreMonitorDelegate?
/* time looking back (in seconds) when performing sample query */
private let dateInterval:TimeInterval = -60.0
/* Polling time (in seconds) */
private let pollingInterval:TimeInterval = 2.5
private var continuePolling:Bool = true
private var sampleType:HKSampleType?
private var healthStore:HKHealthStore?
//limit
var limit:Int = Int(HKObjectQueryNoLimit)
//ascending
var ascending:Bool = true
var timeoutLimit:Int = 240 //in secs - default 4 mins
//MARK: - Start / End Monitoring
func startMonitoring(healthStore:HKHealthStore, sampleType:HKSampleType)
{
self.continuePolling = true
self.healthStore = healthStore
self.sampleType = sampleType
self.scheduleNextPoll()
}//eom
func endMonitoring()
{
self.continuePolling = false
self.healthStore = nil
}//eom
//MARK: - Polling
private func scheduleNextPoll()
{
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
if self.continuePolling
{
self.querySample()
self.scheduleNextPoll()
}
}
}//eom
//MARK: - Query
private func querySample()
{
//type
guard let queryType:HKSampleType = self.sampleType
else
{
let error = NSError(domain: Errors.monitoring.domain, code: Errors.monitoring.type.code, userInfo:Errors.monitoring.type.description )
self.sendError(error: error)
return
}
//date (predicate)
let startDate:NSDate? = NSDate(timeIntervalSinceNow: self.dateInterval)
let endDate:NSDate? = nil
let queryOptions:HKQueryOptions = []
let datePredicate = HKQuery.predicateForSamples(withStart: startDate as Date?, end: endDate as Date?, options: queryOptions)
/*
//device (predicate)
let device:HKDevice = HKDevice.localDevice()
let devicePredicate = HKQuery.predicateForObjectsFromDevices([device])
//final predicate
let predicate:NSCompoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [datePredicate])
*/
//sorting
let sorting:NSSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: self.ascending)
//query
let query:HKSampleQuery = HKSampleQuery(sampleType: queryType,
predicate: datePredicate,
limit: self.limit,
sortDescriptors: [sorting])
{ (query:HKSampleQuery, samples:[HKSample]?, error:Error?) in
//errors
if error != nil
{
let error = NSError(domain: Errors.monitoring.domain, code: Errors.monitoring.query.code, userInfo:Errors.monitoring.query.description )
self.sendError(error: error)
}
else
{
//data
if samples != nil
{
self.delegate?.healthStoreMonitorResults(results: samples!)
}
else
{
//empty results
}
}
}//eo-query
self.healthStore?.execute(query)
}//eom
//MARK: - Error
func sendError(error:NSError)
{
#if DEBUG
print("[\(self)] ERROR: \(error.localizedDescription)")
#endif
self.endMonitoring()
self.delegate?.healthStoreMonitorError(error: error)
}//eom
}//eoc
|
mit
|
e5f89e13d724e7f81c82734d1e6513ee
| 28.284722 | 152 | 0.569362 | 5.238509 | false | false | false | false |
ReiVerdugo/uikit-fundamentals
|
step2.4-prepareForSegueReview/Dice/RollViewController.swift
|
1
|
1096
|
//
// RollViewController.swift
// Dice
//
// Created by Jason Schatz on 11/6/14.
// Copyright (c) 2014 Udacity. All rights reserved.
//
import UIKit
// MARK: - RollViewController: UIViewController
class RollViewController: UIViewController {
// MARKL Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "rollDice" {
let controller = segue.destinationViewController as!
DiceViewController
controller.firstValue = self.randomDiceValue()
controller.secondValue = self.randomDiceValue()
}
}
// MARK: Generate Dice Value
// randomly generates a Int from 1 to 6
func randomDiceValue() -> Int {
// generate a random Int32 using arc4Random
let randomValue = 1 + arc4random() % 6
// return a more convenient Int, initialized with the random value
return Int(randomValue)
}
// MARK: Actions
@IBAction func rollTheDice(){
}
}
|
mit
|
cfef3319b20e238bb69e1380e799ea19
| 23.355556 | 81 | 0.603102 | 4.892857 | false | false | false | false |
reza-ryte-club/firefox-ios
|
Storage/SQL/SQLiteLogins.swift
|
5
|
37556
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
private let log = Logger.syncLogger
let TableLoginsMirror = "loginsM"
let TableLoginsLocal = "loginsL"
let AllLoginTables: Args = [TableLoginsMirror, TableLoginsLocal]
private class LoginsTable: Table {
var name: String { return "LOGINS" }
var version: Int { return 2 }
func run(db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool {
let err = db.executeChange(sql, withArgs: args)
if err != nil {
log.error("Error running SQL in LoginsTable. \(err?.localizedDescription)")
log.error("SQL was \(sql)")
}
return err == nil
}
// TODO: transaction.
func run(db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql, args: nil) {
return false
}
}
return true
}
func create(db: SQLiteDBConnection, version: Int) -> Bool {
// We ignore the version.
let common =
"id INTEGER PRIMARY KEY AUTOINCREMENT" +
", hostname TEXT NOT NULL" +
", httpRealm TEXT" +
", formSubmitURL TEXT" +
", usernameField TEXT" +
", passwordField TEXT" +
", timesUsed INTEGER NOT NULL DEFAULT 0" +
", timeCreated INTEGER NOT NULL" +
", timeLastUsed INTEGER" +
", timePasswordChanged INTEGER NOT NULL" +
", username TEXT" +
", password TEXT NOT NULL"
let mirror = "CREATE TABLE IF NOT EXISTS \(TableLoginsMirror) (" +
common +
", guid TEXT NOT NULL UNIQUE" +
", server_modified INTEGER NOT NULL" + // Integer milliseconds.
", is_overridden TINYINT NOT NULL DEFAULT 0" +
")"
let local = "CREATE TABLE IF NOT EXISTS \(TableLoginsLocal) (" +
common +
", guid TEXT NOT NULL UNIQUE " + // Typically overlaps one in the mirror unless locally new.
", local_modified INTEGER" + // Can be null. Client clock. In extremis only.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean. Locally deleted.
", sync_status TINYINT " + // SyncStatus enum. Set when changed or created.
"NOT NULL DEFAULT \(SyncStatus.Synced.rawValue)" +
")"
return self.run(db, queries: [mirror, local])
}
func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool {
if from == to {
log.debug("Skipping update from \(from) to \(to).")
return true
}
if from == 0 {
// This is likely an upgrade from before Bug 1160399.
log.debug("Updating logins tables from zero. Assuming drop and recreate.")
return drop(db) && create(db, version: to)
}
// TODO: real update!
log.debug("Updating logins table from \(from) to \(to).")
return drop(db) && create(db, version: to)
}
func exists(db: SQLiteDBConnection) -> Bool {
return db.tablesExist(AllLoginTables)
}
func drop(db: SQLiteDBConnection) -> Bool {
log.debug("Dropping logins table.")
let err = db.executeChange("DROP TABLE IF EXISTS \(name)", withArgs: nil)
return err == nil
}
}
public class SQLiteLogins: BrowserLogins {
private let db: BrowserDB
private static let MainColumns = "guid, username, password, hostname, httpRealm, formSubmitURL, usernameField, passwordField"
private static let MainWithLastUsedColumns = MainColumns + ", timeLastUsed, timesUsed"
private static let LoginColumns = MainColumns + ", timeCreated, timeLastUsed, timePasswordChanged, timesUsed"
public init(db: BrowserDB) {
self.db = db
db.createOrUpdate(LoginsTable())
}
private class func populateLogin(login: Login, row: SDRow) {
login.formSubmitURL = row["formSubmitURL"] as? String
login.usernameField = row["usernameField"] as? String
login.passwordField = row["passwordField"] as? String
login.guid = row["guid"] as! String
if let timeCreated = row.getTimestamp("timeCreated"),
let timeLastUsed = row.getTimestamp("timeLastUsed"),
let timePasswordChanged = row.getTimestamp("timePasswordChanged"),
let timesUsed = row["timesUsed"] as? Int {
login.timeCreated = timeCreated
login.timeLastUsed = timeLastUsed
login.timePasswordChanged = timePasswordChanged
login.timesUsed = timesUsed
}
}
private class func constructLogin<T: Login>(row: SDRow, c: T.Type) -> T {
let credential = NSURLCredential(user: row["username"] as? String ?? "",
password: row["password"] as! String,
persistence: NSURLCredentialPersistence.None)
let protectionSpace = NSURLProtectionSpace(host: row["hostname"] as! String,
port: 0,
`protocol`: nil,
realm: row["httpRealm"] as? String,
authenticationMethod: nil)
let login = T(credential: credential, protectionSpace: protectionSpace)
self.populateLogin(login, row: row)
return login
}
class func LocalLoginFactory(row: SDRow) -> LocalLogin {
let login = self.constructLogin(row, c: LocalLogin.self)
login.localModified = row.getTimestamp("local_modified")!
login.isDeleted = row.getBoolean("is_deleted")
login.syncStatus = SyncStatus(rawValue: row["sync_status"] as! Int)!
return login
}
class func MirrorLoginFactory(row: SDRow) -> MirrorLogin {
let login = self.constructLogin(row, c: MirrorLogin.self)
login.serverModified = row.getTimestamp("server_modified")!
login.isOverridden = row.getBoolean("is_overridden")
return login
}
private class func LoginFactory(row: SDRow) -> Login {
return self.constructLogin(row, c: Login.self)
}
private class func LoginDataFactory(row: SDRow) -> LoginData {
return LoginFactory(row) as LoginData
}
private class func LoginUsageDataFactory(row: SDRow) -> LoginUsageData {
return LoginFactory(row) as LoginUsageData
}
func notifyLoginDidChange() {
log.debug("Notifying login did change.")
// For now we don't care about the contents.
// This posts immediately to the shared notification center.
let notification = NSNotification(name: NotificationDataLoginDidChange, object: nil)
NSNotificationCenter.defaultCenter().postNotification(notification)
}
public func getUsageDataForLoginByGUID(guid: GUID) -> Deferred<Maybe<LoginUsageData>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND guid = ? " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginUsageDataFactory)
>>== { value in
deferMaybe(value[0]!)
}
}
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? " +
"ORDER BY timeLastUsed DESC"
let args: Args = [protectionSpace.host, protectionSpace.host]
if Logger.logPII {
log.debug("Looking for login: \(protectionSpace.host)")
}
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
// username is really Either<String, NULL>; we explicitly match no username.
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace, withUsername username: String?) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let args: Args
let usernameMatch: String
if let username = username {
args = [protectionSpace.host, username, protectionSpace.host, username]
usernameMatch = "username = ?"
} else {
args = [protectionSpace.host, protectionSpace.host]
usernameMatch = "username IS NULL"
}
if Logger.logPII {
log.debug("Looking for login: \(username), \(args[0])")
}
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? AND \(usernameMatch) " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? AND username IS ? " +
"ORDER BY timeLastUsed DESC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
public func addLogin(login: LoginData) -> Success {
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = NSNumber(unsignedLongLong: nowMicro)
let dateMilli = NSNumber(unsignedLongLong: nowMilli)
let args: Args = [
login.hostname,
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.username,
login.password,
login.guid,
dateMicro, // timeCreated
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
dateMilli, // localModified
]
let sql =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
// Shared fields.
"( hostname" +
", httpRealm" +
", formSubmitURL" +
", usernameField" +
", passwordField" +
", timesUsed" +
", username" +
", password " +
// Local metadata.
", guid " +
", timeCreated" +
", timeLastUsed" +
", timePasswordChanged" +
", local_modified " +
", is_deleted " +
", sync_status " +
") " +
"VALUES (?,?,?,?,?,1,?,?,?,?,?, " +
"?, ?, 0, \(SyncStatus.New.rawValue)" + // Metadata.
")"
return db.run(sql, withArgs: args)
>>> effect(self.notifyLoginDidChange)
}
private func cloneMirrorToOverlay(whereClause whereClause: String?, args: Args?) -> Deferred<Maybe<Int>> {
let shared =
"guid " +
", hostname" +
", httpRealm" +
", formSubmitURL" +
", usernameField" +
", passwordField" +
", timeCreated" +
", timeLastUsed" +
", timePasswordChanged" +
", timesUsed" +
", username" +
", password "
let local =
", local_modified " +
", is_deleted " +
", sync_status "
let sql = "INSERT OR IGNORE INTO \(TableLoginsLocal) " +
"(\(shared)\(local)) " +
"SELECT \(shared), NULL AS local_modified, 0 AS is_deleted, 0 AS sync_status " +
"FROM \(TableLoginsMirror) " +
(whereClause ?? "")
return self.db.write(sql, withArgs: args)
}
/**
* Returns success if either a local row already existed, or
* one could be copied from the mirror.
*/
private func ensureLocalOverlayExistsForGUID(guid: GUID) -> Success {
let sql = "SELECT guid FROM \(TableLoginsLocal) WHERE guid = ?"
let args: Args = [guid]
let c = db.runQuery(sql, args: args, factory: { row in 1 })
return c >>== { rows in
if rows.count > 0 {
return succeed()
}
log.debug("No overlay; cloning one for GUID \(guid).")
return self.cloneMirrorToOverlay(guid)
>>== { count in
if count > 0 {
return succeed()
}
log.warning("Failed to create local overlay for GUID \(guid).")
return deferMaybe(NoSuchRecordError(guid: guid))
}
}
}
private func cloneMirrorToOverlay(guid: GUID) -> Deferred<Maybe<Int>> {
let whereClause = "WHERE guid = ?"
let args: Args = [guid]
return self.cloneMirrorToOverlay(whereClause: whereClause, args: args)
}
private func markMirrorAsOverridden(guid: GUID) -> Success {
let args: Args = [guid]
let sql =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Replace the local DB row with the provided GUID.
* If no local overlay exists, one is first created.
*
* If `significant` is `true`, the `sync_status` of the row is bumped to at least `Changed`.
* If it's already `New`, it remains marked as `New`.
*
* This flag allows callers to make minor changes (such as incrementing a usage count)
* without triggering an upload or a conflict.
*/
public func updateLoginByGUID(guid: GUID, new: LoginData, significant: Bool) -> Success {
// Right now this method is only ever called if the password changes at
// point of use, so we always set `timePasswordChanged` and `timeLastUsed`.
// We can (but don't) also assume that `significant` will always be `true`,
// at least for the time being.
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = NSNumber(unsignedLongLong: nowMicro)
let dateMilli = NSNumber(unsignedLongLong: nowMilli)
let args: Args = [
dateMilli, // local_modified
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
new.httpRealm,
new.formSubmitURL,
new.usernameField,
new.passwordField,
new.password,
new.hostname,
new.username,
guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?, timeLastUsed = ?, timePasswordChanged = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timesUsed = timesUsed + 1" +
", password = ?, hostname = ?, username = ?" +
// We keep rows marked as New in preference to marking them as changed. This allows us to
// delete them immediately if they don't reach the server.
(significant ? ", sync_status = max(sync_status, 1) " : "") +
" WHERE guid = ?"
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(update, withArgs: args) }
>>> effect(self.notifyLoginDidChange)
}
public func addUseOfLoginByGUID(guid: GUID) -> Success {
let sql =
"UPDATE \(TableLoginsLocal) SET " +
"timesUsed = timesUsed + 1, timeLastUsed = ?, local_modified = ? " +
"WHERE guid = ? AND is_deleted = 0"
// For now, mere use is not enough to flip sync_status to Changed.
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let args: Args = [NSNumber(unsignedLongLong: nowMicro), NSNumber(unsignedLongLong: nowMilli), guid]
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(sql, withArgs: args) }
}
public func removeLoginByGUID(guid: GUID) -> Success {
let nowMillis = NSDate.now()
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE guid = ? AND sync_status = \(SyncStatus.New.rawValue)"
// Otherwise, mark it as changed.
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = \(nowMillis)" +
", sync_status = \(SyncStatus.Changed.rawValue)" +
", is_deleted = 1" +
", password = ''" +
", hostname = ''" +
", username = ''" +
" WHERE guid = ?"
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
"(guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.Changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror) WHERE guid = ?"
let args: Args = [guid]
return self.db.run(delete, withArgs: args)
>>> { self.db.run(update, withArgs: args) }
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(insert, withArgs: args) }
>>> effect(self.notifyLoginDidChange)
}
public func removeAll() -> Success {
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server. If Sync isn't set up, this will be everything.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE sync_status = \(SyncStatus.New.rawValue)"
let nowMillis = NSDate.now()
// Mark anything we haven't already deleted.
let update =
"UPDATE \(TableLoginsLocal) SET local_modified = \(nowMillis), sync_status = \(SyncStatus.Changed.rawValue), is_deleted = 1, password = '', hostname = '', username = '' WHERE is_deleted = 0"
// Copy all the remaining rows from our mirror, marking them as locally deleted. The
// OR IGNORE will cause conflicts due to non-unique guids to be dropped, preserving
// anything we already deleted.
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) (guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.Changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror)"
// After that, we mark all of the mirror rows as overridden.
return self.db.run(delete)
>>> { self.db.run(update) }
>>> { self.db.run("UPDATE \(TableLoginsMirror) SET is_overridden = 1") }
>>> { self.db.run(insert) }
>>> effect(self.notifyLoginDidChange)
}
}
// When a server change is detected (e.g., syncID changes), we should consider shifting the contents
// of the mirror into the local overlay, allowing a content-based reconciliation to occur on the next
// full sync. Or we could flag the mirror as to-clear, download the server records and un-clear, and
// resolve the remainder on completion. This assumes that a fresh start will typically end up with
// the exact same records, so we might as well keep the shared parents around and double-check.
extension SQLiteLogins: SyncableLogins {
/**
* Delete the login with the provided GUID. Succeeds if the GUID is unknown.
*/
public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success {
// Simply ignore the possibility of a conflicting local change for now.
let local = "DELETE FROM \(TableLoginsLocal) WHERE guid = ?"
let remote = "DELETE FROM \(TableLoginsMirror) WHERE guid = ?"
let args: Args = [guid]
return self.db.run(local, withArgs: args) >>> { self.db.run(remote, withArgs: args) }
}
func getExistingMirrorRecordByGUID(guid: GUID) -> Deferred<Maybe<MirrorLogin?>> {
let sql = "SELECT * FROM \(TableLoginsMirror) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.MirrorLoginFactory) >>== { deferMaybe($0[0]) }
}
func getExistingLocalRecordByGUID(guid: GUID) -> Deferred<Maybe<LocalLogin?>> {
let sql = "SELECT * FROM \(TableLoginsLocal) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory) >>== { deferMaybe($0[0]) }
}
private func storeReconciledLogin(login: Login) -> Success {
let dateMilli = NSNumber(unsignedLongLong: NSDate.now())
let args: Args = [
dateMilli, // local_modified
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
NSNumber(unsignedLongLong: login.timeLastUsed),
NSNumber(unsignedLongLong: login.timePasswordChanged),
login.timesUsed,
login.password,
login.hostname,
login.username,
login.guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timeLastUsed = ?, timePasswordChanged = ?, timesUsed = ?" +
", password = ?" +
", hostname = ?, username = ?" +
", sync_status = \(SyncStatus.Changed.rawValue) " +
" WHERE guid = ?"
return self.db.run(update, withArgs: args)
}
public func applyChangedLogin(upstream: ServerLogin) -> Success {
// Our login storage tracks the shared parent from the last sync (the "mirror").
// This allows us to conclusively determine what changed in the case of conflict.
//
// Our first step is to determine whether the record is changed or new: i.e., whether
// or not it's present in the mirror.
//
// TODO: these steps can be done in a single query. Make it work, make it right, make it fast.
// TODO: if there's no mirror record, all incoming records can be applied in one go; the only
// reason we need to fetch first is to establish the shared parent. That would be nice.
let guid = upstream.guid
return self.getExistingMirrorRecordByGUID(guid) >>== { mirror in
return self.getExistingLocalRecordByGUID(guid) >>== { local in
return self.applyChangedLogin(upstream, local: local, mirror: mirror)
}
}
}
private func applyChangedLogin(upstream: ServerLogin, local: LocalLogin?, mirror: MirrorLogin?) -> Success {
// Once we have the server record, the mirror record (if any), and the local overlay (if any),
// we can always know which state a record is in.
// If it's present in the mirror, then we can proceed directly to handling the change;
// we assume that once a record makes it into the mirror, that the local record association
// has already taken place, and we're tracking local changes correctly.
if let mirror = mirror {
log.debug("Mirror record found for changed record \(mirror.guid).")
if let local = local {
log.debug("Changed local overlay found for \(local.guid). Resolving conflict with 3WM.")
// * Changed remotely and locally (conflict). Resolve the conflict using a three-way merge: the
// local mirror is the shared parent of both the local overlay and the new remote record.
// Apply results as in the co-creation case.
return self.resolveConflictBetween(local: local, upstream: upstream, shared: mirror)
}
log.debug("No local overlay found. Updating mirror to upstream.")
// * Changed remotely but not locally. Apply the remote changes to the mirror.
// There is no local overlay to discard or resolve against.
return self.updateMirrorToLogin(upstream, fromPrevious: mirror)
}
// * New both locally and remotely with no shared parent (cocreation).
// Or we matched the GUID, and we're assuming we just forgot the mirror.
//
// Merge and apply the results remotely, writing the result into the mirror and discarding the overlay
// if the upload succeeded. (Doing it in this order allows us to safely replay on failure.)
//
// If the local and remote record are the same, this is trivial.
// At this point we also switch our local GUID to match the remote.
if let local = local {
// We might have randomly computed the same GUID on two devices connected
// to the same Sync account.
// With our 9-byte GUIDs, the chance of that happening is very small, so we
// assume that this device has previously connected to this account, and we
// go right ahead with a merge.
log.debug("Local record with GUID \(local.guid) but no mirror. This is unusual; assuming disconnect-reconnect scenario. Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// If it's not present, we must first check whether we have a local record that's substantially
// the same -- the co-creation or re-sync case.
//
// In this case, we apply the server record to the mirror, change the local record's GUID,
// and proceed to reconcile the change on a content basis.
return self.findLocalRecordByContent(upstream) >>== { local in
if let local = local {
log.debug("Local record \(local.guid) content-matches new remote record \(upstream.guid). Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// * New upstream only; no local overlay, content-based merge,
// or shared parent in the mirror. Insert it in the mirror.
log.debug("Never seen remote record \(upstream.guid). Mirroring.")
return self.insertNewMirror(upstream)
}
}
// N.B., the final guid is sometimes a WHERE and sometimes inserted.
private func mirrorArgs(login: ServerLogin) -> Args {
let args: Args = [
NSNumber(unsignedLongLong: login.serverModified),
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.timesUsed,
NSNumber(unsignedLongLong: login.timeLastUsed),
NSNumber(unsignedLongLong: login.timePasswordChanged),
NSNumber(unsignedLongLong: login.timeCreated),
login.password,
login.hostname,
login.username,
login.guid,
]
return args
}
/**
* Called when we have a changed upstream record and no local changes.
* There's no need to flip the is_overridden flag.
*/
private func updateMirrorToLogin(login: ServerLogin, fromPrevious previous: Login) -> Success {
let args = self.mirrorArgs(login)
let sql =
"UPDATE \(TableLoginsMirror) SET " +
" server_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?" +
// These we need to coalesce, because we might be supplying zeroes if the remote has
// been overwritten by an older client. In this case, preserve the old value in the
// mirror.
", timesUsed = coalesce(nullif(?, 0), timesUsed)" +
", timeLastUsed = coalesce(nullif(?, 0), timeLastUsed)" +
", timePasswordChanged = coalesce(nullif(?, 0), timePasswordChanged)" +
", timeCreated = coalesce(nullif(?, 0), timeCreated)" +
", password = ?, hostname = ?, username = ?" +
" WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Called when we have a completely new record. Naturally the new record
* is marked as non-overridden.
*/
private func insertNewMirror(login: ServerLogin, isOverridden: Int = 0) -> Success {
let args = self.mirrorArgs(login)
let sql =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") VALUES (\(isOverridden), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
return self.db.run(sql, withArgs: args)
}
/**
* We assume a local record matches if it has the same username (password can differ),
* hostname, httpRealm. We also check that the formSubmitURLs are either blank or have the
* same host and port.
*
* This is roughly the same as desktop's .matches():
* <https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginInfo.js#41>
*/
private func findLocalRecordByContent(login: Login) -> Deferred<Maybe<LocalLogin?>> {
let primary =
"SELECT * FROM \(TableLoginsLocal) WHERE " +
"hostname IS ? AND httpRealm IS ? AND username IS ?"
var args: Args = [login.hostname, login.httpRealm, login.username]
let sql: String
if login.formSubmitURL == nil {
sql = primary + " AND formSubmitURL IS NULL"
} else if login.formSubmitURL!.isEmpty {
sql = primary
} else {
if let hostPort = login.formSubmitURL?.asURL?.hostPort {
// Substring check will suffice for now. TODO: proper host/port check after fetching the cursor.
sql = primary + " AND (formSubmitURL = '' OR (instr(formSubmitURL, ?) > 0))"
args.append(hostPort)
} else {
log.warning("Incoming formSubmitURL is non-empty but is not a valid URL with a host. Not matching local.")
return deferMaybe(nil)
}
}
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory)
>>== { cursor in
switch (cursor.count) {
case 0:
return deferMaybe(nil)
case 1:
// Great!
return deferMaybe(cursor[0])
default:
// TODO: join against the mirror table to exclude local logins that
// already match a server record.
// Right now just take the first.
log.warning("Got \(cursor.count) local logins with matching details! This is most unexpected.")
return deferMaybe(cursor[0])
}
}
}
private func resolveConflictBetween(local local: LocalLogin, upstream: ServerLogin, shared: Login) -> Success {
// Attempt to compute two delta sets by comparing each new record to the shared record.
// Then we can merge the two delta sets -- either perfectly or by picking a winner in the case
// of a true conflict -- and produce a resultant record.
let localDeltas = (local.localModified, local.deltas(from: shared))
let upstreamDeltas = (upstream.serverModified, upstream.deltas(from: shared))
let mergedDeltas = Login.mergeDeltas(a: localDeltas, b: upstreamDeltas)
// Not all Sync clients handle the optional timestamp fields introduced in Bug 555755.
// We might get a server record with no timestamps, and it will differ from the original
// mirror!
// We solve that by refusing to generate deltas that discard information. We'll preserve
// the local values -- either from the local record or from the last shared parent that
// still included them -- and propagate them back to the server.
// It's OK for us to reconcile and reupload; it causes extra work for every client, but
// should not cause looping.
let resultant = shared.applyDeltas(mergedDeltas)
// We can immediately write the downloaded upstream record -- the old one -- to
// the mirror store.
// We then apply this record to the local store, and mark it as needing upload.
// When the reconciled record is uploaded, it'll be flushed into the mirror
// with the correct modified time.
return self.updateMirrorToLogin(upstream, fromPrevious: shared)
>>> { self.storeReconciledLogin(resultant) }
}
private func resolveConflictWithoutParentBetween(local local: LocalLogin, upstream: ServerLogin) -> Success {
// Do the best we can. Either the local wins and will be
// uploaded, or the remote wins and we delete our overlay.
if local.timePasswordChanged > upstream.timePasswordChanged {
log.debug("Conflicting records with no shared parent. Using newer local record.")
return self.insertNewMirror(upstream, isOverridden: 1)
}
log.debug("Conflicting records with no shared parent. Using newer remote record.")
let args: Args = [local.guid]
return self.insertNewMirror(upstream, isOverridden: 0)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid = ?", withArgs: args) }
}
public func getModifiedLoginsToUpload() -> Deferred<Maybe<[Login]>> {
let sql =
"SELECT * FROM \(TableLoginsLocal) " +
"WHERE sync_status IS NOT \(SyncStatus.Synced.rawValue) AND is_deleted = 0"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: SQLiteLogins.LoginFactory)
>>== { deferMaybe($0.asArray()) }
}
public func getDeletedLoginsToUpload() -> Deferred<Maybe<[GUID]>> {
// There are no logins that are marked as deleted that were not originally synced --
// others are deleted immediately.
let sql =
"SELECT guid FROM \(TableLoginsLocal) " +
"WHERE is_deleted = 1"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: { return $0["guid"] as! GUID })
>>== { deferMaybe($0.asArray()) }
}
/**
* Chains through the provided timestamp.
*/
public func markAsSynchronized(guids: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> {
// Update the mirror from the local record that we just uploaded.
// sqlite doesn't support UPDATE FROM, so instead of running 10 subqueries * n GUIDs,
// we issue a single DELETE and a single INSERT on the mirror, then throw away the
// local overlay that we just uploaded with another DELETE.
log.debug("Marking \(guids.count) GUIDs as synchronized.")
// TODO: transaction!
let args: Args = guids.map { $0 as AnyObject }
let inClause = BrowserDB.varlist(args.count)
let delMirror = "DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let insMirror =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") SELECT 0, \(modified)" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid " +
"FROM \(TableLoginsLocal) " +
"WHERE guid IN \(inClause)"
let delLocal = "DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)"
return self.db.run(delMirror, withArgs: args)
>>> { self.db.run(insMirror, withArgs: args) }
>>> { self.db.run(delLocal, withArgs: args) }
>>> always(modified)
}
public func markAsDeleted(guids: [GUID]) -> Success {
log.debug("Marking \(guids.count) GUIDs as deleted.")
let args: Args = guids.map { $0 as AnyObject }
let inClause = BrowserDB.varlist(args.count)
return self.db.run("DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)", withArgs: args)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)", withArgs: args) }
}
}
extension SQLiteLogins: ResettableSyncStorage {
/**
* Clean up any metadata.
* TODO: is this safe for a regular reset? It forces a content-based merge.
*/
public func resetClient() -> Success {
// Clone all the mirrors so we don't lose data.
return self.cloneMirrorToOverlay(whereClause: nil, args: nil)
// Drop all of the mirror data.
>>> { self.db.run("DELETE FROM \(TableLoginsMirror)") }
// Mark all of the local data as new.
>>> { self.db.run("UPDATE \(TableLoginsLocal) SET sync_status = \(SyncStatus.New.rawValue)") }
}
}
extension SQLiteLogins: AccountRemovalDelegate {
public func onRemovedAccount() -> Success {
return self.resetClient()
}
}
|
mpl-2.0
|
5fd39920da9e62336b14157c60d393f7
| 41.436158 | 198 | 0.606055 | 4.813021 | false | false | false | false |
FutureKit/Swift-CocoaPod-iOS7-Example
|
CoolSampleAppThatRunsOniOS7/DummyProjectForSwiftPods/Pods/FutureKit/FutureKit/FTask/FTask.swift
|
1
|
10468
|
//
// FTask.swift
// Bikey
//
// Created by Michael Gray on 4/12/15.
// 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 CoreData
public class FTaskCompletion : NSObject {
public typealias rtype = FTask.resultType
var completion : Completion<rtype>
init(completion c:Completion<rtype>) {
self.completion = c
}
init(exception ex:NSException) {
self.completion = FAIL(FutureNSError(exception: ex))
}
init(success : rtype) {
self.completion = SUCCESS(success)
}
init(cancelled : ()) {
self.completion = .Cancelled
}
init (fail : NSError) {
self.completion = FAIL(fail)
}
init (continueWith f: FTask) {
self.completion = COMPLETE_USING(f.future)
}
class func Success(success : rtype) -> FTaskCompletion {
return FTaskCompletion(success: success)
}
class func Fail(fail : NSError) -> FTaskCompletion {
return FTaskCompletion(fail: fail)
}
class func Cancelled() -> FTaskCompletion {
return FTaskCompletion(cancelled: ())
}
}
public class FTaskPromise : NSObject {
public override init() {
super.init()
}
public typealias rtype = FTask.resultType
var promise = Promise<rtype>()
public var ftask : FTask {
get {
return FTask(self.promise.future)
}
}
public final func complete(completion c: FTaskCompletion) {
self.promise.complete(c.completion)
}
public final func completeWithSuccess(result : rtype) {
self.promise.completeWithSuccess(result)
}
public final func completeWithFail(e : NSError) {
self.promise.completeWithFail(e)
}
public final func completeWithException(e : NSException) {
self.promise.completeWithException(e)
}
public final func completeWithCancel() {
self.promise.completeWithCancel()
}
public final func continueWithFuture(f : FTask) {
self.promise.continueWithFuture(f.future)
}
// can return true if completion was successful.
// can block the current thread
final func tryComplete(completion c: FTaskCompletion) -> Bool {
return self.promise.tryComplete(c.completion)
}
public typealias completionErrorHandler = Promise<rtype>.completionErrorHandler
// execute a block if the completion "fails" because the future is already completed.
public final func complete(completion c: FTaskCompletion,onCompletionError errorBlock: completionErrorHandler) {
self.promise.complete(c.completion, onCompletionError: errorBlock)
}
}
extension FTaskPromise : Printable, DebugPrintable {
public override var description: String {
return "FTaskPromise!"
}
public override var debugDescription: String {
return "FTaskPromise! - \(self.promise.future.debugDescription)"
}
public func debugQuickLookObject() -> AnyObject? {
return self.debugDescription + "QL"
}
}
@objc public enum FTaskExecutor : Int {
case Primary // use the default configured executor. Current set to Immediate.
// There are deep philosphical arguments about Immediate vs Async.
// So whenever we figure out what's better we will set the Primary to that!
case Immediate // Never performs an Async Dispatch, Ok for simple mappings. But use with care!
// Blocks using the Immediate executor can run in ANY Block
case Async // Always performs an Async Dispatch to some non-main q (usually Default)
case StackCheckingImmediate // Will try to perform immediate, but does some stack checking. Safer than Immediate
// But is less efficient. Maybe useful if an Immediate handler is somehow causing stack overflow issues
case Main // will use MainAsync or MainImmediate based on MainStrategy
case MainAsync // will always do a dispatch_async to the mainQ
case MainImmediate // will try to avoid dispatch_async if already on the MainQ
case UserInteractive // QOS_CLASS_USER_INTERACTIVE
case UserInitiated // QOS_CLASS_USER_INITIATED
case Default // QOS_CLASS_DEFAULT
case Utility // QOS_CLASS_UTILITY
case Background // QOS_CLASS_BACKGROUND
// case Queue(dispatch_queue_t) // Dispatch to a Queue of your choice!
// Use this for your own custom queues
// case ManagedObjectContext(NSManagedObjectContext) // block will run inside the managed object's context via context.performBlock()
func execute<T>(block b: dispatch_block_t) {
let executionBlock = self.executor().callbackBlockFor(b)
executionBlock()
}
func executor() -> Executor {
switch self {
case .Primary:
return .Primary
case .Immediate:
return .Immediate
case .Async:
return .Async
case StackCheckingImmediate:
return .StackCheckingImmediate
case Main:
return .Main
case MainAsync:
return .MainAsync
case MainImmediate:
return .MainImmediate
case UserInteractive:
return .UserInteractive
case UserInitiated:
return .UserInitiated
case Default:
return .Default
case Utility:
return .Utility
case Background:
return .Background
}
}
}
public class FTask : NSObject {
public typealias resultType = AnyObject?
public typealias futureType = Future<resultType>
var future : Future<resultType>
override init() {
self.future = Future<resultType>()
super.init()
}
init(_ f : Future<resultType>) {
self.future = f
}
}
public extension FTask {
private class func toCompletion(a : AnyObject?) -> Completion<resultType> {
switch a {
case let f as Future<resultType>:
return .CompleteUsing(f)
case let f as FTask:
return .CompleteUsing(f.future)
case let c as Completion<resultType>:
return c
case let c as FTaskCompletion:
return c.completion
case let error as NSError:
return .Fail(error)
case let ex as NSException:
return Completion<resultType>(exception: ex)
default:
return SUCCESS(a)
}
}
private class func toCompletionObjc(a : AnyObject?) -> FTaskCompletion {
return FTaskCompletion(completion: self.toCompletion(a))
}
final func onCompleteQ(q : dispatch_queue_t,block b:( (completion:FTaskCompletion)-> AnyObject?)) -> FTask {
let f = self.future.onComplete(Executor.Queue(q)) { (completion) -> Completion<resultType> in
let c = FTaskCompletion(completion: completion)
return FTask.toCompletion(b(completion: c))
}
return FTask(f)
}
final func onComplete(executor : FTaskExecutor,block b:( (completion:FTaskCompletion)-> AnyObject?)) -> FTask {
let f = self.future.onComplete(executor.executor()) { (completion) -> Completion<resultType> in
let c = FTaskCompletion(completion: completion)
return FTask.toCompletion(b(completion: c))
}
return FTask(f)
}
final func onComplete(block:( (completion:FTaskCompletion)-> AnyObject?)) -> FTask {
return self.onComplete(.Primary, block: block)
}
final func onSuccessResultWithQ(q : dispatch_queue_t, _ block:((result:resultType) -> AnyObject?)) -> FTask {
return self.onCompleteQ(q) { (c) -> AnyObject? in
if c.completion.isSuccess {
return block(result: c.completion.result)
}
else {
return c
}
}
}
final func onSuccessResultWith(executor : FTaskExecutor, _ block:((result:resultType) -> AnyObject?)) -> FTask {
return self.onComplete(executor) { (c) -> AnyObject? in
if c.completion.isSuccess {
return block(result: c.completion.result)
}
else {
return c
}
}
}
final func onSuccessWithQ(q : dispatch_queue_t, block:(() -> AnyObject?)) -> FTask {
return self.onCompleteQ(q) { (c) -> AnyObject? in
if c.completion.isSuccess {
return block()
}
else {
return c
}
}
}
final func onSuccess(executor : FTaskExecutor, block:(() -> AnyObject?)) -> FTask {
return self.onComplete(executor) { (c) -> AnyObject? in
if c.completion.isSuccess {
return block()
}
else {
return c
}
}
}
final func onSuccessResult(block:((result:resultType)-> AnyObject?)) -> FTask {
return self.onSuccessResultWith(.Primary,block)
}
final func onSuccess(block:(() -> AnyObject?)) -> FTask {
return self.onSuccess(.Primary,block: block)
}
}
|
mit
|
830b262660aff07aee70e61294e7fbca
| 28.487324 | 138 | 0.615972 | 4.762511 | false | false | false | false |
twtstudio/WePeiYang-iOS
|
WePeiYang/PartyService/Model/Checkbox.swift
|
1
|
4186
|
//
// Checkbox.swift
// WePeiYang
//
// Created by Allen X on 8/25/16.
// Copyright © 2016 Qin Yubo. All rights reserved.
//
import UIKit
class Checkbox: UIButton {
let partyGray = UIColor(colorLiteralRed: 149.0/255.0, green: 149.0/255.0, blue: 149.0/255.0, alpha: 1)
typealias Quiz = Courses.Study20.Quiz
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
var nameLabel = UILabel()
var wasChosen = false
var belongsToMany = false
override func addTarget(target: AnyObject?, action: Selector, forControlEvents controlEvents: UIControlEvents) {
super.addTarget(target, action: action, forControlEvents: controlEvents)
let tapOnLabel = UITapGestureRecognizer(target: target, action: action)
self.nameLabel.addGestureRecognizer(tapOnLabel)
}
static func initOnlyChoiceBtns(with quizOptions: [Quiz.Option]) -> [Checkbox] {
return quizOptions.flatMap({ (option: Quiz.Option) -> Checkbox? in
return Checkbox(withSingleChoiceBtn: option)
})
}
static func initMultiChoicesBtns(with quizOptions: [Quiz.Option]) -> [Checkbox] {
return quizOptions.flatMap({ (option: Quiz.Option) -> Checkbox? in
return Checkbox(withMultiChoicesBtn: option)
})
}
convenience init(withSingleChoiceBtn quizOptionSingleChoice: Quiz.Option) {
self.init()
self.nameLabel = {
let foo = UILabel(text: quizOptionSingleChoice.name, fontSize: 16)
foo.userInteractionEnabled = true
foo.textColor = .blackColor()
return foo
}()
self.layer.borderWidth = 2
self.layer.borderColor = UIColor.blackColor().CGColor
self.tag = quizOptionSingleChoice.weight
self.frame.size = CGSize(width: 20, height: 20)
self.layer.cornerRadius = self.frame.width/2
if quizOptionSingleChoice.wasChosen {
self.backgroundColor = .greenColor()
self.wasChosen = true
} else {
self.backgroundColor = partyGray
}
/*
self.addSubview(self.nameLabel)
self.nameLabel.snp_makeConstraints {
make in
make.centerY.equalTo(self)
make.left.equalTo(self.snp_right).offset(10)
}*/
self.addTarget(self, action: #selector(Checkbox.beTapped), forControlEvents: .TouchUpInside)
}
convenience init(withMultiChoicesBtn quizOptionMultiChoices: Quiz.Option) {
self.init()
self.nameLabel = {
let foo = UILabel(text: quizOptionMultiChoices.name, fontSize: 16)
foo.userInteractionEnabled = true
foo.textColor = .blackColor()
return foo
}()
//self.layer.cornerRadius = self.frame.width/2
self.layer.borderWidth = 2
self.layer.borderColor = UIColor.blackColor().CGColor
self.tag = quizOptionMultiChoices.weight
if quizOptionMultiChoices.wasChosen {
self.backgroundColor = .greenColor()
self.wasChosen = true
} else {
self.backgroundColor = partyGray
}
/*
self.addSubview(self.nameLabel)
self.nameLabel.snp_makeConstraints {
make in
make.centerY.equalTo(self)
make.left.equalTo(self.snp_right).offset(10)
}*/
self.belongsToMany = true
self.addTarget(self, action: #selector(Checkbox.beTapped), forControlEvents: .TouchUpInside)
}
func beTapped() {
if self.belongsToMany {
self.wasChosen = !self.wasChosen
} else {
if !self.wasChosen {
self.wasChosen = !self.wasChosen
}
}
self.refreshStatus()
}
func refreshStatus() {
if self.wasChosen {
self.backgroundColor = .greenColor()
} else {
self.backgroundColor = partyGray
}
}
}
|
mit
|
1602523782c31b787fa39d467291846f
| 32.214286 | 116 | 0.606213 | 4.593853 | false | false | false | false |
ozpopolam/DoctorBeaver
|
DoctorBeaver/PetImageViewController.swift
|
1
|
15581
|
//
// PetImageViewController.swift
// DoctorBeaver
//
// Created by Anastasia Stepanova-Kolupakhina on 20.05.16.
// Copyright © 2016 Anastasia Stepanova-Kolupakhina. All rights reserved.
//
import UIKit
protocol PetImageViewControllerDelegate: class {
func petImageViewController(viewController: PetImageViewController, didSelectNewImageName imageName: String)
func petImageViewController(viewController: PetImageViewController, didSelectNewImage newImage: UIImage, withName newImageName: String)
}
class PetImageViewController: UIViewController {
@IBOutlet weak var decoratedNavigationBar: DecoratedNavigationBarView!
@IBOutlet weak var collectionView: UICollectionView!
weak var delegate: PetImageViewControllerDelegate?
var petInitialImage: UIImage!
var petInitialImageName: String!
// settings for layout of UICollectionView
let petImageCellId = "petImageCell"
var cellSize = CGSize(width: 0.0, height: 0.0)
var cellCornerRadius: CGFloat = 0.0
var sectionInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
var minimumSpacing: CGFloat = 0.0
let folderName = "DefaultPetImages/"
let defaultImagesNames = ["aquarium", "bird", "bunny", "cat0", "cat1", "cat2", "dog0", "dog1", "dog2", "fish", "snake"] // default images
var imagesNames = [String]() // ~ image from photo/gallery + ~ pet's custom image + default images
var images = [UIImage?]()
//let importedImageName = "imported" // name of image from photo/gallery
var importedImage: UIImage? // image from photo/gallery
let noSelectionIndex = -1
var selectedIndex = 0 // index of selected items
lazy var imagePicker = UIImagePickerController()
// available sources
let cameraIsAvailable = UIImagePickerController.isSourceTypeAvailable(.Camera)
let photoLibraryIsAvailable = UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary)
override func viewDidLoad() {
super.viewDidLoad()
decoratedNavigationBar.titleLabel.font = VisualConfiguration.navigationBarFont
decoratedNavigationBar.titleLabel.text = "Картинка питомца".uppercaseString
// button "Cancel"
decoratedNavigationBar.setButtonImage("cancel", forButton: .Left, withTintColor: VisualConfiguration.darkGrayColor)
decoratedNavigationBar.leftButton.addTarget(self, action: #selector(cancel(_:)), forControlEvents: .TouchUpInside)
if cameraIsAvailable || photoLibraryIsAvailable { // image can be picked from camera or gallery
// button "Add photo"
decoratedNavigationBar.setButtonImage("camera", forButton: .CenterRight, withTintColor: UIColor.fogColor())
decoratedNavigationBar.centerRightButton.addTarget(self, action: #selector(addPhoto(_:)), forControlEvents: .TouchUpInside)
}
// button "Done"
decoratedNavigationBar.setButtonImage("done", forButton: .Right, withTintColor: VisualConfiguration.darkGrayColor)
decoratedNavigationBar.rightButton.addTarget(self, action: #selector(done(_:)), forControlEvents: .TouchUpInside)
prepareDataSource()
let numberOfCellsInALine: CGFloat = 3
(sectionInset, minimumSpacing, cellSize, cellCornerRadius) = countFlowLayoutValues(forNumberOfCellsInALine: numberOfCellsInALine)
collectionView.alwaysBounceVertical = true
reloadImagesCollection()
}
func prepareDataSource() {
// prepare list of images names
imagesNames = defaultImagesNames
imagesNames = imagesNames.map{ folderName + $0 } // update all names to full form
// set names in random order
var randomOrderImagesNames: [String] = []
for _ in 0..<imagesNames.count {
let ind = Int(arc4random_uniform(UInt32(imagesNames.count)))
randomOrderImagesNames.append(imagesNames.removeAtIndex(ind))
}
imagesNames = randomOrderImagesNames
var petHasCustomImage = false
// place current image name first
if let indexOfCurrentImageName = imagesNames.indexOf(petInitialImageName) { // if current pet's image name is already in list (it is from defaults set), set it first
if indexOfCurrentImageName != 0 {
(imagesNames[0], imagesNames[indexOfCurrentImageName]) = (imagesNames[indexOfCurrentImageName], imagesNames[0])
}
selectedIndex = 0 // initially first image is selected
} else {
if petInitialImageName != VisualConfiguration.noImageName {
// pet has custom image
petHasCustomImage = true
imagesNames.insert(petInitialImageName, atIndex: 0)
selectedIndex = 0 // initially first image is selected
} else {
// pet has no image - only placeholder
selectedIndex = noSelectionIndex
}
}
// store image created with imagesNames
images = []
var defaultImagesStartIndex = 0
if petHasCustomImage {
// must be loaded from disk
images.append(petInitialImage)
defaultImagesStartIndex = 1
}
// the rest pictures are added from .xcassests
for ind in defaultImagesStartIndex..<imagesNames.count {
images.append(UIImage(unsafelyNamed: imagesNames[ind]))
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func reloadImagesCollection() {
collectionView.reloadData()
if selectedIndex != noSelectionIndex {
collectionView.selectItemAtIndexPath(NSIndexPath(forItem: selectedIndex, inSection: 0), animated: false, scrollPosition: .Top)
}
}
func countFlowLayoutValues(forNumberOfCellsInALine numberOfCellsInALine: CGFloat) -> (sectionInset: UIEdgeInsets, minimumSpacing: CGFloat, cellSize: CGSize, cellCornerRadius: CGFloat) {
let maxWidth = view.frame.width
let inset = floor(maxWidth * 3.0 / 100.0)
let sectionInset = UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)
let tempMinimumSpacing = maxWidth * 4.0 / 100.0 // temporary value to be specified
let cellWidth = ceil( (maxWidth - (inset * 2 + tempMinimumSpacing * (numberOfCellsInALine - 1) ) ) / numberOfCellsInALine )
let minimumSpacing = floor( (maxWidth - (inset * 2 + cellWidth * numberOfCellsInALine) ) / (numberOfCellsInALine - 1) )
let cellHeight = cellWidth
let cellSize = CGSize(width: cellWidth, height: cellHeight)
let cellCornerRadius = cellWidth / CGFloat(VisualConfiguration.cornerProportion)
return (sectionInset, minimumSpacing, cellSize, cellCornerRadius)
}
// Cancel-button
func cancel(sender: UIButton) {
// delegate?.petImageViewControllerDidCancel(self)
navigationController?.popViewControllerAnimated(true)
}
// Done-button
func done(sender: UIButton) {
var petNewImageName: String // new image name
if selectedIndex == noSelectionIndex {
petNewImageName = VisualConfiguration.noImageName // no image was selected -> return placeholder image name
} else {
petNewImageName = imagesNames[selectedIndex]
}
if petNewImageName != petInitialImageName { // check whether new name and old name are the same
if selectedIndex == 0 {
if let importedImage = importedImage {
// user selected imported image
delegate?.petImageViewController(self, didSelectNewImage: importedImage, withName: petNewImageName)
} else {
delegate?.petImageViewController(self, didSelectNewImageName: petNewImageName)
}
} else {
delegate?.petImageViewController(self, didSelectNewImageName: petNewImageName)
}
}
navigationController?.popViewControllerAnimated(true)
}
// Camera-button
func addPhoto(sender: UIButton) {
if cameraIsAvailable && photoLibraryIsAvailable {
// both Camera and PhotoLibrary are available - need to present popover to choose
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let pickerOptionsViewController = storyboard.instantiateViewControllerWithIdentifier("ImagePickerOptionsPopoverController") as? ImagePickerOptionsPopoverController {
pickerOptionsViewController.modalPresentationStyle = .Popover
pickerOptionsViewController.delegate = self
if let popoverController = pickerOptionsViewController.popoverPresentationController {
popoverController.delegate = self
popoverController.sourceView = decoratedNavigationBar.centerRightButton.superview
popoverController.permittedArrowDirections = .Up
popoverController.backgroundColor = UIColor.whiteColor()
popoverController.sourceRect = decoratedNavigationBar.centerRightButton.frame
}
presentViewController(pickerOptionsViewController, animated: true, completion: nil)
var popoverWidth: CGFloat = 0.0
var popoverHeight: CGFloat = 0.0
if let filledPopoverWidth = pickerOptionsViewController.filledWidth {
let halfWidth = view.frame.width / 2
popoverWidth = filledPopoverWidth < halfWidth ? halfWidth : filledPopoverWidth
}
if let filledPopoverHeight = pickerOptionsViewController.filledHeight {
popoverHeight = filledPopoverHeight
}
pickerOptionsViewController.preferredContentSize = CGSize(width: popoverWidth, height: popoverHeight)
}
} else {
if cameraIsAvailable {
// only camera is available
getPhotoFrom(.Camera)
} else if photoLibraryIsAvailable {
// only photoLibrary is available
getPhotoFrom(.PhotoLibrary)
}
}
}
func getPhotoFrom(sourceType: UIImagePickerControllerSourceType) {
imagePicker.sourceType = sourceType
if let mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(sourceType) {
let imageMediaTypes = mediaTypes.filter{ $0.lowercaseString.containsString("image") }
imagePicker.mediaTypes = imageMediaTypes
}
if sourceType == .Camera {
imagePicker.cameraCaptureMode = .Photo
}
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion: nil)
}
}
extension PetImageViewController: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagesNames.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier(petImageCellId, forIndexPath: indexPath) as? PetImageCell {
cell.selectedView.backgroundColor = VisualConfiguration.lightOrangeColor
cell.selectedView.cornerProportion = VisualConfiguration.cornerProportion
cell.selectionColor = VisualConfiguration.lightOrangeColor
cell.unSelectionColor = UIColor.clearColor()
cell.selected = indexPath.row == selectedIndex ? true : false
cell.petImageView.image = images[indexPath.row]
cell.petImageView.cornerProportion = VisualConfiguration.cornerProportion
return cell
} else {
return UICollectionViewCell()
}
}
}
extension PetImageViewController: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
if selectedIndex == indexPath.row { // user try to select already selected item
collectionView.deselectItemAtIndexPath(indexPath, animated: false)
selectedIndex = noSelectionIndex
return false
} else {
return true
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// update selectedTypeItemsInd
selectedIndex = indexPath.row
}
}
extension PetImageViewController: UICollectionViewDelegateFlowLayout {
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return cellSize
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return sectionInset
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return minimumSpacing
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return minimumSpacing
}
}
extension PetImageViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
}
}
extension PetImageViewController: ImagePickerOptionsPopoverControllerDelegate {
func popoverDidPickTakingPhotoWithCamera() {
dismissViewControllerAnimated(true, completion: nil)
getPhotoFrom(.Camera)
}
func popoverDidPickGettingPhotoFromLibrary() {
dismissViewControllerAnimated(true, completion: nil)
getPhotoFrom(.PhotoLibrary)
}
}
extension PetImageViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
dismissViewControllerAnimated(false, completion: nil) // dismiss UIImagePickerController
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
// present modal view controller to crop picker image
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let imageCropViewController = storyboard.instantiateViewControllerWithIdentifier("ImageCropViewController") as? ImageCropViewController {
imageCropViewController.photo = pickedImage
imageCropViewController.delegate = self
presentViewController(imageCropViewController, animated: true, completion: nil)
}
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
}
extension PetImageViewController: ImageCropViewControllerDelegate {
func imageCropViewControllerDidCancel(viewController: ImageCropViewController) {
}
func imageCropViewController(viewController: ImageCropViewController, didCropImage image: UIImage) {
selectedIndex = 0
let indexPath = NSIndexPath(forItem: selectedIndex, inSection: 0)
let newImageName = String(NSDate().timeIntervalSince1970)
// user has just imported image for the first time
if importedImage == nil {
imagesNames.insert(newImageName, atIndex: 0)
images.insert(image, atIndex: 0)
collectionView.insertItemsAtIndexPaths([indexPath])
} else {
// some image has been imported -> need to rewrite its cell with new image
imagesNames[0] = newImageName
images[0] = image
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? PetImageCell {
cell.petImageView.image = image
}
}
importedImage = image
collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: .Top)
}
}
|
mit
|
4a8ab48c26489e4cd263c9f5e9659f03
| 37.622829 | 187 | 0.734404 | 5.527344 | false | false | false | false |
lieonCX/Live
|
Live/View/Common/BasePlayerVC.swift
|
1
|
8375
|
//
// BasePlayerVC.swift
// Live
//
// Created by lieon on 2017/7/7.
// Copyright © 2017年 ChengDuHuanLeHui. All rights reserved.
//
import UIKit
class BasePlayerVC: BaseViewController {
lazy var txLivePlayer: TXLivePlayer = TXLivePlayer()
lazy var avatarImgeView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "placeholderImage_avatar")
return imageView
}()
lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.backgroundColor = .clear
scrollView.isPagingEnabled = true
scrollView.bounces = false
scrollView.showsHorizontalScrollIndicator = false
return scrollView
}()
lazy var svcontainerView: UIView = {
let view = UIView()
view.backgroundColor = .clear
return view
}()
lazy var containerView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.clear
return view
}()
lazy var nameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12)
label.textAlignment = .left
label.textColor = UIColor.white
return label
}()
lazy var viplevLabel: UILabel = {
let viplevLabel = UILabel()
viplevLabel.font = UIFont.systemFont(ofSize: 11)
viplevLabel.textAlignment = .center
viplevLabel.textColor = UIColor.white
viplevLabel.layer.masksToBounds = true
viplevLabel.layer.cornerRadius = 8
return viplevLabel
}()
lazy var collectionBtn: UIButton = {
let btn = UIButton()
btn.setImage(UIImage(named: "guanzhu_normal"), for: .normal)
btn.setImage(UIImage(named: "details_iscollect_btn"), for: .selected)
return btn
}()
lazy var closeBtn: UIButton = {
let btn = UIButton()
btn.imageView?.contentMode = .center
btn.setImage(UIImage(named: "common_close@3x"), for: .normal)
btn.setImage(UIImage(named: "common_close@3x"), for: .highlighted)
return btn
}()
lazy var IDlabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 11)
label.textAlignment = .left
label.text = "1231231233"
label.textColor = UIColor.white
return label
}()
lazy var seecountLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 11)
label.textAlignment = .center
label.textColor = UIColor.white
return label
}()
lazy var viewerView: ViewerView = ViewerView()
lazy var coverImageView: UIImageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
setupAllContainerView()
setupUserTagView()
setupPlayer()
setupViewerView()
setupIDView()
setupCover()
}
}
extension BasePlayerVC {
fileprivate func setupAllContainerView() {
svcontainerView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
scrollView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
scrollView.contentSize = CGSize(width: view.bounds.width * 2, height: 0)
scrollView.contentOffset = CGPoint(x: view.bounds.width, y: 0)
view.addSubview( svcontainerView)
svcontainerView.addSubview(scrollView)
containerView.frame = CGRect(x: view.bounds.width, y: 0, width: view.bounds.width, height: view.bounds.height)
scrollView.addSubview(containerView)
}
fileprivate func setupUserTagView() {
//room_header_bgView@3x
let bgView : UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 80))
bgView.image = UIImage(named: "room_header_bgView")
bgView.isUserInteractionEnabled = true
containerView.addSubview(bgView)
let view = UIView()//底层的透明
view.backgroundColor = UIColor(hex: 0x605c56, alpha: 0.5)
view.layer.cornerRadius = 20
view.layer.masksToBounds = true
containerView.addSubview(view)
view.addSubview(avatarImgeView)
view.addSubview(seecountLabel)
avatarImgeView.layer.cornerRadius = 17
avatarImgeView.layer.masksToBounds = true
view.addSubview(nameLabel)
view.addSubview(collectionBtn)
view.snp.makeConstraints { (maker) in
maker.left.equalTo(12)
maker.top.equalTo(35)
maker.width.equalTo(150)
maker.height.equalTo(40)
}
avatarImgeView.snp.makeConstraints { (maker) in
maker.left.equalTo(2)
maker.centerY.equalTo(view.snp.centerY)
maker.width.equalTo(34)
maker.height.equalTo(34)
}
nameLabel.snp.makeConstraints { (maker) in
maker.left.equalTo(avatarImgeView.snp.right).offset(4)
maker.top.equalTo(5)
maker.width.equalTo(50)
}
view.addSubview(viplevLabel)
viplevLabel.snp.makeConstraints { (maker) in
maker.left.equalTo(nameLabel.snp.left)
maker.bottom.equalTo(-2)
maker.height.equalTo(16)
maker.width.equalTo(32)
}
seecountLabel.snp.makeConstraints { (maker) in
maker.left.equalTo(viplevLabel.snp.right).offset(12)
maker.bottom.equalTo(-2)
maker.height.equalTo(16)
}
collectionBtn.snp.makeConstraints { (maker) in
maker.right.equalTo(-10)
maker.centerY.equalTo(avatarImgeView.snp.centerY)
maker.size.equalTo(CGSize(width: 16, height: 16))
}
}
fileprivate func setupPlayer() {
txLivePlayer.enableHWAcceleration = true
txLivePlayer.setupVideoWidget(svcontainerView.bounds, contain: svcontainerView, insert: 0)
}
fileprivate func setupViewerView() {
viewerView.backgroundColor = .clear
containerView.addSubview(viewerView)
viewerView.snp.makeConstraints { (maker) in
maker.right.equalTo(-45)
maker.top.equalTo(35)
maker.height.equalTo(40)
maker.width.equalTo(34 * 4)
}
containerView.addSubview(closeBtn)
closeBtn.snp.makeConstraints { (maker) in
maker.right.equalTo(-12)
maker.centerY.equalTo(viewerView.snp.centerY)
maker.width.equalTo(45)
maker.height.equalTo(30)
}
}
fileprivate func setupIDView() {
let view = UIView()
view.backgroundColor = .clear
view.layer.cornerRadius = 9
view.layer.masksToBounds = true
containerView.addSubview(view)
view.snp.makeConstraints { (maker) in
maker.right.equalTo(-15)
maker.top.equalTo(35 + 40 + 5)
maker.width.equalTo(145)
maker.height.equalTo(18)
}
view.addSubview(IDlabel)
IDlabel.snp.makeConstraints { (maker) in
maker.right.equalTo(view.snp.right).offset(-5)
maker.centerY.equalTo(view.snp.centerY)
}
let beanLabel = UILabel()
beanLabel.text = "哆集直播ID: "
beanLabel.textColor = UIColor.white
beanLabel.font = UIFont.systemFont(ofSize: 11)
view.addSubview(beanLabel)
beanLabel.snp.makeConstraints { (maker) in
maker.right.equalTo(IDlabel.snp.left).offset(5)
maker.centerY.equalTo(view.snp.centerY)
}
let cover = UILabel()
cover.backgroundColor = UIColor(hex: 0x605c56, alpha: 0.5)
cover.layer.cornerRadius = 9
cover.layer.masksToBounds = true
view.insertSubview(cover, at: 0)
cover.snp.makeConstraints { (maker) in
maker.left.equalTo(beanLabel.snp.left).offset(-5)
maker.top.equalTo(view.snp.top)
maker.bottom.equalTo(view.snp.bottom)
maker.right.equalTo(IDlabel.snp.right).offset(5)
}
}
fileprivate func setupCover() {
coverImageView.backgroundColor = .red
coverImageView.frame = containerView.bounds
view.insertSubview(coverImageView, at: 0)
}
}
|
mit
|
4fc8dc17a7b8f17e3964fff0a6cac819
| 33.953975 | 118 | 0.611922 | 4.401475 | false | false | false | false |
hhroc/yellr-ios
|
Yellr/Yellr/YellrConstants.swift
|
1
|
5259
|
//
// YellrConstants.swift
// Yellr
//
// Created by Debjit Saha on 6/1/15.
// Copyright (c) 2015 wxxi. All rights reserved.
//
import Foundation
struct YellrConstants {
//Before Publishing to app store, change:
//1. DevMode to false
//2. endPoint to production endpoint
struct AppInfo {
static let Name = "Yellr"
static let version = "0.1.9"
static let DevMode = true
}
struct API {
static let endPoint = "https://yellr.net"
//static let endPoint = "http://yellr.mycodespace.net"
}
struct Direction {
static let Longitude = "ylr_longitude"
static let Latitude = "ylr_latitude"
}
struct Common {
static let CancelButton = "cancel_button_text"
static let BackButton = "back_button_text"
}
struct TagIds {
static let AddPostImageView = 221
static let AddPostVideoView = 222
static let AddPostAudioView = 223
static let BottomTabLocal = 1201
static let BottomTabAssignments = 1202
static let BottomTabStories = 1203
static let AddPostAudioButtonRecord = 331
static let AddPostAudioButtonPlay = 332
static let AddPostAudioButtonStop = 333
}
struct Keys {
static let StoredStoriesCount = "stored_stories_count_key"
static let StoredAssignmentsCount = "stored_assignments_count_key"
static let CUIDKeyName = "ycuid"
static let RepliedToAssignments = "replied_to_assignments"
static let PostListKeyName = "post_list_key"
static let FirstTimeUserKey = "first_time_user_key"
static let SeenAssignments = "seen_assignments"
}
struct LocalPosts {
static let Title = "local_post_title"
static let AnonymousUser = "anonymous_user"
//first time alert
static let FirstTimeTitle = "new_user_welcome_title"
static let FirstTimeMessage = "new_user_welcome_message"
static let FirstTimeOkay = "new_user_welcome_okay"
}
struct LocalPostDetail {
static let ReportTitle = "local_post_detail_title"
static let ReportMessage = "local_post_detail_message"
static let ReportOkay = "local_post_detail_okay"
}
struct Assignments {
static let Title = "assignments_title"
}
struct Stories {
static let Title = "stories_title"
}
struct Profile {
static let Title = "profile_title"
static let ResetCUIDButton = "profile_reset_cuid_button"
static let PostsLabel = "profile_posts_label"
static let PostsViewedLabel = "profile_posts_viewed_label"
static let PostsUsedLabel = "profile_posts_used_label"
static let Unverified = "profile_unverified"
static let ResetDialogTitle = "profile_reset_dialog_title"
static let ResetDialogMessage = "profile_reset_dialog_message"
static let ResetDialogConfirm = "profile_reset_dialog_confirm"
}
struct VerifyProfile {
static let Title = "verify_profile_title"
}
struct AddPost {
static let Title = "new_post_title"
static let FailMsg = "new_post_failed"
static let FailMsgEmptyPost = "new_post_failed_empty_text"
static let FailMsgLocation = "new_post_failed_empty_location"
static let SuccessMsg = "new_post_success"
static let PopMenuTitle = "new_post_pop_menu_title"
static let PopMenuTitleVideo = "new_post_pop_menu_title_video"
static let PopMenuCamera = "new_post_pop_menu_camera"
static let PopMenuGallery = "new_post_pop_menu_gallery"
static let PopMenuCancel = "new_post_pop_menu_cancel"
//first time alert
static let FirstTimeTitle = "new_post_first_time_alert_title"
static let FirstTimeMessage = "new_post_first_time_alert_message"
static let FirstTimeOkay = "new_post_first_time_alert_okay"
//to show the one time screen after free / assgn post
static let checkVersionOnce = "check_version"
static let checkVersionOnceAs = "check_version_as"
}
struct Location {
static let Title = "location_error_title"
static let Message = "location_error_message"
static let Okay = "location_error_okay"
}
struct ApiMethods {
static let get = ""
}
struct Colors {
static let blue:UInt = 0x2980b9;
static let dark_blue:UInt = 0x2c3e50;
static let yellow:UInt = 0xFFD40C;
static let dark_yellow:UInt = 0xF2BF00;
static let light_yellow:UInt = 0xFFF22A;
static let very_light_yellow:UInt = 0xFFEE9E;
static let white:UInt = 0xffffff;
static let black:UInt = 0x2f2f2f;
static let red:UInt = 0xff6347;
static let down_vote_red:UInt = 0xff6347;
static let green:UInt = 0x1abc9c;
static let up_vote_green:UInt = 0x1abc9c;
static let grey:UInt = 0x444444;
static let light_grey:UInt = 0xbbbbbb;
static let very_light_grey:UInt = 0xe8e8e8;
static let assignment_response_grey:UInt = 0xe0e0e0;
static let background:UInt = 0xeeeeee;
}
}
|
mit
|
d0fe962e966b47b4aa37ef0069c959a1
| 33.834437 | 74 | 0.637384 | 3.9217 | false | false | false | false |
cdmx/MiniMancera
|
miniMancera/View/Settings/VSettingsHeader.swift
|
1
|
3485
|
import UIKit
class VSettingsHeader:UICollectionReusableView
{
private weak var controller:CSettings?
private let kBackButtonWidth:CGFloat = 70
private let kVersionHeight:CGFloat = 30
private let kVersionBottom:CGFloat = -80
private let kVersionKey:String = "CFBundleShortVersionString"
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.center
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = #imageLiteral(resourceName: "assetGenericLogoSmall")
let labelVersion:UILabel = UILabel()
labelVersion.translatesAutoresizingMaskIntoConstraints = false
labelVersion.backgroundColor = UIColor.clear
labelVersion.isUserInteractionEnabled = false
labelVersion.textAlignment = NSTextAlignment.center
labelVersion.font = UIFont.game(size:15)
labelVersion.textColor = UIColor.white
let backButton:UIButton = UIButton()
backButton.translatesAutoresizingMaskIntoConstraints = false
backButton.setImage(
#imageLiteral(resourceName: "assetGenericBack").withRenderingMode(UIImageRenderingMode.alwaysOriginal),
for:UIControlState.normal)
backButton.setImage(
#imageLiteral(resourceName: "assetGenericBack").withRenderingMode(UIImageRenderingMode.alwaysTemplate),
for:UIControlState.highlighted)
backButton.imageView!.tintColor = UIColor(white:1, alpha:0.2)
backButton.imageView!.clipsToBounds = true
backButton.imageView!.contentMode = UIViewContentMode.center
backButton.addTarget(
self,
action:#selector(actionBack(sender:)),
for:UIControlEvents.touchUpInside)
addSubview(imageView)
addSubview(labelVersion)
addSubview(backButton)
NSLayoutConstraint.equals(
view:imageView,
toView:self)
NSLayoutConstraint.equalsVertical(
view:backButton,
toView:self)
NSLayoutConstraint.leftToLeft(
view:backButton,
toView:self)
NSLayoutConstraint.width(
view:backButton,
constant:kBackButtonWidth)
NSLayoutConstraint.bottomToBottom(
view:labelVersion,
toView:self,
constant:kVersionBottom)
NSLayoutConstraint.height(
view:labelVersion,
constant:kVersionHeight)
NSLayoutConstraint.equalsHorizontal(
view:labelVersion,
toView:self)
guard
let bundleDictionary:[String:Any] = Bundle.main.infoDictionary
else
{
return
}
let versionString:String? = bundleDictionary[kVersionKey] as? String
labelVersion.text = versionString
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: actions
func actionBack(sender button:UIButton)
{
controller?.back()
}
//MARK: public
func config(controller:CSettings)
{
self.controller = controller
}
}
|
mit
|
433139f8b00665f74001bcc7a32f4433
| 31.268519 | 115 | 0.637877 | 5.936968 | false | false | false | false |
NemProject/NEMiOSApp
|
NEMWallet/Assets/Supporting Files/Cryptography/RIPEMD-160/RIPEMD+Block.swift
|
1
|
7102
|
extension RIPEMD {
public struct Block {
public init() {}
var message: [UInt32] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
// Initial values
var h₀: UInt32 = 0x67452301
var h₁: UInt32 = 0xEFCDAB89
var h₂: UInt32 = 0x98BADCFE
var h₃: UInt32 = 0x10325476
var h₄: UInt32 = 0xC3D2E1F0
public var hash: [UInt32] {
return [h₀, h₁, h₂, h₃, h₄]
}
// FIXME: Make private as! soon as! tests support that
public mutating func compress (_ message: [UInt32]) -> () {
assert(message.count == 16, "Wrong message size")
var Aᴸ = h₀
var Bᴸ = h₁
var Cᴸ = h₂
var Dᴸ = h₃
var Eᴸ = h₄
var Aᴿ = h₀
var Bᴿ = h₁
var Cᴿ = h₂
var Dᴿ = h₃
var Eᴿ = h₄
for j in 0...79 {
// Left side
let wordᴸ = message[r.left[j]]
let functionᴸ = f(j)
let Tᴸ: UInt32 = ((Aᴸ &+ functionᴸ(Bᴸ,Cᴸ,Dᴸ) &+ wordᴸ &+ K.left[j]) ~<< s.left[j]) &+ Eᴸ
Aᴸ = Eᴸ
Eᴸ = Dᴸ
Dᴸ = Cᴸ ~<< 10
Cᴸ = Bᴸ
Bᴸ = Tᴸ
// Right side
let wordᴿ = message[r.right[j]]
let functionᴿ = f(79 - j)
let Tᴿ: UInt32 = ((Aᴿ &+ functionᴿ(Bᴿ,Cᴿ,Dᴿ) &+ wordᴿ &+ K.right[j]) ~<< s.right[j]) &+ Eᴿ
Aᴿ = Eᴿ
Eᴿ = Dᴿ
Dᴿ = Cᴿ ~<< 10
Cᴿ = Bᴿ
Bᴿ = Tᴿ
}
let T = h₁ &+ Cᴸ &+ Dᴿ
h₁ = h₂ &+ Dᴸ &+ Eᴿ
h₂ = h₃ &+ Eᴸ &+ Aᴿ
h₃ = h₄ &+ Aᴸ &+ Bᴿ
h₄ = h₀ &+ Bᴸ &+ Cᴿ
h₀ = T
}
public func f (_ j: Int) -> ((UInt32, UInt32, UInt32) -> UInt32) {
switch j {
case _ where j < 0:
assert(false, "Invalid j")
return {(_, _, _) in 0 }
case _ where j <= 15:
return {(x, y, z) in x ^ y ^ z }
case _ where j <= 31:
return {(x, y, z) in (x & y) | (~x & z) }
case _ where j <= 47:
return {(x, y, z) in (x | ~y) ^ z }
case _ where j <= 63:
return {(x, y, z) in (x & z) | (y & ~z) }
case _ where j <= 79:
return {(x, y, z) in x ^ (y | ~z) }
default:
assert(false, "Invalid j")
return {(_, _, _) in 0 }
}
}
public enum K {
case left, right
public subscript(j: Int) -> UInt32 {
switch j {
case _ where j < 0:
assert(false, "Invalid j")
return 0
case _ where j <= 15:
return self == .left ? 0x00000000 : 0x50A28BE6
case _ where j <= 31:
return self == .left ? 0x5A827999 : 0x5C4DD124
case _ where j <= 47:
return self == .left ? 0x6ED9EBA1 : 0x6D703EF3
case _ where j <= 63:
return self == .left ? 0x8F1BBCDC : 0x7A6D76E9
case _ where j <= 79:
return self == .left ? 0xA953FD4E : 0x00000000
default:
assert(false, "Invalid j")
return 0
}
}
}
public enum r {
case left, right
public subscript (j: Int) -> Int {
switch j {
case _ where j < 0:
assert(false, "Invalid j")
return 0
case let index where j <= 15:
if self == .left {
return index
} else {
return [5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12][index]
}
case let index where j <= 31:
if self == .left {
return [ 7, 4,13, 1,10, 6,15, 3,12, 0, 9, 5, 2,14,11, 8][index - 16]
} else {
return [ 6,11, 3, 7, 0,13, 5,10,14,15, 8,12, 4, 9, 1, 2][index - 16]
}
case let index where j <= 47:
if self == .left {
return [3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12][index - 32]
} else {
return [15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13][index - 32]
}
case let index where j <= 63:
if self == .left {
return [1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2][index - 48]
} else {
return [8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14][index - 48]
}
case let index where j <= 79:
if self == .left {
return [ 4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13][index - 64]
} else {
return [12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11][index - 64]
}
default:
assert(false, "Invalid j")
return 0
}
}
}
public enum s {
case left, right
public subscript(j: Int) -> Int {
switch j {
case _ where j < 0:
assert(false, "Invalid j")
return 0
case _ where j <= 15:
return (self == .left ? [11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8] : [8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6])[j]
case _ where j <= 31:
return (self == .left ? [7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12] : [9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11])[j - 16]
case _ where j <= 47:
return (self == .left ? [11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5] : [9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5])[j - 32]
case _ where j <= 63:
return (self == .left ? [11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12] : [15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8])[j - 48]
case _ where j <= 79:
return (self == .left ? [9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6] : [8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11])[j - 64]
default:
assert(false, "Invalid j")
return 0
}
}
}
}
}
|
mit
|
0c1cff9c331af18b39bc43d2cf2cf032
| 35.240838 | 138 | 0.350621 | 3.188392 | false | false | false | false |
r9ronaldozhang/ZYColumnViewController
|
ZYColumnViewDemo/ZYColumnViewDemo/ZYColumnView/ZYColumnSpreadView.swift
|
1
|
18180
|
//
// ZYColumnSpreadView.swift
// 掌上遂宁
//
// Created by 张宇 on 2016/10/10.
// Copyright © 2016年 张宇. All rights reserved.
//
import UIKit
// 上面item点击的闭包
typealias upItemTapClosure = (_ item : ZYColumnItem) -> Void
// 上面item长按的闭包
typealias upItemLongPressClosure = () -> Void
// 收起spreadView闭包
typealias foldSpreadViewClosure = (_ upTitles : [String] , _ downTitles : [String]) -> Void
class ZYColumnSpreadView: UIScrollView {
// 上面的排序 标题 数组
open var arrayUpTitles = [String]()
// 下面的备选 标题 数组
open var arrayDownTitles = [String]()
// 固定不变的item个数
open var fixedCount = 1
// 标识当前是否排序状态
open var isSortStatus = false
// 上面item tap 的闭包
open var tapClosure : upItemTapClosure?
// 上面item长按闭包
open var longPressClosure : upItemLongPressClosure?
// 收起后的闭包
open var flodClosure : foldSpreadViewClosure?
/************* 上面是对外属性 -----华丽分割线----- 下面是私有属性 ***************/
// 存放up items的数组
fileprivate var arrayUpItems = [ZYColumnItem!]()
// 存放down items 的数组
fileprivate var arrayDownItems = [ZYColumnItem!]()
// 拖动view的下一个view的中心点 逐个赋值
fileprivate var valuePoint = CGPoint(x: 0, y: 0)
// 用于赋值
fileprivate var nextPoint = CGPoint(x: 0, y: 0)
// 下提示view
fileprivate lazy var downPromptView : ZYColumnDownPromptView = {
let upLastItem = self.arrayUpItems.last
let downView = ZYColumnDownPromptView(frame: CGRect(x: 0, y: upLastItem!.frame.maxY + kColumnMarginH, width: ZYScreenWidth, height: kColumnViewH))
downView.backgroundColor = UIColor.init(red: 240.0/255, green: 241.0/255, blue: 246.0/255, alpha: 1.0)
return downView
}()
}
// MARK: - 公共方法
extension ZYColumnSpreadView {
/// 展开或者合拢
open func doSpreadOrFold(toSpread : Bool , cover : UIView , upPromptView : UIView) {
UIApplication.shared.keyWindow?.isUserInteractionEnabled = false
UIView.animate(withDuration: kSpreadDuration, animations: { [weak self]() -> Void in
self?.frame = CGRect(x: 0, y: 0, width: kColumnViewW, height: toSpread ? kSpreadMaxH : 0.0)
}) {(_) -> Void in
upPromptView.isHidden = toSpread ? false : true
cover.isHidden = toSpread ? false : true
UIApplication.shared.keyWindow?.isUserInteractionEnabled = true
}
// 添加items
if toSpread && arrayUpItems.isEmpty {
addItems()
}
// 闭包回传值
if self.flodClosure != nil && !toSpread {
// 同步数组顺序
arrayUpTitles.removeAll()
arrayDownTitles.removeAll()
for i in 0 ..< arrayUpItems.count {
let item = arrayUpItems[i]!
arrayUpTitles.append(item.title)
}
for i in 0 ..< arrayDownItems.count {
let item = arrayDownItems[i]!
arrayDownTitles.append(item.title)
}
self.flodClosure!(arrayUpTitles, arrayDownTitles)
}
}
/// 隐藏或者显示下面的item和downPromptView 参数传false 则变为 显示
open func hideDownItemsAndPromptView(toHide : Bool) {
if arrayDownItems.isEmpty { // 下面备选只要没有,一定不显示
downPromptView.isHidden = true
} else {
downPromptView.isHidden = toHide
}
for i in 0 ..< arrayDownItems.count {
let item : ZYColumnItem = arrayDownItems[i]
item.isHidden = toHide
}
}
/// 开启或者关闭排序按钮删除状态
open func openDelStatus(showDel : Bool) {
for i in 0 ..< arrayUpItems.count {
let item : ZYColumnItem = arrayUpItems[i]
if !item.isFixed {
item.delBtn.isHidden = !showDel
}
}
}
/// 自动回滚到顶部
open func scrollToTop() {
var offect = self.contentOffset;
offect.y = -self.contentInset.top;
self.setContentOffset(offect, animated: false)
}
}
// MARK: - 私有控制方法
extension ZYColumnSpreadView {
// 通过index 计算出上面item的frame
fileprivate func getUpFrameWithIndex(_ index : Int) -> CGRect {
let x = CGFloat(index%kColumnLayoutCount) * (kColumnMarginW + kColumnItemW) + kColumnMarginW
let y = CGFloat(index/kColumnLayoutCount) * (kColumnMarginH + kColumnItemH) + kColumnMarginH + kColumnViewH
let frame = CGRect(x: x, y: y, width: kColumnItemW, height: kColumnItemH)
return frame
}
// 从下面移动到上面
fileprivate func addItemToUp(item : ZYColumnItem) {
let lastItem = arrayUpItems.last
// 判断下面的item是否需要下移
if (lastItem!.tag + 1) % kColumnLayoutCount == 0 {
moveItemsRowDownOrUp(isUp: false)
}
let newFrame = getUpFrameWithIndex(lastItem!.tag + 1)
UIView.animate(withDuration: kSpreadDuration, animations: {
item.frame = newFrame
}) { (_) in
self.reSetContentSize()
}
}
// 将arrayDownItems 的items 整体下移或者上移一行 包含downPromptView
private func moveItemsRowDownOrUp(isUp : Bool) {
let rowH = isUp ? -(kColumnItemH + kColumnMarginH) : (kColumnItemH + kColumnMarginH)
downPromptView.frame = CGRect(x: downPromptView.frame.origin.x, y: downPromptView.frame.origin.y+rowH, width: downPromptView.frame.width, height: downPromptView.frame.height)
for i in 0 ..< arrayDownItems.count {
let item = arrayDownItems[i]!
item.frame = CGRect(x: item.frame.origin.x, y: item.frame.origin.y+rowH, width: item.frame.width, height: item.frame.height)
}
}
// 从上面删除 item插入到下面
fileprivate func removeItemFromUp(item : ZYColumnItem) {
item.delBtn.isHidden = true
item.isHidden = true
reLayoutUpItemsWithAnimation()
reLayoutDownItemsWithAnimation(withAnimate: false)
let lastItem = arrayUpItems.last
if (lastItem!.tag + 1)%kColumnLayoutCount == 0 {
moveItemsRowDownOrUp(isUp: true)
}
reSetContentSize()
}
fileprivate func synchronizeItemsTag() {
var x = 0
for i in 0 ..< arrayUpItems.count {
let item = arrayUpItems[i]!
item.tag = i
x += 1
}
var j = x
for y in 0 ..< arrayDownItems.count {
let item = arrayDownItems[y]!
item.tag = j
j += 1
}
}
// 重新计算最新的contentSize
private func reSetContentSize() {
let lastItem = arrayDownItems.isEmpty ? arrayUpItems.last : arrayDownItems.last
self.contentSize = CGSize(width: 0, height: lastItem!.frame.maxY + kColumnMarginH)
}
// 点击后 动态排序上面的item
private func reLayoutUpItemsWithAnimation(){
for i in 0 ..< arrayUpItems.count {
let item = arrayUpItems[i]!
let newFrame = getUpFrameWithIndex(item.tag)
UIView.animate(withDuration: kSpreadDuration, animations: {
item.frame = newFrame
})
}
}
// 点击后 动态排序下面的item
fileprivate func reLayoutDownItemsWithAnimation(withAnimate : Bool) {
for i in 0 ..< arrayDownItems.count {
let item = arrayDownItems[i]!
let x = CGFloat((item.tag - arrayUpItems.count) % kColumnLayoutCount) * (kColumnMarginW + kColumnItemW) + kColumnMarginW
let y = CGFloat((item.tag - arrayUpItems.count) / kColumnLayoutCount) * (kColumnMarginH + kColumnItemH) + kColumnMarginH + downPromptView.frame.maxY
if withAnimate {
UIView.animate(withDuration: kSpreadDuration, animations: {
item.frame = CGRect(x: x, y: y, width: item.frame.width, height: item.frame.height)
})
} else {
item.frame = CGRect(x: x, y: y, width: item.frame.width, height: item.frame.height)
}
}
}
// 删除图标点击闭包回调处理
fileprivate func handleClosure (item : ZYColumnItem) {
guard !item.isFixed else {
return
}
// 从上面数组移除item 添加到下面数组
arrayUpItems.remove(at: item.tag)
arrayDownItems.insert(item, at: 0)
synchronizeItemsTag()
removeItemFromUp(item: item)
}
}
// MARK: - 初始化 上 下 item 和 downPromptView
extension ZYColumnSpreadView {
fileprivate func addItems(){
// 添加上面 items
for i in 0 ..< arrayUpTitles.count {
let item = ZYColumnItem(frame: getUpFrameWithIndex(i)) // 通过公共方法计算frame
item.title = arrayUpTitles[i]
item.tag = i
if i < fixedCount {
item.isFixed = true
}
// 闭包回调
item.delClosure = {
[weak self](item : ZYColumnItem) -> Void in
self!.handleClosure(item: item)
}
// 添加长按手势
addLongPressGesture(item: item)
// 添加tap手势
addTapGesture(item: item)
addSubview(item)
arrayUpItems.append(item)
}
let upLastItem = arrayUpItems.last
// 添加下提示view
insertSubview(downPromptView, at: 0)
guard !arrayDownTitles.isEmpty else {
// 下面没有备选 直接算出spreadView contentSize
self.contentSize = CGSize(width: 0, height: upLastItem!.frame.maxY + kColumnMarginH + downPromptView.frame.height)
return
}
// 添加下排序items
for i in 0 ..< arrayDownTitles.count {
let x = CGFloat(i%kColumnLayoutCount) * (kColumnMarginW + kColumnItemW) + kColumnMarginW
let y = CGFloat(i/kColumnLayoutCount) * (kColumnMarginH + kColumnItemH) + kColumnMarginH + downPromptView.frame.maxY
let item = ZYColumnItem(frame: CGRect(x: x, y: y, width: kColumnItemW, height: kColumnItemH))
item.title = arrayDownTitles[i]
item.tag = i + arrayUpItems.count
// 添加长按手势
addLongPressGesture(item: item)
// 添加tap手势
addTapGesture(item: item)
// 闭包回调
item.delClosure = {
[weak self](item : ZYColumnItem) -> Void in
self!.handleClosure(item: item)
}
addSubview(item)
arrayDownItems.append(item)
if i == arrayDownTitles.count - 1 {
let downLastItem = arrayDownItems.last
self.contentSize = CGSize(width: 0, height: downLastItem!.frame.maxY + kColumnMarginH)
}
}
}
}
// MARK: - 手势绑定 与手势处理
extension ZYColumnSpreadView {
/// 为一个item绑定长按手势
fileprivate func addLongPressGesture(item : ZYColumnItem) {
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.upItmesDidLongPress(longPress:)))
item.addGestureRecognizer(longPressGesture)
}
/// item 长按手势处理
@objc fileprivate func upItmesDidLongPress(longPress: UILongPressGestureRecognizer) {
let item = longPress.view as! ZYColumnItem
if item.isFixed { // 固定的item 不做处理
return
}
// 只响应上面的item的长按事件
for i in 0 ..< arrayUpItems.count {
let element = arrayUpItems[i]
if element == item {
handleLongPressGesture(item: item, longPress: longPress)
return
}
}
}
/// 为一个item绑定tap手势
fileprivate func addTapGesture(item : ZYColumnItem) {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.itemDidTap(tapGesture:)))
item.addGestureRecognizer(tapGesture)
}
// item tap事件处理
@objc fileprivate func itemDidTap(tapGesture : UITapGestureRecognizer) {
let item = tapGesture.view as! ZYColumnItem
// 点击的是上面的item 回传值
for i in 0 ..< arrayUpItems.count {
let element = arrayUpItems[i]
if element == item {
if isSortStatus {
return
}
// 闭包传值
if self.tapClosure != nil {
self.tapClosure!(item)
}
return
}
}
// 点击的是下面的item 上移
for i in 0 ..< arrayDownItems.count {
let element = arrayDownItems[i]
if element == item {
addItemToUp(item: item)
arrayDownItems.remove(at: item.tag - arrayUpItems.count)
arrayUpItems.append(item)
synchronizeItemsTag()
reLayoutDownItemsWithAnimation(withAnimate: true)
if arrayDownItems.isEmpty { // 当最后一个item都上移了,下面的指示view 隐藏掉
downPromptView.isHidden = true
}
return
}
}
}
private func handleLongPressGesture(item : ZYColumnItem, longPress : UILongPressGestureRecognizer) {
// 拿到当前的最新位置
let recognizerPoint = longPress.location(in: self)
switch longPress.state {
case UIGestureRecognizerState.began:
// 如果没有显示“删除”按钮,回传闭包,开启删除排序模式
if !isSortStatus {
if longPressClosure != nil {
longPressClosure!()
}
}
// 禁用其他item的交互
for i in 0 ..< arrayUpItems.count {
let element = arrayUpItems[i]!
if element != item {
element.isUserInteractionEnabled = false
}
}
self.bringSubview(toFront: item)
valuePoint = item.center
item.scaleItemToLarge()
case UIGestureRecognizerState.changed:
// 更新长按item的位置
item.center = recognizerPoint
// 判断item的center是否移动到了其他item的位置上了
for i in 0 ..< arrayUpItems.count {
let element = arrayUpItems[i]!
if element.frame.contains(item.center) && element != item && element.tag >= fixedCount {
// 开始位置索引
let fromIndex = item.tag
// 需要移动到的索引
let toIndex = element.tag
if toIndex > fromIndex { // 往后移
// 把移动view的下一个view移动到记录的view的位置(valuePoint),并把下一view的位置记为新的nextPoint,并把view的tag值-1,依次类推
UIView.animate(withDuration: kSpreadDuration, animations: {
for i in fromIndex + 1 ... toIndex {
let nextItem = self.viewWithTag(i) as! ZYColumnItem
self.nextPoint = nextItem.center
nextItem.center = self.valuePoint
self.valuePoint = self.nextPoint
nextItem.tag -= 1
}
item.tag = toIndex
})
} else { // 往前移
// 把移动view的上一个view移动到记录的view的位置(valuePoint),并把上一view的位置记为新的nextPoint,并把view的tag值+1,依次类推
UIView.animate(withDuration: kSpreadDuration, animations: {
for i in (toIndex ... fromIndex - 1).reversed(){
let nextItem = self.viewWithTag(i) as! ZYColumnItem
self.nextPoint = nextItem.center
nextItem.center = self.valuePoint
self.valuePoint = self.nextPoint
nextItem.tag += 1
}
item.tag = toIndex
})
}
}
}
case UIGestureRecognizerState.ended:
// 恢复其他item的交互
for i in 0 ..< arrayUpItems.count {
let element = arrayUpItems[i]!
if element != item {
element.isUserInteractionEnabled = true
}
}
// 还原item的大小
item.scaleItemToOriginal()
// 返回对应的中心点
UIView.animate(withDuration: kSpreadDuration, animations: {
})
UIView.animate(withDuration: kSpreadDuration, animations: {
item.center = self.valuePoint
}, completion: { [weak self](_) in
// 同步数组
var temp = [ZYColumnItem!]()
for i in 0 ..< self!.arrayUpItems.count {
for j in 0 ..< self!.arrayUpItems.count {
let item = self!.arrayUpItems[j]!
if item.tag == i {
temp.append(item)
break
}
}
}
self!.arrayUpItems = temp
})
default:
break
}
}
}
|
mit
|
b67cb0149a2ce6473e55e0ccb8996d49
| 36.724832 | 182 | 0.548301 | 4.36639 | false | false | false | false |
alblue/swift
|
test/expr/closure/closures.swift
|
2
|
13945
|
// RUN: %target-typecheck-verify-swift
var func6 : (_ fn : (Int,Int) -> Int) -> ()
var func6a : ((Int, Int) -> Int) -> ()
var func6b : (Int, (Int, Int) -> Int) -> ()
func func6c(_ f: (Int, Int) -> Int, _ n: Int = 0) {}
// Expressions can be auto-closurified, so that they can be evaluated separately
// from their definition.
var closure1 : () -> Int = {4} // Function producing 4 whenever it is called.
var closure2 : (Int,Int) -> Int = { 4 } // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{36-36= _,_ in}}
var closure3a : () -> () -> (Int,Int) = {{ (4, 2) }} // multi-level closing.
var closure3b : (Int,Int) -> (Int) -> (Int,Int) = {{ (4, 2) }} // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{52-52=_,_ in }}
var closure4 : (Int,Int) -> Int = { $0 + $1 }
var closure5 : (Double) -> Int = {
$0 + 1.0
// expected-error@+1 {{cannot convert value of type 'Double' to closure result type 'Int'}}
}
var closure6 = $0 // expected-error {{anonymous closure argument not contained in a closure}}
var closure7 : Int =
{ 4 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{9-9=()}}
var capturedVariable = 1
var closure8 = { [capturedVariable] in
capturedVariable += 1 // expected-error {{left side of mutating operator isn't mutable: 'capturedVariable' is an immutable capture}}
}
func funcdecl1(_ a: Int, _ y: Int) {}
func funcdecl3() -> Int {}
func funcdecl4(_ a: ((Int) -> Int), _ b: Int) {}
func funcdecl5(_ a: Int, _ y: Int) {
// Pass in a closure containing the call to funcdecl3.
funcdecl4({ funcdecl3() }, 12) // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{14-14= _ in}}
func6({$0 + $1}) // Closure with two named anonymous arguments
func6({($0) + $1}) // Closure with sequence expr inferred type
func6({($0) + $0}) // // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
var testfunc : ((), Int) -> Int // expected-note {{'testfunc' declared here}}
testfunc({$0+1}) // expected-error {{missing argument for parameter #2 in call}}
funcdecl5(1, 2) // recursion.
// Element access from a tuple.
var a : (Int, f : Int, Int)
var b = a.1+a.f
// Tuple expressions with named elements.
var i : (y : Int, x : Int) = (x : 42, y : 11)
funcdecl1(123, 444)
// Calls.
4() // expected-error {{cannot call value of non-function type 'Int'}}{{4-6=}}
// rdar://12017658 - Infer some argument types from func6.
func6({ a, b -> Int in a+b})
// Return type inference.
func6({ a,b in a+b })
// Infer incompatible type.
func6({a,b -> Float in 4.0 }) // expected-error {{declared closure result 'Float' is incompatible with contextual type 'Int'}} {{17-22=Int}} // Pattern doesn't need to name arguments.
func6({ _,_ in 4 })
func6({a,b in 4.0 }) // expected-error {{cannot convert value of type 'Double' to closure result type 'Int'}}
// TODO: This diagnostic can be improved: rdar://22128205
func6({(a : Float, b) in 4 }) // expected-error {{cannot convert value of type '(Float, _) -> Int' to expected argument type '(Int, Int) -> Int'}}
var fn = {}
var fn2 = { 4 }
var c : Int = { a,b -> Int in a+b} // expected-error{{cannot convert value of type '(Int, Int) -> Int' to specified type 'Int'}}
}
func unlabeledClosureArgument() {
func add(_ x: Int, y: Int) -> Int { return x + y }
func6a({$0 + $1}) // single closure argument
func6a(add)
func6b(1, {$0 + $1}) // second arg is closure
func6b(1, add)
func6c({$0 + $1}) // second arg is default int
func6c(add)
}
// rdar://11935352 - closure with no body.
func closure_no_body(_ p: () -> ()) {
return closure_no_body({})
}
// rdar://12019415
func t() {
let u8 : UInt8 = 1
let x : Bool = true
if 0xA0..<0xBF ~= Int(u8) && x {
}
}
// <rdar://problem/11927184>
func f0(_ a: Any) -> Int { return 1 }
assert(f0(1) == 1)
var selfRef = { selfRef() } // expected-error {{variable used within its own initial value}}
var nestedSelfRef = {
var recursive = { nestedSelfRef() } // expected-error {{variable used within its own initial value}}
recursive()
}
var shadowed = { (shadowed: Int) -> Int in
let x = shadowed
return x
} // no-warning
var shadowedShort = { (shadowedShort: Int) -> Int in shadowedShort+1 } // no-warning
func anonymousClosureArgsInClosureWithArgs() {
func f(_: String) {}
var a1 = { () in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a2 = { () -> Int in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a3 = { (z: Int) in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{26-28=z}}
var a4 = { (z: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{7-9=z}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
var a5 = { (_: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
}
func doStuff(_ fn : @escaping () -> Int) {}
func doVoidStuff(_ fn : @escaping () -> ()) {}
// <rdar://problem/16193162> Require specifying self for locations in code where strong reference cycles are likely
class ExplicitSelfRequiredTest {
var x = 42
func method() -> Int {
// explicit closure requires an explicit "self." base.
doVoidStuff({ self.x += 1 })
doStuff({ x+1 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{15-15=self.}}
doVoidStuff({ x += 1 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{19-19=self.}}
// Methods follow the same rules as properties, uses of 'self' must be marked with "self."
doStuff { method() } // expected-error {{call to method 'method' in closure requires explicit 'self.' to make capture semantics explicit}} {{15-15=self.}}
doVoidStuff { _ = method() } // expected-error {{call to method 'method' in closure requires explicit 'self.' to make capture semantics explicit}} {{23-23=self.}}
doStuff { self.method() }
// <rdar://problem/18877391> "self." shouldn't be required in the initializer expression in a capture list
// This should not produce an error, "x" isn't being captured by the closure.
doStuff({ [myX = x] in myX })
// This should produce an error, since x is used within the inner closure.
doStuff({ [myX = {x}] in 4 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{23-23=self.}}
// expected-warning @-1 {{capture 'myX' was never used}}
return 42
}
}
class SomeClass {
var field : SomeClass?
func foo() -> Int {}
}
func testCaptureBehavior(_ ptr : SomeClass) {
// Test normal captures.
weak var wv : SomeClass? = ptr
unowned let uv : SomeClass = ptr
unowned(unsafe) let uv1 : SomeClass = ptr
unowned(safe) let uv2 : SomeClass = ptr
doStuff { wv!.foo() }
doStuff { uv.foo() }
doStuff { uv1.foo() }
doStuff { uv2.foo() }
// Capture list tests
let v1 : SomeClass? = ptr
let v2 : SomeClass = ptr
doStuff { [weak v1] in v1!.foo() }
// expected-warning @+2 {{variable 'v1' was written to, but never read}}
doStuff { [weak v1, // expected-note {{previous}}
weak v1] in v1!.foo() } // expected-error {{definition conflicts with previous value}}
doStuff { [unowned v2] in v2.foo() }
doStuff { [unowned(unsafe) v2] in v2.foo() }
doStuff { [unowned(safe) v2] in v2.foo() }
doStuff { [weak v1, weak v2] in v1!.foo() + v2!.foo() }
let i = 42
// expected-warning @+1 {{variable 'i' was never mutated}} {{19-20=let}}
doStuff { [weak i] in i! } // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}}
}
extension SomeClass {
func bar() {
doStuff { [unowned self] in self.foo() }
doStuff { [unowned xyz = self.field!] in xyz.foo() }
doStuff { [weak xyz = self.field] in xyz!.foo() }
// rdar://16889886 - Assert when trying to weak capture a property of self in a lazy closure
doStuff { [weak self.field] in field!.foo() } // expected-error {{fields may only be captured by assigning to a specific name}} expected-error {{reference to property 'field' in closure requires explicit 'self.' to make capture semantics explicit}} {{36-36=self.}}
// expected-warning @+1 {{variable 'self' was written to, but never read}}
doStuff { [weak self&field] in 42 } // expected-error {{expected ']' at end of capture list}}
}
func strong_in_capture_list() {
// <rdar://problem/18819742> QOI: "[strong self]" in capture list generates unhelpful error message
_ = {[strong self] () -> () in return } // expected-error {{expected 'weak', 'unowned', or no specifier in capture list}}
}
}
// <rdar://problem/16955318> Observed variable in a closure triggers an assertion
var closureWithObservedProperty: () -> () = {
var a: Int = 42 {
willSet {
_ = "Will set a to \(newValue)"
}
didSet {
_ = "Did set a with old value of \(oldValue)"
}
}
}
;
{}() // expected-error{{top-level statement cannot begin with a closure expression}}
// rdar://19179412 - Crash on valid code.
func rdar19179412() -> (Int) -> Int {
return { x in
class A {
let d : Int = 0
}
return 0
}
}
// Test coercion of single-expression closure return types to void.
func takesVoidFunc(_ f: () -> ()) {}
var i: Int = 1
// expected-warning @+1 {{expression of type 'Int' is unused}}
takesVoidFunc({i})
// expected-warning @+1 {{expression of type 'Int' is unused}}
var f1: () -> () = {i}
var x = {return $0}(1)
func returnsInt() -> Int { return 0 }
takesVoidFunc(returnsInt) // expected-error {{cannot convert value of type '() -> Int' to expected argument type '() -> ()'}}
takesVoidFunc({() -> Int in 0}) // expected-error {{declared closure result 'Int' is incompatible with contextual type '()'}} {{22-25=()}}
// These used to crash the compiler, but were fixed to support the implementation of rdar://problem/17228969
Void(0) // expected-error{{argument passed to call that takes no arguments}}
_ = {0}
// <rdar://problem/22086634> "multi-statement closures require an explicit return type" should be an error not a note
let samples = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{16-16= () -> Bool in }}
if (i > 10) { return true }
else { return false }
}()
// <rdar://problem/19756953> Swift error: cannot capture '$0' before it is declared
func f(_ fp : (Bool, Bool) -> Bool) {}
f { $0 && !$1 }
// <rdar://problem/18123596> unexpected error on self. capture inside class method
func TakesIntReturnsVoid(_ fp : ((Int) -> ())) {}
struct TestStructWithStaticMethod {
static func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
class TestClassWithStaticMethod {
class func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
// Test that we can infer () as the result type of these closures.
func genericOne<T>(_ a: () -> T) {}
func genericTwo<T>(_ a: () -> T, _ b: () -> T) {}
genericOne {}
genericTwo({}, {})
// <rdar://problem/22344208> QoI: Warning for unused capture list variable should be customized
class r22344208 {
func f() {
let q = 42
let _: () -> Int = {
[unowned self, // expected-warning {{capture 'self' was never used}}
q] in // expected-warning {{capture 'q' was never used}}
1 }
}
}
var f = { (s: Undeclared) -> Int in 0 } // expected-error {{use of undeclared type 'Undeclared'}}
// <rdar://problem/21375863> Swift compiler crashes when using closure, declared to return illegal type.
func r21375863() {
var width = 0
var height = 0
var bufs: [[UInt8]] = (0..<4).map { _ -> [asdf] in // expected-error {{use of undeclared type 'asdf'}}
[UInt8](repeating: 0, count: width*height)
}
}
// <rdar://problem/25993258>
// Don't crash if we infer a closure argument to have a tuple type containing inouts.
func r25993258_helper(_ fn: (inout Int, Int) -> ()) {}
func r25993258a() {
r25993258_helper { x in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
func r25993258b() {
r25993258_helper { _ in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
// We have to map the captured var type into the right generic environment.
class GenericClass<T> {}
func lvalueCapture<T>(c: GenericClass<T>) {
var cc = c
weak var wc = c
func innerGeneric<U>(_: U) {
_ = cc
_ = wc
cc = wc!
}
}
|
apache-2.0
|
fca8814dbb7c90174d55a2759d2a16b1
| 38.061625 | 270 | 0.64066 | 3.560123 | false | false | false | false |
sivakumarscorpian/INTPushnotification1
|
REIOSSDK/REiosAutoTracker.swift
|
1
|
5120
|
//
// ResulticsAutoTracker.swift
// INTPushNotification
//
// Created by Sivakumar on 19/10/17.
// Copyright © 2017 Interakt. All rights reserved.
//
import UIKit
import CoreData
class REiosAutoTracker {
class func setScreenName(name:String?) {
var _arryScreenData:[Any] = []
let _startTime = String(describing: Date())
var _screenName = name
let _subScreen = "None"
if name == nil {
_screenName = "Unidentified screen"
}
let dict = [REiosParamsApi.startTime:_startTime , REiosParamsApi.subScreenName:_subScreen, REiosParamsApi.screenName:_screenName!] as [String : Any]
print(dict)
if REiosDataManager.shared.isFirstTimeAuto == "" {
REiosDataManager.shared.setFirstTimeValueAuto(value: name!)
// Setting current screen info to singleton
REiosDataManager.shared.setAutoScreenData(params: dict)
} else {
var _campaignId:String? = nil
if let cId = REiosDataManager.shared._campaignId {
_campaignId = cId
}
// Common for this api
let _appId = REiosDataManager.shared.getApiKey()
let _deviceId = REiosDataManager.shared.getDeviceId()
let _userId = REiosDataManager.shared.getUserId()
// End time for the screen
let _endTime = String(describing: Date())
// Screen info
var _screenData:[String:Any] = REiosDataManager.shared._autoScreenData
_screenData[REiosParamsApi.endTime] = _endTime
print(_screenData)
// Adding event info to screen data
// _screenData[REiosParamsApi.events] = REiosDataManager.shared._autoEventData
// Adding field capture info to screen data
_screenData["fieldCapture"] = REiosDataManager.shared.getTfObject()
// Adding error log info to screen data
// _screenData["errorLog"] = []
_arryScreenData.append(_screenData)
var _params:[String:Any] = [:]
_params[REiosParamsApi.appId] = _appId
_params[REiosParamsDevice.id] = _deviceId
_params[REiosParamsUser.Id] = _userId
_params[REiosParamsApi.screen] = _arryScreenData
if _campaignId != nil {
_params[REiosParamsApi.campaignId] = _campaignId
}
print("params auto tracker \(_params)")
print(dict)
// Setting current screen info to singleton
REiosDataManager.shared.setAutoScreenData(params: dict)
let jsonData = try? JSONSerialization.data(withJSONObject: _params, options: .prettyPrinted)
let jsonString = String(data: jsonData!, encoding: .utf8)
print(jsonString ?? "no val")
if REiosReachability.isInternetReachable() == true {
REiosNetwork.getDataFromServer7(path: REiosUrls.screenTracking, params: _params, method: .post, successHandler: { returnData in
print("success auto tracker \(returnData)")
REiosDataManager.shared.setAutoEmptyEvent()
}, failureHandler: { error in
print("failure auto tracker \(error.description)")
let managedContext = REiosDataManager.shared.persistentContainer.viewContext
let screen = NSEntityDescription.insertNewObject(forEntityName: "Screen", into: managedContext) as! Screen
screen.json = jsonString
do {
try managedContext.save()
REiosDataManager.shared.setEmptyEvent()
} catch {
fatalError("Failure to save context: \(error)")
}
})
} else {
let managedContext = REiosDataManager.shared.persistentContainer.viewContext
let screen = NSEntityDescription.insertNewObject(forEntityName: "Screen", into: managedContext) as! Screen
screen.json = jsonString
do {
try managedContext.save()
REiosDataManager.shared.setEmptyEvent()
} catch {
fatalError("Failure to save context: \(error)")
}
}
}
}
class func addEventDetails(eName: String) {
let _timeStamp = String(describing: Date())
let dictEvent = [REiosParamsApi.eventName:"AutoTrackerEvent", REiosParamsApi.timeStamp:_timeStamp, "viewId":eName]
REiosDataManager.shared.setAutoEventData(params: dictEvent)
}
}
|
mit
|
6187bbcc5c8b4219c9419ee679be41d7
| 38.076336 | 156 | 0.541121 | 5.282766 | false | false | false | false |
tgosp/pitch-perfect
|
PitchPerfect/Constants.swift
|
1
|
710
|
//
// Constants.swift
// PitchPerfect
//
// Created by Todor Gospodinov on 12/14/15.
// Copyright © 2015 Todor Gospodinov. All rights reserved.
//
struct Constants {
static let fileName = "recorded_audio.wav"
static let recordingInProgress = "recording in progress"
static let tapToRecord = "tap to record"
static let stopRecordingSegue = "stopRecording"
static let playAudio = "Play audio"
static let recordingWasNotSuccessful = "Recording was not successful"
static let dismiss = "Dismiss"
static let errorAlertTitle = "Error occured"
static let errorAlertMessage = "Recording was not successfull, please try again"
}
|
mit
|
abf1fde7e9e03dcc06aa8ba3bad16b3c
| 23.448276 | 85 | 0.67701 | 4.487342 | false | false | false | false |
bootstraponline/FBSimulatorControl
|
fbsimctl/FBSimulatorControlKit/Sources/EventReporter.swift
|
1
|
3145
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import Foundation
import FBSimulatorControl
import XCTestBootstrap
public protocol EventReporter {
func report(_ subject: EventReporterSubject)
}
extension EventReporter {
func reportSimpleBridge(_ eventName: EventName, _ eventType: EventType, _ subject: ControlCoreValue) {
self.reportSimple(eventName, eventType, ControlCoreSubject(subject))
}
func reportSimple(_ eventName: EventName, _ eventType: EventType, _ subject: EventReporterSubject) {
self.report(SimpleSubject(eventName, eventType, subject))
}
func reportError(_ message: String) {
self.reportSimpleBridge(EventName.Failure, EventType.Discrete, message as NSString)
}
func logDebug(_ string: String) {
self.report(LogSubject(logString: string, level: Constants.asl_level_debug()))
}
func logInfo(_ string: String) {
self.report(LogSubject(logString: string, level: Constants.asl_level_info()))
}
}
open class HumanReadableEventReporter : EventReporter {
let writer: Writer
init(writer: Writer) {
self.writer = writer
}
open func report(_ subject: EventReporterSubject) {
for item in subject.subSubjects {
let string = item.description
if string.isEmpty {
return
}
self.writer.write(string)
}
}
}
open class JSONEventReporter : NSObject, EventReporter {
let writer: Writer
let pretty: Bool
init(writer: Writer, pretty: Bool) {
self.writer = writer
self.pretty = pretty
}
open func report(_ subject: EventReporterSubject) {
for item in subject.subSubjects {
guard let line = try? item.jsonDescription.serializeToString(pretty) else {
assertionFailure("\(item) could not be encoded to a string")
break
}
self.writer.write(line as String)
}
}
}
public extension OutputOptions {
public func createReporter(_ writer: Writer) -> EventReporter {
if self.contains(OutputOptions.JSON) {
let pretty = self.contains(OutputOptions.Pretty)
return JSONEventReporter(writer: writer, pretty: pretty)
}
return HumanReadableEventReporter(writer: writer)
}
public func createLogWriter() -> Writer {
return self.contains(OutputOptions.JSON) ? FileHandleWriter.stdOutWriter : FileHandleWriter.stdErrWriter
}
}
public extension Help {
public func createReporter(_ writer: Writer) -> EventReporter {
return self.outputOptions.createReporter(writer)
}
}
public extension Command {
public func createReporter(_ writer: Writer) -> EventReporter {
return self.configuration.outputOptions.createReporter(writer)
}
}
public extension CLI {
public func createReporter(_ writer: Writer) -> EventReporter {
switch self {
case .run(let command):
return command.createReporter(writer)
case .show(let help):
return help.createReporter(writer)
}
}
}
|
bsd-3-clause
|
781e3b2656877de6371dcfb70e425467
| 26.831858 | 108 | 0.715421 | 4.193333 | false | false | false | false |
tavultesoft/keymanweb
|
ios/engine/KMEI/KeymanEngine/Classes/Manager.swift
|
1
|
37059
|
//
// Manager.swift
// KeymanEngine
//
// Created by Gabriel Wong on 2017-10-06.
// Copyright © 2017 SIL International. All rights reserved.
//
import UIKit
import WebKit
import XCGLogger
import DeviceKit
import Reachability
typealias FetchKeyboardsBlock = ([String: Any]?) -> Void
// MARK: - Constants
// Possible states that a keyboard or lexical model can be in
@available(*, deprecated, message: "Version checks against keyboards and models are now based on their package. Use `KeymanPackage.InstallationState` and `KeymanPackage.VersionState` instead.")
public enum KeyboardState {
case needsDownload
case needsUpdate
case upToDate
case downloading
case none
}
public enum VibrationSupport {
case none // Has no vibrator
case basic // Has only the basic 0.4 sec long vibration
case basic_plus // Has undocumented access to three other vibration lengths
case taptic // Has the Taptic engine, allowing use of UIImpactFeedbackGenerator for customizable vibrations
}
public enum SpacebarText: String {
// Maps to enum SpacebarText in kmwbase.ts
case LANGUAGE = "language"
case KEYBOARD = "keyboard"
case LANGUAGE_KEYBOARD = "languageKeyboard"
case BLANK = "blank"
};
/**
* Obtains the bundle for KeymanEngine.framework.
*/
internal let engineBundle: Bundle = Bundle(for: Manager.self)
public class Manager: NSObject, UIGestureRecognizerDelegate {
/// Application group identifier for shared container. Set this before accessing the shared manager.
public static var applicationGroupIdentifier: String?
public static let shared = Manager()
public var fileBrowserLauncher: ((UINavigationController) -> Void)? = nil
/// Display the help bubble on first use.
public var isKeymanHelpOn = true
public var isSystemKeyboard: Bool {
guard let kbd = self._inputViewController else {
return false
}
return kbd.isSystemKeyboard
}
// TODO: Change API to not disable removing as well
/// Allow users to add new keyboards in the keyboard picker.
/// - Default value is true.
/// - Setting this to false will also disable keyboard removal. To enable keyboard removal you should set
/// canRemoveKeyboards to true.
public var canAddNewKeyboards: Bool {
get {
return _canAddNewKeyboards
}
set(canAddNewKeyboards) {
_canAddNewKeyboards = canAddNewKeyboards
if !canAddNewKeyboards {
canRemoveKeyboards = false
}
}
}
private var _canAddNewKeyboards = true
/// Allow users to remove keyboards.
/// - Default value is true.
/// - The default keyboard is additionally prevented from being removed by canRemoveDefaultkeyboard.
public var canRemoveKeyboards = true
/// Allow the default keyboard to be removed.
/// The last keyboard cannot be removed, so the default keyboard cannot be removed if it
/// is the only keyboard in the list, regardless of the value of this property.
/// The default value is false.
public var canRemoveDefaultKeyboard = false
// TODO: Change API to not disable removing as well
/// Allow users to add new lexical models in the lexical model picker.
/// - Default value is true.
/// - Setting this to false will also disable lexical model removal. To enable lexical model removal you should set
/// canRemoveLexicalModels to true.
public var canAddNewLexicalModels: Bool {
get {
return _canAddNewLexicalModels
}
set(canAddNewLexicalModels) {
_canAddNewLexicalModels = canAddNewLexicalModels
if !canAddNewLexicalModels {
canRemoveLexicalModels = false
}
}
}
private var _canAddNewLexicalModels = true
/// Allow users to remove lexical models.
/// - Default value is true.
/// - The default lexical model is additionally prevented from being removed by canRemoveDefaultLexicalModel.
public var canRemoveLexicalModels = true
/// Allow the default lexical model to be removed.
/// The last lexical model CAN be removed, as this is an optional feature
/// The default value is true.
public var canRemoveDefaultLexicalModel = true
/// In keyboard extensions (system keyboard), `UIApplication.openURL(_:)` is unavailable. The API is not called in
/// the system keyboard since `KeyboardInfoViewController` is never used. `openURL(:_)` is only used in applications,
/// where it is safe. However, the entire Keyman Engine framework must be compiled with extension-safe APIs.
///
/// Set this to `UIApplication.shared.openURL` in your application.
@available(*, deprecated)
public var openURL: ((URL) -> Bool)?
var currentKeyboardID: FullKeyboardID?
private var _currentLexicalModelID: FullLexicalModelID?
var currentLexicalModelID: FullLexicalModelID? {
get {
if _currentLexicalModelID == nil {
let userData = Util.isSystemKeyboard ? UserDefaults.standard : Storage.active.userDefaults
_currentLexicalModelID = userData.currentLexicalModelID
}
return _currentLexicalModelID
}
set(value) {
_currentLexicalModelID = value
let userData = Util.isSystemKeyboard ? UserDefaults.standard : Storage.active.userDefaults
userData.currentLexicalModelID = _currentLexicalModelID
userData.synchronize()
}
}
var shouldReloadLexicalModel = false
var _inputViewController: InputViewController?
var currentResponder: KeymanResponder?
// This allows for 'lazy' initialization of the keyboard.
open var inputViewController: InputViewController! {
get {
// Occurs for the in-app keyboard ONLY.
if _inputViewController == nil {
_inputViewController = InputViewController(forSystem: false)
}
return _inputViewController
}
set(value) {
_inputViewController = value
}
}
//private var downloadQueue: HTTPDownloader?
private var reachability: Reachability!
var didSynchronize = false
private var _spacebarText: SpacebarText
public var spacebarText: SpacebarText {
get {
return _spacebarText
}
set(value) {
_spacebarText = value
let userData = Storage.active.userDefaults
userData.optSpacebarText = _spacebarText
userData.synchronize()
inputViewController.updateSpacebarText()
}
}
// MARK: - Object Admin
private override init() {
_spacebarText = Storage.active.userDefaults.optSpacebarText
super.init()
URLProtocol.registerClass(KeymanURLProtocol.self)
/**
* As of 14.0, ResourceFileManager is responsible for handlng resources... including
* any necessary "migration" of their internal storage structure & tracked metadata.
*/
ResourceFileManager.shared.runMigrationsIfNeeded()
if Util.isSystemKeyboard || Storage.active.userDefaults.bool(forKey: Key.keyboardPickerDisplayed) {
isKeymanHelpOn = false
}
do {
try Storage.active.copyKMWFiles(from: Resources.bundle)
} catch {
SentryManager.captureAndLog(error, message: "Failed to copy KMW files from bundle: \(error)")
}
updateUserKeyboards(with: Defaults.keyboard)
do {
try reachability = Reachability(hostname: KeymanHosts.API_KEYMAN_COM.host!)
} catch {
SentryManager.captureAndLog(error, message: "Could not start Reachability object: \(error)")
}
if(!Util.isSystemKeyboard) {
NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged),
name: .reachabilityChanged, object: reachability)
do {
try reachability.startNotifier()
} catch {
SentryManager.captureAndLog(error, message: "failed to start Reachability notifier: \(error)")
}
}
// We used to preload the old KeymanWebViewController, but now that it's embedded within the
// InputViewController, that's not exactly viable.
}
// MARK: - Keyboard management
public func showKeymanEngineSettings(inVC: UIViewController) -> Void {
hideKeyboard()
// Allows us to set a custom UIToolbar for download/update status displays.
let nc = UINavigationController(navigationBarClass: nil, toolbarClass: ResourceDownloadStatusToolbar.self)
// Grab our newly-generated toolbar instance and inform it of its parent NavigationController.
// This will help streamline use of the 'toolbar' as a status/update bar.
let toolbar = nc.toolbar as? ResourceDownloadStatusToolbar
toolbar?.navigationController = nc
// As it's the first added view controller, settingsVC will function as root automatically.
let settingsVC = SettingsViewController()
nc.pushViewController(settingsVC, animated: false)
nc.modalTransitionStyle = .coverVertical
nc.modalPresentationStyle = .pageSheet
inVC.present(nc, animated: true)
}
/// Sets the current keyboard, querying from the user's list of keyboards.
///
/// - Precondition:
/// - The keyboard must be added with `addKeyboard()`.
///
/// - SeeAlso:
/// - addKeyboard()
/// - Returns: Whether the keyboard was set successfully
//TODO: this method appears unused, should we remove it?
public func setKeyboard(withFullID fullID: FullKeyboardID) -> Bool {
if let keyboard = Storage.active.userDefaults.userKeyboard(withFullID: fullID) {
return setKeyboard(keyboard)
}
return false
}
// returns lexical model id, given language id
func preferredLexicalModel(_ ud: UserDefaults, forLanguage lgCode: String) -> InstallableLexicalModel? {
if let preferredID = ud.preferredLexicalModelID(forLanguage: lgCode) {
// We need to match both the model id and the language code - registration fails
// when the language code mismatches the current keyboard's set code!
return ud.userLexicalModels?.first { $0.id == preferredID && $0.languageID == lgCode }
}
return nil
}
/// Set the current keyboard.
///
/// - Returns: `false` if the requested keyboard could not be set
public func setKeyboard(_ kb: InstallableKeyboard) -> Bool {
// KeymanWebViewController relies upon this method to activate the keyboard after a page reload,
// and as a system keyboard, the controller is rebuilt each time the keyboard is loaded.
//
// We MUST NOT shortcut this method as a result; doing so may (rarely) result in the infamous
// blank keyboard bug!
if kb.fullID == currentKeyboardID && !self.isSystemKeyboard && !inputViewController.shouldReload {
SentryManager.breadcrumbAndLog("Keyboard unchanged: \(kb.fullID)")
return false
}
SentryManager.breadcrumbAndLog("Setting language: \(kb.fullID)")
currentKeyboardID = kb.fullID
if let fontFilename = kb.font?.source.first(where: { $0.hasFontExtension }) {
_ = FontManager.shared.registerFont(at: Storage.active.fontURL(forResource: kb, filename: fontFilename)!)
}
if let oskFontFilename = kb.oskFont?.source.first(where: { $0.hasFontExtension }) {
_ = FontManager.shared.registerFont(at: Storage.active.fontURL(forResource: kb, filename: oskFontFilename)!)
}
do {
try inputViewController.setKeyboard(kb)
} catch {
// Here, errors are logged by the error's thrower.
return false
}
let userData = Util.isSystemKeyboard ? UserDefaults.standard : Storage.active.userDefaults
userData.currentKeyboardID = kb.fullID
userData.synchronize()
if isKeymanHelpOn {
inputViewController.showHelpBubble(afterDelay: 1.5)
}
// getAssociatedLexicalModel(langID) and setLexicalModel
NotificationCenter.default.post(name: Notifications.keyboardChanged,
object: self,
value: kb)
// Now to handle lexical model + banner management
inputViewController.clearModel()
let userDefaults: UserDefaults = Storage.active.userDefaults
// If we have a lexical model for the keyboard's language, activate it.
if let preferred_model = preferredLexicalModel(userDefaults, forLanguage: kb.languageID) {
_ = Manager.shared.registerLexicalModel(preferred_model)
} else if let first_model = userDefaults.userLexicalModels?.first(where: { $0.languageID == kb.languageID }) {
_ = Manager.shared.registerLexicalModel(first_model)
}
inputViewController.fixLayout()
return true
}
/// Adds a new keyboard to the list in the keyboard picker if it doesn't already exist.
/// The keyboard must be downloaded (see `downloadKeyboard()`) or preloaded (see `preloadLanguageFile()`)
@available(*, deprecated, message: "Deprecated in favor of ResourceFileManager.install(resourceWithID:from:)")
public func addKeyboard(_ keyboard: InstallableKeyboard) {
var kbdToInstall = keyboard
// 3rd party installation of keyboards (13.0 and before):
// - Manager.shared.preloadFiles was called first to import the file resources
// - Then Manager.shared.addKeyboard installs the keyboard.
//
// Since 3rd-party uses never provided kmp.json files, we need to instant-migrate
// them here.
if !Migrations.resourceHasPackageMetadata(keyboard) {
let wrappedKbds = Migrations.migrateToKMPFormat([keyboard])
guard wrappedKbds.count == 1 else {
SentryManager.captureAndLog("Could not properly import keyboard")
return
}
kbdToInstall = wrappedKbds[0]
} else {
ResourceFileManager.shared.addResource(kbdToInstall)
}
}
/// Sets the current lexical model, querying from the user's list of lexical models.
///
/// - Precondition:
/// - The lexical model must be added with `addLexicalModel()`.
///
/// - SeeAlso:
/// - addLexicalModel()
/// - Returns: Whether the lexical model was set successfully
//TODO: this method appears unused, should we remove it?
public func registerLexicalModel(withFullID fullID: FullLexicalModelID) -> Bool {
if let lexicalModel = Storage.active.userDefaults.userLexicalModel(withFullID: fullID) {
return registerLexicalModel(lexicalModel)
}
return false
}
/*
* Called from FirstVoices app to add a lexical model.
*/
public func addLexicalModel(lexicalModelId: String, languageId: String, from package: LexicalModelKeymanPackage) -> Bool {
let fullId = FullLexicalModelID(lexicalModelID: lexicalModelId, languageID: languageId)
do {
try ResourceFileManager.shared.install(resourceWithID: fullId, from: package)
}
catch {
log.error("Could not add lexical model for id '\(lexicalModelId)' and languageId '\(languageId)' due to error: \(error)")
}
if let lexicalModel = Storage.active.userDefaults.userLexicalModel(withFullID: fullId) {
return registerLexicalModel(lexicalModel)
}
return false
}
/*
* Called from FirstVoices app as a workaround to cause dictionary options to be applied.
*/
public func registerLexicalModel(lexicalModelId: String, languageId: String) -> Bool {
let fullId = FullLexicalModelID(lexicalModelID: lexicalModelId, languageID: languageId)
if let lexicalModel = Storage.active.userDefaults.userLexicalModel(withFullID: fullId) {
return registerLexicalModel(lexicalModel)
}
return false
}
/// Registers a lexical model with KMW.
public func registerLexicalModel(_ lm: InstallableLexicalModel) -> Bool {
SentryManager.breadcrumbAndLog("Setting lexical model: \(lm.fullID)")
currentLexicalModelID = lm.fullID
do {
try inputViewController.registerLexicalModel(lm)
} catch {
// Here, errors are logged by the error's thrower.
return false
}
if isKeymanHelpOn {
inputViewController.showHelpBubble(afterDelay: 1.5)
}
// While this does only register the model with KMW, the timing of this generally does
// result in a change of the actual model.
NotificationCenter.default.post(name: Notifications.lexicalModelChanged,
object: self,
value: lm)
return true
}
/** Adds a new lexical model to the list in the lexical model picker if it doesn't already exist.
* The lexical model must be downloaded (see `downloadLexicalModel()`) or preloaded (see `preloadLanguageFile()`)
* I believe this is background-thread-safe (no UI done)
*/
@available(*, deprecated, message: "Deprecated in favor of ResourceFileManager.install(resourceWithID:from:)")
static public func addLexicalModel(_ lexicalModel: InstallableLexicalModel) {
var modelToInstall = lexicalModel
// Potential 3rd party installation of lexical models (12.0, 13.0):
// - Manager.shared.preloadFiles was called first to import the file resources
// - Then Manager.addLexicalModel installs the lexical model.
//
// Since 3rd-party uses never provided kmp.json files, we need to instant-migrate
// them here.
if !Migrations.resourceHasPackageMetadata(lexicalModel) {
let wrappedModels = Migrations.migrateToKMPFormat([lexicalModel])
guard wrappedModels.count == 1 else {
SentryManager.captureAndLog("Could not properly import lexical model")
return
}
modelToInstall = wrappedModels[0]
} else {
ResourceFileManager.shared.addResource(modelToInstall)
}
}
/// Removes a keyboard from the list in the keyboard picker if it exists.
/// - Returns: The keyboard exists and was removed
public func removeKeyboard(withFullID fullID: FullKeyboardID) -> Bool {
// Remove keyboard from the list if it exists
let index = Storage.active.userDefaults.userKeyboards?.firstIndex { $0.fullID == fullID }
if let index = index {
return removeKeyboard(at: index)
}
return false
}
/// Removes the keyboard at index from the keyboards list if it exists.
/// - Returns: The keyboard exists and was removed
public func removeKeyboard(at index: Int) -> Bool {
let userData = Storage.active.userDefaults
// If user defaults for keyboards list does not exist, do nothing.
guard var userKeyboards = userData.userKeyboards else {
return false
}
guard index < userKeyboards.count else {
return false
}
let kb = userKeyboards[index]
userKeyboards.remove(at: index)
userData.userKeyboards = userKeyboards
userData.set([Date()], forKey: Key.synchronizeSWKeyboard)
userData.synchronize()
SentryManager.breadcrumbAndLog("Removing keyboard with ID \(kb.id) and languageID \(kb.languageID)")
// Set a new keyboard if deleting the current one
if kb.fullID == currentKeyboardID {
if userKeyboards.count > 0 {
_ = setKeyboard(userKeyboards[0])
}
}
if !userKeyboards.contains(where: { $0.id == kb.id }) {
// TODO: should make sure that there are no resources in the package,
// rather than just 'no matching keyboards'.
let keyboardDir = Storage.active.resourceDir(for: kb)!
FontManager.shared.unregisterFonts(in: keyboardDir, fromSystemOnly: false)
SentryManager.breadcrumbAndLog("Deleting directory \(keyboardDir)")
if (try? FileManager.default.removeItem(at: keyboardDir)) == nil {
SentryManager.captureAndLog("Failed to delete \(keyboardDir) when removing keyboard")
}
} else {
SentryManager.breadcrumbAndLog("User has another language installed. Skipping delete of keyboard files.")
}
NotificationCenter.default.post(name: Notifications.keyboardRemoved, object: self, value: kb)
return true
}
/// - Returns: Info for the current keyboard, if a keyboard is set
public var currentKeyboard: InstallableKeyboard? {
guard let fullID = currentKeyboardID else {
return nil
}
return Storage.active.userDefaults.userKeyboard(withFullID: fullID)
}
/*
* Called from FirstVoices app.
*/
public func removeLexicalModel(lexicalModelId: String, languageId: String) -> Bool {
let fullId = FullLexicalModelID(lexicalModelID: lexicalModelId, languageID: languageId)
return removeLexicalModel(withFullID: fullId)
}
/// Removes a lexical model from the list in the lexical model picker if it exists.
/// - Returns: The lexical model exists and was removed
public func removeLexicalModel(withFullID fullID: FullLexicalModelID) -> Bool {
// Remove lexical model from the list if it exists
let index = Storage.active.userDefaults.userLexicalModels?.firstIndex { $0.fullID == fullID }
if let index = index {
return removeLexicalModel(at: index)
}
return false
}
/// Removes the lexical model at index from the lexical models list if it exists.
public func removeLexicalModelFromUserList(userDefs ud: UserDefaults, at index: Int) -> InstallableLexicalModel? {
// If user defaults for lexical models list does not exist, do nothing.
guard var userLexicalModels = ud.userLexicalModels else {
return nil
}
guard index < userLexicalModels.count else {
return nil
}
let lm = userLexicalModels[index]
SentryManager.breadcrumbAndLog("Removing lexical model with ID \(lm.id) and languageID \(lm.languageID) from user list of all models")
userLexicalModels.remove(at: index)
ud.userLexicalModels = userLexicalModels
ud.set([Date()], forKey: Key.synchronizeSWLexicalModel)
ud.synchronize()
return lm
}
/// Removes the lexical model at index from the lexical models list if it exists.
public func removeLexicalModelFromLanguagePreference(userDefs ud: UserDefaults, _ lm: InstallableLexicalModel) {
SentryManager.breadcrumbAndLog("Removing lexical model with ID \(lm.id) and languageID \(lm.languageID) from per-language prefs")
ud.set(preferredLexicalModelID: nil, forKey: lm.languageID)
}
/// Removes the lexical model at index from the lexical models list if it exists.
/// - Returns: The lexical model exists and was removed
public func removeLexicalModel(at index: Int) -> Bool {
let userData = Storage.active.userDefaults
guard let lm = removeLexicalModelFromUserList(userDefs: userData, at: index) else {
return false
}
removeLexicalModelFromLanguagePreference(userDefs: userData, lm)
inputViewController.deregisterLexicalModel(lm);
// Set a new lexical model if deleting the current one
let userLexicalModels = userData.userLexicalModels! //removeLexicalModelFromUserList fails above if this is not present
if lm.fullID == currentLexicalModelID {
if let first_lm = userLexicalModels.first(where: {$0.languageID == lm.languageID}) {
_ = registerLexicalModel(first_lm)
} else {
SentryManager.breadcrumbAndLog("no more lexical models available for language \(lm.fullID)")
currentLexicalModelID = nil
}
}
if !userLexicalModels.contains(where: { $0.id == lm.id }) {
let lexicalModelDir = Storage.active.resourceDir(for: lm)!
FontManager.shared.unregisterFonts(in: lexicalModelDir, fromSystemOnly: false)
SentryManager.breadcrumbAndLog("Deleting directory \(lexicalModelDir)")
if (try? FileManager.default.removeItem(at: lexicalModelDir)) == nil {
SentryManager.captureAndLog("Failed to delete \(lexicalModelDir) when removing lexical model")
}
} else {
SentryManager.breadcrumbAndLog("User has another language installed. Skipping delete of lexical model files.")
}
NotificationCenter.default.post(name: Notifications.lexicalModelRemoved, object: self, value: lm)
return true
}
/// - Returns: Info for the current lexical model, if a lexical model is set
public var currentLexicalModel: InstallableLexicalModel? {
guard let fullID = currentLexicalModelID else {
return nil
}
return Storage.active.userDefaults.userLexicalModel(withFullID: fullID)
}
/// Switch to the next keyboard.
/// - Returns: Index of the newly selected keyboard.
public func switchToNextKeyboard() -> Int? {
guard let userKeyboards = Storage.active.userDefaults.userKeyboards,
let index = userKeyboards.firstIndex(where: { self.currentKeyboardID == $0.fullID })
else {
return nil
}
let newIndex = (index + 1) % userKeyboards.count
_ = setKeyboard(userKeyboards[newIndex])
return newIndex
}
/// - Returns: The font name for the given keyboard ID and languageID, or returns nil if
/// - The keyboard doesn't have a font
/// - The keyboard info is not available in the user keyboards list
public func fontNameForKeyboard(withFullID fullID: FullKeyboardID) -> String? {
if let kb = Storage.active.userDefaults.userKeyboard(withFullID: fullID),
let filename = kb.font?.source.first(where: { $0.hasFontExtension }) {
let fontURL = Storage.active.fontURL(forResource: kb, filename: filename)!
return FontManager.shared.fontName(at: fontURL)
}
return nil
}
/// - Returns: the OSK font name for the given keyboard ID and languageID, or returns nil if
/// - The keyboard doesn't have an OSK font
/// - The keyboard info is not available in the user keyboards list
func oskFontNameForKeyboard(withFullID fullID: FullKeyboardID) -> String? {
if let kb = Storage.active.userDefaults.userKeyboard(withFullID: fullID),
let filename = kb.oskFont?.source.first(where: { $0.hasFontExtension }) {
let fontURL = Storage.active.fontURL(forResource: kb, filename: filename)!
return FontManager.shared.fontName(at: fontURL)
}
return nil
}
// MARK: - Adhoc keyboards
public func parseKbdKMP(_ folder: URL, isCustom: Bool) throws -> Void {
guard let kmp = try? KeymanPackage.parse(folder) as? KeyboardKeymanPackage else {
throw KMPError.wrongPackageType
}
for resourceSet in kmp.installables {
for resource in resourceSet {
try ResourceFileManager.shared.install(resourceWithID: resource.fullID, from: kmp)
// Install the keyboard for only the first language pairing defined in the package.
break
}
}
}
// MARK: - Adhoc lexical models
static public func parseLMKMP(_ folder: URL, isCustom: Bool) throws -> Void {
guard let kmp = try? KeymanPackage.parse(folder) as? LexicalModelKeymanPackage else {
throw KMPError.wrongPackageType
}
try kmp.installables.forEach { resourceSet in
try resourceSet.forEach { resource in
try ResourceFileManager.shared.install(resourceWithID: resource.fullID, from: kmp)
}
}
}
@objc func reachabilityChanged(_ notification: Notification) {
log.debug {
let reachStr: String
switch reachability.connection {
case Reachability.Connection.wifi:
reachStr = "Reachable Via WiFi"
case Reachability.Connection.cellular:
reachStr = "Reachable Via WWan"
default:
reachStr = "Not Reachable"
}
return "Reachability changed to '\(reachStr)'"
}
}
// MARK: - Loading custom keyboards
/// Preloads the JS and font files required for a keyboard.
@available(*, deprecated, message: "Use ResourceFileManager's methods to install resources from KMPs.")
public func preloadFiles(forKeyboardID keyboardID: String, at urls: [URL], shouldOverwrite: Bool) throws {
let keyboardDir = Storage.active.legacyKeyboardDir(forID: keyboardID)
try FileManager.default.createDirectory(at: keyboardDir, withIntermediateDirectories: true)
for url in urls {
try Storage.copy(at: url,
to: keyboardDir.appendingPathComponent(url.lastPathComponent),
shouldOverwrite: shouldOverwrite,
excludeFromBackup: true)
}
}
// MARK: - File system and UserData management
/// Updates the user's installed keyboards and current keyboard with information in newKeyboard.
/// - Parameter newKeyboard: Info for updated keyboard.
func updateUserKeyboards(with newKeyboard: InstallableKeyboard) {
let userData = Storage.active.userDefaults
guard var userKeyboards = userData.userKeyboards else {
return
}
// Set version in user keyboards list
for i in userKeyboards.indices {
var kb = userKeyboards[i]
if kb.id == newKeyboard.id {
if kb.languageID == newKeyboard.languageID {
kb = newKeyboard
} else {
kb.version = newKeyboard.version
}
userKeyboards[i] = kb
}
}
userData.userKeyboards = userKeyboards
userData.synchronize()
}
/// Updates the user's installed lexical models and current lexical model with information in newLexicalModel.
/// - Parameter newLexicalModel: Info for updated lexical model.
func updateUserLexicalModels(with newLexicalModel: InstallableLexicalModel) {
let userData = Storage.active.userDefaults
guard var userLexicalModels = userData.userLexicalModels else {
return
}
// Set version in user lexical models list
for i in userLexicalModels.indices {
var lm = userLexicalModels[i]
if lm.id == newLexicalModel.id {
if lm.languageID == newLexicalModel.languageID {
lm = newLexicalModel
} else {
lm.version = newLexicalModel.version
}
userLexicalModels[i] = lm
}
}
userData.userLexicalModels = userLexicalModels
userData.synchronize()
}
func synchronizeSWKeyboard() {
if let shared = Storage.shared,
let nonShared = Storage.nonShared {
let keysToCopy = [Key.userKeyboardsList, Key.engineVersion]
shared.copyUserDefaults(to: nonShared, withKeys: keysToCopy, shouldOverwrite: true)
do {
try shared.copyFiles(to: nonShared)
FontManager.shared.registerCustomFonts()
} catch {
SentryManager.captureAndLog(error, message: "Failed to copy from shared container: \(error)")
}
}
}
// MARK: - View management
/// Displays a list of available keyboards and allows a user to add/download new keyboards
/// or remove existing ones.
///
/// - Parameters:
/// - in: The current UIViewController (recommended) or the navigation controller
/// - shouldAddKeyboard: Whether to immediately open the view to add a new keyboard
/// - SeeAlso:
/// TextView/TextField to enable/disable the keyboard picker
public func showKeyboardPicker(in viewController: UIViewController, shouldAddKeyboard: Bool) {
hideKeyboard()
let vc = KeyboardSwitcherViewController()
let nc = UINavigationController(rootViewController: vc)
nc.modalTransitionStyle = .coverVertical
nc.modalPresentationStyle = .pageSheet
viewController.present(nc, animated: true) {() -> Void in
if shouldAddKeyboard {
vc.showAddKeyboard()
} else {
let userData = Storage.active.userDefaults
userData.set(true, forKey: Key.keyboardPickerDisplayed)
userData.synchronize()
self.isKeymanHelpOn = false
}
}
}
public func dismissKeyboardPicker(_ viewController: UIViewController) {
// #1045 - Setting animated to false "fixes" the display problems and prevents the crash (on iPad 10.5"
// and 12.9"), but it makes the transition less smooth (obviously) and probably isn't the "right"
// way to fix the problem. Presumably there is some kind of underlying plumbing issue that is the
// true source of the problems.
viewController.dismiss(animated: false)
showKeyboard()
inputViewController.reloadIfNeeded()
NotificationCenter.default.post(name: Notifications.keyboardPickerDismissed, object: self, value: ())
}
public func dismissLexicalModelPicker(_ viewController: UIViewController) {
// #1045 - Setting animated to false "fixes" the display problems and prevents the crash (on iPad 10.5"
// and 12.9"), but it makes the transition less smooth (obviously) and probably isn't the "right"
// way to fix the problem. Presumably there is some kind of underlying plumbing issue that is the
// true source of the problems.
viewController.dismiss(animated: false)
showKeyboard()
if shouldReloadLexicalModel {
inputViewController.reload()
}
NotificationCenter.default.post(name: Notifications.lexicalModelPickerDismissed, object: self, value: ())
}
// MARK: - Text
public func showKeyboard() {
currentResponder?.summonKeyboard()
}
public func hideKeyboard() {
currentResponder?.dismissKeyboard()
Manager.shared.inputViewController.resetKeyboardState()
}
func clearText() {
inputViewController.clearText()
}
func resetContext() {
inputViewController.resetContext()
}
func setContextState(text: String?, range: NSRange) {
inputViewController.setContextState(text: text, range: range)
}
var vibrationSupportLevel: VibrationSupport {
let device = Device.current
if device.isPod {
return .none
} else if device.isPad {
// May not be entirely true, but I can't find any documentation on which
// ones DO have it. Closest thing is https://discussions.apple.com/thread/7415858
// that suggests none before Jan 2016 had it, at least.
return .none
} else if device.isPhone {
let basicVibrationModels: [Device] = [.iPhone4, .iPhone4s, .iPhone5, Device.iPhone5s,
.iPhone5c, .iPhone6, .iPhone6Plus, .iPhoneSE]
if device.isOneOf(Device.allSimulators) {
// The Simulator for testing on macOS doesn't emulate or indicate vibration, unfortunately.
return .none
} else if device == Device.iPhone6s || device == Device.iPhone6sPlus {
return .basic_plus
} else if device.isOneOf(basicVibrationModels) {
return .basic
} else {
return .taptic
}
} else {
return .none
}
}
/*-----------------------------
* Legacy API endpoints -
*-----------------------------
*
* Some functionality has been refactored into separate classes for 12.0.
* No reason we can't add a couple of helper functions to help forward
* the data for apps built on older versions of KMEI, though.
*/
public func downloadKeyboard(withID: String, languageID: String, isUpdate: Bool, fetchRepositoryIfNeeded: Bool = true) {
let kbdFullID = FullKeyboardID(keyboardID: withID, languageID: languageID)
let completionBlock = ResourceDownloadManager.shared.standardKeyboardInstallCompletionBlock(forFullID: kbdFullID, withModel: true)
ResourceDownloadManager.shared.downloadKeyboard(withID: withID,
languageID: languageID,
isUpdate: isUpdate,
fetchRepositoryIfNeeded: fetchRepositoryIfNeeded,
completionBlock: completionBlock)
}
// A new API, but it so closely parallels downloadKeyboard that we should add a 'helper' handler here.
public func downloadLexicalModel(withID: String, languageID: String, isUpdate: Bool, fetchRepositoryIfNeeded: Bool = true) {
let lmFullID = FullLexicalModelID(lexicalModelID: withID, languageID: languageID)
let completionBlock = ResourceDownloadManager.shared.standardLexicalModelInstallCompletionBlock(forFullID: lmFullID)
ResourceDownloadManager.shared.downloadLexicalModel(withID: withID,
languageID: languageID,
isUpdate: isUpdate,
fetchRepositoryIfNeeded: fetchRepositoryIfNeeded,
completionBlock: completionBlock)
}
@available(*, deprecated, message: "") // TODO: Write method on KeymanPackage for this.
public func stateForKeyboard(withID keyboardID: String) -> KeyboardState {
return ResourceDownloadManager.shared.stateForKeyboard(withID: keyboardID)
}
// Technically new, but it does closely parallel an old API point.
@available(*, deprecated, message: "") // TODO: Write method on KeymanPackage for this.
public func stateForLexicalModel(withID modelID: String) -> KeyboardState {
return ResourceDownloadManager.shared.stateForLexicalModel(withID: modelID)
}
public func parseKMP(_ folder: URL, type: LanguageResourceType = .keyboard, isCustom: Bool) throws -> Void {
switch type {
case .keyboard:
try! parseKbdKMP(folder, isCustom: isCustom)
break
case .lexicalModel:
// Yep. Unlike the original, THIS one is static.
try! Manager.parseLMKMP(folder, isCustom: isCustom)
break
}
}
// To re-implement the old API (missing from v11!) we need to pick one version of height.
// For library users, the total height of the InputViewController should be most useful.
public func keyboardHeight() -> CGFloat {
return inputViewController?.expandedHeight ?? 0
}
}
|
apache-2.0
|
e339736c93182f1c4085c4e19d093c15
| 37.926471 | 194 | 0.696152 | 4.703389 | false | false | false | false |
qinting513/SwiftNote
|
youtube/YouTube/ViewControllers/PlayVC.swift
|
1
|
8138
|
//
// PlayVC.swift
// YouTube
//
// Created by Haik Aslanyan on 7/25/16.
// Copyright © 2016 Haik Aslanyan. All rights reserved.
//
protocol PlayerVCDelegate {
func didMinimize()
func didmaximize()
func swipeToMinimize(translation: CGFloat, toState: stateOfVC)
func didEndedSwipe(toState: stateOfVC)
}
import UIKit
import AVFoundation
class PlayVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {
//MARK: Properties
@IBOutlet weak var player: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var minimizeButton: UIButton!
let link: URL = globalVariables.videoLink
var video: Video?
var delegate: PlayerVCDelegate?
var state = stateOfVC.hidden
var direction = Direction.none
var videoPlayer = AVPlayer.init()
//MARK: Methods
func customization() {
self.view.backgroundColor = UIColor.clear
self.player.layer.anchorPoint.applying(CGAffineTransform.init(translationX: -0.5, y: -0.5))
self.tableView.tableFooterView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0))
self.player.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(PlayVC.tapPlayView)))
NotificationCenter.default.addObserver(self, selector: #selector(PlayVC.tapPlayView), name: NSNotification.Name("open"), object: nil)
}
func animate() {
switch self.state {
case .fullScreen:
UIView.animate(withDuration: 0.3, animations: {
self.minimizeButton.alpha = 1
self.tableView.alpha = 1
self.player.transform = CGAffineTransform.identity
UIApplication.shared.isStatusBarHidden = true
})
case .minimized:
UIView.animate(withDuration: 0.3, animations: {
UIApplication.shared.isStatusBarHidden = false
self.minimizeButton.alpha = 0
self.tableView.alpha = 0
let scale = CGAffineTransform.init(scaleX: 0.5, y: 0.5)
let trasform = scale.concatenating(CGAffineTransform.init(translationX: -self.player.bounds.width/4, y: -self.player.bounds.height/4))
self.player.transform = trasform
})
default: break
}
}
func changeValues(scaleFactor: CGFloat) {
self.minimizeButton.alpha = 1 - scaleFactor
self.tableView.alpha = 1 - scaleFactor
let scale = CGAffineTransform.init(scaleX: (1 - 0.5 * scaleFactor), y: (1 - 0.5 * scaleFactor))
let trasform = scale.concatenating(CGAffineTransform.init(translationX: -(self.player.bounds.width / 4 * scaleFactor), y: -(self.player.bounds.height / 4 * scaleFactor)))
self.player.transform = trasform
}
func tapPlayView() {
self.videoPlayer.play()
self.state = .fullScreen
self.delegate?.didmaximize()
self.animate()
}
@IBAction func minimize(_ sender: UIButton) {
self.state = .minimized
self.delegate?.didMinimize()
self.animate()
}
@IBAction func minimizeGesture(_ sender: UIPanGestureRecognizer) {
if sender.state == .began {
let velocity = sender.velocity(in: nil)
if abs(velocity.x) < abs(velocity.y) {
self.direction = .up
} else {
self.direction = .left
}
}
var finalState = stateOfVC.fullScreen
switch self.state {
case .fullScreen:
let factor = (abs(sender.translation(in: nil).y) / UIScreen.main.bounds.height)
self.changeValues(scaleFactor: factor)
self.delegate?.swipeToMinimize(translation: factor, toState: .minimized)
finalState = .minimized
case .minimized:
if self.direction == .left {
finalState = .hidden
let factor: CGFloat = sender.translation(in: nil).x
self.delegate?.swipeToMinimize(translation: factor, toState: .hidden)
} else {
finalState = .fullScreen
let factor = 1 - (abs(sender.translation(in: nil).y) / UIScreen.main.bounds.height)
self.changeValues(scaleFactor: factor)
self.delegate?.swipeToMinimize(translation: factor, toState: .fullScreen)
}
default: break
}
if sender.state == .ended {
self.state = finalState
self.animate()
self.delegate?.didEndedSwipe(toState: self.state)
if self.state == .hidden {
self.videoPlayer.pause()
}
}
}
//MARK: Delegate & dataSource methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let count = self.video?.suggestedVideos.count {
return count + 1
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var returnCell = UITableViewCell()
switch indexPath.row {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "Header") as! headerCell
cell.title.text = self.video!.title
cell.viewCount.text = "\(self.video!.viewCount) views"
cell.likes.text = String(self.video!.likes)
cell.disLikes.text = String(self.video!.disLikes)
cell.channelTitle.text = self.video!.channelTitle
cell.channelPic.image = self.video!.channelPic
cell.channelPic.layer.cornerRadius = 25
cell.channelPic.clipsToBounds = true
cell.channelSubscribers.text = "\(self.video!.channelSubscribers) subscribers"
cell.selectionStyle = .none
returnCell = cell
default:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! videoCell
cell.name.text = self.video?.suggestedVideos[indexPath.row - 1].name
cell.title.text = self.video?.suggestedVideos[indexPath.row - 1].title
cell.tumbnail.image = self.video?.suggestedVideos[indexPath.row - 1].thumbnail
returnCell = cell
}
return returnCell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var height: CGFloat
switch indexPath.row {
case 0:
height = 180
default:
height = 90
}
return height
}
//MARK: ViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.customization()
Video.download(link: self.link) { (video) in
self.video = video
DispatchQueue.main.async(execute: {
self.videoPlayer = AVPlayer.init(url: video.videoLink)
let playerLayer = AVPlayerLayer.init(player: self.videoPlayer)
playerLayer.frame = self.player.bounds
self.player.layer.addSublayer(playerLayer)
if self.state != .hidden {
self.videoPlayer.play()
}
self.tableView.reloadData()
})
}
}
}
class headerCell: UITableViewCell {
//MARK: Properties
@IBOutlet weak var title: UILabel!
@IBOutlet weak var viewCount: UILabel!
@IBOutlet weak var likes: UILabel!
@IBOutlet weak var disLikes: UILabel!
@IBOutlet weak var channelTitle: UILabel!
@IBOutlet weak var channelPic: UIImageView!
@IBOutlet weak var channelSubscribers: UILabel!
//MARK: Inits
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class videoCell: UITableViewCell {
//MARK: Properties
@IBOutlet weak var tumbnail: UIImageView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var name: UILabel!
//MARK: Inits
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
|
apache-2.0
|
67b155b9e459461d60242cc5e0e8bdea
| 36.846512 | 178 | 0.610913 | 4.641757 | false | false | false | false |
fablabruffini/iOS-weather-app
|
MeteoProject_WE/ViewController.swift
|
1
|
4142
|
//
// ViewController.swift
// MeteoProject
//
// Created by Luca on 19/01/2017.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var refreshButton: UIButton!
@IBOutlet var barometerLabel: UILabel!
@IBOutlet var outTemp: UILabel!
@IBOutlet var windChill: UILabel!
@IBOutlet var windDirection: UILabel!
@IBOutlet var windSpeed: UILabel!
@IBOutlet var lastData: UILabel!
@IBOutlet var Statuslabel: UILabel!
@IBOutlet weak var loadingView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.refreshButton.isEnabled = false
let when = DispatchTime.now() + 2 // change 2 to desired number of seconds
DispatchQueue.main.asyncAfter(deadline: when) {
_ = self.data()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
//Dispose of any resources that can be recreated.
}
//api reference
func weather_request(forComune: String) -> Data? {
let api_key = "daily.json"
guard let url = URL(string: "http://www.ruffinifablab.it/weewx/\(api_key)") else {
return nil
}
guard let data = try? Data(contentsOf: url) else {
print("[ERROR] There is an unspecified error with the connection")
return nil
}
print("[CONNECTION] OK, data correctly downloaded")
return data
}
//json parsing function
func json_parseData(_ data: Data) -> NSDictionary? {
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
print("[JSON] OK!")
print(json)
return (json as? NSDictionary)
} catch _ {
print("[ERROR] An error has happened with parsing of json data")
return nil
}
}
//internet connection check
func checkWiFi() -> Bool {
let networkStatus = Reachability().connectionStatus()
switch networkStatus {
case .Unknown, .Offline:
print("No connection")
return false
case .Online(.WWAN):
print("Connected via WWAN")
return true
case .Online(.WiFi):
print("Connected via WiFi")
return true
}
}
func data() {
let connection = checkWiFi()
barometerLabel.text = "--"
outTemp.text = "--"
windChill.text = "--"
windDirection.text = "--"
windSpeed.text = "--"
lastData.text = "Connessione Assente."
Statuslabel.text = "N/A"
if(connection == true){
let data = weather_request(forComune: "Viterbo")
_ = json_parseData(data!)
//extraction data
if let json = json_parseData(data!) {
let weather_array: NSArray = (json["current"] as? NSArray)!
let weather: NSDictionary = weather_array[0] as! NSDictionary
//UIoutput
barometerLabel.text = weather["barometer"] as? String
outTemp.text = weather["outTemp"] as? String
windChill.text = weather["windchill"] as? String
windDirection.text = weather["windDirText"] as? String
windSpeed.text = weather["windSpeed"] as? String
lastData.text = weather["time"] as? String
Statuslabel.text = weather["isonline"] as? String
}
}
self.loadingView.isHidden = true
self.refreshButton.isEnabled = true
}
@IBAction func refresh(_ sender: Any) {
//invoke data function
self.loadingView.isHidden = false
self.refreshButton.isEnabled = false
let when = DispatchTime.now() + 2
DispatchQueue.main.asyncAfter(deadline: when) {
_ = self.data()
}
}
}
|
gpl-3.0
|
c94bf282d4f1d0b9f1577168eb6713c6
| 29.681481 | 128 | 0.547803 | 4.966427 | false | false | false | false |
moked/iuob
|
iUOB 2/Models/Course.swift
|
1
|
1032
|
//
// Course.swift
// iUOB 2
//
// Created by Miqdad Altaitoon on 8/10/16.
// Copyright © 2016 Miqdad Altaitoon. All rights reserved.
//
import Foundation
struct Course {
init(name: String, code: String, credits: String, preRequisite: String, url: String, abv: String, courseNo: String, departmentCode: String) {
self.name = name
self.code = code
self.credits = credits
self.preRequisite = preRequisite
self.url = url
self.abv = abv
self.courseNo = courseNo
self.departmentCode = departmentCode
}
var name: String = "" // ANALYSIS AND DESIGN
var code: String = "" // ITCS346
var credits: String = "" // 3
var preRequisite: String = "" // ITCS215 ITCS253
var url: String = "" // ..prog=1&abv=ITCS&inl=222&crsno=346&crd=3&cyer=2016&csms=1
var abv: String = "" // ITCS
var courseNo: String = "" // 346
var departmentCode: String = "" // 222
}
|
mit
|
bd01ec85d818bef8d7c336ff908e5465
| 29.352941 | 145 | 0.57032 | 3.391447 | false | false | false | false |
cuappdev/podcast-ios
|
old/Podcast/ListeningHistoryEndpointRequests.swift
|
1
|
3177
|
//
// ListeningHistoryEndpointRequests.swift
// Podcast
//
// Created by Jack Thompson on 8/27/18.
// Copyright © 2018 Cornell App Development. All rights reserved.
//
import Foundation
import SwiftyJSON
class FetchListeningHistoryEndpointRequest: EndpointRequest {
var offset: Int
var max: Int
// dismissed is an optional argument that if supplied will filter the
// listening history such that all returned listening history entries have their dismissed value equal to the supplied value.
var dismissed: Bool?
init(offset: Int, max: Int, dismissed: Bool? = nil) {
self.offset = offset
self.max = max
self.dismissed = dismissed
super.init()
path = "/history/listening/"
httpMethod = .get
queryParameters = ["offset": offset, "max": max]
if let dismiss = dismissed {
queryParameters["dismissed"] = dismiss.description
}
}
override func processResponseJSON(_ json: JSON) {
processedResponseValue = json["data"]["listening_histories"].map{ episodeJosn in
Cache.sharedInstance.update(episodeJson: episodeJosn.1["episode"])
}
}
}
class DeleteListeningHistoryElementEndpointRequest: EndpointRequest {
var episodeID: String
init(episodeID: String) {
self.episodeID = episodeID
super.init()
path = "/history/listening/\(episodeID)/"
httpMethod = .delete
}
}
class SaveListeningDurationEndpointRequest: EndpointRequest {
var listeningDurations: [String: ListeningDuration]
init(listeningDurations: [String: ListeningDuration]) {
self.listeningDurations = listeningDurations
super.init()
path = "/history/listening/"
httpMethod = .post
var params: [String: Any] = [:]
listeningDurations.forEach { (id, listeningDuration) in
var episodeJSON: [String:Any] = [:]
if let currentProgress = listeningDuration.currentProgress {
episodeJSON["current_progress"] = currentProgress
}
if let duration = listeningDuration.realDuration {
episodeJSON["real_duration"] = duration
}
episodeJSON["percentage_listened"] = listeningDuration.percentageListened
params[id] = episodeJSON
}
bodyParameters = params
}
}
class DismissCurrentListeningHistoryEndpointRequest: EndpointRequest {
var episodeID: String
var dismissed: Bool?
// dismissed is an optional boolean argument.
// Supplying true will dismiss the episode and supplying false will un-dismiss it. Supplying no argument defaults to true.
init(episodeID: String, dismissed: Bool? = nil) {
self.episodeID = episodeID
self.dismissed = dismissed
super.init()
path = "/history/listening/dismiss/\(episodeID)/"
httpMethod = .post
if let dismiss = dismissed {
queryParameters = ["dismissed": dismiss.description]
}
}
}
|
mit
|
45f6b0f50361acd2b2e06988159f8b08
| 29.247619 | 129 | 0.62437 | 5.0816 | false | false | false | false |
strike65/SwiftyStats
|
SwiftyStats/CommonSource/ProbDist/ProbDist-FRatio.swift
|
1
|
21854
|
//
// Created by VT on 20.07.18.
// Copyright © 2018 strike65. All rights reserved.
/*
Copyright (2017-2019) strike65
GNU GPL 3+
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, version 3 of the License.
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 Foundation
#if os(macOS) || os(iOS)
import os.log
#endif
extension SSProbDist {
/// F Ratio distribution
public enum FRatio {
/// Returns a SSProbDistParams struct containing mean, variance, kurtosis and skewness of the F ratio distribution.
/// - Parameter df1: numerator degrees of freedom
/// - Parameter df2: denominator degrees of freedom
/// - Throws: SSSwiftyStatsError if df1 <= 0 and/or df2 <= 0
public static func para<FPT: SSFloatingPoint & Codable>(numeratorDF df1: FPT, denominatorDF df2: FPT) throws -> SSProbDistParams<FPT> {
var result: SSProbDistParams<FPT> = SSProbDistParams<FPT>()
if df1 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("numerator degrees of freedom are expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if df2 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("denominator degrees of freedom expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if (df2 > 2) {
result.mean = df2 / (df2 - 2)
}
else {
result.mean = FPT.nan
}
if (df2 > 4) {
let e1: FPT = (df1 + df2 - 2)
let e2: FPT = (df2 - 4)
let e3: FPT = df1 * SSMath.pow1(df2 - 2, 2)
let e4: FPT = 2 * SSMath.pow1(df2, 2)
result.variance = (e4 * e1) / (e3 * e2)
}
else {
result.variance = FPT.nan
}
if (df2 > 6) {
let d1 = (2 * df1 + df2 - 2)
let d2 = (df2 - 6)
let s1 = (8 * (df2 - 4))
let s2 = (df1 * (df1 + df2 - 2))
result.skewness = (d1 / d2) * sqrt(s1 / s2)
}
else {
result.skewness = FPT.nan
}
if (df2 > 8) {
let s1 = SSMath.pow1(df2 - 2,2)
let s2 = df2 - 4
let s3 = df1 + df2 - 2
let s4 = 5 * df2 - 22
let s5 = df2 - 6
let s6 = df2 - 8
let s7 = df1 + df2 - 2
let ss1 = (s1 * (s2) + df1 * (s3) * (s4))
let ss2 = df1 * (s5) * (s6) * (s7)
result.kurtosis = 3 + (12 * ss1) / (ss2)
}
else {
result.kurtosis = FPT.nan
}
return result
}
/// Returns the pdf of the F-ratio distribution.
/// - Parameter f: f-value
/// - Parameter df1: numerator degrees of freedom
/// - Parameter df2: denominator degrees of freedom
/// - Throws: SSSwiftyStatsError if df1 <= 0 and/or df2 <= 0
public static func pdf<FPT: SSFloatingPoint & Codable>(f: FPT, numeratorDF df1: FPT, denominatorDF df2: FPT) throws -> FPT {
if df1 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("numerator degrees of freedom are expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if df2 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("denominator degrees of freedom are expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
var result: FPT
var f1: FPT
var f2: FPT
var f3: FPT
var f4: FPT
var f5: FPT
var f6: FPT
var f7: FPT
var f8: FPT
var f9: FPT
var lg1: FPT
var lg2: FPT
var lg3: FPT
var ex1: FPT
var ex2: FPT
var ex3: FPT
if f >= 0 {
f1 = (df1 + df2) / 2
f2 = df1 / 2
f3 = df2 / 2
lg1 = SSMath.lgamma1(f1)
lg2 = SSMath.lgamma1(f2)
lg3 = SSMath.lgamma1(f3)
f4 = (df1 / 2) * SSMath.log1(df1 / df2)
f5 = (df1 / 2 - 1) * SSMath.log1(f)
ex1 = (df1 + df2) / 2
ex2 = df1 * f / df2
ex3 = FPT.one + ex2
f6 = ex1 * SSMath.log1(ex3)
// f6 = ((df1 + df2) / 2) * SSMath.log1(1 + df1 * f / df2)
f7 = lg1 - (lg2 + lg3) + f4
f8 = f5 - f6
f9 = f7 + f8
result = SSMath.exp1(f9)
}
else {
result = 0
}
return result
}
/// Returns the cdf of the F-ratio distribution. (http://mathworld.wolfram.com/F-Distribution.html)
/// - Parameter f: f-value
/// - Parameter df1: numerator degrees of freedom
/// - Parameter df2: denominator degrees of freedom
/// - Throws: SSSwiftyStatsError if df1 <= 0 and/or df2 <= 0
public static func cdf<FPT: SSFloatingPoint & Codable>(f: FPT, numeratorDF df1: FPT, denominatorDF df2: FPT) throws -> FPT {
var ex1: FPT
var ex2: FPT
var ex3: FPT
var ex4: FPT
var ex5: FPT
if f <= 0 {
return 0
}
if df1 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("numerator degrees of freedom are expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if df2 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("denominator degrees of freedom are expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
ex1 = f * df1
ex2 = df2 + ex1
ex3 = ex1 / ex2
ex4 = df1 * FPT.half
ex5 = df2 * FPT.half
let result = SSSpecialFunctions.betaNormalized(x: ex3, a: ex4, b: ex5)
return result
}
/// Returns the quantile function of the F-ratio distribution.
/// - Parameter p: p
/// - Parameter df1: numerator degrees of freedom
/// - Parameter df2: denominator degrees of freedom
/// - Throws: SSSwiftyStatsError if df1 <= 0 and/or df2 <= 0 and/or p < 0 and/or p > 1
public static func quantile<FPT: SSFloatingPoint & Codable>(p: FPT,numeratorDF df1: FPT, denominatorDF df2: FPT) throws -> FPT {
if df1 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("numerator degrees of freedom are expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if df2 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("denominator degrees of freedom expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if p < 0 || p > 1 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("p is expected to be >= 0.0 and <= 1.0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
let eps: FPT = FPT.ulpOfOne
if abs( p - 1 ) <= eps {
return FPT.infinity
}
if abs(p) <= eps {
return 0
}
var fVal: FPT
var maxF: FPT
var minF: FPT
maxF = 9999
minF = 0
fVal = 1 / p
var it: Int = 0
var temp_p: FPT
let lower: FPT = Helpers.makeFP(1E-12)
let half: FPT = FPT.half
while((maxF - minF) > lower)
{
if it == 1000 {
break
}
do {
temp_p = try cdf(f: fVal, numeratorDF: df1, denominatorDF: df2)
}
catch {
return FPT.nan
}
if temp_p > p {
maxF = fVal
}
else {
minF = fVal
}
fVal = (maxF + minF) * half
it = it + 1
}
return fVal
}
}
}
extension SSProbDist {
/// Non central F Ratio distribution
public enum NonCentralFRatio {
/// Returns a SSProbDistParams struct containing mean, variance, kurtosis and skewness of the noncentral F ratio distribution.
/// - Parameter df1: numerator degrees of freedom
/// - Parameter df2: denominator degrees of freedom
/// - Parameter lambda: noncentrality
/// - Throws: SSSwiftyStatsError if df1 <= 0 and/or df2 <= 0
public static func para<FPT: SSFloatingPoint & Codable>(numeratorDF df1: FPT, denominatorDF df2: FPT, lambda: FPT) throws -> SSProbDistParams<FPT> {
var e1, e2, e3, e4, e5, e6, e7: FPT
var ex1: FPT
var ex2: FPT
var ex3: FPT
var ex4: FPT
var ex5: FPT
var result: SSProbDistParams<FPT> = SSProbDistParams<FPT>()
if df1 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("numerator degrees of freedom are expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if df2 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("denominator degrees of freedom expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if lambda.isZero {
do {
return try SSProbDist.FRatio.para(numeratorDF: df1, denominatorDF: df2)
}
catch {
throw error
}
}
if (df2 > 2) {
ex1 = lambda + df1
ex2 = df2 * ex1
ex3 = df2 - 2
ex4 = ex3 * df1
result.mean = ex2 / ex4
}
else {
result.mean = FPT.nan
}
if (df2 > 4) {
e1 = (1 + df1) * (1 + df1)
ex1 = df2 - 2
ex2 = 2 * lambda + df1
e2 = ex1 * ex2
e3 = 2 * SSMath.pow1(df2, 2) * (e1 + e2)
e1 = df2 - 4
e2 = SSMath.pow1(df2 - 2, 2) * SSMath.pow1(df1, 2)
result.variance = e3 / (e1 * e2)
}
else {
result.variance = FPT.nan
}
if (df2 > 6) {
e1 = 2 * FPT.sqrt2 * sqrt(df2 - 4)
e2 = df1 * (df1 + df2 - 2)
ex1 = 2 * df1
ex2 = df2 - FPT.one
ex3 = ex1 + ex2
e3 = e2 * ex3
e4 = 3 * (df2 + 2 * df1)
ex1 = 2 * df1
ex2 = df2 - 2
ex3 = ex1 + ex2
ex4 = ex3 * lambda
e5 = e4 * ex4
ex1 = df1 + df2 - 2
ex2 = 6 * ex1
e6 = ex2 * SSMath.pow1(lambda,2)
ex1 = e3 + e5 + e6
ex2 = ex1 + 2
e7 = ex2 * SSMath.pow1(lambda, 3)
let d1 = e1 * e7
e1 = df2 - 6
e2 = df1 * (df1 + df2 - 2)
ex1 = df1 + df2 - 2
ex2 = 2 * ex1
ex3 = ex2 * lambda
e3 = e2 + ex3
e4 = e3 + SSMath.pow1(lambda, 2)
let d2 = e1 * SSMath.pow1(e4, Helpers.makeFP(1.5))
result.skewness = (d1 / d2) * e1
}
else {
result.skewness = FPT.nan
}
if (df2 > 8) {
e1 = 3 * (df2 - 4)
e2 = df1 * (-2 + df1 + df2)
e3 = 4 * SSMath.pow1(-2 + df2, 2)
e4 = e3 + SSMath.pow1(df1, 2) * (10 + df2)
ex1 = (df2 - 2)
ex2 = (10 + df2)
ex3 = ex1 * ex2
ex4 = df1 * ex3
e5 = e4 + ex4
let d1: FPT = e2 * e5
e2 = 4 * (-2 + df1 + df2)
e3 = 4 * SSMath.pow1(-2 + df2, 2)
e4 = e3 + SSMath.pow1(df1, 2) * (10 + df2)
ex1 = (df2 - 2)
ex2 = (10 + df2)
ex3 = ex1 * ex2
ex4 = df1 * ex3
e5 = e4 + ex4
let d2: FPT = e1 * e4 * lambda
e2 = 2 * (10 + df2)
e3 = e2 * (-2 + df1 + df2)
ex1 = 3 * df1
ex2 = 2 * df2
ex3 = ex1 + ex2
ex4 = ex3 - 4
e4 = e3 * ex4
let d3: FPT = e4 * SSMath.pow1(lambda,2)
e2 = 4 * (10 + df2)
ex1 = df1 + df2 - 2
ex2 = ex1 * SSMath.pow1(lambda, 3)
let d4: FPT = e2 * ex2
let d5: FPT = SSMath.pow1(lambda, 4) * (10 + df2)
ex1 = d1 + d2
ex2 = ex1 + d3
ex3 = ex2 + d4
ex5 = ex4 + d5
let A: FPT = e1 * ex5
let d6: FPT = (-8 + df2) * (-8 + df2)
e1 = df1 * (-2 + df1 + df2)
ex1 = df1 + df2
ex2 = ex1 - 2
ex3 = ex2 * lambda
ex4 = 2 * ex3
e2 = e1 + ex4
e3 = e2 + SSMath.pow1(lambda, 2)
let d7: FPT = SSMath.pow1(e3, 2)
let B: FPT = d6 * d7
result.kurtosis = A / B
}
else {
result.kurtosis = FPT.nan
}
return result
}
/// Returns the pdf of the F-ratio distribution.
/// - Parameter f: f-value
/// - Parameter df1: numerator degrees of freedom
/// - Parameter df2: denominator degrees of freedom
/// - Parameter lambda: Noncentrality
/// - Throws: SSSwiftyStatsError if df1 <= 0 and/or df2 <= 0
public static func pdf<FPT: SSFloatingPoint & Codable>(f: FPT, numeratorDF df1: FPT, denominatorDF df2: FPT, lambda: FPT) throws -> FPT {
var ex1: FPT
var ex2: FPT
var ex3: FPT
var ex4: FPT
if df1 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("numerator degrees of freedom are expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if df2 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("denominator degrees of freedom expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if lambda.isZero {
do {
return try SSProbDist.FRatio.pdf(f: f, numeratorDF: df1, denominatorDF: df2)
}
catch {
throw error
}
}
let y: FPT = f * df1 / df2
let beta: FPT
do {
ex1 = y / (FPT.one + y)
ex2 = df1 / 2
ex3 = df2 / 2
beta = try SSProbDist.NoncentralBeta.pdf(x: ex1, shapeA: ex2, shapeB: ex3, lambda: lambda)
}
catch {
throw error
}
ex1 = df1 / df2
ex2 = (1 + y)
ex3 = ex2 * ex2
ex4 = ex1 / ex3
let ans: FPT = ex4 * beta
return ans
}
/// Returns the cdf of the noncentral F-ratio distribution. (http://mathworld.wolfram.com/F-Distribution.html)
/// - Parameter f: f-value
/// - Parameter df1: numerator degrees of freedom
/// - Parameter df2: denominator degrees of freedom
/// - Parameter lambda: Noncentrality
/// - Throws: SSSwiftyStatsError if df1 <= 0 and/or df2 <= 0
public static func cdf<FPT: SSFloatingPoint & Codable>(f: FPT, numeratorDF df1: FPT, denominatorDF df2: FPT, lambda: FPT) throws -> FPT {
if f <= 0 {
return 0
}
if df1 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("numerator degrees of freedom are expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if df2 <= 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("denominator degrees of freedom are expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if lambda == 0 {
do {
return try SSProbDist.FRatio.cdf(f: f, numeratorDF: df1, denominatorDF: df2)
}
catch {
throw error
}
}
let y: FPT = f * df1 / (df2 + df1 * f)
var ans: FPT = FPT.nan
do {
let ncbeta: FPT = try SSProbDist.NoncentralBeta.cdf(x: y, shapeA: df1 / 2, shapeB: df2 / 2, lambda: lambda)
ans = ncbeta
}
catch {
throw error
}
return ans
}
}
}
|
gpl-3.0
|
43642eae0fe30c669772dc3001af1a12
| 36.939236 | 156 | 0.430513 | 4.077052 | false | false | false | false |
jeremyabannister/JABSwiftCore
|
JABSwiftCore/JABBlurLayer.swift
|
1
|
4855
|
//
// JABBlurLayer.swift
// JABSwiftCore
//
// Created by Jeremy Bannister on 4/25/17.
// Copyright © 2017 Jeremy Bannister. All rights reserved.
//
import UIKit
public class JABBlurLayer: JABView {
// MARK:
// MARK: Properties
// MARK:
// MARK: Delegate
// MARK: State
public var blurStyle: UIBlurEffectStyle = .extraLight
public var blurFraction: CGFloat = 1.0
public var blurAnimationCurve: UIViewAnimationCurve = .linear
private var blurAnimator: Any?
private var blurPauseTimer: Timer?
private var isUnblurring = false
// MARK: UI
private let visualEffectView = UIVisualEffectView()
// MARK: Parameters
// **********************************************************************************************************************
// MARK:
// MARK: Methods
// MARK:
// MARK:
// MARK: Init
// MARK:
public init () {
super.init(frame: CGRect.zero)
}
public required init? (coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
print("Should not be initializing from coder \(self)")
}
// MARK: Parameters
override public func updateParameters() {
}
// MARK:
// MARK: UI
// MARK:
// MARK: All
override public func addAllUI() {
addVisualEffectView()
}
override public func updateAllUI() {
updateParameters()
configureVisualEffectView()
positionVisualEffectView()
}
// MARK: Adding
private func addVisualEffectView () {
addSubview(visualEffectView)
}
// MARK: Visual Effect View
private func configureVisualEffectView () {
// let view = visualEffectView
}
private func positionVisualEffectView () {
let view = visualEffectView
var newSite = CGRect.zero
newSite.size.width = width
newSite.size.height = height
newSite.origin.x = (width - newSite.size.width)/2
newSite.origin.y = (height - newSite.size.height)/2
view.site = newSite
}
// MARK:
// MARK: Actions
// MARK:
// MARK: Blur
public func blur (duration: TimeInterval = defaultAnimationDuration, completion: @escaping (Bool) -> () = { position in }) {
if #available(iOS 10, *) {
let animator = UIViewPropertyAnimator(duration: duration/Double(blurFraction), curve: .linear, animations: { self.visualEffectView.effect = UIBlurEffect(style: self.blurStyle) })
if let blurAnimator = blurAnimator as? UIViewPropertyAnimator {
// If we give blurAnimator a new value while it currently holds a paused or stopped animator the app will crash. Therefore we must always stop the potential preexisting animator before assigning a new value to it. However, stopping it while it is already stopped will also cause a crash, so we have to check for it
if blurAnimator.state == .stopped { blurAnimator.finishAnimation(at: .current) }
}
blurAnimator = animator
animator.startAnimation()
blurPauseTimer = Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(pauseBlur), userInfo: completion, repeats: false)
} else {
UIView.animate(withDuration: duration, animations: { self.visualEffectView.effect = UIBlurEffect(style: self.blurStyle) }, completion: completion)
}
}
@objc public func pauseBlur (timer: Timer) {
if let completion = timer.userInfo as? (Bool) -> () { completion(true) }
if #available(iOS 10, *) {
guard let animator = blurAnimator as? UIViewPropertyAnimator else { return }
if !isUnblurring { animator.stopAnimation(false) }
}
}
/**
Reverse the original blur animation
- Author:
Jeremy Bannister
*/
public func unblur (duration: TimeInterval = defaultAnimationDuration, completion: @escaping (Bool) -> () = { position in }) {
if #available(iOS 10, *) {
blurPauseTimer?.invalidate()
if let blurAnimator = blurAnimator as? UIViewPropertyAnimator { if blurAnimator.state == .stopped { blurAnimator.finishAnimation(at: .current) } }
let animator = UIViewPropertyAnimator(duration: duration, curve: .linear, animations: { self.visualEffectView.effect = nil })
// In iOS 10, setting fractionComplete causes the animator to get stuck at this fraction, but in iOS 11 this is essential to prevent the animation starting from full blur
if #available(iOS 11, *) { animator.fractionComplete = 1 - blurFraction }
animator.addCompletion({ (position) in self.isUnblurring = false; completion(true) })
isUnblurring = true
animator.startAnimation()
} else {
UIView.animate(withDuration: duration, animations: { self.visualEffectView.effect = nil }, completion: completion)
}
}
// MARK:
// MARK: Delegate Methods
// MARK:
}
|
mit
|
c9a38533f50f3ee168d5c7480cc5937b
| 25.966667 | 322 | 0.646271 | 4.636103 | false | false | false | false |
hovansuit/FoodAndFitness
|
FoodAndFitness/Controllers/TrackingDetail/TrackingDetailViewModel.swift
|
1
|
1254
|
//
// TrackingDetailViewModel.swift
// FoodAndFitness
//
// Created by Mylo Ho on 5/29/17.
// Copyright © 2017 SuHoVan. All rights reserved.
//
import UIKit
import CoreLocation
class TrackingDetailViewModel {
let params: TrackingParams
init(params: TrackingParams) {
self.params = params
}
func save(completion: @escaping Completion) {
if User.me == nil {
let error = NSError(message: Strings.Errors.tokenError)
completion(.failure(error))
} else {
TrackingServices.save(params: params, completion: completion)
}
}
func data() -> TrackingDetailController.Data {
let active = Strings.active + ": " + params.active
let duration = Strings.duration + ": \(params.duration)"
let distance = Strings.distance + ": \(params.distance)"
return TrackingDetailController.Data(active: active, duration: duration, distance: distance)
}
func coordinatesForMap() -> [CLLocationCoordinate2D] {
var result: [CLLocationCoordinate2D] = []
for location in params.locations {
let clLocation = location.toCLLocation
result.append(clLocation.coordinate)
}
return result
}
}
|
mit
|
07d487b1155d509f456641ad42c33435
| 27.477273 | 100 | 0.636872 | 4.523466 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin
|
Pod/Classes/Sources.Api/BasePIMBridge.swift
|
1
|
3200
|
/**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:carlos@adaptive.me>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:ferran.vila.conesa@gmail.com>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Base application for PIM purposes
Auto-generated implementation of IBasePIM specification.
*/
public class BasePIMBridge : IBasePIM {
/**
Group of API.
*/
private var apiGroup : IAdaptiveRPGroup? = nil
/**
Default constructor.
*/
public init() {
self.apiGroup = IAdaptiveRPGroup.PIM
}
/**
Return the API group for the given interface.
*/
public final func getAPIGroup() -> IAdaptiveRPGroup? {
return self.apiGroup!
}
/**
Return the API version for the given interface.
*/
public final func getAPIVersion() -> String? {
return "v2.2.15"
}
/**
Invokes the given method specified in the API request object.
@param request APIRequest object containing method name and parameters.
@return APIResponse with status code, message and JSON response or a JSON null string for void functions. Status code 200 is OK, all others are HTTP standard error conditions.
*/
public func invoke(request : APIRequest) -> APIResponse? {
let response : APIResponse = APIResponse()
var responseCode : Int32 = 200
var responseMessage : String = "OK"
let responseJSON : String? = "null"
switch request.getMethodName()! {
default:
// 404 - response null.
responseCode = 404
responseMessage = "BasePIMBridge does not provide the function '\(request.getMethodName()!)' Please check your client-side API version; should be API version >= v2.2.15."
}
response.setResponse(responseJSON!)
response.setStatusCode(responseCode)
response.setStatusMessage(responseMessage)
return response
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
|
apache-2.0
|
3065ed460bc7b14d9926eb96b8f732f1
| 33.021277 | 186 | 0.607255 | 4.942813 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Modules/Principal Content/ApplicationPrincipalModuleFactory.swift
|
1
|
1427
|
import ComponentBase
import ContentController
import UIKit
public struct ApplicationPrincipalModuleFactory: PrincipalContentModuleFactory {
private let applicationModuleFactories: [ApplicationModuleFactory]
public init(applicationModuleFactories: [ApplicationModuleFactory]) {
self.applicationModuleFactories = applicationModuleFactories
}
public func makePrincipalContentModule() -> UIViewController {
let applicationModules = applicationModuleFactories.map({ $0.makeApplicationModuleController() })
let navigationControllers = applicationModules.map(BrandedNavigationController.init)
let splitViewControllers = navigationControllers.map { (navigationController) -> UISplitViewController in
let splitViewController = BrandedSplitViewController()
let noContentPlaceholder = NoContentPlaceholderViewController.fromStoryboard()
let noContentNavigation = UINavigationController(rootViewController: noContentPlaceholder)
splitViewController.viewControllers = [navigationController, noContentNavigation]
splitViewController.tabBarItem = navigationController.tabBarItem
return splitViewController
}
let tabBarController = TabBarController()
tabBarController.viewControllers = splitViewControllers
return tabBarController
}
}
|
mit
|
59068800d66d7a79f8e9267888d1869c
| 43.59375 | 113 | 0.749124 | 6.927184 | false | false | false | false |
jphacks/TK_08
|
iOS/AirMeet/AirMeet/SABlurImageView/SABlurImageView.swift
|
1
|
5932
|
//
// UIImageView+BlurEffect.swift
// SABlurImageView
//
// Created by 鈴木大貴 on 2015/03/27.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
import Foundation
import QuartzCore
public class SABlurImageView : UIImageView {
private typealias AnimationFunction = Void -> ()
//MARK: - Static Properties
static private let FadeAnimationKey = "Fade"
//MARK: - Instance Properties
private let kMaxImageCount: Int = 10
private var cgImages: [CGImage] = [CGImage]()
private var nextBlurLayer: CALayer?
private var previousImageIndex: Int = -1
private var previousPercentage: Float = 0.0
private var animations: [AnimationFunction]?
deinit {
cgImages.removeAll(keepCapacity: false)
nextBlurLayer?.removeFromSuperlayer()
nextBlurLayer = nil
animations?.removeAll(keepCapacity: false)
animations = nil
layer.removeAllAnimations()
}
}
//MARK: = Life Cycle
public extension SABlurImageView {
public override func layoutSubviews() {
super.layoutSubviews()
nextBlurLayer?.frame = bounds
}
}
//MARK: - Public Methods
public extension SABlurImageView {
public func addBlurEffect(boxSize: Float, times: UInt = 1) {
if var image = image {
for _ in 0..<times {
image = image.blurEffect(boxSize)
}
self.image = image
}
}
public func configrationForBlurAnimation(boxSize: Float = 100) {
guard var image = image else {
return
}
if let cgImage = image.CGImage {
cgImages += [cgImage]
}
var newBoxSize = boxSize
if newBoxSize > 200 {
newBoxSize = 200
} else if newBoxSize < 0 {
newBoxSize = 0
}
let number = sqrt(Double(newBoxSize)) / Double(kMaxImageCount)
for index in 0..<kMaxImageCount {
let value = Double(index) * number
let boxSize = value * value
image = image.blurEffect(Float(boxSize))
if let cgImage = image.CGImage {
cgImages += [cgImage]
}
}
}
public func blur(percentage: Float) {
var newPercentage = percentage
if newPercentage < 0.0 {
newPercentage = 0.0
} else if newPercentage > 1.0 {
newPercentage = 0.99
}
if previousPercentage - newPercentage > 0 {
let index = Int(floor(newPercentage * 10)) + 1
if index > 0 {
setLayers(index, percentage: newPercentage, currentIndex: index - 1, nextIndex: index)
}
} else {
let index = Int(floor(newPercentage * 10))
if index < cgImages.count - 1 {
setLayers(index, percentage: newPercentage, currentIndex: index, nextIndex: index + 1)
}
}
previousPercentage = newPercentage
}
private func setLayers(index: Int, percentage: Float, currentIndex: Int, nextIndex: Int) {
if index != previousImageIndex {
CATransaction.begin()
CATransaction.setAnimationDuration(0)
layer.contents = cgImages[currentIndex]
CATransaction.commit()
if nextBlurLayer == nil {
let nextBlurLayer = CALayer()
nextBlurLayer.frame = bounds
layer.addSublayer(nextBlurLayer)
self.nextBlurLayer = nextBlurLayer
}
CATransaction.begin()
CATransaction.setAnimationDuration(0)
nextBlurLayer?.contents = cgImages[nextIndex]
nextBlurLayer?.opacity = 1.0
CATransaction.commit()
}
previousImageIndex = index
let minPercentage = percentage * 100.0
var alpha = (minPercentage - Float(Int(minPercentage / 10.0) * 10)) / 10.0
if alpha > 1.0 {
alpha = 1.0
} else if alpha < 0.0 {
alpha = 0.0
}
CATransaction.begin()
CATransaction.setAnimationDuration(0)
nextBlurLayer?.opacity = alpha
CATransaction.commit()
}
public func startBlurAnimation(duration _duration: Double) {
if animations == nil {
animations = [AnimationFunction]()
}
let count = Double(cgImages.count)
for cgImage in cgImages {
animations?.append() { [weak self] in
let transition = CATransition()
transition.duration = (_duration) / count
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
transition.type = kCATransitionFade
transition.fillMode = kCAFillModeForwards
transition.repeatCount = 1
transition.removedOnCompletion = false
transition.delegate = self
self?.layer.addAnimation(transition, forKey: SABlurImageView.FadeAnimationKey)
self?.layer.contents = cgImage
}
}
if let animation = animations?.first {
animation()
let _ = animations?.removeFirst()
}
cgImages = cgImages.reverse()
}
override public func animationDidStop(anim: CAAnimation, finished flag: Bool) {
guard let _ = anim as? CATransition else {
return
}
layer.removeAllAnimations()
if let animation = animations?.first {
animation()
let _ = animations?.removeFirst()
} else {
animations?.removeAll(keepCapacity: false)
animations = nil
}
}
}
|
mit
|
a93596ce09cac587141e87fe4b0edca7
| 29.963351 | 102 | 0.555969 | 5.111495 | false | false | false | false |
Antondomashnev/ADMozaicCollectionViewLayout
|
Pods/Nimble/Sources/Nimble/Matchers/BeginWith.swift
|
1
|
2640
|
import Foundation
/// A Nimble matcher that succeeds when the actual sequence's first element
/// is equal to the expected value.
public func beginWith<S: Sequence, T: Equatable>(_ startingElement: T) -> Predicate<S>
where S.Iterator.Element == T {
return Predicate.simple("begin with <\(startingElement)>") { actualExpression in
if let actualValue = try actualExpression.evaluate() {
var actualGenerator = actualValue.makeIterator()
return PredicateStatus(bool: actualGenerator.next() == startingElement)
}
return .fail
}
}
/// A Nimble matcher that succeeds when the actual collection's first element
/// is equal to the expected object.
public func beginWith(_ startingElement: Any) -> Predicate<NMBOrderedCollection> {
return Predicate.simple("begin with <\(startingElement)>") { actualExpression in
guard let collection = try actualExpression.evaluate() else { return .fail }
guard collection.count > 0 else { return .doesNotMatch }
#if os(Linux)
guard let collectionValue = collection.object(at: 0) as? NSObject else {
return .fail
}
#else
let collectionValue = collection.object(at: 0) as AnyObject
#endif
return PredicateStatus(bool: collectionValue.isEqual(startingElement))
}
}
/// A Nimble matcher that succeeds when the actual string contains expected substring
/// where the expected substring's location is zero.
public func beginWith(_ startingSubstring: String) -> Predicate<String> {
return Predicate.simple("begin with <\(startingSubstring)>") { actualExpression in
if let actual = try actualExpression.evaluate() {
let range = actual.range(of: startingSubstring)
return PredicateStatus(bool: range != nil && range!.lowerBound == actual.startIndex)
}
return .fail
}
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
extension NMBObjCMatcher {
@objc public class func beginWithMatcher(_ expected: Any) -> NMBMatcher {
return NMBPredicate { actualExpression in
let actual = try actualExpression.evaluate()
if actual is String {
let expr = actualExpression.cast { $0 as? String }
// swiftlint:disable:next force_cast
return try beginWith(expected as! String).satisfies(expr).toObjectiveC()
} else {
let expr = actualExpression.cast { $0 as? NMBOrderedCollection }
return try beginWith(expected).satisfies(expr).toObjectiveC()
}
}
}
}
#endif
|
mit
|
de931cabbb6dcc9f3082c2feb68f69a9
| 42.278689 | 96 | 0.654545 | 4.879852 | false | false | false | false |
voyages-sncf-technologies/Collor
|
Example/Collor/WeatherSample/service/WheatherService.swift
|
1
|
1185
|
//
// WeatherService.swift
// BABA
//
// Created by Guihal Gwenn on 16/02/17.
// Copyright © 2017 Guihal Gwenn. All rights reserved.
//
import Alamofire
import UIKit
final class WeatherService {
enum WheatherError : Error {
case unknowError
case networkError
}
enum WeatherResponse {
case success(WeatherModel)
case error(WheatherError)
}
func get16DaysWeather(completion: @escaping (WeatherResponse)->Void ) {
let url = "http://api.openweathermap.org/data/2.5/forecast/daily?id=6455259&appid=92b25fae9369a3cf06456eda297b162a&units=metric"
Alamofire.request(url).responseJSON { response in
switch (response.result) {
case .success(let data):
if let dictionary = data as? [String:Any], let weatherModel = WeatherModel(json: dictionary) {
completion( .success(weatherModel) )
} else {
completion( .error( .unknowError ) )
}
case .failure( _):
completion( .error( .networkError ) )
}
}
}
}
|
bsd-3-clause
|
7461eaff81a53dd936581181449b9c3e
| 26.534884 | 136 | 0.565034 | 4.228571 | false | false | false | false |
squall09s/VegOresto
|
VegoResto/UIView+Material.swift
|
1
|
7365
|
//
// UIView+Material.swift
// Pumpkin-v3
//
// Created by Nicolas on 03/10/2017.
// Copyright © 2017 Victor Lennel. All rights reserved.
//
import UIKit
let UIViewMaterialDesignTransitionDurationCoeff: TimeInterval = 0.65
extension UIView {
static func mdInflateTransitionFromView( fromView: UIView, toView: UIView, originalPoint: CGPoint, duration: TimeInterval, completion: ( () -> Void )? ) {
if let containerView = fromView.superview {
let convertedPoint: CGPoint = fromView.convert(originalPoint, to: fromView)
containerView.layer.masksToBounds = true
let animationHandler: (() -> Void) = {
toView.alpha = 0.0
toView.frame = fromView.frame
containerView.addSubview(toView)
fromView.removeFromSuperview()
let animationDuration: TimeInterval = (duration - duration * UIViewMaterialDesignTransitionDurationCoeff)
UIView.animate(withDuration: animationDuration, animations: { toView.alpha = 1.0 },
completion: { (_) in
completion?()
})
}
containerView.mdAnimateAtPoint(point: convertedPoint, backgroundColor: toView.backgroundColor ?? UIColor.black,
duration: duration * UIViewMaterialDesignTransitionDurationCoeff, inflating: true,
zTopPosition: true, shapeLayer: nil, completion: animationHandler)
} else {
completion?()
}
}
static func mdDeflateTransitionFromView(fromView: UIView, toView: UIView, originalPoint: CGPoint, duration: TimeInterval, completion : ( () -> Void )? ) {
if let containerView = fromView.superview {
containerView.insertSubview(toView, belowSubview: fromView)
toView.frame = fromView.frame
// convert point into container view coordinate system
let convertedPoint: CGPoint = toView.convert(originalPoint, to: fromView)
// insert layer
let layer: CAShapeLayer = toView.mdShapeLayerForAnimationAtPoint(point: convertedPoint)
layer.fillColor = fromView.backgroundColor?.cgColor
toView.layer.addSublayer(layer)
toView.layer.masksToBounds = true
// hide fromView
let animationDuration: TimeInterval = (duration - duration * UIViewMaterialDesignTransitionDurationCoeff)
UIView.animate(withDuration: animationDuration, animations: {
fromView.alpha = 0.0
}, completion: { (_) in
toView.mdAnimateAtPoint(point: convertedPoint, backgroundColor: fromView.backgroundColor ?? UIColor.black,
duration: duration * UIViewMaterialDesignTransitionDurationCoeff, inflating: false,
zTopPosition: true, shapeLayer: layer, completion: completion)
})
} else {
completion?()
}
}
func mdInflateAnimatedFromPoint(point: CGPoint, backgroundColor: UIColor, duration: TimeInterval, completion : ( () -> Void )? ) {
self.mdAnimateAtPoint(point: point, backgroundColor: backgroundColor, duration: duration, inflating: true, zTopPosition: false, shapeLayer: nil, completion: completion)
}
func mdDeflateAnimatedToPoint(point: CGPoint, backgroundColor: UIColor, duration: TimeInterval, completion : ( () -> Void )? ) {
self.mdAnimateAtPoint(point: point, backgroundColor: backgroundColor, duration: duration, inflating: false, zTopPosition: false, shapeLayer: nil, completion: completion)
}
func mdShapeDiameterForPoint(point: CGPoint ) -> CGFloat {
let cornerPoints: [CGPoint] = [ CGPoint(x: 0, y: 0),
CGPoint(x: 0, y: self.bounds.size.height),
CGPoint(x: self.bounds.size.width, y: self.bounds.size.height),
CGPoint(x: self.bounds.size.width, y: 0) ]
var radius: CGFloat = 0.0
for i in 0...(cornerPoints.count - 1) {
let p: CGPoint = cornerPoints[i]
let d: CGFloat = sqrt( pow(p.x - point.x, 2.0) + pow(p.y - point.y, 2.0) )
if d > radius {
radius = d
}
}
return radius * 2.0
}
func mdShapeLayerForAnimationAtPoint(point: CGPoint) -> CAShapeLayer {
let shapeLayer: CAShapeLayer = CAShapeLayer()
let diameter: CGFloat = self.mdShapeDiameterForPoint(point: point)
shapeLayer.frame = CGRect(x: floor(point.x - diameter * 0.5), y: floor(point.y - diameter * 0.5), width: diameter, height: diameter)
shapeLayer.path = UIBezierPath(ovalIn: CGRect(x: 0.0, y: 0.0, width: diameter, height: diameter) ).cgPath
return shapeLayer
}
func shapeAnimationWithTimingFunction(timingFunction: CAMediaTimingFunction, scale: CGFloat, inflating: Bool) -> CABasicAnimation {
let animation: CABasicAnimation = CABasicAnimation(keyPath: "transform")
if inflating {
animation.toValue = NSValue.init(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0))
animation.fromValue = NSValue.init(caTransform3D: CATransform3DMakeScale(scale, scale, 1.0))
} else {
animation.toValue = NSValue.init(caTransform3D: CATransform3DMakeScale(scale, scale, 1.0))
animation.fromValue = NSValue.init(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0))
}
animation.timingFunction = timingFunction
animation.isRemovedOnCompletion = true
return animation
}
func mdAnimateAtPoint(point: CGPoint, backgroundColor: UIColor, duration: TimeInterval, inflating: Bool, zTopPosition: Bool, shapeLayer: CAShapeLayer?, completion : ( () -> Void )? ) {
let shapeLayer = self.mdShapeLayerForAnimationAtPoint(point: point)
// create layer
self.layer.masksToBounds = true
if zTopPosition {
self.layer.addSublayer(shapeLayer)
} else {
self.layer.insertSublayer(shapeLayer, at: 0)
}
if inflating == false {
shapeLayer.fillColor = self.backgroundColor?.cgColor
self.backgroundColor = backgroundColor
} else {
shapeLayer.fillColor = backgroundColor.cgColor
}
// animate
let scale: CGFloat = 1.0 / shapeLayer.frame.size.width
let timingFunctionName: String = kCAMediaTimingFunctionDefault
let animation: CABasicAnimation = self.shapeAnimationWithTimingFunction(timingFunction: CAMediaTimingFunction(name: timingFunctionName), scale: scale, inflating: inflating)
animation.duration = duration
if let anim = (animation.toValue as? NSValue)?.caTransform3DValue {
shapeLayer.transform = anim
}
CATransaction.begin()
CATransaction.setCompletionBlock {
if inflating {
self.backgroundColor = backgroundColor
}
shapeLayer.removeFromSuperlayer()
completion?()
}
shapeLayer.add(animation, forKey: "shapeBackgroundAnimation")
CATransaction.commit()
}
}
|
gpl-3.0
|
80b27ba5282a679750135282693dd87f
| 37.962963 | 188 | 0.625068 | 5.043836 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.