repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ChrisSukhram/CKSButtonSlider | CKSButtonSlider/CKSButtonSlider.swift | 1 | 3753 | //
// CKSButtonSlider.swift
// CKSButtonSlider
//
// Created by Chris Sukhram on 1/26/16.
// Copyright © 2016 CKSMedia. All rights reserved.
//
import UIKit
@IBDesignable
public class CKSButtonSlider: UIButton {
@IBInspectable var fillViewColor:UIColor = UIColor.whiteColor() {
didSet {
fillView.backgroundColor = fillViewColor
}
}
@IBInspectable var cornerRadius:CGFloat = 0 {
didSet {
self.layer.cornerRadius = cornerRadius
}
}
@IBInspectable var borderColor:UIColor = UIColor.clearColor() {
didSet {
self.layer.borderColor = borderColor.CGColor
}
}
@IBInspectable var borderWidth:CGFloat = 0 {
didSet {
self.layer.borderWidth = borderWidth
}
}
public var percentValue:CGFloat {
let percent = CGFloat(currentTick)/CGFloat(numberOfTicks)
return min(max(percent, 0), 1)
}
@IBInspectable var currentTick:Int = 0 {
didSet {
if currentTick > numberOfTicks {
currentTick = numberOfTicks
}
else if currentTick < 0 {
currentTick = 0
}
updateFillView()
}
}
private var tickSize:CGFloat {
return self.bounds.width/CGFloat(numberOfTicks)
}
@IBInspectable var numberOfTicks:Int = 50
private let fillView = UIView()
private var dragThreshold:CGFloat = 10
private var initalTouch:CGPoint = CGPointMake(0, 0)
private var isDragging = false
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
self.setupFillView()
self.clipsToBounds = true
self.layer.cornerRadius = cornerRadius
self.layer.borderWidth = borderWidth
self.layer.borderColor = borderColor.CGColor
self.layer.addSublayer(fillView.layer)
}
private func setupFillView() {
fillView.backgroundColor = fillViewColor
fillView.userInteractionEnabled = false
}
public override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
isDragging = false
initalTouch = touch.locationInView(self)
return super.beginTrackingWithTouch(touch, withEvent: event)
}
public override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
let touchLoc = touch.locationInView(self)
if abs(touchLoc.x - initalTouch.x) > dragThreshold{
isDragging = true
}
if isDragging{
updateFillView(touchLoc)
sendActionsForControlEvents(.ValueChanged)
}
return super.continueTrackingWithTouch(touch, withEvent: event)
}
public override func cancelTrackingWithEvent(event: UIEvent?) {
super.cancelTrackingWithEvent(event)
isDragging = false
}
public override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) {
super.endTrackingWithTouch(touch, withEvent: event)
isDragging = false
}
private func updateFillView(touchLoc:CGPoint) {
currentTick = min(max(Int((touchLoc.x/self.frame.width) * CGFloat(numberOfTicks)), 0), numberOfTicks)
fillView.frame = CGRectMake(0, 0, touchLoc.x, self.bounds.height)
}
private func updateFillView() {
fillView.frame = CGRectMake(0, 0, CGFloat(currentTick) * tickSize, self.bounds.height)
}
}
| mit | 10bab71848ebd7c0736c3633fec77536 | 27.210526 | 109 | 0.614072 | 4.969536 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ChatCallRowItem.swift | 1 | 6660 | //
// ChatCallRowItem.swift
// Telegram
//
// Created by keepcoder on 05/05/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import InAppSettings
import SwiftSignalKit
import Postbox
class ChatCallRowItem: ChatRowItem {
private(set) var headerLayout:TextViewLayout
private(set) var timeLayout:TextViewLayout?
let outgoing:Bool
let failed: Bool
let isVideo: Bool
private let requestSessionId = MetaDisposable()
override func viewClass() -> AnyClass {
return ChatCallRowView.self
}
private let callId: Int64?
override init(_ initialSize: NSSize, _ chatInteraction: ChatInteraction, _ context: AccountContext, _ object: ChatHistoryEntry, _ downloadSettings: AutomaticMediaDownloadSettings, theme: TelegramPresentationTheme) {
let message = object.message!
let action = message.media[0] as! TelegramMediaAction
let isIncoming: Bool = message.isIncoming(context.account, object.renderType == .bubble)
outgoing = !message.flags.contains(.Incoming)
let video: Bool
switch action.action {
case let .phoneCall(callId, _, _, isVideo):
video = isVideo
self.callId = callId
default:
video = false
self.callId = nil
}
self.isVideo = video
headerLayout = TextViewLayout(.initialize(string: outgoing ? (video ? strings().chatVideoCallOutgoing : strings().chatCallOutgoing) : (video ? strings().chatVideoCallIncoming : strings().chatCallIncoming), color: theme.chat.textColor(isIncoming, object.renderType == .bubble), font: .medium(.text)), maximumNumberOfLines: 1)
switch action.action {
case let .phoneCall(_, reason, duration, _):
let attr = NSMutableAttributedString()
if let duration = duration, duration > 0 {
_ = attr.append(string: String.stringForShortCallDurationSeconds(for: duration), color: theme.chat.grayText(isIncoming, object.renderType == .bubble), font: .normal(.text))
failed = false
} else if let reason = reason {
switch reason {
case .busy:
_ = attr.append(string: outgoing ? strings().chatServiceCallCancelled : strings().chatServiceCallMissed, color: theme.chat.grayText(isIncoming, object.renderType == .bubble), font: .normal(.text))
case .disconnect:
_ = attr.append(string: outgoing ? strings().chatServiceCallCancelled : strings().chatServiceCallMissed, color: theme.chat.grayText(isIncoming, object.renderType == .bubble), font: .normal(.text))
case .hangup:
_ = attr.append(string: outgoing ? strings().chatServiceCallCancelled : strings().chatServiceCallMissed, color: theme.chat.grayText(isIncoming, object.renderType == .bubble), font: .normal(.text))
case .missed:
_ = attr.append(string: outgoing ? strings().chatServiceCallCancelled : strings().chatServiceCallMissed, color: theme.chat.grayText(isIncoming, object.renderType == .bubble), font: .normal(.text))
}
failed = true
} else {
failed = true
}
timeLayout = TextViewLayout(attr, maximumNumberOfLines: 1)
break
default:
failed = true
}
super.init(initialSize, chatInteraction, context, object, downloadSettings, theme: theme)
}
override func makeContentSize(_ width: CGFloat) -> NSSize {
timeLayout?.measure(width: width)
headerLayout.measure(width: width)
let widths:[CGFloat] = [timeLayout?.layoutSize.width ?? width, headerLayout.layoutSize.width]
return NSMakeSize((widths.max() ?? 0) + 60, 36)
}
func requestCall() {
if let peerId = message?.id.peerId {
let context = self.context
requestSessionId.set((phoneCall(context: context, peerId: peerId, isVideo: isVideo) |> deliverOnMainQueue).start(next: { result in
applyUIPCallResult(context, result)
}))
}
}
override var lastLineContentWidth: ChatRowItem.LastLineData? {
if let timeLayout = timeLayout {
return .init(width: timeLayout.layoutSize.width + 60, single: true)
} else {
return super.lastLineContentWidth
}
}
deinit {
requestSessionId.dispose()
}
}
private class ChatCallRowView : ChatRowView {
private let fallbackControl:ImageButton = ImageButton()
private let imageView:ImageView = ImageView()
private let headerView: TextView = TextView()
private let timeView:TextView = TextView()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
fallbackControl.animates = false
addSubview(fallbackControl)
addSubview(imageView)
addSubview(headerView)
addSubview(timeView)
headerView.userInteractionEnabled = false
timeView.userInteractionEnabled = false
fallbackControl.userInteractionEnabled = false
}
override func mouseUp(with event: NSEvent) {
if contentView.mouseInside() {
if let item = item as? ChatCallRowItem {
item.requestCall()
}
} else {
super.mouseUp(with: event)
}
}
override func set(item: TableRowItem, animated: Bool) {
super.set(item: item, animated: animated)
if let item = item as? ChatCallRowItem {
fallbackControl.set(image: theme.chat.chatCallFallbackIcon(item), for: .Normal)
_ = fallbackControl.sizeToFit()
imageView.image = theme.chat.chatCallIcon(item)
imageView.sizeToFit()
headerView.update(item.headerLayout, origin: NSMakePoint(fallbackControl.frame.maxX + 10, 0))
timeView.update(item.timeLayout, origin: NSMakePoint(fallbackControl.frame.maxX + 14 + imageView.frame.width, item.headerLayout.layoutSize.height + 3))
}
}
override func layout() {
super.layout()
fallbackControl.centerY(x: 0)
imageView.setFrameOrigin(fallbackControl.frame.maxX + 10, contentView.frame.height - 4 - imageView.frame.height)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-2.0 | c64da00e7971056ef255e83e13d45c4e | 37.270115 | 332 | 0.622316 | 5.040878 | false | false | false | false |
kstaring/swift | test/Constraints/diagnostics.swift | 1 | 41001 | // RUN: %target-parse-verify-swift
protocol P {
associatedtype SomeType
}
protocol P2 {
func wonka()
}
extension Int : P {
typealias SomeType = Int
}
extension Double : P {
typealias SomeType = Double
}
func f0(_ x: Int,
_ y: Float) { }
func f1(_: @escaping (Int, Float) -> Int) { }
func f2(_: (_: (Int) -> Int)) -> Int {}
func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {}
func f4(_ x: Int) -> Int { }
func f5<T : P2>(_ : T) { }
func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {}
var i : Int
var d : Double
// Check the various forms of diagnostics the type checker can emit.
// Tuple size mismatch.
f1(
f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}}
)
// Tuple element unused.
f0(i, i,
i) // expected-error{{extra argument in call}}
// Position mismatch
f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}}
// Tuple element not convertible.
f0(i,
d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}}
)
// Function result not a subtype.
f1(
f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}}
)
f3(
f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}}
)
f4(i, d) // expected-error {{extra argument in call}}
// Missing member.
i.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}}
// Generic member does not conform.
extension Int {
func wibble<T: P2>(_ x: T, _ y: T) -> T { return x }
func wubble<T>(_ x: (Int) -> T) -> T { return x(self) }
}
i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Generic member args correct, but return type doesn't match.
struct A : P2 {
func wonka() {}
}
let a = A()
for j in i.wibble(a, a) { // expected-error {{type 'A' does not conform to protocol 'Sequence'}}
}
// Generic as part of function/tuple types
func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) {
return (c: 0, i: g())
}
func f7() -> (c: Int, v: A) {
let g: (Void) -> A = { return A() }
return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}}
}
func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {}
f8(3, f4) // expected-error {{in argument type '(Int) -> Int', 'Int' does not conform to expected type 'P2'}}
typealias Tup = (Int, Double)
func f9(_ x: Tup) -> Tup { return x }
f8((1,2.0), f9) // expected-error {{in argument type '(Tup) -> Tup', 'Tup' (aka '(Int, Double)') does not conform to expected type 'P2'}}
// <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals
1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}}
[1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}}
"awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}}
// Does not conform to protocol.
f5(i) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Make sure we don't leave open existentials when diagnosing.
// <rdar://problem/20598568>
func pancakes(_ p: P2) {
f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}}
f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}}
}
protocol Shoes {
static func select(_ subject: Shoes) -> Self
}
// Here the opaque value has type (metatype_type (archetype_type ... ))
func f(_ x: Shoes, asType t: Shoes.Type) {
return t.select(x) // expected-error{{unexpected non-void return value in void function}}
}
precedencegroup Starry {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator **** : Starry
func ****(_: Int, _: String) { }
i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
infix operator ***~ : Starry
func ***~(_: Int, _: String) { }
i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
@available(*, unavailable, message: "call the 'map()' method on the sequence")
public func myMap<C : Collection, T>(
_ source: C, _ transform: (C.Iterator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "call the 'map()' method on the optional value")
public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? {
fatalError("unavailable function can't be called")
}
// <rdar://problem/20142523>
// FIXME: poor diagnostic, to be fixed in 20142462. For now, we just want to
// make sure that it doesn't crash.
func rdar20142523() {
myMap(0..<10, { x in // expected-error{{ambiguous reference to member '..<'}}
()
return x
})
}
// <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral
func rdar21080030() {
var s = "Hello"
if s.characters.count() == 0 {} // expected-error{{cannot call value of non-function type 'String.CharacterView.IndexDistance'}}{{24-26=}}
}
// <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments
func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136'}}
r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors
func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}}
// <rdar://problem/17080659> Error Message QOI - wrong return type in an overload
func recArea(_ h: Int, w : Int) {
return h * w // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong
func r17224804(_ monthNumber : Int) {
// expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}}
// expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}}
let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber)
}
// <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?'
func r17020197(_ x : Int?, y : Int) {
if x! { } // expected-error {{'Int' is not convertible to 'Bool'}}
// <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible
if y {} // expected-error {{'Int' is not convertible to 'Bool'}}
}
// <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different
func validateSaveButton(_ text: String) {
return (text.characters.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype
class r20201968C {
func blah() {
r20201968C.blah() // expected-error {{use of instance member 'blah' on type 'r20201968C'; did you mean to use a value of type 'r20201968C' instead?}}
}
}
// <rdar://problem/21459429> QoI: Poor compilation error calling assert
func r21459429(_ a : Int) {
assert(a != nil, "ASSERT COMPILATION ERROR")
// expected-warning @-1 {{comparing non-optional value of type 'Int' to nil always returns true}}
}
// <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an index of type 'Int'
struct StructWithOptionalArray {
var array: [Int]?
}
func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int {
return foo.array[0] // expected-error {{value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?}} {{19-19=!}}
}
// <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types
var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}}
// <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf
String().asdf // expected-error {{value of type 'String' has no member 'asdf'}}
// <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment
protocol r21553065Protocol {}
class r21553065Class<T : AnyObject> {}
_ = r21553065Class<r21553065Protocol>() // expected-error {{type 'r21553065Protocol' does not conform to protocol 'AnyObject'}}
// Type variables not getting erased with nested closures
struct Toe {
let toenail: Nail // expected-error {{use of undeclared type 'Nail'}}
func clip() {
toenail.inspect { x in
toenail.inspect { y in }
}
}
}
// <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic
class r21447318 {
var x = 42
func doThing() -> r21447318 { return self }
}
func test21447318(_ a : r21447318, b : () -> r21447318) {
a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}}
b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}}
}
// <rdar://problem/20409366> Diagnostics for init calls should print the class name
class r20409366C {
init(a : Int) {}
init?(a : r20409366C) {
let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}}
}
}
// <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match
func r18800223(_ i : Int) {
// 20099385
_ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}}
// 19648528
_ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}}
var buttonTextColor: String?
_ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{result values in '? :' expression have mismatching types 'Int' and '(_) -> _'}}
}
// <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back
_ = { $0 } // expected-error {{unable to infer closure type in the current context}}
_ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}}
_ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}}
// <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure.
func rdar21784170() {
let initial = (1.0 as Double, 2.0 as Double)
(Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}}
}
// <rdar://problem/21829141> BOGUS: unexpected trailing closure
func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } }
func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } }
let expectType1 = expect(Optional(3))(Optional<Int>.self)
let expectType1Check: Int = expectType1
// <rdar://problem/19804707> Swift Enum Scoping Oddity
func rdar19804707() {
enum Op {
case BinaryOperator((Double, Double) -> Double)
}
var knownOps : Op
knownOps = Op.BinaryOperator({$1 - $0})
knownOps = Op.BinaryOperator(){$1 - $0}
knownOps = Op.BinaryOperator{$1 - $0}
knownOps = .BinaryOperator({$1 - $0})
// rdar://19804707 - trailing closures for contextual member references.
knownOps = .BinaryOperator(){$1 - $0}
knownOps = .BinaryOperator{$1 - $0}
_ = knownOps
}
func f7(_ a: Int) -> (_ b: Int) -> Int {
return { b in a+b }
}
_ = f7(1)(1)
f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}}
let f8 = f7(2)
_ = f8(1)
f8(10) // expected-warning {{result of call is unused, but produces 'Int'}}
f8(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f8(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}}
class CurriedClass {
func method1() {}
func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } }
func method3(_ a: Int, b : Int) {} // expected-note 5 {{'method3(_:b:)' declared here}}
}
let c = CurriedClass()
_ = c.method1
c.method1(1) // expected-error {{argument passed to call that takes no arguments}}
_ = c.method2(1)
_ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2)
c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method1(c)()
_ = CurriedClass.method1(c)
CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}}
CurriedClass.method1(2.0)(1) // expected-error {{use of instance member 'method1' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}}
CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}}
_ = CurriedClass.method2(c)
_ = CurriedClass.method2(c)(32)
_ = CurriedClass.method2(1,2) // expected-error {{use of instance member 'method2' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}}
CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}}
CurriedClass.method3(c)(32, b: 1)
_ = CurriedClass.method3(c)
_ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }}
_ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}}
_ = CurriedClass.method3(1, 2) // expected-error {{use of instance member 'method3' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}}
CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}}
CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter 'b' in call}}
extension CurriedClass {
func f() {
method3(1, b: 2)
method3() // expected-error {{missing argument for parameter #1 in call}}
method3(42) // expected-error {{missing argument for parameter 'b' in call}}
method3(self) // expected-error {{missing argument for parameter 'b' in call}}
}
}
extension CurriedClass {
func m1(_ a : Int, b : Int) {}
func m2(_ a : Int) {}
}
// <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method
CurriedClass.m1(2, b: 42) // expected-error {{use of instance member 'm1' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}}
// <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method
CurriedClass.m2(12) // expected-error {{use of instance member 'm2' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}}
// <rdar://problem/20491794> Error message does not tell me what the problem is
enum Color {
case Red
case Unknown(description: String)
static func rainbow() -> Color {}
static func overload(a : Int) -> Color {}
static func overload(b : Int) -> Color {}
static func frob(_ a : Int, b : inout Int) -> Color {}
}
let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{'map' produces '[T]', not the expected contextual result type '(Int, Color)'}}
let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} {{51-51=description: }}
let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }}
let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }}
let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }}
let _: Color = .Unknown // expected-error {{member 'Unknown' expects argument of type '(description: String)'}}
let _: Color = .Unknown(42) // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}}
let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}}
let _ : Color = .rainbow // expected-error {{member 'rainbow' is a function; did you mean to call it?}} {{25-25=()}}
let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .frob(1.0, &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}}
let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}}
let _: Color = .frob(1, &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
func testTypeSugar(_ a : Int) {
typealias Stride = Int
let x = Stride(a)
x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
}
// <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr
func r21974772(_ y : Int) {
let x = &(1.0 + y) // expected-error {{binary operator '+' cannot be applied to operands of type 'Double' and 'Int'}}
//expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (Double, Double), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}}
}
// <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc
protocol r22020088P {}
func r22020088Foo<T>(_ t: T) {}
func r22020088bar(_ p: r22020088P?) {
r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}}
}
// <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type
func f(_ arguments: [String]) -> [ArraySlice<String>] {
return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" })
}
struct AOpts : OptionSet {
let rawValue : Int
}
class B {
func function(_ x : Int8, a : AOpts) {}
func f2(_ a : AOpts) {}
static func f1(_ a : AOpts) {}
}
func test(_ a : B) {
B.f1(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}}
a.function(42, a: nil) //expected-error {{nil is not compatible with expected argument type 'AOpts'}}
a.function(42, nil) //expected-error {{missing argument label 'a:' in call}}
a.f2(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}}
}
// <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure
typealias MyClosure = ([Int]) -> Bool
func r21684487() {
var closures = Array<MyClosure>()
let testClosure = {(list: [Int]) -> Bool in return true}
let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions; operands here have types '_' and '([Int]) -> Bool'}}
}
// <rdar://problem/18397777> QoI: special case comparisons with nil
func r18397777(_ d : r21447318?) {
let c = r21447318()
if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to nil always returns true}}
}
if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}}
}
if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{8-8= != nil)}}
}
if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{18-18= != nil)}}
}
}
// <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list
func r22255907_1<T>(_ a : T, b : Int) {}
func r22255907_2<T>(_ x : Int, a : T, b: Int) {}
func reachabilityForInternetConnection() {
var variable: Int = 42
r22255907_1(&variable, b: 2.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}}
r22255907_2(1, a: &variable, b: 2.1)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}}
}
// <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message
if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}}
_ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}}
// <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init
func r22263468(_ a : String?) {
typealias MyTuple = (Int, String)
_ = MyTuple(42, a) // expected-error {{value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?}} {{20-20=!}}
}
// rdar://22470302 - Crash with parenthesized call result.
class r22470302Class {
func f() {}
}
func r22470302(_ c: r22470302Class) {
print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}}
}
// <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile
extension String {
@available(*, unavailable, message: "calling this is unwise")
func unavail<T : Sequence> // expected-note 2 {{'unavail' has been explicitly marked unavailable here}}
(_ a : T) -> String where T.Iterator.Element == String {}
}
extension Array {
func g() -> String {
return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
func h() -> String {
return "foo".unavail([0]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
}
// <rdar://problem/22519983> QoI: Weird error when failing to infer archetype
func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {}
// expected-note @-1 {{in call to function 'safeAssign'}}
let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure
struct Radar21692808<Element> {
init(count: Int, value: Element) {}
}
func radar21692808() -> Radar21692808<Int> {
return Radar21692808<Int>(count: 1) { // expected-error {{cannot invoke initializer for type 'Radar21692808<Int>' with an argument list of type '(count: Int, () -> Int)'}}
// expected-note @-1 {{expected an argument list of type '(count: Int, value: Element)'}}
return 1
}
}
// <rdar://problem/17557899> - This shouldn't suggest calling with ().
func someOtherFunction() {}
func someFunction() -> () {
// Producing an error suggesting that this
return someOtherFunction // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic
func r23560128() {
var a : (Int,Int)?
a.0 = 42 // expected-error {{value of optional type '(Int, Int)?' not unwrapped; did you mean to use '!' or '?'?}} {{4-4=?}}
}
// <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping
struct ExampleStruct21890157 {
var property = "property"
}
var example21890157: ExampleStruct21890157?
example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' not unwrapped; did you mean to use '!' or '?'?}} {{16-16=?}}
struct UnaryOp {}
_ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}}
// expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists: (Float), (Double)}}
// <rdar://problem/23433271> Swift compiler segfault in failure diagnosis
func f23433271(_ x : UnsafePointer<Int>) {}
func segfault23433271(_ a : UnsafeMutableRawPointer) {
f23433271(a[0]) // expected-error {{type 'UnsafeMutableRawPointer' has no subscript members}}
}
// <rdar://problem/23272739> Poor diagnostic due to contextual constraint
func r23272739(_ contentType: String) {
let actualAcceptableContentTypes: Set<String> = []
return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets
func r23641896() {
var g = "Hello World"
g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot invoke 'replaceSubrange' with an argument list of type '(CountableClosedRange<Int>, with: String)'}} expected-note {{overloads for 'replaceSubrange' exist}}
_ = g[12] // expected-error {{'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}}
}
// <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note
func test17875634() {
var match: [(Int, Int)] = []
var row = 1
var col = 2
match.append(row, col) // expected-error {{extra argument in call}}
}
// <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values
enum AssocTest {
case one(Int)
}
if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}}
// expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}}
// <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types
func r24251022() {
var a = 1
var b: UInt32 = 2
a += a + // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{expected an argument list of type '(Int, Int)'}}
b
}
func overloadSetResultType(_ a : Int, b : Int) -> Int {
// https://twitter.com/_jlfischer/status/712337382175952896
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect
func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) {
let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}}
let r = bytes[i++] // expected-error {{cannot pass immutable value as inout argument: 'i' is a 'let' constant}}
}
// SR-1594: Wrong error description when using === on non-class types
class SR1594 {
func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) {
_ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}}
_ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns false}}
_ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}}
_ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns true}}
}
}
func nilComparison(i: Int, o: AnyObject) {
_ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to nil always returns false}}
_ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to nil always returns false}}
_ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to nil always returns true}}
_ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to nil always returns true}}
_ = i < nil // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = nil < i // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = i <= nil // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = nil <= i // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = i > nil // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = nil > i // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = i >= nil // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = nil >= i // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns false}}
_ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns true}}
}
func secondArgumentNotLabeled(a: Int, _ b: Int) { }
secondArgumentNotLabeled(10, 20)
// expected-error@-1 {{missing argument label 'a' in call}}
// <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion
func testImplConversion(a : Float?) -> Bool {}
func testImplConversion(a : Int?) -> Bool {
let someInt = 42
let a : Int = testImplConversion(someInt) // expected-error {{argument labels '(_:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'testImplConversion' exist with these partially matching parameter lists: (a: Float?), (a: Int?)}}
}
// <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands
class Foo23752537 {
var title: String?
var message: String?
}
extension Foo23752537 {
func isEquivalent(other: Foo23752537) {
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
// expected-error @+1 {{unexpected non-void return value in void function}}
return (self.title != other.title && self.message != other.message)
}
}
// <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
func rdar27391581(_ a : Int, b : Int) -> Int {
return a == b && b != 0
// expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints
func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {}
func read<T : Integer>() -> T? {
var buffer : T
let n = withUnsafePointer(to: &buffer) { (p) in
read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<_>' to expected argument type 'UnsafeMutableRawPointer'}}
}
}
func f23213302() {
var s = Set<Int>()
s.subtractInPlace(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}}
}
// <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context
func rdar24202058(a : Int) {
return a <= 480 // expected-error {{unexpected non-void return value in void function}}
}
// SR-1752: Warning about unused result with ternary operator
struct SR1752 {
func foo() {}
}
let sr1752: SR1752?
true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void
// <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try'
struct rdar27891805 {
init(contentsOf: String, encoding: String) throws {}
init(contentsOf: String, usedEncoding: inout String) throws {}
init<T>(_ t: T) {}
}
try rdar27891805(contentsOfURL: nil, usedEncoding: nil)
// expected-error@-1 {{argument labels '(contentsOfURL:, usedEncoding:)' do not match any available overloads}}
// expected-note@-2 {{overloads for 'rdar27891805' exist with these partially matching parameter lists: (contentsOf: String, encoding: String), (contentsOf: String, usedEncoding: inout String)}}
// Make sure RawRepresentable fix-its don't crash in the presence of type variables
class NSCache<K, V> {
func object(forKey: K) -> V? {}
}
class CacheValue {
func value(x: Int) -> Int {} // expected-note {{found this candidate}}
func value(y: String) -> String {} // expected-note {{found this candidate}}
}
func valueForKey<K>(_ key: K) -> CacheValue? {
let cache = NSCache<K, CacheValue>()
return cache.object(forKey: key)?.value // expected-error {{ambiguous reference to member 'value(x:)'}}
}
// SR-2242: poor diagnostic when argument label is omitted
func r27212391(x: Int, _ y: Int) {
let _: Int = x + y
}
func r27212391(a: Int, x: Int, _ y: Int) {
let _: Int = a + x + y
}
r27212391(3, 5) // expected-error {{missing argument label 'x' in call}}
r27212391(3, y: 5) // expected-error {{missing argument label 'x' in call}}
r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}}
r27212391(y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}}
r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}}
r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}}
r27212391(a: 1, 3, y: 5) // expected-error {{missing argument label 'x' in call}}
r27212391(1, x: 3, y: 5) // expected-error {{missing argument label 'a' in call}}
r27212391(a: 1, y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}}
r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}}
// SR-1255
func foo1255_1() {
return true || false // expected-error {{unexpected non-void return value in void function}}
}
func foo1255_2() -> Int {
return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// SR-2505: "Call arguments did not match up" assertion
func sr_2505(_ a: Any) {} // expected-note {{}}
sr_2505() // expected-error {{missing argument for parameter #1 in call}}
sr_2505(a: 1) // expected-error {{extraneous argument label 'a:' in call}}
sr_2505(1, 2) // expected-error {{extra argument in call}}
sr_2505(a: 1, 2) // expected-error {{extra argument in call}}
struct C_2505 {
init(_ arg: Any) {
}
}
protocol P_2505 {
}
extension C_2505 {
init<T>(from: [T]) where T: P_2505 {
}
}
class C2_2505: P_2505 {
}
let c_2505 = C_2505(arg: [C2_2505()]) // expected-error {{argument labels '(arg:)' do not match any available overloads}} expected-note {{overloads for 'C_2505' exist}}
// Diagnostic message for initialization with binary operations as right side
let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}}
let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
// SR-2208
struct Foo2208 {
func bar(value: UInt) {}
}
func test2208() {
let foo = Foo2208()
let a: Int = 1
let b: Int = 2
let result = a / b
foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: UInt(result)) // Ok
}
// SR-2164: Erroneous diagnostic when unable to infer generic type
struct SR_2164<A, B> { // expected-note 3 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}}
init(a: A) {}
init(b: B) {}
init(c: Int) {}
init(_ d: A) {}
init(e: A?) {}
}
struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}}
init(_ a: [A]) {}
}
struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}}
init(a: [A: Double]) {}
}
SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(c: 2) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
let _ = SR_2164<Int, Bool>(a: 0) // Ok
let _ = SR_2164<Int, Bool>(b: true) // Ok
SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
| apache-2.0 | b704dc6871c34ad713d4b58a9fb1265c | 44.205072 | 223 | 0.672569 | 3.616565 | false | false | false | false |
Raizlabs/Shift | Source/Shift/Classes/SplitTransition.swift | 1 | 24894 | //
// SplitTransition.swift
// Shift
//
// Created by Matthew Buckley on 12/10/15.
// Copyright 2015 Raizlabs and other contributors
// http://raizlabs.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
final public class SplitTransition: UIPercentDrivenInteractiveTransition {
/**
The type of transition.
- Push: A push transition.
- Pop: A pop transition.
- Interactive: An interactive transition.
- Presentation: a modal transition.
*/
public enum TransitionType {
case Push
case Pop
case Interactive
case Presentation(UIViewController, UIViewController)
case Dismissal(UIViewController, UIViewController)
}
/**
Scope of screenshot used to generate top and bottom split views
- View: bounds of fromVC's view
- Window: bounds of window
*/
public enum ScreenshotScope {
case View
case Window
}
/**
The progress state of the transition.
- Initial: transition has not begun.
- Finished: transition is complete.
- Cancelled: transition has been cancelled.
*/
enum TransitionState {
case Initial
case Finished
case Cancelled
}
/// The duration (in seconds) of the transition.
public var transitionDuration: NSTimeInterval = 1.0
/// The delay before/after the transition (in seconds).
public var transitionDelay: NSTimeInterval = 0.0
/// Animation type (e.g. push/pop). Defaults to "push".
public var transitionType: TransitionType = .Push
/// Scope of screenshot (determines whether to use view's bounds or window's bounds). Defaults to "view".
public var screenshotScope: ScreenshotScope = .View
/// Y coordinate where top and bottom screen captures should split.
public var splitLocation = CGFloat(0.0)
/// Screen capture extending from split location to top of screen
lazy var topSplitImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = self.screenCapture
imageView.contentMode = .Top
imageView.clipsToBounds = true
return imageView
}()
/// Screen capture extending from split location to bottom of screen
lazy var bottomSplitImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = self.screenCapture
imageView.contentMode = .Bottom
imageView.clipsToBounds = true
return imageView
}()
/**
In an interactive transition, splitOffset
determines the vertical distance of the initial
split when the cell is first tapped.
*/
public var splitOffset = CGFloat(0.0)
/// Scroll distance in UI points.
var interactiveTransitionScrollDistance = CGFloat(0.0)
/// State of interactive transition.
var transitionState: TransitionState = .Initial {
didSet {
switch transitionState {
case .Initial:
break
case .Finished:
break
case .Cancelled:
fromVC?.navigationController?.navigationBarHidden = false
fromVC?.navigationController?.delegate = initialNavigationControllerDelegate
previousTouchLocation = nil
}
}
}
/// Transition progress in UIPoints (essentially, distance scrolled from splitLocation)
private var transitionProgress = CGFloat(0.0) {
didSet {
/// Calculate how much of the bottom and top screenshots have been scrolled off-screen
let bottomHeight = bottomSplitImageView.bounds.size.height
let topHeight = topSplitImageView.bounds.size.height
let bottomPctComplete = max(transitionProgress / bottomHeight,
0.0)
let topPctComplete = max(transitionProgress / topHeight,
0.0)
/// Set new transforms for top and bottom imageViews
topSplitImageView.transform = CGAffineTransformMakeTranslation(0.0,
-(topPctComplete * topHeight))
bottomSplitImageView.transform = CGAffineTransformMakeTranslation(0.0,
(bottomPctComplete * bottomHeight))
}
}
/**
For interactive transition, reflects whether
the current pan is the first one (necessary to correctly
manage transition progress vis a vis initial offset)
*/
private var initialPan = true
/// Stores a gesture recognizer (interactive transition only)
private var gestureRecognizer: UIPanGestureRecognizer?
/// Current transition context
private var transitionContext: UIViewControllerContextTransitioning?
/// Stores the location of the most recent touch (interactive transition only)
private var previousTouchLocation: CGPoint?
/// Transition container view
private var container: UIView?
/// Destination view controller for current transition
private var toVC: UIViewController?
/// Origin view controller for current transition
private var fromVC: UIViewController?
/// Completion for the current transition
private var completion: (() -> ())?
/// Optional capture of entire screen
var screenCapture: UIImage?
/// The previous UINavigationControllerDelegate of the origin view controller
var initialNavigationControllerDelegate: UINavigationControllerDelegate?
public convenience init(transitionDuration: NSTimeInterval,
transitionType: TransitionType,
initialNavigationControllerDelegate: UINavigationControllerDelegate?) {
self.init()
self.transitionDuration = transitionDuration
self.transitionType = transitionType
self.initialNavigationControllerDelegate = initialNavigationControllerDelegate
}
func didPan(gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .Began:
break
case .Changed:
panGestureDidChange(gesture: gesture)
updateTransitionState()
case .Ended:
initialPan = false
previousTouchLocation = nil
default:
break
}
}
public override func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
setupTransition(transitionContext)
}
}
extension SplitTransition: UIViewControllerAnimatedTransitioning {
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return transitionDuration
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
setupTransition(transitionContext)
guard let fromVC = fromVC,
toVC = toVC,
container = container,
completion = completion else {
debugPrint("animation setup failed")
return
}
gestureRecognizer = UIPanGestureRecognizer(target: self, action: "didPan:")
if let gestureRecognizer = gestureRecognizer {
gestureRecognizer.delegate = self
fromVC.view.window?.addGestureRecognizer(gestureRecognizer)
}
switch transitionType {
case .Push:
pushOrPresent(toViewController: toVC, fromViewController: fromVC, containerView: container, completion: completion)
case .Pop:
popOrDismiss(toVC, fromViewController: fromVC, containerView: container, completion: completion)
case .Interactive:
pushOrPresent(splitOffset, toViewController: toVC, fromViewController: fromVC, containerView: container, completion: nil)
case .Presentation:
pushOrPresent(toViewController: toVC, fromViewController: fromVC, containerView: container, completion: completion)
case .Dismissal:
popOrDismiss(toVC, fromViewController: fromVC, containerView: container, completion: completion)
break
}
}
}
private extension SplitTransition {
// MARK: private interface
func animatePush(toOffset toOffset: CGFloat,
animations: (() -> ())?,
completion: (() -> ())?) -> Void {
/// Set animation options
let options: UIViewAnimationOptions = transitionType == .Interactive ? .AllowUserInteraction : .LayoutSubviews
UIView.animateWithDuration(transitionDuration,
delay: 0.0,
usingSpringWithDamping: 0.65,
initialSpringVelocity: 1.0,
options: options,
animations: { () -> Void in
animations?()
}) { [weak self] (Bool) -> Void in
/// When the transition is finished, top and bottom
/// split views are removed from the view hierarchy
if let controller = self {
if !(controller.transitionType == .Interactive) {
controller.topSplitImageView.removeFromSuperview()
controller.bottomSplitImageView.removeFromSuperview()
}
/// If a completion was passed as a parameter,
/// execute it
completion?()
}
}
}
func panGestureDidChange(gesture gesture: UIPanGestureRecognizer) -> Void {
/// Continue tracking touch location
let currentTouchLocation = gesture.locationInView(container)
/// Calculate distance between current touch location and previous
/// touch location
var distanceMoved = CGFloat(0.0)
if let previousTouchLocation = previousTouchLocation {
distanceMoved = currentTouchLocation.y - previousTouchLocation.y
}
else {
distanceMoved = initialPan ? splitOffset : 0.0
}
/// Update transition progress
transitionProgress += (abs(currentTouchLocation.y - splitLocation) / splitLocation)
/// Update interactive transition
let percentComplete = max((transitionProgress / interactiveTransitionScrollDistance), 0.0)
/// Update 'previousTouchLocation'
previousTouchLocation = currentTouchLocation
/// Increment 'transitionProgress' by calculated distance
transitionProgress += distanceMoved
/// Update transition
transitionContext?.updateInteractiveTransition(percentComplete)
if percentComplete >= 1.0 {
transitionState = .Finished
}
else if percentComplete == 0.0 {
transitionState = .Cancelled
}
}
func updateTransitionState() -> Void {
switch transitionState {
case .Finished:
/// split views are removed from the view hierarchy
topSplitImageView.removeFromSuperview()
bottomSplitImageView.removeFromSuperview()
completion?()
/// Make destination view controller's view visible
toVC?.view.alpha = 1.0
fromVC?.view.alpha = 0.0
case .Cancelled:
/// split views are removed from the view hierarchy
topSplitImageView.removeFromSuperview()
bottomSplitImageView.removeFromSuperview()
/// Cancel transition
cancelInteractiveTransition()
completion?()
/// Make source view controller's view visible again
toVC?.view.alpha = 0.0
fromVC?.view.alpha = 1.0
default:
break
}
}
/**
Return origin view controller.
- parameter transitionContext: an optional `UIViewControllerContextTransitioning`.
- returns: an optional `UIViewController`.
*/
func fromViewController(transitionContext: UIViewControllerContextTransitioning?) -> UIViewController? {
return transitionContext?.viewControllerForKey(UITransitionContextFromViewControllerKey)
}
/**
Return destination view controller..
- parameter transitionContext: an optional `UIViewControllerContextTransitioning`.
- returns: an optional `UIViewController`.
*/
func toViewController(transitionContext: UIViewControllerContextTransitioning?) -> UIViewController? {
return transitionContext?.viewControllerForKey(UITransitionContextToViewControllerKey)
}
/**
Return the container view for the given transition context.
- parameter transitionContext: an optional `UIViewControllerContextTransitioning`.
- returns: the container `UIView` for the transition context.
*/
func containerView(transitionContext: UIViewControllerContextTransitioning?) -> UIView? {
return transitionContext?.containerView()
}
func setupTransition(transitionContext: UIViewControllerContextTransitioning?) -> Void {
/// Grab the view in which the transition should take place.
/// Coalesce to UIView()
container = containerView(transitionContext) ?? UIView()
guard let container = container else {
debugPrint("Failed to set up container view")
return
}
container.frame = fromVC?.view.superview?.frame ?? container.frame
/// Set source and destination view controllers
switch transitionType {
case .Presentation(let originVC, let destinationVC):
fromVC = originVC
toVC = destinationVC
case .Dismissal(let originVC, let destinationVC):
fromVC = originVC
toVC = destinationVC
default:
fromVC = fromViewController(transitionContext) ?? UIViewController()
toVC = toViewController(transitionContext) ?? UIViewController()
}
toVC?.navigationController?.navigationBarHidden = true
/// Take screenshot and store resulting UIImage
screenCapture = screenshotScope == .Window ? UIWindow.screenshot() : screenshot()
/// Set completion handler for transition
completion = {
let cancelled: Bool = transitionContext?.transitionWasCancelled() ?? false
/// Remove gesture recognizer from view
if let gestureRecognizer = self.gestureRecognizer {
gestureRecognizer.view?.removeGestureRecognizer(gestureRecognizer)
}
/// Complete the transition
transitionContext?.completeTransition(!cancelled)
transitionContext?.finishInteractiveTransition()
}
}
/**
Push fromViewController onto navigation stack or present it modally.
- parameter toOffset: vertical offset at which to start interactive animation.
- parameter toViewController: destination view controller.
- parameter fromViewController: origin view controller.
- parameter containerView: container view for transition context.
- parameter completion: completion handler.
*/
func pushOrPresent(toOffset: CGFloat = 0.0,
toViewController: UIViewController,
fromViewController: UIViewController,
containerView: UIView,
completion: (() -> ())?) {
/// Add subviews
containerView.clipsToBounds = true
containerView.addSubview(toViewController.view)
containerView.addSubview(topSplitImageView)
containerView.addSubview(bottomSplitImageView)
/// Set initial frames for screen captures
setInitialScreenCaptureFrames(containerView)
/// source view controller is initially hidden
fromViewController.view.alpha = 0.0
toViewController.view.alpha = 1.0
toViewController.view.transform = CGAffineTransformMakeTranslation(0.0, topSplitImageView.frame.size.height)
/// Animate all the way or only partially if a toOffset parameter is passed in
let targetOffsetTop = toOffset != 0.0 ? -toOffset : -topSplitImageView.bounds.size.height
let targetOffsetBottom = toOffset != 0.0 ? toOffset : bottomSplitImageView.bounds.size.height
let animations = { [weak self] in
self?.topSplitImageView.transform = CGAffineTransformMakeTranslation(0.0, targetOffsetTop)
self?.bottomSplitImageView.transform = CGAffineTransformMakeTranslation(0.0, targetOffsetBottom)
toViewController.view.transform = CGAffineTransformIdentity
}
animatePush(toOffset: toOffset,
animations: animations,
completion: completion)
}
/**
Pop fromViewController from navigation stack or (if modally presented) dismiss it.
- parameter toViewController: destination view controller.
- parameter fromViewController: origin view controller.
- parameter containerView: container view for transition context.
- parameter completion: completion handler.
*/
func popOrDismiss(toViewController: UIViewController,
fromViewController: UIViewController,
containerView: UIView,
completion: (() -> ())?) {
/// Add subviews
if transitionType == .Pop {
// If view controller is modally presented (transitionType == .Dismiss),
// it will already be in the view hierarchy
containerView.addSubview(toViewController.view)
}
containerView.addSubview(topSplitImageView)
containerView.addSubview(bottomSplitImageView)
/// Destination view controller is initially hidden
toViewController.view.alpha = 0.0
/// Set initial transforms for top and bottom split views
topSplitImageView.transform = CGAffineTransformMakeTranslation(0.0, -topSplitImageView.bounds.size.height)
bottomSplitImageView.transform = CGAffineTransformMakeTranslation(0.0, bottomSplitImageView.bounds.size.height)
UIView.animateWithDuration(transitionDuration, delay: 0.0, usingSpringWithDamping: 0.65, initialSpringVelocity: 1.0, options: .LayoutSubviews, animations: { [weak self] () -> Void in
if let controller = self {
/// Restore the top and bottom screen captures to their original positions
controller.topSplitImageView.transform = CGAffineTransformIdentity
controller.bottomSplitImageView.transform = CGAffineTransformIdentity
/// Restore fromVC's view to its original position
fromViewController.view.transform = CGAffineTransformMakeTranslation(0.0, controller.topSplitImageView.bounds.size.height)
}
}) { [weak self] (Bool) -> Void in
/// When the transition is finished, top and bottom split views are removed from the view hierarchy
if let controller = self {
controller.topSplitImageView.removeFromSuperview()
controller.bottomSplitImageView.removeFromSuperview()
}
/// Make destination view controller's view visible again
toViewController.view.alpha = 1.0
toViewController.navigationController?.navigationBarHidden = self?.fromVC?.navigationController?.navigationBar.hidden ?? false
toViewController.navigationController?.delegate = self?.initialNavigationControllerDelegate
/// If a completion was passed as a parameter, execute it
completion?()
}
}
func setInitialScreenCaptureFrames(containerView: UIView) {
/// Set bounds for top and bottom screen captures
let width = containerView.frame.size.width ?? 0.0
let height = containerView.frame.size.height ?? 0.0
/// Top screen capture extends from split location to top of view
topSplitImageView.frame = CGRect(x: 0.0, y: 0.0, width: width, height: splitLocation)
/// Bottom screen capture extends from split location to bottom of view
bottomSplitImageView.frame = CGRect(x: 0.0, y: splitLocation, width: width, height: height - splitLocation)
/// Store a distance figure to use to calculate percent complete for
/// the interactive transition
interactiveTransitionScrollDistance = max(topSplitImageView.bounds.size.height, bottomSplitImageView.bounds.size.height)
}
func screenshot() -> UIImage {
let viewFrame = fromVC?.view.frame ?? CGRectZero
UIGraphicsBeginImageContext(viewFrame.size)
if let ctx = UIGraphicsGetCurrentContext() {
UIColor.blackColor().set()
CGContextFillRect(ctx, CGRect(x: 0.0, y: 0.0, width: viewFrame.width, height: viewFrame.height))
fromVC?.view.layer.renderInContext(ctx)
} else {
debugPrint("Unable to get current graphics context")
}
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return screenshot
}
}
extension SplitTransition: UIGestureRecognizerDelegate {
public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
let location = gestureRecognizer.locationInView(container)
let presentationLayer = container?.layer.presentationLayer()
if (presentationLayer?.hitTest(location)) != nil {
return true
}
return false
}
}
extension SplitTransition: UIViewControllerTransitioningDelegate {
public func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return transitionType == .Interactive ? self : nil
}
public func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return transitionType == .Interactive ? self : nil
}
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return transitionType != .Interactive ? self : nil
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return transitionType != .Interactive ? self : nil
}
}
// MARK: - Equatable
extension SplitTransition.TransitionType: Equatable {}
/**
Implementation of Equatable Protocol
- parameter lhs: a transition type.
- parameter rhs: a transition type.
- returns: true if the 2 transition types are equal, false if not.
*/
public func == (lhs: SplitTransition.TransitionType, rhs: SplitTransition.TransitionType) -> Bool {
switch(lhs, rhs) {
case (.Push, .Push):
return true
case (.Pop, .Pop):
return true
case (.Interactive, .Interactive):
return true
case (let .Dismissal(vc1, vc2), let .Dismissal(vc3, vc4)):
return vc1 == vc3 && vc2 == vc4
case (let .Presentation(vc1, vc2), let .Presentation(vc3, vc4)):
return vc1 == vc3 && vc2 == vc4
default:
return false
}
}
| mit | 3520600c9e43a98bb69e3879569e0e7b | 38.20315 | 224 | 0.649434 | 6.211078 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPressKit/WordPressKit/GravatarServiceRemote.swift | 2 | 5040 | import Foundation
import AFNetworking
import WordPressShared
/// This ServiceRemote encapsulates all of the interaction with the Gravatar endpoint.
///
open class GravatarServiceRemote {
let baseGravatarURL = "https://www.gravatar.com/"
public init() {}
/// This method fetches the Gravatar profile for the specified email address.
///
/// - Parameters:
/// - email: The email address of the gravatar profile to fetch.
/// - success: A success block.
/// - failure: A failure block.
///
open func fetchProfile(_ email: String, success:@escaping ((_ profile: RemoteGravatarProfile) -> Void), failure:@escaping ((_ error: Error?) -> Void)) {
guard let hash = (email as NSString).md5() else {
assertionFailure()
return
}
let path = baseGravatarURL + hash + ".json"
guard let targetURL = URL(string: path) else {
assertionFailure()
return
}
let session = URLSession.shared
let task = session.dataTask(with: targetURL) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async {
let errPointer: NSErrorPointer = nil
if let response = AFJSONResponseSerializer().responseObject(for: response, data: data, error: errPointer) as? [String: Array<Any>],
let entry = response["entry"],
let profileData = entry.first as? NSDictionary {
let profile = RemoteGravatarProfile(dictionary: profileData)
success(profile)
return
}
let err = errPointer?.pointee ?? error
failure(err)
}
}
task.resume()
}
/// This method hits the Gravatar Endpoint, and uploads a new image, to be used as profile.
///
/// - Parameters:
/// - image: The new Gravatar Image, to be uploaded
/// - completion: An optional closure to be executed on completion.
///
open func uploadImage(_ image: UIImage, accountEmail: String, accountToken: String, completion: ((_ error: NSError?) -> ())?) {
guard let targetURL = URL(string: UploadParameters.endpointURL) else {
assertionFailure()
return
}
// Boundary
let boundary = boundaryForRequest()
// Request
let request = NSMutableURLRequest(url: targetURL)
request.httpMethod = UploadParameters.HTTPMethod
request.setValue("Bearer \(accountToken)", forHTTPHeaderField: "Authorization")
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
// Body
let gravatarData = UIImagePNGRepresentation(image)!
let requestBody = bodyWithGravatarData(gravatarData, account: accountEmail, boundary: boundary)
// Task
let session = URLSession.shared
let task = session.uploadTask(with: request as URLRequest, from: requestBody, completionHandler: { (data, response, error) in
completion?(error as NSError?)
})
task.resume()
}
// MARK: - Private Helpers
/// Returns a new (randomized) Boundary String
///
fileprivate func boundaryForRequest() -> String {
return "Boundary-" + UUID().uuidString
}
/// Returns the Body for a Gravatar Upload OP.
///
/// - Parameters:
/// - gravatarData: The NSData-Encoded Image
/// - account: The account that will get updated
/// - boundary: The request's Boundary String
///
/// - Returns: A NSData instance, containing the Request's Payload.
///
fileprivate func bodyWithGravatarData(_ gravatarData: Data, account: String, boundary: String) -> Data {
let body = NSMutableData()
// Image Payload
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\(UploadParameters.imageKey); ")
body.appendString("filename=\(UploadParameters.filename)\r\n")
body.appendString("Content-Type: \(UploadParameters.contentType);\r\n\r\n")
body.append(gravatarData)
body.appendString("\r\n")
// Account Payload
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(UploadParameters.accountKey)\"\r\n\r\n")
body.appendString("\(account)\r\n")
// EOF!
body.appendString("--\(boundary)--\r\n")
return body as Data
}
// MARK: - Private Structs
fileprivate struct UploadParameters {
static let endpointURL = "https://api.gravatar.com/v1/upload-image"
static let HTTPMethod = "POST"
static let contentType = "application/octet-stream"
static let filename = "profile.png"
static let imageKey = "filedata"
static let accountKey = "account"
}
}
| gpl-2.0 | 8fbcc30f021b68b33e546659c329e5fb | 35.521739 | 156 | 0.603571 | 4.950884 | false | false | false | false |
legendecas/Rocket.Chat.iOS | Rocket.ChatTests/Managers/AuthManagerSpec.swift | 1 | 1687 | //
// AuthManagerSpec.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/8/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import XCTest
import RealmSwift
@testable import Rocket_Chat
class AuthManagerSpec: XCTestCase, AuthManagerInjected {
override func setUp() {
super.setUp()
// Clear all the Auth objects in Realm
Realm.executeOnMainThread({ realm in
for obj in realm.objects(Auth.self) {
realm.delete(obj)
}
})
}
}
// MARK: isAuthenticated method
extension AuthManagerSpec {
func testIsAuthenticatedUserNotAuthenticated() {
XCTAssert(authManager.isAuthenticated() == nil, "isAuthenticated returns nil for non authenticated users")
}
func testIsAuthenticatedUserAuthenticated() {
Realm.executeOnMainThread({ realm in
let auth = Auth()
auth.serverURL = "http://foo.com"
realm.add(auth)
XCTAssert(self.authManager.isAuthenticated()?.serverURL == auth.serverURL, "isAuthenticated returns Auth instance")
})
}
func testIsAuthenticatedReturnsLastAccessed() {
Realm.executeOnMainThread({ realm in
let auth1 = Auth()
auth1.serverURL = "ws://one.cc"
auth1.lastAccess = Date()
let auth2 = Auth()
auth2.serverURL = "ws://two.cc"
auth2.lastAccess = Date(timeIntervalSince1970: 1)
realm.add(auth1)
realm.add(auth2)
XCTAssert(self.authManager.isAuthenticated()?.serverURL == auth1.serverURL, "isAuthenticated returns the latests Auth instance")
})
}
}
| mit | bce0f468a883052b57a4c45129eb4246 | 24.938462 | 140 | 0.622776 | 4.657459 | false | true | false | false |
deuiore/mpv | video/out/mac/window.swift | 1 | 19802 | /*
* This file is part of mpv.
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* mpv 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
import Cocoa
class Window: NSWindow, NSWindowDelegate {
weak var common: Common! = nil
var mpv: MPVHelper? { get { return common.mpv } }
var targetScreen: NSScreen?
var previousScreen: NSScreen?
var currentScreen: NSScreen?
var unfScreen: NSScreen?
var unfsContentFrame: NSRect?
var isInFullscreen: Bool = false
var isAnimating: Bool = false
var isMoving: Bool = false
var forceTargetScreen: Bool = false
var unfsContentFramePixel: NSRect { get { return convertToBacking(unfsContentFrame ?? NSRect(x: 0, y: 0, width: 160, height: 90)) } }
var framePixel: NSRect { get { return convertToBacking(frame) } }
var keepAspect: Bool = true {
didSet {
if let contentViewFrame = contentView?.frame, !isInFullscreen {
unfsContentFrame = convertToScreen(contentViewFrame)
}
if keepAspect {
contentAspectRatio = unfsContentFrame?.size ?? contentAspectRatio
} else {
resizeIncrements = NSSize(width: 1.0, height: 1.0)
}
}
}
var border: Bool = true {
didSet { if !border { common.titleBar?.hide() } }
}
override var canBecomeKey: Bool { return true }
override var canBecomeMain: Bool { return true }
override var styleMask: NSWindow.StyleMask {
get { return super.styleMask }
set {
let responder = firstResponder
let windowTitle = title
super.styleMask = newValue
makeFirstResponder(responder)
title = windowTitle
}
}
convenience init(contentRect: NSRect, screen: NSScreen?, view: NSView, common com: Common) {
self.init(contentRect: contentRect,
styleMask: [.titled, .closable, .miniaturizable, .resizable],
backing: .buffered, defer: false, screen: screen)
// workaround for an AppKit bug where the NSWindow can't be placed on a
// none Main screen NSScreen outside the Main screen's frame bounds
if let wantedScreen = screen, screen != NSScreen.main {
var absoluteWantedOrigin = contentRect.origin
absoluteWantedOrigin.x += wantedScreen.frame.origin.x
absoluteWantedOrigin.y += wantedScreen.frame.origin.y
if !NSEqualPoints(absoluteWantedOrigin, self.frame.origin) {
self.setFrameOrigin(absoluteWantedOrigin)
}
}
common = com
title = com.title
minSize = NSMakeSize(160, 90)
collectionBehavior = .fullScreenPrimary
delegate = self
if let cView = contentView {
cView.addSubview(view)
view.frame = cView.frame
unfsContentFrame = convertToScreen(cView.frame)
}
targetScreen = screen
currentScreen = screen
unfScreen = screen
if let app = NSApp as? Application {
app.menuBar.register(#selector(setHalfWindowSize), for: MPM_H_SIZE)
app.menuBar.register(#selector(setNormalWindowSize), for: MPM_N_SIZE)
app.menuBar.register(#selector(setDoubleWindowSize), for: MPM_D_SIZE)
app.menuBar.register(#selector(performMiniaturize(_:)), for: MPM_MINIMIZE)
app.menuBar.register(#selector(performZoom(_:)), for: MPM_ZOOM)
}
}
override func toggleFullScreen(_ sender: Any?) {
if isAnimating {
return
}
isAnimating = true
targetScreen = common.getTargetScreen(forFullscreen: !isInFullscreen)
if targetScreen == nil && previousScreen == nil {
targetScreen = screen
} else if targetScreen == nil {
targetScreen = previousScreen
previousScreen = nil
} else {
previousScreen = screen
}
if let contentViewFrame = contentView?.frame, !isInFullscreen {
unfsContentFrame = convertToScreen(contentViewFrame)
unfScreen = screen
}
// move window to target screen when going to fullscreen
if let tScreen = targetScreen, !isInFullscreen && (tScreen != screen) {
let frame = calculateWindowPosition(for: tScreen, withoutBounds: false)
setFrame(frame, display: true)
}
if Bool(mpv?.opts.native_fs ?? 1) {
super.toggleFullScreen(sender)
} else {
if !isInFullscreen {
setToFullScreen()
}
else {
setToWindow()
}
}
}
func customWindowsToEnterFullScreen(for window: NSWindow) -> [NSWindow]? {
return [window]
}
func customWindowsToExitFullScreen(for window: NSWindow) -> [NSWindow]? {
return [window]
}
func window(_ window: NSWindow, startCustomAnimationToEnterFullScreenWithDuration duration: TimeInterval) {
guard let tScreen = targetScreen else { return }
common.view?.layerContentsPlacement = .scaleProportionallyToFit
common.titleBar?.hide()
NSAnimationContext.runAnimationGroup({ (context) -> Void in
context.duration = getFsAnimationDuration(duration - 0.05)
window.animator().setFrame(tScreen.frame, display: true)
}, completionHandler: { })
}
func window(_ window: NSWindow, startCustomAnimationToExitFullScreenWithDuration duration: TimeInterval) {
guard let tScreen = targetScreen, let currentScreen = screen else { return }
let newFrame = calculateWindowPosition(for: tScreen, withoutBounds: tScreen == screen)
let intermediateFrame = aspectFit(rect: newFrame, in: currentScreen.frame)
common.view?.layerContentsPlacement = .scaleProportionallyToFill
common.titleBar?.hide()
styleMask.remove(.fullScreen)
setFrame(intermediateFrame, display: true)
NSAnimationContext.runAnimationGroup({ (context) -> Void in
context.duration = getFsAnimationDuration(duration - 0.05)
window.animator().setFrame(newFrame, display: true)
}, completionHandler: { })
}
func windowDidEnterFullScreen(_ notification: Notification) {
isInFullscreen = true
mpv?.setOption(fullscreen: isInFullscreen)
common.updateCursorVisibility()
endAnimation(frame)
common.titleBar?.show()
}
func windowDidExitFullScreen(_ notification: Notification) {
guard let tScreen = targetScreen else { return }
isInFullscreen = false
mpv?.setOption(fullscreen: isInFullscreen)
endAnimation(calculateWindowPosition(for: tScreen, withoutBounds: targetScreen == screen))
common.view?.layerContentsPlacement = .scaleProportionallyToFit
}
func windowDidFailToEnterFullScreen(_ window: NSWindow) {
guard let tScreen = targetScreen else { return }
let newFrame = calculateWindowPosition(for: tScreen, withoutBounds: targetScreen == screen)
setFrame(newFrame, display: true)
endAnimation()
}
func windowDidFailToExitFullScreen(_ window: NSWindow) {
guard let targetFrame = targetScreen?.frame else { return }
setFrame(targetFrame, display: true)
endAnimation()
common.view?.layerContentsPlacement = .scaleProportionallyToFit
}
func endAnimation(_ newFrame: NSRect = NSZeroRect) {
if !NSEqualRects(newFrame, NSZeroRect) && isAnimating {
NSAnimationContext.runAnimationGroup({ (context) -> Void in
context.duration = 0.01
self.animator().setFrame(newFrame, display: true)
}, completionHandler: nil )
}
isAnimating = false
common.windowDidEndAnimation()
}
func setToFullScreen() {
guard let targetFrame = targetScreen?.frame else { return }
styleMask.insert(.fullScreen)
NSApp.presentationOptions = [.autoHideMenuBar, .autoHideDock]
setFrame(targetFrame, display: true)
endAnimation()
isInFullscreen = true
mpv?.setOption(fullscreen: isInFullscreen)
common.windowSetToFullScreen()
}
func setToWindow() {
guard let tScreen = targetScreen else { return }
let newFrame = calculateWindowPosition(for: tScreen, withoutBounds: targetScreen == screen)
NSApp.presentationOptions = []
setFrame(newFrame, display: true)
styleMask.remove(.fullScreen)
endAnimation()
isInFullscreen = false
mpv?.setOption(fullscreen: isInFullscreen)
common.windowSetToWindow()
}
func getFsAnimationDuration(_ def: Double) -> Double {
let duration = mpv?.macOpts.macos_fs_animation_duration ?? -1
if duration < 0 {
return def
} else {
return Double(duration)/1000
}
}
func setOnTop(_ state: Bool, _ ontopLevel: Int) {
if state {
switch ontopLevel {
case -1:
level = .floating
case -2:
level = .statusBar + 1
default:
level = NSWindow.Level(ontopLevel)
}
collectionBehavior.remove(.transient)
collectionBehavior.insert(.managed)
} else {
level = .normal
}
}
func setMinimized(_ stateWanted: Bool) {
if isMiniaturized == stateWanted { return }
if stateWanted {
performMiniaturize(self)
} else {
deminiaturize(self)
}
}
func setMaximized(_ stateWanted: Bool) {
if isZoomed == stateWanted { return }
zoom(self)
}
func updateMovableBackground(_ pos: NSPoint) {
if !isInFullscreen {
isMovableByWindowBackground = mpv?.canBeDraggedAt(pos) ?? true
} else {
isMovableByWindowBackground = false
}
}
func updateFrame(_ rect: NSRect) {
if rect != frame {
let cRect = frameRect(forContentRect: rect)
unfsContentFrame = rect
setFrame(cRect, display: true)
common.windowDidUpdateFrame()
}
}
func updateSize(_ size: NSSize) {
if let currentSize = contentView?.frame.size, size != currentSize {
let newContentFrame = centeredContentSize(for: frame, size: size)
if !isInFullscreen {
updateFrame(newContentFrame)
} else {
unfsContentFrame = newContentFrame
}
}
}
override func setFrame(_ frameRect: NSRect, display flag: Bool) {
if frameRect.width < minSize.width || frameRect.height < minSize.height {
common.log.sendVerbose("tried to set too small window size: \(frameRect.size)")
return
}
super.setFrame(frameRect, display: flag)
if let size = unfsContentFrame?.size, keepAspect {
contentAspectRatio = size
}
}
func centeredContentSize(for rect: NSRect, size sz: NSSize) -> NSRect {
let cRect = contentRect(forFrameRect: rect)
let dx = (cRect.size.width - sz.width) / 2
let dy = (cRect.size.height - sz.height) / 2
return NSInsetRect(cRect, dx, dy)
}
func aspectFit(rect r: NSRect, in rTarget: NSRect) -> NSRect {
var s = rTarget.width / r.width
if r.height*s > rTarget.height {
s = rTarget.height / r.height
}
let w = r.width * s
let h = r.height * s
return NSRect(x: rTarget.midX - w/2, y: rTarget.midY - h/2, width: w, height: h)
}
func calculateWindowPosition(for tScreen: NSScreen, withoutBounds: Bool) -> NSRect {
guard let contentFrame = unfsContentFrame, let screen = unfScreen else {
return frame
}
var newFrame = frameRect(forContentRect: contentFrame)
let targetFrame = tScreen.frame
let targetVisibleFrame = tScreen.visibleFrame
let unfsScreenFrame = screen.frame
let visibleWindow = NSIntersectionRect(unfsScreenFrame, newFrame)
// calculate visible area of every side
let left = newFrame.origin.x - unfsScreenFrame.origin.x
let right = unfsScreenFrame.size.width -
(newFrame.origin.x - unfsScreenFrame.origin.x + newFrame.size.width)
let bottom = newFrame.origin.y - unfsScreenFrame.origin.y
let top = unfsScreenFrame.size.height -
(newFrame.origin.y - unfsScreenFrame.origin.y + newFrame.size.height)
// normalize visible areas, decide which one to take horizontal/vertical
var xPer = (unfsScreenFrame.size.width - visibleWindow.size.width)
var yPer = (unfsScreenFrame.size.height - visibleWindow.size.height)
if xPer != 0 { xPer = (left >= 0 || right < 0 ? left : right) / xPer }
if yPer != 0 { yPer = (bottom >= 0 || top < 0 ? bottom : top) / yPer }
// calculate visible area for every side for target screen
let xNewLeft = targetFrame.origin.x +
(targetFrame.size.width - visibleWindow.size.width) * xPer
let xNewRight = targetFrame.origin.x + targetFrame.size.width -
(targetFrame.size.width - visibleWindow.size.width) * xPer - newFrame.size.width
let yNewBottom = targetFrame.origin.y +
(targetFrame.size.height - visibleWindow.size.height) * yPer
let yNewTop = targetFrame.origin.y + targetFrame.size.height -
(targetFrame.size.height - visibleWindow.size.height) * yPer - newFrame.size.height
// calculate new coordinates, decide which one to take horizontal/vertical
newFrame.origin.x = left >= 0 || right < 0 ? xNewLeft : xNewRight
newFrame.origin.y = bottom >= 0 || top < 0 ? yNewBottom : yNewTop
// don't place new window on top of a visible menubar
let topMar = targetFrame.size.height -
(newFrame.origin.y - targetFrame.origin.y + newFrame.size.height)
let menuBarHeight = targetFrame.size.height -
(targetVisibleFrame.size.height + targetVisibleFrame.origin.y)
if topMar < menuBarHeight {
newFrame.origin.y -= top - menuBarHeight
}
if withoutBounds {
return newFrame
}
// screen bounds right and left
if newFrame.origin.x + newFrame.size.width > targetFrame.origin.x + targetFrame.size.width {
newFrame.origin.x = targetFrame.origin.x + targetFrame.size.width - newFrame.size.width
}
if newFrame.origin.x < targetFrame.origin.x {
newFrame.origin.x = targetFrame.origin.x
}
// screen bounds top and bottom
if newFrame.origin.y + newFrame.size.height > targetFrame.origin.y + targetFrame.size.height {
newFrame.origin.y = targetFrame.origin.y + targetFrame.size.height - newFrame.size.height
}
if newFrame.origin.y < targetFrame.origin.y {
newFrame.origin.y = targetFrame.origin.y
}
return newFrame
}
override func constrainFrameRect(_ frameRect: NSRect, to tScreen: NSScreen?) -> NSRect {
if (isAnimating && !isInFullscreen) || (!isAnimating && isInFullscreen) {
return frameRect
}
guard let ts: NSScreen = tScreen ?? screen ?? NSScreen.main else {
return frameRect
}
var nf: NSRect = frameRect
let of: NSRect = frame
let vf: NSRect = (isAnimating ? (targetScreen ?? ts) : ts).visibleFrame
let ncf: NSRect = contentRect(forFrameRect: nf)
// screen bounds top and bottom
if NSMaxY(nf) > NSMaxY(vf) {
nf.origin.y = NSMaxY(vf) - NSHeight(nf)
}
if NSMaxY(ncf) < NSMinY(vf) {
nf.origin.y = NSMinY(vf) + NSMinY(ncf) - NSMaxY(ncf)
}
// screen bounds right and left
if NSMinX(nf) > NSMaxX(vf) {
nf.origin.x = NSMaxX(vf) - NSWidth(nf)
}
if NSMaxX(nf) < NSMinX(vf) {
nf.origin.x = NSMinX(vf)
}
if NSHeight(nf) < NSHeight(vf) && NSHeight(of) > NSHeight(vf) && !isInFullscreen {
// If the window height is smaller than the visible frame, but it was
// bigger previously recenter the smaller window vertically. This is
// needed to counter the 'snap to top' behaviour.
nf.origin.y = (NSHeight(vf) - NSHeight(nf)) / 2
}
return nf
}
@objc func setNormalWindowSize() { setWindowScale(1.0) }
@objc func setHalfWindowSize() { setWindowScale(0.5) }
@objc func setDoubleWindowSize() { setWindowScale(2.0) }
func setWindowScale(_ scale: Double) {
mpv?.command("set window-scale \(scale)")
}
func addWindowScale(_ scale: Double) {
if !isInFullscreen {
mpv?.command("add window-scale \(scale)")
}
}
func windowDidChangeScreen(_ notification: Notification) {
if screen == nil {
return
}
if !isAnimating && (currentScreen != screen) {
previousScreen = screen
}
if currentScreen != screen {
common.updateDisplaylink()
common.windowDidChangeScreen()
}
currentScreen = screen
}
func windowDidChangeScreenProfile(_ notification: Notification) {
common.windowDidChangeScreenProfile()
}
func windowDidChangeBackingProperties(_ notification: Notification) {
common.windowDidChangeBackingProperties()
common.flagEvents(VO_EVENT_DPI)
}
func windowWillStartLiveResize(_ notification: Notification) {
common.windowWillStartLiveResize()
}
func windowDidEndLiveResize(_ notification: Notification) {
common.windowDidEndLiveResize()
mpv?.setOption(maximized: isZoomed)
if let contentViewFrame = contentView?.frame,
!isAnimating && !isInFullscreen
{
unfsContentFrame = convertToScreen(contentViewFrame)
}
}
func windowDidResize(_ notification: Notification) {
common.windowDidResize()
}
func windowShouldClose(_ sender: NSWindow) -> Bool {
cocoa_put_key(MP_KEY_CLOSE_WIN)
return false
}
func windowDidMiniaturize(_ notification: Notification) {
mpv?.setOption(minimized: true)
}
func windowDidDeminiaturize(_ notification: Notification) {
mpv?.setOption(minimized: false)
}
func windowDidResignKey(_ notification: Notification) {
common.setCursorVisiblility(true)
}
func windowDidBecomeKey(_ notification: Notification) {
common.updateCursorVisibility()
}
func windowDidChangeOcclusionState(_ notification: Notification) {
if occlusionState.contains(.visible) {
common.windowDidChangeOcclusionState()
common.updateCursorVisibility()
}
}
func windowWillMove(_ notification: Notification) {
isMoving = true
}
func windowDidMove(_ notification: Notification) {
mpv?.setOption(maximized: isZoomed)
}
}
| gpl-2.0 | 525461396418f086000c5d37e8fb0e22 | 35.201097 | 137 | 0.62125 | 4.864161 | false | false | false | false |
volodg/iAsync.social | Pods/iAsync.network/Lib/NSError/NSNetworkErrors/JNSNetworkError.swift | 1 | 2045 | //
// JNSNetworkError.swift
// Wishdates
//
// Created by Vladimir Gorbenko on 18.08.14.
// Copyright (c) 2014 EmbeddedSources. All rights reserved.
//
import Foundation
import iAsync_utils
public class JNSNetworkError : JNetworkError {
let context: JURLConnectionParams
let nativeError: NSError
public required init(context: JURLConnectionParams, nativeError: NSError) {
self.context = context
self.nativeError = nativeError
super.init(description:"")
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override var localizedDescription: String {
return NSLocalizedString(
"J_NETWORK_GENERIC_ERROR",
bundle: NSBundle(forClass: self.dynamicType),
comment:"")
}
public class func createJNSNetworkErrorWithContext(
context: JURLConnectionParams, nativeError: NSError) -> JNSNetworkError {
var selfType: JNSNetworkError.Type!
//select class for error
let errorClasses: [JNSNetworkError.Type] =
[
JNSNoInternetNetworkError.self
]
selfType = firstMatch(errorClasses) { (object: JNSNetworkError.Type) -> Bool in
return object.isMineNSNetworkError(nativeError)
}
if selfType == nil {
selfType = JNSNetworkError.self
}
return selfType(context: context, nativeError: nativeError)
}
class func isMineNSNetworkError(error: NSError) -> Bool {
return false
}
public override func copyWithZone(zone: NSZone) -> AnyObject {
return self.dynamicType(context: context, nativeError: nativeError)
}
public override var errorLogDescription: String {
return "\(self.dynamicType) : \(localizedDescription) nativeError:\(nativeError) context:\(context)"
}
}
| mit | 3ad278946667da727e4f974e9331ca1b | 26.266667 | 108 | 0.616137 | 5.339426 | false | false | false | false |
AlvinL33/TownHunt | TownHunt-1.9/TownHunt/RegistrationPageViewController.swift | 1 | 5789 | //
// RegistrationPageViewController.swift
// TownHunt
//
// Created by Alvin Lee on 18/02/2017.
// Copyright © 2017 LeeTech. All rights reserved.
//
import UIKit
class RegistrationPageViewController: FormTemplateExtensionOfViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
@IBOutlet weak var userRepeatPassWordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "registrationBackgroundImage")?.draw(in: self.view.bounds)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func registerButtonTapped(_ sender: Any) {
// Initialises database interaction object
let dbInteraction = DatabaseInteraction()
// Tests for internet connectivity
if dbInteraction.connectedToNetwork(){
let username = usernameTextField.text
let userEmail = userEmailTextField.text
let userPassword = userPasswordTextField.text
let userRepeatPassword = userRepeatPassWordTextField.text
//Check for empty fields
if((username?.isEmpty)! || (userEmail?.isEmpty)! || (userPassword?.isEmpty)! || (userRepeatPassword?.isEmpty)!) {
//Display error message
displayAlertMessage(alertTitle: "Data Entry Error", alertMessage: "All fields must be complete")
return
// Checks if email is a valid email address
} else if !isEmailValid(testStr: userEmail!){
displayAlertMessage(alertTitle: "Email Invalid", alertMessage: "Please enter a valid email")
return
// Checks if username only contains alphanumberic characters
} else if !isAlphanumeric(testStr: username!){
displayAlertMessage(alertTitle: "Username Invalid", alertMessage: "Username must only contain alphanumeric characters")
return
//Check if passwords are the same
}else if(userPassword != userRepeatPassword){
//Displays error message
displayAlertMessage(alertTitle: "ERROR", alertMessage: "Passwords do not match")
return
}
//Sends data to be posted and receives a response
let responseJSON = dbInteraction.postToDatabase(apiName: "registerUser.php", postData: "username=\(username!)&userEmail=\(userEmail!)&userPassword=\(userPassword!)"){ (dbResponse: NSDictionary) in
//If there is an error, the error is presented to the user
var alertTitle = "ERROR"
var alertMessage = "JSON File Invalid"
var isUserRegistered = false
if dbResponse["error"]! as! Bool{
print("error: \(dbResponse["error"]!)")
alertTitle = "ERROR"
alertMessage = dbResponse["message"]! as! String
}
else if !(dbResponse["error"]! as! Bool){
alertTitle = "Thank You"
alertMessage = dbResponse["message"]! as! String
isUserRegistered = true
}
else{
alertTitle = "ERROR"
alertMessage = "JSON File Invalid"
}
DispatchQueue.main.async(execute: {
let alertCon = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
alertCon.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in
if isUserRegistered{
self.dismiss(animated: true, completion: nil)
}}))
self.present(alertCon, animated: true, completion: nil)
})
}
}else{ // If no internet connectivity, an error message is diplayed asking the user to connect to the internet
let alertCon = UIAlertController(title: "Error: Couldn't Connect to Database", message: "No internet connectivity found. Please check your internet connection", preferredStyle: .alert)
alertCon.addAction(UIAlertAction(title: "Try Again", style: .default, handler: { action in
// Recursion is used to recall the register function until internet connectivity is restored
self.registerButtonTapped(Any.self)
}))
self.present(alertCon, animated: true, completion: nil)
}
}
@IBAction func alreadyHaveAccountButtonTapped(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
override func displayAlertMessage(alertTitle: String, alertMessage: String){
let alertCon = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
alertCon.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alertCon, animated: true, completion: nil)
}
}
| apache-2.0 | 8aa88f4f5bdedb0285b061546f3df73b | 41.874074 | 208 | 0.593296 | 6.004149 | false | false | false | false |
jindulys/Leetcode_Solutions_Swift | Sources/Array/350_IntersectionOfTwoArraysII.swift | 1 | 1316 | //
// 350_IntersectionOfTwoArraysII.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-08-27.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:350 Intersection of two arrays II
URL: https://leetcode.com/problems/intersection-of-two-arrays-ii/
Space: O(n)
Time: O(n) Hsn
*/
class IntersectionOfTwoArraysII_Solution {
func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
var result: [Int] = []
let nums1Dict = nums1.generateCountDict()
let nums2Dict = nums2.generateCountDict()
for (element, occuranceCount) in nums1Dict {
if let nums2OccuranceCount = nums2Dict[element] {
result.append(contentsOf: Array(repeating: element,
count: min(occuranceCount, nums2OccuranceCount)))
}
}
return result
}
}
// TODO(simonli): move to `LeetCodeKit`.
extension Array where Element: Hashable {
/// generate count dict.
/// - key : the element in the array.
/// - value: the occurance count of this array.
public func generateCountDict() -> [Element: Int] {
var dict: [Element: Int] = [:]
for element in self {
if let occuranceCount = dict[element] {
dict[element] = occuranceCount + 1
} else {
dict[element] = 1
}
}
return dict
}
}
| mit | 3abac40e046ba1651f8a35c77adcf6d5 | 25.836735 | 79 | 0.637262 | 3.534946 | false | false | false | false |
TouchInstinct/LeadKit | TILogging/Sources/Views/LoggerList/LogEntryCellView.swift | 1 | 3515 | //
// Copyright (c) 2022 Touch Instinct
//
// 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 TIUIElements
import UIKit
open class LogEntryCellView: BaseInitializableView {
public let containerView = UIStackView()
public let timeLabel = UILabel()
public let processLabel = UILabel()
public let messageLabel = UILabel()
public let levelTypeView = UIView()
// MARK: - Life cycle
open override func addViews() {
super.addViews()
containerView.addArrangedSubviews(timeLabel, processLabel)
addSubviews(containerView,
messageLabel,
levelTypeView)
}
open override func configureLayout() {
super.configureLayout()
[containerView, timeLabel, processLabel, messageLabel, levelTypeView]
.forEach { $0.translatesAutoresizingMaskIntoConstraints = false }
NSLayoutConstraint.activate([
containerView.centerYAnchor.constraint(equalTo: centerYAnchor),
containerView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
containerView.topAnchor.constraint(equalTo: topAnchor, constant: 8),
containerView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8),
messageLabel.leadingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: 8),
messageLabel.topAnchor.constraint(equalTo: topAnchor, constant: 8),
messageLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8),
messageLabel.trailingAnchor.constraint(equalTo: levelTypeView.leadingAnchor, constant: -8),
levelTypeView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
levelTypeView.centerYAnchor.constraint(equalTo: centerYAnchor),
levelTypeView.heightAnchor.constraint(equalToConstant: 10),
levelTypeView.widthAnchor.constraint(equalToConstant: 10),
])
}
open override func configureAppearance() {
super.configureAppearance()
containerView.axis = .vertical
containerView.spacing = 4
timeLabel.font = .systemFont(ofSize: 10)
processLabel.lineBreakMode = .byTruncatingTail
processLabel.font = .systemFont(ofSize: 12)
messageLabel.numberOfLines = 0
messageLabel.lineBreakMode = .byWordWrapping
messageLabel.font = .systemFont(ofSize: 12)
levelTypeView.layer.cornerRadius = 3
}
}
| apache-2.0 | 36edf17c42e2f890bec460870a3d4f4c | 39.872093 | 103 | 0.7101 | 5.293675 | false | false | false | false |
manderson-productions/RompAround | RompAround/LootSprite.swift | 1 | 1944 | //
// LootSprite.swift
// RompAround
//
// Created by Mark Anderson on 10/15/15.
// Copyright © 2015 manderson-productions. All rights reserved.
//
import Foundation
import SpriteKit
class LootSprite: SKSpriteNode {
enum LootType: Int {
case Gold, Card, Random
static func getRandom() -> LootType {
return LootType(rawValue: (0...LootType.Random.rawValue - 1).randomInt)!
}
init(var type: LootType) {
if type == .Random { type = LootType.getRandom() }
self = type
}
}
func getLoot() -> Lootable? {
let json: [String: AnyObject] = Dictionary.jsonDictionaryFromResourceName("Zero")!
let lootArray = (json["loot"] as! [[String: AnyObject]])
switch type {
case .Gold:
for gold in lootArray {
if (gold["type"] as! String) == "\(LootType.Gold)" {
let minValue = gold["amount_min"] as! Int
let maxValue = gold["amount_max"] as! Int
let randomGoldAmount = (minValue...maxValue).randomInt
return Gold(amount: randomGoldAmount)
}
}
case .Card:
for card in lootArray {
if (card["type"] as! String) == "\(LootType.Card)" {
return Card(info: (card["info"] as! String), attack: (card["attack"] as! Int), defense: (card["defense"] as! Int), health: (card["health"] as! Int))
}
}
default:
return nil
}
return nil
}
let type: LootType
init(color: UIColor, size: CGSize, type: LootType = .Random) {
self.type = LootType(type: type)
super.init(texture: nil, color: color, size: size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} | apache-2.0 | f2dca382abecbdf0947a620ede03b38a | 29.375 | 168 | 0.528564 | 4.327394 | false | false | false | false |
derekcdaley/anipalooza | Level2Scene.swift | 1 | 4786 | //
// Level2Scene.swift
// AniPalooza
//
// Created by Derek Daley on 3/29/17.
// Copyright © 2017 DSkwared. All rights reserved.
//
import SpriteKit
import AVFoundation
class Level2Scene: SKScene {
private let homeButton = HomeButton();
private let positioning = Positioning();
private let musicButton = MusicButton();
private let playSoundButton = PlaySoundButton();
private let notificationSound = NotificationSounds();
private let settings = SettingsScene();
private let animalController = AnimalController();
private let randonmizeButton = RandomizeButton();
private var bgMusic = BackgroundMusicController();
private var musicButtons = [SKNode]();
private var timeAtPress : NSDate? = nil
override func didMove(to view: SKView) {
self.intializeView();
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
var tapCount = 0;
for touch in touches {
let location = touch.location(in: self);
let touchedNode = self.atPoint(location);
if touchedNode.name != nil {
//if home button tapped, go home
if touchedNode.name == "Home" ||
touchedNode.parent?.name == "Home"{
tapCount = touch.tapCount;
if tapCount == 1 {
homeButton.singleTapHome(scene: self.scene!);
}else if tapCount == 2 {
homeButton.doubleTapHome(scene: self);
}
}
//if music button tapped, toggle music
if (touchedNode.name?.contains("Music"))!{
//if the music is on, we need to turn it off
let musicOnOff = (touchedNode.name!.contains("On")) ? "Off" : "On";
bgMusic.toggleMusic(musicOnOff: musicOnOff, scene: self.scene!, musicButtons: musicButtons);
}
//debounce all actions after this
if (timeAtPress == nil){
timeAtPress = NSDate();
}else{
let elapsed = NSDate().timeIntervalSince(timeAtPress! as Date);
if (elapsed < 1.0){
return;
}else{
timeAtPress = nil;
}
}
if (touchedNode.name?.contains("_anm"))! {
let touched = self.childNode(withName: touchedNode.name!);
if (touched!.contains(location)) {
isTouchedAnimalCorrect(node: touchedNode);
}
}
//if play sound button tapped
if touchedNode.name == "PlaySoundBtn" {
playSoundButton.generateRandomSound(scene: self);
}
}
}
}
func intializeView(){
let musicPref = settings.defaults.string(forKey: "MusicPref");
let defaultPos = (positioning.getDeviceForPos() == "ipad") ? 70 : 40;
getScoreLabels();
ScoringController.instance.initializeVariables();
animalController.arrangeAnimalsInScene(scene: self.scene!);
playSoundButton.createPlaySoundButton(scene: self.scene!);
musicButtons = musicButton.createButtons(scene: self.scene!);
homeButton.setHomePosition(defaultPos: defaultPos, scene: self.scene!);
bgMusic.toggleMusic(musicOnOff: musicPref!, scene: self.scene!, musicButtons: musicButtons);
}
func isTouchedAnimalCorrect(node: SKNode){
let playButton:CustomNode = self.childNode(withName: "PlaySoundBtn") as! CustomNode;
var sound:AVAudioPlayer! = nil;
if node.name == playButton.soundName{
sound = notificationSound.retrieveSoundEffect(notification: "correct");
ScoringController.instance.incrementScore();
playButton.removeFromParent();
randonmizeButton.retrieveDifferentAnimals(scene: self.scene!);
playSoundButton.createPlaySoundButton(scene: self.scene!);
}else{
sound = notificationSound.retrieveSoundEffect(notification: "incorrect");
}
ScoringController.instance.incrementAttempt();
sound.play();
}
func getScoreLabels() {
ScoringController.instance.level2ScoringText = self.childNode(withName: "ScoreNumber") as? SKLabelNode;
ScoringController.instance.level2AttemptsText = self.childNode(withName: "ScoreAttempt") as? SKLabelNode;
}
}
| gpl-3.0 | d9b7a91d73518ce26bbdc29e0e23e79f | 37.902439 | 113 | 0.56092 | 5.240964 | false | false | false | false |
mobgeek/swift | Swift em 4 Semanas/Swift4Semanas (7.0).playground/Pages/S4 - Nested Types.xcplaygroundpage/Contents.swift | 1 | 1444 | //: [Anterior: Subscripts](@previous)
// Playground - noun: a place where people can play
import UIKit
// Nested Types
struct PapelMoeda {
// tipo aninhado: Moeda
enum Moeda: String {
case Dolar = "$", Euro = "€", Real = "R$"
var porExtenso: String {
switch self {
case .Dolar:
return "Dólar Americano"
case .Euro:
return "Euro"
case .Real:
return "Real"
}
}
}
//tipo aninhado: Valor
enum Valor: Int {
case Dois = 2, Cinco = 5, Dez = 10, Vinte = 20, Cinquenta = 50, Cem = 100
}
// Propriedades de PapelMoeda:
let moeda: Moeda, valor: Valor
var descrição: String {
return "Nota impressa de \(moeda.porExtenso) valendo \(moeda.rawValue)\(valor.rawValue)"
}
}
let cemReais = PapelMoeda(moeda: .Real, valor: .Cem)
cemReais.descrição
let vinteEuros = PapelMoeda(moeda: .Euro, valor: .Vinte)
vinteEuros.descrição
//E se Swift não inferisse o tipo?
let maisCemReais = PapelMoeda(moeda: PapelMoeda.Moeda.Real, valor: .Cem)
let simboloEuro = PapelMoeda.Moeda.Euro.rawValue
//: [Próximo: Extensions](@next)
| mit | 90562eeeef025c68f8fc4aa928d43f57 | 18.630137 | 96 | 0.49686 | 4.03662 | false | false | false | false |
AlesTsurko/DNMKit | DNM_iOS/DNM_iOS/MeasureView.swift | 1 | 6929 | //
// Measure.swift
// denm_view
//
// Created by James Bean on 8/19/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import UIKit
import DNMModel
public class MeasureView: ViewNode, BuildPattern {
public override var description: String { get { return getDescription() } }
public var system: SystemLayer?
public var measure: Measure?
//public var duration: Duration?
public var offsetDur: Duration = DurationZero
public var dur: Duration?
public var durationSpan: DurationSpan!
//var left: CGFloat = 0
public var g: CGFloat = 0
public var scale: CGFloat = 0
//var width: CGFloat = 0
public var height: CGFloat = 200 // to be set by system
public var number: Int = 0
public var beatWidth: CGFloat = 0
public var barlineLeft: Barline?
public var barlineRight: Barline?
public var timeSignature: TimeSignature?
public var measureNumber: MeasureNumber?
public var hasTimeSignature: Bool = true
public var hasBeenBuilt: Bool = false
//public var mgRects: [MetronomeGridRect] = []
//public var mgRectsShown: Bool = true // temporary!
public class func rangeFromMeasures(
measures: [MeasureView],
startingAtIndex index: Int,
constrainedByMaximumTotalWidth maximumWidth: CGFloat
) -> [MeasureView]
{
var measureRange: [MeasureView] = []
var m: Int = index
var accumLeft: CGFloat = 0
while m < measures.count && accumLeft < maximumWidth {
let measure_width = measures[m].dur!.width(beatWidth: measures[m].beatWidth)
if accumLeft + measure_width <= maximumWidth {
measureRange.append(measures[m])
accumLeft += measure_width
m++
}
else { break }
}
return measureRange
}
public init(measure: Measure) {
self.measure = measure
self.hasTimeSignature = measure.hasTimeSignature
self.durationSpan = measure.durationSpan
self.offsetDur = measure.offsetDuration
self.dur = measure.duration
self.number = measure.number
super.init()
}
public init(offsetDuration: Duration) {
self.offsetDur = offsetDuration
super.init()
}
public init(duration: Duration) {
self.dur = duration
super.init()
}
public init(
duration: Duration,
number: Int,
g: CGFloat,
scale: CGFloat,
left: CGFloat,
beatWidth: CGFloat
)
{
self.dur = duration
self.number = number
self.g = g
self.scale = scale
self.beatWidth = beatWidth
super.init()
self.left = left
build()
}
public override init() { super.init() }
public override init(layer: AnyObject) { super.init(layer: layer) }
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
public func setDuration(duration: Duration) {
self.dur = duration
}
public func build() {
// for now:
setFrame()
addMeasureNumber()
// make more intelligent
if hasTimeSignature { addTimeSignature() }
// addMGRects()
// add barline(s) --> handoff to system
// add measure number --> handoff to system
hasBeenBuilt = true
}
public func addBarlineLeft() {
barlineLeft = Barline(x: 0, top: timeSignature!.frame.maxY + g, bottom: 200)
barlineLeft?.lineWidth = 0.382 * g
addSublayer(barlineLeft!)
}
public func addBarlineRight() {
barlineRight = Barline(x: frame.width, top: timeSignature!.frame.maxY + g, bottom: 200)
barlineRight?.lineWidth = 0.382 * g
addSublayer(barlineRight!)
}
// modify this to work with new TemporalInfoNode infrastructrue
private func addTimeSignature() {
timeSignature = TimeSignature(
numerator: dur!.beats!.amount,
denominator: dur!.subdivision!.value,
x: 0,
top: 0,
height: 3.82 * g
)
timeSignature?.measure = self
addSublayer(timeSignature!)
}
// modify this to work with new TemporalInfoNode infrastructrue
private func addMeasureNumber() {
measureNumber = MeasureNumber(number: number, x: 0, top: 0, height: 1.618 * g)
measureNumber?.measure = self
addSublayer(measureNumber!)
}
private func addBarline() {
// to be handed off later?
barlineLeft = Barline(x: 0, top: 2.25 * g, bottom: 0)
addSublayer(barlineLeft!)
}
/*
public func switchMGRects() {
print("switch mgrects", terminator: "")
if mgRectsShown {
print("are shown", terminator: "")
// remove
CATransaction.setDisableActions(true)
for mgRect in mgRects {
mgRect.removeFromSuperlayer()
mgRectsShown = false
}
CATransaction.setDisableActions(false)
}
else {
print("are not shown", terminator: "")
// add
CATransaction.setDisableActions(true)
for mgRect in mgRects {
system?.addSublayer(mgRect)
mgRectsShown = true
}
CATransaction.setDisableActions(false)
}
}
*/
/*
private func addMGRects() {
// encapsulate
// add metronome grid rect
if dur != nil {
let rect_dur = Duration(1, dur!.subdivision!.value)
let rect_width = graphicalWidth(duration: rect_dur, beatWidth: beatWidth) // temp!
//let rect_width = rect_dur.getGraphicalWidth(beatWidth: 120)
var accumLeft: CGFloat = left
for _ in 0..<dur!.beats!.amount {
let mgRect = MetronomeGridRect(
rect: CGRectMake(accumLeft, 0, rect_width, frame.height)
)
mgRects.append(mgRect)
accumLeft += mgRect.frame.width
}
}
}
*/
// refine, move down
private func getDurationSpan() -> DurationSpan {
if dur == nil { return DurationSpan() }
let durationSpan = DurationSpan(duration: dur!, startDuration: offsetDur)
return durationSpan
}
private func setFrame() {
//let width = dur!.getGraphicalWidth(beatWidth: beatWidth)
//let width = graphicalWidth(duration: dur!, beatWidth: beatWidth)
let width = dur!.width(beatWidth: beatWidth)
frame = CGRectMake(0, 0, width, 0)
}
private func getDescription() -> String {
return "Measure: \(dur!), offset: \(offsetDur)"
}
}
| gpl-2.0 | c3850604b3099f5220a67b3a318070db | 27.987448 | 95 | 0.573614 | 4.758242 | false | false | false | false |
hernan43/OctoStatus | OctoStatus/OctoStatusMenu.swift | 1 | 3376 | //
// OctoStatusMenu.swift
// OctoStatus
//
// Created by Ramon Hernandez on 11/22/14.
// Copyright (c) 2014 Shaclack. All rights reserved.
//
import Cocoa
class OctoStatusMenu: NSMenu {
// MARK: IBOutlets
@IBOutlet weak var jobStatusItem: NSMenuItem!
@IBOutlet weak var filenameItem: NSMenuItem!
@IBOutlet weak var timeRemainingItem: NSMenuItem!
@IBOutlet weak var settingsItem: NSMenuItem!
@IBOutlet weak var quitItem: NSMenuItem!
// MARK: Class and instance variables
lazy var settingsController = SettingsController(windowNibName: "SettingsController")
// will use this to poll OctoPrint via the client
var jobStatusTimer: NSTimer?
// MARK: Required functions
override init(title aTitle: String){
super.init(title: aTitle)
startPolling()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
startPolling()
}
// MARK: Public functions
func getJobStatus() -> String {
return jobStatusItem.title
}
func checkJobStatus(){
OctoPrintClient.sharedInstance.jobStatus().responseJSON { (_, _, JSON, _) in
if let json: AnyObject = JSON? {
//println(json)
self.processJSONResponse(json)
}
}
}
func setMenuItems(json: AnyObject){
setFilename(json)
// hide everything but the status
jobStatusItem.hidden = false
timeRemainingItem.hidden = true
}
func setFilename(json: AnyObject){
// default state
filenameItem.hidden = true
// set active filename, if loaded
if let filename = json.valueForKeyPath("job.file.name") as? String {
filenameItem.title = "file: \(filename)"
// show filename if file is loaded
filenameItem.hidden = false
}
}
func processJSONResponse(json: AnyObject) {
if let status = json["state"]? as? String {
// set both the statusitem and menuitem
jobStatusItem.title = status.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
/*
List of states I could find in the OctoPrint source
Offline
Opening serial port
Detecting serial port
Detecting baudrate
Connecting
Operational
Printing from SD
Sending file to SD
Printing
Paused
Closed
Error: %s
Transfering file to SD
*/
switch status {
default:
setMenuItems(json)
}
}
}
func startPolling(){
jobStatusTimer = NSTimer.scheduledTimerWithTimeInterval(
5.0,
target: self,
selector: "checkJobStatus",
userInfo: nil,
repeats: true)
}
// MARK: IBActions
@IBAction func settingsClicked(sender: AnyObject) {
if let window = settingsController.window? {
window.center()
window.makeKeyAndOrderFront(window)
}
}
@IBAction func quitClicked(sender: AnyObject) {
NSApplication.sharedApplication().terminate(nil)
}
}
| gpl-3.0 | 2bbd1d6cde660afd09aec829626e44ee | 25.793651 | 123 | 0.57731 | 5.299843 | false | false | false | false |
jonasman/TeslaSwift | TeslaSwiftDemo/SecondViewController.swift | 1 | 2278 | //
// SecondViewController.swift
// TeslaSwift
//
// Created by Joao Nunes on 04/03/16.
// Copyright © 2016 Joao Nunes. All rights reserved.
//
import UIKit
#if canImport(Combine)
import Combine
#endif
class SecondViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var data:[Product]?
override func viewDidLoad() {
super.viewDidLoad()
getProducts()
NotificationCenter.default.addObserver(forName: Notification.Name.loginDone, object: nil, queue: nil) { [weak self] (notification: Notification) in
self?.getProducts()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.estimatedRowHeight = 50.0
}
func getProducts() {
Task { @MainActor in
self.data = try await api.getProducts()
self.tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "product-cell", for: indexPath)
let product = data![(indexPath as NSIndexPath).row]
if let vehicle = product.vehicle {
cell.textLabel?.text = vehicle.displayName
cell.detailTextLabel?.text = vehicle.vin
} else if let energySite = product.energySite {
cell.textLabel?.text = energySite.siteName
cell.detailTextLabel?.text = energySite.resourceType
} else {
cell.textLabel?.text = "Unknown"
cell.detailTextLabel?.text = "Unknown"
}
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if segue.identifier == "toProductDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
let vc = segue.destination as! ProductViewController
vc.product = data![indexPath.row]
}
}
}
}
| mit | 242b0db4ee5243416edfe8ea59ad0c1f | 29.36 | 155 | 0.614844 | 5.037611 | false | false | false | false |
ZamzamInc/ZamzamKit | Tests/ZamzamKitTests/Extensions/WebTests.swift | 1 | 1025 | //
// WebHelperTests.swift
// ZamzamCore
//
// Created by Basem Emara on 1/20/16.
// Copyright © 2020 Zamzam Inc. All rights reserved.
//
import XCTest
import ZamzamCore
final class WebTests: XCTestCase {
}
extension WebTests {
func testStrippedHTML() {
let value = "<html><head><title>Test</title></head><body></body></html>"
let expectedValue = "Test"
XCTAssertEqual(value.htmlStripped, expectedValue)
}
func testStrippedHTML2() {
let test = "<p>This is <em>web</em> content with a <a href=\"http://example.com\">link</a>.</p>"
let expected = "This is web content with a link."
XCTAssertEqual(test.htmlStripped, expected)
}
}
extension WebTests {
func testDecodeHTML() {
let value = "<strong> 4 < 5 & 3 > 2 .</strong> Price: 12 €. @"
let newValue = value.htmlDecoded()
let expectedValue = "<strong> 4 < 5 & 3 > 2 .</strong> Price: 12 €. @"
XCTAssertEqual(newValue, expectedValue)
}
}
| mit | 01382d316ada1e93f9169f26daded0a4 | 27.388889 | 104 | 0.617417 | 3.611307 | false | true | false | false |
pablogm/CameraKit | Pod/Classes/Camera/PGMCameraKitHelper.swift | 1 | 7680 | /*
Copyright (c) 2015 Pablo GM <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
import Photos
import Accelerate
public typealias LocalIdentifierType = String
public typealias LocalIdentifierBlock = (localIdentifier: LocalIdentifierType?, error: NSError?) -> ()
public typealias ImageWithIdentifierBlock = (image:UIImage?) -> ()
public typealias VideoWithIdentifierBlock = (video:NSURL?) -> ()
public typealias FrameBuffer = (inBuffer: vImage_Buffer, outBuffer: vImage_Buffer, pixelBuffer: UnsafeMutablePointer<Void>)
@objc public class PGMCameraKitHelper: NSObject {
var manager = PHImageManager.defaultManager()
// MARK: Save Image
public func saveImageAsAsset(image: UIImage, completion: LocalIdentifierBlock) {
var imageIdentifier: LocalIdentifierType?
PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> () in
let changeRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
let placeHolder = changeRequest.placeholderForCreatedAsset
imageIdentifier = placeHolder?.localIdentifier
},
completionHandler: { (success, error) -> () in
if success {
completion(localIdentifier: imageIdentifier, error: nil)
}
else {
completion(localIdentifier: nil, error: error)
}
})
}
// MARK: Save Video
public func saveVideoAsAsset(videoURL: NSURL, completion: LocalIdentifierBlock) {
var videoIdentifier: LocalIdentifierType?
PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> () in
let changeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(videoURL)
let placeHolder = changeRequest?.placeholderForCreatedAsset
videoIdentifier = placeHolder?.localIdentifier
},
completionHandler: { (success, error) -> () in
if success {
completion(localIdentifier: videoIdentifier, error: nil)
}
else {
completion(localIdentifier: nil, error: error)
}
})
}
// MARK: Retrieve Image by Id
public func retrieveImageWithIdentifer(localIdentifier:LocalIdentifierType, completion: ImageWithIdentifierBlock) {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.Image.rawValue)
let fetchResults = PHAsset.fetchAssetsWithLocalIdentifiers([localIdentifier], options: fetchOptions)
if fetchResults.count > 0 {
if let imageAsset = fetchResults.objectAtIndex(0) as? PHAsset {
let requestOptions = PHImageRequestOptions()
requestOptions.deliveryMode = .HighQualityFormat
manager.requestImageForAsset(imageAsset, targetSize: PHImageManagerMaximumSize,
contentMode: .AspectFill, options: requestOptions,
resultHandler: { (image, info) -> () in
completion(image: image)
})
}
else {
completion(image: nil)
}
}
else {
completion(image: nil)
}
}
// MARK: Retrive video by id
public func retrieveVideoWithIdentifier(localIdentifier:LocalIdentifierType, completion: VideoWithIdentifierBlock) {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.Video.rawValue)
let fetchResults = PHAsset.fetchAssetsWithLocalIdentifiers([localIdentifier], options: fetchOptions)
if fetchResults.count > 0 {
if let videoAsset = fetchResults.objectAtIndex(0) as? PHAsset {
/* We want to be able to display a video even if it currently
resides only on the cloud and not on the device */
let options = PHVideoRequestOptions()
options.deliveryMode = .Automatic
options.networkAccessAllowed = true
options.version = .Current
options.progressHandler = {(progress: Double,
error: NSError?,
stop: UnsafeMutablePointer<ObjCBool>,
info: [NSObject : AnyObject]?) in
/* You can write your code here that shows a progress bar to the
user and then using the progress parameter of this block object, you
can update your progress bar. */
}
/* Now get the video */
PHCachingImageManager().requestAVAssetForVideo(videoAsset,
options: options,
resultHandler: {(asset: AVAsset?,
audioMix: AVAudioMix?,
info: [NSObject : AnyObject]?) in
if let asset = asset as? AVURLAsset{
completion(video: asset.URL)
} else {
print("This is not a URL asset. Cannot play")
}
})
}
else {
completion(video: nil)
}
}
else {
completion(video: nil)
}
}
// MARK: Compress Video
public func compressVideo(inputURL: NSURL, outputURL: NSURL, outputFileType:String, handler:(session: AVAssetExportSession?)-> Void)
{
let urlAsset = AVURLAsset(URL: inputURL, options: nil)
let exportSession = AVAssetExportSession(asset: urlAsset, presetName: AVAssetExportPresetMediumQuality)
exportSession?.outputURL = outputURL
exportSession?.outputFileType = outputFileType
exportSession?.shouldOptimizeForNetworkUse = true
exportSession?.exportAsynchronouslyWithCompletionHandler { () -> Void in
handler(session: exportSession)
}
}
}
| mit | 81dbe26cf22b9668d3e13ee25f37cb88 | 38.183673 | 137 | 0.581901 | 6.295082 | false | false | false | false |
apple/swift | test/SILOptimizer/assemblyvision_remark/chacha.swift | 2 | 1950 | // RUN: %target-swiftc_driver -Osize -emit-sil %s -o /dev/null -Xfrontend -verify
// REQUIRES: optimized_stdlib,swift_stdlib_no_asserts
// REQUIRES: swift_in_compiler
// An extraction from the benchmark ChaCha20 that we were not ignoring
// dealloc_stack and other end scope instructions.
enum ChaCha20 { }
extension ChaCha20 {
@inline(never)
public static func encrypt<Key: Collection, Nonce: Collection, Bytes: MutableCollection>(bytes: inout Bytes, key: Key, nonce: Nonce, initialCounter: UInt32 = 0) where Bytes.Element == UInt8, Key.Element == UInt8, Nonce.Element == UInt8 {
print("I am lost...")
}
}
@inline(never)
func checkResult(_ plaintext: [UInt8]) {
precondition(plaintext.first! == 6 && plaintext.last! == 254)
var hash: UInt64 = 0
for byte in plaintext {
// rotate
hash = (hash &<< 8) | (hash &>> (64 - 8))
hash ^= UInt64(byte)
}
precondition(hash == 0xa1bcdb217d8d14e4)
}
@_semantics("optremark.sil-assembly-vision-remark-gen")
public func run_ChaCha(_ N: Int) {
let key = Array(repeating: UInt8(1), count: 32)
let nonce = Array(repeating: UInt8(2), count: 12)
var checkedtext = Array(repeating: UInt8(0), count: 1024)
ChaCha20.encrypt(bytes: &checkedtext, key: key, nonce: nonce)
checkResult(checkedtext)// expected-note @-2 {{of 'checkedtext}}
var plaintext = Array(repeating: UInt8(0), count: 30720)
for _ in 1...N {
ChaCha20.encrypt(bytes: &plaintext, key: key, nonce: nonce)
print(plaintext.first!) // expected-remark @:11 {{heap allocated ref of type '}}
// expected-remark @-1:27 {{release of type '}}
}
} // expected-remark {{release of type '}}
// expected-note @-7 {{of 'plaintext}}
// expected-remark @-2 {{release of type '}}
// expected-note @-16 {{of 'nonce}}
// expected-remark @-4 {{release of type '}}
// expected-note @-19 {{of 'key}}
// expected-remark @-6 {{release of type '}}
| apache-2.0 | 0d2f8095bb0c7586092bfe2cf920362b | 37.235294 | 241 | 0.648718 | 3.558394 | false | false | false | false |
graycampbell/GCCountryPicker | Sources/GCCountryPickerDemo/ViewController.swift | 1 | 1936 | //
// ViewController.swift
// GCCountryPickerDemo
//
// Created by Gray Campbell on 9/28/17.
//
import UIKit
import GCCountryPicker
// MARK: Properties & Initializers
class ViewController: UIViewController {
// MARK: Properties
fileprivate var country: GCCountry!
}
// MARK: - View
extension ViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.configureNavigationBar()
}
}
// MARK: - Navigation Bar
extension ViewController {
fileprivate func configureNavigationBar() {
self.navigationItem.title = GCCountry(countryCode: "US")?.localizedDisplayName
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(self.showCountryPicker(barButtonItem:)))
}
@objc func showCountryPicker(barButtonItem: UIBarButtonItem) {
let countryPickerViewController = GCCountryPickerViewController(displayMode: .withCallingCodes)
countryPickerViewController.delegate = self
countryPickerViewController.navigationItem.title = NSLocalizedString("Countries", comment: "")
let navigationController = UINavigationController(rootViewController: countryPickerViewController)
self.present(navigationController, animated: true, completion: nil)
}
}
// MARK: - GCCountryPickerDelegate
extension ViewController: GCCountryPickerDelegate {
func countryPickerDidCancel(_ countryPicker: GCCountryPickerViewController) {
self.dismiss(animated: true, completion: nil)
}
func countryPicker(_ countryPicker: GCCountryPickerViewController, didSelectCountry country: GCCountry) {
self.country = country
self.navigationItem.title = country.localizedDisplayName
self.dismiss(animated: true, completion: nil)
}
}
| mit | dc4b4a263159f9bebcc39c2b44657e1b | 26.267606 | 165 | 0.696281 | 5.744807 | false | false | false | false |
abertelrud/swift-package-manager | Sources/SPMBuildCore/BuildSystemDelegate.swift | 2 | 2115 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2018-2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
/// BuildSystem delegate
public protocol BuildSystemDelegate: AnyObject {
///Called when build command is about to start.
func buildSystem(_ buildSystem: BuildSystem, willStartCommand command: BuildSystemCommand)
/// Called when build command did start.
func buildSystem(_ buildSystem: BuildSystem, didStartCommand command: BuildSystemCommand)
/// Called when build task did update progress.
func buildSystem(_ buildSystem: BuildSystem, didUpdateTaskProgress text: String)
/// Called when build command did finish.
func buildSystem(_ buildSystem: BuildSystem, didFinishCommand command: BuildSystemCommand)
func buildSystemDidDetectCycleInRules(_ buildSystem: BuildSystem)
/// Called when build did finish.
func buildSystem(_ buildSystem: BuildSystem, didFinishWithResult success: Bool)
/// Called when build did cancel
func buildSystemDidCancel(_ buildSystem: BuildSystem)
}
public extension BuildSystemDelegate {
func buildSystem(_ buildSystem: BuildSystem, willStartCommand command: BuildSystemCommand) { }
func buildSystem(_ buildSystem: BuildSystem, didStartCommand command: BuildSystemCommand) { }
func buildSystem(_ buildSystem: BuildSystem, didUpdateTaskProgress text: String) { }
func buildSystem(_ buildSystem: BuildSystem, didFinishCommand command: BuildSystemCommand) { }
func buildSystemDidDetectCycleInRules(_ buildSystem: BuildSystem) { }
func buildSystem(_ buildSystem: BuildSystem, didFinishWithResult success: Bool) { }
func buildSystemDidCancel(_ buildSystem: BuildSystem) { }
}
| apache-2.0 | 76bc6afaa9718eb8d6217336e009da1d | 44.978261 | 98 | 0.707801 | 5.778689 | false | false | false | false |
mackoj/GOTiPad | GOTIpad/GameLogic/Game.swift | 1 | 5692 | //
// Game.swift
// GOTIpad
//
// Created by jeffreymacko on 29/12/2015.
// Copyright © 2015 jeffreymacko. All rights reserved.
//
import Foundation
class Game {
var turn : UInt
var wildingTrack : UInt
let players : [Player]
var startTime : Date
let lands : [Land]
let westerosCardDeck1 : EventCardDeck
let westerosCardDeck2 : EventCardDeck
let westerosCardDeck3 : EventCardDeck
let wildingsCardDeck : WildingsCardDeck
// utiliser un pointeur ?
var ironThroneTrack : [Player]
var valerianSwordTrack : [Player]
var kingsCourtTrack : [Player]
let bank : Bank
var gamePhase : GamePhase = .globaleGameStateInit
func setGamePhase(actualGamePhase : GamePhase) {
gamePhase = actualGamePhase
self.executeNextGamePhase(gamePhase: actualGamePhase)
}
// var delegate : GameProtocol
init(players inputPlayer : [Player]) {
players = inputPlayer
ironThroneTrack = inputPlayer
valerianSwordTrack = inputPlayer
kingsCourtTrack = inputPlayer
bank = Bank()
turn = 0
startTime = Current.date()
// filling decks
westerosCardDeck1 = EventCardDeck(deckType: .deck1)
westerosCardDeck2 = EventCardDeck(deckType: .deck2)
westerosCardDeck3 = EventCardDeck(deckType: .deck3)
wildingsCardDeck = WildingsCardDeck(cards: [])
// Fill Lands
self.lands = LandFactory.fillLands(seed: Current.seed)
// Position on wildings Track
wildingTrack = 0;
// Suffle Decks
setGamePhase(actualGamePhase: .globaleGameStateInit)
}
func pause() {}
func stop() {}
func restart() {
turn = 0
setGamePhase(actualGamePhase: .globaleGameStateInit)
}
func processNextTurn() {}
// + (instancetype)sharedGOTGame;
// + (void)killInstance;
// + (instancetype)getInstance;
func executeNextGamePhase(gamePhase : GamePhase) {
switch gamePhase {
case .globaleGameStateInit:
// Allows Player to Select Familys
// Set Defaut Pawns
// Set Defaut power token
// Position on influence Track
// Position on supply Track
// Position on victory Track
// Set Game Limit & misc Parameters
setGamePhase(actualGamePhase: .globaleGameStateStartFirstTurn)
case .globaleGameStateStartFirstTurn: break
case .gamePhaseStartWesteros:
break
case .gameStateForWesterosGamePhaseAdvanceGameRoundMarker:
if self.turn == Current.endGameTurn {
setGamePhase(actualGamePhase: .gamePhaseWinningResolution) // fin du jeu
} else {
self.turn += 1
setGamePhase(actualGamePhase: .gameStateForWesterosGamePhaseDrawEventCards)
}
case .gameStateForWesterosGamePhaseDrawEventCards:
break
case .gameStateForWesterosGamePhaseAdvanceWildlingsTrack:
break
case .gameStateForWesterosGamePhaseWildlingsAttack:
break
case .gameStateForWesterosGamePhaseResolveEventCards:
break
case .gamePhaseEndWesteros:
break
case .gamePhaseStartPlanning:
// Dis a l'UI que la phase X commande si elle veut jouer une animation ou quoi
setGamePhase(actualGamePhase: .gameStateForPlanningGamePhaseAssignOrders)
case .gameStateForPlanningGamePhaseAssignOrders:
// demander aux joueurs de positionner leur pions d'action
// player in order + completion ?
for player in self.ironThroneTrack {
self.assignOrders(player: player) // future ???
}
// une fois que tout les joueurs on jouer
if self.allOrdersHasBeenPlayed() {
setGamePhase(actualGamePhase: .gameStateForPlanningGamePhaseRevealOrders)
}
case .gameStateForPlanningGamePhaseRevealOrders:
// player in order + completion ?
for player in self.ironThroneTrack {
for orderToken in player.house.orderTokens {
if orderToken.isOnBoard {
orderToken.isFold
}
}
}
self.revealOrders() // future ???
setGamePhase(actualGamePhase: .gameStateForPlanningGamePhaseUseMessengerRaven)
case .gameStateForPlanningGamePhaseUseMessengerRaven:
self.useMessageRaven(player: self.kingsCourtTrack.first!) // useNonEmptyArray
let ravenAction = RavenMessengerAction.changeOrder
switch ravenAction {
case .nothing: break
case .changeOrder: break
case .lookIntoWildingsDeck: break
}
setGamePhase(actualGamePhase: .gamePhaseEndPlanning)
case .gamePhaseEndPlanning:
self.endPlanningPhase()
setGamePhase(actualGamePhase: .gamePhaseStartAction)
case .gamePhaseStartAction:
break
case .gameStateForActionGamePhaseResolveRaidOrders:
break
case .gameStateForActionGamePhaseResolveMarchOrders:
break
case .gamePhaseStartCombat:
break
case .gamePhaseCombatCallForSupport:
break
case .gamePhaseCombatCalculateInitialCombatStrength:
break
case .gamePhaseCombatChooseandRevealHouseCards:
break
case .gamePhaseCombatUseValyrianSteelBlade:
break
case .gamePhaseCombatCalculateFinalCombatStrength:
break
case .gamePhaseCombatResolution:
break
case .gamePhaseCombatResolutionDetermineVictor:
break
case .gamePhaseCombatResolutionCasualties:
break
case .gamePhaseCombatResolutionRetreatsandRouting:
break
case .gamePhaseCombatResolutionCombatCleanUp:
break
case .gamePhaseEndCombat:
break
case .gameStateForActionGamePhaseResolveConsolidatePowerOrders:
break
case .gameStateForActionGameCleanUp:
break
case .gamePhaseEndAction:
break
case .gamePhaseWinningResolution:
break
case .globaleGameStateFinish:
break
}
}
}
| mit | d6ec528d654d566d054648cdc5408b23 | 27.173267 | 84 | 0.710596 | 4.770327 | false | false | false | false |
AboutObjectsTraining/Swift4Examples | ModelTests/ModelTests.swift | 1 | 2485 | //
// Copyright (C) 2017 About Objects, Inc. All Rights Reserved.
// See LICENSE.txt for this example's licensing information.
//
import XCTest
@testable import Model
let book1 = Book(title: "Book One", year: 1999, favorite: false, rating: Rating(average: 4.75, count: 32))
let book2 = Book(title: "Book Two", year: 2001, favorite: true, rating: Rating(average: 3.5, count: 27))
let author1 = Author(firstName: "Fred", lastName: "Smith", books: [book1, book2])
let ebook1 = Ebook(ebookId: 123456, title: "Ebook One", rating: Rating(average: 2.75, count: 42))
let ebook2: Ebook = {
var ebook = Ebook(ebookId: 56789, title: "Ebook Two", rating: Rating(average: 3.75, count: 11));
ebook.currency = Ebook.Currency.euro
return ebook
}()
let book1Json = """
{
"title": "Title One",
"year": 2017,
"favorite": true,
"rating": { "average": 4.5, "count": 23 }
}
"""
let book2Json = """
{
"title": "Title Two",
"year": 2016,
"favorite": false,
"rating": { "average": 5, "count": 12 }
}
"""
let authorJson = """
{
"firstName": "FNameOne",
"lastName": "LNameOne"
}
"""
let authorAndBooksJson = """
{
"firstName": "FNameTwo",
"lastName": "LNameTwo",
"books": [\(book1Json), \(book2Json)]
}
"""
let iTunesEbookJson = """
{
"fileSizeBytes":5990135,
"artistId":2122513,
"artistName":"Ernest Hemingway",
"genres":["Classics", "Books", "Fiction & Literature", "Literary"],
"kind":"ebook",
"price":9.99,
"currency":"USD",
"description":"One of the enduring works of American fiction.",
"trackName":"The Old Man and the Sea",
"trackId":381645838,
"formattedPrice":"$9.99",
"releaseDate":"2002-07-25T07:00:00Z",
"averageUserRating":4.5,
"userRatingCount":660
}
"""
let iTunesEbookJson2 = """
{
"fileSizeBytes":5990135,
"artistId":2122513,
"artistName":"Ernest Hemingway",
"genres":["Classics", "Books", "Fiction & Literature", "Literary"],
"kind":"ebook",
"price":9.99,
"currency": "GBP",
"description":"One of the enduring works of American fiction.",
"trackName":"The Old Man and the Sea",
"trackId":381645838,
"formattedPrice":"$9.99",
"releaseDate":"2002-07-25T07:00:00Z",
"averageUserRating":4.5,
"userRatingCount":660
}
"""
let personInfoString = """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>name</key>
<string>John Doe</string>
<key>phones</key>
<array>
<string>408-974-0000</string>
<string>503-333-5555</string>
</array>
</dict>
</plist>
"""
| mit | 7a45d389a7d1291e0896beec18b70b79 | 22.894231 | 106 | 0.667606 | 2.869515 | false | false | false | false |
quran/quran-ios | Sources/QuranAudioKit/Timing/ReciterTimingRetriever.swift | 1 | 1803 | //
// SQLiteReciterTimingRetriever.swift
// Quran
//
// Created by Mohamed Afifi on 5/20/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Foundation
import PromiseKit
import QuranKit
protocol ReciterTimingRetriever {
func retrieveTiming(for reciter: Reciter, suras: [Sura]) -> Promise<[Sura: SuraTiming]>
}
struct SQLiteReciterTimingRetriever: ReciterTimingRetriever {
let persistenceFactory: AyahTimingPersistenceFactory
func retrieveTiming(for reciter: Reciter, suras: [Sura]) -> Promise<[Sura: SuraTiming]> {
guard case .gapless(let databaseName) = reciter.audioType else {
fatalError("Gapped reciters are not supported.")
}
return DispatchQueue.global().async(.promise) {
let fileURL = reciter.localFolder().appendingPathComponent(databaseName).appendingPathExtension(Files.databaseLocalFileExtension)
let persistence = self.persistenceFactory.persistenceForURL(fileURL)
var result: [Sura: SuraTiming] = [:]
for sura in suras {
let timings = try persistence.getOrderedTimingForSura(startAyah: sura.firstVerse)
result[sura] = timings
}
return result
}
}
}
| apache-2.0 | 62b73b4217e10a6483b89608fe88974d | 36.5625 | 141 | 0.700499 | 4.59949 | false | false | false | false |
14lox/coinbase-ios-sdk | Example/coinbase/CoinbaseCurrenciesViewController.swift | 1 | 1259 | //
// CoinbaseCurrenciesViewController.swift
// Example of unautheticated API usage and of APIs returning arrays
//
import UIKit
class CoinbaseCurrenciesViewController: UITableViewController, UITableViewDataSource {
var currencies: [[String]]?
override func viewDidAppear(animated: Bool) {
// Load currencies
Coinbase().doGet("currencies", parameters: [:]) {
(response: AnyObject?, error: NSError?) in
if let error = error {
NSLog("Error: \(error)")
} else {
self.currencies = response as? [[String]]
self.tableView.reloadData()
}
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let currencies = self.currencies {
return currencies.count
} else {
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("currency") as? UITableViewCell
let label = cell?.viewWithTag(1) as? UILabel
label?.text = currencies?[indexPath.row][0]
return cell!
}
}
| mit | ea5ea6fcfefaf5055bda6296caf7b399 | 28.97619 | 118 | 0.623511 | 5.334746 | false | false | false | false |
godlift/XWSwiftRefresh | XWSwiftRefresh/Footer/XWRefreshFooter.swift | 1 | 12333 | //
// XWRefreshFooter.swift
// XWRefresh
//
// Created by Xiong Wei on 15/9/11.
// Copyright © 2015年 Xiong Wei. All rights reserved.
//
import UIKit
/** footer状态 */
enum XWRefreshFooterState:Int{
/**普通闲置状态 */
case Idle = 1
/**正在刷新中的状态 */
case Refreshing = 2
/**没有数据需要加载 */
case NoMoreData = 3
}
class XWRefreshFooter: XWRefreshComponent {
typealias colsureType = ()->()
//MARK: 公有的 提供外界访问的
/** 提示没有更多数据 */
func noticeNoMoreData(){ self.state = .NoMoreData }
/** 进入刷新状态 */
override func beginRefreshing(){ self.state = .Refreshing }
/** 结束刷新状态 */
override func endRefreshing(){ self.state = .Idle}
/** 是否正在刷新 */
override func isRefreshing(){ self.state = .Refreshing }
/** 从新刷新控件的状态交给子类重写 默认闲置状态 */
var state:XWRefreshFooterState = .Idle {
//观察状态的改变 来进行相应的操作
willSet{
if state == newValue {return}
switch newValue {
case .Idle:
self.noMoreLabel.hidden = true
self.stateLabel.hidden = true
self.loadMoreButton.hidden = false
case .Refreshing:
self.loadMoreButton.hidden = true
self.noMoreLabel.hidden = true
if !self.stateHidden { self.stateLabel.hidden = false}
//回调
self.refreshingBlock()
case .NoMoreData:
self.loadMoreButton.hidden = true;
self.noMoreLabel.hidden = false;
self.stateLabel.hidden = true;
}
}
}
/** 是否隐藏状态标签 */
var stateHidden:Bool = false {
didSet{
self.stateLabel.hidden = stateHidden
//重写布局子控件
self.setNeedsLayout()
}
}
/** 监听父类的属性 font */
override var font:UIFont?{
didSet{
self.loadMoreButton.titleLabel!.font = font;
self.noMoreLabel.font = font;
self.stateLabel.font = font;
}
}
/** 监听父类的属性 textColor */
override var textColor:UIColor?{
didSet{
self.stateLabel.textColor = textColor;
self.loadMoreButton.setTitleColor(textColor, forState: UIControlState.Normal)
self.noMoreLabel.textColor = textColor;
}
}
/** 设置footer状态下的文字*/
func setTitle(title:String?, state:XWRefreshFooterState){
if let realTitle = title {
switch state {
case .Idle:
self.loadMoreButton.setTitle(realTitle, forState: UIControlState.Normal)
self.loadMoreButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
break
case .Refreshing:
self.stateLabel.text = realTitle
break
case .NoMoreData:
self.noMoreLabel.text = realTitle
}
}
}
/** 是否自动刷新,默认 true */
var automaticallyRefresh:Bool = true
/** 当底部控件出现多少时就自动刷新(默认为0.5,也就是底部控件完全出现一半的时候时,才会自动刷新) */
var appearencePercentTriggerAutoRefresh:CGFloat = 0.5
//MARK: 私有
/** 显示转态的 lable 文字 */
private lazy var stateLabel:UILabel = {
[unowned self] in
let stateLable = UILabel()
stateLable.backgroundColor = UIColor.clearColor()
stateLable.textAlignment = NSTextAlignment.Center
self.addSubview(stateLable)
return stateLable
}()
/** 显示没有更多 lable 文字 */
private lazy var noMoreLabel:UILabel = {
[unowned self] in
let noMoreLabel = UILabel()
noMoreLabel.backgroundColor = UIColor.clearColor()
noMoreLabel.textAlignment = NSTextAlignment.Center
self.addSubview(noMoreLabel)
return noMoreLabel
}()
/** 点击可以加载更多 按钮 */
private lazy var loadMoreButton:UIButton = {
[unowned self] in
let loadMoreButton = UIButton()
loadMoreButton.backgroundColor = UIColor.clearColor()
loadMoreButton.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(loadMoreButton)
return loadMoreButton
}()
/** 点击可以加载更多 执行的方法 */
func buttonClick(){
if self.state != XWRefreshFooterState.Refreshing {
self.state = .Refreshing
}
}
/** 即将执行的代码块 */
private var willExeColsuresM:Array<colsureType> = []
//MARK: 重写父类方法
override init(frame: CGRect) {
super.init(frame: frame)
//初始化文字
self.setTitle(XWRefreshFooterStateIdleText, state: .Idle)
self.setTitle(XWRefreshFooterStateRefreshingText, state: .Refreshing)
self.setTitle(XWRefreshFooterStateNoMoreDataText, state: .NoMoreData)
//初始状态
self.noMoreLabel.hidden = true
self.stateLabel.hidden = true
self.loadMoreButton.hidden = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
//移除旧的监听
self.superview?.removeObserver(self, forKeyPath: XWRefreshContentSize, context: nil )
self.superview?.removeObserver(self, forKeyPath: XWRefreshPanState, context: nil )
if let realSuperView = newSuperview {
//1.如果存在 就添加到父控件中去
//1.1 添加监听
realSuperView.addObserver(self, forKeyPath: XWRefreshContentSize, options: NSKeyValueObservingOptions.New, context: nil)
realSuperView.addObserver(self, forKeyPath: XWRefreshPanState, options: NSKeyValueObservingOptions.New, context: nil)
//1.2.添加到父控件
self.xw_height = XWRefreshFooterHeight
self.scrollView.contentInset.bottom += self.xw_height
// realSuperView.addSubview(self)
//1.3从新调整frame
self.adjustFrameWithContentSize()
}
}
//根据能滚动的距离调整
private func adjustFrameWithContentSize(){
self.xw_y = self.scrollView.contentSize.height
}
//重写layoutSubview
override func layoutSubviews() {
super.layoutSubviews()
//给要显示的控件设置frame
self.noMoreLabel.frame = self.bounds
self.stateLabel.frame = self.bounds
self.loadMoreButton.frame = self.bounds
}
//监听属性的改变
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//1.遇到不能交互的直接返回
if !self.userInteractionEnabled || self.alpha <= 0.01 || self.hidden || self.state == .NoMoreData { return }
//contenInset.top 是一开始的内部的 内边距 有导航条的情况下是 64
// contentOffset .以 内容也就是 以 真正的content 到 frame 来计算偏移
// contentOffset.y = content.y 也就是内容的 y 值 contentOffset.x 也就是 内容的 x 值
/*
frame 相当于 墙上的一个窗户
content 决定 窗户里面的人物
*/
//2. 根据contentOffset 来调整state状态
switch keyPath {
//2.1 如果是监听到 手式
case XWRefreshPanState :
//2.1.1 抬起
if self.scrollView.panGestureRecognizer.state == UIGestureRecognizerState.Ended {
// 向上拖拽
func draggingUp(){
//如果是向 上拖拽 刷新
if self.scrollView.contentOffset.y > -self.scrollView.contentInset.top {
beginRefreshing()
}
}
//2.2.1.1 不够一个屏幕的滚动 top + content.height 就是内容显示的高度
if self.scrollView.contentInset.top +
self.scrollView.contentSize.height < self.scrollView.xw_height {
draggingUp()
//2.1.1.2 超出一个屏幕 也就是scrollView的
}else {
//拖拽到了底部
if self.scrollView.contentSize.height - self.scrollView.contentOffset.y + self.scrollView.contentInset.top + self.scrollView.contentInset.bottom == self.scrollView.xw_height {
// beginRefreshing()
draggingUp()
}
}
}
case XWRefreshContentOffset:
//如果不是正在刷新的状态,且 是自动刷新
if self.state != XWRefreshFooterState.Refreshing && self.automaticallyRefresh{
//调整State
self.adjustStateWithContentOffset()
}
case XWRefreshContentSize:
self.adjustFrameWithContentSize()
default: break
}
}
//根据 contentOffset 调整 状态
private func adjustStateWithContentOffset(){
if self.xw_y == 0 {return}
//超过屏幕
if self.scrollView.contentInset.top +
self.scrollView.contentSize.height > self.scrollView.xw_height {
//拖拽到了底部, appearencePercentTriggerAutoRefresh 底部显示多少的 百分比,默认是不用显示
//TODO: 计算公式,判断是不是在拖在到了底部
//去掉 + self.scrollView.contentInset.top
if self.scrollView.contentSize.height - self.scrollView.contentOffset.y + self.scrollView.contentInset.bottom + self.xw_height * self.appearencePercentTriggerAutoRefresh - self.xw_height <= self.scrollView.xw_height {
//当底部控件完全出现才刷新
self.beginRefreshing()
}
}
}
// var colsure:NSMutableArray<()->()>!
//MARK: 给父类 hidden 添加观察者属性 这里设计到一些知识
override var hidden:Bool{
//拦截
willSet{
// 最后一次设置的 hidden
let lastHidden = self.hidden
//将常量 写在闭包的外面
let h = self.xw_height
self.willExeColsuresM.append({
[unowned self] in
//之前的是不隐藏,现在是隐藏,所以要减去之前的 高度
if !lastHidden && newValue {
self.state = XWRefreshFooterState.Idle
self.scrollView.contentInset.bottom -= h
}else if lastHidden && !newValue {
self.scrollView.contentInset.bottom += h
self.adjustFrameWithContentSize()
}
})
// 放到drawRect是为了延迟执行,防止因为修改了inset,导致循环调用数据源方法
self.setNeedsDisplay()
}
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
//执行闭包
for calsure in self.willExeColsuresM {
calsure()
}
//移除闭包
self.willExeColsuresM.removeAll()
}
}
| mit | 4309762c1085a9d98c48fe425ef86ac9 | 29.541436 | 233 | 0.546581 | 5.025455 | false | false | false | false |
SomaticLabs/SwiftMomentSDK | SwiftyZorb/Internal/PacketQueue.swift | 1 | 1841 | //
// PacketQueue.swift
// SwiftyZorb
//
// Created by Jacob Rockland on 12/22/17.
// Copyright © 2017 Somatic Technologies, Inc. All rights reserved.
//
import Foundation
// MARK: - Packet Queue
/**
A simple FIFO (first in, first out) queue for managing data to be written to the Javascript BLE characteristic (thread safe)
*/
final internal class PacketQueue {
// MARK: - Private Properties
/// Internal array for managing queue
private var array = [ArraySlice<UInt8>]()
/// Internal access queue for managing packet queue
private let accessQueue = DispatchQueue(label: "SynchronizedArrayAccess", attributes: .concurrent)
// MARK: - Accessible Properties
/// Variable for counting the number of packet sets queued
var numSets = 0
/// Variable for getting count in queue
var count: Int {
var count = 0
accessQueue.sync {
count = self.array.count
}
return count
}
/// Variable for checking if the queue is empty
var isEmpty: Bool {
var isEmpty = true
accessQueue.sync {
isEmpty = self.array.isEmpty
}
return isEmpty
}
// MARK: - Queue Methods
/// Method for adding item to the queue
func enqueue(_ element: ArraySlice<UInt8>) {
accessQueue.async(flags:.barrier) {
self.array.append(element)
}
}
/// Method for removing item from the queue
func dequeue() -> ArraySlice<UInt8>? {
var element: ArraySlice<UInt8>? = nil
accessQueue.sync {
element = self.array.first
}
accessQueue.async(flags:.barrier) {
self.array.removeFirst()
}
return element
}
}
| mit | 308015475cc07dc486d903159d4d59ad | 23.210526 | 125 | 0.583152 | 4.829396 | false | false | false | false |
Chantalisima/Spirometry-app | EspiroGame/TestViewController.swift | 1 | 7483 | //
// TestViewController.swift
// BLEgame2
//
// Created by Chantal de Leste on 23/3/17.
// Copyright © 2017 Universidad de Sevilla. All rights reserved.
//
import Foundation
import UIKit
import CoreBluetooth
class TestViewController: UIViewController, CBPeripheralDelegate {
private var count: Int = 0
private var valorPrevio: Int = 0
private var test: Int = 0
private var rpm: Int = 0
var arrayRPM: [[Int]] = []
var mainperipheral: CBPeripheral?
var mainView: MainViewController?
var dataArray: [Int] = []
@IBOutlet weak var backToMainButton: UIButton!
@IBOutlet weak var readLabel: UILabel!
@IBOutlet weak var counterView: CounterView!
private var isFirst: Bool = true
private var isSecond: Bool = false
private var isThird: Bool = false
var text = ["Test(1 of 3): Breath normally 2 or 3 times, take a deep breath and exhale as hard and fast as you can through the mouth piece.","Test(2 of 3): Breath normally 2 or 3 times, take a deep breath and exhale as hard and fast as you can through the mouth piece.", "Test(3 of 3): Breath normally 2 or 3 times, take a deep breath and exhale as hard and fast as you can through the mouth piece.","Test is over"]
@IBAction func prepareForUnwind(segue: UIStoryboardSegue){
}
override func viewDidLoad() {
super.viewDidLoad()
readLabel.text = text[0]
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "result-segue"{
let resultadosVC: ResultViewController = segue.destination as! ResultViewController
resultadosVC.arrayRPM1 = arrayRPM[0]
resultadosVC.arrayRPM2 = arrayRPM[1]
resultadosVC.arrayRPM3 = arrayRPM[2]
mainperipheral = nil
}
}
let BLEDeviceUUID = "19F407A3-48DC-46F9-8924-F208579AE025"
let BLEServiceUUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
let TxCharacteristicUUID = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
let RxCharacteristicUUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
var ServicesList = [CBService]()
var uartService: CBService?
var rxCharacteristic: CBCharacteristic?
var txCharacteristic: CBCharacteristic?
//MARK : CBPeripheral Methods
// GET SERVICES and GET CHARACTERISTICS
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
mainperipheral = peripheral
for service in peripheral.services! {
let thisService = service as CBService
print("service found with UUID:" + service.uuid.uuidString)
if thisService.uuid.uuidString == BLEServiceUUID {
print("servicio requerido encontrado")
peripheral.discoverCharacteristics(nil, for: thisService)
}
}
}
// SETUP NOTIFICATIONS
//Existen diferentes maneras de enfocar la obtención de datos desde el dispositivo BLE. Vamos a leer los cambios de forma incremental.
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let e = error{
print("error didupdatevalue \(e)")
return
}
if service.uuid.uuidString == BLEServiceUUID {
for characteristic in service.characteristics! {
let thisCharacteristic = characteristic as CBCharacteristic
if thisCharacteristic.uuid.uuidString .caseInsensitiveCompare(RxCharacteristicUUID) == .orderedSame {
rxCharacteristic = thisCharacteristic
print(thisCharacteristic.isNotifying)
mainperipheral?.setNotifyValue(true, for: thisCharacteristic)
mainperipheral?.readValue(for: thisCharacteristic)
print("Rx char found: \(thisCharacteristic.uuid.uuidString)")
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
print("didUpdateNotificationStateForCharacteristic")
if error != nil {
print("Encountered error: \(error?.localizedDescription)")
}
if characteristic.uuid != rxCharacteristic?.uuid{
return
}
if characteristic.isNotifying {
print("notification started for:\(characteristic)")
} else {
print("notification stoped for:\(characteristic)")
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
print("didUpdateValueForCharacteristic")
if let dataBytes = characteristic.value {
convertDataToInt(data: dataBytes)
}
}
func convertDataToInt(data: Data?) {
if let da = data {
if let str: String = NSString(data: da, encoding: String.Encoding.utf8.rawValue) as String? {
if let pul = Int(str){
if valorPrevio < 151 && pul > 150 {
dataArray.append(pul)
print("encontrado un valor distinto de 0")
print("\(pul)")
counterView.counter += 0.5
}
else if pul > 150 && valorPrevio > 150 {
print("en medio")
dataArray.append(pul)
counterView.counter += 0.5
}
else if valorPrevio < 151 && pul < 151 {
print("final del sopliooo")
if dataArray.count < 6{
dataArray.removeAll()
counterView.counter = 0
}
else{
count += 1
print(count)
arrayRPM.append(dataArray)
readLabel.text = text[count]
dataArray.removeAll()
counterView.counter = 0
if arrayRPM.count == 3 {
performSegue(withIdentifier: "result-segue", sender: nil)
}
}
valorPrevio = pul
}
}
}
}
}
}
| apache-2.0 | 2dabeef35b2410eb0298b6b9ec95260e | 28.337255 | 419 | 0.503676 | 5.862853 | false | false | false | false |
wikimedia/wikipedia-ios | WMF Framework/URLComponents+Extensions.swift | 1 | 3239 | import Foundation
extension URLComponents {
static func with(host: String, scheme: String = "https", path: String = "/", queryParameters: [String: Any]? = nil) -> URLComponents {
var components = URLComponents()
components.host = host
components.scheme = scheme
components.path = path
components.replacePercentEncodedQueryWithQueryParameters(queryParameters)
return components
}
public static func percentEncodedQueryStringFrom(_ queryParameters: [String: Any]) -> String {
var query = ""
// sort query parameters by key, this allows for consistency when itemKeys are generated for the persistent cache.
struct KeyValue {
let key: String
let value: Any
}
var unorderedKeyValues: [KeyValue] = []
for (name, value) in queryParameters {
unorderedKeyValues.append(KeyValue(key: name, value: value))
}
let orderedKeyValues = unorderedKeyValues.sorted { (lhs, rhs) -> Bool in
return lhs.key < rhs.key
}
for keyValue in orderedKeyValues {
guard
let encodedName = keyValue.key.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryComponentAllowed),
let encodedValue = String(describing: keyValue.value).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryComponentAllowed) else {
continue
}
if query != "" {
query.append("&")
}
query.append("\(encodedName)=\(encodedValue)")
}
return query
}
mutating func appendQueryParametersToPercentEncodedQuery(_ queryParameters: [String: Any]?) {
guard let queryParameters = queryParameters else {
return
}
var newPEQ = ""
if let existing = percentEncodedQuery {
newPEQ = existing + "&"
}
newPEQ = newPEQ + URLComponents.percentEncodedQueryStringFrom(queryParameters)
percentEncodedQuery = newPEQ
}
mutating func replacePercentEncodedQueryWithQueryParameters(_ queryParameters: [String: Any]?) {
guard let queryParameters = queryParameters else {
percentEncodedQuery = nil
return
}
percentEncodedQuery = URLComponents.percentEncodedQueryStringFrom(queryParameters)
}
mutating func replacePercentEncodedPathWithPathComponents(_ pathComponents: [String]?) {
guard let pathComponents = pathComponents else {
percentEncodedPath = "/"
return
}
let fullComponents = [""] + pathComponents
#if DEBUG
for component in fullComponents {
assert(!component.contains("/"))
}
#endif
percentEncodedPath = fullComponents.joined(separator: "/") // NSString.path(with: components) removes the trailing slash that the reading list API needs
}
public func wmf_URLWithLanguageVariantCode(_ code: String?) -> URL? {
return (self as NSURLComponents).wmf_URL(withLanguageVariantCode: code)
}
}
| mit | 641f8a00ab09e2a733bab34103336a3a | 36.229885 | 160 | 0.615931 | 5.943119 | false | false | false | false |
chinaljw/PhotoBrowser | PhotoBrowser/PhotoBrowser/Controller/PhotoBrowser+HUD.swift | 12 | 1204 | //
// PhotoBrowser+HUD.swift
// PhotoBrowser
//
// Created by 冯成林 on 15/8/11.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
extension PhotoBrowser{
/** 展示 */
func showHUD(text: String,autoDismiss: Double){
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.hud.alpha = 1
})
hud.text = text
self.view.addSubview(hud)
let margin = self.view.bounds.size.width * 0.3
hud.make_center(CGPointZero, width: 120, height: 44)
if autoDismiss == -1 {return}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(autoDismiss * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {[unowned self] () -> Void in
self.dismissHUD()
})
}
/** 消失 */
func dismissHUD(){
UIView.animateWithDuration(0.25, animations: {[unowned self] () -> Void in
self.hud.alpha = 0
}) { (compelte) -> Void in
self.hud.text = ""
self.hud.removeFromSuperview()
}
}
}
| mit | 9d9b860819028d1b9df1e1b761637761 | 21.730769 | 155 | 0.506768 | 4.191489 | false | false | false | false |
gaowanli/PinGo | PinGo/PinGo/Discover/DiscoverHomeController.swift | 1 | 934 | //
// DiscoverHomeController.swift
// PinGo
//
// Created by GaoWanli on 16/1/31.
// Copyright © 2016年 GWL. All rights reserved.
//
import UIKit
class DiscoverHomeController: UIViewController {
@IBOutlet fileprivate weak var discoverContainerView: UIView!
@IBOutlet fileprivate weak var topicContainerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.titleView = topMenu
}
// MARK: lazy loading
fileprivate lazy var topMenu: TopMenu = {
let t = TopMenu.loadFromNib()
t.showText = ("话题", "广场")
t.delegate = self
return t
}()
}
extension DiscoverHomeController: TopMenuDelegate {
func topMenu(_ topMenu: TopMenu, didClickButton index: Int) {
self.discoverContainerView.isHidden = (index == 1)
self.topicContainerView.isHidden = !discoverContainerView.isHidden
}
}
| mit | 7a877af92828bec25939d3bbfcce4365 | 23.945946 | 74 | 0.659805 | 4.52451 | false | false | false | false |
alexzatsepin/omim | iphone/Maps/Classes/Components/Modal/RemoveAds/RemoveAdsPresentationController.swift | 9 | 829 | final class RemoveAdsPresentationController: DimmedModalPresentationController {
override func presentationTransitionWillBegin() {
super.presentationTransitionWillBegin()
guard let containerView = containerView, let presentedView = presentedView else { return }
presentedView.frame = containerView.bounds
presentedView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
containerView.addSubview(presentedView)
presentedViewController.modalPresentationCapturesStatusBarAppearance = true
presentedViewController.setNeedsStatusBarAppearanceUpdate()
}
override func dismissalTransitionDidEnd(_ completed: Bool) {
super.presentationTransitionDidEnd(completed)
guard let presentedView = presentedView else { return }
if completed {
presentedView.removeFromSuperview()
}
}
}
| apache-2.0 | afaeea4e00650074738eb8edfcd0ac61 | 42.631579 | 94 | 0.797346 | 6.85124 | false | false | false | false |
mshhmzh/firefox-ios | Client/Frontend/Browser/BrowserViewController.swift | 1 | 148215 | /* 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 Photos
import UIKit
import WebKit
import Shared
import Storage
import SnapKit
import XCGLogger
import Alamofire
import Account
import ReadingList
import MobileCoreServices
import WebImage
private let log = Logger.browserLogger
private let KVOLoading = "loading"
private let KVOEstimatedProgress = "estimatedProgress"
private let KVOURL = "URL"
private let KVOCanGoBack = "canGoBack"
private let KVOCanGoForward = "canGoForward"
private let KVOContentSize = "contentSize"
private let ActionSheetTitleMaxLength = 120
private struct BrowserViewControllerUX {
private static let BackgroundColor = UIConstants.AppBackgroundColor
private static let ShowHeaderTapAreaHeight: CGFloat = 32
private static let BookmarkStarAnimationDuration: Double = 0.5
private static let BookmarkStarAnimationOffset: CGFloat = 80
}
class BrowserViewController: UIViewController {
var homePanelController: HomePanelViewController?
var webViewContainer: UIView!
var menuViewController: MenuViewController?
var urlBar: URLBarView!
var readerModeBar: ReaderModeBarView?
var readerModeCache: ReaderModeCache
private var statusBarOverlay: UIView!
private(set) var toolbar: TabToolbar?
private var searchController: SearchViewController?
private var screenshotHelper: ScreenshotHelper!
private var homePanelIsInline = false
private var searchLoader: SearchLoader!
private let snackBars = UIView()
private let webViewContainerToolbar = UIView()
private var findInPageBar: FindInPageBar?
private let findInPageContainer = UIView()
lazy private var customSearchEngineButton: UIButton = {
let searchButton = UIButton()
searchButton.setImage(UIImage(named: "AddSearch")?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal)
searchButton.addTarget(self, action: #selector(BrowserViewController.addCustomSearchEngineForFocusedElement), forControlEvents: .TouchUpInside)
return searchButton
}()
private var customSearchBarButton: UIBarButtonItem?
// popover rotation handling
private var displayedPopoverController: UIViewController?
private var updateDisplayedPopoverProperties: (() -> ())?
private var openInHelper: OpenInHelper?
// location label actions
private var pasteGoAction: AccessibleAction!
private var pasteAction: AccessibleAction!
private var copyAddressAction: AccessibleAction!
private weak var tabTrayController: TabTrayController!
private let profile: Profile
let tabManager: TabManager
// These views wrap the urlbar and toolbar to provide background effects on them
var header: BlurWrapper!
var headerBackdrop: UIView!
var footer: UIView!
var footerBackdrop: UIView!
private var footerBackground: BlurWrapper?
private var topTouchArea: UIButton!
let urlBarTopTabsContainer = UIView(frame: CGRect.zero)
// Backdrop used for displaying greyed background for private tabs
var webViewContainerBackdrop: UIView!
private var scrollController = TabScrollingController()
private var keyboardState: KeyboardState?
let WhiteListedUrls = ["\\/\\/itunes\\.apple\\.com\\/"]
// Tracking navigation items to record history types.
// TODO: weak references?
var ignoredNavigation = Set<WKNavigation>()
var typedNavigation = [WKNavigation: VisitType]()
var navigationToolbar: TabToolbarProtocol {
return toolbar ?? urlBar
}
var topTabsViewController: TopTabsViewController?
let topTabsContainer = UIView(frame: CGRect.zero)
init(profile: Profile, tabManager: TabManager) {
self.profile = profile
self.tabManager = tabManager
self.readerModeCache = DiskReaderModeCache.sharedInstance
super.init(nibName: nil, bundle: nil)
didInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return UIInterfaceOrientationMask.AllButUpsideDown
} else {
return UIInterfaceOrientationMask.All
}
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
displayedPopoverController?.dismissViewControllerAnimated(true, completion: nil)
guard let displayedPopoverController = self.displayedPopoverController else {
return
}
coordinator.animateAlongsideTransition(nil) { context in
self.updateDisplayedPopoverProperties?()
self.presentViewController(displayedPopoverController, animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
log.debug("BVC received memory warning")
}
private func didInit() {
screenshotHelper = ScreenshotHelper(controller: self)
tabManager.addDelegate(self)
tabManager.addNavigationDelegate(self)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
func shouldShowFooterForTraitCollection(previousTraitCollection: UITraitCollection) -> Bool {
return previousTraitCollection.verticalSizeClass != .Compact &&
previousTraitCollection.horizontalSizeClass != .Regular
}
func shouldShowTopTabsForTraitCollection(newTraitCollection: UITraitCollection) -> Bool {
guard AppConstants.MOZ_TOP_TABS else {
return false
}
return newTraitCollection.verticalSizeClass == .Regular &&
newTraitCollection.horizontalSizeClass == .Regular
}
func toggleSnackBarVisibility(show show: Bool) {
if show {
UIView.animateWithDuration(0.1, animations: { self.snackBars.hidden = false })
} else {
snackBars.hidden = true
}
}
private func updateToolbarStateForTraitCollection(newCollection: UITraitCollection) {
let showToolbar = shouldShowFooterForTraitCollection(newCollection)
let showTopTabs = shouldShowTopTabsForTraitCollection(newCollection)
urlBar.topTabsIsShowing = showTopTabs
urlBar.setShowToolbar(!showToolbar)
toolbar?.removeFromSuperview()
toolbar?.tabToolbarDelegate = nil
footerBackground?.removeFromSuperview()
footerBackground = nil
toolbar = nil
if showToolbar {
toolbar = TabToolbar()
toolbar?.tabToolbarDelegate = self
footerBackground = BlurWrapper(view: toolbar!)
footerBackground?.translatesAutoresizingMaskIntoConstraints = false
// Need to reset the proper blur style
if let selectedTab = tabManager.selectedTab where selectedTab.isPrivate {
footerBackground!.blurStyle = .Dark
toolbar?.applyTheme(Theme.PrivateMode)
}
footer.addSubview(footerBackground!)
}
if showTopTabs {
if topTabsViewController == nil {
let topTabsViewController = TopTabsViewController(tabManager: tabManager)
topTabsViewController.delegate = self
addChildViewController(topTabsViewController)
topTabsViewController.view.frame = topTabsContainer.frame
topTabsContainer.addSubview(topTabsViewController.view)
topTabsViewController.view.snp_makeConstraints { make in
make.edges.equalTo(topTabsContainer)
make.height.equalTo(TopTabsUX.TopTabsViewHeight)
}
self.topTabsViewController = topTabsViewController
tabManager.addNavigationDelegate(topTabsViewController)
}
topTabsContainer.snp_updateConstraints { make in
make.height.equalTo(TopTabsUX.TopTabsViewHeight)
}
header.disableBlur = true
}
else {
topTabsContainer.snp_updateConstraints { make in
make.height.equalTo(0)
}
topTabsViewController?.view.removeFromSuperview()
topTabsViewController?.removeFromParentViewController()
topTabsViewController = nil
header.disableBlur = false
}
view.setNeedsUpdateConstraints()
if let home = homePanelController {
home.view.setNeedsUpdateConstraints()
}
if let tab = tabManager.selectedTab,
webView = tab.webView {
updateURLBarDisplayURL(tab)
navigationToolbar.updateBackStatus(webView.canGoBack)
navigationToolbar.updateForwardStatus(webView.canGoForward)
navigationToolbar.updateReloadStatus(tab.loading ?? false)
}
}
override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
// During split screen launching on iPad, this callback gets fired before viewDidLoad gets a chance to
// set things up. Make sure to only update the toolbar state if the view is ready for it.
if isViewLoaded() {
updateToolbarStateForTraitCollection(newCollection)
}
displayedPopoverController?.dismissViewControllerAnimated(true, completion: nil)
// WKWebView looks like it has a bug where it doesn't invalidate it's visible area when the user
// performs a device rotation. Since scrolling calls
// _updateVisibleContentRects (https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/API/Cocoa/WKWebView.mm#L1430)
// this method nudges the web view's scroll view by a single pixel to force it to invalidate.
if let scrollView = self.tabManager.selectedTab?.webView?.scrollView {
let contentOffset = scrollView.contentOffset
coordinator.animateAlongsideTransition({ context in
scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y + 1), animated: true)
self.scrollController.showToolbars(animated: false)
}, completion: { context in
scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y), animated: false)
})
}
}
func SELappDidEnterBackgroundNotification() {
displayedPopoverController?.dismissViewControllerAnimated(false, completion: nil)
}
func SELtappedTopArea() {
scrollController.showToolbars(animated: true)
}
func SELappWillResignActiveNotification() {
// If we are displying a private tab, hide any elements in the tab that we wouldn't want shown
// when the app is in the home switcher
guard let privateTab = tabManager.selectedTab where privateTab.isPrivate else {
return
}
webViewContainerBackdrop.alpha = 1
webViewContainer.alpha = 0
urlBar.locationView.alpha = 0
presentedViewController?.popoverPresentationController?.containerView?.alpha = 0
presentedViewController?.view.alpha = 0
}
func SELappDidBecomeActiveNotification() {
// Re-show any components that might have been hidden because they were being displayed
// as part of a private mode tab
UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.webViewContainer.alpha = 1
self.urlBar.locationView.alpha = 1
self.presentedViewController?.popoverPresentationController?.containerView?.alpha = 1
self.presentedViewController?.view.alpha = 1
self.view.backgroundColor = UIColor.clearColor()
}, completion: { _ in
self.webViewContainerBackdrop.alpha = 0
})
// Re-show toolbar which might have been hidden during scrolling (prior to app moving into the background)
scrollController.showToolbars(animated: false)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: BookmarkStatusChangedNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
override func viewDidLoad() {
log.debug("BVC viewDidLoad…")
super.viewDidLoad()
log.debug("BVC super viewDidLoad called.")
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BrowserViewController.SELBookmarkStatusDidChange(_:)), name: BookmarkStatusChangedNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BrowserViewController.SELappWillResignActiveNotification), name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BrowserViewController.SELappDidBecomeActiveNotification), name: UIApplicationDidBecomeActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BrowserViewController.SELappDidEnterBackgroundNotification), name: UIApplicationDidEnterBackgroundNotification, object: nil)
KeyboardHelper.defaultHelper.addDelegate(self)
log.debug("BVC adding footer and header…")
footerBackdrop = UIView()
footerBackdrop.backgroundColor = UIColor.whiteColor()
view.addSubview(footerBackdrop)
headerBackdrop = UIView()
headerBackdrop.backgroundColor = UIColor.whiteColor()
view.addSubview(headerBackdrop)
log.debug("BVC setting up webViewContainer…")
webViewContainerBackdrop = UIView()
webViewContainerBackdrop.backgroundColor = UIColor.grayColor()
webViewContainerBackdrop.alpha = 0
view.addSubview(webViewContainerBackdrop)
webViewContainer = UIView()
webViewContainer.addSubview(webViewContainerToolbar)
view.addSubview(webViewContainer)
log.debug("BVC setting up status bar…")
// Temporary work around for covering the non-clipped web view content
statusBarOverlay = UIView()
statusBarOverlay.backgroundColor = BrowserViewControllerUX.BackgroundColor
view.addSubview(statusBarOverlay)
log.debug("BVC setting up top touch area…")
topTouchArea = UIButton()
topTouchArea.isAccessibilityElement = false
topTouchArea.addTarget(self, action: #selector(BrowserViewController.SELtappedTopArea), forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(topTouchArea)
log.debug("BVC setting up URL bar…")
// Setup the URL bar, wrapped in a view to get transparency effect
urlBar = URLBarView()
urlBar.translatesAutoresizingMaskIntoConstraints = false
urlBar.delegate = self
urlBar.tabToolbarDelegate = self
header = BlurWrapper(view: urlBarTopTabsContainer)
urlBarTopTabsContainer.addSubview(urlBar)
urlBarTopTabsContainer.addSubview(topTabsContainer)
view.addSubview(header)
// UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC
pasteGoAction = AccessibleAction(name: NSLocalizedString("Paste & Go", comment: "Paste the URL into the location bar and visit"), handler: { () -> Bool in
if let pasteboardContents = UIPasteboard.generalPasteboard().string {
self.urlBar(self.urlBar, didSubmitText: pasteboardContents)
return true
}
return false
})
pasteAction = AccessibleAction(name: NSLocalizedString("Paste", comment: "Paste the URL into the location bar"), handler: { () -> Bool in
if let pasteboardContents = UIPasteboard.generalPasteboard().string {
// Enter overlay mode and fire the text entered callback to make the search controller appear.
self.urlBar.enterOverlayMode(pasteboardContents, pasted: true)
self.urlBar(self.urlBar, didEnterText: pasteboardContents)
return true
}
return false
})
copyAddressAction = AccessibleAction(name: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), handler: { () -> Bool in
if let url = self.urlBar.currentURL {
UIPasteboard.generalPasteboard().URL = url
}
return true
})
log.debug("BVC setting up search loader…")
searchLoader = SearchLoader(profile: profile, urlBar: urlBar)
footer = UIView()
self.view.addSubview(footer)
self.view.addSubview(snackBars)
snackBars.backgroundColor = UIColor.clearColor()
self.view.addSubview(findInPageContainer)
scrollController.urlBar = urlBar
scrollController.header = header
scrollController.footer = footer
scrollController.snackBars = snackBars
log.debug("BVC updating toolbar state…")
self.updateToolbarStateForTraitCollection(self.traitCollection)
log.debug("BVC setting up constraints…")
setupConstraints()
log.debug("BVC done.")
}
private func setupConstraints() {
topTabsContainer.snp_makeConstraints { make in
make.leading.trailing.equalTo(self.header)
make.top.equalTo(urlBarTopTabsContainer)
}
urlBar.snp_makeConstraints { make in
make.leading.trailing.bottom.equalTo(urlBarTopTabsContainer)
make.height.equalTo(UIConstants.ToolbarHeight)
make.top.equalTo(topTabsContainer.snp_bottom)
}
header.snp_makeConstraints { make in
scrollController.headerTopConstraint = make.top.equalTo(snp_topLayoutGuideBottom).constraint
make.left.right.equalTo(self.view)
}
headerBackdrop.snp_makeConstraints { make in
make.edges.equalTo(self.header)
}
webViewContainerBackdrop.snp_makeConstraints { make in
make.edges.equalTo(webViewContainer)
}
webViewContainerToolbar.snp_makeConstraints { make in
make.left.right.top.equalTo(webViewContainer)
make.height.equalTo(0)
}
}
override func viewDidLayoutSubviews() {
log.debug("BVC viewDidLayoutSubviews…")
super.viewDidLayoutSubviews()
statusBarOverlay.snp_remakeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(self.topLayoutGuide.length)
}
self.appDidUpdateState(getCurrentAppState())
log.debug("BVC done.")
}
func loadQueuedTabs() {
log.debug("Loading queued tabs in the background.")
// Chain off of a trivial deferred in order to run on the background queue.
succeed().upon() { res in
self.dequeueQueuedTabs()
}
}
private func dequeueQueuedTabs() {
assert(!NSThread.currentThread().isMainThread, "This must be called in the background.")
self.profile.queue.getQueuedTabs() >>== { cursor in
// This assumes that the DB returns rows in some kind of sane order.
// It does in practice, so WFM.
log.debug("Queue. Count: \(cursor.count).")
if cursor.count <= 0 {
return
}
let urls = cursor.flatMap { $0?.url.asURL }
if !urls.isEmpty {
dispatch_async(dispatch_get_main_queue()) {
self.tabManager.addTabsForURLs(urls, zombie: false)
}
}
// Clear *after* making an attempt to open. We're making a bet that
// it's better to run the risk of perhaps opening twice on a crash,
// rather than losing data.
self.profile.queue.clearQueuedTabs()
}
}
override func viewWillAppear(animated: Bool) {
log.debug("BVC viewWillAppear.")
super.viewWillAppear(animated)
log.debug("BVC super.viewWillAppear done.")
// On iPhone, if we are about to show the On-Boarding, blank out the tab so that it does
// not flash before we present. This change of alpha also participates in the animation when
// the intro view is dismissed.
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
self.view.alpha = (profile.prefs.intForKey(IntroViewControllerSeenProfileKey) != nil) ? 1.0 : 0.0
}
if PLCrashReporter.sharedReporter().hasPendingCrashReport() {
PLCrashReporter.sharedReporter().purgePendingCrashReport()
showRestoreTabsAlert()
} else {
log.debug("Restoring tabs.")
tabManager.restoreTabs()
log.debug("Done restoring tabs.")
}
log.debug("Updating tab count.")
updateTabCountUsingTabManager(tabManager, animated: false)
log.debug("BVC done.")
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(BrowserViewController.openSettings),
name: NotificationStatusNotificationTapped,
object: nil)
}
private func showRestoreTabsAlert() {
guard shouldRestoreTabs() else {
self.tabManager.addTabAndSelect()
return
}
let alert = UIAlertController.restoreTabsAlert(
okayCallback: { _ in
self.tabManager.restoreTabs()
self.updateTabCountUsingTabManager(self.tabManager, animated: false)
},
noCallback: { _ in
self.tabManager.addTabAndSelect()
self.updateTabCountUsingTabManager(self.tabManager, animated: false)
}
)
self.presentViewController(alert, animated: true, completion: nil)
}
private func shouldRestoreTabs() -> Bool {
guard let tabsToRestore = TabManager.tabsToRestore() else { return false }
let onlyNoHistoryTabs = !tabsToRestore.every { $0.sessionData?.urls.count > 1 || !AboutUtils.isAboutHomeURL($0.sessionData?.urls.first) }
return !onlyNoHistoryTabs && !DebugSettingsBundleOptions.skipSessionRestore
}
override func viewDidAppear(animated: Bool) {
log.debug("BVC viewDidAppear.")
presentIntroViewController()
log.debug("BVC intro presented.")
self.webViewContainerToolbar.hidden = false
screenshotHelper.viewIsVisible = true
log.debug("BVC taking pending screenshots….")
screenshotHelper.takePendingScreenshots(tabManager.tabs)
log.debug("BVC done taking screenshots.")
log.debug("BVC calling super.viewDidAppear.")
super.viewDidAppear(animated)
log.debug("BVC done.")
if shouldShowWhatsNewTab() {
if let whatsNewURL = SupportUtils.URLForTopic("new-ios") {
self.openURLInNewTab(whatsNewURL)
profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey)
}
}
showQueuedAlertIfAvailable()
}
private func shouldShowWhatsNewTab() -> Bool {
guard let latestMajorAppVersion = profile.prefs.stringForKey(LatestAppVersionProfileKey)?.componentsSeparatedByString(".").first else {
return DeviceInfo.hasConnectivity()
}
return latestMajorAppVersion != AppInfo.majorAppVersion && DeviceInfo.hasConnectivity()
}
private func showQueuedAlertIfAvailable() {
if var queuedAlertInfo = tabManager.selectedTab?.dequeueJavascriptAlertPrompt() {
let alertController = queuedAlertInfo.alertController()
alertController.delegate = self
presentViewController(alertController, animated: true, completion: nil)
}
}
override func viewWillDisappear(animated: Bool) {
screenshotHelper.viewIsVisible = false
super.viewWillDisappear(animated)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationStatusNotificationTapped, object: nil)
}
func resetBrowserChrome() {
// animate and reset transform for tab chrome
urlBar.updateAlphaForSubviews(1)
[header,
footer,
readerModeBar,
footerBackdrop,
headerBackdrop].forEach { view in
view?.transform = CGAffineTransformIdentity
}
}
override func updateViewConstraints() {
super.updateViewConstraints()
topTouchArea.snp_remakeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight)
}
readerModeBar?.snp_remakeConstraints { make in
make.top.equalTo(self.header.snp_bottom).constraint
make.height.equalTo(UIConstants.ToolbarHeight)
make.leading.trailing.equalTo(self.view)
}
webViewContainer.snp_remakeConstraints { make in
make.left.right.equalTo(self.view)
if let readerModeBarBottom = readerModeBar?.snp_bottom {
make.top.equalTo(readerModeBarBottom)
} else {
make.top.equalTo(self.header.snp_bottom)
}
let findInPageHeight = (findInPageBar == nil) ? 0 : UIConstants.ToolbarHeight
if let toolbar = self.toolbar {
make.bottom.equalTo(toolbar.snp_top).offset(-findInPageHeight)
} else {
make.bottom.equalTo(self.view).offset(-findInPageHeight)
}
}
// Setup the bottom toolbar
toolbar?.snp_remakeConstraints { make in
make.edges.equalTo(self.footerBackground!)
make.height.equalTo(UIConstants.ToolbarHeight)
}
footer.snp_remakeConstraints { make in
scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp_bottom).constraint
make.top.equalTo(self.snackBars.snp_top)
make.leading.trailing.equalTo(self.view)
}
footerBackdrop.snp_remakeConstraints { make in
make.edges.equalTo(self.footer)
}
updateSnackBarConstraints()
footerBackground?.snp_remakeConstraints { make in
make.bottom.left.right.equalTo(self.footer)
make.height.equalTo(UIConstants.ToolbarHeight)
}
urlBar.setNeedsUpdateConstraints()
// Remake constraints even if we're already showing the home controller.
// The home controller may change sizes if we tap the URL bar while on about:home.
homePanelController?.view.snp_remakeConstraints { make in
make.top.equalTo(self.urlBar.snp_bottom)
make.left.right.equalTo(self.view)
if self.homePanelIsInline {
make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom)
} else {
make.bottom.equalTo(self.view.snp_bottom)
}
}
findInPageContainer.snp_remakeConstraints { make in
make.left.right.equalTo(self.view)
if let keyboardHeight = keyboardState?.intersectionHeightForView(self.view) where keyboardHeight > 0 {
make.bottom.equalTo(self.view).offset(-keyboardHeight)
} else if let toolbar = self.toolbar {
make.bottom.equalTo(toolbar.snp_top)
} else {
make.bottom.equalTo(self.view)
}
}
}
private func showHomePanelController(inline inline: Bool) {
log.debug("BVC showHomePanelController.")
homePanelIsInline = inline
if homePanelController == nil {
homePanelController = HomePanelViewController()
homePanelController!.profile = profile
homePanelController!.delegate = self
homePanelController!.appStateDelegate = self
homePanelController!.url = tabManager.selectedTab?.displayURL
homePanelController!.view.alpha = 0
addChildViewController(homePanelController!)
view.addSubview(homePanelController!.view)
homePanelController!.didMoveToParentViewController(self)
}
let panelNumber = tabManager.selectedTab?.url?.fragment
// splitting this out to see if we can get better crash reports when this has a problem
var newSelectedButtonIndex = 0
if let numberArray = panelNumber?.componentsSeparatedByString("=") {
if let last = numberArray.last, lastInt = Int(last) {
newSelectedButtonIndex = lastInt
}
}
homePanelController?.selectedPanel = HomePanelType(rawValue: newSelectedButtonIndex)
homePanelController?.isPrivateMode = tabTrayController?.privateMode ?? tabManager.selectedTab?.isPrivate ?? false
// We have to run this animation, even if the view is already showing because there may be a hide animation running
// and we want to be sure to override its results.
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.homePanelController!.view.alpha = 1
}, completion: { finished in
if finished {
self.webViewContainer.accessibilityElementsHidden = true
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
}
})
view.setNeedsUpdateConstraints()
log.debug("BVC done with showHomePanelController.")
}
private func hideHomePanelController() {
if let controller = homePanelController {
UIView.animateWithDuration(0.2, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in
controller.view.alpha = 0
}, completion: { finished in
if finished {
controller.willMoveToParentViewController(nil)
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
self.homePanelController = nil
self.webViewContainer.accessibilityElementsHidden = false
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// Refresh the reading view toolbar since the article record may have changed
if let readerMode = self.tabManager.selectedTab?.getHelper(name: ReaderMode.name()) as? ReaderMode where readerMode.state == .Active {
self.showReaderModeBar(animated: false)
}
}
})
}
}
private func updateInContentHomePanel(url: NSURL?) {
if !urlBar.inOverlayMode {
if AboutUtils.isAboutHomeURL(url){
let showInline = AppConstants.MOZ_MENU || ((tabManager.selectedTab?.canGoForward ?? false || tabManager.selectedTab?.canGoBack ?? false))
showHomePanelController(inline: showInline)
} else {
hideHomePanelController()
}
}
}
private func showSearchController() {
if searchController != nil {
return
}
let isPrivate = tabManager.selectedTab?.isPrivate ?? false
searchController = SearchViewController(isPrivate: isPrivate)
searchController!.searchEngines = profile.searchEngines
searchController!.searchDelegate = self
searchController!.profile = self.profile
searchLoader.addListener(searchController!)
addChildViewController(searchController!)
view.addSubview(searchController!.view)
searchController!.view.snp_makeConstraints { make in
make.top.equalTo(self.urlBar.snp_bottom)
make.left.right.bottom.equalTo(self.view)
return
}
homePanelController?.view?.hidden = true
searchController!.didMoveToParentViewController(self)
}
private func hideSearchController() {
if let searchController = searchController {
searchController.willMoveToParentViewController(nil)
searchController.view.removeFromSuperview()
searchController.removeFromParentViewController()
self.searchController = nil
homePanelController?.view?.hidden = false
}
}
private func finishEditingAndSubmit(url: NSURL, visitType: VisitType) {
urlBar.currentURL = url
urlBar.leaveOverlayMode()
guard let tab = tabManager.selectedTab else {
return
}
if let webView = tab.webView {
resetSpoofedUserAgentIfRequired(webView, newURL: url)
}
if let nav = tab.loadRequest(PrivilegedRequest(URL: url)) {
self.recordNavigationInTab(tab, navigation: nav, visitType: visitType)
}
}
func addBookmark(tabState: TabState) {
guard let url = tabState.url else { return }
let shareItem = ShareItem(url: url.absoluteString, title: tabState.title, favicon: tabState.favicon)
profile.bookmarks.shareItem(shareItem)
if #available(iOS 9, *) {
var userData = [QuickActions.TabURLKey: shareItem.url]
if let title = shareItem.title {
userData[QuickActions.TabTitleKey] = title
}
QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.OpenLastBookmark,
withUserData: userData,
toApplication: UIApplication.sharedApplication())
}
if let tab = tabManager.getTabForURL(url) {
tab.isBookmarked = true
}
if !AppConstants.MOZ_MENU {
// Dispatch to the main thread to update the UI
dispatch_async(dispatch_get_main_queue()) { _ in
self.animateBookmarkStar()
self.toolbar?.updateBookmarkStatus(true)
self.urlBar.updateBookmarkStatus(true)
}
}
}
private func animateBookmarkStar() {
let offset: CGFloat
let button: UIButton!
if let toolbar: TabToolbar = self.toolbar {
offset = BrowserViewControllerUX.BookmarkStarAnimationOffset * -1
button = toolbar.bookmarkButton
} else {
offset = BrowserViewControllerUX.BookmarkStarAnimationOffset
button = self.urlBar.bookmarkButton
}
JumpAndSpinAnimator.animateFromView(button.imageView ?? button, offset: offset, completion: nil)
}
private func removeBookmark(tabState: TabState) {
guard let url = tabState.url else { return }
profile.bookmarks.modelFactory >>== {
$0.removeByURL(url.absoluteString)
.uponQueue(dispatch_get_main_queue()) { res in
if res.isSuccess {
if let tab = self.tabManager.getTabForURL(url) {
tab.isBookmarked = false
}
if !AppConstants.MOZ_MENU {
self.toolbar?.updateBookmarkStatus(false)
self.urlBar.updateBookmarkStatus(false)
}
}
}
}
}
func SELBookmarkStatusDidChange(notification: NSNotification) {
if let bookmark = notification.object as? BookmarkItem {
if bookmark.url == urlBar.currentURL?.absoluteString {
if let userInfo = notification.userInfo as? Dictionary<String, Bool>{
if let added = userInfo["added"]{
if let tab = self.tabManager.getTabForURL(urlBar.currentURL!) {
tab.isBookmarked = false
}
if !AppConstants.MOZ_MENU {
self.toolbar?.updateBookmarkStatus(added)
self.urlBar.updateBookmarkStatus(added)
}
}
}
}
}
}
override func accessibilityPerformEscape() -> Bool {
if urlBar.inOverlayMode {
urlBar.SELdidClickCancel()
return true
} else if let selectedTab = tabManager.selectedTab where selectedTab.canGoBack {
selectedTab.goBack()
return true
}
return false
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) {
let webView = object as! WKWebView
guard let path = keyPath else { assertionFailure("Unhandled KVO key: \(keyPath)"); return }
switch path {
case KVOEstimatedProgress:
guard webView == tabManager.selectedTab?.webView,
let progress = change?[NSKeyValueChangeNewKey] as? Float else { break }
urlBar.updateProgressBar(progress)
case KVOLoading:
guard let loading = change?[NSKeyValueChangeNewKey] as? Bool else { break }
if webView == tabManager.selectedTab?.webView {
navigationToolbar.updateReloadStatus(loading)
}
if (!loading) {
runScriptsOnWebView(webView)
}
case KVOURL:
guard let tab = tabManager[webView] else { break }
// To prevent spoofing, only change the URL immediately if the new URL is on
// the same origin as the current URL. Otherwise, do nothing and wait for
// didCommitNavigation to confirm the page load.
if tab.url?.origin == webView.URL?.origin {
tab.url = webView.URL
if tab === tabManager.selectedTab {
updateUIForReaderHomeStateForTab(tab)
}
}
case KVOCanGoBack:
guard webView == tabManager.selectedTab?.webView,
let canGoBack = change?[NSKeyValueChangeNewKey] as? Bool else { break }
navigationToolbar.updateBackStatus(canGoBack)
case KVOCanGoForward:
guard webView == tabManager.selectedTab?.webView,
let canGoForward = change?[NSKeyValueChangeNewKey] as? Bool else { break }
navigationToolbar.updateForwardStatus(canGoForward)
default:
assertionFailure("Unhandled KVO key: \(keyPath)")
}
}
private func runScriptsOnWebView(webView: WKWebView) {
webView.evaluateJavaScript("__firefox__.favicons.getFavicons()", completionHandler:nil)
}
private func updateUIForReaderHomeStateForTab(tab: Tab) {
updateURLBarDisplayURL(tab)
scrollController.showToolbars(animated: false)
if let url = tab.url {
if ReaderModeUtils.isReaderModeURL(url) {
showReaderModeBar(animated: false)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BrowserViewController.SELDynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil)
} else {
hideReaderModeBar(animated: false)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationDynamicFontChanged, object: nil)
}
updateInContentHomePanel(url)
}
}
private func isWhitelistedUrl(url: NSURL) -> Bool {
for entry in WhiteListedUrls {
if let _ = url.absoluteString.rangeOfString(entry, options: .RegularExpressionSearch) {
return UIApplication.sharedApplication().canOpenURL(url)
}
}
return false
}
/// Updates the URL bar text and button states.
/// Call this whenever the page URL changes.
private func updateURLBarDisplayURL(tab: Tab) {
urlBar.currentURL = tab.displayURL
let isPage = tab.displayURL?.isWebPage() ?? false
navigationToolbar.updatePageStatus(isWebPage: isPage)
guard let url = tab.displayURL?.absoluteString else {
return
}
profile.bookmarks.modelFactory >>== {
$0.isBookmarked(url).uponQueue(dispatch_get_main_queue()) { [weak tab] result in
guard let bookmarked = result.successValue else {
log.error("Error getting bookmark status: \(result.failureValue).")
return
}
tab?.isBookmarked = bookmarked
if !AppConstants.MOZ_MENU {
self.navigationToolbar.updateBookmarkStatus(bookmarked)
}
}
}
}
// Mark: Opening New Tabs
@available(iOS 9, *)
func switchToPrivacyMode(isPrivate isPrivate: Bool ){
applyTheme(isPrivate ? Theme.PrivateMode : Theme.NormalMode)
let tabTrayController = self.tabTrayController ?? TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self)
if tabTrayController.privateMode != isPrivate {
tabTrayController.changePrivacyMode(isPrivate)
}
self.tabTrayController = tabTrayController
}
func switchToTabForURLOrOpen(url: NSURL, isPrivate: Bool = false) {
popToBVC()
if let tab = tabManager.getTabForURL(url) {
tabManager.selectTab(tab)
} else {
openURLInNewTab(url, isPrivate: isPrivate)
}
}
func openURLInNewTab(url: NSURL?, isPrivate: Bool = false) {
if let selectedTab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(selectedTab)
}
let request: NSURLRequest?
if let url = url {
request = PrivilegedRequest(URL: url)
} else {
request = nil
}
if #available(iOS 9, *) {
switchToPrivacyMode(isPrivate: isPrivate)
tabManager.addTabAndSelect(request, isPrivate: isPrivate)
} else {
tabManager.addTabAndSelect(request)
}
}
func openBlankNewTabAndFocus(isPrivate isPrivate: Bool = false) {
popToBVC()
openURLInNewTab(nil, isPrivate: isPrivate)
urlBar.tabLocationViewDidTapLocation(urlBar.locationView)
}
private func popToBVC() {
guard let currentViewController = navigationController?.topViewController else {
return
}
currentViewController.dismissViewControllerAnimated(true, completion: nil)
if currentViewController != self {
self.navigationController?.popViewControllerAnimated(true)
} else if urlBar.inOverlayMode {
urlBar.SELdidClickCancel()
}
}
// Mark: User Agent Spoofing
private func resetSpoofedUserAgentIfRequired(webView: WKWebView, newURL: NSURL) {
guard #available(iOS 9.0, *) else {
return
}
// Reset the UA when a different domain is being loaded
if webView.URL?.host != newURL.host {
webView.customUserAgent = nil
}
}
private func restoreSpoofedUserAgentIfRequired(webView: WKWebView, newRequest: NSURLRequest) {
guard #available(iOS 9.0, *) else {
return
}
// Restore any non-default UA from the request's header
let ua = newRequest.valueForHTTPHeaderField("User-Agent")
webView.customUserAgent = ua != UserAgent.defaultUserAgent() ? ua : nil
}
private func presentActivityViewController(url: NSURL, tab: Tab? = nil, sourceView: UIView?, sourceRect: CGRect, arrowDirection: UIPopoverArrowDirection) {
var activities = [UIActivity]()
let findInPageActivity = FindInPageActivity() { [unowned self] in
self.updateFindInPageVisibility(visible: true)
}
activities.append(findInPageActivity)
if #available(iOS 9.0, *) {
if let tab = tab where (tab.getHelper(name: ReaderMode.name()) as? ReaderMode)?.state != .Active {
let requestDesktopSiteActivity = RequestDesktopSiteActivity(requestMobileSite: tab.desktopSite) { [unowned tab] in
tab.toggleDesktopSite()
}
activities.append(requestDesktopSiteActivity)
}
}
let helper = ShareExtensionHelper(url: url, tab: tab, activities: activities)
let controller = helper.createActivityViewController({ [unowned self] completed in
// After dismissing, check to see if there were any prompts we queued up
self.showQueuedAlertIfAvailable()
if completed {
// We don't know what share action the user has chosen so we simply always
// update the toolbar and reader mode bar to reflect the latest status.
if let tab = tab {
self.updateURLBarDisplayURL(tab)
}
self.updateReaderModeBar()
}
})
let setupPopover = { [unowned self] in
if let popoverPresentationController = controller.popoverPresentationController {
popoverPresentationController.sourceView = sourceView
popoverPresentationController.sourceRect = sourceRect
popoverPresentationController.permittedArrowDirections = arrowDirection
popoverPresentationController.delegate = self
}
}
setupPopover()
if controller.popoverPresentationController != nil {
displayedPopoverController = controller
updateDisplayedPopoverProperties = setupPopover
}
self.presentViewController(controller, animated: true, completion: nil)
}
private func updateFindInPageVisibility(visible visible: Bool) {
if visible {
if findInPageBar == nil {
let findInPageBar = FindInPageBar()
self.findInPageBar = findInPageBar
findInPageBar.delegate = self
findInPageContainer.addSubview(findInPageBar)
findInPageBar.snp_makeConstraints { make in
make.edges.equalTo(findInPageContainer)
make.height.equalTo(UIConstants.ToolbarHeight)
}
updateViewConstraints()
// We make the find-in-page bar the first responder below, causing the keyboard delegates
// to fire. This, in turn, will animate the Find in Page container since we use the same
// delegate to slide the bar up and down with the keyboard. We don't want to animate the
// constraints added above, however, so force a layout now to prevent these constraints
// from being lumped in with the keyboard animation.
findInPageBar.layoutIfNeeded()
}
self.findInPageBar?.becomeFirstResponder()
} else if let findInPageBar = self.findInPageBar {
findInPageBar.endEditing(true)
guard let webView = tabManager.selectedTab?.webView else { return }
webView.evaluateJavaScript("__firefox__.findDone()", completionHandler: nil)
findInPageBar.removeFromSuperview()
self.findInPageBar = nil
updateViewConstraints()
}
}
override func canBecomeFirstResponder() -> Bool {
return true
}
override func becomeFirstResponder() -> Bool {
// Make the web view the first responder so that it can show the selection menu.
return tabManager.selectedTab?.webView?.becomeFirstResponder() ?? false
}
func reloadTab(){
if(homePanelController == nil){
tabManager.selectedTab?.reload()
}
}
func goBack(){
if(tabManager.selectedTab?.canGoBack == true && homePanelController == nil){
tabManager.selectedTab?.goBack()
}
}
func goForward(){
if(tabManager.selectedTab?.canGoForward == true && homePanelController == nil){
tabManager.selectedTab?.goForward()
}
}
func findOnPage(){
if(homePanelController == nil){
tab( (tabManager.selectedTab)!, didSelectFindInPageForSelection: "")
}
}
func selectLocationBar(){
urlBar.tabLocationViewDidTapLocation(urlBar.locationView)
}
func newTab(){
openBlankNewTabAndFocus(isPrivate: false)
}
func newPrivateTab(){
openBlankNewTabAndFocus(isPrivate: true)
}
func closeTab(){
if(tabManager.tabs.count > 1){
tabManager.removeTab(tabManager.selectedTab!);
}
else{
//need to close the last tab and show the favorites screen thing
}
}
func nextTab(){
if(tabManager.selectedIndex < (tabManager.tabs.count - 1) ){
tabManager.selectTab(tabManager.tabs[tabManager.selectedIndex+1])
}
else{
if(tabManager.tabs.count > 1){
tabManager.selectTab(tabManager.tabs[0]);
}
}
}
func previousTab(){
if(tabManager.selectedIndex > 0){
tabManager.selectTab(tabManager.tabs[tabManager.selectedIndex-1])
}
else{
if(tabManager.tabs.count > 1){
tabManager.selectTab(tabManager.tabs[tabManager.count-1])
}
}
}
override var keyCommands: [UIKeyCommand]? {
if #available(iOS 9.0, *) {
return [
UIKeyCommand(input: "r", modifierFlags: .Command, action: #selector(BrowserViewController.reloadTab), discoverabilityTitle: Strings.ReloadPageTitle),
UIKeyCommand(input: "[", modifierFlags: .Command, action: #selector(BrowserViewController.goBack), discoverabilityTitle: Strings.BackTitle),
UIKeyCommand(input: "]", modifierFlags: .Command, action: #selector(BrowserViewController.goForward), discoverabilityTitle: Strings.ForwardTitle),
UIKeyCommand(input: "f", modifierFlags: .Command, action: #selector(BrowserViewController.findOnPage), discoverabilityTitle: Strings.FindTitle),
UIKeyCommand(input: "l", modifierFlags: .Command, action: #selector(BrowserViewController.selectLocationBar), discoverabilityTitle: Strings.SelectLocationBarTitle),
UIKeyCommand(input: "t", modifierFlags: .Command, action: #selector(BrowserViewController.newTab), discoverabilityTitle: Strings.NewTabTitle),
UIKeyCommand(input: "p", modifierFlags: [.Command, .Shift], action: #selector(BrowserViewController.newPrivateTab), discoverabilityTitle: Strings.NewPrivateTabTitle),
UIKeyCommand(input: "w", modifierFlags: .Command, action: #selector(BrowserViewController.closeTab), discoverabilityTitle: Strings.CloseTabTitle),
UIKeyCommand(input: "\t", modifierFlags: .Control, action: #selector(BrowserViewController.nextTab), discoverabilityTitle: Strings.ShowNextTabTitle),
UIKeyCommand(input: "\t", modifierFlags: [.Control, .Shift], action: #selector(BrowserViewController.previousTab), discoverabilityTitle: Strings.ShowPreviousTabTitle),
]
} else {
// Fallback on earlier versions
return [
UIKeyCommand(input: "r", modifierFlags: .Command, action: #selector(BrowserViewController.reloadTab)),
UIKeyCommand(input: "[", modifierFlags: .Command, action: #selector(BrowserViewController.goBack)),
UIKeyCommand(input: "f", modifierFlags: .Command, action: #selector(BrowserViewController.findOnPage)),
UIKeyCommand(input: "l", modifierFlags: .Command, action: #selector(BrowserViewController.selectLocationBar)),
UIKeyCommand(input: "t", modifierFlags: .Command, action: #selector(BrowserViewController.newTab)),
UIKeyCommand(input: "p", modifierFlags: [.Command, .Shift], action: #selector(BrowserViewController.newPrivateTab)),
UIKeyCommand(input: "w", modifierFlags: .Command, action: #selector(BrowserViewController.closeTab)),
UIKeyCommand(input: "\t", modifierFlags: .Control, action: #selector(BrowserViewController.nextTab)),
UIKeyCommand(input: "\t", modifierFlags: [.Control, .Shift], action: #selector(BrowserViewController.previousTab))
]
}
}
private func getCurrentAppState() -> AppState {
return mainStore.updateState(getCurrentUIState())
}
private func getCurrentUIState() -> UIState {
if let homePanelController = homePanelController {
return .HomePanels(homePanelState: homePanelController.homePanelState)
}
guard let tab = tabManager.selectedTab where !tab.loading else {
return .Loading
}
return .Tab(tabState: tab.tabState)
}
@objc private func openSettings() {
assert(NSThread.isMainThread(), "Opening settings requires being invoked on the main thread")
let settingsTableViewController = AppSettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
settingsTableViewController.settingsDelegate = self
let controller = SettingsNavigationController(rootViewController: settingsTableViewController)
controller.popoverDelegate = self
controller.modalPresentationStyle = UIModalPresentationStyle.FormSheet
self.presentViewController(controller, animated: true, completion: nil)
}
}
extension BrowserViewController: AppStateDelegate {
func appDidUpdateState(appState: AppState) {
if AppConstants.MOZ_MENU {
menuViewController?.appState = appState
}
toolbar?.appDidUpdateState(appState)
urlBar?.appDidUpdateState(appState)
}
}
extension BrowserViewController: MenuActionDelegate {
func performMenuAction(action: MenuAction, withAppState appState: AppState) {
if let menuAction = AppMenuAction(rawValue: action.action) {
switch menuAction {
case .OpenNewNormalTab:
if #available(iOS 9, *) {
self.openURLInNewTab(nil, isPrivate: false)
} else {
self.tabManager.addTabAndSelect(nil)
}
// this is a case that is only available in iOS9
case .OpenNewPrivateTab:
if #available(iOS 9, *) {
self.openURLInNewTab(nil, isPrivate: true)
}
case .FindInPage:
self.updateFindInPageVisibility(visible: true)
case .ToggleBrowsingMode:
if #available(iOS 9, *) {
guard let tab = tabManager.selectedTab else { break }
tab.toggleDesktopSite()
}
case .ToggleBookmarkStatus:
switch appState.ui {
case .Tab(let tabState):
self.toggleBookmarkForTabState(tabState)
default: break
}
case .ShowImageMode:
self.setNoImageMode(false)
case .HideImageMode:
self.setNoImageMode(true)
case .ShowNightMode:
NightModeHelper.setNightMode(self.profile.prefs, tabManager: self.tabManager, enabled: false)
case .HideNightMode:
NightModeHelper.setNightMode(self.profile.prefs, tabManager: self.tabManager, enabled: true)
case .OpenSettings:
self.openSettings()
case .OpenTopSites:
openHomePanel(.TopSites, forAppState: appState)
case .OpenBookmarks:
openHomePanel(.Bookmarks, forAppState: appState)
case .OpenHistory:
openHomePanel(.History, forAppState: appState)
case .OpenReadingList:
openHomePanel(.ReadingList, forAppState: appState)
case .SetHomePage:
guard let tab = tabManager.selectedTab else { break }
HomePageHelper(prefs: profile.prefs).setHomePage(toTab: tab, withNavigationController: navigationController)
case .OpenHomePage:
guard let tab = tabManager.selectedTab else { break }
HomePageHelper(prefs: profile.prefs).openHomePage(inTab: tab, withNavigationController: navigationController)
case .SharePage:
guard let url = tabManager.selectedTab?.url else { break }
let sourceView = self.navigationToolbar.menuButton
presentActivityViewController(url, sourceView: sourceView.superview, sourceRect: sourceView.frame, arrowDirection: .Up)
default: break
}
}
}
private func openHomePanel(panel: HomePanelType, forAppState appState: AppState) {
switch appState.ui {
case .Tab(_):
self.openURLInNewTab(panel.localhostURL, isPrivate: appState.ui.isPrivate())
case .HomePanels(_):
self.homePanelController?.selectedPanel = panel
default: break
}
}
}
extension BrowserViewController: SettingsDelegate {
func settingsOpenURLInNewTab(url: NSURL) {
self.openURLInNewTab(url)
}
}
extension BrowserViewController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(modalViewController: UIViewController, animated: Bool) {
self.appDidUpdateState(getCurrentAppState())
self.dismissViewControllerAnimated(animated, completion: nil)
}
}
/**
* History visit management.
* TODO: this should be expanded to track various visit types; see Bug 1166084.
*/
extension BrowserViewController {
func ignoreNavigationInTab(tab: Tab, navigation: WKNavigation) {
self.ignoredNavigation.insert(navigation)
}
func recordNavigationInTab(tab: Tab, navigation: WKNavigation, visitType: VisitType) {
self.typedNavigation[navigation] = visitType
}
/**
* Untrack and do the right thing.
*/
func getVisitTypeForTab(tab: Tab, navigation: WKNavigation?) -> VisitType? {
guard let navigation = navigation else {
// See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390
return VisitType.Link
}
if let _ = self.ignoredNavigation.remove(navigation) {
return nil
}
return self.typedNavigation.removeValueForKey(navigation) ?? VisitType.Link
}
}
extension BrowserViewController: URLBarDelegate {
func urlBarDidPressReload(urlBar: URLBarView) {
tabManager.selectedTab?.reload()
}
func urlBarDidPressStop(urlBar: URLBarView) {
tabManager.selectedTab?.stop()
}
func urlBarDidPressTabs(urlBar: URLBarView) {
self.webViewContainerToolbar.hidden = true
updateFindInPageVisibility(visible: false)
let tabTrayController = TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self)
if let tab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(tab)
}
self.navigationController?.pushViewController(tabTrayController, animated: true)
self.tabTrayController = tabTrayController
}
func urlBarDidPressReaderMode(urlBar: URLBarView) {
if let tab = tabManager.selectedTab {
if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode {
switch readerMode.state {
case .Available:
enableReaderMode()
case .Active:
disableReaderMode()
case .Unavailable:
break
}
}
}
}
func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool {
guard let tab = tabManager.selectedTab,
url = tab.displayURL,
result = profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name)
else {
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed."))
return false
}
switch result {
case .Success:
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action."))
// TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback?
case .Failure(let error):
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it's already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures."))
log.error("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)")
}
return true
}
func locationActionsForURLBar(urlBar: URLBarView) -> [AccessibleAction] {
if UIPasteboard.generalPasteboard().string != nil {
return [pasteGoAction, pasteAction, copyAddressAction]
} else {
return [copyAddressAction]
}
}
func urlBarDisplayTextForURL(url: NSURL?) -> String? {
// use the initial value for the URL so we can do proper pattern matching with search URLs
var searchURL = self.tabManager.selectedTab?.currentInitialURL
if searchURL == nil || ErrorPageHelper.isErrorPageURL(searchURL!) {
searchURL = url
}
return profile.searchEngines.queryForSearchURL(searchURL) ?? url?.absoluteString
}
func urlBarDidLongPressLocation(urlBar: URLBarView) {
let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
for action in locationActionsForURLBar(urlBar) {
longPressAlertController.addAction(action.alertAction(style: .Default))
}
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .Cancel, handler: { (alert: UIAlertAction) -> Void in
})
longPressAlertController.addAction(cancelAction)
let setupPopover = { [unowned self] in
if let popoverPresentationController = longPressAlertController.popoverPresentationController {
popoverPresentationController.sourceView = urlBar
popoverPresentationController.sourceRect = urlBar.frame
popoverPresentationController.permittedArrowDirections = .Any
popoverPresentationController.delegate = self
}
}
setupPopover()
if longPressAlertController.popoverPresentationController != nil {
displayedPopoverController = longPressAlertController
updateDisplayedPopoverProperties = setupPopover
}
self.presentViewController(longPressAlertController, animated: true, completion: nil)
}
func urlBarDidPressScrollToTop(urlBar: URLBarView) {
if let selectedTab = tabManager.selectedTab {
// Only scroll to top if we are not showing the home view controller
if homePanelController == nil {
selectedTab.webView?.scrollView.setContentOffset(CGPointZero, animated: true)
}
}
}
func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]? {
return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction }
}
func urlBar(urlBar: URLBarView, didEnterText text: String) {
searchLoader.query = text
if text.isEmpty {
hideSearchController()
} else {
showSearchController()
searchController!.searchQuery = text
}
}
func urlBar(urlBar: URLBarView, didSubmitText text: String) {
// If we can't make a valid URL, do a search query.
// If we still don't have a valid URL, something is broken. Give up.
let engine = profile.searchEngines.defaultEngine
guard let url = URIFixup.getURL(text) ??
engine.searchURLForQuery(text) else {
log.error("Error handling URL entry: \"\(text)\".")
return
}
Telemetry.recordEvent(SearchTelemetry.makeEvent(engine: engine, source: .URLBar))
finishEditingAndSubmit(url, visitType: VisitType.Typed)
}
func urlBarDidEnterOverlayMode(urlBar: URLBarView) {
if .BlankPage == NewTabAccessors.getNewTabPage(profile.prefs) {
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
} else {
showHomePanelController(inline: false)
}
}
func urlBarDidLeaveOverlayMode(urlBar: URLBarView) {
hideSearchController()
updateInContentHomePanel(tabManager.selectedTab?.url)
}
}
extension BrowserViewController: TabToolbarDelegate {
func tabToolbarDidPressBack(tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.goBack()
}
func tabToolbarDidLongPressBack(tabToolbar: TabToolbarProtocol, button: UIButton) {
showBackForwardList()
}
func tabToolbarDidPressReload(tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.reload()
}
func tabToolbarDidLongPressReload(tabToolbar: TabToolbarProtocol, button: UIButton) {
guard #available(iOS 9.0, *) else {
return
}
guard let tab = tabManager.selectedTab where tab.webView?.URL != nil && (tab.getHelper(name: ReaderMode.name()) as? ReaderMode)?.state != .Active else {
return
}
let toggleActionTitle: String
if tab.desktopSite {
toggleActionTitle = NSLocalizedString("Request Mobile Site", comment: "Action Sheet Button for Requesting the Mobile Site")
} else {
toggleActionTitle = NSLocalizedString("Request Desktop Site", comment: "Action Sheet Button for Requesting the Desktop Site")
}
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
controller.addAction(UIAlertAction(title: toggleActionTitle, style: .Default, handler: { _ in tab.toggleDesktopSite() }))
controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Label for Cancel button"), style: .Cancel, handler: nil))
controller.popoverPresentationController?.sourceView = toolbar ?? urlBar
controller.popoverPresentationController?.sourceRect = button.frame
presentViewController(controller, animated: true, completion: nil)
}
func tabToolbarDidPressStop(tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.stop()
}
func tabToolbarDidPressForward(tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.goForward()
}
func tabToolbarDidLongPressForward(tabToolbar: TabToolbarProtocol, button: UIButton) {
showBackForwardList()
}
func tabToolbarDidPressMenu(tabToolbar: TabToolbarProtocol, button: UIButton) {
// ensure that any keyboards or spinners are dismissed before presenting the menu
UIApplication.sharedApplication().sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, forEvent:nil)
// check the trait collection
// open as modal if portrait\
let presentationStyle: MenuViewPresentationStyle = (self.traitCollection.horizontalSizeClass == .Compact && traitCollection.verticalSizeClass == .Regular) ? .Modal : .Popover
let mvc = MenuViewController(withAppState: getCurrentAppState(), presentationStyle: presentationStyle)
mvc.delegate = self
mvc.actionDelegate = self
mvc.menuTransitionDelegate = MenuPresentationAnimator()
mvc.modalPresentationStyle = presentationStyle == .Modal ? .OverCurrentContext : .Popover
if let popoverPresentationController = mvc.popoverPresentationController {
popoverPresentationController.backgroundColor = UIColor.clearColor()
popoverPresentationController.delegate = self
popoverPresentationController.sourceView = button
popoverPresentationController.sourceRect = CGRect(x: button.frame.width/2, y: button.frame.size.height * 0.75, width: 1, height: 1)
popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.Up
}
self.presentViewController(mvc, animated: true, completion: nil)
menuViewController = mvc
}
private func setNoImageMode(enabled: Bool) {
self.profile.prefs.setBool(enabled, forKey: PrefsKeys.KeyNoImageModeStatus)
for tab in self.tabManager.tabs {
tab.setNoImageMode(enabled, force: true)
}
self.tabManager.selectedTab?.reload()
}
func toggleBookmarkForTabState(tabState: TabState) {
if tabState.isBookmarked {
self.removeBookmark(tabState)
} else {
self.addBookmark(tabState)
}
}
func tabToolbarDidPressBookmark(tabToolbar: TabToolbarProtocol, button: UIButton) {
guard let tab = tabManager.selectedTab,
let _ = tab.displayURL?.absoluteString else {
log.error("Bookmark error: No tab is selected, or no URL in tab.")
return
}
toggleBookmarkForTabState(tab.tabState)
}
func tabToolbarDidLongPressBookmark(tabToolbar: TabToolbarProtocol, button: UIButton) {
}
func tabToolbarDidPressShare(tabToolbar: TabToolbarProtocol, button: UIButton) {
if let tab = tabManager.selectedTab, url = tab.displayURL {
let sourceView = self.navigationToolbar.shareButton
presentActivityViewController(url, tab: tab, sourceView: sourceView.superview, sourceRect: sourceView.frame, arrowDirection: .Up)
}
}
func tabToolbarDidPressHomePage(tabToolbar: TabToolbarProtocol, button: UIButton) {
guard let tab = tabManager.selectedTab else { return }
HomePageHelper(prefs: profile.prefs).openHomePage(inTab: tab, withNavigationController: navigationController)
}
func showBackForwardList() {
guard AppConstants.MOZ_BACK_FORWARD_LIST else {
return
}
if let backForwardList = tabManager.selectedTab?.webView?.backForwardList {
let backForwardViewController = BackForwardListViewController(profile: profile, backForwardList: backForwardList, isPrivate: tabManager.selectedTab?.isPrivate ?? false)
backForwardViewController.tabManager = tabManager
backForwardViewController.bvc = self
backForwardViewController.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
backForwardViewController.backForwardTransitionDelegate = BackForwardListAnimator()
self.presentViewController(backForwardViewController, animated: true, completion: nil)
}
}
}
extension BrowserViewController: MenuViewControllerDelegate {
func menuViewControllerDidDismiss(menuViewController: MenuViewController) {
self.menuViewController = nil
displayedPopoverController = nil
updateDisplayedPopoverProperties = nil
}
func shouldCloseMenu(menuViewController: MenuViewController, forRotationToNewSize size: CGSize, forTraitCollection traitCollection: UITraitCollection) -> Bool {
// if we're presenting in popover but we haven't got a preferred content size yet, don't dismiss, otherwise we might dismiss before we've presented
if (traitCollection.horizontalSizeClass == .Compact && traitCollection.verticalSizeClass == .Compact) && menuViewController.preferredContentSize == CGSize.zero {
return false
}
func orientationForSize(size: CGSize) -> UIInterfaceOrientation {
return size.height < size.width ? .LandscapeLeft : .Portrait
}
let currentOrientation = orientationForSize(self.view.bounds.size)
let newOrientation = orientationForSize(size)
let isiPhone = UI_USER_INTERFACE_IDIOM() == .Phone
// we only want to dismiss when rotating on iPhone
// if we're rotating from landscape to portrait then we are rotating from popover to modal
return isiPhone && currentOrientation != newOrientation
}
}
extension BrowserViewController: WindowCloseHelperDelegate {
func windowCloseHelper(helper: WindowCloseHelper, didRequestToCloseTab tab: Tab) {
tabManager.removeTab(tab)
}
}
extension BrowserViewController: TabDelegate {
func tab(tab: Tab, didCreateWebView webView: WKWebView) {
webView.frame = webViewContainer.frame
// Observers that live as long as the tab. Make sure these are all cleared
// in willDeleteWebView below!
webView.addObserver(self, forKeyPath: KVOEstimatedProgress, options: .New, context: nil)
webView.addObserver(self, forKeyPath: KVOLoading, options: .New, context: nil)
webView.addObserver(self, forKeyPath: KVOCanGoBack, options: .New, context: nil)
webView.addObserver(self, forKeyPath: KVOCanGoForward, options: .New, context: nil)
tab.webView?.addObserver(self, forKeyPath: KVOURL, options: .New, context: nil)
webView.scrollView.addObserver(self.scrollController, forKeyPath: KVOContentSize, options: .New, context: nil)
webView.UIDelegate = self
let readerMode = ReaderMode(tab: tab)
readerMode.delegate = self
tab.addHelper(readerMode, name: ReaderMode.name())
let favicons = FaviconManager(tab: tab, profile: profile)
tab.addHelper(favicons, name: FaviconManager.name())
// only add the logins helper if the tab is not a private browsing tab
if !tab.isPrivate {
let logins = LoginsHelper(tab: tab, profile: profile)
tab.addHelper(logins, name: LoginsHelper.name())
}
let contextMenuHelper = ContextMenuHelper(tab: tab)
contextMenuHelper.delegate = self
tab.addHelper(contextMenuHelper, name: ContextMenuHelper.name())
let errorHelper = ErrorPageHelper()
tab.addHelper(errorHelper, name: ErrorPageHelper.name())
if #available(iOS 9, *) {} else {
let windowCloseHelper = WindowCloseHelper(tab: tab)
windowCloseHelper.delegate = self
tab.addHelper(windowCloseHelper, name: WindowCloseHelper.name())
}
let findInPageHelper = FindInPageHelper(tab: tab)
findInPageHelper.delegate = self
tab.addHelper(findInPageHelper, name: FindInPageHelper.name())
let noImageModeHelper = NoImageModeHelper(tab: tab)
tab.addHelper(noImageModeHelper, name: NoImageModeHelper.name())
let printHelper = PrintHelper(tab: tab)
tab.addHelper(printHelper, name: PrintHelper.name())
let customSearchHelper = CustomSearchHelper(tab: tab)
tab.addHelper(customSearchHelper, name: CustomSearchHelper.name())
let openURL = {(url: NSURL) -> Void in
self.switchToTabForURLOrOpen(url)
}
let nightModeHelper = NightModeHelper(tab: tab)
tab.addHelper(nightModeHelper, name: NightModeHelper.name())
let spotlightHelper = SpotlightHelper(tab: tab, openURL: openURL)
tab.addHelper(spotlightHelper, name: SpotlightHelper.name())
tab.addHelper(LocalRequestHelper(), name: LocalRequestHelper.name())
}
func tab(tab: Tab, willDeleteWebView webView: WKWebView) {
tab.cancelQueuedAlerts()
webView.removeObserver(self, forKeyPath: KVOEstimatedProgress)
webView.removeObserver(self, forKeyPath: KVOLoading)
webView.removeObserver(self, forKeyPath: KVOCanGoBack)
webView.removeObserver(self, forKeyPath: KVOCanGoForward)
webView.scrollView.removeObserver(self.scrollController, forKeyPath: KVOContentSize)
webView.removeObserver(self, forKeyPath: KVOURL)
webView.UIDelegate = nil
webView.scrollView.delegate = nil
webView.removeFromSuperview()
}
private func findSnackbar(barToFind: SnackBar) -> Int? {
let bars = snackBars.subviews
for (index, bar) in bars.enumerate() {
if bar === barToFind {
return index
}
}
return nil
}
private func updateSnackBarConstraints() {
snackBars.snp_remakeConstraints { make in
make.bottom.equalTo(findInPageContainer.snp_top)
let bars = self.snackBars.subviews
if bars.count > 0 {
let view = bars[bars.count-1]
make.top.equalTo(view.snp_top)
} else {
make.height.equalTo(0)
}
if traitCollection.horizontalSizeClass != .Regular {
make.leading.trailing.equalTo(self.footer)
self.snackBars.layer.borderWidth = 0
} else {
make.centerX.equalTo(self.footer)
make.width.equalTo(SnackBarUX.MaxWidth)
self.snackBars.layer.borderColor = UIConstants.BorderColor.CGColor
self.snackBars.layer.borderWidth = 1
}
}
}
// This removes the bar from its superview and updates constraints appropriately
private func finishRemovingBar(bar: SnackBar) {
// If there was a bar above this one, we need to remake its constraints.
if let index = findSnackbar(bar) {
// If the bar being removed isn't on the top of the list
let bars = snackBars.subviews
if index < bars.count-1 {
// Move the bar above this one
let nextbar = bars[index+1] as! SnackBar
nextbar.snp_updateConstraints { make in
// If this wasn't the bottom bar, attach to the bar below it
if index > 0 {
let bar = bars[index-1] as! SnackBar
nextbar.bottom = make.bottom.equalTo(bar.snp_top).constraint
} else {
// Otherwise, we attach it to the bottom of the snackbars
nextbar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).constraint
}
}
}
}
// Really remove the bar
bar.removeFromSuperview()
}
private func finishAddingBar(bar: SnackBar) {
snackBars.addSubview(bar)
bar.snp_remakeConstraints { make in
// If there are already bars showing, add this on top of them
let bars = self.snackBars.subviews
// Add the bar on top of the stack
// We're the new top bar in the stack, so make sure we ignore ourself
if bars.count > 1 {
let view = bars[bars.count - 2]
bar.bottom = make.bottom.equalTo(view.snp_top).offset(0).constraint
} else {
bar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).offset(0).constraint
}
make.leading.trailing.equalTo(self.snackBars)
}
}
func showBar(bar: SnackBar, animated: Bool) {
finishAddingBar(bar)
updateSnackBarConstraints()
bar.hide()
view.layoutIfNeeded()
UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in
bar.show()
self.view.layoutIfNeeded()
})
}
func removeBar(bar: SnackBar, animated: Bool) {
if let _ = findSnackbar(bar) {
UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in
bar.hide()
self.view.layoutIfNeeded()
}) { success in
// Really remove the bar
self.finishRemovingBar(bar)
self.updateSnackBarConstraints()
}
}
}
func removeAllBars() {
let bars = snackBars.subviews
for bar in bars {
if let bar = bar as? SnackBar {
bar.removeFromSuperview()
}
}
self.updateSnackBarConstraints()
}
func tab(tab: Tab, didAddSnackbar bar: SnackBar) {
showBar(bar, animated: true)
}
func tab(tab: Tab, didRemoveSnackbar bar: SnackBar) {
removeBar(bar, animated: true)
}
func tab(tab: Tab, didSelectFindInPageForSelection selection: String) {
updateFindInPageVisibility(visible: true)
findInPageBar?.text = selection
}
}
extension BrowserViewController: HomePanelViewControllerDelegate {
func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectURL url: NSURL, visitType: VisitType) {
finishEditingAndSubmit(url, visitType: visitType)
}
func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) {
if AboutUtils.isAboutHomeURL(tabManager.selectedTab?.url) {
tabManager.selectedTab?.webView?.evaluateJavaScript("history.replaceState({}, '', '#panel=\(panel)')", completionHandler: nil)
}
}
func homePanelViewControllerDidRequestToCreateAccount(homePanelViewController: HomePanelViewController) {
presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same
}
func homePanelViewControllerDidRequestToSignIn(homePanelViewController: HomePanelViewController) {
presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same
}
}
extension BrowserViewController: SearchViewControllerDelegate {
func searchViewController(searchViewController: SearchViewController, didSelectURL url: NSURL) {
finishEditingAndSubmit(url, visitType: VisitType.Typed)
}
func presentSearchSettingsController() {
let settingsNavigationController = SearchSettingsTableViewController()
settingsNavigationController.model = self.profile.searchEngines
let navController = UINavigationController(rootViewController: settingsNavigationController)
self.presentViewController(navController, animated: true, completion: nil)
}
}
extension BrowserViewController: TabManagerDelegate {
func tabManager(tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) {
// Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it
// and having multiple views with the same label confuses tests.
if let wv = previous?.webView {
removeOpenInView()
wv.endEditing(true)
wv.accessibilityLabel = nil
wv.accessibilityElementsHidden = true
wv.accessibilityIdentifier = nil
wv.removeFromSuperview()
}
if let tab = selected, webView = tab.webView {
updateURLBarDisplayURL(tab)
if tab.isPrivate {
readerModeCache = MemoryReaderModeCache.sharedInstance
applyTheme(Theme.PrivateMode)
} else {
readerModeCache = DiskReaderModeCache.sharedInstance
applyTheme(Theme.NormalMode)
}
ReaderModeHandlers.readerModeCache = readerModeCache
scrollController.tab = selected
webViewContainer.addSubview(webView)
webView.snp_makeConstraints { make in
make.top.equalTo(webViewContainerToolbar.snp_bottom)
make.left.right.bottom.equalTo(self.webViewContainer)
}
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.accessibilityIdentifier = "contentView"
webView.accessibilityElementsHidden = false
if let url = webView.URL?.absoluteString {
// Don't bother fetching bookmark state for about/sessionrestore and about/home.
if AboutUtils.isAboutURL(webView.URL) {
// Indeed, because we don't show the toolbar at all, don't even blank the star.
} else {
profile.bookmarks.modelFactory >>== { [weak tab] in
$0.isBookmarked(url)
.uponQueue(dispatch_get_main_queue()) {
guard let isBookmarked = $0.successValue else {
log.error("Error getting bookmark status: \($0.failureValue).")
return
}
tab?.isBookmarked = isBookmarked
if !AppConstants.MOZ_MENU {
self.toolbar?.updateBookmarkStatus(isBookmarked)
self.urlBar.updateBookmarkStatus(isBookmarked)
}
}
}
}
} else {
// The web view can go gray if it was zombified due to memory pressure.
// When this happens, the URL is nil, so try restoring the page upon selection.
tab.reload()
}
}
if let selected = selected, previous = previous where selected.isPrivate != previous.isPrivate {
updateTabCountUsingTabManager(tabManager)
}
removeAllBars()
if let bars = selected?.bars {
for bar in bars {
showBar(bar, animated: true)
}
}
updateFindInPageVisibility(visible: false)
navigationToolbar.updateReloadStatus(selected?.loading ?? false)
navigationToolbar.updateBackStatus(selected?.canGoBack ?? false)
navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false)
self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0))
if let readerMode = selected?.getHelper(name: ReaderMode.name()) as? ReaderMode {
urlBar.updateReaderModeState(readerMode.state)
if readerMode.state == .Active {
showReaderModeBar(animated: false)
} else {
hideReaderModeBar(animated: false)
}
} else {
urlBar.updateReaderModeState(ReaderModeState.Unavailable)
}
updateInContentHomePanel(selected?.url)
}
func tabManager(tabManager: TabManager, didCreateTab tab: Tab) {
}
func tabManager(tabManager: TabManager, didAddTab tab: Tab) {
// If we are restoring tabs then we update the count once at the end
if !tabManager.isRestoring {
updateTabCountUsingTabManager(tabManager)
}
tab.tabDelegate = self
tab.appStateDelegate = self
}
func tabManager(tabManager: TabManager, didRemoveTab tab: Tab) {
updateTabCountUsingTabManager(tabManager)
// tabDelegate is a weak ref (and the tab's webView may not be destroyed yet)
// so we don't expcitly unset it.
if let url = tab.url where !AboutUtils.isAboutURL(tab.url) && !tab.isPrivate {
profile.recentlyClosedTabs.addTab(url, title: tab.title, faviconURL: tab.displayFavicon?.url)
}
}
func tabManagerDidAddTabs(tabManager: TabManager) {
updateTabCountUsingTabManager(tabManager)
}
func tabManagerDidRestoreTabs(tabManager: TabManager) {
updateTabCountUsingTabManager(tabManager)
}
func tabManagerDidRemoveAllTabs(tabManager: TabManager, toast:ButtonToast?) {
guard !tabTrayController.privateMode else {
return
}
if let undoToast = toast {
let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(ButtonToastUX.ToastDelay * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {
self.view.addSubview(undoToast)
undoToast.snp_makeConstraints { make in
make.left.right.equalTo(self.view)
make.bottom.equalTo(self.webViewContainer)
}
undoToast.showToast()
}
}
}
private func updateTabCountUsingTabManager(tabManager: TabManager, animated: Bool = true) {
if let selectedTab = tabManager.selectedTab {
let count = selectedTab.isPrivate ? tabManager.privateTabs.count : tabManager.normalTabs.count
urlBar.updateTabCount(max(count, 1), animated: animated)
topTabsViewController?.updateTabCount(max(count, 1), animated: animated)
}
}
}
extension BrowserViewController: WKNavigationDelegate {
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
if tabManager.selectedTab?.webView !== webView {
return
}
updateFindInPageVisibility(visible: false)
// If we are going to navigate to a new page, hide the reader mode button. Unless we
// are going to a about:reader page. Then we keep it on screen: it will change status
// (orange color) as soon as the page has loaded.
if let url = webView.URL {
if !ReaderModeUtils.isReaderModeURL(url) {
urlBar.updateReaderModeState(ReaderModeState.Unavailable)
hideReaderModeBar(animated: false)
}
// remove the open in overlay view if it is present
removeOpenInView()
}
}
// Recognize an Apple Maps URL. This will trigger the native app. But only if a search query is present. Otherwise
// it could just be a visit to a regular page on maps.apple.com.
private func isAppleMapsURL(url: NSURL) -> Bool {
if url.scheme == "http" || url.scheme == "https" {
if url.host == "maps.apple.com" && url.query != nil {
return true
}
}
return false
}
// Recognize a iTunes Store URL. These all trigger the native apps. Note that appstore.com and phobos.apple.com
// used to be in this list. I have removed them because they now redirect to itunes.apple.com. If we special case
// them then iOS will actually first open Safari, which then redirects to the app store. This works but it will
// leave a 'Back to Safari' button in the status bar, which we do not want.
private func isStoreURL(url: NSURL) -> Bool {
if url.scheme == "http" || url.scheme == "https" {
if url.host == "itunes.apple.com" {
return true
}
}
return false
}
// This is the place where we decide what to do with a new navigation action. There are a number of special schemes
// and http(s) urls that need to be handled in a different way. All the logic for that is inside this delegate
// method.
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.URL else {
decisionHandler(WKNavigationActionPolicy.Cancel)
return
}
// Fixes 1261457 - Rich text editor fails because requests to about:blank are blocked
if url.scheme == "about" && url.resourceSpecifier == "blank" {
decisionHandler(WKNavigationActionPolicy.Allow)
return
}
if !navigationAction.isAllowed && navigationAction.navigationType != .BackForward {
log.warning("Denying unprivileged request: \(navigationAction.request)")
decisionHandler(WKNavigationActionPolicy.Cancel)
return
}
// First special case are some schemes that are about Calling. We prompt the user to confirm this action. This
// gives us the exact same behaviour as Safari.
if url.scheme == "tel" || url.scheme == "facetime" || url.scheme == "facetime-audio" {
if let phoneNumber = url.resourceSpecifier.stringByRemovingPercentEncoding where !phoneNumber.isEmpty {
let formatter = PhoneNumberFormatter()
let formattedPhoneNumber = formatter.formatPhoneNumber(phoneNumber)
let alert = UIAlertController(title: formattedPhoneNumber, message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Label for Cancel button"), style: UIAlertActionStyle.Cancel, handler: nil))
alert.addAction(UIAlertAction(title: NSLocalizedString("Call", comment:"Alert Call Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in
UIApplication.sharedApplication().openURL(url)
}))
presentViewController(alert, animated: true, completion: nil)
}
decisionHandler(WKNavigationActionPolicy.Cancel)
return
}
// Second special case are a set of URLs that look like regular http links, but should be handed over to iOS
// instead of being loaded in the webview. Note that there is no point in calling canOpenURL() here, because
// iOS will always say yes. TODO Is this the same as isWhitelisted?
if isAppleMapsURL(url) || isStoreURL(url) {
UIApplication.sharedApplication().openURL(url)
decisionHandler(WKNavigationActionPolicy.Cancel)
return
}
// This is the normal case, opening a http or https url, which we handle by loading them in this WKWebView. We
// always allow this.
if url.scheme == "http" || url.scheme == "https" {
if navigationAction.navigationType == .LinkActivated {
resetSpoofedUserAgentIfRequired(webView, newURL: url)
} else if navigationAction.navigationType == .BackForward {
restoreSpoofedUserAgentIfRequired(webView, newRequest: navigationAction.request)
}
decisionHandler(WKNavigationActionPolicy.Allow)
return
}
// Default to calling openURL(). What this does depends on the iOS version. On iOS 8, it will just work without
// prompting. On iOS9, depending on the scheme, iOS will prompt: "Firefox" wants to open "Twitter". It will ask
// every time. There is no way around this prompt. (TODO Confirm this is true by adding them to the Info.plist)
UIApplication.sharedApplication().openURL(url)
decisionHandler(WKNavigationActionPolicy.Cancel)
}
func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
// If this is a certificate challenge, see if the certificate has previously been
// accepted by the user.
let origin = "\(challenge.protectionSpace.host):\(challenge.protectionSpace.port)"
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
let trust = challenge.protectionSpace.serverTrust,
let cert = SecTrustGetCertificateAtIndex(trust, 0) where profile.certStore.containsCertificate(cert, forOrigin: origin) {
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: trust))
return
}
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic ||
challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest ||
challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM,
let tab = tabManager[webView] else {
completionHandler(NSURLSessionAuthChallengeDisposition.PerformDefaultHandling, nil)
return
}
// The challenge may come from a background tab, so ensure it's the one visible.
tabManager.selectTab(tab)
let loginsHelper = tab.getHelper(name: LoginsHelper.name()) as? LoginsHelper
Authenticator.handleAuthRequest(self, challenge: challenge, loginsHelper: loginsHelper).uponQueue(dispatch_get_main_queue()) { res in
if let credentials = res.successValue {
completionHandler(.UseCredential, credentials.credentials)
} else {
completionHandler(NSURLSessionAuthChallengeDisposition.RejectProtectionSpace, nil)
}
}
}
func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) {
guard let tab = tabManager[webView] else { return }
tab.url = webView.URL
if tabManager.selectedTab === tab {
updateUIForReaderHomeStateForTab(tab)
appDidUpdateState(getCurrentAppState())
}
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
let tab: Tab! = tabManager[webView]
tabManager.expireSnackbars()
if let url = webView.URL where !ErrorPageHelper.isErrorPageURL(url) && !AboutUtils.isAboutHomeURL(url) {
tab.lastExecutedTime = NSDate.now()
if navigation == nil {
log.warning("Implicitly unwrapped optional navigation was nil.")
}
postLocationChangeNotificationForTab(tab, navigation: navigation)
// Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore
// because that event wil not always fire due to unreliable page caching. This will either let us know that
// the currently loaded page can be turned into reading mode or if the page already is in reading mode. We
// ignore the result because we are being called back asynchronous when the readermode status changes.
webView.evaluateJavaScript("_firefox_ReaderMode.checkReadability()", completionHandler: nil)
}
if tab === tabManager.selectedTab {
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// must be followed by LayoutChanged, as ScreenChanged will make VoiceOver
// cursor land on the correct initial element, but if not followed by LayoutChanged,
// VoiceOver will sometimes be stuck on the element, not allowing user to move
// forward/backward. Strange, but LayoutChanged fixes that.
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
} else {
// To Screenshot a tab that is hidden we must add the webView,
// then wait enough time for the webview to render.
if let webView = tab.webView {
view.insertSubview(webView, atIndex: 0)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(500 * NSEC_PER_MSEC))
dispatch_after(time, dispatch_get_main_queue()) {
self.screenshotHelper.takeScreenshot(tab)
if webView.superview == self.view {
webView.removeFromSuperview()
}
}
}
}
// Remember whether or not a desktop site was requested
if #available(iOS 9.0, *) {
tab.desktopSite = webView.customUserAgent?.isEmpty == false
}
}
private func addViewForOpenInHelper(openInHelper: OpenInHelper) {
guard let view = openInHelper.openInView else { return }
webViewContainerToolbar.addSubview(view)
webViewContainerToolbar.snp_updateConstraints { make in
make.height.equalTo(OpenInViewUX.ViewHeight)
}
view.snp_makeConstraints { make in
make.edges.equalTo(webViewContainerToolbar)
}
self.openInHelper = openInHelper
}
private func removeOpenInView() {
guard let _ = self.openInHelper else { return }
webViewContainerToolbar.subviews.forEach { $0.removeFromSuperview() }
webViewContainerToolbar.snp_updateConstraints { make in
make.height.equalTo(0)
}
self.openInHelper = nil
}
private func postLocationChangeNotificationForTab(tab: Tab, navigation: WKNavigation?) {
let notificationCenter = NSNotificationCenter.defaultCenter()
var info = [NSObject: AnyObject]()
info["url"] = tab.displayURL
info["title"] = tab.title
if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue {
info["visitType"] = visitType
}
info["isPrivate"] = tab.isPrivate
notificationCenter.postNotificationName(NotificationOnLocationChange, object: self, userInfo: info)
}
}
/// List of schemes that are allowed to open a popup window
private let SchemesAllowedToOpenPopups = ["http", "https", "javascript", "data"]
extension BrowserViewController: WKUIDelegate {
func webView(webView: WKWebView, createWebViewWithConfiguration configuration: WKWebViewConfiguration, forNavigationAction navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
guard let parentTab = tabManager[webView] else { return nil }
if !navigationAction.isAllowed {
log.warning("Denying unprivileged request: \(navigationAction.request)")
return nil
}
if let currentTab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(currentTab)
}
// If the page uses window.open() or target="_blank", open the page in a new tab.
let newTab: Tab
if #available(iOS 9, *) {
newTab = tabManager.addTab(navigationAction.request, configuration: configuration, afterTab: parentTab, isPrivate: parentTab.isPrivate)
} else {
newTab = tabManager.addTab(navigationAction.request, configuration: configuration, afterTab: parentTab)
}
tabManager.selectTab(newTab)
// If the page we just opened has a bad scheme, we return nil here so that JavaScript does not
// get a reference to it which it can return from window.open() - this will end up as a
// CFErrorHTTPBadURL being presented.
guard let scheme = navigationAction.request.URL?.scheme.lowercaseString where SchemesAllowedToOpenPopups.contains(scheme) else {
return nil
}
return newTab.webView
}
private func canDisplayJSAlertForWebView(webView: WKWebView) -> Bool {
// Only display a JS Alert if we are selected and there isn't anything being shown
return (tabManager.selectedTab?.webView == webView ?? false) && (self.presentedViewController == nil)
}
func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) {
let messageAlert = MessageAlert(message: message, frame: frame, completionHandler: completionHandler)
if canDisplayJSAlertForWebView(webView) {
presentViewController(messageAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(messageAlert)
} else {
// This should never happen since an alert needs to come from a web view but just in case call the handler
// since not calling it will result in a runtime exception.
completionHandler()
}
}
func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) {
let confirmAlert = ConfirmPanelAlert(message: message, frame: frame, completionHandler: completionHandler)
if canDisplayJSAlertForWebView(webView) {
presentViewController(confirmAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(confirmAlert)
} else {
completionHandler(false)
}
}
func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String?) -> Void) {
let textInputAlert = TextInputAlert(message: prompt, frame: frame, completionHandler: completionHandler, defaultText: defaultText)
if canDisplayJSAlertForWebView(webView) {
presentViewController(textInputAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(textInputAlert)
} else {
completionHandler(nil)
}
}
/// Invoked when an error occurs while starting to load data for the main frame.
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
// Ignore the "Frame load interrupted" error that is triggered when we cancel a request
// to open an external application and hand it over to UIApplication.openURL(). The result
// will be that we switch to the external app, for example the app store, while keeping the
// original web page in the tab instead of replacing it with an error page.
if error.domain == "WebKitErrorDomain" && error.code == 102 {
return
}
if checkIfWebContentProcessHasCrashed(webView, error: error) {
return
}
if error.code == Int(CFNetworkErrors.CFURLErrorCancelled.rawValue) {
if let tab = tabManager[webView] where tab === tabManager.selectedTab {
urlBar.currentURL = tab.displayURL
}
return
}
if let url = error.userInfo[NSURLErrorFailingURLErrorKey] as? NSURL {
ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView)
}
}
private func checkIfWebContentProcessHasCrashed(webView: WKWebView, error: NSError) -> Bool {
if error.code == WKErrorCode.WebContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" {
log.debug("WebContent process has crashed. Trying to reloadFromOrigin to restart it.")
webView.reloadFromOrigin()
return true
}
return false
}
func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) {
let helperForURL = OpenIn.helperForResponse(navigationResponse.response)
if navigationResponse.canShowMIMEType {
if let openInHelper = helperForURL {
addViewForOpenInHelper(openInHelper)
}
decisionHandler(WKNavigationResponsePolicy.Allow)
return
}
guard let openInHelper = helperForURL else {
let error = NSError(domain: ErrorPageHelper.MozDomain, code: Int(ErrorPageHelper.MozErrorDownloadsNotEnabled), userInfo: [NSLocalizedDescriptionKey: Strings.UnableToDownloadError])
ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.URL!, inWebView: webView)
return decisionHandler(WKNavigationResponsePolicy.Allow)
}
openInHelper.open()
decisionHandler(WKNavigationResponsePolicy.Cancel)
}
@available(iOS 9, *)
func webViewDidClose(webView: WKWebView) {
if let tab = tabManager[webView] {
self.tabManager.removeTab(tab)
}
}
}
extension BrowserViewController: ReaderModeDelegate {
func readerMode(readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forTab tab: Tab) {
// If this reader mode availability state change is for the tab that we currently show, then update
// the button. Otherwise do nothing and the button will be updated when the tab is made active.
if tabManager.selectedTab === tab {
urlBar.updateReaderModeState(state)
}
}
func readerMode(readerMode: ReaderMode, didDisplayReaderizedContentForTab tab: Tab) {
self.showReaderModeBar(animated: true)
tab.showContent(true)
}
}
// MARK: - UIPopoverPresentationControllerDelegate
extension BrowserViewController: UIPopoverPresentationControllerDelegate {
func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
displayedPopoverController = nil
updateDisplayedPopoverProperties = nil
}
}
extension BrowserViewController: UIAdaptivePresentationControllerDelegate {
// Returning None here makes sure that the Popover is actually presented as a Popover and
// not as a full-screen modal, which is the default on compact device classes.
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
}
// MARK: - ReaderModeStyleViewControllerDelegate
extension BrowserViewController: ReaderModeStyleViewControllerDelegate {
func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) {
// Persist the new style to the profile
let encodedStyle: [String:AnyObject] = style.encode()
profile.prefs.setObject(encodedStyle, forKey: ReaderModeProfileKeyStyle)
// Change the reader mode style on all tabs that have reader mode active
for tabIndex in 0..<tabManager.count {
if let tab = tabManager[tabIndex] {
if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode {
if readerMode.state == ReaderModeState.Active {
readerMode.style = style
}
}
}
}
}
}
extension BrowserViewController {
func updateReaderModeBar() {
if let readerModeBar = readerModeBar {
if let tab = self.tabManager.selectedTab where tab.isPrivate {
readerModeBar.applyTheme(Theme.PrivateMode)
} else {
readerModeBar.applyTheme(Theme.NormalMode)
}
if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, record = successValue {
readerModeBar.unread = record.unread
readerModeBar.added = true
} else {
readerModeBar.unread = true
readerModeBar.added = false
}
} else {
readerModeBar.unread = true
readerModeBar.added = false
}
}
}
func showReaderModeBar(animated animated: Bool) {
if self.readerModeBar == nil {
let readerModeBar = ReaderModeBarView(frame: CGRectZero)
readerModeBar.delegate = self
view.insertSubview(readerModeBar, belowSubview: header)
self.readerModeBar = readerModeBar
}
updateReaderModeBar()
self.updateViewConstraints()
}
func hideReaderModeBar(animated animated: Bool) {
if let readerModeBar = self.readerModeBar {
readerModeBar.removeFromSuperview()
self.readerModeBar = nil
self.updateViewConstraints()
}
}
/// There are two ways we can enable reader mode. In the simplest case we open a URL to our internal reader mode
/// and be done with it. In the more complicated case, reader mode was already open for this page and we simply
/// navigated away from it. So we look to the left and right in the BackForwardList to see if a readerized version
/// of the current page is there. And if so, we go there.
func enableReaderMode() {
guard let tab = tabManager.selectedTab, webView = tab.webView else { return }
let backList = webView.backForwardList.backList
let forwardList = webView.backForwardList.forwardList
guard let currentURL = webView.backForwardList.currentItem?.URL, let readerModeURL = ReaderModeUtils.encodeURL(currentURL) else { return }
if backList.count > 1 && backList.last?.URL == readerModeURL {
webView.goToBackForwardListItem(backList.last!)
} else if forwardList.count > 0 && forwardList.first?.URL == readerModeURL {
webView.goToBackForwardListItem(forwardList.first!)
} else {
// Store the readability result in the cache and load it. This will later move to the ReadabilityHelper.
webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in
if let readabilityResult = ReadabilityResult(object: object) {
do {
try self.readerModeCache.put(currentURL, readabilityResult)
} catch _ {
}
if let nav = webView.loadRequest(PrivilegedRequest(URL: readerModeURL)) {
self.ignoreNavigationInTab(tab, navigation: nav)
}
}
})
}
}
/// Disabling reader mode can mean two things. In the simplest case we were opened from the reading list, which
/// means that there is nothing in the BackForwardList except the internal url for the reader mode page. In that
/// case we simply open a new page with the original url. In the more complicated page, the non-readerized version
/// of the page is either to the left or right in the BackForwardList. If that is the case, we navigate there.
func disableReaderMode() {
if let tab = tabManager.selectedTab,
let webView = tab.webView {
let backList = webView.backForwardList.backList
let forwardList = webView.backForwardList.forwardList
if let currentURL = webView.backForwardList.currentItem?.URL {
if let originalURL = ReaderModeUtils.decodeURL(currentURL) {
if backList.count > 1 && backList.last?.URL == originalURL {
webView.goToBackForwardListItem(backList.last!)
} else if forwardList.count > 0 && forwardList.first?.URL == originalURL {
webView.goToBackForwardListItem(forwardList.first!)
} else {
if let nav = webView.loadRequest(NSURLRequest(URL: originalURL)) {
self.ignoreNavigationInTab(tab, navigation: nav)
}
}
}
}
}
}
func SELDynamicFontChanged(notification: NSNotification) {
guard notification.name == NotificationDynamicFontChanged else { return }
var readerModeStyle = DefaultReaderModeStyle
if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let style = ReaderModeStyle(dict: dict) {
readerModeStyle = style
}
}
readerModeStyle.fontSize = ReaderModeFontSize.defaultSize
self.readerModeStyleViewController(ReaderModeStyleViewController(), didConfigureStyle: readerModeStyle)
}
}
extension BrowserViewController: ReaderModeBarViewDelegate {
func readerModeBar(readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) {
switch buttonType {
case .Settings:
if let readerMode = tabManager.selectedTab?.getHelper(name: "ReaderMode") as? ReaderMode where readerMode.state == ReaderModeState.Active {
var readerModeStyle = DefaultReaderModeStyle
if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let style = ReaderModeStyle(dict: dict) {
readerModeStyle = style
}
}
let readerModeStyleViewController = ReaderModeStyleViewController()
readerModeStyleViewController.delegate = self
readerModeStyleViewController.readerModeStyle = readerModeStyle
readerModeStyleViewController.modalPresentationStyle = UIModalPresentationStyle.Popover
let setupPopover = { [unowned self] in
if let popoverPresentationController = readerModeStyleViewController.popoverPresentationController {
popoverPresentationController.backgroundColor = UIColor.whiteColor()
popoverPresentationController.delegate = self
popoverPresentationController.sourceView = readerModeBar
popoverPresentationController.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: UIConstants.ToolbarHeight, width: 1, height: 1)
popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.Up
}
}
setupPopover()
if readerModeStyleViewController.popoverPresentationController != nil {
displayedPopoverController = readerModeStyleViewController
updateDisplayedPopoverProperties = setupPopover
}
self.presentViewController(readerModeStyleViewController, animated: true, completion: nil)
}
case .MarkAsRead:
if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, record = successValue {
profile.readingList?.updateRecord(record, unread: false) // TODO Check result, can this fail?
readerModeBar.unread = false
}
}
case .MarkAsUnread:
if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, record = successValue {
profile.readingList?.updateRecord(record, unread: true) // TODO Check result, can this fail?
readerModeBar.unread = true
}
}
case .AddToReadingList:
if let tab = tabManager.selectedTab,
let url = tab.url where ReaderModeUtils.isReaderModeURL(url) {
if let url = ReaderModeUtils.decodeURL(url) {
profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name) // TODO Check result, can this fail?
readerModeBar.added = true
readerModeBar.unread = true
}
}
case .RemoveFromReadingList:
if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, record = successValue {
profile.readingList?.deleteRecord(record) // TODO Check result, can this fail?
readerModeBar.added = false
readerModeBar.unread = false
}
}
}
}
}
extension BrowserViewController: IntroViewControllerDelegate {
func presentIntroViewController(force: Bool = false) -> Bool{
if force || profile.prefs.intForKey(IntroViewControllerSeenProfileKey) == nil {
let introViewController = IntroViewController()
introViewController.delegate = self
// On iPad we present it modally in a controller
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
introViewController.preferredContentSize = CGSize(width: IntroViewControllerUX.Width, height: IntroViewControllerUX.Height)
introViewController.modalPresentationStyle = UIModalPresentationStyle.FormSheet
}
presentViewController(introViewController, animated: true) {
self.profile.prefs.setInt(1, forKey: IntroViewControllerSeenProfileKey)
// On first run (and forced) open up the homepage in the background.
let state = self.getCurrentAppState()
if let homePageURL = HomePageAccessors.getHomePage(state), tab = self.tabManager.selectedTab where DeviceInfo.hasConnectivity() {
tab.loadRequest(NSURLRequest(URL: homePageURL))
}
}
return true
}
return false
}
func introViewControllerDidFinish(introViewController: IntroViewController) {
introViewController.dismissViewControllerAnimated(true) { finished in
if self.navigationController?.viewControllers.count > 1 {
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
}
func presentSignInViewController() {
// Show the settings page if we have already signed in. If we haven't then show the signin page
let vcToPresent: UIViewController
if profile.hasAccount() {
let settingsTableViewController = AppSettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
vcToPresent = settingsTableViewController
} else {
let signInVC = FxAContentViewController()
signInVC.delegate = self
signInVC.url = profile.accountConfiguration.signInURL
signInVC.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: #selector(BrowserViewController.dismissSignInViewController))
vcToPresent = signInVC
}
let settingsNavigationController = SettingsNavigationController(rootViewController: vcToPresent)
settingsNavigationController.modalPresentationStyle = .FormSheet
self.presentViewController(settingsNavigationController, animated: true, completion: nil)
}
func dismissSignInViewController() {
self.dismissViewControllerAnimated(true, completion: nil)
}
func introViewControllerDidRequestToLogin(introViewController: IntroViewController) {
introViewController.dismissViewControllerAnimated(true, completion: { () -> Void in
self.presentSignInViewController()
})
}
}
extension BrowserViewController: FxAContentViewControllerDelegate {
func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void {
if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil {
// The /settings endpoint sends a partial "login"; ignore it entirely.
log.debug("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.")
return
}
// TODO: Error handling.
let account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)!
profile.setAccount(account)
if let account = self.profile.getAccount() {
account.advance()
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func contentViewControllerDidCancel(viewController: FxAContentViewController) {
log.info("Did cancel out of FxA signin")
self.dismissViewControllerAnimated(true, completion: nil)
}
}
extension BrowserViewController: ContextMenuHelperDelegate {
func contextMenuHelper(contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UILongPressGestureRecognizer) {
// locationInView can return (0, 0) when the long press is triggered in an invalid page
// state (e.g., long pressing a link before the document changes, then releasing after a
// different page loads).
let touchPoint = gestureRecognizer.locationInView(view)
guard touchPoint != CGPointZero else { return }
let touchSize = CGSizeMake(0, 16)
let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
var dialogTitle: String?
if let url = elements.link, currentTab = tabManager.selectedTab {
dialogTitle = url.absoluteString
let isPrivate = currentTab.isPrivate
if !isPrivate {
let newTabTitle = NSLocalizedString("Open In New Tab", comment: "Context menu item for opening a link in a new tab")
let openNewTabAction = UIAlertAction(title: newTabTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) in
self.scrollController.showToolbars(animated: !self.scrollController.toolbarsShowing, completion: { _ in
self.tabManager.addTab(NSURLRequest(URL: url), afterTab: currentTab)
})
}
actionSheetController.addAction(openNewTabAction)
}
if #available(iOS 9, *) {
let openNewPrivateTabTitle = NSLocalizedString("Open In New Private Tab", tableName: "PrivateBrowsing", comment: "Context menu option for opening a link in a new private tab")
let openNewPrivateTabAction = UIAlertAction(title: openNewPrivateTabTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) in
self.scrollController.showToolbars(animated: !self.scrollController.toolbarsShowing, completion: { _ in
self.tabManager.addTab(NSURLRequest(URL: url), afterTab: currentTab, isPrivate: true)
})
}
actionSheetController.addAction(openNewPrivateTabAction)
}
let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard")
let copyAction = UIAlertAction(title: copyTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
let pasteBoard = UIPasteboard.generalPasteboard()
pasteBoard.URL = url
}
actionSheetController.addAction(copyAction)
let shareTitle = NSLocalizedString("Share Link", comment: "Context menu item for sharing a link URL")
let shareAction = UIAlertAction(title: shareTitle, style: UIAlertActionStyle.Default) { _ in
self.presentActivityViewController(url, sourceView: self.view, sourceRect: CGRect(origin: touchPoint, size: touchSize), arrowDirection: .Any)
}
actionSheetController.addAction(shareAction)
}
if let url = elements.image {
if dialogTitle == nil {
dialogTitle = url.absoluteString
}
let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus()
let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image")
let saveImageAction = UIAlertAction(title: saveImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
if photoAuthorizeStatus == PHAuthorizationStatus.Authorized || photoAuthorizeStatus == PHAuthorizationStatus.NotDetermined {
self.getImage(url) { UIImageWriteToSavedPhotosAlbum($0, nil, nil, nil) }
} else {
let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: UIAlertControllerStyle.Alert)
let dismissAction = UIAlertAction(title: UIConstants.CancelString, style: UIAlertActionStyle.Default, handler: nil)
accessDenied.addAction(dismissAction)
let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: UIAlertActionStyle.Default ) { (action: UIAlertAction!) -> Void in
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}
accessDenied.addAction(settingsAction)
self.presentViewController(accessDenied, animated: true, completion: nil)
}
}
actionSheetController.addAction(saveImageAction)
let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard")
let copyAction = UIAlertAction(title: copyImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
// put the actual image on the clipboard
// do this asynchronously just in case we're in a low bandwidth situation
let pasteboard = UIPasteboard.generalPasteboard()
pasteboard.URL = url
let changeCount = pasteboard.changeCount
let application = UIApplication.sharedApplication()
var taskId: UIBackgroundTaskIdentifier = 0
taskId = application.beginBackgroundTaskWithExpirationHandler { _ in
application.endBackgroundTask(taskId)
}
Alamofire.request(.GET, url)
.validate(statusCode: 200..<300)
.response { responseRequest, responseResponse, responseData, responseError in
// Only set the image onto the pasteboard if the pasteboard hasn't changed since
// fetching the image; otherwise, in low-bandwidth situations,
// we might be overwriting something that the user has subsequently added.
if changeCount == pasteboard.changeCount, let imageData = responseData where responseError == nil {
pasteboard.addImageWithData(imageData, forURL: url)
}
application.endBackgroundTask(taskId)
}
}
actionSheetController.addAction(copyAction)
}
// If we're showing an arrow popup, set the anchor to the long press location.
if let popoverPresentationController = actionSheetController.popoverPresentationController {
popoverPresentationController.sourceView = view
popoverPresentationController.sourceRect = CGRect(origin: touchPoint, size: touchSize)
popoverPresentationController.permittedArrowDirections = .Any
}
actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength)
let cancelAction = UIAlertAction(title: UIConstants.CancelString, style: UIAlertActionStyle.Cancel, handler: nil)
actionSheetController.addAction(cancelAction)
self.presentViewController(actionSheetController, animated: true, completion: nil)
}
private func getImage(url: NSURL, success: UIImage -> ()) {
Alamofire.request(.GET, url)
.validate(statusCode: 200..<300)
.response { _, _, data, _ in
if let data = data,
let image = UIImage.dataIsGIF(data) ? UIImage.imageFromGIFDataThreadSafe(data) : UIImage.imageFromDataThreadSafe(data) {
success(image)
}
}
}
}
/**
A third party search engine Browser extension
**/
extension BrowserViewController {
func addCustomSearchButtonToWebView(webView: WKWebView) {
//check if the search engine has already been added.
let domain = webView.URL?.domainURL().host
let matches = self.profile.searchEngines.orderedEngines.filter {$0.shortName == domain}
if !matches.isEmpty {
self.customSearchEngineButton.tintColor = UIColor.grayColor()
self.customSearchEngineButton.userInteractionEnabled = false
} else {
self.customSearchEngineButton.tintColor = UIConstants.SystemBlueColor
self.customSearchEngineButton.userInteractionEnabled = true
}
/*
This is how we access hidden views in the WKContentView
Using the public headers we can find the keyboard accessoryView which is not usually available.
Specific values here are from the WKContentView headers.
https://github.com/JaviSoto/iOS9-Runtime-Headers/blob/master/Frameworks/WebKit.framework/WKContentView.h
*/
guard let webContentView = UIView.findSubViewWithFirstResponder(webView) else {
/*
In some cases the URL bar can trigger the keyboard notification. In that case the webview isnt the first responder
and a search button should not be added.
*/
return
}
guard let input = webContentView.performSelector(Selector("inputAccessoryView")),
let inputView = input.takeUnretainedValue() as? UIInputView,
let nextButton = inputView.valueForKey("_nextItem") as? UIBarButtonItem,
let nextButtonView = nextButton.valueForKey("view") as? UIView else {
//failed to find the inputView instead lets use the inputAssistant
addCustomSearchButtonToInputAssistant(webContentView)
return
}
inputView.addSubview(self.customSearchEngineButton)
self.customSearchEngineButton.snp_remakeConstraints { make in
make.leading.equalTo(nextButtonView.snp_trailing).offset(20)
make.width.equalTo(inputView.snp_height)
make.top.equalTo(nextButtonView.snp_top)
make.height.equalTo(inputView.snp_height)
}
}
/**
This adds the customSearchButton to the inputAssistant
for cases where the inputAccessoryView could not be found for example
on the iPad where it does not exist. However this only works on iOS9
**/
func addCustomSearchButtonToInputAssistant(webContentView: UIView) {
if #available(iOS 9.0, *) {
guard customSearchBarButton == nil else {
return //The searchButton is already on the keyboard
}
let inputAssistant = webContentView.inputAssistantItem
let item = UIBarButtonItem(customView: customSearchEngineButton)
customSearchBarButton = item
inputAssistant.trailingBarButtonGroups.last?.barButtonItems.append(item)
}
}
func addCustomSearchEngineForFocusedElement() {
guard let webView = tabManager.selectedTab?.webView else {
return
}
webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in
guard let searchParams = result as? [String: String] else {
//Javascript responded with an incorrectly formatted message. Show an error.
let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch()
self.presentViewController(alert, animated: true, completion: nil)
return
}
self.addSearchEngine(searchParams)
self.customSearchEngineButton.tintColor = UIColor.grayColor()
self.customSearchEngineButton.userInteractionEnabled = false
}
}
func addSearchEngine(params: [String: String]) {
guard let template = params["url"] where template != "",
let iconString = params["icon"],
let iconURL = NSURL(string: iconString),
let url = NSURL(string: template.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())!),
let shortName = url.domainURL().host else {
let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch()
self.presentViewController(alert, animated: true, completion: nil)
return
}
let alert = ThirdPartySearchAlerts.addThirdPartySearchEngine { alert in
self.customSearchEngineButton.tintColor = UIColor.grayColor()
self.customSearchEngineButton.userInteractionEnabled = false
SDWebImageManager.sharedManager().downloadImageWithURL(iconURL, options: SDWebImageOptions.ContinueInBackground, progress: nil) { (image, error, cacheType, success, url) in
guard image != nil else {
let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch()
self.presentViewController(alert, animated: true, completion: nil)
return
}
self.profile.searchEngines.addSearchEngine(OpenSearchEngine(engineID: nil, shortName: shortName, image: image, searchTemplate: template, suggestTemplate: nil, isCustomEngine: true))
let Toast = SimpleToast()
Toast.showAlertWithText(Strings.ThirdPartySearchEngineAdded)
}
}
self.presentViewController(alert, animated: true, completion: {})
}
}
extension BrowserViewController: KeyboardHelperDelegate {
func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) {
keyboardState = state
updateViewConstraints()
UIView.animateWithDuration(state.animationDuration) {
UIView.setAnimationCurve(state.animationCurve)
self.findInPageContainer.layoutIfNeeded()
self.snackBars.layoutIfNeeded()
}
if let webView = tabManager.selectedTab?.webView {
webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in
guard let _ = result as? [String: String] else {
return
}
self.addCustomSearchButtonToWebView(webView)
}
}
}
func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) {
}
func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) {
keyboardState = nil
updateViewConstraints()
//If the searchEngineButton exists remove it form the keyboard
if #available(iOS 9.0, *) {
if let buttonGroup = customSearchBarButton?.buttonGroup {
buttonGroup.barButtonItems = buttonGroup.barButtonItems.filter { $0 != customSearchBarButton }
customSearchBarButton = nil
}
}
if self.customSearchEngineButton.superview != nil {
self.customSearchEngineButton.removeFromSuperview()
}
UIView.animateWithDuration(state.animationDuration) {
UIView.setAnimationCurve(state.animationCurve)
self.findInPageContainer.layoutIfNeeded()
self.snackBars.layoutIfNeeded()
}
}
}
extension BrowserViewController: TabTrayDelegate {
// This function animates and resets the tab chrome transforms when
// the tab tray dismisses.
func tabTrayDidDismiss(tabTray: TabTrayController) {
resetBrowserChrome()
}
func tabTrayDidAddBookmark(tab: Tab) {
guard let url = tab.url?.absoluteString where url.characters.count > 0 else { return }
self.addBookmark(tab.tabState)
}
func tabTrayDidAddToReadingList(tab: Tab) -> ReadingListClientRecord? {
guard let url = tab.url?.absoluteString where url.characters.count > 0 else { return nil }
return profile.readingList?.createRecordWithURL(url, title: tab.title ?? url, addedBy: UIDevice.currentDevice().name).successValue
}
func tabTrayRequestsPresentationOf(viewController viewController: UIViewController) {
self.presentViewController(viewController, animated: false, completion: nil)
}
}
// MARK: Browser Chrome Theming
extension BrowserViewController: Themeable {
func applyTheme(themeName: String) {
urlBar.applyTheme(themeName)
toolbar?.applyTheme(themeName)
readerModeBar?.applyTheme(themeName)
topTabsViewController?.applyTheme(themeName)
switch(themeName) {
case Theme.NormalMode:
header.blurStyle = .ExtraLight
footerBackground?.blurStyle = .ExtraLight
case Theme.PrivateMode:
header.blurStyle = .Dark
footerBackground?.blurStyle = .Dark
default:
log.debug("Unknown Theme \(themeName)")
}
}
}
// A small convienent class for wrapping a view with a blur background that can be modified
class BlurWrapper: UIView {
var blurStyle: UIBlurEffectStyle = .ExtraLight {
didSet {
let newEffect = UIVisualEffectView(effect: UIBlurEffect(style: blurStyle))
effectView.removeFromSuperview()
effectView = newEffect
insertSubview(effectView, belowSubview: wrappedView)
effectView.snp_remakeConstraints { make in
make.edges.equalTo(self)
}
effectView.hidden = disableBlur
switch blurStyle {
case .ExtraLight, .Light:
background.backgroundColor = TopTabsUX.TopTabsBackgroundNormalColor
case .Dark:
background.backgroundColor = TopTabsUX.TopTabsBackgroundPrivateColor
}
}
}
var disableBlur = false {
didSet {
effectView.hidden = disableBlur
background.hidden = !disableBlur
}
}
private var effectView: UIVisualEffectView
private var wrappedView: UIView
private lazy var background: UIView = {
let background = UIView()
background.hidden = true
return background
}()
init(view: UIView) {
wrappedView = view
effectView = UIVisualEffectView(effect: UIBlurEffect(style: blurStyle))
super.init(frame: CGRectZero)
addSubview(background)
addSubview(effectView)
addSubview(wrappedView)
effectView.snp_makeConstraints { make in
make.edges.equalTo(self)
}
wrappedView.snp_makeConstraints { make in
make.edges.equalTo(self)
}
background.snp_makeConstraints { make in
make.edges.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
protocol Themeable {
func applyTheme(themeName: String)
}
extension BrowserViewController: FindInPageBarDelegate, FindInPageHelperDelegate {
func findInPage(findInPage: FindInPageBar, didTextChange text: String) {
find(text, function: "find")
}
func findInPage(findInPage: FindInPageBar, didFindNextWithText text: String) {
findInPageBar?.endEditing(true)
find(text, function: "findNext")
}
func findInPage(findInPage: FindInPageBar, didFindPreviousWithText text: String) {
findInPageBar?.endEditing(true)
find(text, function: "findPrevious")
}
func findInPageDidPressClose(findInPage: FindInPageBar) {
updateFindInPageVisibility(visible: false)
}
private func find(text: String, function: String) {
guard let webView = tabManager.selectedTab?.webView else { return }
let escaped = text.stringByReplacingOccurrencesOfString("\\", withString: "\\\\")
.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
webView.evaluateJavaScript("__firefox__.\(function)(\"\(escaped)\")", completionHandler: nil)
}
func findInPageHelper(findInPageHelper: FindInPageHelper, didUpdateCurrentResult currentResult: Int) {
findInPageBar?.currentResult = currentResult
}
func findInPageHelper(findInPageHelper: FindInPageHelper, didUpdateTotalResults totalResults: Int) {
findInPageBar?.totalResults = totalResults
}
}
extension BrowserViewController: JSPromptAlertControllerDelegate {
func promptAlertControllerDidDismiss(alertController: JSPromptAlertController) {
showQueuedAlertIfAvailable()
}
}
private extension WKNavigationAction {
/// Allow local requests only if the request is privileged.
private var isAllowed: Bool {
guard let url = request.URL else {
return true
}
return !url.isWebPage() || !url.isLocal || request.isPrivileged
}
}
extension BrowserViewController: TopTabsDelegate {
func topTabsDidPressTabs() {
urlBar.leaveOverlayMode(didCancel: true)
self.urlBarDidPressTabs(urlBar)
}
func topTabsDidPressNewTab() {
let isPrivate = tabManager.selectedTab?.isPrivate ?? false
openBlankNewTabAndFocus(isPrivate: isPrivate)
}
func topTabsDidPressPrivateTab() {
guard let selectedTab = tabManager.selectedTab else {
return
}
urlBar.leaveOverlayMode()
if selectedTab.isPrivate {
if profile.prefs.boolForKey("settings.closePrivateTabs") ?? false {
tabManager.removeAllPrivateTabsAndNotify(false)
}
tabManager.selectTab(tabManager.normalTabs.last)
}
else {
if let privateTab = tabManager.privateTabs.last {
tabManager.selectTab(privateTab)
}
else {
openBlankNewTabAndFocus(isPrivate: true)
}
}
}
func topTabsDidChangeTab() {
urlBar.leaveOverlayMode(didCancel: true)
}
} | mpl-2.0 | c53a766d6c8106045ef43c8a2bdf57c9 | 42.935369 | 406 | 0.654194 | 5.918487 | false | false | false | false |
mshhmzh/firefox-ios | Providers/Profile.swift | 2 | 54417 | /* 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 Alamofire
import Foundation
import Account
import ReadingList
import Shared
import Storage
import Sync
import XCGLogger
import SwiftKeychainWrapper
import Deferred
private let log = Logger.syncLogger
public let NotificationProfileDidStartSyncing = "NotificationProfileDidStartSyncing"
public let NotificationProfileDidFinishSyncing = "NotificationProfileDidFinishSyncing"
public let ProfileRemoteTabsSyncDelay: NSTimeInterval = 0.1
public enum SyncDisplayState {
case InProgress
case Good
case Bad(message: String?)
case Stale(message: String)
func asObject() -> [String: String]? {
switch self {
case .Bad(let msg):
guard let message = msg else {
return ["state": "Error"]
}
return ["state": "Error",
"message": message]
case .Stale(let message):
return ["state": "Warning",
"message": message]
default:
break
}
return nil
}
}
public func ==(a: SyncDisplayState, b: SyncDisplayState) -> Bool {
switch (a, b) {
case (.InProgress, .InProgress): return true
case (.Good, .Good): return true
case (.Bad(let a), .Bad(let b)) where a == b: return true
case (.Stale(let a), .Stale(let b)) where a == b: return true
default: return false
}
}
public protocol SyncManager {
var isSyncing: Bool { get }
var lastSyncFinishTime: Timestamp? { get set }
var syncDisplayState: SyncDisplayState? { get }
func hasSyncedHistory() -> Deferred<Maybe<Bool>>
func hasSyncedLogins() -> Deferred<Maybe<Bool>>
func syncClients() -> SyncResult
func syncClientsThenTabs() -> SyncResult
func syncHistory() -> SyncResult
func syncLogins() -> SyncResult
func syncEverything() -> Success
// The simplest possible approach.
func beginTimedSyncs()
func endTimedSyncs()
func applicationDidEnterBackground()
func applicationDidBecomeActive()
func onNewProfile()
func onRemovedAccount(account: FirefoxAccount?) -> Success
func onAddedAccount() -> Success
}
typealias EngineIdentifier = String
typealias SyncFunction = (SyncDelegate, Prefs, Ready) -> SyncResult
private typealias EngineStatus = (EngineIdentifier, SyncStatus)
class ProfileFileAccessor: FileAccessor {
convenience init(profile: Profile) {
self.init(localName: profile.localName())
}
init(localName: String) {
let profileDirName = "profile.\(localName)"
// Bug 1147262: First option is for device, second is for simulator.
var rootPath: NSString
if let sharedContainerIdentifier = AppInfo.sharedContainerIdentifier(), url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(sharedContainerIdentifier), path = url.path {
rootPath = path as NSString
} else {
log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.")
rootPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]) as NSString
}
super.init(rootPath: rootPath.stringByAppendingPathComponent(profileDirName))
}
}
class CommandStoringSyncDelegate: SyncDelegate {
let profile: Profile
init() {
profile = BrowserProfile(localName: "profile", app: nil)
}
func displaySentTabForURL(URL: NSURL, title: String) {
let item = ShareItem(url: URL.absoluteString, title: title, favicon: nil)
self.profile.queue.addToQueue(item)
}
}
/**
* This exists because the Sync code is extension-safe, and thus doesn't get
* direct access to UIApplication.sharedApplication, which it would need to
* display a notification.
* This will also likely be the extension point for wipes, resets, and
* getting access to data sources during a sync.
*/
let TabSendURLKey = "TabSendURL"
let TabSendTitleKey = "TabSendTitle"
let TabSendCategory = "TabSendCategory"
enum SentTabAction: String {
case View = "TabSendViewAction"
case Bookmark = "TabSendBookmarkAction"
case ReadingList = "TabSendReadingListAction"
}
class BrowserProfileSyncDelegate: SyncDelegate {
let app: UIApplication
init(app: UIApplication) {
self.app = app
}
// SyncDelegate
func displaySentTabForURL(URL: NSURL, title: String) {
// check to see what the current notification settings are and only try and send a notification if
// the user has agreed to them
if let currentSettings = app.currentUserNotificationSettings() {
if currentSettings.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 {
if Logger.logPII {
log.info("Displaying notification for URL \(URL.absoluteString)")
}
let notification = UILocalNotification()
notification.fireDate = NSDate()
notification.timeZone = NSTimeZone.defaultTimeZone()
notification.alertBody = String(format: NSLocalizedString("New tab: %@: %@", comment:"New tab [title] [url]"), title, URL.absoluteString)
notification.userInfo = [TabSendURLKey: URL.absoluteString, TabSendTitleKey: title]
notification.alertAction = nil
notification.category = TabSendCategory
app.presentLocalNotificationNow(notification)
}
}
}
}
/**
* A Profile manages access to the user's data.
*/
protocol Profile: class {
var bookmarks: protocol<BookmarksModelFactorySource, ShareToDestination, SyncableBookmarks, LocalItemSource, MirrorItemSource> { get }
// var favicons: Favicons { get }
var prefs: Prefs { get }
var queue: TabQueue { get }
var searchEngines: SearchEngines { get }
var files: FileAccessor { get }
var history: protocol<BrowserHistory, SyncableHistory, ResettableSyncStorage> { get }
var favicons: Favicons { get }
var readingList: ReadingListService? { get }
var logins: protocol<BrowserLogins, SyncableLogins, ResettableSyncStorage> { get }
var certStore: CertStore { get }
var recentlyClosedTabs: ClosedTabsStore { get }
func shutdown()
// I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter.
// Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>.
func localName() -> String
// URLs and account configuration.
var accountConfiguration: FirefoxAccountConfiguration { get }
// Do we have an account at all?
func hasAccount() -> Bool
// Do we have an account that (as far as we know) is in a syncable state?
func hasSyncableAccount() -> Bool
func getAccount() -> FirefoxAccount?
func removeAccount()
func setAccount(account: FirefoxAccount)
func getClients() -> Deferred<Maybe<[RemoteClient]>>
func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>>
func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>>
func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>>
func sendItems(items: [ShareItem], toClients clients: [RemoteClient])
var syncManager: SyncManager { get }
}
public class BrowserProfile: Profile {
private let name: String
internal let files: FileAccessor
weak private var app: UIApplication?
/**
* N.B., BrowserProfile is used from our extensions, often via a pattern like
*
* BrowserProfile(…).foo.saveSomething(…)
*
* This can break if BrowserProfile's initializer does async work that
* subsequently — and asynchronously — expects the profile to stick around:
* see Bug 1218833. Be sure to only perform synchronous actions here.
*/
init(localName: String, app: UIApplication?, clear: Bool = false) {
log.debug("Initing profile \(localName) on thread \(NSThread.currentThread()).")
self.name = localName
self.files = ProfileFileAccessor(localName: localName)
self.app = app
if clear {
do {
try NSFileManager.defaultManager().removeItemAtPath(self.files.rootPath as String)
} catch {
log.info("Cannot clear profile: \(error)")
}
}
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: #selector(BrowserProfile.onLocationChange(_:)), name: NotificationOnLocationChange, object: nil)
notificationCenter.addObserver(self, selector: #selector(BrowserProfile.onProfileDidFinishSyncing(_:)), name: NotificationProfileDidFinishSyncing, object: nil)
notificationCenter.addObserver(self, selector: #selector(BrowserProfile.onPrivateDataClearedHistory(_:)), name: NotificationPrivateDataClearedHistory, object: nil)
if let baseBundleIdentifier = AppInfo.baseBundleIdentifier() {
KeychainWrapper.serviceName = baseBundleIdentifier
} else {
log.error("Unable to get the base bundle identifier. Keychain data will not be shared.")
}
// If the profile dir doesn't exist yet, this is first run (for this profile).
if !files.exists("") {
log.info("New profile. Removing old account metadata.")
self.removeAccountMetadata()
self.syncManager.onNewProfile()
self.removeExistingAuthenticationInfo()
prefs.clearAll()
}
// Always start by needing invalidation.
// This is the same as self.history.setTopSitesNeedsInvalidation, but without the
// side-effect of instantiating SQLiteHistory (and thus BrowserDB) on the main thread.
prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid)
if isChinaEdition {
// On first run, set the Home button to be in the toolbar.
if prefs.boolForKey(PrefsKeys.KeyHomePageButtonIsInMenu) == nil {
prefs.setBool(false, forKey: PrefsKeys.KeyHomePageButtonIsInMenu)
}
// Set the default homepage.
prefs.setString(PrefsDefaults.ChineseHomePageURL, forKey: PrefsKeys.KeyDefaultHomePageURL)
if prefs.stringForKey(PrefsKeys.KeyNewTab) == nil {
prefs.setString(PrefsDefaults.ChineseNewTabDefault, forKey: PrefsKeys.KeyNewTab)
}
} else {
// Remove the default homepage. This does not change the user's preference,
// just the behaviour when there is no homepage.
prefs.removeObjectForKey(PrefsKeys.KeyDefaultHomePageURL)
}
}
// Extensions don't have a UIApplication.
convenience init(localName: String) {
self.init(localName: localName, app: nil)
}
func shutdown() {
log.debug("Shutting down profile.")
if self.dbCreated {
db.forceClose()
}
if self.loginsDBCreated {
loginsDB.forceClose()
}
}
@objc
func onLocationChange(notification: NSNotification) {
if let v = notification.userInfo!["visitType"] as? Int,
let visitType = VisitType(rawValue: v),
let url = notification.userInfo!["url"] as? NSURL where !isIgnoredURL(url),
let title = notification.userInfo!["title"] as? NSString {
// Only record local vists if the change notification originated from a non-private tab
if !(notification.userInfo!["isPrivate"] as? Bool ?? false) {
// We don't record a visit if no type was specified -- that means "ignore me".
let site = Site(url: url.absoluteString, title: title as String)
let visit = SiteVisit(site: site, date: NSDate.nowMicroseconds(), type: visitType)
history.addLocalVisit(visit)
}
history.setTopSitesNeedsInvalidation()
} else {
log.debug("Ignoring navigation.")
}
}
// These selectors run on which ever thread sent the notifications (not the main thread)
@objc
func onProfileDidFinishSyncing(notification: NSNotification) {
history.setTopSitesNeedsInvalidation()
}
@objc
func onPrivateDataClearedHistory(notification: NSNotification) {
// Immediately invalidate the top sites cache
history.refreshTopSitesCache()
}
deinit {
log.debug("Deiniting profile \(self.localName).")
self.syncManager.endTimedSyncs()
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationOnLocationChange, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationPrivateDataClearedHistory, object: nil)
}
func localName() -> String {
return name
}
lazy var queue: TabQueue = {
withExtendedLifetime(self.history) {
return SQLiteQueue(db: self.db)
}
}()
private var dbCreated = false
var db: BrowserDB {
struct Singleton {
static var token: dispatch_once_t = 0
static var instance: BrowserDB!
}
dispatch_once(&Singleton.token) {
Singleton.instance = BrowserDB(filename: "browser.db", files: self.files)
self.dbCreated = true
}
return Singleton.instance
}
/**
* Favicons, history, and bookmarks are all stored in one intermeshed
* collection of tables.
*
* Any other class that needs to access any one of these should ensure
* that this is initialized first.
*/
private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory, ResettableSyncStorage> = {
return SQLiteHistory(db: self.db, prefs: self.prefs)!
}()
var favicons: Favicons {
return self.places
}
var history: protocol<BrowserHistory, SyncableHistory, ResettableSyncStorage> {
return self.places
}
lazy var bookmarks: protocol<BookmarksModelFactorySource, ShareToDestination, SyncableBookmarks, LocalItemSource, MirrorItemSource> = {
// Make sure the rest of our tables are initialized before we try to read them!
// This expression is for side-effects only.
withExtendedLifetime(self.places) {
return MergedSQLiteBookmarks(db: self.db)
}
}()
lazy var mirrorBookmarks: protocol<BookmarkBufferStorage, BufferItemSource> = {
// Yeah, this is lazy. Sorry.
return self.bookmarks as! MergedSQLiteBookmarks
}()
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs, files: self.files)
}()
func makePrefs() -> Prefs {
return NSUserDefaultsPrefs(prefix: self.localName())
}
lazy var prefs: Prefs = {
return self.makePrefs()
}()
lazy var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath as String)
}()
lazy var remoteClientsAndTabs: protocol<RemoteClientsAndTabs, ResettableSyncStorage, AccountRemovalDelegate> = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
lazy var syncManager: SyncManager = {
return BrowserSyncManager(profile: self)
}()
lazy var certStore: CertStore = {
return CertStore()
}()
lazy var recentlyClosedTabs: ClosedTabsStore = {
return ClosedTabsStore(prefs: self.prefs)
}()
private func getSyncDelegate() -> SyncDelegate {
if let app = self.app {
return BrowserProfileSyncDelegate(app: app)
}
return CommandStoringSyncDelegate()
}
public func getClients() -> Deferred<Maybe<[RemoteClient]>> {
return self.syncManager.syncClients()
>>> { self.remoteClientsAndTabs.getClients() }
}
public func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return self.syncManager.syncClientsThenTabs()
>>> { self.remoteClientsAndTabs.getClientsAndTabs() }
}
public func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return self.remoteClientsAndTabs.getClientsAndTabs()
}
func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs)
}
public func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) {
let commands = items.map { item in
SyncCommand.fromShareItem(item, withAction: "displayURI")
}
self.remoteClientsAndTabs.insertCommands(commands, forClients: clients) >>> { self.syncManager.syncClients() }
}
lazy var logins: protocol<BrowserLogins, SyncableLogins, ResettableSyncStorage> = {
return SQLiteLogins(db: self.loginsDB)
}()
// This is currently only used within the dispatch_once block in loginsDB, so we don't
// have to worry about races giving us two keys. But if this were ever to be used
// elsewhere, it'd be unsafe, so we wrap this in a dispatch_once, too.
private var loginsKey: String? {
let key = "sqlcipher.key.logins.db"
struct Singleton {
static var token: dispatch_once_t = 0
static var instance: String!
}
dispatch_once(&Singleton.token) {
if KeychainWrapper.hasValueForKey(key) {
let value = KeychainWrapper.stringForKey(key)
Singleton.instance = value
} else {
let Length: UInt = 256
let secret = Bytes.generateRandomBytes(Length).base64EncodedString
KeychainWrapper.setString(secret, forKey: key)
Singleton.instance = secret
}
}
return Singleton.instance
}
private var loginsDBCreated = false
private lazy var loginsDB: BrowserDB = {
struct Singleton {
static var token: dispatch_once_t = 0
static var instance: BrowserDB!
}
dispatch_once(&Singleton.token) {
Singleton.instance = BrowserDB(filename: "logins.db", secretKey: self.loginsKey, files: self.files)
self.loginsDBCreated = true
}
return Singleton.instance
}()
var isChinaEdition: Bool {
let locale = NSLocale.currentLocale()
return prefs.boolForKey("useChinaSyncService") ?? (locale.localeIdentifier == "zh_CN")
}
var accountConfiguration: FirefoxAccountConfiguration {
if isChinaEdition {
return ChinaEditionFirefoxAccountConfiguration()
}
return ProductionFirefoxAccountConfiguration()
}
private lazy var account: FirefoxAccount? = {
if let dictionary = KeychainWrapper.objectForKey(self.name + ".account") as? [String: AnyObject] {
return FirefoxAccount.fromDictionary(dictionary)
}
return nil
}()
func hasAccount() -> Bool {
return account != nil
}
func hasSyncableAccount() -> Bool {
return account?.actionNeeded == FxAActionNeeded.None
}
func getAccount() -> FirefoxAccount? {
return account
}
func removeAccountMetadata() {
self.prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime)
KeychainWrapper.removeObjectForKey(self.name + ".account")
}
func removeExistingAuthenticationInfo() {
KeychainWrapper.setAuthenticationInfo(nil)
}
func removeAccount() {
let old = self.account
removeAccountMetadata()
self.account = nil
// Tell any observers that our account has changed.
NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil)
// Trigger cleanup. Pass in the account in case we want to try to remove
// client-specific data from the server.
self.syncManager.onRemovedAccount(old)
// Deregister for remote notifications.
app?.unregisterForRemoteNotifications()
}
func setAccount(account: FirefoxAccount) {
KeychainWrapper.setObject(account.asDictionary(), forKey: name + ".account")
self.account = account
// register for notifications for the account
registerForNotifications()
// tell any observers that our account has changed
let userInfo = [NotificationUserInfoKeyHasSyncableAccount: hasSyncableAccount()]
NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil, userInfo: userInfo)
self.syncManager.onAddedAccount()
}
func registerForNotifications() {
let viewAction = UIMutableUserNotificationAction()
viewAction.identifier = SentTabAction.View.rawValue
viewAction.title = NSLocalizedString("View", comment: "View a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
viewAction.activationMode = UIUserNotificationActivationMode.Foreground
viewAction.destructive = false
viewAction.authenticationRequired = false
let bookmarkAction = UIMutableUserNotificationAction()
bookmarkAction.identifier = SentTabAction.Bookmark.rawValue
bookmarkAction.title = NSLocalizedString("Bookmark", comment: "Bookmark a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
bookmarkAction.activationMode = UIUserNotificationActivationMode.Foreground
bookmarkAction.destructive = false
bookmarkAction.authenticationRequired = false
let readingListAction = UIMutableUserNotificationAction()
readingListAction.identifier = SentTabAction.ReadingList.rawValue
readingListAction.title = NSLocalizedString("Add to Reading List", comment: "Add URL to the reading list - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
readingListAction.activationMode = UIUserNotificationActivationMode.Foreground
readingListAction.destructive = false
readingListAction.authenticationRequired = false
let sentTabsCategory = UIMutableUserNotificationCategory()
sentTabsCategory.identifier = TabSendCategory
sentTabsCategory.setActions([readingListAction, bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Default)
sentTabsCategory.setActions([bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Minimal)
app?.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: [sentTabsCategory]))
app?.registerForRemoteNotifications()
}
// Extends NSObject so we can use timers.
class BrowserSyncManager: NSObject, SyncManager {
// We shouldn't live beyond our containing BrowserProfile, either in the main app or in
// an extension.
// But it's possible that we'll finish a side-effect sync after we've ditched the profile
// as a whole, so we hold on to our Prefs, potentially for a little while longer. This is
// safe as a strong reference, because there's no cycle.
unowned private let profile: BrowserProfile
private let prefs: Prefs
let FifteenMinutes = NSTimeInterval(60 * 15)
let OneMinute = NSTimeInterval(60)
private var syncTimer: NSTimer? = nil
private var backgrounded: Bool = true
func applicationDidEnterBackground() {
self.backgrounded = true
self.endTimedSyncs()
}
func applicationDidBecomeActive() {
self.backgrounded = false
guard self.profile.hasSyncableAccount() else {
return
}
self.beginTimedSyncs()
// Sync now if it's been more than our threshold.
let now = NSDate.now()
let then = self.lastSyncFinishTime ?? 0
guard now >= then else {
log.debug("Time was modified since last sync.")
self.syncEverythingSoon()
return
}
let since = now - then
log.debug("\(since)msec since last sync.")
if since > SyncConstants.SyncOnForegroundMinimumDelayMillis {
self.syncEverythingSoon()
}
}
/**
* Locking is managed by syncSeveral. Make sure you take and release these
* whenever you do anything Sync-ey.
*/
private let syncLock = NSRecursiveLock()
var isSyncing: Bool {
syncLock.lock()
defer { syncLock.unlock() }
return syncDisplayState != nil && syncDisplayState! == .InProgress
}
var syncDisplayState: SyncDisplayState?
// The dispatch queue for coordinating syncing and resetting the database.
private let syncQueue = dispatch_queue_create("com.mozilla.firefox.sync", DISPATCH_QUEUE_SERIAL)
private typealias EngineResults = [(EngineIdentifier, SyncStatus)]
private typealias EngineTasks = [(EngineIdentifier, SyncFunction)]
// Used as a task queue for syncing.
private var syncReducer: AsyncReducer<EngineResults, EngineTasks>?
private func beginSyncing() {
notifySyncing(NotificationProfileDidStartSyncing)
}
private func endSyncing(result: Maybe<EngineResults>?) {
// loop through status's and fill sync state
syncLock.lock()
defer { syncLock.unlock() }
log.info("Ending all queued syncs.")
syncDisplayState = displayStateForEngineResults(result)
reportEndSyncingStatus(syncDisplayState, engineResults: result)
notifySyncing(NotificationProfileDidFinishSyncing)
syncReducer = nil
}
private func reportEndSyncingStatus(displayState: SyncDisplayState?, engineResults: Maybe<EngineResults>?) {
// We don't send this ad hoc telemetry on the release channel.
guard AppConstants.BuildChannel != AppBuildChannel.Release else {
return
}
guard profile.prefs.boolForKey("settings.sendUsageData") ?? true else {
log.debug("Profile isn't sending usage data. Not sending sync status event.")
return
}
guard let displayState = displayState else {
log.debug("Sync display state not set!. Not sending sync status event.")
return
}
self.doInBackgroundAfter(millis: 300) {
self.profile.remoteClientsAndTabs.getClientGUIDs() >>== { clients in
// We would love to include the version and OS etc. of each remote client,
// but we don't store that information. For now, just do a count.
let clientCount = clients.count
let id = DeviceInfo.clientIdentifier(self.prefs)
var engineResultsDict: [String: String]? = nil
if let results = engineResults?.successValue {
engineResultsDict = [:]
results.forEach { (engineIdentifier, syncStatus) in
engineResultsDict![engineIdentifier] = syncStatus.description
}
}
let engineResultsFailure = engineResults?.failureValue
let ping = makeAdHocSyncStatusPing(
NSBundle.mainBundle(),
clientID: id,
statusObject: displayState.asObject(),
engineResults: engineResultsDict,
resultsFailure: engineResultsFailure,
clientCount: clientCount
)
let payload = ping.toString()
log.debug("Payload is: \(payload)")
guard let body = payload.dataUsingEncoding(NSUTF8StringEncoding) else {
log.debug("Invalid JSON!")
return
}
let url = "https://mozilla-anonymous-sync-metrics.moo.mx/post/syncstatus".asURL!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = body
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.Manager.sharedInstance.request(request).response { (request, response, data, error) in
log.debug("Sync Status upload response: \(response?.statusCode ?? -1).")
}
}
}
}
private func notifySyncing(notification: String) {
NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: notification, object: syncDisplayState?.asObject()))
}
init(profile: BrowserProfile) {
self.profile = profile
self.prefs = profile.prefs
super.init()
let center = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: #selector(BrowserSyncManager.onDatabaseWasRecreated(_:)), name: NotificationDatabaseWasRecreated, object: nil)
center.addObserver(self, selector: #selector(BrowserSyncManager.onLoginDidChange(_:)), name: NotificationDataLoginDidChange, object: nil)
center.addObserver(self, selector: #selector(BrowserSyncManager.onStartSyncing(_:)), name: NotificationProfileDidStartSyncing, object: nil)
center.addObserver(self, selector: #selector(BrowserSyncManager.onFinishSyncing(_:)), name: NotificationProfileDidFinishSyncing, object: nil)
center.addObserver(self, selector: #selector(BrowserSyncManager.onBookmarkBufferValidated(_:)), name: NotificationBookmarkBufferValidated, object: nil)
}
func onBookmarkBufferValidated(notification: NSNotification) {
// We don't send this ad hoc telemetry on the release channel.
guard AppConstants.BuildChannel != AppBuildChannel.Release else {
return
}
guard profile.prefs.boolForKey("settings.sendUsageData") ?? true else {
log.debug("Profile isn't sending usage data. Not sending bookmark event.")
return
}
guard let validations = (notification.object as? Box<[String: Bool]>)?.value else {
log.warning("Notification didn't have validations.")
return
}
let attempt: Int32 = self.prefs.intForKey("bookmarkvalidationattempt") ?? 1
self.prefs.setInt(attempt + 1, forKey: "bookmarkvalidationattempt")
// Capture the buffer count ASAP, not in the delayed op, because the merge could wipe it!
let bufferRows = (self.profile.bookmarks as? MergedSQLiteBookmarks)?.synchronousBufferCount()
self.doInBackgroundAfter(millis: 300) {
self.profile.remoteClientsAndTabs.getClientGUIDs() >>== { clients in
// We would love to include the version and OS etc. of each remote client,
// but we don't store that information. For now, just do a count.
let clientCount = clients.count
let id = DeviceInfo.clientIdentifier(self.prefs)
let ping = makeAdHocBookmarkMergePing(NSBundle.mainBundle(), clientID: id, attempt: attempt, bufferRows: bufferRows, valid: validations, clientCount: clientCount)
let payload = ping.toString()
log.debug("Payload is: \(payload)")
guard let body = payload.dataUsingEncoding(NSUTF8StringEncoding) else {
log.debug("Invalid JSON!")
return
}
let url = "https://mozilla-anonymous-sync-metrics.moo.mx/post/bookmarkvalidation".asURL!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = body
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.Manager.sharedInstance.request(request).response { (request, response, data, error) in
log.debug("Bookmark validation upload response: \(response?.statusCode ?? -1).")
}
}
}
}
deinit {
// Remove 'em all.
let center = NSNotificationCenter.defaultCenter()
center.removeObserver(self, name: NotificationDatabaseWasRecreated, object: nil)
center.removeObserver(self, name: NotificationDataLoginDidChange, object: nil)
center.removeObserver(self, name: NotificationProfileDidStartSyncing, object: nil)
center.removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil)
center.removeObserver(self, name: NotificationBookmarkBufferValidated, object: nil)
}
private func handleRecreationOfDatabaseNamed(name: String?) -> Success {
let loginsCollections = ["passwords"]
let browserCollections = ["bookmarks", "history", "tabs"]
switch name ?? "<all>" {
case "<all>":
return self.locallyResetCollections(loginsCollections + browserCollections)
case "logins.db":
return self.locallyResetCollections(loginsCollections)
case "browser.db":
return self.locallyResetCollections(browserCollections)
default:
log.debug("Unknown database \(name).")
return succeed()
}
}
func doInBackgroundAfter(millis millis: Int64, _ block: dispatch_block_t) {
let delay = millis * Int64(NSEC_PER_MSEC)
let when = dispatch_time(DISPATCH_TIME_NOW, delay)
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
dispatch_after(when, queue, block)
}
@objc
func onDatabaseWasRecreated(notification: NSNotification) {
log.debug("Database was recreated.")
let name = notification.object as? String
log.debug("Database was \(name).")
// We run this in the background after a few hundred milliseconds;
// it doesn't really matter when it runs, so long as it doesn't
// happen in the middle of a sync.
let resetDatabase = {
return self.handleRecreationOfDatabaseNamed(name) >>== {
log.debug("Reset of \(name) done")
}
}
self.doInBackgroundAfter(millis: 300) {
self.syncLock.lock()
defer { self.syncLock.unlock() }
// If we're syncing already, then wait for sync to end,
// then reset the database on the same serial queue.
if let reducer = self.syncReducer where !reducer.isFilled {
reducer.terminal.upon { _ in
dispatch_async(self.syncQueue, resetDatabase)
}
} else {
// Otherwise, reset the database on the sync queue now
// Sync can't start while this is still going on.
dispatch_async(self.syncQueue, resetDatabase)
}
}
}
// Simple in-memory rate limiting.
var lastTriggeredLoginSync: Timestamp = 0
@objc func onLoginDidChange(notification: NSNotification) {
log.debug("Login did change.")
if (NSDate.now() - lastTriggeredLoginSync) > OneMinuteInMilliseconds {
lastTriggeredLoginSync = NSDate.now()
// Give it a few seconds.
let when: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, SyncConstants.SyncDelayTriggered)
// Trigger on the main queue. The bulk of the sync work runs in the background.
let greenLight = self.greenLight()
dispatch_after(when, dispatch_get_main_queue()) {
if greenLight() {
self.syncLogins()
}
}
}
}
var lastSyncFinishTime: Timestamp? {
get {
return self.prefs.timestampForKey(PrefsKeys.KeyLastSyncFinishTime)
}
set(value) {
if let value = value {
self.prefs.setTimestamp(value, forKey: PrefsKeys.KeyLastSyncFinishTime)
} else {
self.prefs.removeObjectForKey(PrefsKeys.KeyLastSyncFinishTime)
}
}
}
@objc func onStartSyncing(notification: NSNotification) {
syncLock.lock()
defer { syncLock.unlock() }
syncDisplayState = .InProgress
}
@objc func onFinishSyncing(notification: NSNotification) {
syncLock.lock()
defer { syncLock.unlock() }
if let syncState = syncDisplayState where syncState == .Good {
self.lastSyncFinishTime = NSDate.now()
}
}
private func displayStateForEngineResults(result: Maybe<EngineResults>?) -> SyncDisplayState {
guard let result = result else {
return .Good
}
guard let results = result.successValue else {
switch result.failureValue {
case _ as BookmarksMergeError, _ as BookmarksDatabaseError:
return SyncDisplayState.Stale(message: String(format:Strings.FirefoxSyncPartialTitle, Strings.localizedStringForSyncComponent("bookmarks") ?? ""))
default:
return SyncDisplayState.Bad(message: nil)
}
}
let errorResults: [SyncDisplayState]? = results.flatMap { identifier, status in
let displayState = self.displayStateForSyncState(status, identifier: identifier)
return displayState == .Good ? nil : displayState
}
return errorResults?.first ?? .Good
}
private func displayStateForSyncState(syncStatus: SyncStatus, identifier: String? = nil) -> SyncDisplayState {
switch syncStatus {
case .Completed:
return SyncDisplayState.Good
case .NotStarted(let reason):
let message: String
switch reason {
case .Offline:
message = Strings.FirefoxSyncOfflineTitle
default:
message = Strings.FirefoxSyncNotStartedTitle
}
return SyncDisplayState.Stale(message: message)
case .Partial:
if let identifier = identifier {
return SyncDisplayState.Stale(message: String(format:Strings.FirefoxSyncPartialTitle, Strings.localizedStringForSyncComponent(identifier) ?? ""))
}
return SyncDisplayState.Stale(message: Strings.FirefoxSyncNotStartedTitle)
}
}
var prefsForSync: Prefs {
return self.prefs.branch("sync")
}
func onAddedAccount() -> Success {
// Only sync if we're green lit. This makes sure that we don't sync unverified accounts.
guard self.profile.hasSyncableAccount() else { return succeed() }
self.beginTimedSyncs();
return self.syncEverything()
}
func locallyResetCollections(collections: [String]) -> Success {
return walk(collections, f: self.locallyResetCollection)
}
func locallyResetCollection(collection: String) -> Success {
switch collection {
case "bookmarks":
return BufferingBookmarksSynchronizer.resetSynchronizerWithStorage(self.profile.bookmarks, basePrefs: self.prefsForSync, collection: "bookmarks")
case "clients":
fallthrough
case "tabs":
// Because clients and tabs share storage, and thus we wipe data for both if we reset either,
// we reset the prefs for both at the same time.
return TabsSynchronizer.resetClientsAndTabsWithStorage(self.profile.remoteClientsAndTabs, basePrefs: self.prefsForSync)
case "history":
return HistorySynchronizer.resetSynchronizerWithStorage(self.profile.history, basePrefs: self.prefsForSync, collection: "history")
case "passwords":
return LoginsSynchronizer.resetSynchronizerWithStorage(self.profile.logins, basePrefs: self.prefsForSync, collection: "passwords")
case "forms":
log.debug("Requested reset for forms, but this client doesn't sync them yet.")
return succeed()
case "addons":
log.debug("Requested reset for addons, but this client doesn't sync them.")
return succeed()
case "prefs":
log.debug("Requested reset for prefs, but this client doesn't sync them.")
return succeed()
default:
log.warning("Asked to reset collection \(collection), which we don't know about.")
return succeed()
}
}
func onNewProfile() {
SyncStateMachine.clearStateFromPrefs(self.prefsForSync)
}
func onRemovedAccount(account: FirefoxAccount?) -> Success {
let profile = self.profile
// Run these in order, because they might write to the same DB!
let remove = [
profile.history.onRemovedAccount,
profile.remoteClientsAndTabs.onRemovedAccount,
profile.logins.onRemovedAccount,
profile.bookmarks.onRemovedAccount,
]
let clearPrefs: () -> Success = {
withExtendedLifetime(self) {
// Clear prefs after we're done clearing everything else -- just in case
// one of them needs the prefs and we race. Clear regardless of success
// or failure.
// This will remove keys from the Keychain if they exist, as well
// as wiping the Sync prefs.
SyncStateMachine.clearStateFromPrefs(self.prefsForSync)
}
return succeed()
}
return accumulate(remove) >>> clearPrefs
}
private func repeatingTimerAtInterval(interval: NSTimeInterval, selector: Selector) -> NSTimer {
return NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: selector, userInfo: nil, repeats: true)
}
func beginTimedSyncs() {
if self.syncTimer != nil {
log.debug("Already running sync timer.")
return
}
let interval = FifteenMinutes
let selector = #selector(BrowserSyncManager.syncOnTimer)
log.debug("Starting sync timer.")
self.syncTimer = repeatingTimerAtInterval(interval, selector: selector)
}
/**
* The caller is responsible for calling this on the same thread on which it called
* beginTimedSyncs.
*/
func endTimedSyncs() {
if let t = self.syncTimer {
log.debug("Stopping sync timer.")
self.syncTimer = nil
t.invalidate()
}
}
private func syncClientsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing clients to storage.")
let clientSynchronizer = ready.synchronizer(ClientsSynchronizer.self, delegate: delegate, prefs: prefs)
return clientSynchronizer.synchronizeLocalClients(self.profile.remoteClientsAndTabs, withServer: ready.client, info: ready.info)
}
private func syncTabsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
let storage = self.profile.remoteClientsAndTabs
let tabSynchronizer = ready.synchronizer(TabsSynchronizer.self, delegate: delegate, prefs: prefs)
return tabSynchronizer.synchronizeLocalTabs(storage, withServer: ready.client, info: ready.info)
}
private func syncHistoryWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing history to storage.")
let historySynchronizer = ready.synchronizer(HistorySynchronizer.self, delegate: delegate, prefs: prefs)
return historySynchronizer.synchronizeLocalHistory(self.profile.history, withServer: ready.client, info: ready.info, greenLight: self.greenLight())
}
private func syncLoginsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing logins to storage.")
let loginsSynchronizer = ready.synchronizer(LoginsSynchronizer.self, delegate: delegate, prefs: prefs)
return loginsSynchronizer.synchronizeLocalLogins(self.profile.logins, withServer: ready.client, info: ready.info)
}
private func mirrorBookmarksWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Synchronizing server bookmarks to storage.")
let bookmarksMirrorer = ready.synchronizer(BufferingBookmarksSynchronizer.self, delegate: delegate, prefs: prefs)
return bookmarksMirrorer.synchronizeBookmarksToStorage(self.profile.bookmarks, usingBuffer: self.profile.mirrorBookmarks, withServer: ready.client, info: ready.info, greenLight: self.greenLight())
}
func takeActionsOnEngineStateChanges<T: EngineStateChanges>(changes: T) -> Deferred<Maybe<T>> {
var needReset = Set<String>(changes.collectionsThatNeedLocalReset())
needReset.unionInPlace(changes.enginesDisabled())
needReset.unionInPlace(changes.enginesEnabled())
if needReset.isEmpty {
log.debug("No collections need reset. Moving on.")
return deferMaybe(changes)
}
// needReset needs at most one of clients and tabs, because we reset them
// both if either needs reset. This is strictly an optimization to avoid
// doing duplicate work.
if needReset.contains("clients") {
if needReset.remove("tabs") != nil {
log.debug("Already resetting clients (and tabs); not bothering to also reset tabs again.")
}
}
return walk(Array(needReset), f: self.locallyResetCollection)
>>> effect(changes.clearLocalCommands)
>>> always(changes)
}
/**
* Runs the single provided synchronization function and returns its status.
*/
private func sync(label: EngineIdentifier, function: SyncFunction) -> SyncResult {
return syncSeveral([(label, function)]) >>== { statuses in
let status = statuses.find { label == $0.0 }?.1
return deferMaybe(status ?? .NotStarted(.Unknown))
}
}
/**
* Convenience method for syncSeveral([(EngineIdentifier, SyncFunction)])
*/
private func syncSeveral(synchronizers: (EngineIdentifier, SyncFunction)...) -> Deferred<Maybe<[(EngineIdentifier, SyncStatus)]>> {
return syncSeveral(synchronizers)
}
/**
* Runs each of the provided synchronization functions with the same inputs.
* Returns an array of IDs and SyncStatuses at least length as the input.
* The statuses returned will be a superset of the ones that are requested here.
* While a sync is ongoing, each engine from successive calls to this method will only be called once.
*/
private func syncSeveral(synchronizers: [(EngineIdentifier, SyncFunction)]) -> Deferred<Maybe<[(EngineIdentifier, SyncStatus)]>> {
syncLock.lock()
defer { syncLock.unlock() }
if (!isSyncing) {
// A sync isn't already going on, so start another one.
let reducer = AsyncReducer<EngineResults, EngineTasks>(initialValue: [], queue: syncQueue) { (statuses, synchronizers) in
let done = Set(statuses.map { $0.0 })
let remaining = synchronizers.filter { !done.contains($0.0) }
if remaining.isEmpty {
log.info("Nothing left to sync")
return deferMaybe(statuses)
}
return self.syncWith(remaining) >>== { deferMaybe(statuses + $0) }
}
reducer.terminal.upon(self.endSyncing)
// The actual work of synchronizing doesn't start until we append
// the synchronizers to the reducer below.
self.syncReducer = reducer
self.beginSyncing()
}
do {
return try syncReducer!.append(synchronizers)
} catch let error {
log.error("Synchronizers appended after sync was finished. This is a bug. \(error)")
let statuses = synchronizers.map {
($0.0, SyncStatus.NotStarted(.Unknown))
}
return deferMaybe(statuses)
}
}
// This SHOULD NOT be called directly: use syncSeveral instead.
private func syncWith(synchronizers: [(EngineIdentifier, SyncFunction)]) -> Deferred<Maybe<[(EngineIdentifier, SyncStatus)]>> {
guard let account = self.profile.account else {
log.info("No account to sync with.")
let statuses = synchronizers.map {
($0.0, SyncStatus.NotStarted(.NoAccount))
}
return deferMaybe(statuses)
}
log.info("Syncing \(synchronizers.map { $0.0 })")
let authState = account.syncAuthState
let delegate = self.profile.getSyncDelegate()
let readyDeferred = SyncStateMachine(prefs: self.prefsForSync).toReady(authState)
let function: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<[EngineStatus]>> = { delegate, syncPrefs, ready in
let thunks = synchronizers.map { (i, f) in
return { () -> Deferred<Maybe<EngineStatus>> in
log.debug("Syncing \(i)…")
return f(delegate, syncPrefs, ready) >>== { deferMaybe((i, $0)) }
}
}
return accumulate(thunks)
}
return readyDeferred >>== self.takeActionsOnEngineStateChanges >>== { ready in
function(delegate, self.prefsForSync, ready)
}
}
func syncEverything() -> Success {
return self.syncSeveral(
("clients", self.syncClientsWithDelegate),
("tabs", self.syncTabsWithDelegate),
("logins", self.syncLoginsWithDelegate),
("bookmarks", self.mirrorBookmarksWithDelegate),
("history", self.syncHistoryWithDelegate)
) >>> succeed
}
func syncEverythingSoon() {
self.doInBackgroundAfter(millis: SyncConstants.SyncOnForegroundAfterMillis) {
log.debug("Running delayed startup sync.")
self.syncEverything()
}
}
@objc func syncOnTimer() {
self.syncEverything()
}
func hasSyncedHistory() -> Deferred<Maybe<Bool>> {
return self.profile.history.hasSyncedHistory()
}
func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
return self.profile.logins.hasSyncedLogins()
}
func syncClients() -> SyncResult {
// TODO: recognize .NotStarted.
return self.sync("clients", function: syncClientsWithDelegate)
}
func syncClientsThenTabs() -> SyncResult {
return self.syncSeveral(
("clients", self.syncClientsWithDelegate),
("tabs", self.syncTabsWithDelegate)
) >>== { statuses in
let status = statuses.find { "tabs" == $0.0 }
return deferMaybe(status!.1)
}
}
func syncLogins() -> SyncResult {
return self.sync("logins", function: syncLoginsWithDelegate)
}
func syncHistory() -> SyncResult {
// TODO: recognize .NotStarted.
return self.sync("history", function: syncHistoryWithDelegate)
}
func mirrorBookmarks() -> SyncResult {
return self.sync("bookmarks", function: mirrorBookmarksWithDelegate)
}
/**
* Return a thunk that continues to return true so long as an ongoing sync
* should continue.
*/
func greenLight() -> () -> Bool {
let start = NSDate.now()
// Give it one minute to run before we stop.
let stopBy = start + OneMinuteInMilliseconds
log.debug("Checking green light. Backgrounded: \(self.backgrounded).")
return {
NSDate.now() < stopBy &&
self.profile.hasSyncableAccount()
}
}
}
}
| mpl-2.0 | ab2a5fc0c872d5a7eb941511a16b133a | 40.81937 | 238 | 0.622732 | 5.485683 | false | false | false | false |
klundberg/swift-corelibs-foundation | Foundation/NSAttributedString.swift | 1 | 10162 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
public class AttributedString: NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
private let _cfinfo = _CFInfo(typeID: CFAttributedStringGetTypeID())
private var _string: NSString
private var _attributeArray: CFRunArrayRef
public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
public func encode(with aCoder: NSCoder) {
NSUnimplemented()
}
static public func supportsSecureCoding() -> Bool {
return true
}
public override func copy() -> AnyObject {
return copy(with: nil)
}
public func copy(with zone: NSZone? = nil) -> AnyObject {
NSUnimplemented()
}
public override func mutableCopy() -> AnyObject {
return mutableCopy(with: nil)
}
public func mutableCopy(with zone: NSZone? = nil) -> AnyObject {
NSUnimplemented()
}
public var string: String {
return _string._swiftObject
}
public func attributesAtIndex(_ location: Int, effectiveRange range: NSRangePointer) -> [String : AnyObject] {
let rangeInfo = RangeInfo(
rangePointer: range,
shouldFetchLongestEffectiveRange: false,
longestEffectiveRangeSearchRange: nil)
return _attributesAtIndex(location, rangeInfo: rangeInfo)
}
public var length: Int {
return CFAttributedStringGetLength(_cfObject)
}
public func attribute(_ attrName: String, atIndex location: Int, effectiveRange range: NSRangePointer) -> AnyObject? {
let rangeInfo = RangeInfo(
rangePointer: range,
shouldFetchLongestEffectiveRange: false,
longestEffectiveRangeSearchRange: nil)
return _attribute(attrName, atIndex: location, rangeInfo: rangeInfo)
}
public func attributedSubstringFromRange(_ range: NSRange) -> AttributedString { NSUnimplemented() }
public func attributesAtIndex(_ location: Int, longestEffectiveRange range: NSRangePointer, inRange rangeLimit: NSRange) -> [String : AnyObject] {
let rangeInfo = RangeInfo(
rangePointer: range,
shouldFetchLongestEffectiveRange: true,
longestEffectiveRangeSearchRange: rangeLimit)
return _attributesAtIndex(location, rangeInfo: rangeInfo)
}
public func attribute(_ attrName: String, atIndex location: Int, longestEffectiveRange range: NSRangePointer, inRange rangeLimit: NSRange) -> AnyObject? {
let rangeInfo = RangeInfo(
rangePointer: range,
shouldFetchLongestEffectiveRange: true,
longestEffectiveRangeSearchRange: rangeLimit)
return _attribute(attrName, atIndex: location, rangeInfo: rangeInfo)
}
public func isEqualToAttributedString(_ other: AttributedString) -> Bool { NSUnimplemented() }
public init(string str: String) {
_string = str._nsObject
_attributeArray = CFRunArrayCreate(kCFAllocatorDefault)
super.init()
addAttributesToAttributeArray(attrs: nil)
}
public init(string str: String, attributes attrs: [String : AnyObject]?) {
_string = str._nsObject
_attributeArray = CFRunArrayCreate(kCFAllocatorDefault)
super.init()
addAttributesToAttributeArray(attrs: attrs)
}
public init(attributedString attrStr: AttributedString) { NSUnimplemented() }
public func enumerateAttributesInRange(_ enumerationRange: NSRange, options opts: EnumerationOptions, usingBlock block: ([String : AnyObject], NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() }
public func enumerateAttribute(_ attrName: String, inRange enumerationRange: NSRange, options opts: EnumerationOptions, usingBlock block: (AnyObject?, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() }
}
private extension AttributedString {
private struct RangeInfo {
let rangePointer: NSRangePointer
let shouldFetchLongestEffectiveRange: Bool
let longestEffectiveRangeSearchRange: NSRange?
}
private func _attributesAtIndex(_ location: Int, rangeInfo: RangeInfo) -> [String : AnyObject] {
var cfRange = CFRange()
return withUnsafeMutablePointer(&cfRange) { (cfRangePointer: UnsafeMutablePointer<CFRange>) -> [String : AnyObject] in
// Get attributes value using CoreFoundation function
let value: CFDictionary
if rangeInfo.shouldFetchLongestEffectiveRange, let searchRange = rangeInfo.longestEffectiveRangeSearchRange {
value = CFAttributedStringGetAttributesAndLongestEffectiveRange(_cfObject, location, CFRange(searchRange), cfRangePointer)
} else {
value = CFAttributedStringGetAttributes(_cfObject, location, cfRangePointer)
}
// Convert the value to [String : AnyObject]
let dictionary = unsafeBitCast(value, to: NSDictionary.self)
var results = [String : AnyObject]()
for (key, value) in dictionary {
guard let stringKey = (key as? NSString)?._swiftObject else {
continue
}
results[stringKey] = value
}
// Update effective range
let hasAttrs = results.count > 0
rangeInfo.rangePointer.pointee.location = hasAttrs ? cfRangePointer.pointee.location : NSNotFound
rangeInfo.rangePointer.pointee.length = hasAttrs ? cfRangePointer.pointee.length : 0
return results
}
}
private func _attribute(_ attrName: String, atIndex location: Int, rangeInfo: RangeInfo) -> AnyObject? {
var cfRange = CFRange()
return withUnsafeMutablePointer(&cfRange) { (cfRangePointer: UnsafeMutablePointer<CFRange>) -> AnyObject? in
// Get attribute value using CoreFoundation function
let attribute: AnyObject?
if rangeInfo.shouldFetchLongestEffectiveRange, let searchRange = rangeInfo.longestEffectiveRangeSearchRange {
attribute = CFAttributedStringGetAttributeAndLongestEffectiveRange(_cfObject, location, attrName._cfObject, CFRange(searchRange), cfRangePointer)
} else {
attribute = CFAttributedStringGetAttribute(_cfObject, location, attrName._cfObject, cfRangePointer)
}
// Update effective range and return the result
if let attribute = attribute {
rangeInfo.rangePointer.pointee.location = cfRangePointer.pointee.location
rangeInfo.rangePointer.pointee.length = cfRangePointer.pointee.length
return attribute
} else {
rangeInfo.rangePointer.pointee.location = NSNotFound
rangeInfo.rangePointer.pointee.length = 0
return nil
}
}
}
private func addAttributesToAttributeArray(attrs: [String : AnyObject]?) {
guard _string.length > 0 else {
return
}
let range = CFRange(location: 0, length: _string.length)
if let attrs = attrs {
CFRunArrayInsert(_attributeArray, range, attrs._cfObject)
} else {
let emptyAttrs = [String : AnyObject]()
CFRunArrayInsert(_attributeArray, range, emptyAttrs._cfObject)
}
}
}
extension AttributedString: _CFBridgable {
internal var _cfObject: CFAttributedString { return unsafeBitCast(self, to: CFAttributedString.self) }
}
extension AttributedString {
public struct EnumerationOptions: OptionSet {
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
public static let Reverse = EnumerationOptions(rawValue: 1 << 1)
public static let LongestEffectiveRangeNotRequired = EnumerationOptions(rawValue: 1 << 20)
}
}
public class NSMutableAttributedString : AttributedString {
public func replaceCharactersInRange(_ range: NSRange, withString str: String) { NSUnimplemented() }
public func setAttributes(_ attrs: [String : AnyObject]?, range: NSRange) { NSUnimplemented() }
public var mutableString: NSMutableString {
return _string as! NSMutableString
}
public func addAttribute(_ name: String, value: AnyObject, range: NSRange) {
CFAttributedStringSetAttribute(_cfMutableObject, CFRange(range), name._cfObject, value)
}
public func addAttributes(_ attrs: [String : AnyObject], range: NSRange) { NSUnimplemented() }
public func removeAttribute(_ name: String, range: NSRange) { NSUnimplemented() }
public func replaceCharactersInRange(_ range: NSRange, withAttributedString attrString: AttributedString) { NSUnimplemented() }
public func insertAttributedString(_ attrString: AttributedString, atIndex loc: Int) { NSUnimplemented() }
public func appendAttributedString(_ attrString: AttributedString) { NSUnimplemented() }
public func deleteCharactersInRange(_ range: NSRange) { NSUnimplemented() }
public func setAttributedString(_ attrString: AttributedString) { NSUnimplemented() }
public func beginEditing() { NSUnimplemented() }
public func endEditing() { NSUnimplemented() }
public override init(string str: String) {
super.init(string: str)
_string = NSMutableString(string: str)
}
public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
}
extension NSMutableAttributedString {
internal var _cfMutableObject: CFMutableAttributedString { return unsafeBitCast(self, to: CFMutableAttributedString.self) }
}
| apache-2.0 | 1f4caaee0b12e615bffa959690d5a13c | 40.308943 | 226 | 0.66916 | 5.873988 | false | false | false | false |
TeamYYZ/DineApp | Dine/User.swift | 1 | 8299 | //
// User.swift
// Dine
//
// Created by YiHuang on 3/15/16.
// Copyright © 2016 YYZ. All rights reserved.
//
import UIKit
import Parse
class User {
var userId: String?
var pfUser: PFUser?
var username: String?
var screenName: String?
var password: String?
var dateOfBirth: NSDate?
var gender: Bool?
var email: String?
var profileDescription: String?
var avatarImagePFFile: PFFile?
var avatarImage: UIImage?
var friendList: [String]? // save users' objectID
var current_location: CLLocation?
var currentActivityId: String? // for persistent maintaining activity
var notificationsRecv: [UserNotification]?
static var currentUser: User?
// for persistently store the current User object, generate a User object after restarting in Appdelegate
init (userId: String) {
self.userId = userId
}
init (pfUser: PFUser) {
self.pfUser = pfUser
self.userId = pfUser.objectId
self.username = pfUser.username
self.password = pfUser.password
self.currentActivityId = pfUser["currentActivity"] as? String
self.avatarImagePFFile = pfUser["avatar"] as? PFFile
if let file = self.avatarImagePFFile{
file.getDataInBackgroundWithBlock({
(result, error) in
self.avatarImage = UIImage(data: result!)
})
}else{
self.avatarImage = UIImage(named: "User")
}
if let screenName = pfUser["screenName"] as? String {
self.screenName = screenName
}
if let description = pfUser["description"] as? String{
self.profileDescription = description
}
self.friendList = pfUser["friendList"] as? [String]
self.notificationsRecv = [UserNotification]()
if let notificationDictArray = pfUser["notificationsRecv"] as? [NSDictionary] {
for notification in notificationDictArray {
self.notificationsRecv?.append(UserNotification(dict: notification))
}
}
}
// passing nil activityId will clear currentActivity Field in User object
func setCurrentActivity(activityId: String?, successHandler: (()->())?, failureHandler: ((NSError?)->())?) {
if let pfUser = self.pfUser {
if let activityId = activityId {
pfUser["currentActivity"] = activityId
} else {
pfUser.removeObjectForKey("currentActivity")
}
pfUser.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) in
if success {
successHandler?()
} else {
failureHandler?(error)
}
})
} else {
failureHandler?(NSError(domain: "Current user not Found", code: 2, userInfo: nil))
}
}
func getNotifications(successHandler: ([UserNotification]?)->()) {
let userQuery = PFUser.query()
userQuery?.getObjectInBackgroundWithId(userId!, block: { (user: PFObject?, error: NSError?) -> Void in
if error == nil && user != nil {
self.notificationsRecv = [UserNotification]()
let notificationDictArray = user!["notificationsRecv"] as? [NSDictionary]
print(notificationDictArray)
if let dictArray = notificationDictArray {
for notification in dictArray {
self.notificationsRecv?.append(UserNotification(dict: notification))
}
successHandler(self.notificationsRecv)
} else {
successHandler(nil)
}
} else {
successHandler(nil)
}
})
}
func getFriendsList(successHandler: ([String]?)->()) {
let userQuery = PFUser.query()
userQuery?.getObjectInBackgroundWithId(userId!, block: { (user: PFObject?, error: NSError?) -> Void in
if error == nil && user != nil{
self.friendList = [String]()
let notificationArray = user!["friendList"] as? [String]
if let friendArray = notificationArray {
self.friendList = friendArray
successHandler(self.friendList)
}
}
})
}
func updateScreenName(screenName: String?, withCompletion completion: PFBooleanResultBlock?) {
// Create Parse object PFObject
if let name = screenName {
if let user = pfUser {
// Add relevant fields to the object
user["screenName"] = name // PFFile column type
user.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) in
if success == true && error == nil{
User.currentUser?.screenName = name
completion?(success, error)
//print("EEEEE")
}else{
print(error)
}
})
}
}
}
func updateUsername(username: String?, withCompletion completion: PFBooleanResultBlock?) {
// Create Parse object PFObject
if let name = username{
if let user = pfUser {
// Add relevant fields to the object
user["username"] = name // PFFile column type
user.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) in
if success == true && error == nil{
User.currentUser?.username = name
completion?(success, error)
//print("EEEEE")
}else{
print(error)
}
})
}
}
}
func updateDescription(description: String?, withCompletion completion: PFBooleanResultBlock?) {
// Create Parse object PFObject
if let text = description{
if let user = pfUser {
// Add relevant fields to the object
user["description"] = text // PFFile column type
user.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) in
if success == true && error == nil{
User.currentUser?.profileDescription = text
completion?(success, error)
//print("EEEEE")
}else{
print(error)
}
})
}
}
}
func updateProfilePhoto(image: UIImage?, withCompletion completion: PFBooleanResultBlock?) {
// Create Parse object PFObject
if let image = image {
if let user = pfUser {
// Add relevant fields to the object
user["avatar"] = getPFFileFromImage(image) // PFFile column type
user.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) in
if success == true && error == nil{
User.currentUser?.avatarImage = image
User.currentUser?.avatarImagePFFile = user["avatar"] as? PFFile
completion?(success, error)
}else{
print(error)
}
})
}
}
}
func save(){
let userQuery = PFUser.query()
userQuery?.getObjectInBackgroundWithId(userId!, block: { (pfUser: PFObject?, error: NSError?) in
if pfUser != nil && error == nil{
print(pfUser)
pfUser?.saveInBackground()
}
})
}
} | gpl-3.0 | ffae2129241563ee1511570024415b33 | 32.873469 | 112 | 0.499397 | 6.017404 | false | false | false | false |
justinyaoqi/SwiftForms | SwiftForms/cells/base/FormValueCell.swift | 4 | 2687 | //
// FormValueCell.swift
// SwiftForms
//
// Created by Miguel Ángel Ortuño Ortuño on 13/11/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
public class FormValueCell: FormBaseCell {
/// MARK: Cell views
public let titleLabel = UILabel()
public let valueLabel = UILabel()
/// MARK: Properties
private var customConstraints: [AnyObject]!
/// MARK: FormBaseCell
public override func configure() {
super.configure()
accessoryType = .DisclosureIndicator
titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
valueLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
valueLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
valueLabel.textColor = UIColor.lightGrayColor()
valueLabel.textAlignment = .Right
contentView.addSubview(titleLabel)
contentView.addSubview(valueLabel)
titleLabel.setContentHuggingPriority(500, forAxis: .Horizontal)
titleLabel.setContentCompressionResistancePriority(1000, forAxis: .Horizontal)
// apply constant constraints
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Height, relatedBy: .Equal, toItem: contentView, attribute: .Height, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .Height, relatedBy: .Equal, toItem: contentView, attribute: .Height, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
}
public override func constraintsViews() -> [String : UIView] {
return ["titleLabel" : titleLabel, "valueLabel" : valueLabel]
}
public override func defaultVisualConstraints() -> [String] {
// apply default constraints
var rightPadding = 0
if accessoryType == .None {
rightPadding = 16
}
if titleLabel.text != nil && count(titleLabel.text!) > 0 {
return ["H:|-16-[titleLabel]-[valueLabel]-\(rightPadding)-|"]
}
else {
return ["H:|-16-[valueLabel]-\(rightPadding)-|"]
}
}
}
| mit | e210093e4cc65cc6df62d991838a8d4e | 37.328571 | 185 | 0.663064 | 5.291913 | false | false | false | false |
marcoconti83/DiceExpression | Source/ResultWithLog.swift | 1 | 1979 | // Copyright (c) 2016 Marco Conti
//
//
//
// 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
/**
A value type modeling the result of an operation.
It encapsulating the result value and a log describing how the calculation was done.
*/
public struct ResultWithLog<ResultType> {
/// The value of the result
public let result : ResultType
/// The logs associated with the result
public let logs : String
/**
Creates a result with a log
*/
public init(result : ResultType, log : String) {
self.result = result
self.logs = log
}
/**
Creates a result with multiple logs
- Param: logs multiple logs that will be concatenated into one
*/
public init<S: Sequence>(result : ResultType, logs: S) where S.Iterator.Element == String {
self.result = result
self.logs = logs.reduce("") { "\($0)\($1)\n"}
}
}
| mit | 0d236ddad0792c138c5af1e9f0208909 | 32.542373 | 95 | 0.693279 | 4.487528 | false | false | false | false |
Monnoroch/Cuckoo | Generator/Dependencies/FileKit/Sources/FilePermissions.swift | 1 | 3281 | //
// FilePermissions.swift
// FileKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015-2016 Nikolai Vazquez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// The permissions of a file.
public struct FilePermissions: OptionSet, CustomStringConvertible {
/// The file can be read from.
public static let Read = FilePermissions(rawValue: 1)
/// The file can be written to.
public static let Write = FilePermissions(rawValue: 2)
/// The file can be executed.
public static let Execute = FilePermissions(rawValue: 4)
/// The raw integer value of `self`.
public let rawValue: Int
/// A textual representation of `self`.
public var description: String {
var description = ""
for permission in [.Read, .Write, .Execute] as [FilePermissions] {
if self.contains(permission) {
description += !description.isEmpty ? ", " : ""
if permission == .Read {
description += "Read"
} else if permission == .Write {
description += "Write"
} else if permission == .Execute {
description += "Execute"
}
}
}
return String(describing: type(of: self)) + "[" + description + "]"
}
/// Creates a set of file permissions.
///
/// - Parameter rawValue: The raw value to initialize from.
///
public init(rawValue: Int) {
self.rawValue = rawValue
}
/// Creates a set of permissions for the file at `path`.
///
/// - Parameter path: The path to the file to create a set of persmissions for.
///
public init(forPath path: Path) {
var permissions = FilePermissions(rawValue: 0)
if path.isReadable { permissions.formUnion(.Read) }
if path.isWritable { permissions.formUnion(.Write) }
if path.isExecutable { permissions.formUnion(.Execute) }
self = permissions
}
/// Creates a set of permissions for `file`.
///
/// - Parameter file: The file to create a set of persmissions for.
public init<Data: DataType>(forFile file: File<Data>) {
self.init(forPath: file.path)
}
}
| mit | a96a98ddde2be6a964481a49a2e46fa4 | 35.455556 | 83 | 0.644621 | 4.550624 | false | false | false | false |
LuizZak/GPEngine | Tests/GPEngineTests/EventingTests.swift | 1 | 10326 | //
// EventingTests.swift
// GPEngine
//
// Created by Luiz Fernando Silva on 06/08/14.
// Copyright (c) 2014 Luiz Fernando Silva. All rights reserved.
//
import XCTest
@testable import GPEngine
class EventingTests: XCTestCase {
var sut = GameEventDispatcher()
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
sut = GameEventDispatcher()
}
func testMultiEventAdd() { // TODO: This test may be misconstructed: The test doesn't perform the script it claims in the comments
// Test multiple event hooking
//
// 1. Add one listener to two events
// -> The event count should be 2!
//
// 2. Remove all listeners on that listener
// 3. Add the same listener twice on the same event
// 4. Dispatch that event
// -> The listener should only be called once!
let receiver = EventReceiverTestClass()
let key1 = sut.addListener(receiver, forEventType: CustomEvent.self)
_ = sut.addListener(receiver, forEventType: OtherCustomEvent.self)
XCTAssertEqual(sut.eventCount, 2)
sut.removeListener(forKey: key1)
sut.dispatchEvent(OtherCustomEvent())
XCTAssertEqual(receiver.hitCount, 1)
}
func testEventRemove() {
// Test the removeListener(forKey:)
//
// 1. Add one listener to two event types
// 2. Use the removeListener(forKey:) with that listener
// -> The event count should be 1!
//
// 3. Remove the other missing event
// -> The event count should be 0!
//
// 4. Add two listeners to an event type
// -> The event count should be 1!
//
// 5. Use the removeListener() with one of the listeners
// -> The event count should still be 1!
let receiver1 = EventReceiverTestClass()
let receiver2 = EventReceiverTestClass()
var key1 = sut.addListener(receiver1, forEventType: CustomEvent.self)
var key2 = sut.addListener(receiver1, forEventType: OtherCustomEvent.self)
sut.removeListener(forKey: key1)
XCTAssertEqual(sut.eventCount, 1)
sut.removeListener(forKey: key2)
XCTAssertEqual(sut.eventCount, 0)
key1 = sut.addListener(receiver1, forEventType: CustomEvent.self)
key2 = sut.addListener(receiver2, forEventType: OtherCustomEvent.self)
XCTAssert(sut.eventCount == 2)
sut.removeListener(receiver1)
XCTAssertEqual(sut.eventCount, 1)
}
func testEventRemoveAll() {
// Test the removeListener(_:)
//
// 1. Add one listener to two different event types
// 2. Use the removeListener() with that listener
// -> The event count should be 0!
let receiver = EventReceiverTestClass()
_ = sut.addListener(receiver, forEventType: CustomEvent.self)
_ = sut.addListener(receiver, forEventType: OtherCustomEvent.self)
sut.removeListener(receiver)
XCTAssertEqual(sut.eventCount, 0, "The event count should reset to 0 once the receiver was removed as a sole listener to multiple events")
}
func testEventDispatch() {
// Test the basic event dispatching
//
// 1. Add one listener to an event type
// 2. Dispatch that event
// -> The listener should be called!
let receiver = EventReceiverTestClass()
_ = sut.addListener(receiver, forEventType: CustomEvent.self)
sut.dispatchEvent(CustomEvent())
XCTAssert(receiver.received, "The entity should have received the event")
}
func testMultiListenersEventDispatch() {
// Test multiple listeners to same event dispatching
//
// 1. Add two listeners to an event type
// 2. Dispatch that event
// -> Both listeners should be called!
let receiver1 = EventReceiverTestClass()
let receiver2 = EventReceiverTestClass()
_ = sut.addListener(receiver1, forEventType: CustomEvent.self)
_ = sut.addListener(receiver2, forEventType: CustomEvent.self)
sut.dispatchEvent(CustomEvent())
XCTAssert(receiver1.received && receiver2.received, "All listeners must receive events dispatched from the dispatcher")
}
func testRemoveAllListeners() {
// Test the removeAllEvents() method on the dispatcher
//
// 1. Add two listeners to two distinct events
// 2. Use the removeAllEvents() to clear the events
// -> The event count should be 0!
let receiver1 = EventReceiverTestClass()
let receiver2 = EventReceiverTestClass()
_ = sut.addListener(receiver1, forEventType: CustomEvent.self)
_ = sut.addListener(receiver2, forEventType: OtherCustomEvent.self)
sut.removeAllListeners()
XCTAssertEqual(sut.eventCount, 0, "The event dispatcher must be clear after a removeAllEvents() call")
}
func testRemoveListenerForKeyIgnoresInvalidatedKeys() {
let receiver = EventReceiverTestClass()
let key = sut.addListener(receiver, forEventType: CustomEvent.self)
key.valid.value = false
sut.removeListener(forKey: key)
XCTAssertEqual(sut.eventCount, 1)
}
func testKeyInvalidateOnRemoveAllEvents() {
// Tests that an event listener key invalidates when calling
// dispatcher.removeAllEvents
let receiver = EventReceiverTestClass()
let key = sut.addListener(receiver, forEventType: CustomEvent.self)
sut.removeAllListeners()
XCTAssertFalse(key.valid.value)
}
func testKeyInvalidateOnRemoveByKey() {
// Tests that an event listener key invalidates when calling
// dispatcher.removeListener(forKey:)
let receiver = EventReceiverTestClass()
let key = sut.addListener(receiver, forEventType: CustomEvent.self)
sut.removeListener(forKey: key)
XCTAssertFalse(key.valid.value)
}
func testKeyInvalidateOnRemoveListener() {
// Tests that an event listener key invalidates when calling
// dispatcher.removeListener(_:)
let receiver = EventReceiverTestClass()
let key = sut.addListener(receiver, forEventType: CustomEvent.self)
sut.removeListener(receiver)
XCTAssertFalse(key.valid.value)
}
func testKeyInvalidateOnDispatcherDealloc() {
// Tests that an event listener key invalidates when the event
// dispatcher deinits
var key: EventListenerKey!
let receiver = EventReceiverTestClass()
autoreleasepool {
let sut = GameEventDispatcher()
key = sut.addListener(receiver, forEventType: CustomEvent.self)
_ = sut.addListener(receiver, forEventType: CustomEvent.self)
} // sut is invalidated here!
XCTAssertFalse(key.valid.value)
}
func testClosureEventListener() {
// Test the ClosureEventListener utility struct, which filters event
// types using a generic type
let exp = expectation(description: "")
let receiver1 = ClosureEventListener<CustomEvent> { _ in
exp.fulfill()
}
let receiver2 = ClosureEventListener<OtherCustomEvent> { _ in
XCTFail("Should not have fired")
}
_ = sut.addListener(receiver1, forEventType: CustomEvent.self)
_ = sut.addListener(receiver2, forEventType: OtherCustomEvent.self)
sut.dispatchEvent(CustomEvent())
waitForExpectations(timeout: 0, handler: nil)
}
func testGlobalEventNotifier() {
let receiver = EventReceiverTestClass()
_ = sut.addListenerForAllEvents(receiver)
sut.dispatchEvent(CustomEvent())
sut.dispatchEvent(OtherCustomEvent())
XCTAssertEqual(receiver.hitCount, 2)
// Make sure we're able to unsubscribe the event listener normally
sut.removeListener(receiver)
sut.dispatchEvent(CustomEvent())
XCTAssertEqual(receiver.hitCount, 2)
}
func testClosureGlobalEventListener() {
var count = 0
let exp = expectation(description: "")
let receiver = ClosureAnyEventListener { _ in
count += 1
if count == 2 {
exp.fulfill()
}
}
let key = sut.addListenerForAllEvents(receiver)
sut.dispatchEvent(CustomEvent())
sut.dispatchEvent(OtherCustomEvent())
waitForExpectations(timeout: 0, handler: nil)
// Make sure we're able to unsubscribe the event listener normally
sut.removeListener(forKey: key)
sut.dispatchEvent(CustomEvent())
XCTAssertEqual(count, 2)
}
func testRemoveEventIgnoresEventKeysFromOtherDispatchers() {
let dispatcher1 = GameEventDispatcher()
let dispatcher2 = GameEventDispatcher()
let receiver = EventReceiverTestClass()
_ = dispatcher1.addListener(receiver, forEventType: CustomEvent.self)
let key = dispatcher2.addListener(receiver, forEventType: CustomEvent.self)
dispatcher1.removeListener(forKey: key)
XCTAssertTrue(key.valid.value)
}
}
// Test class used to capture event receiving
class EventReceiverTestClass: Entity, GameEventListener {
var received = false
var hitCount = 0
func receiveEvent(_ event: GameEvent) {
received = true
hitCount += 1
}
}
// Custom event used to test different event types
class CustomEvent: GameEvent {
}
// Custom event used to test different event types
class OtherCustomEvent: GameEvent {
}
| mit | 57302f5d3875f04a37bf49b0c2d9e51b | 32.202572 | 146 | 0.615727 | 5.397804 | false | true | false | false |
PureSwift/Predicate | Sources/Encoder.swift | 1 | 13726 | //
// Encoder.swift
//
//
// Created by Alsey Coleman Miller on 4/12/20.
//
import Foundation
/// Predicate Encoder
internal struct PredicateEncoder {
// MARK: - Properties
/// Any contextual information set by the user for encoding.
public var userInfo = [CodingUserInfoKey : Any]()
/// Logger handler
public var log: ((String) -> ())?
// MARK: - Initialization
public init() { }
// MARK: - Methods
public func encode <T: Encodable> (_ value: T) throws -> PredicateContext {
log?("Will encode \(String(reflecting: T.self))")
let encoder = Encoder(userInfo: userInfo, log: log)
try value.encode(to: encoder)
return PredicateContext(values: encoder.values)
}
}
// MARK: - Codable
public extension Encodable where Self: PredicateEvaluatable {
func evaluate(with predicate: Predicate) throws -> Bool {
return try evaluate(with: predicate, log: nil)
}
internal func evaluate(with predicate: Predicate, log: ((String) -> ())?) throws -> Bool {
let context = try PredicateContext(value: self, log: log)
return try context.evaluate(with: predicate)
}
}
public extension PredicateContext {
init<T>(value: T) throws where T: Encodable {
try self.init(value: value, log: nil)
}
internal init<T>(value: T, log: ((String) -> ())?) throws where T: Encodable {
var encoder = PredicateEncoder()
encoder.log = log
self = try encoder.encode(value)
}
}
// MARK: - Encoder
internal extension PredicateEncoder {
final class Encoder: Swift.Encoder {
// MARK: - Properties
/// The path of coding keys taken to get to this point in encoding.
fileprivate(set) var codingPath: [CodingKey]
/// Any contextual information set by the user for encoding.
let userInfo: [CodingUserInfoKey : Any]
/// Logger
let log: ((String) -> ())?
private(set) var values: [PredicateKeyPath: Value]
// MARK: - Initialization
init(codingPath: [CodingKey] = [],
userInfo: [CodingUserInfoKey : Any],
log: ((String) -> ())?) {
self.values = [:]
self.codingPath = codingPath
self.userInfo = userInfo
self.log = log
}
// MARK: - Encoder
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
log?("Requested container keyed by \(type.sanitizedName) for path \"\(codingPath.path)\"")
let keyedContainer = PredicateKeyedContainer<Key>(referencing: self)
return KeyedEncodingContainer(keyedContainer)
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
log?("Requested unkeyed container for path \"\(codingPath.path)\"")
return PredicateUnkeyedEncodingContainer(referencing: self)
}
func singleValueContainer() -> SingleValueEncodingContainer {
log?("Requested single value container for path \"\(codingPath.path)\"")
return PredicateSingleValueEncodingContainer(referencing: self)
}
}
}
internal extension PredicateEncoder.Encoder {
var keyPath: PredicateKeyPath {
let keys: [PredicateKeyPath.Key] = codingPath.map { (key) in
if let indexKey = key as? IndexCodingKey {
return .index(UInt(indexKey.index))
} else {
return .property(key.stringValue)
}
}
return PredicateContext.KeyPath(keys: keys)
}
func write(_ value: Value) {
let keyPath = self.keyPath
assert(keyPath.description == codingPath.path)
values[keyPath] = value
log?("Did encode \(value.type) value for keyPath \"\(keyPath)\"")
}
func writeEncodable <T: Encodable> (_ value: T) throws {
if let data = value as? Data {
write(.data(data))
} else if let uuid = value as? UUID {
write(.uuid(uuid))
} else if let date = value as? Date {
write(.date(date))
} else {
// encode using Encodable, container should write directly.
try value.encode(to: self)
}
}
}
// MARK: - KeyedEncodingContainerProtocol
internal final class PredicateKeyedContainer <K : CodingKey> : KeyedEncodingContainerProtocol {
typealias Key = K
// MARK: - Properties
/// A reference to the encoder we're writing to.
let encoder: PredicateEncoder.Encoder
/// The path of coding keys taken to get to this point in encoding.
let codingPath: [CodingKey]
// MARK: - Initialization
init(referencing encoder: PredicateEncoder.Encoder) {
self.encoder = encoder
self.codingPath = encoder.codingPath
}
// MARK: - Methods
func encodeNil(forKey key: K) throws {
encode(.null, for: key)
}
func encode(_ value: Bool, forKey key: K) throws {
encode(value, for: key)
}
func encode(_ value: Int, forKey key: K) throws {
encode(Int64(value), for: key)
}
func encode(_ value: Int8, forKey key: K) throws {
encode(value, for: key)
}
func encode(_ value: Int16, forKey key: K) throws {
encode(value, for: key)
}
func encode(_ value: Int32, forKey key: K) throws {
encode(value, for: key)
}
func encode(_ value: Int64, forKey key: K) throws {
encode(value, for: key)
}
func encode(_ value: UInt, forKey key: K) throws {
encode(UInt64(value), for: key)
}
func encode(_ value: UInt8, forKey key: K) throws {
encode(value, for: key)
}
func encode(_ value: UInt16, forKey key: K) throws {
encode(value, for: key)
}
func encode(_ value: UInt32, forKey key: K) throws {
encode(value, for: key)
}
func encode(_ value: UInt64, forKey key: K) throws {
encode(value, for: key)
}
func encode(_ value: Float, forKey key: K) throws {
encode(value, for: key)
}
func encode(_ value: Double, forKey key: K) throws {
encode(value, for: key)
}
func encode(_ value: String, forKey key: K) throws {
encode(value, for: key)
}
func encode <T: Encodable> (_ value: T, forKey key: K) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
try encoder.writeEncodable(value)
}
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: K) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
fatalError()
}
func nestedUnkeyedContainer(forKey key: K) -> UnkeyedEncodingContainer {
fatalError()
}
func superEncoder() -> Encoder {
fatalError()
}
func superEncoder(forKey key: K) -> Encoder {
fatalError()
}
// MARK: - Private Methods
private func encode<T: PredicateValue>(_ value: T, for key: K) {
encode(value.predicateValue, for: key)
}
private func encode(_ value: Value, for key: K) {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
self.encoder.write(value)
}
}
// MARK: - SingleValueEncodingContainer
internal final class PredicateSingleValueEncodingContainer: SingleValueEncodingContainer {
// MARK: - Properties
/// A reference to the encoder we're writing to.
let encoder: PredicateEncoder.Encoder
/// The path of coding keys taken to get to this point in encoding.
let codingPath: [CodingKey]
/// Whether the data has been written
private var didWrite = false
// MARK: - Initialization
init(referencing encoder: PredicateEncoder.Encoder) {
self.encoder = encoder
self.codingPath = encoder.codingPath
}
// MARK: - Methods
func encodeNil() throws { write(.null) }
func encode(_ value: Bool) throws { write(value) }
func encode(_ value: String) throws { write(value) }
func encode(_ value: Double) throws { write(value) }
func encode(_ value: Float) throws { write(value) }
func encode(_ value: Int) throws { write(Int64(value)) }
func encode(_ value: Int8) throws { write(value) }
func encode(_ value: Int16) throws { write(value) }
func encode(_ value: Int32) throws { write(value) }
func encode(_ value: Int64) throws { write(value) }
func encode(_ value: UInt) throws { write(UInt64(value)) }
func encode(_ value: UInt8) throws { write(value) }
func encode(_ value: UInt16) throws { write(value) }
func encode(_ value: UInt32) throws { write(value) }
func encode(_ value: UInt64) throws { write(value) }
func encode <T: Encodable> (_ value: T) throws {
precondition(didWrite == false, "Data already written")
try encoder.writeEncodable(value)
didWrite = true
}
// MARK: - Private Methods
private func write<T: PredicateValue>(_ value: T) {
write(value.predicateValue)
}
private func write(_ value: Value) {
precondition(didWrite == false, "Data already written")
encoder.write(value)
didWrite = true
}
}
// MARK: - UnkeyedEncodingContainer
internal final class PredicateUnkeyedEncodingContainer: UnkeyedEncodingContainer {
// MARK: - Properties
/// A reference to the encoder we're writing to.
let encoder: PredicateEncoder.Encoder
/// The path of coding keys taken to get to this point in encoding.
let codingPath: [CodingKey]
// MARK: - Initialization
deinit {
// write array operators
// count
self.encoder.codingPath.append(OperatorCodingKey(operatorValue: .count))
encoder.write(.uint64(UInt64(count)))
self.encoder.codingPath.removeLast()
}
init(referencing encoder: PredicateEncoder.Encoder) {
self.encoder = encoder
self.codingPath = encoder.codingPath
}
// MARK: - Methods
/// The number of elements encoded into the container.
private(set) var count: Int = 0
func encodeNil() throws { append(.null) }
func encode(_ value: Bool) throws { append(value) }
func encode(_ value: String) throws { append(value) }
func encode(_ value: Double) throws { append(value) }
func encode(_ value: Float) throws { append(value) }
func encode(_ value: Int) throws { append(Int64(value)) }
func encode(_ value: Int8) throws { append(value) }
func encode(_ value: Int16) throws { append(value) }
func encode(_ value: Int32) throws { append(value) }
func encode(_ value: Int64) throws { append(value) }
func encode(_ value: UInt) throws { append(UInt64(value)) }
func encode(_ value: UInt8) throws { append(value) }
func encode(_ value: UInt16) throws { append(value) }
func encode(_ value: UInt32) throws { append(value) }
func encode(_ value: UInt64) throws { append(value) }
func encode <T: Encodable> (_ value: T) throws {
let key = IndexCodingKey(index: count)
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
try encoder.writeEncodable(value)
count += 1
}
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
fatalError()
}
func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
fatalError()
}
func superEncoder() -> Encoder {
fatalError()
}
// MARK: - Private Methods
private func append<T: PredicateValue>(_ value: T) {
append(value.predicateValue)
}
private func append(_ value: Value) {
let key = IndexCodingKey(index: count)
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
encoder.write(value)
count += 1
}
}
internal struct IndexCodingKey: CodingKey, Equatable, Hashable {
let index: Int
init(index: Int) {
self.index = index
}
var stringValue: String {
return index.description
}
init?(stringValue: String) {
guard let index = UInt(stringValue)
else { return nil }
self.init(index: Int(index))
}
var intValue: Int? {
return index
}
init?(intValue: Int) {
self.init(index: intValue)
}
}
internal struct OperatorCodingKey: CodingKey, Equatable, Hashable {
let operatorValue: PredicateKeyPath.Operator
init(operatorValue: PredicateKeyPath.Operator) {
self.operatorValue = operatorValue
}
var stringValue: String {
return operatorValue.rawValue
}
init?(stringValue: String) {
guard let operatorValue = PredicateKeyPath.Operator(rawValue: stringValue)
else { return nil }
self.init(operatorValue: operatorValue)
}
var intValue: Int? {
return nil
}
init?(intValue: Int) {
return nil
}
}
| mit | 4cdb52c132c5ffb5b0e6abc07c0f663f | 26.617706 | 150 | 0.59034 | 4.623105 | false | false | false | false |
KevinMorais/iOS-Mapbox | Test-Mapbox/Controllers/HomeViewController.swift | 1 | 11303 | //
// HomeViewController.swift
// Test-Mapbox
//
// Created by Kevin Morais on 15/01/2017.
// Copyright © 2017 Kevin Morais. All rights reserved.
//
import UIKit
import CoreLocation
protocol HomeViewControllerDelegate: class {
func didSaveCoordinate(coordinates: [CLLocationCoordinate2D])
}
class HomeViewController: UIViewController {
weak var delegate: HomeViewControllerDelegate?
@IBOutlet weak var mapView: TMapView!
@IBOutlet var moveButton: UIBarButtonItem!
@IBOutlet var locateButton: UIButton!
fileprivate var isMovingMode: Bool = false {
didSet {
self.switchRightButton(isMoving: self.isMovingMode)
self.locateButton.animateHide(hidden: self.isMovingMode)
}
}
var isUserLocationMode: Bool = true
fileprivate var userLocationPin: TMapPointAnnotation?
fileprivate var locationManager = CLLocationManager()
fileprivate var searchController: UISearchController!
fileprivate var centerPin: TMapPointAnnotation?
private var blurEffectView: UIVisualEffectView?
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
self.initializeSearchController()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.initializeLocation()
}
/// Initialize the user location
private func initializeLocation() {
self.locationManager.delegate = self
//Check first if the user has accepted to share his location with this application
if CLLocationManager.authorizationStatus() == .notDetermined {
self.locationManager.requestWhenInUseAuthorization()
}
else if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
self.locationManager.startUpdatingLocation()
}
}
private func initializeSearchController() {
//Initialize the controller
let searchTableView = self.storyboard?.instantiateViewController(withIdentifier: "SearchTableViewController") as! SearchTableViewController
self.searchController = UISearchController(searchResultsController: searchTableView)
self.searchController.searchResultsUpdater = searchTableView
searchTableView.delegate = self
//Initialize the search bar
let searchBar = self.searchController.searchBar
searchBar.placeholder = "Search for places"
searchBar.delegate = self
self.navigationItem.titleView = searchBar
self.searchController.hidesNavigationBarDuringPresentation = false
self.searchController.dimsBackgroundDuringPresentation = true
self.definesPresentationContext = true
}
fileprivate func switchRightButton(isMoving: Bool) {
if isMoving {
self.moveButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.userDidTapMoveButton(_:)))
self.moveButton.tintColor = UIColor.red
} else {
self.moveButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(self.userDidTapMoveButton(_:)))
self.moveButton.tintColor = self.view.tintColor
}
self.navigationItem.setRightBarButton(self.moveButton, animated: true)
}
// MARK: UI Actions
@IBAction func userDidTapLocateButton(_ sender: Any) {
self.isMovingMode = false
self.isUserLocationMode = true
if self.userLocationPin != nil {
self.mapView.setCenter(self.userLocationPin!.coordinate, zoomLevel: 16, animated: true)
}
}
@IBAction func userDidTapMoveButton(_ sender: Any) {
self.isUserLocationMode = false
self.isMovingMode = !self.isMovingMode
if self.isMovingMode {
if self.centerPin == nil {
self.centerPin = TMapPointAnnotation(at: mapView.centerCoordinate, title: "Center", subtitle: "")
}
self.mapView.addAnnotation(self.centerPin!)
} else {
//Add a pin depending of the center pin
if self.centerPin != nil {
// Ask for the human readable address
let _ = TMapGeocoder.sharedInstance.geocode(coord: self.centerPin!.coordinate) { (placemarks, error) in
if error != nil {
print(error!.localizedDescription)
return
}
if let placemark = placemarks?.first {
let newAnnot = self.addAnotation(coordinate: placemark.coordinate, center: true, persist: true, title: placemark.name, subtitle: placemark.qualifiedName)
//Set annotation selected
self.mapView.selectAnnotation(newAnnot, animated: true)
}
self.mapView.removeAnnotation(self.centerPin!)
self.centerPin = nil
}
}
}
}
/// This method will show an alert with a cancel button
fileprivate func showAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
/// This method add the user location pin on the map
fileprivate func addUserLocation(coord: CLLocationCoordinate2D) {
//Check if the coordinate have changed, if not we stop here
if self.userLocationPin != nil && self.userLocationPin!.coordinate.equal(coord: coord) {
return
}
//If the userlocation is not nil we remove the one on the map
if self.userLocationPin != nil {
self.mapView.removeAnnotation(self.userLocationPin!)
}
//Add pin and zoom the map on it
self.userLocationPin = self.addAnotation(coordinate: coord, center: self.isUserLocationMode, persist: false, title: "Your position", subtitle: "")
}
/// This method will add an annotation to the map and return the corresponding pin
func addAnotation(coordinate: CLLocationCoordinate2D, center: Bool, persist: Bool, title: String, subtitle: String) -> TMapPointAnnotation {
//Create a pin
let pin = TMapPointAnnotation(at: coordinate, title: title, subtitle: subtitle)
//Add it to the map
self.mapView.addAnnotation(pin)
//Persist the coordinates
if persist {
//Persist the current coordinate and send all the saved coordinates in the main thread
coordinate.persist(completionHandler: { (coordinates) in
DispatchQueue.main.async(execute: {
if coordinates != nil {
self.delegate?.didSaveCoordinate(coordinates: coordinates!)
}
})
})
}
//Center the map to the pin
if center {
self.mapView.setCenter(coordinate, zoomLevel: 16, animated: true)
}
return pin
}
fileprivate func hideBlurView(hide: Bool) {
//only apply the blur if the user hasn't disabled transparency effects
if !UIAccessibilityIsReduceTransparencyEnabled() {
if self.blurEffectView == nil {
self.blurEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
self.blurEffectView?.alpha = 0.99
}
if hide {
self.blurEffectView?.removeFromSuperview()
} else {
self.view.addSubview(self.blurEffectView!)
self.blurEffectView!.bindFrameToSuperviewBounds()
}
} else {
self.view.backgroundColor = UIColor.black
}
}
}
// MARK: CLLocationManagerDelegate
extension HomeViewController: CLLocationManagerDelegate {
internal func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
self.locationManager.startUpdatingLocation()
}
else if status != .notDetermined {
self.showAlert(title: "Error", message: "You must activate the location to be able to use this application")
}
}
internal func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let coordinate = locations.first?.coordinate
//Add a user location pin
if coordinate != nil {
self.addUserLocation(coord: coordinate!)
}
}
}
// MARK: MGLMapViewDelegate
extension HomeViewController: TMapViewDelegate {
// Return nil here to use the default marker.
internal func mapView(_ mapView: TMapView, imageFor annotation: TMapAnnotation) -> TMapAnnotationImage? {
return nil
}
// Allow callout view to appear when an annotation is tapped.
internal func mapView(_ mapView: TMapView, annotationCanShowCallout annotation: TMapAnnotation) -> Bool {
return true
}
internal func mapViewDidFinishRenderingFrame(_ mapView: TMapView, fullyRendered: Bool) {
//If the centered pin is activate we do this
if self.isMovingMode {
self.centerPin?.coordinate = self.mapView.centerCoordinate
}
}
}
// MARK: SearchTableViewControllerDelegate
extension HomeViewController: SearchTableViewControllerDelegate {
internal func userDidSelectPlacemark(placemark: TMapPlacemark) {
self.isUserLocationMode = false
let _ = self.addAnotation(coordinate: placemark.coordinate, center: true, persist: true, title: placemark.name, subtitle: placemark.qualifiedName)
self.searchController.searchBar.text = ""
}
}
extension HomeViewController: UISearchBarDelegate {
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
self.hideBlurView(hide: false)
// Deactivate moving mode if the user is currently in this mode
if self.isMovingMode {
self.isMovingMode = false
if self.centerPin != nil {
self.mapView.removeAnnotation(self.centerPin!)
}
}
//Disable the nav buttons
self.navigationItem.leftBarButtonItem?.isEnabled = false
self.navigationItem.rightBarButtonItem?.isEnabled = false
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
self.hideBlurView(hide: true)
//Enable the nav buttons
self.navigationItem.leftBarButtonItem?.isEnabled = true
self.navigationItem.rightBarButtonItem?.isEnabled = true
}
}
| apache-2.0 | 763bd896daa673b2318175b6b3565c4a | 34.540881 | 177 | 0.622633 | 5.810797 | false | false | false | false |
gottesmm/swift | stdlib/public/core/MutableCollection.swift | 4 | 16218 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A type that provides subscript access to its elements.
///
/// In most cases, it's best to ignore this protocol and use the
/// `MutableCollection` protocol instead, because it has a more complete
/// interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'MutableCollection' instead")
public typealias MutableIndexable = _MutableIndexable
public protocol _MutableIndexable : _Indexable {
// FIXME(ABI)#52 (Recursive Protocol Constraints): there is no reason for this protocol
// to exist apart from missing compiler features that we emulate with it.
// rdar://problem/20531108
//
// This protocol is almost an implementation detail of the standard
// library; it is used to deduce things like the `SubSequence` and
// `Iterator` type from a minimal collection, but it is also used in
// exposed places like as a constraint on `IndexingIterator`.
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
// TODO: swift-3-indexing-model - Index only needs to be comparable or must be comparable..?
associatedtype Index : Comparable
/// The position of the first element in a nonempty collection.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
var startIndex: Index { get }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// When you need a range that includes the last element of a collection, use
/// the half-open range operator (`..<`) with `endIndex`. The `..<` operator
/// creates a range that doesn't include the upper bound, so it's always
/// safe to use with `endIndex`. For example:
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let index = numbers.index(of: 30) {
/// print(numbers[index ..< numbers.endIndex])
/// }
/// // Prints "[30, 40, 50]"
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
var endIndex: Index { get }
// The declaration of _Element and subscript here is a trick used to
// break a cyclic conformance/deduction that Swift can't handle. We
// need something other than a Collection.Iterator.Element that can
// be used as IndexingIterator<T>'s Element. Here we arrange for
// the Collection itself to have an Element type that's deducible from
// its subscript. Ideally we'd like to constrain this Element to be the same
// as Collection.Iterator.Element (see below), but we have no way of
// expressing it today.
associatedtype _Element
/// Accesses the element at the specified position.
///
/// For example, you can replace an element of an array by using its
/// subscript.
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// streets[1] = "Butler"
/// print(streets[1])
/// // Prints "Butler"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one
/// past the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
subscript(position: Index) -> _Element { get set }
/// A collection that represents a contiguous subrange of the collection's
/// elements.
associatedtype SubSequence
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// streets[index!] = "Eustace"
/// print(streets[index!])
/// // Prints "Eustace"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
subscript(bounds: Range<Index>) -> SubSequence { get set }
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(bounds.contains(index))
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>)
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(
/// bounds.contains(range.lowerBound) ||
/// range.lowerBound == bounds.upperBound)
/// precondition(
/// bounds.contains(range.upperBound) ||
/// range.upperBound == bounds.upperBound)
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>)
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
func index(after i: Index) -> Index
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
func formIndex(after i: inout Index)
}
// TODO: swift-3-indexing-model - review the following
/// A collection that supports subscript assignment.
///
/// Collections that conform to `MutableCollection` gain the ability to
/// change the value of their elements. This example shows how you can
/// modify one of the names in an array of students.
///
/// var students = ["Ben", "Ivy", "Jordell", "Maxime"]
/// if let i = students.index(of: "Maxime") {
/// students[i] = "Max"
/// }
/// print(students)
/// // Prints "["Ben", "Ivy", "Jordell", "Max"]"
///
/// In addition to changing the value of an individual element, you can also
/// change the values of a slice of elements in a mutable collection. For
/// example, you can sort *part* of a mutable collection by calling the
/// mutable `sort()` method on a subscripted subsequence. Here's an
/// example that sorts the first half of an array of integers:
///
/// var numbers = [15, 40, 10, 30, 60, 25, 5, 100]
/// numbers[0..<4].sort()
/// print(numbers)
/// // Prints "[10, 15, 30, 40, 60, 25, 5, 100]"
///
/// The `MutableCollection` protocol allows changing the values of a
/// collection's elements but not the length of the collection itself. For
/// operations that require adding or removing elements, see the
/// `RangeReplaceableCollection` protocol instead.
///
/// Conforming to the MutableCollection Protocol
/// ============================================
///
/// To add conformance to the `MutableCollection` protocol to your own
/// custom collection, upgrade your type's subscript to support both read
/// and write access.
///
/// A value stored into a subscript of a `MutableCollection` instance must
/// subsequently be accessible at that same position. That is, for a mutable
/// collection instance `a`, index `i`, and value `x`, the two sets of
/// assignments in the following code sample must be equivalent:
///
/// a[i] = x
/// let y = a[i]
///
/// // Must be equivalent to:
/// a[i] = x
/// let y = x
public protocol MutableCollection : _MutableIndexable, Collection {
// FIXME(ABI)#181: should be constrained to MutableCollection
// (<rdar://problem/20715009> Implement recursive protocol
// constraints)
/// A collection that represents a contiguous subrange of the collection's
/// elements.
associatedtype SubSequence : Collection /*: MutableCollection*/
= MutableSlice<Self>
/// Accesses the element at the specified position.
///
/// For example, you can replace an element of an array by using its
/// subscript.
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// streets[1] = "Butler"
/// print(streets[1])
/// // Prints "Butler"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one
/// past the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
subscript(position: Index) -> Iterator.Element {get set}
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// streets[index!] = "Eustace"
/// print(streets[index!])
/// // Prints "Eustace"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
subscript(bounds: Range<Index>) -> SubSequence {get set}
/// Reorders the elements of the collection such that all the elements
/// that match the given predicate are after all the elements that do
/// not match the predicate.
///
/// After partitioning a collection, there is a pivot index `p` where
/// no element before `p` satisfies the `belongsInSecondPartition`
/// predicate and every element at or after `p` satisfies
/// `belongsInSecondPartition`.
///
/// In the following example, an array of numbers is partitioned by a
/// predicate that matches elements greater than 30.
///
/// var numbers = [30, 40, 20, 30, 30, 60, 10]
/// let p = numbers.partition(by: { $0 > 30 })
/// // p == 5
/// // numbers == [30, 10, 20, 30, 30, 60, 40]
///
/// The `numbers` array is now arranged in two partitions. The first
/// partition, `numbers.prefix(upTo: p)`, is made up of the elements that
/// are not greater than 30. The second partition, `numbers.suffix(from: p)`,
/// is made up of the elements that *are* greater than 30.
///
/// let first = numbers.prefix(upTo: p)
/// // first == [30, 10, 20, 30, 30]
/// let second = numbers.suffix(from: p)
/// // second == [60, 40]
///
/// - Parameter belongsInSecondPartition: A predicate used to partition
/// the collection. All elements satisfying this predicate are ordered
/// after all elements not satisfying it.
/// - Returns: The index of the first element in the reordered collection
/// that matches `belongsInSecondPartition`. If no elements in the
/// collection match `belongsInSecondPartition`, the returned index is
/// equal to the collection's `endIndex`.
///
/// - Complexity: O(*n*)
mutating func partition(
by belongsInSecondPartition: (Iterator.Element) throws -> Bool
) rethrows -> Index
/// Call `body(p)`, where `p` is a pointer to the collection's
/// mutable contiguous storage. If no such storage exists, it is
/// first created. If the collection does not support an internal
/// representation in a form of mutable contiguous storage, `body` is not
/// called and `nil` is returned.
///
/// Often, the optimizer can eliminate bounds- and uniqueness-checks
/// within an algorithm, but when that fails, invoking the
/// same algorithm on `body`\ 's argument lets you trade safety for
/// speed.
mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (UnsafeMutablePointer<Iterator.Element>, Int) throws -> R
) rethrows -> R?
// FIXME(ABI)#53 (Type Checker): the signature should use
// UnsafeMutableBufferPointer, but the compiler can't handle that.
//
// <rdar://problem/21933004> Restore the signature of
// _withUnsafeMutableBufferPointerIfSupported() that mentions
// UnsafeMutableBufferPointer
}
// TODO: swift-3-indexing-model - review the following
extension MutableCollection {
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (UnsafeMutablePointer<Iterator.Element>, Int) throws -> R
) rethrows -> R? {
return nil
}
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// streets[index!] = "Eustace"
/// print(streets[index!])
/// // Prints "Eustace"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
public subscript(bounds: Range<Index>) -> MutableSlice<Self> {
get {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return MutableSlice(base: self, bounds: bounds)
}
set {
_writeBackMutableSlice(&self, bounds: bounds, slice: newValue)
}
}
}
@available(*, unavailable, renamed: "MutableCollection")
public typealias MutableCollectionType = MutableCollection
@available(*, unavailable, message: "Please use 'Collection where SubSequence : MutableCollection'")
public typealias MutableSliceable = Collection
| apache-2.0 | 46936314161cbee1f93b5a6cb737658e | 41.791557 | 110 | 0.660254 | 4.345659 | false | false | false | false |
nixzhu/AudioBot | VoiceMemo/RecordButton.swift | 2 | 5868 | //
// RecordButton.swift
// VoiceMemo
//
// Created by NIX on 15/12/25.
// Copyright © 2015年 nixWork. All rights reserved.
//
import UIKit
@IBDesignable
class RecordButton: UIButton {
override var intrinsicContentSize : CGSize {
return CGSize(width: 100, height: 100)
}
lazy var outerPath: UIBezierPath = {
return UIBezierPath(ovalIn: self.bounds.insetBy(dx: 8, dy: 8))
}()
lazy var innerDefaultPath: UIBezierPath = {
return UIBezierPath(roundedRect: self.bounds.insetBy(dx: 14, dy: 14), cornerRadius: 43)
}()
lazy var innerRecordingPath: UIBezierPath = {
return UIBezierPath(roundedRect: self.bounds.insetBy(dx: 35, dy: 35), cornerRadius: 5)
}()
var fromInnerPath: UIBezierPath {
switch appearance {
case .default:
return innerRecordingPath
case .recording:
return innerDefaultPath
}
}
var toInnerPath: UIBezierPath {
switch appearance {
case .default:
return innerDefaultPath
case .recording:
return innerRecordingPath
}
}
enum Appearance {
case `default`
case recording
var fromOuterLineWidth: CGFloat {
switch self {
case .default:
return 3
case .recording:
return 8
}
}
var toOuterLineWidth: CGFloat {
switch self {
case .default:
return 8
case .recording:
return 3
}
}
var fromOuterFillColor: UIColor {
switch self {
case .default:
return UIColor(red: 237/255.0, green: 247/255.0, blue: 1, alpha: 1)
case .recording:
return UIColor.white
}
}
var toOuterFillColor: UIColor {
switch self {
case .default:
return UIColor.white
case .recording:
return UIColor(red: 237/255.0, green: 247/255.0, blue: 1, alpha: 1)
}
}
var fromInnerFillColor: UIColor {
switch self {
case .default:
return UIColor.red
case .recording:
return UIColor.blue
}
}
var toInnerFillColor: UIColor {
switch self {
case .default:
return UIColor.blue
case .recording:
return UIColor.red
}
}
}
var appearance: Appearance = .default {
didSet {
let duration: TimeInterval = 0.25
do {
let animation = CABasicAnimation(keyPath: "lineWidth")
animation.fromValue = appearance.fromOuterLineWidth
animation.toValue = appearance.toOuterLineWidth
animation.duration = duration
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animation.fillMode = kCAFillModeBoth
animation.isRemovedOnCompletion = false
outerShapeLayer.add(animation, forKey: "lineWidth")
}
do {
let animation = CABasicAnimation(keyPath: "fillColor")
animation.fromValue = appearance.fromOuterFillColor.cgColor
animation.toValue = appearance.toOuterFillColor.cgColor
animation.duration = duration
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animation.fillMode = kCAFillModeBoth
animation.isRemovedOnCompletion = false
outerShapeLayer.add(animation, forKey: "fillColor")
}
do {
let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = fromInnerPath.cgPath
animation.toValue = toInnerPath.cgPath
animation.duration = duration
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animation.fillMode = kCAFillModeBoth
animation.isRemovedOnCompletion = false
innerShapeLayer.add(animation, forKey: "path")
}
do {
let animation = CABasicAnimation(keyPath: "fillColor")
animation.fromValue = appearance.fromInnerFillColor.cgColor
animation.toValue = appearance.toInnerFillColor.cgColor
animation.duration = duration
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animation.fillMode = kCAFillModeBoth
animation.isRemovedOnCompletion = false
innerShapeLayer.add(animation, forKey: "fillColor")
}
}
}
lazy var outerShapeLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.path = self.outerPath.cgPath
layer.lineWidth = self.appearance.toOuterLineWidth
layer.strokeColor = UIColor.blue.cgColor
layer.fillColor = self.appearance.toOuterFillColor.cgColor
layer.fillRule = kCAFillRuleEvenOdd
layer.contentsScale = UIScreen.main.scale
return layer
}()
lazy var innerShapeLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.path = self.toInnerPath.cgPath
layer.fillColor = self.appearance.toInnerFillColor.cgColor
layer.fillRule = kCAFillRuleEvenOdd
layer.contentsScale = UIScreen.main.scale
return layer
}()
override func didMoveToSuperview() {
super.didMoveToSuperview()
layer.addSublayer(outerShapeLayer)
layer.addSublayer(innerShapeLayer)
}
}
| mit | 7f18dacfa1c5aba8ccc3d71499fe19de | 29.868421 | 101 | 0.577835 | 5.744368 | false | false | false | false |
jairoeli/Instasheep | InstagramFirebase/InstagramFirebase/SharePhoto/SharePhotoController.swift | 1 | 3863 | //
// SharePhotoController.swift
// InstagramFirebase
//
// Created by Jairo Eli de Leon on 4/2/17.
// Copyright © 2017 DevMountain. All rights reserved.
//
import UIKit
import Firebase
class SharePhotoController: UIViewController {
// MARK: - Properties
var selectedImage: UIImage? {
didSet {
self.imageView.image = selectedImage
}
}
static let updateFeedNotificationName = NSNotification.Name(rawValue: "UpdateFeed")
let containerView = UIView() <== {
$0.backgroundColor = .white
}
let imageView = UIImageView() <== {
$0.backgroundColor = .red
$0.contentMode = .scaleAspectFill
$0.clipsToBounds = true
}
let textView = UITextView() <== {
$0.font = UIFont.systemFont(ofSize: 14)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.rgb(red: 240, green: 240, blue: 240)
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Share", style: .plain, target: self, action: #selector(handleShare))
setupImageAndTextViews()
}
override var prefersStatusBarHidden: Bool {
return true
}
// MARK: - Share & Save
@objc func handleShare() {
guard let caption = textView.text, caption.count > 0 else { return }
guard let image = selectedImage else { return }
guard let uploadData = UIImageJPEGRepresentation(image, 0.5) else { return }
navigationItem.rightBarButtonItem?.isEnabled = false
let filename = NSUUID().uuidString
Storage.storage().reference().child("posts").child(filename).putData(uploadData, metadata: nil) { (metadata, err) in
if let err = err {
self.navigationItem.rightBarButtonItem?.isEnabled = true
print("Failed to upload post image:", err)
return
}
guard let imageURL = metadata?.downloadURL()?.absoluteString else { return }
print("Successfully uploaded post image:", imageURL)
self.saveToDatabase(with: imageURL)
}
}
fileprivate func saveToDatabase(with imageURL: String) {
guard let postImage = selectedImage else { return }
guard let caption = textView.text else { return }
guard let uid = Auth.auth().currentUser?.uid else { return }
let userPostRef = Database.database().reference().child("posts").child(uid)
let ref = userPostRef.childByAutoId()
let values = ["imageURL": imageURL,
"caption": caption,
"imageWidth": postImage.size.width,
"imageHeight": postImage.size.height,
"creationDate": Date().timeIntervalSince1970] as [String: Any]
ref.updateChildValues(values) { (err, _) in
if let err = err {
self.navigationItem.rightBarButtonItem?.isEnabled = true
print("Failed to save post to DB", err)
}
print("Successfully saved post to DB")
self.dismiss(animated: true, completion: nil)
NotificationCenter.default.post(name: SharePhotoController.updateFeedNotificationName, object: nil)
}
}
}
extension SharePhotoController {
fileprivate func setupImageAndTextViews() {
view.addSubview(containerView)
containerView.addSubview(imageView)
containerView.addSubview(textView)
containerView.anchor(top: topLayoutGuide.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 100)
imageView.anchor(top: containerView.topAnchor, left: containerView.leftAnchor, bottom: containerView.bottomAnchor, right: nil, paddingTop: 8, paddingLeft: 8, paddingBottom: 8, paddingRight: 0, width: 84, height: 0)
textView.anchor(top: containerView.topAnchor, left: imageView.rightAnchor, bottom: containerView.bottomAnchor, right: containerView.rightAnchor, paddingTop: 0, paddingLeft: 4, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
}
}
| mit | 9bc1b2047bb8ffea32ad5825eec0090b | 32.582609 | 235 | 0.692128 | 4.485482 | false | false | false | false |
flovilmart/Carthage | Source/carthage/Build.swift | 1 | 6230 | //
// Build.swift
// Carthage
//
// Created by Justin Spahr-Summers on 2014-10-11.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import CarthageKit
import Commandant
import Foundation
import LlamaKit
import ReactiveCocoa
public struct BuildCommand: CommandType {
public let verb = "build"
public let function = "Build the project's dependencies"
public func run(mode: CommandMode) -> Result<()> {
return ColdSignal.fromResult(BuildOptions.evaluate(mode))
.map { self.buildWithOptions($0) }
.merge(identity)
.wait()
}
/// Builds a project with the given options.
public func buildWithOptions(options: BuildOptions) -> ColdSignal<()> {
return self.createLoggingSink(options)
.map { (stdoutSink, temporaryURL) -> ColdSignal<()> in
let directoryURL = NSURL.fileURLWithPath(options.directoryPath, isDirectory: true)!
let (stdoutSignal, schemeSignals) = self.buildProjectInDirectoryURL(directoryURL, options: options)
stdoutSignal.observe(stdoutSink)
let formatting = options.colorOptions.formatting
return schemeSignals
.concat(identity)
.on(started: {
if let temporaryURL = temporaryURL {
carthage.println(formatting.bullets + "xcodebuild output can be found in " + formatting.path(string: temporaryURL.path!))
}
}, next: { (project, scheme) in
carthage.println(formatting.bullets + "Building scheme " + formatting.quote(scheme) + " in " + formatting.projectName(string: project.description))
})
.then(.empty())
}
.merge(identity)
}
/// Builds the project in the given directory, using the given options.
///
/// Returns a hot signal of `stdout` from `xcodebuild`, and a cold signal of
/// cold signals representing each scheme being built.
private func buildProjectInDirectoryURL(directoryURL: NSURL, options: BuildOptions) -> (HotSignal<NSData>, ColdSignal<BuildSchemeSignal>) {
let (stdoutSignal, stdoutSink) = HotSignal<NSData>.pipe()
let project = Project(directoryURL: directoryURL)
var buildSignal = project.loadCombinedCartfile()
.map { _ in project }
.catch { error in
if options.skipCurrent {
return .error(error)
} else {
// Ignore Cartfile loading failures. Assume the user just
// wants to build the enclosing project.
return .empty()
}
}
.mergeMap { project in
return project
.migrateIfNecessary(options.colorOptions)
.on(next: carthage.println)
.then(.single(project))
}
.mergeMap { (project: Project) -> ColdSignal<BuildSchemeSignal> in
let (dependenciesOutput, dependenciesSignals) = project.buildCheckedOutDependenciesWithConfiguration(options.configuration, forPlatform: options.buildPlatform.platform)
dependenciesOutput.observe(stdoutSink)
return dependenciesSignals
}
if !options.skipCurrent {
let (currentOutput, currentSignals) = buildInDirectory(directoryURL, withConfiguration: options.configuration, platform: options.buildPlatform.platform)
currentOutput.observe(stdoutSink)
buildSignal = buildSignal.concat(currentSignals)
}
return (stdoutSignal, buildSignal)
}
/// Creates a sink for logging, returning the sink and the URL to any
/// temporary file on disk.
private func createLoggingSink(options: BuildOptions) -> ColdSignal<(FileSink<NSData>, NSURL?)> {
if options.verbose {
let out: (FileSink<NSData>, NSURL?) = (FileSink.standardOutputSink(), nil)
return .single(out)
} else {
return FileSink.openTemporaryFile()
.map { sink, URL in (sink, .Some(URL)) }
}
}
}
public struct BuildOptions: OptionsType {
public let configuration: String
public let buildPlatform: BuildPlatform
public let skipCurrent: Bool
public let colorOptions: ColorOptions
public let verbose: Bool
public let directoryPath: String
public static func create(configuration: String)(buildPlatform: BuildPlatform)(skipCurrent: Bool)(colorOptions: ColorOptions)(verbose: Bool)(directoryPath: String) -> BuildOptions {
return self(configuration: configuration, buildPlatform: buildPlatform, skipCurrent: skipCurrent, colorOptions: colorOptions, verbose: verbose, directoryPath: directoryPath)
}
public static func evaluate(m: CommandMode) -> Result<BuildOptions> {
return create
<*> m <| Option(key: "configuration", defaultValue: "Release", usage: "the Xcode configuration to build")
<*> m <| Option(key: "platform", defaultValue: .All, usage: "the platform to build for (one of ‘all’, ‘Mac’, or ‘iOS’)")
<*> m <| Option(key: "skip-current", defaultValue: true, usage: "don't skip building the Carthage project (in addition to its dependencies)")
<*> ColorOptions.evaluate(m)
<*> m <| Option(key: "verbose", defaultValue: false, usage: "print xcodebuild output inline")
<*> m <| Option(defaultValue: NSFileManager.defaultManager().currentDirectoryPath, usage: "the directory containing the Carthage project")
}
}
/// Represents the user’s chosen platform to build for.
public enum BuildPlatform: Equatable {
/// Build for all available platforms.
case All
/// Build only for iOS.
case iOS
/// Build only for OS X.
case Mac
/// The `Platform` corresponding to this setting.
public var platform: Platform? {
switch self {
case .All:
return nil
case .iOS:
return .iOS
case .Mac:
return .Mac
}
}
}
public func == (lhs: BuildPlatform, rhs: BuildPlatform) -> Bool {
switch (lhs, rhs) {
case (.All, .All):
return true
case (.iOS, .iOS):
return true
case (.Mac, .Mac):
return true
default:
return false
}
}
extension BuildPlatform: Printable {
public var description: String {
switch self {
case .All:
return "all"
case .iOS:
return "iOS"
case .Mac:
return "Mac"
}
}
}
extension BuildPlatform: ArgumentType {
public static let name = "platform"
private static let acceptedStrings: [String: BuildPlatform] = [
"Mac": .Mac, "macosx": .Mac,
"iOS": .iOS, "iphoneos": .iOS, "iphonesimulator": .iOS,
"all": .All
]
public static func fromString(string: String) -> BuildPlatform? {
for (key, platform) in acceptedStrings {
if string.caseInsensitiveCompare(key) == NSComparisonResult.OrderedSame {
return platform
}
}
return nil
}
}
| mit | 63922726c911f7cf72b2d8c02246e72e | 29.470588 | 182 | 0.71332 | 3.818182 | false | false | false | false |
limianwang/swift-calculator | Calculator/AppDelegate.swift | 1 | 6387 | //
// AppDelegate.swift
// Calculator
//
// Created by Limian Wang on 2015-08-24.
// Copyright (c) 2015 LiTech Ventures Inc. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.litech.Calculator" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Calculator", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Calculator.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
| mit | e1408fc5735cae41afbf61d58242ea06 | 51.785124 | 290 | 0.698607 | 5.838208 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Pods/OAuthSwift/Sources/HMAC.swift | 3 | 1440 | //
// HMAC.swift
// OAuthSwift
//
// Created by Dongri Jin on 1/28/15.
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Foundation
open class HMAC {
let key: [UInt8] = []
class internal func sha1(key: Data, message: Data) -> Data? {
let blockSize = 64
var key = key.bytes
let message = message.bytes
if key.count > blockSize {
key = SHA1(key).calculate()
} else if key.count < blockSize { // padding
key += [UInt8](repeating: 0, count: blockSize - key.count)
}
var ipad = [UInt8](repeating: 0x36, count: blockSize)
for idx in key.indices {
ipad[idx] = key[idx] ^ ipad[idx]
}
var opad = [UInt8](repeating: 0x5c, count: blockSize)
for idx in key.indices {
opad[idx] = key[idx] ^ opad[idx]
}
let ipadAndMessageHash = SHA1(ipad + message).calculate()
let mac = SHA1(opad + ipadAndMessageHash).calculate()
return Data(bytes: UnsafePointer<UInt8>(mac), count: mac.count)
}
}
extension HMAC: OAuthSwiftSignatureDelegate {
open static func sign(hashMethod: OAuthSwiftHashMethod, key: Data, message: Data) -> Data? {
switch hashMethod {
case .sha1:
return sha1(key: key, message: message)
case .none:
assertionFailure("Must no sign with none")
return nil
}
}
}
| mit | cad0d63bedd642e99df34b3d038ea767 | 25.181818 | 96 | 0.575694 | 3.769634 | false | false | false | false |
sunflash/SwiftHTTPClient | HTTPClient/Classes/Extension/UIImageView+Extension.swift | 1 | 766 | //
// UIImageView+Extension.swift
// HTTPClient
//
// Created by Min Wu on 07/05/2017.
// Copyright © 2017 Min WU. All rights reserved.
//
import Foundation
import UIKit
/// Extension to `UIImageView`
extension UIImageView {
/// Convenience function to display image from web url
///
/// - Parameters:
/// - url: url for image
/// - placeholder: placeholder image, optional
public func displayImage(from url: URL, withPlaceholder placeholder: UIImage? = nil) {
self.image = placeholder
URLSession.shared.dataTask(with: url) { (data, _, _) in
guard let imageData = data, let image = UIImage(data: imageData) else {return}
GCD.main.queue.async {self.image = image}
}.resume()
}
}
| mit | a6061fc975910feb0472b2f642435dfd | 27.333333 | 90 | 0.635294 | 4.090909 | false | false | false | false |
ben-ng/swift | test/Prototypes/CollectionTransformers.swift | 1 | 39487 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-stdlib-swift
// REQUIRES: executable_test
// FIXME: This test runs very slowly on watchOS.
// UNSUPPORTED: OS=watchos
public enum ApproximateCount {
case Unknown
case Precise(IntMax)
case Underestimate(IntMax)
case Overestimate(IntMax)
}
public protocol ApproximateCountableSequence : Sequence {
/// Complexity: amortized O(1).
var approximateCount: ApproximateCount { get }
}
/// A collection that provides an efficient way to split its index ranges.
public protocol SplittableCollection : Collection {
// We need this protocol so that collections with only forward or bidirectional
// traversals could customize their splitting behavior.
//
// FIXME: all collections with random access should conform to this protocol
// automatically.
/// Splits a given range of indices into a set of disjoint ranges covering
/// the same elements.
///
/// Complexity: amortized O(1).
///
/// FIXME: should that be O(log n) to cover some strange collections?
///
/// FIXME: index invalidation rules?
///
/// FIXME: a better name. Users will never want to call this method
/// directly.
///
/// FIXME: return an optional for the common case when split() cannot
/// subdivide the range further.
func split(_ range: Range<Index>) -> [Range<Index>]
}
internal func _splitRandomAccessIndexRange<
C : RandomAccessCollection
>(
_ elements: C,
_ range: Range<C.Index>
) -> [Range<C.Index>] {
let startIndex = range.lowerBound
let endIndex = range.upperBound
let length = elements.distance(from: startIndex, to: endIndex).toIntMax()
if length < 2 {
return [range]
}
let middle = elements.index(startIndex, offsetBy: C.IndexDistance(length / 2))
return [startIndex ..< middle, middle ..< endIndex]
}
/// A helper object to build a collection incrementally in an efficient way.
///
/// Using a builder can be more efficient than creating an empty collection
/// instance and adding elements one by one.
public protocol CollectionBuilder {
associatedtype Destination : Collection
associatedtype Element = Destination.Iterator.Element
init()
/// Gives a hint about the expected approximate number of elements in the
/// collection that is being built.
mutating func sizeHint(_ approximateSize: Int)
/// Append `element` to `self`.
///
/// If a collection being built supports a user-defined order, the element is
/// added at the end.
///
/// Complexity: amortized O(1).
mutating func append(_ element: Destination.Iterator.Element)
/// Append `elements` to `self`.
///
/// If a collection being built supports a user-defined order, the element is
/// added at the end.
///
/// Complexity: amortized O(n), where `n` is equal to `count(elements)`.
mutating func append<
C : Collection
where
C.Iterator.Element == Element
>(contentsOf elements: C)
/// Append elements from `otherBuilder` to `self`, emptying `otherBuilder`.
///
/// Equivalent to::
///
/// self.append(contentsOf: otherBuilder.takeResult())
///
/// but is more efficient.
///
/// Complexity: O(1).
mutating func moveContentsOf(_ otherBuilder: inout Self)
/// Build the collection from the elements that were added to this builder.
///
/// Once this function is called, the builder may not be reused and no other
/// methods should be called.
///
/// Complexity: O(n) or better (where `n` is the number of elements that were
/// added to this builder); typically O(1).
mutating func takeResult() -> Destination
}
public protocol BuildableCollectionProtocol : Collection {
associatedtype Builder : CollectionBuilder
}
extension Array : SplittableCollection {
public func split(_ range: Range<Int>) -> [Range<Int>] {
return _splitRandomAccessIndexRange(self, range)
}
}
public struct ArrayBuilder<T> : CollectionBuilder {
// FIXME: the compiler didn't complain when I remove public on 'Collection'.
// File a bug.
public typealias Destination = Array<T>
public typealias Element = T
internal var _resultParts = [[T]]()
internal var _resultTail = [T]()
public init() {}
public mutating func sizeHint(_ approximateSize: Int) {
_resultTail.reserveCapacity(approximateSize)
}
public mutating func append(_ element: T) {
_resultTail.append(element)
}
public mutating func append<
C : Collection
where
C.Iterator.Element == T
>(contentsOf elements: C) {
_resultTail.append(contentsOf: elements)
}
public mutating func moveContentsOf(_ otherBuilder: inout ArrayBuilder<T>) {
// FIXME: do something smart with the capacity set in this builder and the
// other builder.
_resultParts.append(_resultTail)
_resultTail = []
// FIXME: not O(1)!
_resultParts.append(contentsOf: otherBuilder._resultParts)
otherBuilder._resultParts = []
swap(&_resultTail, &otherBuilder._resultTail)
}
public mutating func takeResult() -> Destination {
_resultParts.append(_resultTail)
_resultTail = []
// FIXME: optimize. parallelize.
return Array(_resultParts.joined())
}
}
extension Array : BuildableCollectionProtocol {
public typealias Builder = ArrayBuilder<Element>
}
//===----------------------------------------------------------------------===//
// Fork-join
//===----------------------------------------------------------------------===//
// As sad as it is, I think for practical performance reasons we should rewrite
// the inner parts of the fork-join framework in C++. In way too many cases
// than necessary Swift requires an extra allocation to pin objects in memory
// for safe multithreaded access. -Dmitri
import SwiftShims
import SwiftPrivate
import Darwin
import Dispatch
// FIXME: port to Linux.
// XFAIL: linux
// A wrapper for pthread_t with platform-independent interface.
public struct _stdlib_pthread_t : Equatable, Hashable {
internal let _value: pthread_t
public var hashValue: Int {
return _value.hashValue
}
}
public func == (lhs: _stdlib_pthread_t, rhs: _stdlib_pthread_t) -> Bool {
return lhs._value == rhs._value
}
public func _stdlib_pthread_self() -> _stdlib_pthread_t {
return _stdlib_pthread_t(_value: pthread_self())
}
struct _ForkJoinMutex {
var _mutex: UnsafeMutablePointer<pthread_mutex_t>
init() {
_mutex = UnsafeMutablePointer.allocate(capacity: 1)
if pthread_mutex_init(_mutex, nil) != 0 {
fatalError("pthread_mutex_init")
}
}
func `deinit`() {
if pthread_mutex_destroy(_mutex) != 0 {
fatalError("pthread_mutex_init")
}
_mutex.deinitialize()
_mutex.deallocate(capacity: 1)
}
func withLock<Result>(_ body: () -> Result) -> Result {
if pthread_mutex_lock(_mutex) != 0 {
fatalError("pthread_mutex_lock")
}
let result = body()
if pthread_mutex_unlock(_mutex) != 0 {
fatalError("pthread_mutex_unlock")
}
return result
}
}
struct _ForkJoinCond {
var _cond: UnsafeMutablePointer<pthread_cond_t>
init() {
_cond = UnsafeMutablePointer.allocate(capacity: 1)
if pthread_cond_init(_cond, nil) != 0 {
fatalError("pthread_cond_init")
}
}
func `deinit`() {
if pthread_cond_destroy(_cond) != 0 {
fatalError("pthread_cond_destroy")
}
_cond.deinitialize()
_cond.deallocate(capacity: 1)
}
func signal() {
pthread_cond_signal(_cond)
}
func wait(_ mutex: _ForkJoinMutex) {
pthread_cond_wait(_cond, mutex._mutex)
}
}
final class _ForkJoinOneShotEvent {
var _mutex: _ForkJoinMutex = _ForkJoinMutex()
var _cond: _ForkJoinCond = _ForkJoinCond()
var _isSet: Bool = false
init() {}
deinit {
_cond.`deinit`()
_mutex.`deinit`()
}
func set() {
_mutex.withLock {
if !_isSet {
_isSet = true
_cond.signal()
}
}
}
/// Establishes a happens-before relation between calls to set() and wait().
func wait() {
_mutex.withLock {
while !_isSet {
_cond.wait(_mutex)
}
}
}
/// If the function returns true, it establishes a happens-before relation
/// between calls to set() and isSet().
func isSet() -> Bool {
return _mutex.withLock {
return _isSet
}
}
}
final class _ForkJoinWorkDeque<T> {
// FIXME: this is just a proof-of-concept; very inefficient.
// Implementation note: adding elements to the head of the deque is common in
// fork-join, so _deque is stored reversed (appending to an array is cheap).
// FIXME: ^ that is false for submission queues though.
var _deque: ContiguousArray<T> = []
var _dequeMutex: _ForkJoinMutex = _ForkJoinMutex()
init() {}
deinit {
precondition(_deque.isEmpty)
_dequeMutex.`deinit`()
}
var isEmpty: Bool {
return _dequeMutex.withLock {
return _deque.isEmpty
}
}
func prepend(_ element: T) {
_dequeMutex.withLock {
_deque.append(element)
}
}
func tryTakeFirst() -> T? {
return _dequeMutex.withLock {
let result = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
return result
}
}
func tryTakeFirstTwo() -> (T?, T?) {
return _dequeMutex.withLock {
let result1 = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
let result2 = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
return (result1, result2)
}
}
func append(_ element: T) {
_dequeMutex.withLock {
_deque.insert(element, at: 0)
}
}
func tryTakeLast() -> T? {
return _dequeMutex.withLock {
let result = _deque.first
if _deque.count > 0 {
_deque.remove(at: 0)
}
return result
}
}
func takeAll() -> ContiguousArray<T> {
return _dequeMutex.withLock {
let result = _deque
_deque = []
return result
}
}
func tryReplace(
_ value: T,
makeReplacement: @escaping () -> T,
isEquivalent: @escaping (T, T) -> Bool
) -> Bool {
return _dequeMutex.withLock {
for i in _deque.indices {
if isEquivalent(_deque[i], value) {
_deque[i] = makeReplacement()
return true
}
}
return false
}
}
}
final class _ForkJoinWorkerThread {
internal var _tid: _stdlib_pthread_t?
internal let _pool: ForkJoinPool
internal let _submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>
internal let _workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase>
internal init(
_pool: ForkJoinPool,
submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>,
workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase>
) {
self._tid = nil
self._pool = _pool
self._submissionQueue = submissionQueue
self._workDeque = workDeque
}
internal func startAsync() {
var queue: DispatchQueue?
if #available(OSX 10.10, iOS 8.0, *) {
queue = DispatchQueue.global(qos: .background)
} else {
queue = DispatchQueue.global(priority: .background)
}
queue!.async {
self._thread()
}
}
internal func _thread() {
print("_ForkJoinWorkerThread begin")
_tid = _stdlib_pthread_self()
outer: while !_workDeque.isEmpty || !_submissionQueue.isEmpty {
_pool._addRunningThread(self)
while true {
if _pool._tryStopThread() {
print("_ForkJoinWorkerThread detected too many threads")
_pool._removeRunningThread(self)
_pool._submitTasksToRandomWorkers(_workDeque.takeAll())
_pool._submitTasksToRandomWorkers(_submissionQueue.takeAll())
print("_ForkJoinWorkerThread end")
return
}
// Process tasks in FIFO order: first the work queue, then the
// submission queue.
if let task = _workDeque.tryTakeFirst() {
task._run()
continue
}
if let task = _submissionQueue.tryTakeFirst() {
task._run()
continue
}
print("_ForkJoinWorkerThread stealing tasks")
if let task = _pool._stealTask() {
task._run()
continue
}
// FIXME: steal from submission queues?
break
}
_pool._removeRunningThread(self)
}
assert(_workDeque.isEmpty)
assert(_submissionQueue.isEmpty)
_ = _pool._totalThreads.fetchAndAdd(-1)
print("_ForkJoinWorkerThread end")
}
internal func _forkTask(_ task: ForkJoinTaskBase) {
// Try to inflate the pool.
if !_pool._tryCreateThread({ task }) {
_workDeque.prepend(task)
}
}
internal func _waitForTask(_ task: ForkJoinTaskBase) {
while true {
if task._isComplete() {
return
}
// If the task is in work queue of the current thread, run the task.
if _workDeque.tryReplace(
task,
makeReplacement: { ForkJoinTask<()>() {} },
isEquivalent: { $0 === $1 }) {
// We found the task. Run it in-place.
task._run()
return
}
// FIXME: also check the submission queue, maybe the task is there?
// FIXME: try to find the task in other threads' queues.
// FIXME: try to find tasks that were forked from this task in other
// threads' queues. Help thieves by stealing those tasks back.
// At this point, we can't do any work to help with running this task.
// We can't start new work either (if we do, we might end up creating
// more in-flight work than we can chew, and crash with out-of-memory
// errors).
_pool._compensateForBlockedWorkerThread() {
task._blockingWait()
// FIXME: do a timed wait, and retry stealing.
}
}
}
}
internal protocol _Future {
associatedtype Result
/// Establishes a happens-before relation between completing the future and
/// the call to wait().
func wait()
func tryGetResult() -> Result?
func tryTakeResult() -> Result?
func waitAndGetResult() -> Result
func waitAndTakeResult() -> Result
}
public class ForkJoinTaskBase {
final internal var _pool: ForkJoinPool?
// FIXME(performance): there is no need to create heavy-weight
// synchronization primitives every time. We could start with a lightweight
// atomic int for the flag and inflate to a full event when needed. Unless
// we really need to block in wait(), we would avoid creating an event.
final internal let _completedEvent: _ForkJoinOneShotEvent =
_ForkJoinOneShotEvent()
final internal func _isComplete() -> Bool {
return _completedEvent.isSet()
}
final internal func _blockingWait() {
_completedEvent.wait()
}
internal func _run() {
fatalError("implement")
}
final public func fork() {
precondition(_pool == nil)
if let thread = ForkJoinPool._getCurrentThread() {
thread._forkTask(self)
} else {
// FIXME: decide if we want to allow this.
precondition(false)
ForkJoinPool.commonPool.forkTask(self)
}
}
final public func wait() {
if let thread = ForkJoinPool._getCurrentThread() {
thread._waitForTask(self)
} else {
_blockingWait()
}
}
}
final public class ForkJoinTask<Result> : ForkJoinTaskBase, _Future {
internal let _task: () -> Result
internal var _result: Result?
public init(_task: @escaping () -> Result) {
self._task = _task
}
override internal func _run() {
_complete(_task())
}
/// It is not allowed to call _complete() in a racy way. Only one thread
/// should ever call _complete().
internal func _complete(_ result: Result) {
precondition(!_completedEvent.isSet())
_result = result
_completedEvent.set()
}
public func tryGetResult() -> Result? {
if _completedEvent.isSet() {
return _result
}
return nil
}
public func tryTakeResult() -> Result? {
if _completedEvent.isSet() {
let result = _result
_result = nil
return result
}
return nil
}
public func waitAndGetResult() -> Result {
wait()
return tryGetResult()!
}
public func waitAndTakeResult() -> Result {
wait()
return tryTakeResult()!
}
}
final public class ForkJoinPool {
internal static var _threadRegistry: [_stdlib_pthread_t : _ForkJoinWorkerThread] = [:]
internal static var _threadRegistryMutex: _ForkJoinMutex = _ForkJoinMutex()
internal static func _getCurrentThread() -> _ForkJoinWorkerThread? {
return _threadRegistryMutex.withLock {
return _threadRegistry[_stdlib_pthread_self()]
}
}
internal let _maxThreads: Int
/// Total number of threads: number of running threads plus the number of
/// threads that are preparing to start).
internal let _totalThreads: _stdlib_AtomicInt = _stdlib_AtomicInt(0)
internal var _runningThreads: [_ForkJoinWorkerThread] = []
internal var _runningThreadsMutex: _ForkJoinMutex = _ForkJoinMutex()
internal var _submissionQueues: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = []
internal var _submissionQueuesMutex: _ForkJoinMutex = _ForkJoinMutex()
internal var _workDeques: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = []
internal var _workDequesMutex: _ForkJoinMutex = _ForkJoinMutex()
internal init(_commonPool: ()) {
self._maxThreads = _stdlib_getHardwareConcurrency()
}
deinit {
_runningThreadsMutex.`deinit`()
_submissionQueuesMutex.`deinit`()
_workDequesMutex.`deinit`()
}
internal func _addRunningThread(_ thread: _ForkJoinWorkerThread) {
ForkJoinPool._threadRegistryMutex.withLock {
_runningThreadsMutex.withLock {
_submissionQueuesMutex.withLock {
_workDequesMutex.withLock {
ForkJoinPool._threadRegistry[thread._tid!] = thread
_runningThreads.append(thread)
_submissionQueues.append(thread._submissionQueue)
_workDeques.append(thread._workDeque)
}
}
}
}
}
internal func _removeRunningThread(_ thread: _ForkJoinWorkerThread) {
ForkJoinPool._threadRegistryMutex.withLock {
_runningThreadsMutex.withLock {
_submissionQueuesMutex.withLock {
_workDequesMutex.withLock {
let i = _runningThreads.index { $0 === thread }!
ForkJoinPool._threadRegistry[thread._tid!] = nil
_runningThreads.remove(at: i)
_submissionQueues.remove(at: i)
_workDeques.remove(at: i)
}
}
}
}
}
internal func _compensateForBlockedWorkerThread(_ blockingBody: @escaping () -> ()) {
// FIXME: limit the number of compensating threads.
let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let thread = _ForkJoinWorkerThread(
_pool: self, submissionQueue: submissionQueue, workDeque: workDeque)
thread.startAsync()
blockingBody()
_ = _totalThreads.fetchAndAdd(1)
}
internal func _tryCreateThread(
_ makeTask: () -> ForkJoinTaskBase?
) -> Bool {
var success = false
var oldNumThreads = _totalThreads.load()
repeat {
if oldNumThreads >= _maxThreads {
return false
}
success = _totalThreads.compareExchange(
expected: &oldNumThreads, desired: oldNumThreads + 1)
} while !success
if let task = makeTask() {
let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>()
workDeque.prepend(task)
let thread = _ForkJoinWorkerThread(
_pool: self, submissionQueue: submissionQueue, workDeque: workDeque)
thread.startAsync()
} else {
_ = _totalThreads.fetchAndAdd(-1)
}
return true
}
internal func _stealTask() -> ForkJoinTaskBase? {
return _workDequesMutex.withLock {
let randomOffset = pickRandom(_workDeques.indices)
let count = _workDeques.count
for i in _workDeques.indices {
let index = (i + randomOffset) % count
if let task = _workDeques[index].tryTakeLast() {
return task
}
}
return nil
}
}
/// Check if the pool has grown too large because of compensating
/// threads.
internal func _tryStopThread() -> Bool {
var success = false
var oldNumThreads = _totalThreads.load()
repeat {
// FIXME: magic number 2.
if oldNumThreads <= _maxThreads + 2 {
return false
}
success = _totalThreads.compareExchange(
expected: &oldNumThreads, desired: oldNumThreads - 1)
} while !success
return true
}
internal func _submitTasksToRandomWorkers<
C : Collection
where
C.Iterator.Element == ForkJoinTaskBase
>(_ tasks: C) {
if tasks.isEmpty {
return
}
_submissionQueuesMutex.withLock {
precondition(!_submissionQueues.isEmpty)
for task in tasks {
pickRandom(_submissionQueues).append(task)
}
}
}
public func forkTask(_ task: ForkJoinTaskBase) {
while true {
// Try to inflate the pool first.
if _tryCreateThread({ task }) {
return
}
// Looks like we can't create more threads. Submit the task to
// a random thread.
let done = _submissionQueuesMutex.withLock {
() -> Bool in
if !_submissionQueues.isEmpty {
pickRandom(_submissionQueues).append(task)
return true
}
return false
}
if done {
return
}
}
}
// FIXME: return a Future instead?
public func forkTask<Result>(task: @escaping () -> Result) -> ForkJoinTask<Result> {
let forkJoinTask = ForkJoinTask(_task: task)
forkTask(forkJoinTask)
return forkJoinTask
}
public static var commonPool = ForkJoinPool(_commonPool: ())
public static func invokeAll(_ tasks: ForkJoinTaskBase...) {
ForkJoinPool.invokeAll(tasks)
}
public static func invokeAll(_ tasks: [ForkJoinTaskBase]) {
if tasks.isEmpty {
return
}
if ForkJoinPool._getCurrentThread() != nil {
// Run the first task in this thread, fork the rest.
let first = tasks.first
for t in tasks.dropFirst() {
// FIXME: optimize forking in bulk.
t.fork()
}
first!._run()
} else {
// FIXME: decide if we want to allow this.
precondition(false)
}
}
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: implementation
//===----------------------------------------------------------------------===//
internal protocol _CollectionTransformerStepProtocol /*: class*/ {
associatedtype PipelineInputElement
associatedtype OutputElement
func transform<
InputCollection : Collection,
Collector : _ElementCollector
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
}
internal class _CollectionTransformerStep<PipelineInputElement_, OutputElement_>
: _CollectionTransformerStepProtocol {
typealias PipelineInputElement = PipelineInputElement_
typealias OutputElement = OutputElement_
func map<U>(_ transform: @escaping (OutputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
fatalError("abstract method")
}
func filter(_ isIncluded: @escaping (OutputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, OutputElement> {
fatalError("abstract method")
}
func reduce<U>(_ initial: U, _ combine: @escaping (U, OutputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
fatalError("abstract method")
}
func collectTo<
C : BuildableCollectionProtocol
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement
>(_: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C> {
fatalError("abstract method")
}
func transform<
InputCollection : Collection,
Collector : _ElementCollector
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
) {
fatalError("abstract method")
}
}
final internal class _CollectionTransformerStepCollectionSource<
PipelineInputElement
> : _CollectionTransformerStep<PipelineInputElement, PipelineInputElement> {
typealias InputElement = PipelineInputElement
override func map<U>(_ transform: @escaping (InputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
return _CollectionTransformerStepOneToMaybeOne(self) {
transform($0)
}
}
override func filter(_ isIncluded: @escaping (InputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, InputElement> {
return _CollectionTransformerStepOneToMaybeOne(self) {
isIncluded($0) ? $0 : nil
}
}
override func reduce<U>(_ initial: U, _ combine: @escaping (U, InputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
return _CollectionTransformerFinalizerReduce(self, initial, combine)
}
override func collectTo<
C : BuildableCollectionProtocol
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement
>(_ c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C> {
return _CollectionTransformerFinalizerCollectTo(self, c)
}
override func transform<
InputCollection : Collection,
Collector : _ElementCollector
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
) {
var i = range.lowerBound
while i != range.upperBound {
let e = c[i]
collector.append(e)
c.formIndex(after: &i)
}
}
}
final internal class _CollectionTransformerStepOneToMaybeOne<
PipelineInputElement,
OutputElement,
InputStep : _CollectionTransformerStepProtocol
where
InputStep.PipelineInputElement == PipelineInputElement
> : _CollectionTransformerStep<PipelineInputElement, OutputElement> {
typealias _Self = _CollectionTransformerStepOneToMaybeOne
typealias InputElement = InputStep.OutputElement
let _input: InputStep
let _transform: (InputElement) -> OutputElement?
init(_ input: InputStep, _ transform: @escaping (InputElement) -> OutputElement?) {
self._input = input
self._transform = transform
super.init()
}
override func map<U>(_ transform: @escaping (OutputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
// Let the closure below capture only one variable, not the whole `self`.
let localTransform = _transform
return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, U, InputStep>(_input) {
(input: InputElement) -> U? in
if let e = localTransform(input) {
return transform(e)
}
return nil
}
}
override func filter(_ isIncluded: @escaping (OutputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, OutputElement> {
// Let the closure below capture only one variable, not the whole `self`.
let localTransform = _transform
return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, OutputElement, InputStep>(_input) {
(input: InputElement) -> OutputElement? in
if let e = localTransform(input) {
return isIncluded(e) ? e : nil
}
return nil
}
}
override func reduce<U>(_ initial: U, _ combine: @escaping (U, OutputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
return _CollectionTransformerFinalizerReduce(self, initial, combine)
}
override func collectTo<
C : BuildableCollectionProtocol
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement
>(_ c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C> {
return _CollectionTransformerFinalizerCollectTo(self, c)
}
override func transform<
InputCollection : Collection,
Collector : _ElementCollector
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
) {
var collectorWrapper =
_ElementCollectorOneToMaybeOne(collector, _transform)
_input.transform(c, range, &collectorWrapper)
collector = collectorWrapper._baseCollector
}
}
struct _ElementCollectorOneToMaybeOne<
BaseCollector : _ElementCollector,
Element_
> : _ElementCollector {
typealias Element = Element_
var _baseCollector: BaseCollector
var _transform: (Element) -> BaseCollector.Element?
init(
_ baseCollector: BaseCollector,
_ transform: @escaping (Element) -> BaseCollector.Element?
) {
self._baseCollector = baseCollector
self._transform = transform
}
mutating func sizeHint(_ approximateSize: Int) {}
mutating func append(_ element: Element) {
if let e = _transform(element) {
_baseCollector.append(e)
}
}
mutating func append<
C : Collection
where
C.Iterator.Element == Element
>(contentsOf elements: C) {
for e in elements {
append(e)
}
}
}
protocol _ElementCollector {
associatedtype Element
mutating func sizeHint(_ approximateSize: Int)
mutating func append(_ element: Element)
mutating func append<
C : Collection
where
C.Iterator.Element == Element
>(contentsOf elements: C)
}
class _CollectionTransformerFinalizer<PipelineInputElement, Result> {
func transform<
InputCollection : Collection
where
InputCollection.Iterator.Element == PipelineInputElement
>(_ c: InputCollection) -> Result {
fatalError("implement")
}
}
final class _CollectionTransformerFinalizerReduce<
PipelineInputElement,
U,
InputElementTy,
InputStep : _CollectionTransformerStepProtocol
where
InputStep.OutputElement == InputElementTy,
InputStep.PipelineInputElement == PipelineInputElement
> : _CollectionTransformerFinalizer<PipelineInputElement, U> {
var _input: InputStep
var _initial: U
var _combine: (U, InputElementTy) -> U
init(_ input: InputStep, _ initial: U, _ combine: @escaping (U, InputElementTy) -> U) {
self._input = input
self._initial = initial
self._combine = combine
}
override func transform<
InputCollection : Collection
where
InputCollection.Iterator.Element == PipelineInputElement
>(_ c: InputCollection) -> U {
var collector = _ElementCollectorReduce(_initial, _combine)
_input.transform(c, c.startIndex..<c.endIndex, &collector)
return collector.takeResult()
}
}
struct _ElementCollectorReduce<Element_, Result> : _ElementCollector {
typealias Element = Element_
var _current: Result
var _combine: (Result, Element) -> Result
init(_ initial: Result, _ combine: @escaping (Result, Element) -> Result) {
self._current = initial
self._combine = combine
}
mutating func sizeHint(_ approximateSize: Int) {}
mutating func append(_ element: Element) {
_current = _combine(_current, element)
}
mutating func append<
C : Collection
where
C.Iterator.Element == Element
>(contentsOf elements: C) {
for e in elements {
append(e)
}
}
mutating func takeResult() -> Result {
return _current
}
}
final class _CollectionTransformerFinalizerCollectTo<
PipelineInputElement,
U : BuildableCollectionProtocol,
InputElementTy,
InputStep : _CollectionTransformerStepProtocol
where
InputStep.OutputElement == InputElementTy,
InputStep.PipelineInputElement == PipelineInputElement,
U.Builder.Destination == U,
U.Builder.Element == U.Iterator.Element,
U.Iterator.Element == InputStep.OutputElement
> : _CollectionTransformerFinalizer<PipelineInputElement, U> {
var _input: InputStep
init(_ input: InputStep, _: U.Type) {
self._input = input
}
override func transform<
InputCollection : Collection
where
InputCollection.Iterator.Element == PipelineInputElement
>(_ c: InputCollection) -> U {
var collector = _ElementCollectorCollectTo<U>()
_input.transform(c, c.startIndex..<c.endIndex, &collector)
return collector.takeResult()
}
}
struct _ElementCollectorCollectTo<
BuildableCollection : BuildableCollectionProtocol
where
BuildableCollection.Builder.Destination == BuildableCollection,
BuildableCollection.Builder.Element == BuildableCollection.Iterator.Element
> : _ElementCollector {
typealias Element = BuildableCollection.Iterator.Element
var _builder: BuildableCollection.Builder
init() {
self._builder = BuildableCollection.Builder()
}
mutating func sizeHint(_ approximateSize: Int) {
_builder.sizeHint(approximateSize)
}
mutating func append(_ element: Element) {
_builder.append(element)
}
mutating func append<
C : Collection
where
C.Iterator.Element == Element
>(contentsOf elements: C) {
_builder.append(contentsOf: elements)
}
mutating func takeResult() -> BuildableCollection {
return _builder.takeResult()
}
}
internal func _optimizeCollectionTransformer<PipelineInputElement, Result>(
_ transformer: _CollectionTransformerFinalizer<PipelineInputElement, Result>
) -> _CollectionTransformerFinalizer<PipelineInputElement, Result> {
return transformer
}
internal func _runCollectionTransformer<
InputCollection : Collection, Result
>(
_ c: InputCollection,
_ transformer: _CollectionTransformerFinalizer<InputCollection.Iterator.Element, Result>
) -> Result {
dump(transformer)
let optimized = _optimizeCollectionTransformer(transformer)
dump(optimized)
return transformer.transform(c)
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: public interface
//===----------------------------------------------------------------------===//
public struct CollectionTransformerPipeline<
InputCollection : Collection, T
> {
internal var _input: InputCollection
internal var _step: _CollectionTransformerStep<InputCollection.Iterator.Element, T>
public func map<U>(_ transform: @escaping (T) -> U)
-> CollectionTransformerPipeline<InputCollection, U> {
return CollectionTransformerPipeline<InputCollection, U>(
_input: _input,
_step: _step.map(transform)
)
}
public func filter(_ isIncluded: @escaping (T) -> Bool)
-> CollectionTransformerPipeline<InputCollection, T> {
return CollectionTransformerPipeline<InputCollection, T>(
_input: _input,
_step: _step.filter(isIncluded)
)
}
public func reduce<U>(
_ initial: U, _ combine: @escaping (U, T) -> U
) -> U {
return _runCollectionTransformer(_input, _step.reduce(initial, combine))
}
public func collectTo<
C : BuildableCollectionProtocol
where
C.Builder.Destination == C,
C.Iterator.Element == T,
C.Builder.Element == T
>(_ c: C.Type) -> C {
return _runCollectionTransformer(_input, _step.collectTo(c))
}
public func toArray() -> [T] {
return collectTo(Array<T>.self)
}
}
public func transform<C : Collection>(_ c: C)
-> CollectionTransformerPipeline<C, C.Iterator.Element> {
return CollectionTransformerPipeline<C, C.Iterator.Element>(
_input: c,
_step: _CollectionTransformerStepCollectionSource<C.Iterator.Element>())
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: tests
//===----------------------------------------------------------------------===//
import StdlibUnittest
var t = TestSuite("t")
t.test("fusion/map+reduce") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.reduce(0, { $0 + $1 })
expectEqual(12, result)
}
t.test("fusion/map+filter+reduce") {
let xs = [ 1, 2, 3 ]
let result = transform(xs)
.map { $0 * 2 }
.filter { $0 != 0 }
.reduce(0, { $0 + $1 })
expectEqual(12, result)
}
t.test("fusion/map+collectTo") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.collectTo(Array<Int>.self)
expectEqual([ 2, 4, 6 ], result)
}
t.test("fusion/map+toArray") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.toArray()
expectEqual([ 2, 4, 6 ], result)
}
t.test("ForkJoinPool.forkTask") {
var tasks: [ForkJoinTask<()>] = []
for i in 0..<100 {
tasks.append(ForkJoinPool.commonPool.forkTask {
() -> () in
var result = 1
for i in 0..<10000 {
result = result &* i
_blackHole(result)
}
return ()
})
}
for t in tasks {
t.wait()
}
}
func fib(_ n: Int) -> Int {
if n == 1 || n == 2 {
return 1
}
if n == 38 {
print("\(pthread_self()) fib(\(n))")
}
if n < 39 {
let r = fib(n - 1) + fib(n - 2)
_blackHole(r)
return r
}
print("fib(\(n))")
let t1 = ForkJoinTask() { fib(n - 1) }
let t2 = ForkJoinTask() { fib(n - 2) }
ForkJoinPool.invokeAll(t1, t2)
return t2.waitAndGetResult() + t1.waitAndGetResult()
}
t.test("ForkJoinPool.forkTask/Fibonacci") {
let t = ForkJoinPool.commonPool.forkTask { fib(40) }
expectEqual(102334155, t.waitAndGetResult())
}
func _parallelMap(_ input: [Int], transform: @escaping (Int) -> Int, range: Range<Int>)
-> Array<Int>.Builder {
var builder = Array<Int>.Builder()
if range.count < 1_000 {
builder.append(contentsOf: input[range].map(transform))
} else {
let tasks = input.split(range).map {
(subRange) in
ForkJoinTask<Array<Int>.Builder> {
_parallelMap(input, transform: transform, range: subRange)
}
}
ForkJoinPool.invokeAll(tasks)
for t in tasks {
var otherBuilder = t.waitAndGetResult()
builder.moveContentsOf(&otherBuilder)
}
}
return builder
}
func parallelMap(_ input: [Int], transform: @escaping (Int) -> Int) -> [Int] {
let t = ForkJoinPool.commonPool.forkTask {
_parallelMap(
input,
transform: transform,
range: input.startIndex..<input.endIndex)
}
var builder = t.waitAndGetResult()
return builder.takeResult()
}
t.test("ForkJoinPool.forkTask/MapArray") {
expectEqual(
Array(2..<1_001),
parallelMap(Array(1..<1_000)) { $0 + 1 }
)
}
/*
* FIXME: reduce compiler crasher
t.test("ForkJoinPool.forkTask") {
func fib(_ n: Int) -> Int {
if n == 0 || n == 1 {
return 1
}
let t1 = ForkJoinPool.commonPool.forkTask { fib(n - 1) }
let t2 = ForkJoinPool.commonPool.forkTask { fib(n - 2) }
return t2.waitAndGetResult() + t1.waitAndGetResult()
}
expectEqual(0, fib(10))
}
*/
/*
Useful links:
http://habrahabr.ru/post/255659/
*/
runAllTests()
| apache-2.0 | bf331d15bdf938081177b71114108b9f | 26.027379 | 108 | 0.651379 | 4.534045 | false | false | false | false |
dshahidehpour/IGListKit | Examples/Examples-iOS/IGListKitExamples/ViewControllers/SingleSectionStoryboardViewController.swift | 2 | 2977 | /**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
import IGListKit
final class SingleSectionStoryboardViewController: UIViewController, IGListAdapterDataSource, IGListSingleSectionControllerDelegate {
lazy var adapter: IGListAdapter = {
return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 0)
}()
@IBOutlet weak var collectionView: IGListCollectionView!
let data = Array(0..<20)
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
adapter.collectionView = collectionView
adapter.dataSource = self
}
//MARK: - IGListAdapterDataSource
func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] {
return data as [IGListDiffable]
}
func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController {
let configureBlock = { (item: Any, cell: UICollectionViewCell) in
guard let cell = cell as? StoryboardCell, let number = item as? Int else { return }
cell.textLabel.text = "Cell: \(number + 1)"
}
let sizeBlock = { (item: Any, context: IGListCollectionContext?) -> CGSize in
guard let context = context else { return .zero }
return CGSize(width: context.containerSize.width, height: 44)
}
let sectionController = IGListSingleSectionController(storyboardCellIdentifier: "cell",
configureBlock: configureBlock,
sizeBlock: sizeBlock)
sectionController.selectionDelegate = self
return sectionController
}
func emptyView(for listAdapter: IGListAdapter) -> UIView? { return nil }
// MARK: - IGListSingleSectionControllerDelegate
func didSelect(_ sectionController: IGListSingleSectionController, with object: Any) {
let section = adapter.section(for: sectionController) + 1
let alert = UIAlertController(title: "Section \(section) was selected \u{1F389}", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
| bsd-3-clause | 81928a91ed4fa80809c3dca53e9d2d31 | 42.144928 | 133 | 0.677192 | 5.472426 | false | false | false | false |
pixyzehn/EsaKit | Sources/EsaKit/Models/MemberUser.swift | 1 | 2059 | //
// MemberUser.swift
// EsaKit
//
// Created by pixyzehn on 2016/11/29.
// Copyright © 2016 pixyzehn. All rights reserved.
//
import Foundation
public struct MemberUser: AutoEquatable, AutoHashable {
public let name: String
public let screenName: String
public let icon: URL
public let email: String
public let postsCount: UInt
enum Key: String {
case name
case screenName = "screen_name"
case icon
case email
case postsCount = "posts_count"
}
}
extension MemberUser: Decodable {
// swiftlint:disable line_length
public static func decode(json: Any) throws -> MemberUser {
guard let dictionary = json as? [String: Any] else {
throw DecodeError.invalidFormat(json: json)
}
guard let name = dictionary[Key.name.rawValue] as? String else {
throw DecodeError.missingValue(key: Key.name.rawValue, actualValue: dictionary[Key.name.rawValue])
}
guard let screenName = dictionary[Key.screenName.rawValue] as? String else {
throw DecodeError.missingValue(key: Key.screenName.rawValue, actualValue: dictionary[Key.screenName.rawValue])
}
guard let iconString = dictionary[Key.icon.rawValue] as? String,
let icon = URL(string: iconString) else {
throw DecodeError.missingValue(key: Key.icon.rawValue, actualValue: dictionary[Key.icon.rawValue])
}
guard let email = dictionary[Key.email.rawValue] as? String else {
throw DecodeError.missingValue(key: Key.email.rawValue, actualValue: dictionary[Key.email.rawValue])
}
guard let postsCount = dictionary[Key.postsCount.rawValue] as? UInt else {
throw DecodeError.missingValue(key: Key.postsCount.rawValue, actualValue: dictionary[Key.postsCount.rawValue])
}
return MemberUser(
name: name,
screenName: screenName,
icon: icon,
email: email,
postsCount: postsCount
)
}
}
| mit | c67169127591e908fd67ab94c37179e2 | 31.666667 | 122 | 0.646259 | 4.59375 | false | false | false | false |
PatrickChow/Swift-Awsome | News/Modules/Auth/View/LabeledTextField.swift | 1 | 2002 | //
// Created by Patrick Chow on 2017/6/16.
// Copyright (c) 2017 JIEMIAN. All rights reserved.
import UIKit
class LabeledTextField: UITextField {
// MARK: Properties
private var bottomLine: UIView!
convenience init(labeledText: String) {
self.init(frame: .zero)
contentVerticalAlignment = .bottom
borderStyle = .none
font = UIFont.systemFont(ofSize: 17)
textColor = .darkGray
clearButtonMode = .whileEditing
clearsOnBeginEditing = false
contentVerticalAlignment = .bottom
let label = TextLabel(frame: CGRect(x: 0, y: 0, width: 60, height: 42))
label.contentVerticalAlignment = .bottom
label.text = labeledText
label.textColor = .darkGray
label.font = UIFont.systemFont(ofSize: 12)
leftViewMode = .always
leftView = label
bottomLine = UIView()
bottomLine.nv.backgroundColor(UIColor(hexNumber: 0xdadada), night: UIColor(hexNumber: 0xdadada))
addSubview(bottomLine)
}
override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
var rect = super.clearButtonRect(forBounds: bounds)
rect.origin.y = bounds.height - rect.height
return rect
}
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var rect = super.leftViewRect(forBounds: bounds)
rect.origin.y = bounds.height - rect.height - 2
return rect
}
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
var rect = super.rightViewRect(forBounds: bounds)
rect.origin.y = bounds.height - rect.height
return rect
}
override func updateConstraints() {
super.updateConstraints()
bottomLine.snp.makeConstraints {
$0.left.right.equalToSuperview()
$0.height.equalTo(1)
$0.bottom.equalToSuperview()
}
}
override class var requiresConstraintBasedLayout: Bool {
return true
}
}
| mit | 6d515eb07a3729874b541f5b7350441f | 28.880597 | 104 | 0.641858 | 4.645012 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureInput/Carthage/Checkouts/RxDataSources/Tests/AlgorithmTests.swift | 3 | 15515 | //
// AlgorithmTests.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 11/26/16.
// Copyright © 2016 kzaher. All rights reserved.
//
import Foundation
import XCTest
import RxDataSources
class AlgorithmTests: XCTestCase {
}
// single section simple
extension AlgorithmTests {
func testItemInsert() {
let initial: [s] = [
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
])
]
let final: [s] = [
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
i(3, ""),
])
]
let differences = try! differencesForSectionedView(initialSections: initial, finalSections: final)
XCTAssertTrue(differences.count == 1)
XCTAssertTrue(differences.first!.onlyContains(insertedItems: 1))
XCTAssertEqual(initial.apply(differences), final)
}
func testItemDelete() {
let initial: [s] = [
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
])
]
let final: [s] = [
s(1, [
i(0, ""),
i(2, ""),
])
]
let differences = try! differencesForSectionedView(initialSections: initial, finalSections: final)
XCTAssertTrue(differences.count == 1)
XCTAssertTrue(differences.first!.onlyContains(deletedItems: 1))
XCTAssertEqual(initial.apply(differences), final)
}
func testItemMove1() {
let initial: [s] = [
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
])
]
let final: [s] = [
s(1, [
i(1, ""),
i(2, ""),
i(0, ""),
])
]
let differences = try! differencesForSectionedView(initialSections: initial, finalSections: final)
XCTAssertTrue(differences.count == 1)
XCTAssertTrue(differences.first!.onlyContains(movedItems: 2))
XCTAssertEqual(initial.apply(differences), final)
}
func testItemMove2() {
let initial: [s] = [
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
])
]
let final: [s] = [
s(1, [
i(2, ""),
i(0, ""),
i(1, ""),
])
]
let differences = try! differencesForSectionedView(initialSections: initial, finalSections: final)
XCTAssertTrue(differences.count == 1)
XCTAssertTrue(differences.first!.onlyContains(movedItems: 1))
XCTAssertEqual(initial.apply(differences), final)
}
func testItemUpdated() {
let initial: [s] = [
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
])
]
let final: [s] = [
s(1, [
i(0, ""),
i(1, "u"),
i(2, ""),
])
]
let differences = try! differencesForSectionedView(initialSections: initial, finalSections: final)
XCTAssertTrue(differences.count == 1)
XCTAssertTrue(differences.first!.onlyContains(updatedItems: 1))
XCTAssertEqual(initial.apply(differences), final)
}
func testItemUpdatedAndMoved() {
let initial: [s] = [
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
])
]
let final: [s] = [
s(1, [
i(1, "u"),
i(0, ""),
i(2, ""),
])
]
let differences = try! differencesForSectionedView(initialSections: initial, finalSections: final)
XCTAssertTrue(differences.count == 2)
// updates ok
XCTAssertTrue(differences[0].onlyContains(updatedItems: 1))
XCTAssertTrue(differences[0].updatedItems[0] == ItemPath(sectionIndex: 0, itemIndex: 1))
// moves ok
XCTAssertTrue(differences[1].onlyContains(movedItems: 1))
XCTAssertEqual(initial.apply(differences), final)
}
}
// multiple sections simple
extension AlgorithmTests {
func testInsertSection() {
let initial: [s] = [
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
])
]
let final: [s] = [
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
]),
s(2, [
i(3, ""),
i(4, ""),
i(5, ""),
]),
]
let differences = try! differencesForSectionedView(initialSections: initial, finalSections: final)
XCTAssertTrue(differences.count == 1)
XCTAssertTrue(differences.first!.onlyContains(insertedSections: 1))
XCTAssertEqual(initial.apply(differences), final)
}
func testDeleteSection() {
let initial: [s] = [
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
])
]
let final: [s] = [
]
let differences = try! differencesForSectionedView(initialSections: initial, finalSections: final)
XCTAssertTrue(differences.count == 1)
XCTAssertTrue(differences.first!.onlyContains(deletedSections: 1))
XCTAssertEqual(initial.apply(differences), final)
}
func testMovedSection1() {
let initial: [s] = [
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
]),
s(2, [
i(3, ""),
i(4, ""),
i(5, ""),
]),
s(3, [
i(6, ""),
i(7, ""),
i(8, ""),
]),
]
let final: [s] = [
s(2, [
i(3, ""),
i(4, ""),
i(5, ""),
]),
s(3, [
i(6, ""),
i(7, ""),
i(8, ""),
]),
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
]),
]
let differences = try! differencesForSectionedView(initialSections: initial, finalSections: final)
XCTAssertTrue(differences.count == 1)
XCTAssertTrue(differences.first!.onlyContains(movedSections: 2))
XCTAssertEqual(initial.apply(differences), final)
}
func testMovedSection2() {
let initial: [s] = [
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
]),
s(2, [
i(3, ""),
i(4, ""),
i(5, ""),
]),
s(3, [
i(6, ""),
i(7, ""),
i(8, ""),
]),
]
let final: [s] = [
s(3, [
i(6, ""),
i(7, ""),
i(8, ""),
]),
s(1, [
i(0, ""),
i(1, ""),
i(2, ""),
]),
s(2, [
i(3, ""),
i(4, ""),
i(5, ""),
]),
]
let differences = try! differencesForSectionedView(initialSections: initial, finalSections: final)
XCTAssertTrue(differences.count == 1)
XCTAssertTrue(differences.first!.onlyContains(movedSections: 1))
XCTAssertEqual(initial.apply(differences), final)
}
}
// errors
extension AlgorithmTests {
func testThrowsErrorOnDuplicateItem() {
let initial: [s] = [
s(1, [
i(1111, ""),
]),
s(2, [
i(1111, ""),
]),
]
do {
_ = try differencesForSectionedView(initialSections: initial, finalSections: initial)
XCTFail()
}
catch let exception {
guard case let .duplicateItem(item) = exception as! DifferentiatorError else {
XCTFail()
return
}
XCTAssertEqual(item as! i, i(1111, ""))
}
}
func testThrowsErrorOnDuplicateSection() {
let initial: [s] = [
s(1, [
i(1111, ""),
]),
s(1, [
i(1112, ""),
]),
]
do {
_ = try differencesForSectionedView(initialSections: initial, finalSections: initial)
XCTFail()
}
catch let exception {
guard case let .duplicateSection(section) = exception as! DifferentiatorError else {
XCTFail()
return
}
XCTAssertEqual(section as! s, s(1, [
i(1112, ""),
]))
}
}
func testThrowsErrorOnInvalidInitializerImplementation1() {
let initial: [sInvalidInitializerImplementation1] = [
sInvalidInitializerImplementation1(1, [
i(1111, ""),
]),
]
do {
_ = try differencesForSectionedView(initialSections: initial, finalSections: initial)
XCTFail()
}
catch let exception {
guard case let .invalidInitializerImplementation(section, expectedItems, identifier) = exception as! DifferentiatorError else {
XCTFail()
return
}
XCTAssertEqual(section as! sInvalidInitializerImplementation1, sInvalidInitializerImplementation1(1, [
i(1111, ""),
i(1111, ""),
]))
XCTAssertEqual(expectedItems as! [i], [i(1111, "")])
XCTAssertEqual(identifier as! Int, 1)
}
}
func testThrowsErrorOnInvalidInitializerImplementation2() {
let initial: [sInvalidInitializerImplementation2] = [
sInvalidInitializerImplementation2(1, [
i(1111, ""),
]),
]
do {
_ = try differencesForSectionedView(initialSections: initial, finalSections: initial)
XCTFail()
}
catch let exception {
guard case let .invalidInitializerImplementation(section, expectedItems, identifier) = exception as! DifferentiatorError else {
XCTFail()
return
}
XCTAssertEqual(section as! sInvalidInitializerImplementation2, sInvalidInitializerImplementation2(-1, [
i(1111, ""),
]))
XCTAssertEqual(expectedItems as! [i], [i(1111, "")])
XCTAssertEqual(identifier as! Int, 1)
}
}
}
// edge cases
extension AlgorithmTests {
func testCase1() {
let initial: [s] = [
s(1, [
i(1111, ""),
]),
s(2, [
i(2222, ""),
]),
]
let final: [s] = [
s(2, [
i(0, "1"),
]),
s(1, [
]),
]
let differences = try! differencesForSectionedView(initialSections: initial, finalSections: final)
XCTAssertEqual(initial.apply(differences), final)
}
func testCase2() {
let initial: [s] = [
s(4, [
i(10, ""),
i(11, ""),
i(12, ""),
]),
s(9, [
i(25, ""),
i(26, ""),
i(27, ""),
]),
]
let final: [s] = [
s(9, [
i(11, "u"),
i(26, ""),
i(27, "u"),
]),
s(4, [
i(10, "u"),
i(12, ""),
]),
]
let differences = try! differencesForSectionedView(initialSections: initial, finalSections: final)
XCTAssertEqual(initial.apply(differences), final)
}
func testCase3() {
let initial: [s] = [
s(4, [
i(5, ""),
]),
s(6, [
i(20, ""),
i(14, ""),
]),
s(9, [
]),
s(2, [
i(2, ""),
i(26, ""),
]),
s(8, [
i(23, ""),
]),
s(10, [
i(8, ""),
i(18, ""),
i(13, ""),
]),
s(1, [
i(28, ""),
i(25, ""),
i(6, ""),
i(11, ""),
i(10, ""),
i(29, ""),
i(24, ""),
i(7, ""),
i(19, ""),
]),
]
let final: [s] = [
s(4, [
i(5, ""),
]),
s(6, [
i(20, "u"),
i(14, ""),
]),
s(9, [
i(16, "u"),
]),
s(7, [
i(17, ""),
i(15, ""),
i(4, "u"),
]),
s(2, [
i(2, ""),
i(26, "u"),
i(23, "u"),
]),
s(8, [
]),
s(10, [
i(8, "u"),
i(18, "u"),
i(13, "u"),
]),
s(1, [
i(28, "u"),
i(25, "u"),
i(6, "u"),
i(11, "u"),
i(10, "u"),
i(29, "u"),
i(24, "u"),
i(7, "u"),
i(19, "u"),
]),
]
let differences = try! differencesForSectionedView(initialSections: initial, finalSections: final)
XCTAssertEqual(initial.apply(differences), final)
}
}
// stress test
extension AlgorithmTests {
func testStress() {
func initialValue() -> [NumberSection] {
let nSections = 100
let nItems = 100
/*
let nSections = 10
let nItems = 2
*/
return (0 ..< nSections).map { (i: Int) in
let items = Array(i * nItems ..< (i + 1) * nItems).map { IntItem(number: $0, date: Date.distantPast) }
return NumberSection(header: "Section \(i + 1)", numbers: items, updated: Date.distantPast)
}
}
let initialRandomizedSections = Randomizer(rng: PseudoRandomGenerator(4, 3), sections: initialValue())
var sections = initialRandomizedSections
for i in 0 ..< 1000 {
if i % 100 == 0 {
print(i)
}
let newSections = sections.randomize()
let differences = try! differencesForSectionedView(initialSections: sections.sections, finalSections: newSections.sections)
XCTAssertEqual(sections.sections.apply(differences), newSections.sections)
sections = newSections
}
}
}
| mit | 0c75bfb807494c2f2f7b112ef970ca30 | 24.642975 | 139 | 0.393773 | 4.878616 | false | false | false | false |
ringly/IOS-Pods-DFU-Library | iOSDFULibrary/Classes/Implementation/SecureDFU/Services/SecureDFUService.swift | 1 | 17928 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CoreBluetooth
@objc internal class SecureDFUService : NSObject, CBPeripheralDelegate, DFUService {
static internal let UUID = CBUUID(string: "FE59")
static func matches(_ service: CBService) -> Bool {
return service.uuid.isEqual(UUID)
}
/// The target DFU Peripheral
internal var targetPeripheral: DFUPeripheralAPI?
/// The logger helper.
private var logger: LoggerHelper
/// The service object from CoreBluetooth used to initialize the SecureDFUService instance.
private let service : CBService
private var dfuPacketCharacteristic : SecureDFUPacket?
private var dfuControlPointCharacteristic : SecureDFUControlPoint?
private var paused = false
private var aborted = false
/// A temporary callback used to report end of an operation.
private var success : Callback?
/// A temporary callback used to report an operation error.
private var report : ErrorCallback?
/// A temporaty callback used to report progress status.
private var progressDelegate : DFUProgressDelegate?
// -- Properties stored when upload started in order to resume it --
private var firmware: DFUFirmware?
private var packetReceiptNotificationNumber: UInt16 = 0
private var range: Range<Int>?
// -- End --
// MARK: - Initialization
required init(_ service: CBService, _ logger: LoggerHelper, controlPointCharacteristicUUID: CBUUID, packetCharacteristicUUID: CBUUID) {
self.service = service
self.logger = logger
super.init()
self.logger.v("Secure DFU Service found")
}
func destroy() {
dfuPacketCharacteristic = nil
dfuControlPointCharacteristic = nil
targetPeripheral = nil
}
// MARK: - Controler API methods
func pause() -> Bool {
if !aborted {
paused = true
}
return paused
}
func resume() -> Bool {
if !aborted && paused && firmware != nil {
paused = false
dfuPacketCharacteristic!.sendNext(packetReceiptNotificationNumber, bytesFrom: range!, of: firmware!,
andReportProgressTo: progressDelegate, andCompletionTo: success!)
return paused
}
paused = false
return paused
}
func abort() -> Bool {
aborted = true
// When upload has been started and paused, we have to send the Reset command here as the device will
// not get a Packet Receipt Notification. If it hasn't been paused, the Reset command will be sent after receiving it, on line 292.
if paused && firmware != nil {
let _report = report!
firmware = nil
range = nil
success = nil
report = nil
progressDelegate = nil
// Upload has been aborted. Reset the target device. It will disconnect automatically
sendReset(onError: _report)
}
paused = false
return aborted
}
// MARK: - Service API methods
/**
Discovers characteristics in the DFU Service.
*/
func discoverCharacteristics(onSuccess success: @escaping Callback, onError report: @escaping ErrorCallback) {
// Save callbacks
self.success = success
self.report = report
// Get the peripheral object
let peripheral = service.peripheral
// Set the peripheral delegate to self
peripheral.delegate = self
// Discover DFU characteristics
logger.v("Discovering characteristics in DFU Service...")
logger.d("peripheral.discoverCharacteristics(nil, for: \(SecureDFUService.UUID.uuidString))")
peripheral.discoverCharacteristics(nil, for: service)
}
/**
Enables notifications for DFU Control Point characteristic. Result it reported using callbacks.
- parameter success: method called when notifications were enabled without a problem
- parameter report: method called when an error occurred
*/
func enableControlPoint(onSuccess success: @escaping Callback, onError report: @escaping ErrorCallback) {
if !aborted {
// Support for experimental Buttonless DFU Service from SDK 12.x
if experimentalButtonlessDfuCharacteristic != nil {
experimentalButtonlessDfuCharacteristic!.enableNotifications(onSuccess: success, onError: report)
return
}
// End
dfuControlPointCharacteristic!.enableNotifications(onSuccess: success, onError: report)
} else {
sendReset(onError: report)
}
}
/**
Reads Command Object Info
*/
func readCommandObjectInfo(onReponse response: @escaping SecureDFUResponseCallback, onError report: @escaping ErrorCallback) {
if !aborted {
dfuControlPointCharacteristic!.send(SecureDFURequest.readCommandObjectInfo, onResponse: response, onError: report)
} else {
sendReset(onError: report)
}
}
/**
Reads object info Data
*/
func readDataObjectInfo(onReponse response: @escaping SecureDFUResponseCallback, onError report: @escaping ErrorCallback) {
if !aborted {
dfuControlPointCharacteristic!.send(SecureDFURequest.readDataObjectInfo, onResponse: response, onError: report)
} else {
sendReset(onError: report)
}
}
/**
Create object command
*/
func createCommandObject(withLength aLength: UInt32, onSuccess success : @escaping Callback, onError report: @escaping ErrorCallback) {
if !aborted {
dfuControlPointCharacteristic!.send(SecureDFURequest.createCommandObject(withSize: aLength), onSuccess: success, onError:report)
} else {
sendReset(onError: report)
}
}
/**
Create object data
*/
func createDataObject(withLength aLength: UInt32, onSuccess success : @escaping Callback, onError report: @escaping ErrorCallback) {
if !aborted {
dfuControlPointCharacteristic!.send(SecureDFURequest.createDataObject(withSize: aLength), onSuccess: success, onError:report)
} else {
sendReset(onError: report)
}
}
/**
Sends a Packet Receipt Notification request eith given value.
*/
func setPacketReceiptNotificationValue(_ aValue: UInt16 = 0, onSuccess success: @escaping Callback, onError report: @escaping ErrorCallback) {
self.packetReceiptNotificationNumber = aValue
dfuControlPointCharacteristic?.send(SecureDFURequest.setPacketReceiptNotification(value: aValue),
onSuccess: {
if aValue > 0 {
self.logger.a("Packet Receipt Notif enabled (Op Code = 2, Value = \(aValue))")
} else {
self.logger.a("Packet Receipt Notif disabled (Op Code = 2, Value = 0)")
}
success()
},
onError: report
)
}
/**
Sends Calculate checksum request
*/
func calculateChecksumCommand(onSuccess success: @escaping SecureDFUResponseCallback, onError report: @escaping ErrorCallback) {
if !aborted {
dfuControlPointCharacteristic!.send(SecureDFURequest.calculateChecksumCommand, onResponse: success, onError: report)
} else {
sendReset(onError: report)
}
}
/**
Sends execute command request
*/
func executeCommand(onSuccess success: @escaping Callback, onError report: @escaping ErrorCallback) {
if !aborted {
dfuControlPointCharacteristic?.send(SecureDFURequest.executeCommand, onSuccess: success, onError: report)
} else {
sendReset(onError: report)
}
}
/**
Disconnects from the device.
- parameter report: a callback called when writing characteristic failed
*/
private func sendReset(onError report: @escaping ErrorCallback) {
aborted = true
// There is no command to reset a Secure DFU device. We can just disconnect
targetPeripheral!.disconnect()
}
//MARK: - Packet commands
/**
Sends the init packet. This method is synchronous and will terminate when all data were written.
The init data file should not have more than ~16 packets of data as the buffer overflow error may occur.
*/
func sendInitPacket(withdata packetData : Data){
dfuPacketCharacteristic!.sendInitPacket(packetData)
}
func sendNextObject(from aRange: Range<Int>, of aFirmware: DFUFirmware, andReportProgressTo progressDelegate: DFUProgressDelegate?,
onSuccess success: @escaping Callback, onError report: @escaping ErrorCallback) {
if aborted {
sendReset(onError: report)
return
}
// Those will be stored here in case of pause/resume
self.firmware = aFirmware
self.range = aRange
self.progressDelegate = progressDelegate
self.report = {
error, message in
self.firmware = nil
self.range = nil
self.success = nil
self.report = nil
self.progressDelegate = nil
report(error, message)
}
self.success = {
self.firmware = nil
self.range = nil
self.success = nil
self.report = nil
self.progressDelegate = nil
self.dfuControlPointCharacteristic!.peripheralDidReceiveObject()
success()
}
dfuControlPointCharacteristic!.waitUntilUploadComplete(onSuccess: self.success!, onPacketReceiptNofitication: { bytesReceived in
if !self.paused && !self.aborted {
let bytesSent = self.dfuPacketCharacteristic!.bytesSent + UInt32(aRange.lowerBound)
if bytesSent == bytesReceived {
self.dfuPacketCharacteristic!.sendNext(self.packetReceiptNotificationNumber, bytesFrom: aRange, of: aFirmware,
andReportProgressTo: progressDelegate, andCompletionTo: self.success!)
} else {
// Target device deported invalid number of bytes received
report(.bytesLost, "\(bytesSent) bytes were sent while \(bytesReceived) bytes were reported as received")
}
} else if self.aborted {
self.firmware = nil
self.range = nil
self.success = nil
self.report = nil
self.progressDelegate = nil
self.sendReset(onError: report)
}
}, onError: self.report!)
// A new object is started, reset counters before sending the next object
// It must be done even if the upload was paused, otherwise it would be resumed from a wrong place
dfuPacketCharacteristic!.resetCounters()
if !paused && !aborted {
// ...and start sending firmware if
dfuPacketCharacteristic!.sendNext(packetReceiptNotificationNumber, bytesFrom: aRange, of: aFirmware,
andReportProgressTo: progressDelegate, andCompletionTo: self.success!)
} else if aborted {
self.firmware = nil
self.range = nil
self.success = nil
self.report = nil
self.progressDelegate = nil
sendReset(onError: report)
}
}
// MARK: - Peripheral Delegate callbacks
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
// Create local references to callback to release the global ones
let _success = self.success
let _report = self.report
self.success = nil
self.report = nil
if error != nil {
logger.e("Characteristics discovery failed")
logger.e(error!)
_report?(.serviceDiscoveryFailed, "Characteristics discovery failed")
} else {
logger.i("DFU characteristics discovered")
// Find DFU characteristics
for characteristic in service.characteristics! {
if SecureDFUPacket.matches(characteristic) {
dfuPacketCharacteristic = SecureDFUPacket(characteristic, logger)
} else if SecureDFUControlPoint.matches(characteristic) {
dfuControlPointCharacteristic = SecureDFUControlPoint(characteristic, logger)
}
// Support for experimental Buttonless DFU Service from SDK 12.x
else if ExperimentalButtonlessDFU.matches(characteristic) {
experimentalButtonlessDfuCharacteristic = ExperimentalButtonlessDFU(characteristic, logger)
_success?()
return
}
// End
}
// Some validation
if dfuControlPointCharacteristic == nil {
logger.e("DFU Control Point characteristics not found")
// DFU Control Point characteristic is required
_report?(.deviceNotSupported, "DFU Control Point characteristic not found")
return
}
if dfuPacketCharacteristic == nil {
logger.e("DFU Packet characteristics not found")
// DFU Packet characteristic is required
_report?(.deviceNotSupported, "DFU Packet characteristic not found")
return
}
if !dfuControlPointCharacteristic!.valid {
logger.e("DFU Control Point characteristics must have Write and Notify properties")
// DFU Control Point characteristic must have Write and Notify properties
_report?(.deviceNotSupported, "DFU Control Point characteristic does not have the Write and Notify properties")
return
}
_success?()
}
}
// MARK: - Support for experimental Buttonless DFU Service from SDK 12.x
/// The buttonless jump feature was experimental in SDK 12. It did not support passing bond information to the DFU bootloader,
/// was not safe (possible DOS attack) and had bugs. This is the service UUID used by this service.
static internal let ExperimentalButtonlessDfuUUID = CBUUID(string: "8E400001-F315-4F60-9FB8-838830DAEA50")
static func matches(experimental service: CBService) -> Bool {
return service.uuid.isEqual(ExperimentalButtonlessDfuUUID)
}
private var experimentalButtonlessDfuCharacteristic:ExperimentalButtonlessDFU?
/**
This method tries to estimate whether the DFU target device is in Application mode which supports
the buttonless jump to the DFU Bootloader.
- returns: true, if it is for sure in the Application more, false, if definitely is not, nil if uknown
*/
func isInApplicationMode() -> Bool? {
// If the experimental buttonless DFU characteristic is not nil it means that the device is in app mode
return experimentalButtonlessDfuCharacteristic != nil
}
var newAddressExpected: Bool {
// The experimental Buttonless DFU will cause the device to advertise with address +1
return experimentalButtonlessDfuCharacteristic != nil
}
/**
Triggers a switch to DFU Bootloader mode on the remote target by sending DFU Start command.
- parameter report: method called when an error occurred
*/
func jumpToBootloaderMode(onError report:@escaping ErrorCallback) {
if !aborted {
experimentalButtonlessDfuCharacteristic!.send(ExperimentalButtonlessDFURequest.enterBootloader, onSuccess: nil, onError: report)
} else {
sendReset(onError: report)
}
}
// End
}
| bsd-3-clause | c980092e2e3a3fcacb326413f4bce64a | 41.283019 | 146 | 0.632586 | 5.746154 | false | false | false | false |
kalanyuz/SwiftR | CommonSource/macOS/NSBezierPath+CGPath.swift | 1 | 998 | //
// NSBezierPath+CGPath.swift
// NativeSigP
//
// Created by Kalanyu Zintus-art on 10/16/15.
// Copyright © 2017 KalanyuZ. All rights reserved.
// Credit : icodeforlove
// URL : https://gist.github.com/jorgenisaksson/76a8dae54fd3dc4e31c2
extension NSBezierPath {
var cgPath : CGPath {
let path = CGMutablePath()
var didClosePath = false
for i in 0..<self.elementCount {
var points = [NSPoint](repeating: .zero, count: 3)
switch self.element(at: i, associatedPoints: &points) {
case .moveToBezierPathElement:
path.move(to: points[0])
case .lineToBezierPathElement:
path.addLine(to: points[0])
case .curveToBezierPathElement:
path.addCurve(to: points[0], control1: points[1], control2: points[2])
case .closePathBezierPathElement:
path.closeSubpath()
didClosePath = true;
}
}
if !didClosePath {
path.closeSubpath()
}
let result = path.copy() ?? CGMutablePath()
return result
}
}
| apache-2.0 | 006acb2075556f4f9fde23559d814974 | 25.236842 | 86 | 0.658977 | 3.40273 | false | false | false | false |
skyylex/HaffmanSwift | Haffman.playground/Contents.swift | 1 | 1094 | //
// main.swift
// HaffmanCoding
//
// Created by Yury Lapitsky on 12/9/15.
// Copyright © 2015 skyylex. All rights reserved.
//
import Foundation
let text = "MIT License \n\ns"
let builder = HaffmanTreeBuilder(text: text)
let tree = builder.buildTree()
if let encodingMap = tree?.generateEncodingMap(), decodingMap = tree?.generateDecodingMap() {
let encodingInfo = encodingMap
var dataStorage = [[Bit]]()
for char in text.characters {
let key = String(char)
if let value = encodingMap[char] {
var digits = value.characters.map { $0 == "0" ? Bit.Zero : Bit.One }
dataStorage.append(digits)
}
}
let bits = Array(dataStorage.flatten())
let bitsString = String.bitString(bits)
let encodedInfo = BitsCoder.transform(dataStorage)
let digits = encodedInfo.bytes
let decodedString = BitsDecoder.decode(encodedInfo.bytes, decodingMap: decodingMap, digitsLeft:encodedInfo.digitsLeft)
let compressedCount = encodedInfo.bytes.count * bytesInUInt32
let rawCount = text.characters.count
}
| mit | f33db98cc9ddc2cfebd468aca58285d1 | 29.361111 | 122 | 0.677951 | 3.768966 | false | false | false | false |
Sharelink/Bahamut | Bahamut/RESTfulAPI/Message/Message.swift | 1 | 3709 | //
// Message.swift
// BahamutRFKit
//
// Created by AlexChow on 15/9/29.
// Copyright (c) 2015年 GStudio. All rights reserved.
//
import Foundation
import EVReflection
import Alamofire
//MARK: Entities
public enum MessageType:String
{
case Text = "text"
case Voice = "voice"
case Picture = "pic"
}
public class Message: BahamutObject
{
public var msgId:String!
public var senderId:String!
public var chatId:String!
public var shareId:String!
public var msg:String!
public var time:String!
public var data:String!
public var msgType:String!
public override func getObjectUniqueIdName() -> String {
return "msgId"
}
public var msgData:NSData!{
if let dataStr = data
{
return NSData(base64String: dataStr)
}
return nil
}
public var timeOfDate:NSDate!{
if let date = DateHelper.stringToAccurateDate(time)
{
return date
}
return NSDate()
}
}
//MARK: Requests
/*
newerThanTime: get the messages that time newer than this messageId
chatId:
GET /Messages/{shareId} : get share messages
*/
public class GetShareMessageRequest: BahamutRFRequestBase
{
public override init() {
super.init()
self.method = Method.GET
self.api = "/Messages"
}
public var newerThanTime:NSDate! = nil{
didSet{
self.paramenters.updateValue(newerThanTime.toAccurateDateTimeString(), forKey: "newerThanTime")
}
}
public var chatId:String!{
didSet{
self.api = "/Messages/\(chatId)"
}
}
}
/*
GET /Message/New : get all new message from server
*/
public class GetNewMessagesRequest : BahamutRFRequestBase
{
public override init() {
super.init()
self.method = Method.GET
self.api = "/Messages/New"
}
}
/*
DELETE /Message/New : notify all new message received
*/
public class NotifyNewMessagesReceivedRequest : BahamutRFRequestBase
{
public override init() {
super.init()
self.method = Method.DELETE
self.api = "/Messages/New"
}
}
/*
POST /Message/{shareId} : send a new message to sharelinker of the share
*/
public class SendMessageRequest : BahamutRFRequestBase
{
public override init() {
super.init()
self.method = Method.POST
self.api = "/Messages"
}
//No limit request
public override func getMaxRequestCount() -> Int32 {
return BahamutRFRequestBase.maxRequestNoLimitCount
}
public var time:NSDate!{
didSet{
self.paramenters.updateValue(time.toAccurateDateTimeString(), forKey: "time")
}
}
public var chatId:String!{
didSet{
self.api = "/Messages/\(chatId)"
}
}
public var type:String = MessageType.Text.rawValue{
didSet{
self.paramenters.updateValue(type, forKey: "type")
}
}
public var message:String!{
didSet{
self.paramenters.updateValue(message, forKey: "message")
}
}
public var messageData:NSData!{
didSet{
if messageData != nil
{
if let str = messageData.base64String()
{
self.paramenters.updateValue(str, forKey: "messageData")
}
}
}
}
public var audienceId:String!{
didSet{
self.paramenters.updateValue(audienceId, forKey: "audienceId")
}
}
public var shareId:String!{
didSet{
self.paramenters.updateValue(shareId, forKey: "shareId")
}
}
} | mit | 7cc7d1b7c572e24eb68739e2c7091db3 | 20.940828 | 107 | 0.594281 | 4.402613 | false | false | false | false |
jordane-quincy/M2_DevMobileIos | JSONProject/ServiceOption.swift | 1 | 626 | //
// ServiceOption.swift
// Demo
//
// Created by MAC ISTV on 28/04/2017.
// Copyright © 2017 UVHC. All rights reserved.
//
import Foundation
import RealmSwift
class ServiceOption: Object {
dynamic var title: String = ""
dynamic var optionDescription: String = ""
dynamic var price: Int = 0
let owner = LinkingObjects(fromType: Person.self, property: "serviceOptions")
convenience public init(title: String, optionDescription: String, price: Int) {
self.init();
self.title = title
self.optionDescription = optionDescription
self.price = price
}
}
| mit | ac118259a1233ad95df6e61501171199 | 23.038462 | 83 | 0.656 | 4.222973 | false | false | false | false |
machelix/swift-2048 | swift-2048/Models/GameModel.swift | 2 | 13710 | //
// GameModel.swift
// swift-2048
//
// Created by Austin Zheng on 6/3/14.
// Copyright (c) 2014 Austin Zheng. All rights reserved.
//
import UIKit
/// A protocol that establishes a way for the game model to communicate with its parent view controller.
protocol GameModelProtocol : class {
func scoreChanged(score: Int)
func moveOneTile(from: (Int, Int), to: (Int, Int), value: Int)
func moveTwoTiles(from: ((Int, Int), (Int, Int)), to: (Int, Int), value: Int)
func insertTile(location: (Int, Int), value: Int)
}
/// A class representing the game state and game logic for swift-2048. It is owned by a NumberTileGame view controller.
class GameModel : NSObject {
let dimension : Int
let threshold : Int
var score : Int = 0 {
didSet {
delegate.scoreChanged(score)
}
}
var gameboard: SquareGameboard<TileObject>
unowned let delegate : GameModelProtocol
var queue: [MoveCommand]
var timer: NSTimer
let maxCommands = 100
let queueDelay = 0.3
init(dimension d: Int, threshold t: Int, delegate: GameModelProtocol) {
dimension = d
threshold = t
self.delegate = delegate
queue = [MoveCommand]()
timer = NSTimer()
gameboard = SquareGameboard(dimension: d, initialValue: .Empty)
super.init()
}
/// Reset the game state.
func reset() {
score = 0
gameboard.setAll(.Empty)
queue.removeAll(keepCapacity: true)
timer.invalidate()
}
/// Order the game model to perform a move (because the user swiped their finger). The queue enforces a delay of a few
/// milliseconds between each move.
func queueMove(direction: MoveDirection, completion: (Bool) -> ()) {
guard queue.count <= maxCommands else {
// Queue is wedged. This should actually never happen in practice.
return
}
queue.append(MoveCommand(direction: direction, completion: completion))
if !timer.valid {
// Timer isn't running, so fire the event immediately
timerFired(timer)
}
}
//------------------------------------------------------------------------------------------------------------------//
/// Inform the game model that the move delay timer fired. Once the timer fires, the game model tries to execute a
/// single move that changes the game state.
func timerFired(_: NSTimer) {
if queue.count == 0 {
return
}
// Go through the queue until a valid command is run or the queue is empty
var changed = false
while queue.count > 0 {
let command = queue[0]
queue.removeAtIndex(0)
changed = performMove(command.direction)
command.completion(changed)
if changed {
// If the command doesn't change anything, we immediately run the next one
break
}
}
if changed {
timer = NSTimer.scheduledTimerWithTimeInterval(queueDelay,
target: self,
selector:
Selector("timerFired:"),
userInfo: nil,
repeats: false)
}
}
//------------------------------------------------------------------------------------------------------------------//
/// Insert a tile with a given value at a position upon the gameboard.
func insertTile(position: (Int, Int), value: Int) {
let (x, y) = position
if case .Empty = gameboard[x, y] {
gameboard[x, y] = TileObject.Tile(value)
delegate.insertTile(position, value: value)
}
}
/// Insert a tile with a given value at a random open position upon the gameboard.
func insertTileAtRandomLocation(value: Int) {
let openSpots = gameboardEmptySpots()
if openSpots.isEmpty {
// No more open spots; don't even bother
return
}
// Randomly select an open spot, and put a new tile there
let idx = Int(arc4random_uniform(UInt32(openSpots.count-1)))
let (x, y) = openSpots[idx]
insertTile((x, y), value: value)
}
/// Return a list of tuples describing the coordinates of empty spots remaining on the gameboard.
func gameboardEmptySpots() -> [(Int, Int)] {
var buffer : [(Int, Int)] = []
for i in 0..<dimension {
for j in 0..<dimension {
if case .Empty = gameboard[i, j] {
buffer += [(i, j)]
}
}
}
return buffer
}
//------------------------------------------------------------------------------------------------------------------//
func tileBelowHasSameValue(location: (Int, Int), _ value: Int) -> Bool {
let (x, y) = location
guard y != dimension - 1 else {
return false
}
if case let .Tile(v) = gameboard[x, y+1] {
return v == value
}
return false
}
func tileToRightHasSameValue(location: (Int, Int), _ value: Int) -> Bool {
let (x, y) = location
guard x != dimension - 1 else {
return false
}
if case let .Tile(v) = gameboard[x+1, y] {
return v == value
}
return false
}
func userHasLost() -> Bool {
guard gameboardEmptySpots().isEmpty else {
// Player can't lose before filling up the board
return false
}
// Run through all the tiles and check for possible moves
for i in 0..<dimension {
for j in 0..<dimension {
switch gameboard[i, j] {
case .Empty:
assert(false, "Gameboard reported itself as full, but we still found an empty tile. This is a logic error.")
case let .Tile(v):
if tileBelowHasSameValue((i, j), v) || tileToRightHasSameValue((i, j), v) {
return false
}
}
}
}
return true
}
func userHasWon() -> (Bool, (Int, Int)?) {
for i in 0..<dimension {
for j in 0..<dimension {
// Look for a tile with the winning score or greater
if case let .Tile(v) = gameboard[i, j] where v >= threshold {
return (true, (i, j))
}
}
}
return (false, nil)
}
//------------------------------------------------------------------------------------------------------------------//
// Perform all calculations and update state for a single move.
func performMove(direction: MoveDirection) -> Bool {
// Prepare the generator closure. This closure differs in behavior depending on the direction of the move. It is
// used by the method to generate a list of tiles which should be modified. Depending on the direction this list
// may represent a single row or a single column, in either direction.
let coordinateGenerator: (Int) -> [(Int, Int)] = { (iteration: Int) -> [(Int, Int)] in
var buffer = Array<(Int, Int)>(count:self.dimension, repeatedValue: (0, 0))
for i in 0..<self.dimension {
switch direction {
case .Up: buffer[i] = (i, iteration)
case .Down: buffer[i] = (self.dimension - i - 1, iteration)
case .Left: buffer[i] = (iteration, i)
case .Right: buffer[i] = (iteration, self.dimension - i - 1)
}
}
return buffer
}
var atLeastOneMove = false
for i in 0..<dimension {
// Get the list of coords
let coords = coordinateGenerator(i)
// Get the corresponding list of tiles
let tiles = coords.map() { (c: (Int, Int)) -> TileObject in
let (x, y) = c
return self.gameboard[x, y]
}
// Perform the operation
let orders = merge(tiles)
atLeastOneMove = orders.count > 0 ? true : atLeastOneMove
// Write back the results
for object in orders {
switch object {
case let MoveOrder.SingleMoveOrder(s, d, v, wasMerge):
// Perform a single-tile move
let (sx, sy) = coords[s]
let (dx, dy) = coords[d]
if wasMerge {
score += v
}
gameboard[sx, sy] = TileObject.Empty
gameboard[dx, dy] = TileObject.Tile(v)
delegate.moveOneTile(coords[s], to: coords[d], value: v)
case let MoveOrder.DoubleMoveOrder(s1, s2, d, v):
// Perform a simultaneous two-tile move
let (s1x, s1y) = coords[s1]
let (s2x, s2y) = coords[s2]
let (dx, dy) = coords[d]
score += v
gameboard[s1x, s1y] = TileObject.Empty
gameboard[s2x, s2y] = TileObject.Empty
gameboard[dx, dy] = TileObject.Tile(v)
delegate.moveTwoTiles((coords[s1], coords[s2]), to: coords[d], value: v)
}
}
}
return atLeastOneMove
}
//------------------------------------------------------------------------------------------------------------------//
/// When computing the effects of a move upon a row of tiles, calculate and return a list of ActionTokens
/// corresponding to any moves necessary to remove interstital space. For example, |[2][ ][ ][4]| will become
/// |[2][4]|.
func condense(group: [TileObject]) -> [ActionToken] {
var tokenBuffer = [ActionToken]()
for (idx, tile) in group.enumerate() {
// Go through all the tiles in 'group'. When we see a tile 'out of place', create a corresponding ActionToken.
switch tile {
case let .Tile(value) where tokenBuffer.count == idx:
tokenBuffer.append(ActionToken.NoAction(source: idx, value: value))
case let .Tile(value):
tokenBuffer.append(ActionToken.Move(source: idx, value: value))
default:
break
}
}
return tokenBuffer;
}
class func quiescentTileStillQuiescent(inputPosition: Int, outputLength: Int, originalPosition: Int) -> Bool {
// Return whether or not a 'NoAction' token still represents an unmoved tile
return (inputPosition == outputLength) && (originalPosition == inputPosition)
}
/// When computing the effects of a move upon a row of tiles, calculate and return an updated list of ActionTokens
/// corresponding to any merges that should take place. This method collapses adjacent tiles of equal value, but each
/// tile can take part in at most one collapse per move. For example, |[1][1][1][2][2]| will become |[2][1][4]|.
func collapse(group: [ActionToken]) -> [ActionToken] {
var tokenBuffer = [ActionToken]()
var skipNext = false
for (idx, token) in group.enumerate() {
if skipNext {
// Prior iteration handled a merge. So skip this iteration.
skipNext = false
continue
}
switch token {
case .SingleCombine:
assert(false, "Cannot have single combine token in input")
case .DoubleCombine:
assert(false, "Cannot have double combine token in input")
case let .NoAction(s, v)
where (idx < group.count-1
&& v == group[idx+1].getValue()
&& GameModel.quiescentTileStillQuiescent(idx, outputLength: tokenBuffer.count, originalPosition: s)):
// This tile hasn't moved yet, but matches the next tile. This is a single merge
// The last tile is *not* eligible for a merge
let next = group[idx+1]
let nv = v + group[idx+1].getValue()
skipNext = true
tokenBuffer.append(ActionToken.SingleCombine(source: next.getSource(), value: nv))
case let t where (idx < group.count-1 && t.getValue() == group[idx+1].getValue()):
// This tile has moved, and matches the next tile. This is a double merge
// (The tile may either have moved prevously, or the tile might have moved as a result of a previous merge)
// The last tile is *not* eligible for a merge
let next = group[idx+1]
let nv = t.getValue() + group[idx+1].getValue()
skipNext = true
tokenBuffer.append(ActionToken.DoubleCombine(source: t.getSource(), second: next.getSource(), value: nv))
case let .NoAction(s, v) where !GameModel.quiescentTileStillQuiescent(idx, outputLength: tokenBuffer.count, originalPosition: s):
// A tile that didn't move before has moved (first cond.), or there was a previous merge (second cond.)
tokenBuffer.append(ActionToken.Move(source: s, value: v))
case let .NoAction(s, v):
// A tile that didn't move before still hasn't moved
tokenBuffer.append(ActionToken.NoAction(source: s, value: v))
case let .Move(s, v):
// Propagate a move
tokenBuffer.append(ActionToken.Move(source: s, value: v))
default:
// Don't do anything
break
}
}
return tokenBuffer
}
/// When computing the effects of a move upon a row of tiles, take a list of ActionTokens prepared by the condense()
/// and convert() methods and convert them into MoveOrders that can be fed back to the delegate.
func convert(group: [ActionToken]) -> [MoveOrder] {
var moveBuffer = [MoveOrder]()
for (idx, t) in group.enumerate() {
switch t {
case let .Move(s, v):
moveBuffer.append(MoveOrder.SingleMoveOrder(source: s, destination: idx, value: v, wasMerge: false))
case let .SingleCombine(s, v):
moveBuffer.append(MoveOrder.SingleMoveOrder(source: s, destination: idx, value: v, wasMerge: true))
case let .DoubleCombine(s1, s2, v):
moveBuffer.append(MoveOrder.DoubleMoveOrder(firstSource: s1, secondSource: s2, destination: idx, value: v))
default:
// Don't do anything
break
}
}
return moveBuffer
}
/// Given an array of TileObjects, perform a collapse and create an array of move orders.
func merge(group: [TileObject]) -> [MoveOrder] {
// Calculation takes place in three steps:
// 1. Calculate the moves necessary to produce the same tiles, but without any interstital space.
// 2. Take the above, and calculate the moves necessary to collapse adjacent tiles of equal value.
// 3. Take the above, and convert into MoveOrders that provide all necessary information to the delegate.
return convert(collapse(condense(group)))
}
}
| mit | 97237df624aa9283912af94a79598f06 | 36.255435 | 135 | 0.604814 | 4.275023 | false | false | false | false |
inder/ios-ranking-visualization | RankViz/RankViz/ScrollableEquitiesRowHeadersViewController.swift | 1 | 2479 | //
// ScrollableEquitiesRowHeadersViewController.swift
// Reverse Graph
//
// Created by Inder Sabharwal on 1/21/15.
// Copyright (c) 2015 truquity. All rights reserved.
//
import Foundation
import UIKit
class ScrollableEquitiesRowHeadersViewController : SimpleBidirectionalTableViewController, SimpleBidirectionalTableViewDelegate {
var portfolio: Portfolio!
var rowHeaderDimensions: CGSize!
weak var controller: LineChartVizViewController?
init(portfolio: Portfolio, rowHeaderDimensions: CGSize) {
self.portfolio = portfolio
self.rowHeaderDimensions = rowHeaderDimensions
super.init(direction: .Vertical)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func loadView() {
super.loadView()
self.tableView.tableViewDelegate = self
}
func numberOfCells(source: SimpleBidirectionalTableView) -> Int {
return portfolio.equities.count
}
func heightOfCells(source: SimpleBidirectionalTableView) -> CGFloat {
return rowHeaderDimensions.height
}
func widthOfCells(source: SimpleBidirectionalTableView) -> CGFloat {
return rowHeaderDimensions.width
}
var equities = [Equity]()
func viewForCell(atIndex idx: Int, source: SimpleBidirectionalTableView) -> UIView? {
if (idx >= portfolio.equities.count) {
return nil
}
var view = EquityRowHeaderView(frame: CGRectMake(0, 0, rowHeaderDimensions.width, rowHeaderDimensions.height))
view.equity = portfolio.rankings[idx].1
equities.append(portfolio.rankings[idx].1)
return view
}
var startIndex: Int = 0
func didShowCellsInRange(fromStartIdx startIdx: Int, toEndIndex endIdx: Int, withStartOffset startOffset: CGFloat, source: SimpleBidirectionalTableView) {
startIndex = startIdx
controller?.didShowCellsInRange(fromStartIdx: startIdx, toEndIndex: endIdx, withStartOffset: startOffset, source: source)
}
//take some action, if you want to.
func userSelectedCell(atIndex row: Int, cell: UIView, source: SimpleBidirectionalTableView) {
//for now rank calculation is a hack. I do not like it, it has to be more than a fixed offset.
//maybe it is okay for now since this is a rank based visualization??!!
controller?.lineChartView.highlightLinesForElement(atRank: row + 1) //rank is 1 indexed.
}
} | apache-2.0 | 61558cc52c1211b8910b51eb902c4503 | 34.942029 | 158 | 0.701089 | 4.851272 | false | false | false | false |
mityung/XERUNG | IOS/Xerung/Xerung/ContactsViewController.swift | 1 | 5047 | //
// ContactsViewController.swift
// Xerung
//
// Created by mityung on 15/02/17.
// Copyright © 2017 mityung. All rights reserved.
//
import UIKit
class ContactsViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var name = [String]()
var dataDict = [String:String]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "All Contacts"
// tableView.backgroundView = UIImageView(image: UIImage(named: "backScreen.png"))
tableView.separatorStyle = .none
// Do any additional setup after loading the view.
getContactDetails { (response) in
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
for i in 0 ..< phoneBook.count {
self.dataDict.updateValue(phoneBook[i].phone, forKey: phoneBook[i].name)
}
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sideMenu(_ sender: Any) {
self.menuContainerViewController.toggleLeftSideMenuCompletion { () -> Void in
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return phoneBook.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ContactViewCell", for: indexPath) as! ContactViewCell
let temp = phoneBook[indexPath.row].name
let index = temp.characters.index(temp.startIndex, offsetBy: 0)
cell.firstLetterLabel.text = String(temp[index])
cell.firstLetterLabel.textColor = UIColor.white
cell.firstLetterLabel.backgroundColor = UIColor.randomColor()
cell.nameLabel.text = phoneBook[indexPath.row].name
cell.numberLabel.text = phoneBook[indexPath.row].phone
cell.backgroundColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 0.2)
cell.callButton.tag = indexPath.row
cell.callButton.addTarget(self, action: #selector(self.call(sender:)), for: UIControlEvents.touchUpInside)
cell.selectionStyle = .none
return cell
}
func call(sender:UIButton) {
if let url = URL(string: "tel://\(phoneBook[sender.tag].phone.removingWhitespaces())"), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
}
@IBAction func syncContacts(_ sender: AnyObject) {
if phoneBook.count == 0 {
return
}else {
self.sync()
}
}
func sync(){
do {
let jsonData = try JSONSerialization.data(withJSONObject: dataDict, options: JSONSerialization.WritingOptions.prettyPrinted)
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
if let dictFromJSON = decoded as? [String:String] {
let sendJson: [String: String] = [
"PFLAG": "1",
"PUID":userID,
"PBACKUPLIST" : String(describing: dictFromJSON)
]
if Reachability.isConnectedToNetwork() {
startLoader(view: self.view)
DataProvider.sharedInstance.getServerData2(sendJson, path: "Mibackupsend", successBlock: { (response) in
stopLoader()
print(response)
}) { (error) in
print(error)
stopLoader()
}
}else{
showAlert("Alert", message: "No internet connectivity.")
}
}
} catch let error as NSError {
print(error)
}
}
func showAlert(_ title:String,message:String){
let refreshAlert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction!) in
}))
present(refreshAlert, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | e5874b41d233c00775539e5ad4852fd3 | 33.326531 | 136 | 0.581649 | 5.180698 | false | false | false | false |
lojals/QRGen | Pods/LiquidFloatingActionButton/Pod/Classes/LiquidFloatingActionButton.swift | 1 | 17320 | //
// LiquidFloatingActionButton.swift
// Pods
//
// Created by Takuma Yoshida on 2015/08/25.
//
//
import Foundation
import QuartzCore
// LiquidFloatingButton DataSource methods
@objc public protocol LiquidFloatingActionButtonDataSource {
func numberOfCells(liquidFloatingActionButton: LiquidFloatingActionButton) -> Int
func cellForIndex(index: Int) -> LiquidFloatingCell
}
@objc public protocol LiquidFloatingActionButtonDelegate {
// selected method
optional func liquidFloatingActionButton(liquidFloatingActionButton: LiquidFloatingActionButton, didSelectItemAtIndex index: Int)
}
public enum LiquidFloatingActionButtonAnimateStyle : Int {
case Up
case Right
case Left
case Down
}
@IBDesignable
public class LiquidFloatingActionButton : UIView {
private let internalRadiusRatio: CGFloat = 20.0 / 56.0
public var cellRadiusRatio: CGFloat = 0.38
public var animateStyle: LiquidFloatingActionButtonAnimateStyle = .Up {
didSet {
baseView.animateStyle = animateStyle
}
}
public var enableShadow = true {
didSet {
setNeedsDisplay()
}
}
public var delegate: LiquidFloatingActionButtonDelegate?
public var dataSource: LiquidFloatingActionButtonDataSource?
public var responsible = true
public var isClosed: Bool {
get {
return plusRotation == 0
}
}
@IBInspectable public var color: UIColor = UIColor(red: 82 / 255.0, green: 112 / 255.0, blue: 235 / 255.0, alpha: 1.0) {
didSet {
baseView.color = color
}
}
private let plusLayer = CAShapeLayer()
private let circleLayer = CAShapeLayer()
private var touching = false
private var plusRotation: CGFloat = 0
private var baseView = CircleLiquidBaseView()
private let liquidView = UIView()
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setup()
}
private func insertCell(cell: LiquidFloatingCell) {
cell.color = self.color
cell.radius = self.frame.width * cellRadiusRatio
cell.center = self.center.minus(self.frame.origin)
cell.actionButton = self
insertSubview(cell, aboveSubview: baseView)
}
private func cellArray() -> [LiquidFloatingCell] {
var result: [LiquidFloatingCell] = []
if let source = dataSource {
for i in 0..<source.numberOfCells(self) {
result.append(source.cellForIndex(i))
}
}
return result
}
// open all cells
public func open() {
// rotate plus icon
self.plusLayer.addAnimation(plusKeyframe(true), forKey: "plusRot")
self.plusRotation = CGFloat(M_PI * 0.25) // 45 degree
let cells = cellArray()
for cell in cells {
insertCell(cell)
}
self.baseView.open(cells)
setNeedsDisplay()
}
// close all cells
public func close() {
// rotate plus icon
self.plusLayer.addAnimation(plusKeyframe(false), forKey: "plusRot")
self.plusRotation = 0
self.baseView.close(cellArray())
setNeedsDisplay()
}
// MARK: draw icon
public override func drawRect(rect: CGRect) {
drawCircle()
drawShadow()
drawPlus(plusRotation)
}
private func drawCircle() {
self.circleLayer.frame = CGRect(origin: CGPointZero, size: self.frame.size)
self.circleLayer.cornerRadius = self.frame.width * 0.5
self.circleLayer.masksToBounds = true
if touching && responsible {
self.circleLayer.backgroundColor = self.color.white(0.5).CGColor
} else {
self.circleLayer.backgroundColor = self.color.CGColor
}
}
private func drawPlus(rotation: CGFloat) {
plusLayer.frame = CGRect(origin: CGPointZero, size: self.frame.size)
plusLayer.lineCap = kCALineCapRound
plusLayer.strokeColor = UIColor.whiteColor().CGColor // TODO: customizable
plusLayer.lineWidth = 3.0
plusLayer.path = pathPlus(rotation).CGPath
}
private func drawShadow() {
if enableShadow {
circleLayer.appendShadow()
}
}
// draw button plus or close face
private func pathPlus(rotation: CGFloat) -> UIBezierPath {
let radius = self.frame.width * internalRadiusRatio * 0.5
let center = self.center.minus(self.frame.origin)
let points = [
CGMath.circlePoint(center, radius: radius, rad: rotation),
CGMath.circlePoint(center, radius: radius, rad: CGFloat(M_PI_2) + rotation),
CGMath.circlePoint(center, radius: radius, rad: CGFloat(M_PI_2) * 2 + rotation),
CGMath.circlePoint(center, radius: radius, rad: CGFloat(M_PI_2) * 3 + rotation)
]
let path = UIBezierPath()
path.moveToPoint(points[0])
path.addLineToPoint(points[2])
path.moveToPoint(points[1])
path.addLineToPoint(points[3])
return path
}
private func plusKeyframe(closed: Bool) -> CAKeyframeAnimation {
let paths = closed ? [
pathPlus(CGFloat(M_PI * 0)),
pathPlus(CGFloat(M_PI * 0.125)),
pathPlus(CGFloat(M_PI * 0.25)),
] : [
pathPlus(CGFloat(M_PI * 0.25)),
pathPlus(CGFloat(M_PI * 0.125)),
pathPlus(CGFloat(M_PI * 0)),
]
let anim = CAKeyframeAnimation(keyPath: "path")
anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
anim.values = paths.map { $0.CGPath }
anim.duration = 0.5
anim.removedOnCompletion = true
anim.fillMode = kCAFillModeForwards
anim.delegate = self
return anim
}
// MARK: Events
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.touching = true
setNeedsDisplay()
}
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.touching = false
setNeedsDisplay()
didTapped()
}
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
self.touching = false
setNeedsDisplay()
}
public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
for cell in cellArray() {
let pointForTargetView = cell.convertPoint(point, fromView: self)
if (CGRectContainsPoint(cell.bounds, pointForTargetView)) {
if cell.userInteractionEnabled {
return cell.hitTest(pointForTargetView, withEvent: event)
}
}
}
return super.hitTest(point, withEvent: event)
}
// MARK: private methods
private func setup() {
self.backgroundColor = UIColor.clearColor()
self.clipsToBounds = false
baseView.setup(self)
addSubview(baseView)
liquidView.frame = baseView.frame
liquidView.userInteractionEnabled = false
addSubview(liquidView)
liquidView.layer.addSublayer(circleLayer)
circleLayer.addSublayer(plusLayer)
}
private func didTapped() {
if isClosed {
open()
} else {
close()
}
}
public func didTappedCell(target: LiquidFloatingCell) {
if let _ = dataSource {
let cells = cellArray()
for i in 0..<cells.count {
let cell = cells[i]
if target === cell {
delegate?.liquidFloatingActionButton?(self, didSelectItemAtIndex: i)
}
}
}
}
}
class ActionBarBaseView : UIView {
var opening = false
func setup(actionButton: LiquidFloatingActionButton) {
}
func translateY(layer: CALayer, duration: CFTimeInterval, f: (CABasicAnimation) -> ()) {
let translate = CABasicAnimation(keyPath: "transform.translation.y")
f(translate)
translate.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
translate.removedOnCompletion = false
translate.fillMode = kCAFillModeForwards
translate.duration = duration
layer.addAnimation(translate, forKey: "transYAnim")
}
}
class CircleLiquidBaseView : ActionBarBaseView {
let openDuration: CGFloat = 0.6
let closeDuration: CGFloat = 0.2
let viscosity: CGFloat = 0.65
var animateStyle: LiquidFloatingActionButtonAnimateStyle = .Up
var color: UIColor = UIColor(red: 82 / 255.0, green: 112 / 255.0, blue: 235 / 255.0, alpha: 1.0) {
didSet {
engine?.color = color
bigEngine?.color = color
}
}
var baseLiquid: LiquittableCircle?
var engine: SimpleCircleLiquidEngine?
var bigEngine: SimpleCircleLiquidEngine?
var enableShadow = true
private var openingCells: [LiquidFloatingCell] = []
private var keyDuration: CGFloat = 0
private var displayLink: CADisplayLink?
override func setup(actionButton: LiquidFloatingActionButton) {
self.frame = actionButton.frame
self.center = actionButton.center.minus(actionButton.frame.origin)
self.animateStyle = actionButton.animateStyle
let radius = min(self.frame.width, self.frame.height) * 0.5
self.engine = SimpleCircleLiquidEngine(radiusThresh: radius * 0.73, angleThresh: 0.45)
engine?.viscosity = viscosity
self.bigEngine = SimpleCircleLiquidEngine(radiusThresh: radius, angleThresh: 0.55)
bigEngine?.viscosity = viscosity
self.engine?.color = actionButton.color
self.bigEngine?.color = actionButton.color
baseLiquid = LiquittableCircle(center: self.center.minus(self.frame.origin), radius: radius, color: actionButton.color)
baseLiquid?.clipsToBounds = false
baseLiquid?.layer.masksToBounds = false
clipsToBounds = false
layer.masksToBounds = false
addSubview(baseLiquid!)
}
func open(cells: [LiquidFloatingCell]) {
stop()
let distance: CGFloat = self.frame.height * 1.25
displayLink = CADisplayLink(target: self, selector: Selector("didDisplayRefresh:"))
displayLink?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
opening = true
for cell in cells {
cell.layer.removeAllAnimations()
cell.layer.eraseShadow()
openingCells.append(cell)
}
}
func close(cells: [LiquidFloatingCell]) {
stop()
let distance: CGFloat = self.frame.height * 1.25
opening = false
displayLink = CADisplayLink(target: self, selector: Selector("didDisplayRefresh:"))
displayLink?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
for cell in cells {
cell.layer.removeAllAnimations()
cell.layer.eraseShadow()
openingCells.append(cell)
cell.userInteractionEnabled = false
}
}
func didFinishUpdate() {
if opening {
for cell in openingCells {
cell.userInteractionEnabled = true
}
} else {
for cell in openingCells {
cell.removeFromSuperview()
}
}
}
func update(delay: CGFloat, duration: CGFloat, f: (LiquidFloatingCell, Int, CGFloat) -> ()) {
if openingCells.isEmpty {
return
}
let maxDuration = duration + CGFloat(openingCells.count) * CGFloat(delay)
let t = keyDuration
let allRatio = easeInEaseOut(t / maxDuration)
if allRatio >= 1.0 {
didFinishUpdate()
stop()
return
}
engine?.clear()
bigEngine?.clear()
for i in 0..<openingCells.count {
let liquidCell = openingCells[i]
let cellDelay = CGFloat(delay) * CGFloat(i)
let ratio = easeInEaseOut((t - cellDelay) / duration)
f(liquidCell, i, ratio)
}
if let firstCell = openingCells.first {
bigEngine?.push(baseLiquid!, other: firstCell)
}
for i in 1..<openingCells.count {
let prev = openingCells[i - 1]
let cell = openingCells[i]
engine?.push(prev, other: cell)
}
engine?.draw(baseLiquid!)
bigEngine?.draw(baseLiquid!)
}
func updateOpen() {
update(0.1, duration: openDuration) { cell, i, ratio in
let posRatio = ratio > CGFloat(i) / CGFloat(self.openingCells.count) ? ratio : 0
let distance = (cell.frame.height * 0.5 + CGFloat(i + 1) * cell.frame.height * 1.5) * posRatio
cell.center = self.center.plus(self.differencePoint(distance))
cell.update(ratio, open: true)
}
}
func updateClose() {
update(0, duration: closeDuration) { cell, i, ratio in
let distance = (cell.frame.height * 0.5 + CGFloat(i + 1) * cell.frame.height * 1.5) * (1 - ratio)
cell.center = self.center.plus(self.differencePoint(distance))
cell.update(ratio, open: false)
}
}
func differencePoint(distance: CGFloat) -> CGPoint {
switch animateStyle {
case .Up:
return CGPoint(x: 0, y: -distance)
case .Right:
return CGPoint(x: distance, y: 0)
case .Left:
return CGPoint(x: -distance, y: 0)
case .Down:
return CGPoint(x: 0, y: distance)
}
}
func stop() {
for cell in openingCells {
if enableShadow {
cell.layer.appendShadow()
}
}
openingCells = []
keyDuration = 0
displayLink?.invalidate()
}
func easeInEaseOut(t: CGFloat) -> CGFloat {
if t >= 1.0 {
return 1.0
}
if t < 0 {
return 0
}
var t2 = t * 2
return -1 * t * (t - 2)
}
func didDisplayRefresh(displayLink: CADisplayLink) {
if opening {
keyDuration += CGFloat(displayLink.duration)
updateOpen()
} else {
keyDuration += CGFloat(displayLink.duration)
updateClose()
}
}
}
public class LiquidFloatingCell : LiquittableCircle {
let internalRatio: CGFloat = 0.75
public var responsible = true
public var imageView = UIImageView()
weak var actionButton: LiquidFloatingActionButton?
// for implement responsible color
private var originalColor: UIColor
public override var frame: CGRect {
didSet {
resizeSubviews()
}
}
init(center: CGPoint, radius: CGFloat, color: UIColor, icon: UIImage) {
self.originalColor = color
super.init(center: center, radius: radius, color: color)
setup(icon)
}
init(center: CGPoint, radius: CGFloat, color: UIColor, view: UIView) {
self.originalColor = color
super.init(center: center, radius: radius, color: color)
setupView(view)
}
public init(icon: UIImage) {
self.originalColor = UIColor.clearColor()
super.init()
setup(icon)
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(image: UIImage, tintColor: UIColor = UIColor.whiteColor()) {
imageView.image = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
imageView.tintColor = tintColor
setupView(imageView)
}
func setupView(view: UIView) {
userInteractionEnabled = false
addSubview(view)
resizeSubviews()
}
private func resizeSubviews() {
let size = CGSize(width: frame.width * 0.5, height: frame.height * 0.5)
imageView.frame = CGRect(x: frame.width - frame.width * internalRatio, y: frame.height - frame.height * internalRatio, width: size.width, height: size.height)
}
func update(key: CGFloat, open: Bool) {
for subview in self.subviews {
if let view = subview as? UIView {
let ratio = max(2 * (key * key - 0.5), 0)
view.alpha = open ? ratio : -ratio
}
}
}
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if responsible {
originalColor = color
color = originalColor.white(0.5)
setNeedsDisplay()
}
}
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
if responsible {
color = originalColor
setNeedsDisplay()
}
}
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
color = originalColor
actionButton?.didTappedCell(self)
}
} | mit | 210fd17191c72e7c7d9af0a2e9b6ad9f | 30.665448 | 166 | 0.602887 | 4.80844 | false | false | false | false |
proversity-org/edx-app-ios | Source/UserProfile.swift | 1 | 4397 | //
// Profile.swift
// edX
//
// Created by Michael Katz on 9/24/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
import edXCore
public class UserProfile {
public enum ProfilePrivacy: String {
case Private = "private"
case Public = "all_users"
}
enum ProfileFields: String, RawStringExtractable {
case Image = "profile_image"
case HasImage = "has_image"
case ImageURL = "image_url_full"
case Username = "username"
case LanguagePreferences = "language_proficiencies"
case Country = "country"
case Bio = "bio"
case YearOfBirth = "year_of_birth"
case ParentalConsent = "requires_parental_consent"
case AccountPrivacy = "account_privacy"
}
let hasProfileImage: Bool
let imageURL: String?
let username: String?
var preferredLanguages: [[String: Any]]?
var countryCode: String?
var bio: String?
var birthYear: Int?
let parentalConsent: Bool?
var accountPrivacy: ProfilePrivacy?
var hasUpdates: Bool { return updateDictionary.count > 0 }
var updateDictionary = [String: AnyObject]()
public init?(json: JSON) {
let profileImage = json[ProfileFields.Image]
if let hasImage = profileImage[ProfileFields.HasImage].bool, hasImage {
hasProfileImage = true
imageURL = profileImage[ProfileFields.ImageURL].string
} else {
hasProfileImage = false
imageURL = nil
}
username = json[ProfileFields.Username].string
preferredLanguages = json[ProfileFields.LanguagePreferences].arrayObject as? [[String: Any]]
countryCode = json[ProfileFields.Country].string
bio = json[ProfileFields.Bio].string
birthYear = json[ProfileFields.YearOfBirth].int
parentalConsent = json[ProfileFields.ParentalConsent].bool
accountPrivacy = ProfilePrivacy(rawValue: json[ProfileFields.AccountPrivacy].string ?? "")
}
internal init(username : String, bio : String? = nil, parentalConsent : Bool? = false, countryCode : String? = nil, accountPrivacy : ProfilePrivacy? = nil) {
self.accountPrivacy = accountPrivacy
self.username = username
self.hasProfileImage = false
self.imageURL = nil
self.parentalConsent = parentalConsent
self.bio = bio
self.countryCode = countryCode
}
var languageCode: String? {
get {
guard let languages = preferredLanguages, languages.count > 0 else { return nil }
return languages[0]["code"] as? String
}
set {
guard let code = newValue else { preferredLanguages = []; return }
guard preferredLanguages != nil && preferredLanguages!.count > 0 else {
preferredLanguages = [["code": code]]
return
}
let cRange = 0...0
let range = Range(cRange)
preferredLanguages?.replaceSubrange(range, with: [["code": code]])
}
}
}
extension UserProfile { //ViewModel
func image(networkManager: NetworkManager) -> RemoteImage {
let placeholder = UIImage(named: "profilePhotoPlaceholder")
if let url = imageURL, hasProfileImage {
return RemoteImageImpl(url: url, networkManager: networkManager, placeholder: placeholder, persist: true)
}
else {
return RemoteImageJustImage(image: placeholder)
}
}
var country: String? {
guard let code = countryCode else { return nil }
return (Locale.current as NSLocale).displayName(forKey: NSLocale.Key.countryCode, value: code) ?? ""
}
var language: String? {
return languageCode.flatMap { return (Locale.current as NSLocale).displayName(forKey: NSLocale.Key.languageCode, value: $0) }
}
var sharingLimitedProfile: Bool {
get {
return (parentalConsent ?? false) || (accountPrivacy == nil) || (accountPrivacy! == .Private)
}
}
func setLimitedProfile(newValue:Bool) {
let newStatus: ProfilePrivacy = newValue ? .Private: .Public
if newStatus != accountPrivacy {
updateDictionary[ProfileFields.AccountPrivacy.rawValue] = newStatus.rawValue as AnyObject?
}
accountPrivacy = newStatus
}
}
| apache-2.0 | 0123b6d43233f7b1855b11ec5176a188 | 34.451613 | 161 | 0.628981 | 4.984127 | false | false | false | false |
sschiau/swift-package-manager | Sources/Basic/Thread.swift | 2 | 2903 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Foundation
/// This class bridges the gap between Darwin and Linux Foundation Threading API.
/// It provides closure based execution and a join method to block the calling thread
/// until the thread is finished executing.
final public class Thread {
/// The thread implementation which is Foundation.Thread on Linux and
/// a Thread subclass which provides closure support on Darwin.
private var thread: ThreadImpl!
/// Condition variable to support blocking other threads using join when this thread has not finished executing.
private var finishedCondition: Condition
/// A boolean variable to track if this thread has finished executing its task.
private var isFinished: Bool
/// Creates an instance of thread class with closure to be executed when start() is called.
public init(task: @escaping () -> Void) {
isFinished = false
finishedCondition = Condition()
// Wrap the task with condition notifying any other threads blocked due to this thread.
// Capture self weakly to avoid reference cycle. In case Thread is deinited before the task
// runs, skip the use of finishedCondition.
let theTask = { [weak self] in
if let strongSelf = self {
precondition(!strongSelf.isFinished)
strongSelf.finishedCondition.whileLocked {
task()
strongSelf.isFinished = true
strongSelf.finishedCondition.broadcast()
}
} else {
// If the containing thread has been destroyed, we can ignore the finished condition and just run the
// task.
task()
}
}
self.thread = ThreadImpl(block: theTask)
}
/// Starts the thread execution.
public func start() {
thread.start()
}
/// Blocks the calling thread until this thread is finished execution.
public func join() {
finishedCondition.whileLocked {
while !isFinished {
finishedCondition.wait()
}
}
}
}
#if os(macOS)
/// A helper subclass of Foundation's Thread with closure support.
final private class ThreadImpl: Foundation.Thread {
/// The task to be executed.
private let task: () -> Void
override func main() {
task()
}
init(block task: @escaping () -> Void) {
self.task = task
}
}
#else
// Thread on Linux supports closure so just use it directly.
typealias ThreadImpl = Foundation.Thread
#endif
| apache-2.0 | 48a7ec6b775b2394e2d29bf9032fcfd1 | 32.367816 | 117 | 0.650706 | 5.128975 | false | false | false | false |
mzeeshanid/MZDownloadManager | Sources/MZDownloadManager/Classes/MZUtility.swift | 1 | 4328 | //
// MZUtility.swift
// MZDownloadManager
//
// Created by Muhammad Zeeshan on 22/10/2014.
// Copyright (c) 2014 ideamakerz. All rights reserved.
//
import UIKit
open class MZUtility: NSObject {
@objc public static let DownloadCompletedNotif: String = {
return "com.MZDownloadManager.DownloadCompletedNotif"
}()
@objc public static let baseFilePath: String = {
return (NSHomeDirectory() as NSString).appendingPathComponent("Documents") as String
}()
@objc public class func getUniqueFileNameWithPath(_ filePath : NSString) -> NSString {
let fullFileName : NSString = filePath.lastPathComponent as NSString
let fileName : NSString = fullFileName.deletingPathExtension as NSString
let fileExtension : NSString = fullFileName.pathExtension as NSString
var suggestedFileName : NSString = fileName
var isUnique : Bool = false
var fileNumber : Int = 0
let fileManger : FileManager = FileManager.default
repeat {
var fileDocDirectoryPath : NSString?
if fileExtension.length > 0 {
fileDocDirectoryPath = "\(filePath.deletingLastPathComponent)/\(suggestedFileName).\(fileExtension)" as NSString?
} else {
fileDocDirectoryPath = "\(filePath.deletingLastPathComponent)/\(suggestedFileName)" as NSString?
}
let isFileAlreadyExists : Bool = fileManger.fileExists(atPath: fileDocDirectoryPath! as String)
if isFileAlreadyExists {
fileNumber += 1
suggestedFileName = "\(fileName)(\(fileNumber))" as NSString
} else {
isUnique = true
if fileExtension.length > 0 {
suggestedFileName = "\(suggestedFileName).\(fileExtension)" as NSString
}
}
} while isUnique == false
return suggestedFileName
}
@objc public class func calculateFileSizeInUnit(_ contentLength : Int64) -> Float {
let dataLength : Float64 = Float64(contentLength)
if dataLength >= (1024.0*1024.0*1024.0) {
return Float(dataLength/(1024.0*1024.0*1024.0))
} else if dataLength >= 1024.0*1024.0 {
return Float(dataLength/(1024.0*1024.0))
} else if dataLength >= 1024.0 {
return Float(dataLength/1024.0)
} else {
return Float(dataLength)
}
}
@objc public class func calculateUnit(_ contentLength : Int64) -> NSString {
if(contentLength >= (1024*1024*1024)) {
return "GB"
} else if contentLength >= (1024*1024) {
return "MB"
} else if contentLength >= 1024 {
return "KB"
} else {
return "Bytes"
}
}
@objc public class func addSkipBackupAttributeToItemAtURL(_ docDirectoryPath : NSString) -> Bool {
let url : URL = URL(fileURLWithPath: docDirectoryPath as String)
let fileManager = FileManager.default
if fileManager.fileExists(atPath: url.path) {
do {
try (url as NSURL).setResourceValue(NSNumber(value: true as Bool), forKey: URLResourceKey.isExcludedFromBackupKey)
return true
} catch let error as NSError {
print("Error excluding \(url.lastPathComponent) from backup \(error)")
return false
}
} else {
return false
}
}
@objc public class func getFreeDiskspace() -> NSNumber? {
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let systemAttributes: AnyObject?
do {
systemAttributes = try FileManager.default.attributesOfFileSystem(forPath: documentDirectoryPath.last!) as AnyObject?
let freeSize = systemAttributes?[FileAttributeKey.systemFreeSize] as? NSNumber
return freeSize
} catch let error as NSError {
print("Error Obtaining System Memory Info: Domain = \(error.domain), Code = \(error.code)")
return nil;
}
}
}
| bsd-3-clause | a88e88521db78ee18d609f8e284c99ec | 37.300885 | 130 | 0.591728 | 5.584516 | false | false | false | false |
martrik/BadulakeMap | Apps/iOS/BadulakeMap/BMNewBadu.swift | 1 | 779 | //
// BMAddBadulakeVC.swift
// BadulakeMap
//
// Created by Martí Serra Vivancos on 08/06/15.
// Copyright (c) 2015 Tomorrow Developers s.c.p. All rights reserved.
//
import UIKit
class BMNewBadu: UIView {
override func viewDidLoad() {
super.viewDidLoad()
// Title
var title = UILabel(frame: CGRectMake(0, 0, 0, 0))
// Info
var baduName = UILabel()
var baduNameField = UITextField()
var baduLocation = UILabel()
var baduAlways = UILabel()
var baduAlwaysSwitch = UISwitch()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 596c4da0a432b618afeeddfc27f78a9c | 18.948718 | 70 | 0.57455 | 4.346369 | false | false | false | false |
firebase/snippets-ios | dl-invites-sample/InvitesSample/ViewController.swift | 1 | 2306 | //
// Copyright (c) 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import FirebaseDynamicLinks
class ViewController: UIViewController {
@IBOutlet var linkLabel: UILabel!
// [START share_controller]
lazy private var shareController: UIActivityViewController = {
let activities: [Any] = [
"Learn how to share content via Firebase",
URL(string: "https://firebase.google.com")!
]
let controller = UIActivityViewController(activityItems: activities,
applicationActivities: nil)
return controller
}()
@IBAction func shareButtonPressed(_ sender: Any) {
let inviteController = UIStoryboard(name: "Main", bundle: nil)
.instantiateViewController(withIdentifier: "InviteViewController")
self.navigationController?.pushViewController(inviteController, animated: true)
}
// [END share_controller]
// [START generate_link]
func generateContentLink() -> URL {
let baseURL = URL(string: "https://your-custom-name.page.link")!
let domain = "https://your-app.page.link"
let linkBuilder = DynamicLinkComponents(link: baseURL, domainURIPrefix: domain)
linkBuilder?.iOSParameters = DynamicLinkIOSParameters(bundleID: "com.your.bundleID")
linkBuilder?.androidParameters =
DynamicLinkAndroidParameters(packageName: "com.your.packageName")
// Fall back to the base url if we can't generate a dynamic link.
return linkBuilder?.link ?? baseURL
}
// [END generate_link]
@IBAction func shareLinkButtonPressed(_ sender: Any) {
guard let item = sender as? UIView else { return }
shareController.popoverPresentationController?.sourceView = item
self.present(shareController, animated: true, completion: nil)
}
}
| apache-2.0 | 49387d6fbe91fe6deab0c302ac13eada | 35.03125 | 88 | 0.713356 | 4.530452 | false | false | false | false |
narner/AudioKit | AudioKit/Common/Internals/CoreAudio/AudioUnit+Helpers.swift | 1 | 4615 | //
// AudioUnit+Helpers.swift
// AudioKit
//
// Created by Daniel Clelland on 25/06/16.
// Updated for AudioKit by Aurelius Prochazka.
//
// Copyright © 2017 Daniel Clelland. All rights reserved.
//
import CoreAudio
// MARK: - AudioUnit helpers
/// Get, set, and listen to properties
public extension AudioUnit {
//swiftlint:disable force_try
/// Get value for a property
func getValue<T>(forProperty property: AudioUnitPropertyID) -> T {
let (dataSize, _) = try! getPropertyInfo(propertyID: property)
return try! getProperty(propertyID: property, dataSize: dataSize)
}
/// Set value for a property
func setValue<T>(value: T, forProperty property: AudioUnitPropertyID) {
let (dataSize, _) = try! getPropertyInfo(propertyID: property)
return try! setProperty(propertyID: property, dataSize: dataSize, data: value)
}
/// Add a listener to a property
func add(listener: AudioUnitPropertyListener, toProperty property: AudioUnitPropertyID) {
do {
try addPropertyListener(listener: listener, toProperty: property)
} catch {
AKLog("Error Adding Property Listener")
}
}
/// Remove a listener from a property
func remove(listener: AudioUnitPropertyListener, fromProperty property: AudioUnitPropertyID) {
do {
try removePropertyListener(listener: listener, fromProperty: property)
} catch {
AKLog("Error Removing Property Listener")
}
}
}
// MARK: - AudioUnit callbacks
/// Listener to properties in an audio unit
public struct AudioUnitPropertyListener {
public typealias AudioUnitPropertyListenerCallback = (
_ audioUnit: AudioUnit,
_ property: AudioUnitPropertyID) -> Void
let proc: AudioUnitPropertyListenerProc
let procInput: UnsafeMutablePointer<AudioUnitPropertyListenerCallback>
/// Initialize the listener with a callback
public init(callback: @escaping AudioUnitPropertyListenerCallback) {
self.proc = { (inRefCon, inUnit, inID, inScope, inElement) in
// UnsafeMutablePointer<Callback>(inRefCon).memory(audioUnit: inUnit, property: inID)
inRefCon.assumingMemoryBound(to: AudioUnitPropertyListenerCallback.self).pointee(inUnit, inID)
}
self.procInput = UnsafeMutablePointer<AudioUnitPropertyListenerCallback>.allocate(
capacity: MemoryLayout<AudioUnitPropertyListenerCallback>.stride
)
self.procInput.initialize(to: callback)
}
}
// MARK: - AudioUnit function wrappers
/// Extension for getting and setting properties
public extension AudioUnit {
/// Get property information
func getPropertyInfo(propertyID: AudioUnitPropertyID) throws -> (dataSize: UInt32, writable: Bool) {
var dataSize: UInt32 = 0
var writable: DarwinBoolean = false
try AudioUnitGetPropertyInfo(self, propertyID, kAudioUnitScope_Global, 0, &dataSize, &writable).check()
return (dataSize: dataSize, writable: writable.boolValue)
}
/// Get property
func getProperty<T>(propertyID: AudioUnitPropertyID, dataSize: UInt32) throws -> T {
var dataSize = dataSize
var data = UnsafeMutablePointer<T>.allocate(capacity: Int(dataSize))
defer {
data.deallocate(capacity: Int(dataSize))
}
try AudioUnitGetProperty(self, propertyID, kAudioUnitScope_Global, 0, data, &dataSize).check()
return data.pointee
}
/// Set a property
func setProperty<T>(propertyID: AudioUnitPropertyID, dataSize: UInt32, data: T) throws {
var data = data
try AudioFileSetProperty(self, propertyID, dataSize, &data).check()
}
internal func addPropertyListener(listener: AudioUnitPropertyListener,
toProperty propertyID: AudioUnitPropertyID) throws {
try AudioUnitAddPropertyListener(self, propertyID, listener.proc, listener.procInput).check()
}
internal func removePropertyListener(listener: AudioUnitPropertyListener,
fromProperty propertyID: AudioUnitPropertyID) throws {
try AudioUnitRemovePropertyListenerWithUserData(self, propertyID, listener.proc, listener.procInput).check()
}
}
// MARK: - AudioUnit function validation
/// Extension to add a check function
public extension OSStatus {
/// Check for and throw an error
func check() throws {
if self != noErr {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(self), userInfo: nil)
}
}
}
| mit | 6382ad5bd0e6171e9ec47953a6e85cd7 | 32.194245 | 116 | 0.683138 | 5.075908 | false | false | false | false |
saagarjha/iina | iina/PlaybackHistory.swift | 3 | 1894 | //
// PlaybackHistory.swift
// iina
//
// Created by lhc on 28/4/2017.
// Copyright © 2017 lhc. All rights reserved.
//
import Cocoa
fileprivate let KeyUrl = "IINAPHUrl"
fileprivate let KeyName = "IINAPHNme"
fileprivate let KeyMpvMd5 = "IINAPHMpvmd5"
fileprivate let KeyPlayed = "IINAPHPlayed"
fileprivate let KeyAddedDate = "IINAPHDate"
fileprivate let KeyDuration = "IINAPHDuration"
class PlaybackHistory: NSObject, NSCoding {
var url: URL
var name: String
var mpvMd5: String
var played: Bool
var addedDate: Date
var duration: VideoTime
var mpvProgress: VideoTime?
required init?(coder aDecoder: NSCoder) {
guard
let url = (aDecoder.decodeObject(forKey: KeyUrl) as? URL),
let name = (aDecoder.decodeObject(forKey: KeyName) as? String),
let md5 = (aDecoder.decodeObject(forKey: KeyMpvMd5) as? String),
let date = (aDecoder.decodeObject(forKey: KeyAddedDate) as? Date)
else {
return nil
}
let played = aDecoder.decodeBool(forKey: KeyPlayed)
let duration = aDecoder.decodeDouble(forKey: KeyDuration)
self.url = url
self.name = name
self.mpvMd5 = md5
self.played = played
self.addedDate = date
self.duration = VideoTime(duration)
self.mpvProgress = Utility.playbackProgressFromWatchLater(mpvMd5)
}
init(url: URL, duration: Double, name: String? = nil) {
self.url = url
self.name = name ?? url.lastPathComponent
self.mpvMd5 = Utility.mpvWatchLaterMd5(url.path)
self.played = true
self.addedDate = Date()
self.duration = VideoTime(duration)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(url, forKey: KeyUrl)
aCoder.encode(name, forKey: KeyName)
aCoder.encode(mpvMd5, forKey: KeyMpvMd5)
aCoder.encode(played, forKey: KeyPlayed)
aCoder.encode(addedDate, forKey: KeyAddedDate)
aCoder.encode(duration.second, forKey: KeyDuration)
}
}
| gpl-3.0 | ed672ea0bf3ed8b7943be46734c1ebb2 | 25.661972 | 69 | 0.704702 | 3.605714 | false | false | false | false |
alvarozizou/Noticias-Leganes-iOS | NoticiasLeganes/Data/ViewModel.swift | 1 | 1343 | //
// ViewModel.swift
// NoticiasLeganes
//
// Created by Alvaro Blazquez Montero on 3/10/17.
// Copyright © 2017 Alvaro Blazquez Montero. All rights reserved.
//
import UIKit
class ViewModel<T>: NSObject {
private var apiService : DataManager
private weak var viewDelegate : ListViewModelDelegate?
private var data = [T]()
private var mappingData: (Any?) -> [T]
init(apiService: DataManager, viewDelegate: ListViewModelDelegate, mappingData: @escaping (Any?) -> [T]) {
self.apiService = apiService
self.viewDelegate = viewDelegate
self.mappingData = mappingData
}
func reloadData() {
//Poner lo de fatalError
guard let _viewDelegate = self.viewDelegate else {
fatalError("ViewModel without view delegate")
}
apiService.getData(completionHandler: {response, error in
if error == nil {
self.data = self.mappingData(response)
_viewDelegate.itemsDidChange()
} else {
_viewDelegate.itemsError()
}
})
}
var count: Int {
return data.count
}
func itemAtIndex(_ index: Int) -> T? {
return data.count > index ? data[index] : nil
}
func getData() -> [T] {
return data
}
}
| mit | c1d97a130556b98af00069446f8bd536 | 25.313725 | 110 | 0.584948 | 4.580205 | false | false | false | false |
MatthiasU/TimeKeeper | TimeKeeper/Util/NSDateTimeDifferenceExtension.swift | 1 | 1264 | //
// NSDateTimeDifferenceExtension.swift
// TimeKeeper
//
// Created by Matthias Uttendorfer on 11/06/16.
// Copyright © 2016 Matthias Uttendorfer. All rights reserved.
//
import Foundation
// MARK: Time Difference Algorithm
extension Date {
static func timeDifference(_ start: Date, end: Date) -> Time {
let calendar = Calendar.current
let dateComponents = calendar.components([.minute, .hour], from: start, to: end, options: .wrapComponents)
return Time(hours: dateComponents.hour!, minutes: dateComponents.minute!)
}
static func currentDayTime(_ hours: Int , minutes: Int) -> Date? {
if hours > 24 {
return nil
}
if minutes > 60 {
return nil
}
let calendar = Calendar.current
let midnight = calendar.startOfDay(for: Date())
let convertedMinutesToSeconds = minutes * 60
let convertedHoursToSeconds = hours * 3600
let secondsToAdd = Double(convertedHoursToSeconds + convertedMinutesToSeconds)
let currentTimeDate = midnight.addingTimeInterval(secondsToAdd)
return currentTimeDate
}
static func currentDayTime(_ time: Time) -> Date? {
return Date.currentDayTime(time.hours, minutes: time.minutes)
}
}
| gpl-3.0 | 981d967010113c253bd54f1aeb792140 | 22.830189 | 110 | 0.669834 | 4.400697 | false | false | false | false |
shiguredo/sora-ios-sdk | Sora/DataChannel.swift | 1 | 9956 | import Compression
import Foundation
import WebRTC
import zlib
// Apple が提供する圧縮を扱う API は zlib のヘッダーとチェックサムをサポートしていないため、当該処理を実装する必要があった
// https://developer.apple.com/documentation/accelerate/compressing_and_decompressing_data_with_buffer_compression
//
// TODO: iOS 12 のサポートが不要になれば、 Compression Framework の関数を、 NSData の compressed(using), decompressed(using:) に書き換えることができる
// それに伴い、処理に必要なバッファーのサイズを指定する必要もなくなる
private enum ZLibUtil {
static func zip(_ input: Data) -> Data? {
if input.isEmpty {
return nil
}
// TODO: 毎回確保するには大きいので、 stream を利用して圧縮する API、もしくは NSData の compressed(using:) を使用することを検討する
// 2021年10月時点では、 DataChannel の最大メッセージサイズは 262,144 バイトだが、これを拡張する RFC が提案されている
// https://sora-doc.shiguredo.jp/DATA_CHANNEL_SIGNALING#48cff8
// https://www.rfc-editor.org/rfc/rfc8260.html
let bufferSize = 262_144
let destinationBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
defer {
destinationBuffer.deallocate()
}
var sourceBuffer = [UInt8](input)
let size = compression_encode_buffer(destinationBuffer, bufferSize,
&sourceBuffer, sourceBuffer.count,
nil,
COMPRESSION_ZLIB)
if size == 0 {
return nil
}
var zipped = Data(capacity: size + 6) // ヘッダー: 2バイト, チェックサム: 4バイト
zipped.append(contentsOf: [0x78, 0x5E]) // ヘッダーを追加
zipped.append(destinationBuffer, count: size)
let checksum = input.withUnsafeBytes { (p: UnsafeRawBufferPointer) -> UInt32 in
let bytef = p.baseAddress!.assumingMemoryBound(to: Bytef.self)
return UInt32(adler32(1, bytef, UInt32(input.count)))
}
zipped.append(UInt8(checksum >> 24 & 0xFF))
zipped.append(UInt8(checksum >> 16 & 0xFF))
zipped.append(UInt8(checksum >> 8 & 0xFF))
zipped.append(UInt8(checksum & 0xFF))
return zipped
}
static func unzip(_ input: Data) -> Data? {
if input.isEmpty {
return nil
}
// TODO: zip と同様に、stream を利用して解凍する API、もしくは NSData の decompressed(using:) を使用することを検討する
let bufferSize = 262_144
let destinationBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
var sourceBuffer = [UInt8](input)
// header を削除
sourceBuffer.removeFirst(2)
// checksum も削除
let checksum = Data(sourceBuffer.suffix(4))
sourceBuffer.removeLast(4)
let size = compression_decode_buffer(destinationBuffer, bufferSize,
&sourceBuffer, sourceBuffer.count,
nil,
COMPRESSION_ZLIB)
if size == 0 {
return nil
}
let data = Data(bytesNoCopy: destinationBuffer, count: size, deallocator: .free)
let calculatedChecksum = data.withUnsafeBytes { (p: UnsafeRawBufferPointer) -> Data in
let bytef = p.baseAddress!.assumingMemoryBound(to: Bytef.self)
var result = UInt32(adler32(1, bytef, UInt32(data.count))).bigEndian
return Data(bytes: &result, count: MemoryLayout<UInt32>.size)
}
// checksum の検証が成功したら data を返す
return checksum == calculatedChecksum ? data : nil
}
}
extension RTCDataChannelState: CustomStringConvertible {
public var description: String {
switch self {
case .connecting:
return "connecting"
case .open:
return "open"
case .closing:
return "closing"
case .closed:
return "closed"
@unknown default:
return "unknown"
}
}
}
class BasicDataChannelDelegate: NSObject, RTCDataChannelDelegate {
let compress: Bool
weak var peerChannel: PeerChannel?
weak var mediaChannel: MediaChannel?
init(compress: Bool, mediaChannel: MediaChannel?, peerChannel: PeerChannel?) {
self.compress = compress
self.mediaChannel = mediaChannel
self.peerChannel = peerChannel
}
func dataChannelDidChangeState(_ dataChannel: RTCDataChannel) {
Logger.debug(type: .dataChannel, message: "\(#function): label => \(dataChannel.label), state => \(dataChannel.readyState)")
if dataChannel.readyState == .closed {
if let peerChannel = peerChannel {
// DataChannel が切断されたタイミングで PeerChannel を切断する
// PeerChannel -> DataChannel の順に切断されるパターンも存在するが、
// PeerChannel.disconnect(error:reason:) 側で排他処理が実装されているため問題ない
peerChannel.disconnect(error: nil, reason: DisconnectReason.dataChannelClosed)
}
}
}
func dataChannel(_ dataChannel: RTCDataChannel, didChangeBufferedAmount amount: UInt64) {
Logger.debug(type: .dataChannel, message: "\(#function): label => \(dataChannel.label), amount => \(amount)")
}
func dataChannel(_ dataChannel: RTCDataChannel, didReceiveMessageWith buffer: RTCDataBuffer) {
Logger.debug(type: .dataChannel, message: "\(#function): label => \(dataChannel.label)")
guard let peerChannel = peerChannel else {
Logger.error(type: .dataChannel, message: "peerChannel is unavailable")
return
}
guard let dc = peerChannel.dataChannels[dataChannel.label] else {
Logger.error(type: .dataChannel, message: "DataChannel for label: \(dataChannel.label) is unavailable")
return
}
guard let data = dc.compress ? ZLibUtil.unzip(buffer.data) : buffer.data else {
Logger.error(type: .dataChannel, message: "failed to decompress data channel message")
return
}
if let message = String(data: data, encoding: .utf8) {
Logger.info(type: .dataChannel, message: "received data channel message: \(String(describing: message))")
}
// Sora から送られてきたメッセージ
if !dataChannel.label.starts(with: "#") {
switch dataChannel.label {
case "stats":
peerChannel.nativeChannel?.statistics {
// NOTE: stats の型を Signaling.swift に定義していない
let reports = Statistics(contentsOf: $0).jsonObject
let json: [String: Any] = ["type": "stats",
"reports": reports]
var data: Data?
do {
data = try JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted])
} catch {
Logger.error(type: .dataChannel, message: "failed to encode stats data to json")
}
if let data = data {
let ok = dc.send(data)
if !ok {
Logger.error(type: .dataChannel, message: "failed to send stats data over DataChannel")
}
}
}
case "signaling", "push", "notify":
switch Signaling.decode(data) {
case let .success(signaling):
peerChannel.handleSignalingOverDataChannel(signaling)
case let .failure(error):
Logger.error(type: .dataChannel,
message: "decode failed (\(error.localizedDescription)) => ")
}
case "e2ee":
Logger.error(type: .dataChannel, message: "NOT IMPLEMENTED: label => \(dataChannel.label)")
default:
Logger.error(type: .dataChannel, message: "unknown data channel label: \(dataChannel.label)")
}
}
if let mediaChannel = mediaChannel, let handler = mediaChannel.handlers.onDataChannelMessage {
handler(mediaChannel, dataChannel.label, data)
}
}
}
class DataChannel {
let native: RTCDataChannel
let delegate: BasicDataChannelDelegate
init(dataChannel: RTCDataChannel, compress: Bool, mediaChannel: MediaChannel?, peerChannel: PeerChannel?) {
Logger.info(type: .dataChannel, message: "initialize DataChannel: label => \(dataChannel.label), compress => \(compress)")
native = dataChannel
delegate = BasicDataChannelDelegate(compress: compress, mediaChannel: mediaChannel, peerChannel: peerChannel)
native.delegate = delegate
}
var label: String {
native.label
}
var compress: Bool {
delegate.compress
}
var readyState: RTCDataChannelState {
native.readyState
}
func send(_ data: Data) -> Bool {
Logger.debug(type: .dataChannel, message: "\(String(describing: type(of: self))):\(#function): label => \(label), data => \(data.base64EncodedString())")
guard let data = compress ? ZLibUtil.zip(data) : data else {
Logger.error(type: .dataChannel, message: "failed to compress message")
return false
}
return native.sendData(RTCDataBuffer(data: data, isBinary: true))
}
}
| apache-2.0 | 3aedfac56c9a50ecdddf08b99c93067e | 38.228814 | 161 | 0.592785 | 4.553861 | false | false | false | false |
stephencelis/SQLite.swift | Sources/SQLite/Core/Value.swift | 1 | 3372 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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.
//
/// - Warning: `Binding` is a protocol that SQLite.swift uses internally to
/// directly map SQLite types to Swift types.
///
/// Do not conform custom types to the Binding protocol. See the `Value`
/// protocol, instead.
public protocol Binding {}
public protocol Number: Binding {}
public protocol Value: Expressible { // extensions cannot have inheritance clauses
associatedtype ValueType = Self
associatedtype Datatype: Binding
static var declaredDatatype: String { get }
static func fromDatatypeValue(_ datatypeValue: Datatype) -> ValueType
var datatypeValue: Datatype { get }
}
extension Double: Number, Value {
public static let declaredDatatype = "REAL"
public static func fromDatatypeValue(_ datatypeValue: Double) -> Double {
datatypeValue
}
public var datatypeValue: Double {
self
}
}
extension Int64: Number, Value {
public static let declaredDatatype = "INTEGER"
public static func fromDatatypeValue(_ datatypeValue: Int64) -> Int64 {
datatypeValue
}
public var datatypeValue: Int64 {
self
}
}
extension String: Binding, Value {
public static let declaredDatatype = "TEXT"
public static func fromDatatypeValue(_ datatypeValue: String) -> String {
datatypeValue
}
public var datatypeValue: String {
self
}
}
extension Blob: Binding, Value {
public static let declaredDatatype = "BLOB"
public static func fromDatatypeValue(_ datatypeValue: Blob) -> Blob {
datatypeValue
}
public var datatypeValue: Blob {
self
}
}
// MARK: -
extension Bool: Binding, Value {
public static var declaredDatatype = Int64.declaredDatatype
public static func fromDatatypeValue(_ datatypeValue: Int64) -> Bool {
datatypeValue != 0
}
public var datatypeValue: Int64 {
self ? 1 : 0
}
}
extension Int: Number, Value {
public static var declaredDatatype = Int64.declaredDatatype
public static func fromDatatypeValue(_ datatypeValue: Int64) -> Int {
Int(datatypeValue)
}
public var datatypeValue: Int64 {
Int64(self)
}
}
| mit | d6067d7918188e8ddc9974b4e1660721 | 24.537879 | 82 | 0.701572 | 4.754584 | false | false | false | false |
jjatie/Charts | Source/Charts/Charts/ChartViewBase.swift | 1 | 22893 | //
// ChartViewBase.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
// Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880
import CoreGraphics
import Foundation
#if !os(OSX)
import UIKit
#endif
public protocol ChartViewDelegate: AnyObject {
/// Called when a value has been selected inside the chart.
///
/// - Parameters:
/// - entry: The selected Entry.
/// - highlight: The corresponding highlight object that contains information about the highlighted position such as dataSetIndex etc.
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight)
/// Called when a user stops panning between values on the chart
func chartViewDidEndPanning(_ chartView: ChartViewBase)
// Called when nothing has been selected or an "un-select" has been made.
func chartValueNothingSelected(_ chartView: ChartViewBase)
// Callbacks when the chart is scaled / zoomed via pinch zoom gesture.
func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat)
// Callbacks when the chart is moved / translated via drag gesture.
func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat)
// Callbacks when Animator stops animating
func chartView(_ chartView: ChartViewBase, animatorDidStop animator: Animator)
}
open class ChartViewBase: NSUIView {
// MARK: - Properties
/// The default IValueFormatter that has been determined by the chart considering the provided minimum and maximum values.
internal lazy var defaultValueFormatter: ValueFormatter = DefaultValueFormatter(decimals: 0)
/// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied
open var data: ChartData? {
didSet {
offsetsCalculated = false
guard let data = data else { return }
// calculate how many digits are needed
setupDefaultFormatter(min: data.yRange.min, max: data.yRange.max)
for set in data where set.valueFormatter is DefaultValueFormatter {
set.valueFormatter = defaultValueFormatter
}
// let the chart know there is new data
notifyDataSetChanged()
}
}
/// If set to true, chart continues to scroll after touch up
public var isDragDecelerationEnabled = true
/// The object representing the labels on the x-axis
public internal(set) lazy var xAxis = XAxis()
/// The `Description` object of the chart.
public lazy var chartDescription = Description()
/// The legend object containing all data associated with the legend
open internal(set) lazy var legend = Legend()
/// delegate to receive chart events
open weak var delegate: ChartViewDelegate?
/// text that is displayed when the chart is empty
open var noDataText = "No chart data available."
/// Font to be used for the no data text.
open var noDataFont = NSUIFont.systemFont(ofSize: 12)
/// color of the no data text
open var noDataTextColor: NSUIColor = .labelOrBlack
/// alignment of the no data text
open var noDataTextAlignment: TextAlignment = .left
/// The renderer object responsible for rendering / drawing the Legend.
open lazy var legendRenderer = LegendRenderer(viewPortHandler: viewPortHandler, legend: legend)
/// object responsible for rendering the data
open var renderer: DataRenderer?
open var highlighter: Highlighter?
/// The ViewPortHandler of the chart that is responsible for the
/// content area of the chart and its offsets and dimensions.
open internal(set) lazy var viewPortHandler = ViewPortHandler(width: bounds.size.width, height: bounds.size.height)
/// The animator responsible for animating chart values.
lazy var chartAnimator: Animator = {
let animator = Animator()
animator.delegate = self
return animator
}()
/// flag that indicates if offsets calculation has already been done or not
private var offsetsCalculated = false
/// The array of currently highlighted values. This might an empty if nothing is highlighted.
open internal(set) var highlighted = [Highlight]()
/// `true` if drawing the marker is enabled when tapping on values
/// (use the `marker` property to specify a marker)
open var drawMarkers = true
/// - Returns: `true` if drawing the marker is enabled when tapping on values
/// (use the `marker` property to specify a marker)
open var isDrawMarkersEnabled: Bool { return drawMarkers }
/// The marker that is displayed when a value is clicked on the chart
open var marker: Marker?
/// An extra offset to be appended to the viewport's top
open var extraTopOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's right
open var extraRightOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's bottom
open var extraBottomOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's left
open var extraLeftOffset: CGFloat = 0.0
open func setExtraOffsets(left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) {
extraLeftOffset = left
extraTopOffset = top
extraRightOffset = right
extraBottomOffset = bottom
}
// MARK: - Initializers
override public init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
deinit {
removeObserver(self, forKeyPath: "bounds")
removeObserver(self, forKeyPath: "frame")
}
internal func initialize() {
#if os(iOS)
backgroundColor = .clear
#endif
addObserver(self, forKeyPath: "bounds", options: .new, context: nil)
addObserver(self, forKeyPath: "frame", options: .new, context: nil)
}
// MARK: - ChartViewBase
/// Lets the chart know its underlying data has changed and should perform all necessary recalculations.
/// It is crucial that this method is called everytime data is changed dynamically. Not calling this method can lead to crashes or unexpected behaviour.
open func notifyDataSetChanged() {
fatalError("notifyDataSetChanged() cannot be called on ChartViewBase")
}
/// Calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position
internal func calculateOffsets() {
fatalError("calculateOffsets() cannot be called on ChartViewBase")
}
/// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter
internal func setupDefaultFormatter(min: Double, max: Double) {
// check if a custom formatter is set or not
var reference = 0.0
if let data = data, data.entryCount >= 2 {
reference = abs(max - min)
} else {
reference = Swift.max(abs(min), abs(max))
}
if let formatter = defaultValueFormatter as? DefaultValueFormatter {
// setup the formatter with a new number of digits
let digits = reference.decimalPlaces
formatter.decimals = digits
}
}
override open func draw(_: CGRect) {
guard let context = NSUIGraphicsGetCurrentContext() else { return }
if data === nil, !noDataText.isEmpty {
context.saveGState()
defer { context.restoreGState() }
let paragraphStyle = MutableParagraphStyle.default.mutableCopy() as! MutableParagraphStyle
paragraphStyle.minimumLineHeight = noDataFont.lineHeight
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = noDataTextAlignment
context.drawMultilineText(noDataText,
at: CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0),
constrainedTo: bounds.size,
anchor: CGPoint(x: 0.5, y: 0.5),
angleRadians: 0.0,
attributes: [.font: noDataFont,
.foregroundColor: noDataTextColor,
.paragraphStyle: paragraphStyle])
return
}
if !offsetsCalculated {
calculateOffsets()
offsetsCalculated = true
}
}
/// Draws the description text in the bottom right corner of the chart (per default)
internal func drawDescription(in context: CGContext) {
let description = chartDescription
// check if description should be drawn
guard
description.isEnabled,
let descriptionText = description.text,
!descriptionText.isEmpty
else { return }
let position = description.position ?? CGPoint(x: bounds.width - viewPortHandler.offsetRight - description.xOffset,
y: bounds.height - viewPortHandler.offsetBottom - description.yOffset - description.font.lineHeight)
let attrs: [NSAttributedString.Key: Any] = [
.font: description.font,
.foregroundColor: description.textColor,
]
context.drawText(descriptionText,
at: position,
align: description.textAlign,
attributes: attrs)
}
// MARK: - Accessibility
override open func accessibilityChildren() -> [Any]? {
return renderer?.accessibleChartElements
}
// MARK: - Highlighting
/// Set this to false to prevent values from being highlighted by tap gesture.
/// Values can still be highlighted via drag or programmatically.
/// **default**: true
public var isHighLightPerTapEnabled: Bool = true
/// Checks if the highlight array is null, has a length of zero or if the first object is null.
///
/// - Returns: `true` if there are values to highlight, `false` ifthere are no values to highlight.
public final var valuesToHighlight: Bool {
!highlighted.isEmpty
}
/// Highlights the values at the given indices in the given DataSets. Provide
/// null or an empty array to undo all highlighting.
/// This should be used to programmatically highlight values.
/// This method *will not* call the delegate.
public final func highlightValues(_ highs: [Highlight]?) {
// set the indices to highlight
highlighted = highs ?? []
lastHighlighted = highlighted.first
// redraw the chart
setNeedsDisplay()
}
/// Highlights the value at the given x-value and y-value in the given DataSet.
/// Provide -1 as the dataSetIndex to undo all highlighting.
///
/// - Parameters:
/// - x: The x-value to highlight
/// - y: The y-value to highlight. Supply `NaN` for "any"
/// - dataSetIndex: The dataset index to search in
/// - dataIndex: The data index to search in (only used in CombinedChartView currently)
/// - callDelegate: Should the delegate be called for this change
public final func highlightValue(x: Double, y: Double = .nan, dataSetIndex: Int, dataIndex: Int = -1, callDelegate: Bool = true)
{
guard let data = data else {
Swift.print("Value not highlighted because data is nil")
return
}
if data.indices.contains(dataSetIndex) {
highlightValue(Highlight(x: x, y: y, dataSetIndex: dataSetIndex, dataIndex: dataIndex), callDelegate: callDelegate)
} else {
highlightValue(nil, callDelegate: callDelegate)
}
}
/// Highlights the value selected by touch gesture.
public final func highlightValue(_ highlight: Highlight?, callDelegate: Bool = false) {
var high = highlight
guard
let h = high,
let entry = data?.entry(for: h)
else {
high = nil
highlighted.removeAll(keepingCapacity: false)
if callDelegate {
delegate?.chartValueNothingSelected(self)
}
return
}
// set the indices to highlight
highlighted = [h]
if callDelegate {
// notify the listener
delegate?.chartValueSelected(self, entry: entry, highlight: h)
}
// redraw the chart
setNeedsDisplay()
}
/// - Returns: The Highlight object (contains x-index and DataSet index) of the
/// selected value at the given touch point inside the Line-, Scatter-, or
/// CandleStick-Chart.
open func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight? {
guard data != nil else {
Swift.print("Can't select by touch. No data set.")
return nil
}
return highlighter?.getHighlight(x: pt.x, y: pt.y)
}
/// The last value that was highlighted via touch.
open var lastHighlighted: Highlight?
// MARK: - Markers
/// draws all MarkerViews on the highlighted positions
func drawMarkers(context: CGContext) {
// if there is no marker view or drawing marker is disabled
guard let marker = marker,
isDrawMarkersEnabled,
valuesToHighlight
else { return }
for highlight in highlighted {
guard let set = data?[highlight.dataSetIndex],
let e = data?.entry(for: highlight),
let entryIndex = set.firstIndex(of: e),
entryIndex <= Int(Double(set.count) * chartAnimator.phaseX)
else { continue }
let pos = getMarkerPosition(highlight: highlight)
// check bounds
guard viewPortHandler.isInBounds(x: pos.x, y: pos.y) else { continue }
// callbacks to update the content
marker.refreshContent(entry: e, highlight: highlight)
// draw the marker
marker.draw(context: context, point: pos)
}
}
/// - Returns: The actual position in pixels of the MarkerView for the given Entry in the given DataSet.
public func getMarkerPosition(highlight: Highlight) -> CGPoint {
CGPoint(x: highlight.drawX, y: highlight.drawY)
}
// MARK: - Animation
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - yAxisDuration: duration for animating the y axis
/// - easingX: an easing function for the animation on the x axis
/// - easingY: an easing function for the animation on the y axis
public final func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?)
{
chartAnimator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - yAxisDuration: duration for animating the y axis
/// - easingOptionX: the easing function for the animation on the x axis
/// - easingOptionY: the easing function for the animation on the y axis
public final func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption)
{
chartAnimator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - yAxisDuration: duration for animating the y axis
/// - easing: an easing function for the animation
public final func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?)
{
chartAnimator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - yAxisDuration: duration for animating the y axis
/// - easingOption: the easing function for the animation
public final func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOption: ChartEasingOption = .easeInOutSine)
{
chartAnimator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - easing: an easing function for the animation
public final func animate(xAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) {
chartAnimator.animate(xAxisDuration: xAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - easingOption: the easing function for the animation
public final func animate(xAxisDuration: TimeInterval, easingOption: ChartEasingOption = .easeInOutSine) {
chartAnimator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - yAxisDuration: duration for animating the y axis
/// - easing: an easing function for the animation
public final func animate(yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) {
chartAnimator.animate(yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - yAxisDuration: duration for animating the y axis
/// - easingOption: the easing function for the animation
public final func animate(yAxisDuration: TimeInterval, easingOption: ChartEasingOption = .easeInOutSine) {
chartAnimator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption)
}
// MARK: - Accessors
/// The center of the chart taking offsets under consideration. (returns the center of the content rectangle)
public final var centerOffsets: CGPoint {
viewPortHandler.contentCenter
}
/// The rectangle that defines the borders of the chart-value surface (into which the actual values are drawn).
public final var contentRect: CGRect {
viewPortHandler.contentRect
}
private var _viewportJobs = [ViewPortJob]()
override open func observeValue(forKeyPath keyPath: String?, of _: Any?, change _: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer?)
{
if keyPath == "bounds" || keyPath == "frame" {
let bounds = self.bounds
if bounds.size.width != viewPortHandler.chartWidth ||
bounds.size.height != viewPortHandler.chartHeight
{
viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
// This may cause the chart view to mutate properties affecting the view port -- lets do this
// before we try to run any pending jobs on the view port itself
notifyDataSetChanged()
// Finish any pending viewport changes
while !_viewportJobs.isEmpty {
let job = _viewportJobs.remove(at: 0)
job.doJob()
}
}
}
}
public final func addViewportJob(_ job: ViewPortJob) {
if viewPortHandler.hasChartDimens {
job.doJob()
} else {
_viewportJobs.append(job)
}
}
public final func removeViewportJob(_ job: ViewPortJob) {
if let index = _viewportJobs.firstIndex(where: { $0 === job }) {
_viewportJobs.remove(at: index)
}
}
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
public final var dragDecelerationFrictionCoef: CGFloat {
get { _dragDecelerationFrictionCoef }
set { _dragDecelerationFrictionCoef = newValue.clamped(to: 0...0.999) }
}
private var _dragDecelerationFrictionCoef: CGFloat = 0.9
/// The maximum distance in screen pixels away from an entry causing it to highlight.
/// **default**: 500.0
public final var maxHighlightDistance: CGFloat = 500.0
}
// MARK: - AnimatorDelegate
extension ChartViewBase: AnimatorDelegate {
public final func animatorUpdated(_: Animator) {
setNeedsDisplay()
}
public final func animatorStopped(_ chartAnimator: Animator) {
delegate?.chartView(self, animatorDidStop: chartAnimator)
}
}
| apache-2.0 | e5f1a4111ba57adbda8d0f6127a335e0 | 39.734875 | 183 | 0.655353 | 5.247078 | false | false | false | false |
frc5431/2016StrongholdAll | FrcScoutingApp-IOS/5431 Scouting Application FRC/FRCDataModel.swift | 2 | 3521 | //
// FRCDataModel.swift
// 5431 Scouting Application FRC
//
// Created by learner on 2/5/16.
// Copyright © 2016 Titian Robotics. All rights reserved.
//
import UIKit
class FRCTeams {
// Team Bio Data
let TeamName : String
let TeamNumber : String
let TeamType : String
let RobotType : String
let TeamBIo : String
// Team Performace Data
let PortcullsScore : String
let PortcullsSpeed : String
let RampartScore : String
let RampartSpeed : String
let RockWallScore : String
let RockWallSpeed : String
let RoughTerrainScore : String
let RoughTerrainSpeed : String
let SallyPortScore : String
let SallyPortSpeed : String
let ChevalDeFrise : String
let DrawbridgeScore : String
let DrawbridgeSpeed : String
let LowBarScore : String
let LowBarSpeed : String
let MoatScore : String
let MoatSpeed : String
// Game Fied Stats
let DefensivePushing : String
let ClimbingTower : String
let BoulderPickup : String
let ChallengedTowers : String
// Auto Task Statistics
let BoulderStart : String
let DefenseReached : String
let CrossedDefense : String
let LowGoalScore : String
let LowGoalFails : String
let HighGoalScore : String
let HighGoalFails : String
// initalizer
init( TeamName: String, TeamNumber: String, TeamType: String, RobotType: String, TeamBio: String, PortcullsScore: String, PortcullsSpeed: String, RampartScore: String, RampartSpeed: String, RockWallScore: String, RockWallSpeed: String, RoughTerrainScore: String, RoughTerrainSpeed: String, SallyPortScore: String, SallyPortSpeed: String, ChevalDeFrise: String, DrawbridgeScore: String, DrawbridgeSpeed: String, LowBarScore: String, LowBarSpeed: String, MoatScore: String, MoatSpeed: String, DefensivePushing: String, ClimbingTower: String, BoulderPickup: String, ChallengedTowers: String, BoulderStart: String, DefenseReached: String, CrossedDefense: String, LowGoalScore: String, LowGoalFails: String, HighGoalScore: String, HighGoalFails: String) {
self.TeamName = TeamName
self.TeamNumber = TeamNumber
self.TeamType = TeamType
self.RobotType = RobotType
self.TeamBIo = TeamBio
self.PortcullsScore = PortcullsScore
self.PortcullsSpeed = PortcullsSpeed
self.RampartScore = RampartScore
self.RampartSpeed = RampartSpeed
self.RockWallScore = RockWallScore
self.RockWallSpeed = RockWallSpeed
self.RoughTerrainScore = RoughTerrainScore
self.RoughTerrainSpeed = RoughTerrainSpeed
self.SallyPortScore = SallyPortScore
self.SallyPortSpeed = SallyPortSpeed
self.ChevalDeFrise = ChevalDeFrise
self.DrawbridgeScore = DrawbridgeScore
self.DrawbridgeSpeed = DrawbridgeSpeed
self.LowBarScore = LowBarScore
self.LowBarSpeed = LowBarSpeed
self.MoatScore = MoatScore
self.MoatSpeed = MoatSpeed
self.DefensivePushing = DefensivePushing
self.ClimbingTower = ClimbingTower
self.BoulderPickup = BoulderPickup
self.ChallengedTowers = ChallengedTowers
self.BoulderStart = BoulderStart
self.DefenseReached = DefenseReached
self.CrossedDefense = CrossedDefense
self.LowGoalScore = LowGoalScore
self.LowGoalFails = LowGoalFails
self.HighGoalScore = HighGoalScore
self.HighGoalFails = HighGoalFails
}
} | gpl-3.0 | 013a260b0be3e45993006c53acb052d2 | 34.928571 | 754 | 0.70625 | 4.536082 | false | false | false | false |
superk589/DereGuide | DereGuide/Toolbox/BirthdayNotification/BirthdayNotificationViewController.swift | 2 | 9716 | //
// BirthdayNotificationViewController.swift
// DereGuide
//
// Created by zzk on 16/8/13.
// Copyright © 2016 zzk. All rights reserved.
//
import UIKit
import UserNotifications
class BirthdayNotificationViewController: BaseTableViewController {
let sectionTitles = [NSLocalizedString("今天", comment: "生日提醒页面"), NSLocalizedString("明天", comment: "生日提醒页面"), NSLocalizedString("七天内", comment: "生日提醒页面"), NSLocalizedString("一个月内", comment: "生日提醒页面")]
let ranges: [CountableClosedRange<Int>] = [0...0, 1...1, 2...6, 7...30]
private struct Row {
var title: String
var charas: [CGSSChar]
}
private struct StaticRow {
var title: String
var detail: String?
var hasDisclosure: Bool
var accessoryView: UIView?
var selector: Selector?
var detailTextLabelColor: UIColor?
}
private var rows = [Row]()
private var staticRows = [StaticRow]()
override func viewDidLoad() {
super.viewDidLoad()
prepareStaticCellData()
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableView.automaticDimension
tableView.tableFooterView = UIView()
tableView.cellLayoutMarginsFollowReadableWidth = true
tableView.register(BirthdayNotificationTableViewCell.self, forCellReuseIdentifier: "BirthdayNotificationCell")
NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: .updateEnd, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(reloadSettings), name: UIApplication.didBecomeActiveNotification, object: nil)
reloadData()
popoverPresentationController?.delegate = self
}
private func prepareChars() {
rows.removeAll()
let bc = BirthdayCenter.default
for i in 0...3 {
let charas = bc.getRecent(ranges[i].lowerBound, endDays: ranges[i].upperBound)
if charas.count > 0 {
rows.append(Row(title: sectionTitles[i], charas: charas))
}
}
}
private var isSystemNotificationSettingOn: Bool {
let settings = DispatchSemaphore.sync { (closure) in
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: closure)
}
switch settings?.authorizationStatus {
case .some(.authorized):
return true
default:
return false
}
}
private var isBirthdayNotificationOn: Bool {
return UserDefaults.standard.value(forKey: "BirthdayNotice") as? Bool ?? false
}
private var birthdayNotificationTimeZone: String {
return UserDefaults.standard.value(forKey: "BirthdayTimeZone") as? String ?? "Asia/Tokyo"
}
private func prepareStaticCellData() {
staticRows.append(StaticRow(title: NSLocalizedString("系统通知设置", comment: "生日提醒页面"), detail: isSystemNotificationSettingOn ? NSLocalizedString("已开启", comment: "生日提醒页面") : NSLocalizedString("未开启", comment: "生日提醒页面"), hasDisclosure: true, accessoryView: nil, selector: #selector(gotoSystemNotificationSettings), detailTextLabelColor: nil))
let `switch` = UISwitch.init(frame: CGRect.zero)
`switch`.isOn = isBirthdayNotificationOn
`switch`.addTarget(self, action: #selector(valueChanged), for: .valueChanged)
staticRows.append(StaticRow(title: NSLocalizedString("开启生日通知提醒", comment: "生日提醒页面"), detail: nil, hasDisclosure: false, accessoryView: `switch`, selector: nil, detailTextLabelColor: nil))
staticRows.append(StaticRow(title: NSLocalizedString("时区", comment: "生日提醒页面"), detail: birthdayNotificationTimeZone, hasDisclosure: false, accessoryView: nil, selector: #selector(selectTimeZone), detailTextLabelColor: .parade))
}
@objc func valueChanged(_ sw: UISwitch) {
UserDefaults.standard.setValue(sw.isOn, forKey: "BirthdayNotice")
rescheduleBirthdayNotifications()
reloadData()
}
@objc func gotoSystemNotificationSettings() {
if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
@objc func selectTimeZone() {
if let cell = tableView.cellForRow(at: IndexPath(row: 2, section: 0)) {
let alvc = UIAlertController.init(title: NSLocalizedString("选择提醒时区", comment: "生日提醒页面"), message: nil, preferredStyle: .actionSheet)
alvc.popoverPresentationController?.sourceView = cell.detailTextLabel
alvc.popoverPresentationController?.sourceRect = CGRect(x: cell.detailTextLabel!.fwidth / 2, y: cell.detailTextLabel!.fheight, width: 0, height: 0)
alvc.addAction(UIAlertAction.init(title: "System", style: .default, handler: { [weak self] (a) in
UserDefaults.standard.setValue("System", forKey: "BirthdayTimeZone")
self?.rescheduleBirthdayNotifications()
self?.reloadSettings()
self?.reloadData()
}))
alvc.addAction(UIAlertAction.init(title: "Asia/Tokyo", style: .default, handler: { [weak self] (a) in
UserDefaults.standard.setValue("Asia/Tokyo", forKey: "BirthdayTimeZone")
self?.rescheduleBirthdayNotifications()
self?.reloadSettings()
self?.reloadData()
}))
alvc.addAction(UIAlertAction.init(title: NSLocalizedString("取消", comment: "生日提醒页面"), style: .cancel, handler: nil))
self.present(alvc, animated: true, completion: nil)
}
}
func rescheduleBirthdayNotifications() {
if UserDefaults.standard.shouldPostBirthdayNotice {
(UIApplication.shared.delegate as! AppDelegate).registerUserNotification()
BirthdayCenter.default.scheduleNotifications()
} else {
BirthdayCenter.default.removeBirthdayNotifications()
}
}
@objc func reloadData() {
prepareChars()
tableView.reloadData()
}
@objc func reloadSettings() {
staticRows[0].detail = isSystemNotificationSettingOn ? NSLocalizedString("已开启", comment: "生日提醒页面") : NSLocalizedString("未开启", comment: "生日提醒页面")
staticRows[2].detail = birthdayNotificationTimeZone
tableView.reloadRows(at: [IndexPath(row: 0, section: 0), IndexPath(row: 2, section: 0)], with: .none)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return rows.count + staticRows.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0..<staticRows.count:
var cell = tableView.dequeueReusableCell(withIdentifier: "BirthdayNotificationSettingCell")
if cell == nil {
cell = UITableViewCell(style: .value1, reuseIdentifier: "BirthdayNotificationSettingCell")
}
let row = staticRows[indexPath.row]
cell?.textLabel?.text = row.title
cell?.detailTextLabel?.text = row.detail
cell?.accessoryType = row.hasDisclosure ? .disclosureIndicator : .none
cell?.accessoryView = row.accessoryView
cell?.selectionStyle = .none
cell?.detailTextLabel?.textColor = row.detailTextLabelColor ?? .gray
return cell!
default:
let cell = tableView.dequeueReusableCell(withIdentifier: "BirthdayNotificationCell", for: indexPath) as! BirthdayNotificationTableViewCell
cell.setup(with: rows[indexPath.row - 3].charas, title: rows[indexPath.row - 3].title)
cell.delegate = self
return cell
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0..<staticRows.count:
let row = staticRows[indexPath.row]
if let selector = row.selector {
self.perform(selector)
}
default:
break
}
}
}
extension BirthdayNotificationViewController: BirthdayNotificationTableViewCellDelegate {
func charIconClick(_ icon: CGSSCharaIconView) {
let vc = CharaDetailViewController()
vc.chara = CGSSDAO.shared.findCharById(icon.charaID!)
self.navigationController?.pushViewController(vc, animated: true)
}
}
extension BirthdayNotificationViewController: UIPopoverPresentationControllerDelegate {
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
staticRows[0].detail = isSystemNotificationSettingOn ? NSLocalizedString("已开启", comment: "生日提醒页面") : NSLocalizedString("未开启", comment: "生日提醒页面")
tableView.reloadRows(at: [IndexPath.init(row: 0, section: 0)], with: .none)
}
}
| mit | f80993a28ec5525eb9e67e31ce36b035 | 41.282511 | 343 | 0.655107 | 5.175082 | false | false | false | false |
onevcat/Kingfisher | Sources/SwiftUI/KFImage.swift | 3 | 4158 | //
// KFImage.swift
// Kingfisher
//
// Created by onevcat on 2019/06/26.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if canImport(SwiftUI) && canImport(Combine)
import SwiftUI
import Combine
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public struct KFImage: KFImageProtocol {
public var context: Context<Image>
public init(context: Context<Image>) {
self.context = context
}
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension Image: KFImageHoldingView {
public typealias RenderingView = Image
public static func created(from image: KFCrossPlatformImage?, context: KFImage.Context<Self>) -> Image {
Image(crossPlatformImage: image)
}
}
// MARK: - Image compatibility.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension KFImage {
public func resizable(
capInsets: EdgeInsets = EdgeInsets(),
resizingMode: Image.ResizingMode = .stretch) -> KFImage
{
configure { $0.resizable(capInsets: capInsets, resizingMode: resizingMode) }
}
public func renderingMode(_ renderingMode: Image.TemplateRenderingMode?) -> KFImage {
configure { $0.renderingMode(renderingMode) }
}
public func interpolation(_ interpolation: Image.Interpolation) -> KFImage {
configure { $0.interpolation(interpolation) }
}
public func antialiased(_ isAntialiased: Bool) -> KFImage {
configure { $0.antialiased(isAntialiased) }
}
/// Starts the loading process of `self` immediately.
///
/// By default, a `KFImage` will not load its source until the `onAppear` is called. This is a lazily loading
/// behavior and provides better performance. However, when you refresh the view, the lazy loading also causes a
/// flickering since the loading does not happen immediately. Call this method if you want to start the load at once
/// could help avoiding the flickering, with some performance trade-off.
///
/// - Deprecated: This is not necessary anymore since `@StateObject` is used for holding the image data.
/// It does nothing now and please just remove it.
///
/// - Returns: The `Self` value with changes applied.
@available(*, deprecated, message: "This is not necessary anymore since `@StateObject` is used. It does nothing now and please just remove it.")
public func loadImmediately(_ start: Bool = true) -> KFImage {
return self
}
}
#if DEBUG
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
struct KFImage_Previews: PreviewProvider {
static var previews: some View {
Group {
KFImage.url(URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/logo.png")!)
.onSuccess { r in
print(r)
}
.placeholder { p in
ProgressView(p)
}
.resizable()
.aspectRatio(contentMode: .fit)
.padding()
}
}
}
#endif
#endif
| mit | f9f30f3e40d9adcadb501c31e376e1ae | 38.226415 | 148 | 0.675806 | 4.33125 | false | false | false | false |
ilhanadiyaman/firefox-ios | Client/Frontend/Reader/ReaderModeStyleViewController.swift | 3 | 15372 | /* 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 UIKit
private struct ReaderModeStyleViewControllerUX {
static let RowHeight = 50
static let Width = 270
static let Height = 4 * RowHeight
static let FontTypeRowBackground = UIColor(rgb: 0xfbfbfb)
static let FontTypeTitleSelectedColor = UIColor(rgb: 0x333333)
static let FontTypeTitleNormalColor = UIColor.lightGrayColor() // TODO THis needs to be 44% of 0x333333
static let FontSizeRowBackground = UIColor(rgb: 0xf4f4f4)
static let FontSizeLabelColor = UIColor(rgb: 0x333333)
static let FontSizeButtonTextColorEnabled = UIColor(rgb: 0x333333)
static let FontSizeButtonTextColorDisabled = UIColor.lightGrayColor() // TODO THis needs to be 44% of 0x333333
static let ThemeRowBackgroundColor = UIColor.whiteColor()
static let ThemeTitleColorLight = UIColor(rgb: 0x333333)
static let ThemeTitleColorDark = UIColor.whiteColor()
static let ThemeTitleColorSepia = UIColor(rgb: 0x333333)
static let ThemeBackgroundColorLight = UIColor.whiteColor()
static let ThemeBackgroundColorDark = UIColor(rgb: 0x333333)
static let ThemeBackgroundColorSepia = UIColor(rgb: 0xF0E6DC)
static let BrightnessRowBackground = UIColor(rgb: 0xf4f4f4)
static let BrightnessSliderTintColor = UIColor(rgb: 0xe66000)
static let BrightnessSliderWidth = 140
static let BrightnessIconOffset = 10
}
// MARK: -
protocol ReaderModeStyleViewControllerDelegate {
func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle)
}
// MARK: -
class ReaderModeStyleViewController: UIViewController {
var delegate: ReaderModeStyleViewControllerDelegate?
var readerModeStyle: ReaderModeStyle = DefaultReaderModeStyle
private var fontTypeButtons: [FontTypeButton]!
private var fontSizeLabel: FontSizeLabel!
private var fontSizeButtons: [FontSizeButton]!
private var themeButtons: [ThemeButton]!
override func viewDidLoad() {
// Our preferred content size has a fixed width and height based on the rows + padding
preferredContentSize = CGSize(width: ReaderModeStyleViewControllerUX.Width, height: ReaderModeStyleViewControllerUX.Height)
popoverPresentationController?.backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
// Font type row
let fontTypeRow = UIView()
view.addSubview(fontTypeRow)
fontTypeRow.backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
fontTypeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.view)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
fontTypeButtons = [
FontTypeButton(fontType: ReaderModeFontType.SansSerif),
FontTypeButton(fontType: ReaderModeFontType.Serif)
]
setupButtons(fontTypeButtons, inRow: fontTypeRow, action: "SELchangeFontType:")
// Font size row
let fontSizeRow = UIView()
view.addSubview(fontSizeRow)
fontSizeRow.backgroundColor = ReaderModeStyleViewControllerUX.FontSizeRowBackground
fontSizeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(fontTypeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
fontSizeLabel = FontSizeLabel()
fontSizeRow.addSubview(fontSizeLabel)
fontSizeLabel.snp_makeConstraints { (make) -> () in
make.center.equalTo(fontSizeRow)
return
}
fontSizeButtons = [
FontSizeButton(fontSizeAction: FontSizeAction.Smaller),
FontSizeButton(fontSizeAction: FontSizeAction.Bigger)
]
setupButtons(fontSizeButtons, inRow: fontSizeRow, action: "SELchangeFontSize:")
// Theme row
let themeRow = UIView()
view.addSubview(themeRow)
themeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(fontSizeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
themeButtons = [
ThemeButton(theme: ReaderModeTheme.Light),
ThemeButton(theme: ReaderModeTheme.Dark),
ThemeButton(theme: ReaderModeTheme.Sepia)
]
setupButtons(themeButtons, inRow: themeRow, action: "SELchangeTheme:")
// Brightness row
let brightnessRow = UIView()
view.addSubview(brightnessRow)
brightnessRow.backgroundColor = ReaderModeStyleViewControllerUX.BrightnessRowBackground
brightnessRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(themeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
let slider = UISlider()
brightnessRow.addSubview(slider)
slider.accessibilityLabel = NSLocalizedString("Brightness", comment: "Accessibility label for brightness adjustment slider in Reader Mode display settings")
slider.tintColor = ReaderModeStyleViewControllerUX.BrightnessSliderTintColor
slider.addTarget(self, action: "SELchangeBrightness:", forControlEvents: UIControlEvents.ValueChanged)
slider.snp_makeConstraints { make in
make.center.equalTo(brightnessRow.center)
make.width.equalTo(ReaderModeStyleViewControllerUX.BrightnessSliderWidth)
}
let brightnessMinImageView = UIImageView(image: UIImage(named: "brightnessMin"))
brightnessRow.addSubview(brightnessMinImageView)
brightnessMinImageView.snp_makeConstraints { (make) -> () in
make.centerY.equalTo(slider)
make.right.equalTo(slider.snp_left).offset(-ReaderModeStyleViewControllerUX.BrightnessIconOffset)
}
let brightnessMaxImageView = UIImageView(image: UIImage(named: "brightnessMax"))
brightnessRow.addSubview(brightnessMaxImageView)
brightnessMaxImageView.snp_makeConstraints { (make) -> () in
make.centerY.equalTo(slider)
make.left.equalTo(slider.snp_right).offset(ReaderModeStyleViewControllerUX.BrightnessIconOffset)
}
selectFontType(readerModeStyle.fontType)
updateFontSizeButtons()
selectTheme(readerModeStyle.theme)
slider.value = Float(UIScreen.mainScreen().brightness)
}
/// Setup constraints for a row of buttons. Left to right. They are all given the same width.
private func setupButtons(buttons: [UIButton], inRow row: UIView, action: Selector) {
for (idx, button) in buttons.enumerate() {
row.addSubview(button)
button.addTarget(self, action: action, forControlEvents: UIControlEvents.TouchUpInside)
button.snp_makeConstraints { make in
make.top.equalTo(row.snp_top)
if idx == 0 {
make.left.equalTo(row.snp_left)
} else {
make.left.equalTo(buttons[idx - 1].snp_right)
}
make.bottom.equalTo(row.snp_bottom)
make.width.equalTo(self.preferredContentSize.width / CGFloat(buttons.count))
}
}
}
func SELchangeFontType(button: FontTypeButton) {
selectFontType(button.fontType)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func selectFontType(fontType: ReaderModeFontType) {
readerModeStyle.fontType = fontType
for button in fontTypeButtons {
button.selected = (button.fontType == fontType)
}
for button in themeButtons {
button.fontType = fontType
}
fontSizeLabel.fontType = fontType
}
func SELchangeFontSize(button: FontSizeButton) {
switch button.fontSizeAction {
case .Smaller:
readerModeStyle.fontSize = readerModeStyle.fontSize.smaller()
case .Bigger:
readerModeStyle.fontSize = readerModeStyle.fontSize.bigger()
}
updateFontSizeButtons()
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func updateFontSizeButtons() {
for button in fontSizeButtons {
switch button.fontSizeAction {
case .Bigger:
button.enabled = !readerModeStyle.fontSize.isLargest()
break
case .Smaller:
button.enabled = !readerModeStyle.fontSize.isSmallest()
break
}
}
}
func SELchangeTheme(button: ThemeButton) {
selectTheme(button.theme)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func selectTheme(theme: ReaderModeTheme) {
readerModeStyle.theme = theme
}
func SELchangeBrightness(slider: UISlider) {
UIScreen.mainScreen().brightness = CGFloat(slider.value)
}
}
// MARK: -
class FontTypeButton: UIButton {
var fontType: ReaderModeFontType = .SansSerif
convenience init(fontType: ReaderModeFontType) {
self.init(frame: CGRectZero)
self.fontType = fontType
setTitleColor(ReaderModeStyleViewControllerUX.FontTypeTitleSelectedColor, forState: UIControlState.Selected)
setTitleColor(ReaderModeStyleViewControllerUX.FontTypeTitleNormalColor, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
accessibilityHint = NSLocalizedString("Changes font type.", comment: "Accessibility hint for the font type buttons in reader mode display settings")
switch fontType {
case .SansSerif:
setTitle(NSLocalizedString("Sans-serif", comment: "Font type setting in the reading view settings"), forState: UIControlState.Normal)
let f = UIFont(name: "FiraSans-Book", size: DynamicFontHelper.defaultHelper.ReaderStandardFontSize)
titleLabel?.font = f
case .Serif:
setTitle(NSLocalizedString("Serif", comment: "Font type setting in the reading view settings"), forState: UIControlState.Normal)
let f = UIFont(name: "Charis SIL", size: DynamicFontHelper.defaultHelper.ReaderStandardFontSize)
titleLabel?.font = f
}
}
}
// MARK: -
enum FontSizeAction {
case Smaller
case Bigger
}
class FontSizeButton: UIButton {
var fontSizeAction: FontSizeAction = .Bigger
convenience init(fontSizeAction: FontSizeAction) {
self.init(frame: CGRectZero)
self.fontSizeAction = fontSizeAction
setTitleColor(ReaderModeStyleViewControllerUX.FontSizeButtonTextColorEnabled, forState: UIControlState.Normal)
setTitleColor(ReaderModeStyleViewControllerUX.FontSizeButtonTextColorDisabled, forState: UIControlState.Disabled)
switch fontSizeAction {
case .Smaller:
let smallerFontLabel = NSLocalizedString("-", comment: "Button for smaller reader font size. Keep this extremely short! This is shown in the reader mode toolbar.")
let smallerFontAccessibilityLabel = NSLocalizedString("Decrease text size", comment: "Accessibility label for button decreasing font size in display settings of reader mode")
setTitle(smallerFontLabel, forState: .Normal)
accessibilityLabel = smallerFontAccessibilityLabel
case .Bigger:
let largerFontLabel = NSLocalizedString("+", comment: "Button for larger reader font size. Keep this extremely short! This is shown in the reader mode toolbar.")
let largerFontAccessibilityLabel = NSLocalizedString("Increase text size", comment: "Accessibility label for button increasing font size in display settings of reader mode")
setTitle(largerFontLabel, forState: .Normal)
accessibilityLabel = largerFontAccessibilityLabel
}
// TODO Does this need to change with the selected font type? Not sure if makes sense for just +/-
titleLabel?.font = UIFont(name: "FiraSans-Light", size: DynamicFontHelper.defaultHelper.ReaderBigFontSize)
}
}
// MARK: -
class FontSizeLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
let fontSizeLabel = NSLocalizedString("Aa", comment: "Button for reader mode font size. Keep this extremely short! This is shown in the reader mode toolbar.")
text = fontSizeLabel
isAccessibilityElement = false
}
required init?(coder aDecoder: NSCoder) {
// TODO
fatalError("init(coder:) has not been implemented")
}
var fontType: ReaderModeFontType = .SansSerif {
didSet {
switch fontType {
case .SansSerif:
font = UIFont(name: "FiraSans-Book", size: DynamicFontHelper.defaultHelper.ReaderBigFontSize)
case .Serif:
font = UIFont(name: "Charis SIL", size: DynamicFontHelper.defaultHelper.ReaderBigFontSize)
}
}
}
}
// MARK: -
class ThemeButton: UIButton {
var theme: ReaderModeTheme!
convenience init(theme: ReaderModeTheme) {
self.init(frame: CGRectZero)
self.theme = theme
setTitle(theme.rawValue, forState: UIControlState.Normal)
accessibilityHint = NSLocalizedString("Changes color theme.", comment: "Accessibility hint for the color theme setting buttons in reader mode display settings")
switch theme {
case .Light:
setTitle(NSLocalizedString("Light", comment: "Light theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorLight, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorLight
case .Dark:
setTitle(NSLocalizedString("Dark", comment: "Dark theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorDark, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorDark
case .Sepia:
setTitle(NSLocalizedString("Sepia", comment: "Sepia theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorSepia, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorSepia
}
}
var fontType: ReaderModeFontType = .SansSerif {
didSet {
switch fontType {
case .SansSerif:
titleLabel?.font = UIFont(name: "FiraSans-Book", size: DynamicFontHelper.defaultHelper.ReaderStandardFontSize)
case .Serif:
titleLabel?.font = UIFont(name: "Charis SIL", size: DynamicFontHelper.defaultHelper.ReaderStandardFontSize)
}
}
}
} | mpl-2.0 | b5fd0e09843ef157a64ba3718d9f86e9 | 40.548649 | 186 | 0.693078 | 5.515608 | false | false | false | false |
kevinsumios/KSiShuHui | Project/Controller/CategoryViewController.swift | 1 | 3229 | //
// CategoryViewController.swift
// Project
//
// Created by Kevin Sum on 10/7/2017.
// Copyright © 2017 Kevin iShuHui. All rights reserved.
//
import UIKit
class CategoryViewController: BaseTableController {
var categoryId = 0
override func loadView() {
super.loadView()
api = ApiHelper.Name.getBook
tableView.allowsSelectionDuringEditing = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tabBarController?.title = tabBarItem.title
tableView.reloadData()
}
override func loadData() {
parameter = ["ClassifyId":categoryId, "PageIndex":index]
super.loadData()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryId", for: indexPath) as! CategoryTableViewCell
if let book = data[indexPath.row].dictionary {
let title = book["Title"]?.string ?? ""
let author = book["Author"]?.string ?? ""
cell.title = "\(title) \(author)"
if let chapter = book["LastChapter"]?.dictionary?["Sort"]?.int {
cell.chapter = "第\(chapter)話"
}
cell.cover = book["FrontCover"]?.string
cell.subscribed = Subscription.isSubscribe(bookId: book["Id"]?.int16)
}
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
if let cell = tableView.cellForRow(at: indexPath) as? CategoryTableViewCell {
let title = cell.subscribed ? "退訂" : "訂閱"
let action = UITableViewRowAction(style: .default, title: title, handler: { (action, indexPath) in
if let bookId = self.data[indexPath.row].dictionary?["Id"]?.int16 {
Subscription.subscribe(bookId: bookId, YesOrNo: !cell.subscribed)
}
cell.subscribed = !cell.subscribed
tableView.setEditing(false, animated: true)
})
action.backgroundColor = cell.subscribed ? .red : .orange
return [action]
} else {
return []
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "bookChapterTable", let table = segue.destination as? BookChapterTableController {
if let selectedRow = tableView.indexPathForSelectedRow?.row {
let book = data[selectedRow].dictionary
table.cover = book?["FrontCover"]?.string
table.name = book?["Title"]?.string
table.author = book?["Author"]?.string
table.status = book?["SerializedState"]?.string
table.explain = book?["Explain"]?.string
table.id = book?["Id"]?.int16 ?? 0
}
}
}
}
| mit | a6358d54c27eff96463fb31d3a74abae | 36.395349 | 124 | 0.592662 | 5.032864 | false | false | false | false |
courteouselk/Transactions | Sources/WeakWrapper.swift | 1 | 556 | //
// WeakWrapper.swift
// Transactions
//
// Created by Anton Bronnikov on 23/03/2017.
// Copyright © 2017 Anton Bronnikov. All rights reserved.
//
import Foundation
struct WeakWrapper<Object: AnyObject> : Equatable, Hashable {
let hashValue: Int
private (set) weak var object: Object? = nil
init(_ object: Object) {
self.object = object
self.hashValue = ObjectIdentifier(object).hashValue
}
static func == (lhs: WeakWrapper, rhs: WeakWrapper) -> Bool {
return lhs.object === rhs.object
}
}
| mit | 782c19024fc67a647c71d1410e310935 | 20.346154 | 65 | 0.646847 | 4.111111 | false | false | false | false |
huangboju/GesturePassword | GesturePassword/Classes/Views/LockView.swift | 1 | 6636 | //
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
public protocol LockViewDelegate: class {
func lockViewDidTouchesEnd(_ lockView: LockView)
}
open class LockView: UIView {
open weak var delegate: LockViewDelegate?
open var lineColor: UIColor = LockCenter.lineHighlightColor {
didSet {
shapeLayer?.strokeColor = lineColor.cgColor
}
}
open var lineWarnColor: UIColor = LockCenter.lineWarnColor
open var lineWidth: CGFloat = LockCenter.lineWidth {
didSet {
shapeLayer?.lineWidth = lineWidth
}
}
open var itemDiameter: CGFloat = LockCenter.itemDiameter {
didSet {
relayoutLayers()
}
}
private var selectedItemViews: [LockItemLayer] = []
private var allItemLayers: [LockItemLayer] = []
private(set) var password = ""
private var shapeLayer: CAShapeLayer? {
return layer as? CAShapeLayer
}
private var mainPath = UIBezierPath()
private var interval: TimeInterval = 0
override open class var layerClass: AnyClass {
return CAShapeLayer.self
}
override init(frame: CGRect) {
super.init(frame: frame)
layoutLayers()
shapeLayer?.lineWidth = lineWidth
shapeLayer?.lineCap = CAShapeLayerLineCap.round
shapeLayer?.lineJoin = CAShapeLayerLineJoin.round
shapeLayer?.fillColor = UIColor.clear.cgColor
shapeLayer?.strokeColor = lineColor.cgColor
}
override open var intrinsicContentSize: CGSize {
let side = preferedSide
return CGSize(width: side, height: side)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func touchesBegan(_ touches: Set<UITouch>, with _: UIEvent?) {
processTouch(touches)
}
override open func touchesMoved(_ touches: Set<UITouch>, with _: UIEvent?) {
processTouch(touches)
}
override open func touchesEnded(_: Set<UITouch>, with _: UIEvent?) {
touchesEnd()
}
// 电话等打断触摸过程时,会调用这个方法。
override open func touchesCancelled(_: Set<UITouch>?, with _: UIEvent?) {
touchesEnd()
}
private func layoutLayers() {
let padding = self.padding
for i in 0 ..< 9 {
let lockItemLayer = LockItemLayer()
lockItemLayer.side = itemDiameter
lockItemLayer.index = i
let row = CGFloat(i % 3)
let col = CGFloat(i / 3)
lockItemLayer.origin = CGPoint(x: padding * row, y: padding * col)
allItemLayers.append(lockItemLayer)
layer.addSublayer(lockItemLayer)
}
}
private func relayoutLayers() {
let padding = self.padding
for (i, lockItemLayer) in allItemLayers.enumerated() {
lockItemLayer.side = itemDiameter
let row = CGFloat(i % 3)
let col = CGFloat(i / 3)
lockItemLayer.origin = CGPoint(x: padding * col, y: padding * row)
}
invalidateIntrinsicContentSize()
}
private var padding: CGFloat {
let count: CGFloat = 3
let margin = (UIScreen.main.bounds.width - itemDiameter * count) / (count + 1)
return itemDiameter + margin
}
private var preferedSide: CGFloat {
return allItemLayers.last?.frame.maxX ?? 0
}
private func drawLine() {
if selectedItemViews.isEmpty { return }
for (idx, itemView) in selectedItemViews.enumerated() {
let directPoint = itemView.position
if idx == 0 {
mainPath.move(to: directPoint)
} else {
mainPath.addLine(to: directPoint)
}
}
shapeLayer?.path = mainPath.cgPath
}
private func touchesEnd() {
delegate?.lockViewDidTouchesEnd(self)
delay(interval) {
self.reset()
}
}
private func processTouch(_ touches: Set<UITouch>) {
let location = touches.first!.location(in: self)
guard let itemView = itemView(with: location) else {
return
}
if selectedItemViews.contains(itemView) {
return
}
selectedItemViews.append(itemView)
password += itemView.index.description
calDirect()
itemView.turnHighlight()
drawLine()
}
private func calDirect() {
let count = selectedItemViews.count
guard selectedItemViews.count > 1 else {
return
}
let last_1_ItemView = selectedItemViews[count - 1]
let last_2_ItemView = selectedItemViews[count - 2]
let rect1 = last_1_ItemView.frame
let rect2 = last_2_ItemView.frame
let last_1_x = rect1.minX
let last_1_y = rect1.minY
let last_2_x = rect2.minX
let last_2_y = rect2.minY
if last_2_x == last_1_x && last_2_y > last_1_y {
last_2_ItemView.direction = .top
}
if last_2_y == last_1_y && last_2_x > last_1_x {
last_2_ItemView.direction = .left
}
if last_2_x == last_1_x && last_2_y < last_1_y {
last_2_ItemView.direction = .bottom
}
if last_2_y == last_1_y && last_2_x < last_1_x {
last_2_ItemView.direction = .right
}
if last_2_x > last_1_x && last_2_y > last_1_y {
last_2_ItemView.direction = .leftTop
}
if last_2_x < last_1_x && last_2_y > last_1_y {
last_2_ItemView.direction = .rightTop
}
if last_2_x > last_1_x && last_2_y < last_1_y {
last_2_ItemView.direction = .leftBottom
}
if last_2_x < last_1_x && last_2_y < last_1_y {
last_2_ItemView.direction = .rightBottom
}
}
private func itemView(with touchLocation: CGPoint) -> LockItemLayer? {
for subLayer in allItemLayers {
if !subLayer.frame.contains(touchLocation) {
continue
}
return subLayer
}
return nil
}
public func warn() {
interval = 1
selectedItemViews.forEach { $0.turnWarn() }
shapeLayer?.strokeColor = lineWarnColor.cgColor
}
public func reset() {
interval = 0
shapeLayer?.strokeColor = lineColor.cgColor
selectedItemViews.forEach { $0.reset() }
selectedItemViews.removeAll()
mainPath.removeAllPoints()
shapeLayer?.path = mainPath.cgPath
password = ""
drawLine()
}
}
| mit | 087c96317880ceb6175a47a08bcd30d3 | 27.799127 | 86 | 0.579378 | 4.471186 | false | false | false | false |
huonw/swift | test/SILGen/properties_swift4.swift | 1 | 7760 |
// RUN: %target-swift-emit-silgen -swift-version 4 -module-name properties -Xllvm -sil-full-demangle -parse-as-library %s | %FileCheck %s
var zero: Int = 0
protocol ForceAccessors {
var a: Int { get set }
}
struct DidSetWillSetTests: ForceAccessors {
static var defaultValue: DidSetWillSetTests {
return DidSetWillSetTests(a: 0)
}
var a: Int {
// CHECK-LABEL: sil private @$S10properties010DidSetWillC5TestsV1a{{[_0-9a-zA-Z]*}}vw
willSet(newA) {
// CHECK: bb0(%0 : $Int, %1 : $*DidSetWillSetTests):
a = zero // reassign, but don't infinite loop.
// CHECK: // function_ref properties.zero.unsafeMutableAddressor : Swift.Int
// CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$S10properties4zero{{[_0-9a-zA-Z]*}}vau
// CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer
// CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int
// CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]]
// CHECK-NEXT: end_access [[READ]] : $*Int
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] %1
// CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a
// CHECK-NEXT: assign [[ZERO]] to [[AADDR]]
var unrelatedValue = DidSetWillSetTests.defaultValue
// CHECK: [[BOX:%.*]] = alloc_box ${ var DidSetWillSetTests }, var, name "unrelatedValue"
// CHECK-NEXT: [[BOXADDR:%.*]] = project_box [[BOX]] : ${ var DidSetWillSetTests }, 0
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin DidSetWillSetTests.Type
// CHECK-NEXT: // function_ref static properties.DidSetWillSetTests.defaultValue.getter : properties.DidSetWillSetTests
// CHECK-NEXT: [[DEFAULTVALUE_FN:%.*]] = function_ref @$S10properties{{[_0-9a-zA-Z]*}}vgZ : $@convention(method) (@thin DidSetWillSetTests.Type) -> DidSetWillSetTests
// CHECK-NEXT: [[DEFAULTRESULT:%.*]] = apply [[DEFAULTVALUE_FN]]([[METATYPE]]) : $@convention(method) (@thin DidSetWillSetTests.Type) -> DidSetWillSetTests
// CHECK-NEXT: store [[DEFAULTRESULT]] to [trivial] [[BOXADDR]] : $*DidSetWillSetTests
// Access directly even when calling on another instance in order to maintain < Swift 5 behaviour.
unrelatedValue.a = zero
// CHECK-NEXT: // function_ref properties.zero.unsafeMutableAddressor : Swift.Int
// CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$S10properties4zero{{[_0-9a-zA-Z]*}}vau
// CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer
// CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int
// CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]]
// CHECK-NEXT: end_access [[READ]] : $*Int
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOXADDR]] : $*DidSetWillSetTests
// CHECK-NEXT: [[ELEMADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a
// CHECK-NEXT: assign [[ZERO]] to [[ELEMADDR]] : $*Int
// CHECK-NEXT: end_access [[WRITE]] : $*DidSetWillSetTests
}
// CHECK-LABEL: sil private @$S10properties010DidSetWillC5TestsV1a{{[_0-9a-zA-Z]*}}vW
didSet {
(self).a = zero // reassign, but don't infinite loop.
// CHECK: // function_ref properties.zero.unsafeMutableAddressor : Swift.Int
// CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$S10properties4zero{{[_0-9a-zA-Z]*}}vau
// CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer
// CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int
// CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]]
// CHECK-NEXT: end_access [[READ]] : $*Int
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] %1
// CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a
// CHECK-NEXT: assign [[ZERO]] to [[AADDR]]
var unrelatedValue = DidSetWillSetTests.defaultValue
// CHECK: [[BOX:%.*]] = alloc_box ${ var DidSetWillSetTests }, var, name "unrelatedValue"
// CHECK-NEXT: [[BOXADDR:%.*]] = project_box [[BOX]] : ${ var DidSetWillSetTests }, 0
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin DidSetWillSetTests.Type
// CHECK-NEXT: // function_ref static properties.DidSetWillSetTests.defaultValue.getter : properties.DidSetWillSetTests
// CHECK-NEXT: [[DEFAULTVALUE_FN:%.*]] = function_ref @$S10properties{{[_0-9a-zA-Z]*}}vgZ : $@convention(method) (@thin DidSetWillSetTests.Type) -> DidSetWillSetTests
// CHECK-NEXT: [[DEFAULTRESULT:%.*]] = apply [[DEFAULTVALUE_FN]]([[METATYPE]]) : $@convention(method) (@thin DidSetWillSetTests.Type) -> DidSetWillSetTests
// CHECK-NEXT: store [[DEFAULTRESULT]] to [trivial] [[BOXADDR]] : $*DidSetWillSetTests
// Access directly even when calling on another instance in order to maintain < Swift 5 behaviour.
unrelatedValue.a = zero
// CHECK-NEXT: // function_ref properties.zero.unsafeMutableAddressor : Swift.Int
// CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$S10properties4zero{{[_0-9a-zA-Z]*}}vau
// CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer
// CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int
// CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]]
// CHECK-NEXT: end_access [[READ]] : $*Int
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOXADDR]] : $*DidSetWillSetTests
// CHECK-NEXT: [[ELEMADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a
// CHECK-NEXT: assign [[ZERO]] to [[ELEMADDR]] : $*Int
// CHECK-NEXT: end_access [[WRITE]] : $*DidSetWillSetTests
var other = self
// CHECK: [[BOX:%.*]] = alloc_box ${ var DidSetWillSetTests }, var, name "other"
// CHECK-NEXT: [[BOXADDR:%.*]] = project_box [[BOX]] : ${ var DidSetWillSetTests }, 0
// CHECK-NEXT: [[READ_SELF:%.*]] = begin_access [read] [unknown] %1 : $*DidSetWillSetTests
// CHECK-NEXT: copy_addr [[READ_SELF]] to [initialization] [[BOXADDR]] : $*DidSetWillSetTests
// CHECK-NEXT: end_access [[READ_SELF]] : $*DidSetWillSetTests
other.a = zero
// CHECK-NEXT: // function_ref properties.zero.unsafeMutableAddressor : Swift.Int
// CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$S10properties4zero{{[_0-9a-zA-Z]*}}vau
// CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer
// CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int
// CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]]
// CHECK-NEXT: end_access [[READ]] : $*Int
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOXADDR]] : $*DidSetWillSetTests
// CHECK-NEXT: [[ELEMADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a
// CHECK-NEXT: assign [[ZERO]] to [[ELEMADDR]] : $*Int
// CHECK-NEXT: end_access [[WRITE]] : $*DidSetWillSetTests
}
}
}
| apache-2.0 | 22863f25d2500bcf82a32f8c911cc369 | 60.587302 | 172 | 0.616753 | 4.014485 | false | true | false | false |
lukevanin/OCRAI | CardScanner/AsyncOperation.swift | 1 | 1557 | //
// AsyncOperation.swift
// CardScanner
//
// Created by Luke Van In on 2017/02/09.
// Copyright © 2017 Luke Van In. All rights reserved.
//
import Foundation
class AsyncOperation: Operation, Cancellable {
typealias Completion = () -> Void
override var isConcurrent: Bool {
return true
}
override var isExecuting: Bool {
return self.internalExecuting
}
override var isFinished: Bool {
return self.internalFinished
}
private var internalExecuting = false {
willSet {
self.willChangeValue(forKey: "isExecuting")
}
didSet {
self.didChangeValue(forKey: "isExecuting")
}
}
private var internalFinished = false {
willSet {
self.willChangeValue(forKey: "isFinished")
}
didSet {
self.didChangeValue(forKey: "isFinished")
}
}
override func start() {
super.start()
guard !isCancelled else {
return
}
beginExecuting()
execute() {
self.finishExecuting()
}
}
open func execute(completion: @escaping Completion) {
completion()
}
private func beginExecuting() {
internalExecuting = true
}
private func finishExecuting() {
guard !isCancelled else {
// Operation cancelled
return
}
internalExecuting = false
internalFinished = true
}
}
| mit | d22dcfb7a0d9ba2efd326a68d954413d | 19.746667 | 57 | 0.54563 | 5.365517 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Cartography/Cartography/Context.swift | 6 | 1878 | //
// Context.swift
// Cartography
//
// Created by Robert Böhnke on 06/10/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
public typealias LayoutRelation = NSLayoutConstraint.Relation
#else
import AppKit
public typealias LayoutRelation = NSLayoutConstraint.Relation
#endif
public class Context {
internal var constraints: [Constraint] = []
internal func addConstraint(_ from: Property, to: Property? = nil, coefficients: Coefficients = Coefficients(), relation: LayoutRelation = .equal) -> NSLayoutConstraint {
if let fromItem = from.item as? View {
fromItem.translatesAutoresizingMaskIntoConstraints = false
}
let layoutConstraint = NSLayoutConstraint(item: from.item,
attribute: from.attribute,
relatedBy: relation,
toItem: to?.item,
attribute: to?.attribute ?? .notAnAttribute,
multiplier: CGFloat(coefficients.multiplier),
constant: CGFloat(coefficients.constant))
constraints.append(Constraint(layoutConstraint))
return layoutConstraint
}
internal func addConstraint(_ from: Compound, coefficients: [Coefficients]? = nil, to: Compound? = nil, relation: LayoutRelation = .equal) -> [NSLayoutConstraint] {
var results: [NSLayoutConstraint] = []
for i in 0..<from.properties.count {
let n: Coefficients = coefficients?[i] ?? Coefficients()
results.append(addConstraint(from.properties[i], to: to?.properties[i], coefficients: n, relation: relation))
}
return results
}
}
| mit | 16c904552cfb08a4f69d456e181c5264 | 35.784314 | 174 | 0.586354 | 5.469388 | false | false | false | false |
charmaex/favorite-movies | FavoriteMovies/MenuVC.swift | 1 | 3443 | //
// ViewController.swift
// FavoriteMovies
//
// Created by Jan Dammshäuser on 17.02.16.
// Copyright © 2016 Jan Dammshäuser. All rights reserved.
//
import UIKit
class MenuVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
setLogo()
CoreDataService.inst.fetchData()
tableView.delegate = self
tableView.dataSource = self
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MenuVC.openWebView(_:)), name: "imdbTapped", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MenuVC.reloadTableView), name: "reloadData", object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
func openWebView(notif: NSNotification) {
guard let info = notif.userInfo as? Dictionary <String, String>, let link = info["link"] else {
print("No link provided")
return
}
let view = ImdbVC(link: link)
presentViewController(view, animated: true, completion: nil)
}
func reloadTableView() {
tableView.reloadData()
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .Default, title: "Edit") { (UITableViewRowAction, indexPath: NSIndexPath) -> Void in
let movie = CoreDataService.inst.movies[indexPath.row]
self.performSegueWithIdentifier("AddVC", sender: movie)
}
let deleteAction = UITableViewRowAction(style: .Default, title: "Delete") { (UITableViewRowAction, indexPath: NSIndexPath) -> Void in
CoreDataService.inst.deleteData(indexPath.row)
}
editAction.backgroundColor = UIColor.grayColor()
deleteAction.backgroundColor = UIColor.darkGrayColor()
return [deleteAction, editAction]
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let movie = CoreDataService.inst.movies[indexPath.row]
let view = DetailVC(movie: movie)
presentViewController(view, animated: true, completion: nil)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return CoreDataService.inst.movies.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCellWithIdentifier("MovieCell") as? MovieCell else {
return MovieCell()
}
let movie = CoreDataService.inst.movies[indexPath.row]
cell.initializeCell(movie)
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let send = sender as? Movie where segue.identifier == "AddVC" {
if let addVC = segue.destinationViewController as? AddVC {
addVC.movie = send
}
}
}
}
| gpl-3.0 | f25ef2405fd825e25629552af7df9baf | 33.059406 | 141 | 0.644186 | 5.408805 | false | false | false | false |
flagoworld/romp | Romp/Shared/States/Editor/EditorStateObject.swift | 1 | 2105 | //
// EditorStateMap.swift
// Romp
//
// Created by Ryan Layne on 2/10/17.
// Copyright © 2017 Ryan Layne. All rights reserved.
//
import GameplayKit
class EditorStateObject: EditorState {
var mouseDownEvent = MouseEvent(action: .down, buttons: [], modifiers: [], location: CGPoint.zero)
override func mouseDownEvent(mouseEvent: MouseEvent) {
guard let editorScene = self.editorScene else { return }
mouseDownEvent = mouseEvent
if mouseEvent.modifiers.contains(.shift) {
if let entity = editorScene.getEntity(mouseEvent.location) {
if editorScene.isEntitySelected(entity) {
editorScene.deselectEntities([entity])
} else {
editorScene.selectEntity(entity: entity)
}
}
} else {
if !editorScene.grabSelectionHandle(mouseEvent.location) {
let entity = editorScene.getEntity(mouseEvent.location)
if entity == nil || !editorScene.isEntitySelected(entity!) {
editorScene.deselectEntities(editorScene.selectedEntities)
editorScene.selectEntity(mouseEvent.location)
}
}
}
super.mouseDownEvent(mouseEvent: mouseEvent)
}
override func mouseDragEvent(mouseEvent: MouseEvent) {
guard let editorScene = self.editorScene else { return }
if !editorScene.moveSelectionHandle(mouseEvent.location) {
editorScene.moveSelectedEntities(from: mouseDownEvent.location, to: mouseEvent.location)
}
}
override func mouseUpEvent(mouseEvent: MouseEvent) {
guard let editorScene = self.editorScene else { return }
editorScene.releaseSelectionHandle()
}
}
| mit | 51b33c38560af58d8240d7f7e0391bdd | 25.974359 | 102 | 0.537072 | 5.828255 | false | false | false | false |
n41l/OMChartView | Example/Tests/Tests.swift | 1 | 1178 | // https://github.com/Quick/Quick
import Quick
import Nimble
import OMChartView
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | 38f19d51a66f97ea825dedc1acfa66a4 | 22.44 | 63 | 0.364334 | 5.502347 | false | false | false | false |
willpowell8/UIDesignKit_iOS | UIDesignKit/Classes/Extensions/UILabel+UIDesign.swift | 1 | 2702 | //
// UILabel+UIDesign.swift
// Pods
//
// Created by Will Powell on 26/11/2016.
//
//
import Foundation
import SDWebImage
extension UILabel{
override open func updateDesign(type:String, data:[AnyHashable: Any]) {
super.updateDesign(type:type, data: data);
self.applyData(data: data, property: "textColor", targetType: .color, apply: { (value) in
guard let c = value as? UIColor else {
return
}
self.textColor = c
})
self.applyData(data: data, property: "font", targetType: .font, apply: {(value) in
guard let f = value as? UIFont else {
return
}
self.font = f
})
self.applyData(data: data, property: "adjustsFontSizeToFitWidth", targetType: .bool, apply: {(value) in
guard let a = value as? Bool else {
return
}
self.adjustsFontSizeToFitWidth = a
})
self.applyData(data: data, property: "textAlignment", targetType: .int) { (value) in
guard let i = value as? Int, var alignment = NSTextAlignment(rawValue: i) else {
return
}
if self.designLayout == true {
alignment = NSTextAlignment.designConvertAlignment(alignment, layout: UIDesign.layoutAlignment)
}
self.textAlignment = alignment
}
}
override open func getDesignProperties(data:[String:Any]) -> [String:Any]{
var dataReturn = super.getDesignProperties(data: data)
var alignment = self.textAlignment
if self.designLayout == true {
alignment = NSTextAlignment.designConvertAlignment(alignment, layout: UIDesign.layoutAlignment)
}
dataReturn["textAlignment"] = ["type":"INT", "value":alignment.rawValue]
if #available(iOS 13.0, *) {
let lightColor = colorForTrait(color: self.textColor, trait: .light)
let darkColor = colorForTrait(color: self.textColor, trait: .dark)
dataReturn["textColor"] = ["type":"COLOR", "value":lightColor?.toHexString()];
dataReturn["textColor-dark"] = ["type":"COLOR", "value":darkColor?.toHexString()];
}else{
dataReturn["textColor"] = ["type":"COLOR", "value":self.textColor.toHexString()]
}
dataReturn["font"] = ["type":"FONT", "value": font.toDesignString()]
dataReturn["adjustsFontSizeToFitWidth"] = ["type":"BOOL", "value": adjustsFontSizeToFitWidth ? 1 : 0]
return dataReturn;
}
override public func getDesignType() -> String{
return "LABEL";
}
}
| mit | ef5b4c34d7394d7e172b26295b662c09 | 37.056338 | 111 | 0.580681 | 4.642612 | false | false | false | false |
Azuritul/AZDropdownMenu | Example/AZDropdownMenu/ViewController.swift | 1 | 9197 | //
// ViewController.swift
// AZDropdownMenu
//
// Created by Chris Wu on 01/05/2016.
// Copyright (c) 2016 Chris Wu. All rights reserved.
//
import UIKit
import AZDropdownMenu
class ViewController: UIViewController {
var rightMenu: AZDropdownMenu?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.hidesBackButton = false
navigationController?.navigationBar.isTranslucent = false
view.backgroundColor = UIColor(red: 80/255, green: 70/255, blue: 66/255, alpha: 1.0)
title = "AZDropdownMenu"
/// Add DemoButton 1
let demoButton1 = buildButton("Demo 1")
demoButton1.addTarget(self, action: #selector(ViewController.onDemo1Tapped), for: .touchUpInside)
view.addSubview(demoButton1)
view.addConstraint(NSLayoutConstraint(item: demoButton1, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: demoButton1, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: -180))
/// Add DemoButton 2
let demoButton2 = buildButton("Demo 2")
demoButton2.addTarget(self, action: #selector(ViewController.onDemo2Tapped), for: .touchUpInside)
view.addSubview(demoButton2)
view.addConstraint(NSLayoutConstraint(item: demoButton2, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: demoButton2, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: -80))
}
func buildButton(_ title: String) -> UIButton {
let button = UIButton(type: .system)
button.backgroundColor = UIColor(red: 80/255, green: 70/255, blue: 66/255, alpha: 1.0)
button.setTitle(title, for: UIControlState())
button.layer.cornerRadius = 4.0
button.setTitleColor(UIColor(red: 233/255, green: 205/255, blue: 193/255, alpha: 1.0), for: UIControlState())
button.translatesAutoresizingMaskIntoConstraints = false
return button
}
@objc func onDemo1Tapped() {
let controller = DemoViewController1()
let nv = UINavigationController(rootViewController: controller)
nv.navigationBar.isTranslucent = false
nv.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black]
self.present(nv, animated: true, completion: nil)
}
@objc func onDemo2Tapped() {
let controller = DemoViewController2()
let nv = UINavigationController(rootViewController: controller)
nv.navigationBar.isTranslucent = false
nv.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black]
self.present(nv, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
/// Example controller that shows the use of menu with UIViewController
class DemoViewController1: UIViewController {
var rightMenu: AZDropdownMenu?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 80/255, green: 70/255, blue: 66/255, alpha: 1.0)
let cancelButton = UIBarButtonItem(image: UIImage(named: "cancel"), style: .plain, target: self, action: #selector(UIViewController.dismissFromController))
let rightButton = UIBarButtonItem(image: UIImage(named: "options"), style: .plain, target: self, action: #selector(DemoViewController1.showRightDropdown))
navigationItem.leftBarButtonItem = cancelButton
navigationItem.rightBarButtonItem = rightButton
title = "Demo 1"
rightMenu = buildDummyDefaultMenu()
}
@objc func showRightDropdown() {
if self.rightMenu?.isDescendant(of: self.view) == true {
self.rightMenu?.hideMenu()
} else {
self.rightMenu?.showMenuFromView(self.view)
}
}
}
/// Example that shows the use of menu with UITableViewController
class DemoViewController2: UIViewController, UITableViewDataSource, UITableViewDelegate {
var rightMenu: AZDropdownMenu?
var tableView: UITableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
title = "Demo 2"
view.backgroundColor = UIColor.white
let cancelButton = UIBarButtonItem(image: UIImage(named: "cancel"), style: .plain, target: self, action: #selector(UIViewController.dismissFromController))
let menuButton = UIBarButtonItem(image: UIImage(named: "options"), style: .plain, target: self, action: #selector(DemoViewController2.showRightDropdown))
tableView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
navigationItem.leftBarButtonItem = cancelButton
navigationItem.rightBarButtonItem = menuButton
rightMenu = buildDummyCustomMenu()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.tableView.dataSource = self
self.tableView.delegate = self
self.view.addSubview(self.tableView)
}
@objc
func showRightDropdown() {
if self.rightMenu?.isDescendant(of: self.view) == true {
self.rightMenu?.hideMenu()
} else {
self.rightMenu?.showMenuFromView(self.view)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 16
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cell") {
cell.textLabel?.text = "TestCell \(indexPath.row)"
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
let nextVC = UIViewController()
nextVC.view.backgroundColor = UIColor.white
nextVC.title = "VC \(indexPath.row)"
self.navigationController?.show(nextVC, sender: self)
}
}
// MARK: - Extension for holding custom methods
extension UIViewController {
/**
Create dummy menu with default settings
- returns: The dummy menu
*/
fileprivate func buildDummyDefaultMenu() -> AZDropdownMenu {
let leftTitles = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"]
let menu = AZDropdownMenu(titles: leftTitles)
menu.itemFontSize = 16.0
menu.itemFontName = "Helvetica"
menu.cellTapHandler = { [weak self] (indexPath: IndexPath) -> Void in
self?.pushNewViewController(leftTitles[indexPath.row])
}
return menu
}
/**
Create dummy menu with some custom configuration
- returns: The dummy menu
*/
fileprivate func buildDummyCustomMenu() -> AZDropdownMenu {
let dataSource = createDummyDatasource()
let menu = AZDropdownMenu(dataSource: dataSource )
menu.cellTapHandler = { [weak self] (indexPath: IndexPath) -> Void in
self?.pushNewViewController(dataSource[indexPath.row])
}
menu.itemHeight = 70
menu.itemFontSize = 14.0
menu.itemFontName = "Menlo-Bold"
menu.itemColor = UIColor.white
menu.itemFontColor = UIColor(red: 55/255, green: 11/255, blue: 17/255, alpha: 1.0)
menu.overlayColor = UIColor.black
menu.overlayAlpha = 0.3
menu.itemAlignment = .center
menu.itemImagePosition = .postfix
menu.menuSeparatorStyle = .none
menu.shouldDismissMenuOnDrag = true
return menu
}
fileprivate func pushNewViewController(_ title: String) {
let newController = UIViewController()
newController.title = title
newController.view.backgroundColor = UIColor.white
DispatchQueue.main.async(execute: {
self.show(newController, sender: self)
})
}
fileprivate func pushNewViewController(_ item: AZDropdownMenuItemData) {
self.pushNewViewController(item.title)
}
fileprivate func createDummyDatasource() -> [AZDropdownMenuItemData] {
var dataSource: [AZDropdownMenuItemData] = []
dataSource.append(AZDropdownMenuItemData(title:"Action With Icon 1", icon:UIImage(imageLiteralResourceName: "1_a")))
dataSource.append(AZDropdownMenuItemData(title:"Action With Icon 2", icon:UIImage(imageLiteralResourceName: "2_a")))
dataSource.append(AZDropdownMenuItemData(title:"Action With Icon 3", icon:UIImage(imageLiteralResourceName: "3_a")))
dataSource.append(AZDropdownMenuItemData(title:"Action With Icon 4", icon:UIImage(imageLiteralResourceName: "4_a")))
dataSource.append(AZDropdownMenuItemData(title:"Action With Icon 5", icon:UIImage(imageLiteralResourceName: "5_a")))
return dataSource
}
@objc func dismissFromController() {
self.dismiss(animated: true, completion: nil)
}
}
| mit | f1777e38306bf8624c07e1a20a77f135 | 39.515419 | 171 | 0.683049 | 4.782631 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/HCIDisconnectionComplete.swift | 1 | 1948 | //
// HCIDisconnectionComplete.swift
// Bluetooth
//
// Created by Carlos Duclos on 8/1/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// Disconnection Complete Event
///
/// The Disconnection Complete event occurs when a connection is terminated. The status parameter indicates if the disconnection was successful or not. The reason parameter indicates the reason for the disconnection if the disconnection was successful. If the disconnection was not successful, the value of the reason parameter can be ignored by the Host. For example, this can be the case if the Host has issued the Disconnect command and there was a parameter error, or the command was not presently allowed, or a Connection_Handle that didn’t correspond to a connection was given.
///
/// - Note: When a physical link fails, one Disconnection Complete event will be returned for each logical channel on the physical link with the corresponding Connection_Handle as a parameter.
@frozen
public struct HCIDisconnectionComplete: HCIEventParameter {
public static let event = HCIGeneralEvent.disconnectionComplete
public static let length: Int = 4
public let status: HCIStatus
/// Connection_Handle which was disconnected.
/// Range: 0x0000-0x0EFF (0x0F00 - 0x0FFF Reserved for future use)
public let handle: UInt16
/// Reason for disconnection.
public let error: HCIError
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
guard let status = HCIStatus(rawValue: data[0])
else { return nil }
let handle = UInt16(littleEndian: UInt16(bytes: (data[1], data[2])))
guard let error = HCIError(rawValue: data[3])
else { return nil }
self.status = status
self.handle = handle
self.error = error
}
}
| mit | aa640d365731f60e34d2cd117773ce45 | 37.9 | 583 | 0.690488 | 4.609005 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/HCILEReadSupportedStates.swift | 1 | 1524 | //
// HCILEReadSupportedStates.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/15/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
// MARK: - Method
public extension BluetoothHostControllerInterface {
/// LE Read Supported States
///
/// The LE_Read_Supported_States command reads the states and state combinations that the link layer supports.
func readSupportedStates(timeout: HCICommandTimeout = .default) async throws -> LowEnergyStateSet {
let returValue = try await deviceRequest(HCILEReadSupportedStates.self, timeout: timeout)
return returValue.state
}
}
// MARK: - Return parameter
/// LE Read Supported States
///
/// The LE_Read_Supported_States command reads the states and state combinations that the link layer supports.
@frozen
public struct HCILEReadSupportedStates: HCICommandReturnParameter {
public static let command = HCILowEnergyCommand.readSupportedStates //0x001C
public static let length: Int = 8
public let state: LowEnergyStateSet
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
let stateRawValue = UInt64(littleEndian: UInt64(bytes: (data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7])))
guard let state = LowEnergyStateSet(rawValue: stateRawValue)
else { return nil }
self.state = state
}
}
| mit | e05d16c6420c1fdfd197990c95a97e36 | 28.288462 | 137 | 0.666448 | 4.389049 | false | false | false | false |
Vostro162/VaporTelegram | Sources/App/TelegramService.swift | 1 | 41133 | //
// TelegramService.swift
// VaporTelegram
//
// Created by Marius Hartig on 09.05.17.
//
//
import Foundation
import Vapor
import HTTP
import Multipart
import FormData
class TelegramService {
let drop: Droplet
init(drop: Droplet) {
self.drop = drop
}
/*
*
* Create Tlegram File URL from a Path
*
*/
func url(filePath: String) throws -> URL {
guard
let token = drop.config["telegrambot", "token"]?.string,
let url = URL(string: "https://api.telegram.org/file/bot\(token)/\(filePath)")
else { throw TelegramServiceError.unknowError }
return url
}
/*
*
* Create URL String from a Methode
*
*/
fileprivate func uri(methodName: String) throws -> String {
guard let token = drop.config["telegrambot", "token"]?.string else { throw TelegramServiceError.unknowError }
return "https://api.telegram.org/bot\(token)/\(methodName)"
}
/*
*
* Send Sync Post Request
*
*/
fileprivate func sendPost(methodName: String, params: [String: Node]) throws -> Response {
let json = try JSON(node: params)
return try drop.client.post(
try self.uri(methodName: methodName),
headers: [
"Content-Type": "application/json"
],
body: Body(json)
)
}
/*
*
* Send Sync Put Request
*
*/
fileprivate func sendPut(methodName: String, params: [String: Node]) throws -> Response {
let json = try JSON(node: params)
return try drop.client.put(
try self.uri(methodName: methodName),
headers: [
"Content-Type": "application/json"
],
body: Body(json)
)
}
/*
*
* Send Sync File Request Multipart Form Data
* see https://tools.ietf.org/html/rfc2388
*
*/
fileprivate func sendFile(methodName: String, formData: [String: Field]) throws -> Response {
let request = try Request(
method: .post,
uri: try uri(methodName: methodName),
headers: [
"Content-Type": "multipart/form-data"
]
)
request.formData = formData
return try drop.client.respond(to: request)
}
/*
*
* Send Sync Get Request
*
*/
fileprivate func sendGet(methodName: String, params: [String: CustomStringConvertible]) throws -> Response {
return try drop.client.get(try uri(methodName: methodName), query: params)
}
/*
*
* Error Check
*
*/
fileprivate func checkForServerError(response: Response) throws -> JSON {
print(response)
guard
let json = response.json,
let isOk = json["ok"]?.bool
else { throw TelegramServiceError.unknowError }
guard
isOk == true,
let resultJSON = json["result"]
else {
if let code = json["error_code"]?.int, let description = json["description"]?.string {
throw TelegramServiceError.server(code: code, description: description)
}
throw TelegramServiceError.unknowError
}
return resultJSON
}
}
// MARK: - MethodsAble
extension TelegramService: MethodsAble {
//MARK: Send
func sendMessage(chatId: ChatId, text: String, disableWebPagePreview: Bool = false, disableNotification: Bool = false, parseMode: ParseMode? = nil, replyToMessageId: MessageId? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"text": text.makeNode(),
"disable_web_page_preview": disableWebPagePreview.makeNode(),
"disable_notification": disableNotification.makeNode()
]
if let parseMode = parseMode {
params["parse_mode"] = parseMode.rawValue.makeNode()
}
if let replyToMessageId = replyToMessageId {
params["reply_to_message_id"] = try replyToMessageId.makeNode()
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "sendMessage", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendPhoto(chatId: ChatId, photo: InputFile, fileName: String, disableNotification: Bool = false, caption: String? = nil, replyToMessageId: MessageId? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
let chatIdBody = try String(describing: chatId).makeBytes()
let chatIdField = Field(name: "chat_id", filename: nil, part: Part(headers: [:], body: chatIdBody))
let photoBody = try photo.makeBytes()
let photoField = Field(name: "photo", filename: fileName, part: Part(headers: [:], body: photoBody))
let disableNotificationBody = try String(describing: disableNotification).makeBytes()
let disableNotificationField = Field(name: "disable_notification", filename: nil, part: Part(headers: [:], body: disableNotificationBody))
var formData: [String: Field] = [
"chat_id": chatIdField,
"photo": photoField,
"disable_notification": disableNotificationField
]
if let caption = caption {
let captionBody = try caption.makeBytes()
formData["caption"] = Field(name: "caption", filename: nil, part: Part(headers: [:], body: captionBody))
}
if
let replyToMessageId = replyToMessageId
{
let replyToMessageIdBody = try String(describing: replyToMessageId).makeBytes()
formData["reply_to_message_id"] = Field(name: "reply_to_message_id", filename: nil, part: Part(headers: [:], body: replyToMessageIdBody))
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
let node = try replyMarkupNode.makeNode()
let json = try JSON(node: node)
let jsonBody = try json.makeBytes()
formData["reply_markup"] = Field(name: "reply_markup", filename: nil, part: Part(headers: [:], body: jsonBody))
}
let response = try sendFile(methodName: "sendPhoto", formData: formData)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendPhoto(chatId: ChatId, photo: URL, disableNotification: Bool = false, caption: String? = nil, replyToMessageId: MessageId? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"photo": photo.absoluteString.makeNode(),
"disable_notification": disableNotification.makeNode()
]
if let caption = caption {
params["caption"] = caption.makeNode()
}
if let replyToMessageId = replyToMessageId {
params["reply_to_message_id"] = try replyToMessageId.makeNode()
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "sendPhoto", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendAudio(chatId: ChatId, audio: InputFile, fileName: String, disableNotification: Bool = false, caption: String? = nil, duration: Int? = nil, performer: String? = nil, title: String? = nil, replyToMessageId: MessageId? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
let chatIdBody = try String(describing: chatId).makeBytes()
let chatIdField = Field(name: "chat_id", filename: nil, part: Part(headers: [:], body: chatIdBody))
let audioBody = try audio.makeBytes()
let audioField = Field(name: "audio", filename: fileName, part: Part(headers: [:], body: audioBody))
let disableNotificationBody = try String(describing: disableNotification).makeBytes()
let disableNotificationField = Field(name: "disable_notification", filename: nil, part: Part(headers: [:], body: disableNotificationBody))
var formData: [String: Field] = [
"chat_id": chatIdField,
"audio": audioField,
"disable_notification": disableNotificationField
]
if let caption = caption {
let captionBody = try caption.makeBytes()
formData["caption"] = Field(name: "caption", filename: nil, part: Part(headers: [:], body: captionBody))
}
if let performer = performer {
let performerBody = try performer.makeBytes()
formData["performer"] = Field(name: "performer", filename: nil, part: Part(headers: [:], body: performerBody))
}
if let title = title {
let titleBody = try title.makeBytes()
formData["title"] = Field(name: "title", filename: nil, part: Part(headers: [:], body: titleBody))
}
if
let duration = duration
{
let durationBody = try String(describing: duration).makeBytes()
formData["duration"] = Field(name: "duration", filename: nil, part: Part(headers: [:], body: durationBody))
}
if
let replyToMessageId = replyToMessageId
{
let replyToMessageIdBody = try String(describing: replyToMessageId).makeBytes()
formData["reply_to_message_id"] = Field(name: "reply_to_message_id", filename: nil, part: Part(headers: [:], body: replyToMessageIdBody))
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
let node = try replyMarkupNode.makeNode()
let json = try JSON(node: node)
let jsonBody = try json.makeBytes()
formData["reply_markup"] = Field(name: "reply_markup", filename: nil, part: Part(headers: [:], body: jsonBody))
}
let response = try sendFile(methodName: "sendAudio", formData: formData)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendAudio(chatId: ChatId, audio: URL, disableNotification: Bool = false, caption: String? = nil, duration: Int? = nil, performer: String? = nil, title: String? = nil, replyToMessageId: MessageId? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"audio": audio.absoluteString.makeNode(),
"disable_notification": disableNotification.makeNode()
]
if let caption = caption {
params["caption"] = caption.makeNode()
}
if let performer = performer {
params["performer"] = performer.makeNode()
}
if let title = title {
params["title"] = title.makeNode()
}
if let duration = duration {
params["duration"] = try duration.makeNode()
}
if let replyToMessageId = replyToMessageId {
params["reply_to_message_id"] = try replyToMessageId.makeNode()
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "sendAudio", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendDocument(chatId: ChatId, document: InputFile, fileName: String, disableNotification: Bool = false, caption: String? = nil, replyToMessageId: MessageId? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
let chatIdBody = try String(describing: chatId).makeBytes()
let chatIdField = Field(name: "chat_id", filename: nil, part: Part(headers: [:], body: chatIdBody))
let documentBody = try document.makeBytes()
let documentField = Field(name: "document", filename: fileName, part: Part(headers: [:], body: documentBody))
let disableNotificationBody = try String(describing: disableNotification).makeBytes()
let disableNotificationField = Field(name: "disable_notification", filename: nil, part: Part(headers: [:], body: disableNotificationBody))
var formData: [String: Field] = [
"chat_id": chatIdField,
"document": documentField,
"disable_notification": disableNotificationField
]
if let caption = caption {
let captionBody = try caption.makeBytes()
formData["caption"] = Field(name: "caption", filename: nil, part: Part(headers: [:], body: captionBody))
}
if
let replyToMessageId = replyToMessageId
{
let replyToMessageIdBody = try String(describing: replyToMessageId).makeBytes()
formData["reply_to_message_id"] = Field(name: "reply_to_message_id", filename: nil, part: Part(headers: [:], body: replyToMessageIdBody))
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
let node = try replyMarkupNode.makeNode()
let json = try JSON(node: node)
let jsonBody = try json.makeBytes()
formData["reply_markup"] = Field(name: "reply_markup", filename: nil, part: Part(headers: [:], body: jsonBody))
}
let response = try sendFile(methodName: "sendDocument", formData: formData)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendDocument(chatId: ChatId, document: URL, disableNotification: Bool = false, caption: String? = nil, replyToMessageId: MessageId? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"document": document.absoluteString.makeNode(),
"disable_notification": disableNotification.makeNode()
]
if let caption = caption {
params["caption"] = caption.makeNode()
}
if let replyToMessageId = replyToMessageId {
params["reply_to_message_id"] = try replyToMessageId.makeNode()
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "sendDocument", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendSticker(chatId: ChatId, sticker: InputFile, fileName: String, disableNotification: Bool = false, replyToMessageId: MessageId? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
let chatIdBody = try String(describing: chatId).makeBytes()
let chatIdField = Field(name: "chat_id", filename: nil, part: Part(headers: [:], body: chatIdBody))
let stickerBody = try sticker.makeBytes()
let stickerField = Field(name: "sticker", filename: fileName, part: Part(headers: [:], body: stickerBody))
let disableNotificationBody = try String(describing: disableNotification).makeBytes()
let disableNotificationField = Field(name: "disable_notification", filename: nil, part: Part(headers: [:], body: disableNotificationBody))
var formData: [String: Field] = [
"chat_id": chatIdField,
"sticker": stickerField,
"disable_notification": disableNotificationField
]
if
let replyToMessageId = replyToMessageId
{
let replyToMessageIdBody = try String(describing: replyToMessageId).makeBytes()
formData["reply_to_message_id"] = Field(name: "reply_to_message_id", filename: nil, part: Part(headers: [:], body: replyToMessageIdBody))
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
let node = try replyMarkupNode.makeNode()
let json = try JSON(node: node)
let jsonBody = try json.makeBytes()
formData["reply_markup"] = Field(name: "reply_markup", filename: nil, part: Part(headers: [:], body: jsonBody))
}
let response = try sendFile(methodName: "sendSticker", formData: formData)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendSticker(chatId: ChatId, sticker: URL, disableNotification: Bool = false, replyToMessageId: MessageId? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"sticker": sticker.absoluteString.makeNode(),
"disable_notification": disableNotification.makeNode()
]
if let replyToMessageId = replyToMessageId {
params["reply_to_message_id"] = try replyToMessageId.makeNode()
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "sendSticker", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendVideo(chatId: ChatId, video: InputFile, fileName: String, disableNotification: Bool = false, replyToMessageId: MessageId? = nil, duration: Int? = nil, width: Int? = nil, height: Int? = nil, caption: String? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
let chatIdBody = try String(describing: chatId).makeBytes()
let chatIdField = Field(name: "chat_id", filename: nil, part: Part(headers: [:], body: chatIdBody))
let videoBody = try video.makeBytes()
let videoField = Field(name: "video", filename: fileName, part: Part(headers: [:], body: videoBody))
let disableNotificationBody = try String(describing: disableNotification).makeBytes()
let disableNotificationField = Field(name: "disable_notification", filename: nil, part: Part(headers: [:], body: disableNotificationBody))
var formData: [String: Field] = [
"chat_id": chatIdField,
"document": videoField,
"disable_notification": disableNotificationField
]
if
let duration = duration
{
let durationBody = try String(describing: duration).makeBytes()
formData["duration"] = Field(name: "duration", filename: nil, part: Part(headers: [:], body: durationBody))
}
if
let width = width
{
let widthBody = try String(describing: width).makeBytes()
formData["width"] = Field(name: "duration", filename: nil, part: Part(headers: [:], body: widthBody))
}
if
let height = height
{
let heightBody = try String(describing: height).makeBytes()
formData["height"] = Field(name: "duration", filename: nil, part: Part(headers: [:], body: heightBody))
}
if let caption = caption {
let captionBody = try caption.makeBytes()
formData["caption"] = Field(name: "caption", filename: nil, part: Part(headers: [:], body: captionBody))
}
if
let replyToMessageId = replyToMessageId
{
let replyToMessageIdBody = try String(describing: replyToMessageId).makeBytes()
formData["reply_to_message_id"] = Field(name: "reply_to_message_id", filename: nil, part: Part(headers: [:], body: replyToMessageIdBody))
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
let node = try replyMarkupNode.makeNode()
let json = try JSON(node: node)
let jsonBody = try json.makeBytes()
formData["reply_markup"] = Field(name: "reply_markup", filename: nil, part: Part(headers: [:], body: jsonBody))
}
let response = try sendFile(methodName: "sendVideo", formData: formData)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendVideo(chatId: ChatId, video: URL, disableNotification: Bool = false, replyToMessageId: MessageId? = nil, duration: Int? = nil, width: Int? = nil, height: Int? = nil, caption: String? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"video": video.absoluteString.makeNode(),
"disable_notification": disableNotification.makeNode()
]
if let duration = duration {
params["duration"] = try duration.makeNode()
}
if let width = width {
params["width"] = try width.makeNode()
}
if let height = height {
params["height"] = try height.makeNode()
}
if let caption = caption {
params["caption"] = caption.makeNode()
}
if let replyToMessageId = replyToMessageId {
params["reply_to_message_id"] = try replyToMessageId.makeNode()
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "sendVideo", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendVoice(chatId: ChatId, voice: InputFile, fileName: String, disableNotification: Bool = false, caption: String? = nil, duration: Int? = nil, replyToMessageId: MessageId? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
let chatIdBody = try String(describing: chatId).makeBytes()
let chatIdField = Field(name: "chat_id", filename: nil, part: Part(headers: [:], body: chatIdBody))
let voiceBody = try voice.makeBytes()
let voiceField = Field(name: "voice", filename: fileName, part: Part(headers: [:], body: voiceBody))
let disableNotificationBody = try String(describing: disableNotification).makeBytes()
let disableNotificationField = Field(name: "disable_notification", filename: nil, part: Part(headers: [:], body: disableNotificationBody))
var formData: [String: Field] = [
"chat_id": chatIdField,
"voice": voiceField,
"disable_notification": disableNotificationField
]
if let caption = caption {
let captionBody = try caption.makeBytes()
formData["caption"] = Field(name: "caption", filename: nil, part: Part(headers: [:], body: captionBody))
}
if
let duration = duration
{
let durationBody = try String(describing: duration).makeBytes()
formData["duration"] = Field(name: "duration", filename: nil, part: Part(headers: [:], body: durationBody))
}
if
let replyToMessageId = replyToMessageId
{
let replyToMessageIdBody = try String(describing: replyToMessageId).makeBytes()
formData["reply_to_message_id"] = Field(name: "reply_to_message_id", filename: nil, part: Part(headers: [:], body: replyToMessageIdBody))
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
let node = try replyMarkupNode.makeNode()
let json = try JSON(node: node)
let jsonBody = try json.makeBytes()
formData["reply_markup"] = Field(name: "reply_markup", filename: nil, part: Part(headers: [:], body: jsonBody))
}
let response = try sendFile(methodName: "sendVoice", formData: formData)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendVoice(chatId: ChatId, voice: URL, disableNotification: Bool = false, caption: String? = nil, duration: Int? = nil, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message {
var params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"voice": voice.absoluteString.makeNode(),
"disable_notification": disableNotification.makeNode()
]
if let caption = caption {
params["caption"] = caption.makeNode()
}
if let duration = duration {
params["duration"] = try duration.makeNode()
}
if let replyToMessageId = replyToMessageId {
params["reply_to_message_id"] = try replyToMessageId.makeNode()
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "sendVoice", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendLocation(chatId: ChatId, latitude: Float, longitude: Float, disableNotification: Bool = false, replyToMessageId: MessageId? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"latitude": latitude.makeNode(),
"longitude": longitude.makeNode(),
"disable_notification": disableNotification.makeNode()
]
if let replyToMessageId = replyToMessageId {
params["reply_to_message_id"] = try replyToMessageId.makeNode()
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "sendLocation", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendVenue(chatId: ChatId, latitude: Float, longitude: Float, title: String, address: String, disableNotification: Bool = false, foursquareId: FoursquareId? = nil, replyToMessageId: MessageId? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"latitude": latitude.makeNode(),
"longitude": longitude.makeNode(),
"title": title.makeNode(),
"address": address.makeNode(),
"disable_notification": disableNotification.makeNode()
]
if let foursquareId = foursquareId {
params["foursquare_id"] = foursquareId.makeNode()
}
if let replyToMessageId = replyToMessageId {
params["reply_to_message_id"] = try replyToMessageId.makeNode()
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "sendVenue", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendContact(chatId: ChatId, phoneNumber: String, firstName: String, lastName: String, disableNotification: Bool = false, replyToMessageId: MessageId? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"phone_number": phoneNumber.makeNode(),
"first_name": firstName.makeNode(),
"last_name": lastName.makeNode(),
"disable_notification": disableNotification.makeNode()
]
if let replyToMessageId = replyToMessageId {
params["reply_to_message_id"] = try replyToMessageId.makeNode()
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "sendContact", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func sendChatAction(chatId: ChatId, action: ChatAction) throws -> Bool {
let params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"action": action.rawValue.makeNode(),
]
let response = try sendPost(methodName: "sendChatAction", params: params)
let json = try checkForServerError(response: response)
return json.bool ?? false
}
//MARK: Get
func getMe() throws -> User {
let response = try sendGet(methodName: "getMe", params: [:])
let json = try checkForServerError(response: response)
return try User(json: json)
}
func getUserProfilePhotos(userId: UserId, offset: Int, limit: Int) throws -> UserProfilePhotos {
let params: [String: CustomStringConvertible] = [
"user_id": userId,
"offset": offset,
"limit": limit
]
let response = try sendGet(methodName: "getUserProfilePhotos", params: params)
let json = try checkForServerError(response: response)
return try UserProfilePhotos(json: json)
}
func getFile(fileId: FileId) throws -> File {
let response = try sendGet(methodName: "getFile", params: ["file_id": fileId])
let json = try checkForServerError(response: response)
return try File(json: json)
}
func getChat(chatId: ChatId) throws -> Chat {
let params: [String: CustomStringConvertible] = [
"chat_id": chatId
]
let response = try sendGet(methodName: "getChat", params: params)
let json = try checkForServerError(response: response)
return try Chat(json: json)
}
func getChatAdministrators(chatId: ChatId) throws -> [ChatMember] {
let params: [String: CustomStringConvertible] = [
"chat_id": chatId
]
let response = try sendGet(methodName: "getChatAdministrators", params: params)
let json = try checkForServerError(response: response)
return try ChatMember.create(arrayJSON: json)
}
func getChatMembersCount(chatId: ChatId) throws -> Int {
let params: [String: CustomStringConvertible] = [
"chat_id": chatId
]
let response = try sendGet(methodName: "getChatMembersCount", params: params)
let json = try checkForServerError(response: response)
return json.int ?? 0
}
func getChatMember(chatId: ChatId, userId: UserId) throws -> ChatMember {
let params: [String: CustomStringConvertible] = [
"chat_id": chatId,
"user_id": userId
]
let response = try sendGet(methodName: "getChatMember", params: params)
let json = try checkForServerError(response: response)
return try ChatMember(json: json)
}
//MARK: Actions
func kickChatMember(chatId: ChatId, userId: UserId) throws -> Bool {
let params: [String: CustomStringConvertible] = [
"chat_id": chatId,
"user_id": userId
]
let response = try sendGet(methodName: "kickChatMember", params: params)
let json = try checkForServerError(response: response)
return json.bool ?? false
}
func forwardMessage(chatId: ChatId, fromChatId: ChatId, messageId: MessageId , disableNotification: Bool = false) throws -> Message {
let response = try sendPost(methodName: "forwardMessage", params: [
"chat_id": try chatId.makeNode(),
"from_chat_id": try fromChatId.makeNode(),
"message_id": try messageId.makeNode(),
"disable_notification": disableNotification.makeNode()
]
)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func leaveChat(chatId: ChatId, userId: UserId) throws -> Bool {
let params: [String: CustomStringConvertible] = [
"chat_id": chatId,
"user_id": userId
]
let response = try sendGet(methodName: "leaveChat", params: params)
let json = try checkForServerError(response: response)
return json.bool ?? false
}
func unbanChatMember(chatId: ChatId, userId: UserId) throws -> Bool {
let params: [String: CustomStringConvertible] = [
"chat_id": chatId,
"user_id": userId
]
let response = try sendGet(methodName: "unbanChatMember", params: params)
let json = try checkForServerError(response: response)
return json.bool ?? false
}
func answerCallbackQuery(callbackQueryId: CallbackQueryId, showAlert: Bool = false, text: String? = nil, url: URL? = nil, cacheTime: Int? = nil) throws -> Bool {
var params: [String: CustomStringConvertible] = [
"callback_query_id": callbackQueryId,
"show_alert": showAlert
]
if let text = text {
params["text"] = text
}
let response = try sendGet(methodName: "answerCallbackQuery", params: params)
let json = try checkForServerError(response: response)
return json.bool ?? false
}
func editMessageText(chatId: ChatId, messageId: MessageId, text: String, disableWebPagePreview: Bool = false, parseMode: ParseMode? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"message_id": try messageId.makeNode(),
"text": text.makeNode(),
"disable_web_page_preview": disableWebPagePreview.makeNode()
]
if let parseMode = parseMode {
params["parse_mode"] = parseMode.rawValue.makeNode()
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "editMessageText", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func editMessageText(inlineMessageId: InlineMessageId, text: String, disableWebPagePreview: Bool = false, parseMode: ParseMode? = nil, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"inline_message_id": try inlineMessageId.makeNode(),
"text": text.makeNode(),
"disable_web_page_preview": disableWebPagePreview.makeNode()
]
if let parseMode = parseMode {
params["parse_mode"] = parseMode.rawValue.makeNode()
}
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "editMessageText", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func editMessageCaption(chatId: ChatId, messageId: MessageId, caption: String, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"message_id": try messageId.makeNode(),
"caption": caption.makeNode()
]
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "editMessageCaption", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func editMessageCaption(inlineMessageId: InlineMessageId, caption: String, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"inline_message_id": try inlineMessageId.makeNode(),
"caption": caption.makeNode()
]
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "editMessageCaption", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func editMessageReplyMarkup(chatId: ChatId, messageId: MessageId, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"message_id": try messageId.makeNode()
]
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "editMessageReplyMarkup", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func editMessageReplyMarkup(inlineMessageId: InlineMessageId, replyMarkup: ReplyMarkup? = nil) throws -> Message {
var params: [String: Node] = [
"inline_message_id": try inlineMessageId.makeNode()
]
if let replyMarkup = replyMarkup, let replyMarkupNode = replyMarkup as? NodeRepresentable {
params["reply_markup"] = try replyMarkupNode.makeNode()
}
let response = try sendPost(methodName: "editMessageReplyMarkup", params: params)
let json = try checkForServerError(response: response)
return try Message(json: json)
}
func deleteMessage(chatId: ChatId, messageId: MessageId) throws -> Bool {
let params: [String: Node] = [
"chat_id": try chatId.makeNode(),
"message_id": try messageId.makeNode()
]
let response = try sendPost(methodName: "deleteMessage", params: params)
let json = try checkForServerError(response: response)
return json.bool ?? false
}
func inlineQuery(id: String, from: User, query: String, offset: String, location: Location?) throws -> Bool {
return false
}
}
| mit | 186c8b77afd4f2866d9830c5b5da0f2f | 37.804717 | 289 | 0.590694 | 5.114772 | false | false | false | false |
lstanii-magnet/ChatKitSample-iOS | ChatMessenger/Pods/ChatKit/ChatKit/source/ChatKit/DefaultChatListControllerDelegate.swift | 1 | 2479 | /*
* Copyright (c) 2016 Magnet Systems, Inc.
* 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
import CocoaLumberjack
import MagnetMax
public class DefaultChatListControllerDelegate : NSObject, ChatListControllerDelegate {
//MARK : Public Variables
public weak var controller : MMXChatListViewController?
//MARK: ChatListControllerDelegate
public func mmxListDidSelectChannel(channel : MMXChannel, channelDetails : MMXChannelDetailResponse) {
let chatViewController = MMXChatViewController.init(channel : channel)
chatViewController.view.tintColor = controller?.view.tintColor
let myId = MMUser.currentUser()?.userID
let subscribers = channelDetails.subscribers.filter({$0.userId != myId})
let users : [MMUser] = subscribers.map({
let user = MMUser()
user.firstName = ""
user.lastName = ""
user.userName = $0.displayName
user.userID = $0.userId
return user
})
self.controller?.presentChatViewController(chatViewController, users: users)
//Delays cell deselection from reloading data - not necessary
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {() in
self.controller?.reloadData()
})
}
public func mmxListCanLeaveChannel(channel : MMXChannel, channelDetails : MMXChannelDetailResponse) -> Bool {
return true
}
func mmxContactsControllerDidFinish(with selectedUsers: [MMUser]) {
}
public func mmxListWillShowChatController(chatController : MMXChatViewController) {
}
public func mmxAvatarDidClick(user: MMUser) {
DDLogInfo("[Clicked] \(user.userName) - Avatar! - DefaultChatListControllerDelegate")
}
} | apache-2.0 | 87d2e5fc6e9acfada759e72eae8adb1f | 30.794872 | 127 | 0.666398 | 5.038618 | false | false | false | false |
CodeMozart/MHzSinaWeibo-Swift- | SinaWeibo(stroyboard)/SinaWeibo/Classes/Home/MHzTableViewCell.swift | 1 | 7023 | //
// MHzTableViewCell.swift
// SinaWeibo
//
// Created by Minghe on 15/11/15.
// Copyright © 2015年 Stanford swift. All rights reserved.
//
import UIKit
import SDWebImage
// Swift中的枚举比OC强大很多, 可以赋值任意类型的数据, 以及可以定义方法
enum MHzTableViewCellIdentifier: String
{
case NormalCellIdentifier = "originCell"
case ForwardCellIdentifier = "forwardCell"
static func identifierWithViewModel(viewModel: StatusViewModel) -> String
{
// rawValue代表获取枚举的原始值
return (viewModel.status.retweeted_status != nil) ? ForwardCellIdentifier.rawValue : NormalCellIdentifier.rawValue
}
}
class MHzTableViewCell: UITableViewCell {
// MARK: - outlet ------------------------------
/// 用户头像
@IBOutlet weak var iconImageView: UIImageView!
/// 会员图标
@IBOutlet weak var vipImageView: UIImageView!
/// 认证图标
@IBOutlet weak var verifiedImageView: UIImageView!
/// 昵称
@IBOutlet weak var nameLabel: UILabel!
/// 时间
@IBOutlet weak var timeLabel: UILabel!
/// 来源
@IBOutlet weak var sourceLabel: UILabel!
/// 正文
@IBOutlet weak var contentLabel: UILabel!
/// 正文的宽度约束
@IBOutlet weak var contentLabelWidthCons: NSLayoutConstraint!
/// 转发正文
@IBOutlet weak var forwardContentLabel: UILabel!
/// 转发正文的宽度约束
@IBOutlet weak var forwardContentLabelWidthCons: NSLayoutConstraint!
/// 配图容器
@IBOutlet weak var pictureCollectionView: UICollectionView!
/// 配图容器宽度约束
@IBOutlet weak var pictureCollectionViewWidthCons: NSLayoutConstraint!
/// 配图容器高度约束
@IBOutlet weak var pictureCollectionViewHeightCons: NSLayoutConstraint!
/// 底部工具试图
@IBOutlet weak var footerToolView: UIView!
@IBOutlet weak var footerView: UIView!
/// 模型对象
var viewModel: StatusViewModel?
{
didSet {
/// 1.设置头像
// let url = NSURL(string: status?.user?.profile_image_url ?? "")
iconImageView.sd_setImageWithURL(viewModel?.avatarURL)
/// 2.设置昵称
nameLabel.text = viewModel?.status.user?.screen_name ?? ""
// nameLabel.text = viewModel?.status.retweeted_status.screen_name ?? ""
/// 3.设置时间
timeLabel.text = viewModel?.createdText ?? ""
/// 4.设置来源
sourceLabel.text = viewModel?.sourceText ?? ""
/// 5.设置正文
contentLabel.text = viewModel?.status.text ?? ""
/// 6.认证图标
verifiedImageView.image = viewModel?.verifiedImage
/// 7.会员图片
vipImageView.image = viewModel?.mbrankImage
/// 8.配图
let (itemSize, size) = calculateSize()
pictureCollectionViewWidthCons.constant = size.width
pictureCollectionViewHeightCons.constant = size.height
if itemSize != CGSizeZero
{
(pictureCollectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize = itemSize
(pictureCollectionView.collectionViewLayout as! UICollectionViewFlowLayout).minimumLineSpacing = 5
(pictureCollectionView.collectionViewLayout as! UICollectionViewFlowLayout).minimumInteritemSpacing = 5
}
/// 9.转发正文
if let temp = viewModel?.status.retweeted_status?.text
{
forwardContentLabelWidthCons.constant = UIScreen.mainScreen().bounds.width - 20
forwardContentLabel.text = temp
}
pictureCollectionView.reloadData()
}
}
// MARK: - 外部控制方法 ------------------------------
// 计算当前行高度
func calculateRowHeight(viewModel: StatusViewModel) -> CGFloat
{
self.viewModel = viewModel
layoutIfNeeded()
return CGRectGetMaxY(footerView.frame)
}
// MARK: - 内部控制方法 ------------------------------
/// 计算配图尺寸
// 第一个参数:imageView的尺寸;第二个参数:配图容器的尺寸
private func calculateSize() -> (CGSize, CGSize)
{
let count = viewModel?.thumbnail_pics?.count ?? 0
if count == 0 {
return (CGSizeZero,CGSizeZero)
}
if count == 1
{
let urlStr = viewModel!.thumbnail_pics!.last!.absoluteString
// 加载已经下载好得图片
if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlStr) {
// 获取图片的size
return (image.size, image.size)
}
}
var imageWidth : CGFloat = 90
var imageHeight = imageWidth
let imageMargin : CGFloat = 5
if count == 4
{
let col : CGFloat = 2
let width = col * imageWidth + (col - 1) * imageMargin
let height = width
return (CGSize(width: 90, height: 90), CGSize(width: width, height: height))
}
let col : CGFloat = 3
let row = (count - 1) / 3 + 1
let width = UIScreen.mainScreen().bounds.width - 20
imageWidth = (width - (col - 1) * imageMargin) / col
imageHeight = imageWidth
let height = CGFloat(row) * imageHeight + CGFloat(row - 1) * imageMargin
return (CGSize(width: imageWidth, height: imageHeight), CGSize(width: width, height: height))
}
override func awakeFromNib() {
super.awakeFromNib()
// 动态设置正文宽度约束
contentLabelWidthCons.constant = UIScreen.mainScreen().bounds.width - 20
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension MHzTableViewCell: UICollectionViewDataSource
{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel?.thumbnail_pics?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("pictureCell", forIndexPath: indexPath) as! MHzPictureCollectionViewCell
let url = viewModel!.thumbnail_pics![indexPath.item]
cell.imageURL = url
return cell
}
}
class MHzPictureCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
var imageURL: NSURL?
{
didSet{
imageView.sd_setImageWithURL(imageURL)
}
}
}
| mit | 0b12f4d09791d0ddc5fa276f7cddde5b | 30.990291 | 145 | 0.604401 | 5.250996 | false | false | false | false |
shial4/api-loltracker | Sources/App/Models/Tracker.swift | 1 | 1327 | //
// Tracker.swift
// lolTracker-API
//
// Created by Shial on 13/01/2017.
//
//
import Foundation
import Vapor
import Fluent
final class Tracker: Model {
var exists: Bool = false
public var id: Node?
var summonerId: Node?
var date: String
init(date: String, summonerId: Node? = nil) {
self.id = nil
self.summonerId = summonerId
self.date = date
}
required init(node: Node, in context: Context) throws {
id = try node.extract("id")
date = try node.extract("date")
summonerId = try node.extract("summoner_id")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"date": date,
"summoner_id": summonerId
])
}
}
extension Tracker: Preparation {
static func prepare(_ database: Database) throws {
try database.create(entity, closure: { (tracks) in
tracks.id()
tracks.int("date")
tracks.parent(Summoner.self, optional: false)
})
}
static func revert(_ database: Database) throws {
try database.delete(entity)
}
}
extension Tracker {
func summoner() throws -> Summoner? {
return try parent(summonerId, nil, Summoner.self).get()
}
}
| mit | 3887355b64633770e164b5f7154e3d0f | 21.491525 | 63 | 0.571213 | 3.996988 | false | false | false | false |
brave/browser-ios | Shared/Extensions/ArrayExtensions.swift | 2 | 2104 | /* 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
public extension Array {
func find(_ f: (Iterator.Element) -> Bool) -> Iterator.Element? {
for x in self {
if f(x) {
return x
}
}
return nil
}
// Laughably inefficient, but good enough for a handful of items.
func sameElements(_ arr: [Element], f: (Element, Element) -> Bool) -> Bool {
return self.count == arr.count && every { arr.contains($0, f: f) }
}
func contains(_ x: Element, f: (Element, Element) -> Bool) -> Bool {
for y in self {
if f(x, y) {
return true
}
}
return false
}
// Performs a union operator using the result of f(Element) as the value to base uniqueness on.
func union<T: Hashable>(_ arr: [Element], f: ((Element) -> T)) -> [Element] {
let result = self + arr
return result.unique(f)
}
// Returns unique values in an array using the result of f()
func unique<T: Hashable>(_ f: ((Element) -> T)) -> [Element] {
var map: [T: Element] = [T: Element]()
return self.flatMap { a in
let t = f(a)
if map[t] == nil {
map[t] = a
return a
} else {
return nil
}
}
}
/// Returns a unique list of Elements using a custom comparator
/// Super inefficient
func unique(f: (Element, Element) -> Bool) -> [Element] {
var result = [Element]()
self.forEach {
if !result.contains($0, f: f) {
result.append($0)
}
}
return result
}
}
public extension Sequence {
func every(_ f: (Self.Iterator.Element) -> Bool) -> Bool {
for x in self {
if !f(x) {
return false
}
}
return true
}
}
| mpl-2.0 | 6297071cf91ae0e75e01f5163ae7991d | 27.053333 | 99 | 0.502852 | 4.022945 | false | false | false | false |
dcunited001/SwiftState | SwiftStateTests/StateMachineTests.swift | 3 | 18068 | //
// StateMachineTests.swift
// StateMachineTests
//
// Created by Yasuhiro Inami on 2014/08/03.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import SwiftState
import XCTest
class StateMachineTests: _TestCase
{
func testInit()
{
let machine = StateMachine<MyState, String>(state: .State0)
XCTAssertEqual(machine.state, MyState.State0)
}
//--------------------------------------------------
// MARK: - addRoute
//--------------------------------------------------
// add state1 => state2
func testAddRoute()
{
let machine = StateMachine<MyState, String>(state: .State0)
machine.addRoute(.State0 => .State1)
XCTAssertFalse(machine.hasRoute(.State0 => .State0))
XCTAssertTrue(machine.hasRoute(.State0 => .State1)) // true
XCTAssertFalse(machine.hasRoute(.State0 => .State2))
XCTAssertFalse(machine.hasRoute(.State1 => .State0))
XCTAssertFalse(machine.hasRoute(.State1 => .State1))
XCTAssertFalse(machine.hasRoute(.State1 => .State2))
}
// add nil => state
func testAddRoute_fromAnyState()
{
let machine = StateMachine<MyState, String>(state: .State0)
machine.addRoute(nil => .State1) // Any => State1
XCTAssertFalse(machine.hasRoute(.State0 => .State0))
XCTAssertTrue(machine.hasRoute(.State0 => .State1)) // true
XCTAssertFalse(machine.hasRoute(.State0 => .State2))
XCTAssertFalse(machine.hasRoute(.State1 => .State0))
XCTAssertTrue(machine.hasRoute(.State1 => .State1)) // true
XCTAssertFalse(machine.hasRoute(.State1 => .State2))
}
// add state => nil
func testAddRoute_toAnyState()
{
let machine = StateMachine<MyState, String>(state: .State0)
machine.addRoute(.State1 => nil) // State1 => Any
XCTAssertFalse(machine.hasRoute(.State0 => .State0))
XCTAssertFalse(machine.hasRoute(.State0 => .State1))
XCTAssertFalse(machine.hasRoute(.State0 => .State2))
XCTAssertTrue(machine.hasRoute(.State1 => .State0)) // true
XCTAssertTrue(machine.hasRoute(.State1 => .State1)) // true
XCTAssertTrue(machine.hasRoute(.State1 => .State2)) // true
}
// add nil => nil
func testAddRoute_bothAnyState()
{
let machine = StateMachine<MyState, String>(state: .State0)
machine.addRoute(nil => nil) // Any => Any
XCTAssertTrue(machine.hasRoute(.State0 => .State0)) // true
XCTAssertTrue(machine.hasRoute(.State0 => .State1)) // true
XCTAssertTrue(machine.hasRoute(.State0 => .State2)) // true
XCTAssertTrue(machine.hasRoute(.State1 => .State0)) // true
XCTAssertTrue(machine.hasRoute(.State1 => .State1)) // true
XCTAssertTrue(machine.hasRoute(.State1 => .State2)) // true
}
// add state0 => state0
func testAddRoute_sameState()
{
let machine = StateMachine<MyState, String>(state: .State0)
machine.addRoute(.State0 => .State0)
XCTAssertTrue(machine.hasRoute(.State0 => .State0))
// tryState 0 => 0
XCTAssertTrue(machine <- .State0)
}
// add route + condition
func testAddRoute_condition()
{
let machine = StateMachine<MyState, String>(state: .State0)
var flag = false
// add 0 => 1
machine.addRoute(.State0 => .State1, condition: flag)
XCTAssertFalse(machine.hasRoute(.State0 => .State1))
flag = true
XCTAssertTrue(machine.hasRoute(.State0 => .State1))
}
// add route + condition + blacklist
func testAddRoute_condition_blacklist()
{
let machine = StateMachine<MyState, String>(state: .State0)
// add 0 => Any, except 0 => 2
machine.addRoute(.State0 => nil, condition: { transition in
return transition.toState != .State2
})
XCTAssertTrue(machine.hasRoute(.State0 => .State0))
XCTAssertTrue(machine.hasRoute(.State0 => .State1))
XCTAssertFalse(machine.hasRoute(.State0 => .State2))
XCTAssertTrue(machine.hasRoute(.State0 => .State3))
}
// add route + handler
func testAddRoute_handler()
{
let machine = StateMachine<MyState, String>(state: .State0)
var returnedTransition: StateTransition<MyState>?
machine.addRoute(.State0 => .State1) { context in
returnedTransition = context.transition
}
XCTAssertTrue(returnedTransition == nil, "Transition has not started yet.")
// tryState 0 => 1
machine <- .State1
XCTAssertTrue(returnedTransition != nil)
XCTAssertEqual(returnedTransition!.fromState, MyState.State0)
XCTAssertEqual(returnedTransition!.toState, MyState.State1)
}
// add route + conditional handler
func testAddRoute_conditionalHandler()
{
let machine = StateMachine<MyState, String>(state: .State0)
var flag = false
var returnedTransition: StateTransition<MyState>?
// add 0 => 1 without condition to guarantee 0 => 1 transition
machine.addRoute(.State0 => .State1)
// add 0 => 1 with condition + conditionalHandler
machine.addRoute(.State0 => .State1, condition: flag) { context in
returnedTransition = context.transition
}
// tryState 0 => 1
machine <- .State1
XCTAssertEqual(machine.state, MyState.State1 , "0 => 1 transition should be performed.")
XCTAssertTrue(returnedTransition == nil, "Conditional handler should NOT be performed because flag=false.")
// add 1 => 0 for resetting state
machine.addRoute(.State1 => .State0)
// tryState 1 => 0
machine <- .State0
flag = true
// tryState 0 => 1
machine <- .State1
XCTAssertTrue(returnedTransition != nil)
XCTAssertEqual(returnedTransition!.fromState, MyState.State0)
XCTAssertEqual(returnedTransition!.toState, MyState.State1)
}
// MARK: addRoute using array
func testAddRoute_array_left()
{
let machine = StateMachine<MyState, String>(state: .State0)
// add 0 => 2 or 1 => 2
machine.addRoute([.State0, .State1] => .State2)
XCTAssertFalse(machine.hasRoute(.State0 => .State0))
XCTAssertFalse(machine.hasRoute(.State0 => .State1))
XCTAssertTrue(machine.hasRoute(.State0 => .State2))
XCTAssertFalse(machine.hasRoute(.State1 => .State0))
XCTAssertFalse(machine.hasRoute(.State1 => .State1))
XCTAssertTrue(machine.hasRoute(.State1 => .State2))
}
func testAddRoute_array_right()
{
let machine = StateMachine<MyState, String>(state: .State0)
// add 0 => 1 or 0 => 2
machine.addRoute(.State0 => [.State1, .State2])
XCTAssertFalse(machine.hasRoute(.State0 => .State0))
XCTAssertTrue(machine.hasRoute(.State0 => .State1))
XCTAssertTrue(machine.hasRoute(.State0 => .State2))
XCTAssertFalse(machine.hasRoute(.State1 => .State0))
XCTAssertFalse(machine.hasRoute(.State1 => .State1))
XCTAssertFalse(machine.hasRoute(.State1 => .State2))
}
func testAddRoute_array_both()
{
let machine = StateMachine<MyState, String>(state: .State0)
// add 0 => 2 or 0 => 3 or 1 => 2 or 1 => 3
machine.addRoute([MyState.State0, MyState.State1] => [MyState.State2, MyState.State3])
XCTAssertFalse(machine.hasRoute(.State0 => .State0))
XCTAssertFalse(machine.hasRoute(.State0 => .State1))
XCTAssertTrue(machine.hasRoute(.State0 => .State2))
XCTAssertTrue(machine.hasRoute(.State0 => .State3))
XCTAssertFalse(machine.hasRoute(.State1 => .State0))
XCTAssertFalse(machine.hasRoute(.State1 => .State1))
XCTAssertTrue(machine.hasRoute(.State1 => .State2))
XCTAssertTrue(machine.hasRoute(.State1 => .State3))
XCTAssertFalse(machine.hasRoute(.State2 => .State0))
XCTAssertFalse(machine.hasRoute(.State2 => .State1))
XCTAssertFalse(machine.hasRoute(.State2 => .State2))
XCTAssertFalse(machine.hasRoute(.State2 => .State3))
XCTAssertFalse(machine.hasRoute(.State3 => .State0))
XCTAssertFalse(machine.hasRoute(.State3 => .State1))
XCTAssertFalse(machine.hasRoute(.State3 => .State2))
XCTAssertFalse(machine.hasRoute(.State3 => .State3))
}
//--------------------------------------------------
// MARK: - removeRoute
//--------------------------------------------------
func testRemoveRoute()
{
let machine = StateMachine<MyState, String>(state: .State0)
let routeID = machine.addRoute(.State0 => .State1)
XCTAssertTrue(machine.hasRoute(.State0 => .State1))
var success: Bool
success = machine.removeRoute(routeID)
XCTAssertTrue(success)
XCTAssertFalse(machine.hasRoute(.State0 => .State1))
// fails removing already unregistered route
success = machine.removeRoute(routeID)
XCTAssertFalse(success)
}
//--------------------------------------------------
// MARK: - tryState a.k.a <-
//--------------------------------------------------
// machine <- state
func testTryState()
{
let machine = StateMachine<MyState, String>(state: .State0)
// tryState 0 => 1, without registering any transitions
machine <- .State1
XCTAssertEqual(machine.state, MyState.State0, "0 => 1 should fail because transition is not added yet.")
// add 0 => 1
machine.addRoute(.State0 => .State1)
// tryState 0 => 1, returning flag
let success = machine <- .State1
XCTAssertTrue(success)
XCTAssertEqual(machine.state, MyState.State1)
}
func testTryState_string()
{
let machine = StateMachine<String, String>(state: "0")
// tryState 0 => 1, without registering any transitions
machine <- "1"
XCTAssertEqual(machine.state, "0", "0 => 1 should fail because transition is not added yet.")
// add 0 => 1
machine.addRoute("0" => "1")
// tryState 0 => 1, returning flag
let success = machine <- "1"
XCTAssertTrue(success)
XCTAssertEqual(machine.state, "1")
}
//--------------------------------------------------
// MARK: - addHandler
//--------------------------------------------------
func testAddHandler()
{
let machine = StateMachine<MyState, String>(state: .State0)
var returnedTransition: StateTransition<MyState>?
// add 0 => 1
machine.addRoute(.State0 => .State1)
machine.addHandler(.State0 => .State1) { context in
// returnedTransition = context.transition
}
machine.addHandler(.State0 => .State1) { context in
returnedTransition = context.transition
}
// not tried yet
XCTAssertTrue(returnedTransition == nil, "Transition has not started yet.")
// tryState 0 => 1
machine <- .State1
XCTAssertTrue(returnedTransition != nil)
XCTAssertEqual(returnedTransition!.fromState, MyState.State0)
XCTAssertEqual(returnedTransition!.toState, MyState.State1)
}
func testAddHandler_order()
{
let machine = StateMachine<MyState, String>(state: .State0)
var returnedTransition: StateTransition<MyState>?
// add 0 => 1
machine.addRoute(.State0 => .State1)
// order = 100 (default)
machine.addHandler(.State0 => .State1) { context in
// XCTAssertEqual(context.order, 100) // TODO: Xcode6.1-GM bug
XCTAssertTrue(context.order == 100)
XCTAssertTrue(returnedTransition != nil, "returnedTransition should already be set.")
returnedTransition = context.transition
}
// order = 99
machine.addHandler(.State0 => .State1, order: 99) { context in
// XCTAssertEqual(context.order, 99) // TODO: Xcode6.1-GM bug
XCTAssertTrue(context.order == 99)
XCTAssertTrue(returnedTransition == nil, "returnedTransition should NOT be set at this point.")
returnedTransition = context.transition // set returnedTransition for first time
}
// tryState 0 => 1
machine <- .State1
XCTAssertTrue(returnedTransition != nil)
XCTAssertEqual(returnedTransition!.fromState, MyState.State0)
XCTAssertEqual(returnedTransition!.toState, MyState.State1)
}
func testAddHandler_multiple()
{
let machine = StateMachine<MyState, String>(state: .State0)
var returnedTransition: StateTransition<MyState>?
var returnedTransition2: StateTransition<MyState>?
// add 0 => 1
machine.addRoute(.State0 => .State1)
machine.addHandler(.State0 => .State1) { context in
returnedTransition = context.transition
}
// add 0 => 1 once more
machine.addRoute(.State0 => .State1)
machine.addHandler(.State0 => .State1) { context in
returnedTransition2 = context.transition
}
// tryState 0 => 1
machine <- .State1
XCTAssertTrue(returnedTransition != nil)
XCTAssertTrue(returnedTransition2 != nil)
}
func testAddHandler_overload()
{
let machine = StateMachine<MyState, String>(state: .State0)
var returnedTransition: StateTransition<MyState>?
machine.addRoute(.State0 => .State1)
machine.addHandler(.State0 => .State1) { context in
// empty
}
machine.addHandler(.State0 => .State1) { context in
returnedTransition = context.transition
}
XCTAssertTrue(returnedTransition == nil)
machine <- .State1
XCTAssertTrue(returnedTransition != nil)
}
//--------------------------------------------------
// MARK: - removeHandler
//--------------------------------------------------
func testRemoveHandler()
{
let machine = StateMachine<MyState, String>(state: .State0)
var returnedTransition: StateTransition<MyState>?
var returnedTransition2: StateTransition<MyState>?
// add 0 => 1
machine.addRoute(.State0 => .State1)
let handlerID = machine.addHandler(.State0 => .State1) { context in
returnedTransition = context.transition
XCTFail("Should never reach here")
}
// add 0 => 1 once more
machine.addRoute(.State0 => .State1)
machine.addHandler(.State0 => .State1) { context in
returnedTransition2 = context.transition
}
machine.removeHandler(handlerID)
// tryState 0 => 1
machine <- .State1
XCTAssertTrue(returnedTransition == nil, "Handler should be removed and never performed.")
XCTAssertTrue(returnedTransition2 != nil)
}
func testRemoveHandler_unregistered()
{
let machine = StateMachine<MyState, String>(state: .State0)
// add 0 => 1
machine.addRoute(.State0 => .State1)
let handlerID = machine.addHandler(.State0 => .State1) { context in
// empty
}
// remove handler
XCTAssertTrue(machine.removeHandler(handlerID))
// remove already unregistered handler
XCTAssertFalse(machine.removeHandler(handlerID), "removeHandler should fail because handler is already removed.")
}
func testRemoveErrorHandler()
{
let machine = StateMachine<MyState, String>(state: .State0)
var returnedTransition: StateTransition<MyState>?
var returnedTransition2: StateTransition<MyState>?
// add 2 => 1
machine.addRoute(.State2 => .State1)
let handlerID = machine.addErrorHandler { context in
returnedTransition = context.transition
XCTFail("Should never reach here")
}
// add 2 => 1 once more
machine.addRoute(.State2 => .State1)
machine.addErrorHandler { context in
returnedTransition2 = context.transition
}
machine.removeHandler(handlerID)
// tryState 0 => 1
machine <- .State1
XCTAssertTrue(returnedTransition == nil, "Handler should be removed and never performed.")
XCTAssertTrue(returnedTransition2 != nil)
}
func testRemoveErrorHandler_unregistered()
{
let machine = StateMachine<MyState, String>(state: .State0)
// add 0 => 1
machine.addRoute(.State0 => .State1)
let handlerID = machine.addErrorHandler { context in
// empty
}
// remove handler
XCTAssertTrue(machine.removeHandler(handlerID))
// remove already unregistered handler
XCTAssertFalse(machine.removeHandler(handlerID), "removeHandler should fail because handler is already removed.")
}
}
| mit | fbb58f82bc1144b5f123963aad40ff0a | 32.831461 | 121 | 0.568582 | 5.074719 | false | true | false | false |
bhajian/raspi-remote | Carthage/Checkouts/ios-sdk/Source/AlchemyLanguageV1/Models/DisambiguatedLinks.swift | 2 | 3902 | /**
* Copyright IBM Corporation 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import Freddy
/**
**DisambiguatedLinks**
Disambiguate detected entities
*/
public struct DisambiguatedLinks: JSONDecodable {
/** detected language */
public let language: String?
/** content URL */
public let url: String?
/**
sameAs link to the US Census for this concept tag
Note: Provided only for entities that exist in this linked data-set
*/
public let census: String?
/**
sameAs link to the CIA World Factbook for this concept tag
Note: Provided only for entities that exist in this linked data-set
*/
public let ciaFactbook: String?
/**
website link to CrunchBase for this concept tag.
Note: Provided only for entities that exist in CrunchBase.
*/
public let crunchbase: String?
/**
sameAs link to DBpedia for this concept tag
Note: Provided only for entities that exist in this linked data-set
*/
public let dbpedia: String?
/**
sameAs link to Freebase for this concept tag.
Note: Provided only for entities that exist in this linked data-set
*/
public let freebase: String?
/** latitude longitude - the geographic coordinates associated with this concept tag */
public let geo: String?
/**
sameAs link to Geonames for this concept tag
Note: Provided only for entities that exist in this linked data-set
*/
public let geonames: String?
/**
* The music link to MusicBrainz for the disambiguated entity. Note: Provided only for
* entities that exist in this linked data-set.
*/
public let musicBrainz: String?
/** The entity name. */
public let name: String?
/**
* The link to OpenCyc for the disambiguated entity. Note: Provided only for entities
* that exist in this linked data-set.
*/
public let opencyc: String?
/** The disambiguated entity subType. */
public let subType: [String]?
/**
* The link to UMBEL for the disambiguated entity. Note: Provided only for entities
* that exist in this linked data-set.
*/
public let umbel: String?
/** The website. */
public let website: String?
/**
* The link to YAGO for the disambiguated entity. Note: Provided only for entities
* that exist in this linked data-set.
*/
public let yago: String?
/// Used internally to initialize a DisambiguatedLinks object
public init(json: JSON) throws {
language = try? json.string("language")
url = try? json.string("url")
census = try? json.string("census")
ciaFactbook = try? json.string("ciaFactbook")
crunchbase = try? json.string("crunchbase")
dbpedia = try? json.string("dbpedia")
freebase = try? json.string("freebase")
geo = try? json.string("geo")
geonames = try? json.string("geonames")
musicBrainz = try? json.string("musicBrainz")
name = try? json.string("name")
opencyc = try? json.string("opencyc")
subType = try? json.arrayOf("subType", type: Swift.String)
umbel = try? json.string("umbel")
website = try? json.string("website")
yago = try? json.string("yago")
}
}
| mit | a72b6437cc24406460016d9418e3c3a4 | 29.484375 | 91 | 0.646335 | 4.325942 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.