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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sunfei/Spring
|
Spring/SoundPlayer.swift
|
20
|
2093
|
// The MIT License (MIT)
//
// Copyright (c) 2015 James Tang ([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 AudioToolbox
struct SoundPlayer {
static var filename : String?
static var enabled : Bool = true
private struct Internal {
static var cache = [NSURL:SystemSoundID]()
}
static func playSound(soundFile: String) {
if !enabled {
return
}
if let url = NSBundle.mainBundle().URLForResource(soundFile, withExtension: nil) {
var soundID : SystemSoundID = Internal.cache[url] ?? 0
if soundID == 0 {
AudioServicesCreateSystemSoundID(url, &soundID)
Internal.cache[url] = soundID
}
AudioServicesPlaySystemSound(soundID)
} else {
println("Could not find sound file name `\(soundFile)`")
}
}
static func play(file: String) {
self.playSound(file)
}
}
|
mit
|
2d137f518fd16767007357e5bcd758e7
| 33.883333 | 90 | 0.655996 | 4.890187 | false | false | false | false |
rasmusth/BluetoothKit
|
Example/Vendor/CryptoSwift/Sources/CryptoSwift/SHA2.swift
|
1
|
13294
|
//
// SHA2.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 24/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
// TODO: generic for process32/64 (UInt32/UInt64)
//
public final class SHA2: DigestType {
let variant: Variant
var size: Int { return variant.rawValue }
var blockSize: Int { return variant.blockSize }
var digestLength: Int { return variant.digestLength }
fileprivate var accumulated = Array<UInt8>()
fileprivate var accumulatedLength: Int = 0
fileprivate var accumulatedHash32 = Array<UInt32>()
fileprivate var accumulatedHash64 = Array<UInt64>()
public init(variant: SHA2.Variant) {
self.variant = variant
switch self.variant {
case .sha224, .sha256:
self.accumulatedHash32 = variant.h.map { UInt32($0) } //FIXME: UInt64 for process64
case .sha384, .sha512:
self.accumulatedHash64 = variant.h
}
}
public enum Variant: RawRepresentable {
case sha224, sha256, sha384, sha512
public var digestLength:Int {
return self.rawValue / 8
}
public var blockSize: Int {
switch self {
case .sha224, .sha256:
return 64
case .sha384, .sha512:
return 128
}
}
public typealias RawValue = Int
public var rawValue: RawValue {
switch self {
case .sha224:
return 224
case .sha256:
return 256
case .sha384:
return 384
case .sha512:
return 512
}
}
public init?(rawValue: RawValue) {
switch (rawValue) {
case 224:
self = .sha224
break;
case 256:
self = .sha256
break;
case 384:
self = .sha384
break;
case 512:
self = .sha512
break;
default:
return nil
}
}
fileprivate var h:Array<UInt64> {
switch self {
case .sha224:
return [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4]
case .sha256:
return [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]
case .sha384:
return [0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4]
case .sha512:
return [0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179]
}
}
fileprivate var k:Array<UInt64> {
switch self {
case .sha224, .sha256:
return [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]
case .sha384, .sha512:
return [0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538,
0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe,
0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235,
0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab,
0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725,
0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed,
0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218,
0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53,
0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373,
0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c,
0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6,
0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc,
0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817]
}
}
fileprivate func resultingArray<T>(_ hh:[T]) -> ArraySlice<T> {
switch (self) {
case .sha224:
return hh[0..<7]
case .sha384:
return hh[0..<6]
default:
return ArraySlice(hh)
}
}
}
func calculate(for bytes: Array<UInt8>) -> Array<UInt8> {
do {
return try self.update(withBytes: bytes, isLast: true)
} catch {
return []
}
}
fileprivate func process64(block chunk: ArraySlice<UInt8>, currentHash hh: inout Array<UInt64>) {
// break chunk into sixteen 64-bit words M[j], 0 ≤ j ≤ 15, big-endian
// Extend the sixteen 64-bit words into eighty 64-bit words:
var M = Array<UInt64>(repeating: 0, count: variant.k.count)
for x in 0..<M.count {
switch (x) {
case 0...15:
let start = chunk.startIndex.advanced(by: x * 8) // * MemoryLayout<UInt64>.size
M[x] = UInt64(bytes: chunk, fromIndex: start)
break
default:
let s0 = rotateRight(M[x-15], by: 1) ^ rotateRight(M[x-15], by: 8) ^ (M[x-15] >> 7)
let s1 = rotateRight(M[x-2], by: 19) ^ rotateRight(M[x-2], by: 61) ^ (M[x-2] >> 6)
M[x] = M[x-16] &+ s0 &+ M[x-7] &+ s1
break
}
}
var A = hh[0]
var B = hh[1]
var C = hh[2]
var D = hh[3]
var E = hh[4]
var F = hh[5]
var G = hh[6]
var H = hh[7]
// Main loop
for j in 0..<variant.k.count {
let s0 = rotateRight(A, by: 28) ^ rotateRight(A, by: 34) ^ rotateRight(A, by: 39)
let maj = (A & B) ^ (A & C) ^ (B & C)
let t2 = s0 &+ maj
let s1 = rotateRight(E, by: 14) ^ rotateRight(E, by: 18) ^ rotateRight(E, by: 41)
let ch = (E & F) ^ ((~E) & G)
let t1 = H &+ s1 &+ ch &+ variant.k[j] &+ UInt64(M[j])
H = G
G = F
F = E
E = D &+ t1
D = C
C = B
B = A
A = t1 &+ t2
}
hh[0] = (hh[0] &+ A)
hh[1] = (hh[1] &+ B)
hh[2] = (hh[2] &+ C)
hh[3] = (hh[3] &+ D)
hh[4] = (hh[4] &+ E)
hh[5] = (hh[5] &+ F)
hh[6] = (hh[6] &+ G)
hh[7] = (hh[7] &+ H)
}
// mutating currentHash in place is way faster than returning new result
fileprivate func process32(block chunk: ArraySlice<UInt8>, currentHash hh: inout Array<UInt32>) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian
// Extend the sixteen 32-bit words into sixty-four 32-bit words:
var M = Array<UInt32>(repeating: 0, count: variant.k.count)
for x in 0..<M.count {
switch (x) {
case 0...15:
let start = chunk.startIndex.advanced(by: x * 4) // * MemoryLayout<UInt32>.size
M[x] = UInt32(bytes: chunk, fromIndex: start)
break
default:
let s0 = rotateRight(M[x-15], by: 7) ^ rotateRight(M[x-15], by: 18) ^ (M[x-15] >> 3)
let s1 = rotateRight(M[x-2], by: 17) ^ rotateRight(M[x-2], by: 19) ^ (M[x-2] >> 10)
M[x] = M[x-16] &+ s0 &+ M[x-7] &+ s1
break
}
}
var A = hh[0]
var B = hh[1]
var C = hh[2]
var D = hh[3]
var E = hh[4]
var F = hh[5]
var G = hh[6]
var H = hh[7]
// Main loop
for j in 0..<variant.k.count {
let s0 = rotateRight(A, by: 2) ^ rotateRight(A, by: 13) ^ rotateRight(A, by: 22)
let maj = (A & B) ^ (A & C) ^ (B & C)
let t2 = s0 &+ maj
let s1 = rotateRight(E, by: 6) ^ rotateRight(E, by: 11) ^ rotateRight(E, by: 25)
let ch = (E & F) ^ ((~E) & G)
let t1 = H &+ s1 &+ ch &+ UInt32(variant.k[j]) &+ M[j]
H = G
G = F
F = E
E = D &+ t1
D = C
C = B
B = A
A = t1 &+ t2
}
hh[0] = hh[0] &+ A
hh[1] = hh[1] &+ B
hh[2] = hh[2] &+ C
hh[3] = hh[3] &+ D
hh[4] = hh[4] &+ E
hh[5] = hh[5] &+ F
hh[6] = hh[6] &+ G
hh[7] = hh[7] &+ H
}
}
extension SHA2: Updatable {
public func update<T: Sequence>(withBytes bytes: T, isLast: Bool = false) throws -> Array<UInt8> where T.Iterator.Element == UInt8 {
let prevAccumulatedLength = self.accumulated.count
self.accumulated += bytes
self.accumulatedLength += self.accumulated.count - prevAccumulatedLength //avoid Array(bytes).count
if isLast {
// Step 1. Append padding
self.accumulated = bitPadding(to: self.accumulated, blockSize: self.blockSize, allowance: self.blockSize / 8)
// Step 2. Append Length a 64-bit representation of lengthInBits
let lengthInBits = self.accumulatedLength * 8
self.accumulated += lengthInBits.bytes(totalBytes: self.blockSize / 8) // A 64-bit/128-bit representation of b. blockSize fit by accident.
}
for chunk in BytesSequence(chunkSize: self.blockSize, data: self.accumulated) {
if (isLast || self.accumulated.count >= self.blockSize) {
switch self.variant {
case .sha224, .sha256:
self.process32(block: chunk, currentHash: &self.accumulatedHash32)
case .sha384, .sha512:
self.process64(block: chunk, currentHash: &self.accumulatedHash64)
}
self.accumulated.removeFirst(chunk.count)
}
}
// output current hash
var result = Array<UInt8>()
result.reserveCapacity(self.variant.digestLength)
switch self.variant {
case .sha224, .sha256:
self.variant.resultingArray(self.accumulatedHash32).forEach { //TODO: rename resultingArray -> resultSlice
let item = $0.bigEndian
result += [UInt8(item & 0xff), UInt8((item >> 8) & 0xff), UInt8((item >> 16) & 0xff), UInt8((item >> 24) & 0xff)]
}
case .sha384, .sha512:
self.variant.resultingArray(self.accumulatedHash64).forEach {
let item = $0.bigEndian
var partialResult = Array<UInt8>()
partialResult.reserveCapacity(8)
for i in 0..<8 {
partialResult.append(UInt8((item >> UInt64(8 * i)) & 0xff))
}
result += partialResult
}
}
// reset hash value for instance
if isLast {
switch self.variant {
case .sha224, .sha256:
self.accumulatedHash32 = variant.h.map { UInt32($0) } //FIXME: UInt64 for process64
case .sha384, .sha512:
self.accumulatedHash64 = variant.h
}
}
return result
}
}
|
mit
|
6406d2c6e725f43f09b5f9b6b7198c80
| 40.389408 | 183 | 0.540945 | 3.104931 | false | false | false | false |
frootloops/swift
|
test/SILGen/switch_var.swift
|
1
|
28452
|
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int, Int), y: (Int, Int)) -> Bool {
return x.0 == y.0 && x.1 == y.1
}
// Some fake predicates for pattern guards.
func runced() -> Bool { return true }
func funged() -> Bool { return true }
func ansed() -> Bool { return true }
func runced(x x: Int) -> Bool { return true }
func funged(x x: Int) -> Bool { return true }
func ansed(x x: Int) -> Bool { return true }
func foo() -> Int { return 0 }
func bar() -> Int { return 0 }
func foobar() -> (Int, Int) { return (0, 0) }
func foos() -> String { return "" }
func bars() -> String { return "" }
func a() {}
func b() {}
func c() {}
func d() {}
func e() {}
func f() {}
func g() {}
func a(x x: Int) {}
func b(x x: Int) {}
func c(x x: Int) {}
func d(x x: Int) {}
func a(x x: String) {}
func b(x x: String) {}
func aa(x x: (Int, Int)) {}
func bb(x x: (Int, Int)) {}
func cc(x x: (Int, Int)) {}
// CHECK-LABEL: sil hidden @_T010switch_var05test_B2_1yyF
func test_var_1() {
// CHECK: function_ref @_T010switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK-NOT: br bb
case var x:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var1aySi1x_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_T010switch_var1byyF
b()
}
// CHECK-LABEL: sil hidden @_T010switch_var05test_B2_2yyF
func test_var_2() {
// CHECK: function_ref @_T010switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var6runcedSbSi1x_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
// -- TODO: Clean up these empty waypoint bbs.
case var x where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var1aySi1x_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var6fungedSbSi1x_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case var y where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var1bySi1x_tF
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: br [[CASE3:bb[0-9]+]]
case var z:
// CHECK: [[CASE3]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var1cySi1x_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK: br [[CONT]]
c(x: z)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_T010switch_var1dyyF
d()
}
// CHECK-LABEL: sil hidden @_T010switch_var05test_B2_3yyF
func test_var_3() {
// CHECK: function_ref @_T010switch_var3fooSiyF
// CHECK: function_ref @_T010switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: function_ref @_T010switch_var6runcedSbSi1x_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var2aaySi_Sit1x_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
aa(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: br [[NO_CASE1_TARGET:bb[0-9]+]]
// CHECK: [[NO_CASE1_TARGET]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var6fungedSbSi1x_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var1aySi1x_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var1bySi1x_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
a(x: y)
b(x: z)
// CHECK: [[NO_CASE2]]:
// CHECK: [[WADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: function_ref @_T010switch_var5ansedSbSi1x_tF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case var w where ansed(x: w.0):
// CHECK: [[CASE3]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var2bbySi_Sit1x_tF
// CHECK: br [[CONT]]
bb(x: w)
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[WADDR]]
// CHECK: br [[CASE4:bb[0-9]+]]
case var v:
// CHECK: [[CASE4]]:
// CHECK: [[VADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%.*]] = project_box [[VADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[V]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var2ccySi_Sit1x_tF
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[CONT]]
cc(x: v)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @_T010switch_var1dyyF
d()
}
protocol P { func p() }
struct X : P { func p() {} }
struct Y : P { func p() {} }
struct Z : P { func p() {} }
// CHECK-LABEL: sil hidden @_T010switch_var05test_B2_4yAA1P_p1p_tF
func test_var_4(p p: P) {
// CHECK: function_ref @_T010switch_var3fooSiyF
switch (p, foo()) {
// CHECK: [[PAIR:%.*]] = alloc_stack $(P, Int)
// CHECK: store
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[T0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 1
// CHECK: [[PAIR_1:%.*]] = load [trivial] [[T0]] : $*Int
// CHECK: [[TMP:%.*]] = alloc_stack $X
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to X in [[TMP]] : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
// CHECK: [[IS_X]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*X
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[X]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var6runcedSbSi1x_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case (is X, var x) where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: function_ref @_T010switch_var1aySi1x_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_X]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[TMP:%.*]] = alloc_stack $Y
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to Y in [[TMP]] : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]]
// CHECK: [[IS_Y]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*Y
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[Y]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var6fungedSbSi1x_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (is Y, var y) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var1bySi1x_tF
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_Y]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var (P, Int) }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: function_ref @_T010switch_var5ansedSbSi1x_tF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[DFLT_NO_CASE3:bb[0-9]+]]
case var z where ansed(x: z.1):
// CHECK: [[CASE3]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: function_ref @_T010switch_var1cySi1x_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK-NEXT: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
c(x: z.1)
// CHECK: [[DFLT_NO_CASE3]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: br [[CASE4:bb[0-9]+]]
case (_, var w):
// CHECK: [[CASE4]]:
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[WADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @_T010switch_var1dySi1x_tF
// CHECK: destroy_value [[WADDR]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
d(x: w)
}
e()
}
// CHECK-LABEL: sil hidden @_T010switch_var05test_B2_5yyF : $@convention(thin) () -> () {
func test_var_5() {
// CHECK: function_ref @_T010switch_var3fooSiyF
// CHECK: function_ref @_T010switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b()
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case (_, _) where runced():
// CHECK: [[CASE3]]:
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK: br [[CASE4:bb[0-9]+]]
case _:
// CHECK: [[CASE4]]:
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
e()
}
// CHECK-LABEL: sil hidden @_T010switch_var05test_B7_returnyyF : $@convention(thin) () -> () {
func test_var_return() {
switch (foo(), bar()) {
case var x where runced():
// CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%[0-9]+]] = project_box [[XADDR]]
// CHECK: function_ref @_T010switch_var1ayyF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[EPILOG:bb[0-9]+]]
a()
return
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
case (var y, var z) where funged():
// CHECK: function_ref @_T010switch_var1byyF
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[EPILOG]]
b()
return
case var w where ansed():
// CHECK: [[WADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%[0-9]+]] = project_box [[WADDR]]
// CHECK: function_ref @_T010switch_var1cyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[WADDR]]
// CHECK: br [[EPILOG]]
c()
return
case var v:
// CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%[0-9]+]] = project_box [[VADDR]]
// CHECK: function_ref @_T010switch_var1dyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[EPILOG]]
d()
return
}
}
// When all of the bindings in a column are immutable, don't emit a mutable
// box. <rdar://problem/15873365>
// CHECK-LABEL: sil hidden @_T010switch_var8test_letyyF : $@convention(thin) () -> () {
func test_let() {
// CHECK: [[FOOS:%.*]] = function_ref @_T010switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: function_ref @_T010switch_var6runcedSbyF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
switch foos() {
case let x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[VAL_COPY_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY]]
// CHECK: [[A:%.*]] = function_ref @_T010switch_var1aySS1x_tF
// CHECK: apply [[A]]([[VAL_COPY_COPY]])
// CHECK: end_borrow [[BORROWED_VAL_COPY]] from [[VAL_COPY]]
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: br [[TRY_CASE2:bb[0-9]+]]
// CHECK: [[TRY_CASE2]]:
// CHECK: [[VAL_COPY_2:%.*]] = copy_value [[VAL]]
// CHECK: function_ref @_T010switch_var6fungedSbyF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[BORROWED_VAL_COPY_2:%.*]] = begin_borrow [[VAL_COPY_2]]
// CHECK: [[VAL_COPY_2_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY_2]]
// CHECK: [[B:%.*]] = function_ref @_T010switch_var1bySS1x_tF
// CHECK: apply [[B]]([[VAL_COPY_2_COPY]])
// CHECK: end_borrow [[BORROWED_VAL_COPY_2]] from [[VAL_COPY_2]]
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: br [[NEXT_CASE:bb6]]
// CHECK: [[NEXT_CASE]]:
// CHECK: [[VAL_COPY_3:%.*]] = copy_value [[VAL]]
// CHECK: function_ref @_T010switch_var4barsSSyF
// CHECK: [[BORROWED_VAL_COPY_3:%.*]] = begin_borrow [[VAL_COPY_3]]
// CHECK: [[VAL_COPY_3_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY_3]]
// CHECK: store [[VAL_COPY_3_COPY]] to [init] [[IN_ARG:%.*]] :
// CHECK: apply {{%.*}}<String>({{.*}}, [[IN_ARG]])
// CHECK: cond_br {{%.*}}, [[YES_CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
// ExprPatterns implicitly contain a 'let' binding.
case bars():
// CHECK: [[YES_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: destroy_value [[VAL]]
// CHECK: function_ref @_T010switch_var1cyyF
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: br [[NEXT_CASE:bb9+]]
// CHECK: [[NEXT_CASE]]:
case _:
// CHECK: destroy_value [[VAL]]
// CHECK: function_ref @_T010switch_var1dyyF
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '_T010switch_var8test_letyyF'
// If one of the bindings is a "var", allocate a box for the column.
// CHECK-LABEL: sil hidden @_T010switch_var015test_mixed_let_B0yyF : $@convention(thin) () -> () {
func test_mixed_let_var() {
// CHECK: bb0:
// CHECK: [[FOOS:%.*]] = function_ref @_T010switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
switch foos() {
// First pattern.
// CHECK: [[BOX:%.*]] = alloc_box ${ var String }, var, name "x"
// CHECK: [[PBOX:%.*]] = project_box [[BOX]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: store [[VAL_COPY]] to [init] [[PBOX]]
// CHECK: cond_br {{.*}}, [[CASE1:bb[0-9]+]], [[NOCASE1:bb[0-9]+]]
case var x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOX]]
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[A:%.*]] = function_ref @_T010switch_var1aySS1x_tF
// CHECK: apply [[A]]([[X]])
// CHECK: destroy_value [[BOX]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NOCASE1]]:
// CHECK: destroy_value [[BOX]]
// CHECK: br [[NEXT_PATTERN:bb[0-9]+]]
// CHECK: [[NEXT_PATTERN]]:
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: cond_br {{.*}}, [[CASE2:bb[0-9]+]], [[NOCASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[VAL_COPY_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY]]
// CHECK: [[B:%.*]] = function_ref @_T010switch_var1bySS1x_tF
// CHECK: apply [[B]]([[VAL_COPY_COPY]])
// CHECK: end_borrow [[BORROWED_VAL_COPY]] from [[VAL_COPY]]
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NOCASE2]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: br [[NEXT_CASE:bb[0-9]+]]
// CHECK: [[NEXT_CASE]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[VAL_COPY_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY]]
// CHECK: store [[VAL_COPY_COPY]] to [init] [[TMP_VAL_COPY_ADDR:%.*]] : $*String
// CHECK: apply {{.*}}<String>({{.*}}, [[TMP_VAL_COPY_ADDR]])
// CHECK: cond_br {{.*}}, [[CASE3:bb[0-9]+]], [[NOCASE3:bb[0-9]+]]
case bars():
// CHECK: [[CASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: [[FUNC:%.*]] = function_ref @_T010switch_var1cyyF : $@convention(thin) () -> ()
// CHECK: apply [[FUNC]]()
// CHECK: br [[CONT]]
c()
// CHECK: [[NOCASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: br [[NEXT_CASE:bb[0-9]+]]
// CHECK: [[NEXT_CASE]]:
// CHECK: destroy_value [[VAL]]
// CHECK: [[D_FUNC:%.*]] = function_ref @_T010switch_var1dyyF : $@convention(thin) () -> ()
// CHECK: apply [[D_FUNC]]()
// CHECK: br [[CONT]]
case _:
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '_T010switch_var015test_mixed_let_B0yyF'
// CHECK-LABEL: sil hidden @_T010switch_var23test_multiple_patterns1yyF : $@convention(thin) () -> () {
func test_multiple_patterns1() {
// CHECK: function_ref @_T010switch_var6foobarSi_SityF
switch foobar() {
// CHECK-NOT: br bb
case (0, let x), (let x, 0):
// CHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// CHECK: [[FIRST_MATCH_CASE]]:
// CHECK: debug_value [[FIRST_X:%.*]] :
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[FIRST_X]] : $Int)
// CHECK: [[FIRST_FAIL]]:
// CHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// CHECK: [[SECOND_MATCH_CASE]]:
// CHECK: debug_value [[SECOND_X:%.*]] :
// CHECK: br [[CASE_BODY]]([[SECOND_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// CHECK: [[A:%.*]] = function_ref @_T010switch_var1aySi1x_tF
// CHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// CHECK: [[SECOND_FAIL]]:
// CHECK: function_ref @_T010switch_var1byyF
b()
}
}
// FIXME(integers): the following checks should be updated for the new integer
// protocols. <rdar://problem/29939484>
// XCHECK-LABEL: sil hidden @_T010switch_var23test_multiple_patterns2yyF : $@convention(thin) () -> () {
func test_multiple_patterns2() {
let t1 = 2
let t2 = 4
// XCHECK: debug_value [[T1:%.*]] :
// XCHECK: debug_value [[T2:%.*]] :
switch (0,0) {
// XCHECK-NOT: br bb
case (_, let x) where x > t1, (let x, _) where x > t2:
// XCHECK: [[FIRST_X:%.*]] = tuple_extract {{%.*}} : $(Int, Int), 1
// XCHECK: debug_value [[FIRST_X]] :
// XCHECK: apply {{%.*}}([[FIRST_X]], [[T1]])
// XCHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// XCHECK: [[FIRST_MATCH_CASE]]:
// XCHECK: br [[CASE_BODY:bb[0-9]+]]([[FIRST_X]] : $Int)
// XCHECK: [[FIRST_FAIL]]:
// XCHECK: debug_value [[SECOND_X:%.*]] :
// XCHECK: apply {{%.*}}([[SECOND_X]], [[T2]])
// XCHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// XCHECK: [[SECOND_MATCH_CASE]]:
// XCHECK: br [[CASE_BODY]]([[SECOND_X]] : $Int)
// XCHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// XCHECK: [[A:%.*]] = function_ref @_T010switch_var1aySi1x_tF
// XCHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// XCHECK: [[SECOND_FAIL]]:
// XCHECK: function_ref @_T010switch_var1byyF
b()
}
}
enum Foo {
case A(Int, Double)
case B(Double, Int)
case C(Int, Int, Double)
}
// CHECK-LABEL: sil hidden @_T010switch_var23test_multiple_patterns3yyF : $@convention(thin) () -> () {
func test_multiple_patterns3() {
let f = Foo.C(0, 1, 2.0)
switch f {
// CHECK: switch_enum {{%.*}} : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
case .A(let x, let n), .B(let n, let x), .C(_, let x, let n):
// CHECK: [[A]]({{%.*}} : $(Int, Double)):
// CHECK: [[A_X:%.*]] = tuple_extract
// CHECK: [[A_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int, [[A_N]] : $Double)
// CHECK: [[B]]({{%.*}} : $(Double, Int)):
// CHECK: [[B_N:%.*]] = tuple_extract
// CHECK: [[B_X:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int, [[B_N]] : $Double)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: [[C__:%.*]] = tuple_extract
// CHECK: [[C_X:%.*]] = tuple_extract
// CHECK: [[C_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[C_X]] : $Int, [[C_N]] : $Double)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int, [[BODY_N:%.*]] : $Double):
// CHECK: [[FUNC_A:%.*]] = function_ref @_T010switch_var1aySi1x_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
enum Bar {
case Y(Foo, Int)
case Z(Int, Foo)
}
// CHECK-LABEL: sil hidden @_T010switch_var23test_multiple_patterns4yyF : $@convention(thin) () -> () {
func test_multiple_patterns4() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]]
case .Y(.A(let x, _), _), .Y(.B(_, let x), _), .Y(.C, let x), .Z(let x, _):
// CHECK: [[Y]]({{%.*}} : $(Foo, Int)):
// CHECK: [[Y_F:%.*]] = tuple_extract
// CHECK: [[Y_X:%.*]] = tuple_extract
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
// CHECK: [[A]]({{%.*}} : $(Int, Double)):
// CHECK: [[A_X:%.*]] = tuple_extract
// CHECK: [[A_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]({{%.*}} : $(Double, Int)):
// CHECK: [[B_N:%.*]] = tuple_extract
// CHECK: [[B_X:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]({{%.*}} : $(Int, Foo)):
// CHECK: [[Z_X:%.*]] = tuple_extract
// CHECK: [[Z_F:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: [[FUNC_A:%.*]] = function_ref @_T010switch_var1aySi1x_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
func aaa(x x: inout Int) {}
// CHECK-LABEL: sil hidden @_T010switch_var23test_multiple_patterns5yyF : $@convention(thin) () -> () {
func test_multiple_patterns5() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]]
case .Y(.A(var x, _), _), .Y(.B(_, var x), _), .Y(.C, var x), .Z(var x, _):
// CHECK: [[Y]]({{%.*}} : $(Foo, Int)):
// CHECK: [[Y_F:%.*]] = tuple_extract
// CHECK: [[Y_X:%.*]] = tuple_extract
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
// CHECK: [[A]]({{%.*}} : $(Int, Double)):
// CHECK: [[A_X:%.*]] = tuple_extract
// CHECK: [[A_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]({{%.*}} : $(Double, Int)):
// CHECK: [[B_N:%.*]] = tuple_extract
// CHECK: [[B_X:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]({{%.*}} : $(Int, Foo)):
// CHECK: [[Z_X:%.*]] = tuple_extract
// CHECK: [[Z_F:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: store [[BODY_X]] to [trivial] [[BOX_X:%.*]] : $*Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOX_X]]
// CHECK: [[FUNC_AAA:%.*]] = function_ref @_T010switch_var3aaaySiz1x_tF
// CHECK: apply [[FUNC_AAA]]([[WRITE]])
aaa(x: &x)
}
}
// rdar://problem/29252758 -- local decls must not be reemitted.
func test_against_reemission(x: Bar) {
switch x {
case .Y(let a, _), .Z(_, let a):
let b = a
}
}
class C {}
class D: C {}
func f(_: D) -> Bool { return true }
// CHECK-LABEL: sil hidden @{{.*}}test_multiple_patterns_value_semantics
func test_multiple_patterns_value_semantics(_ y: C) {
switch y {
// CHECK: checked_cast_br {{%.*}} : $C to $D, [[AS_D:bb[0-9]+]], [[NOT_AS_D:bb[0-9]+]]
// CHECK: [[AS_D]]({{.*}}):
// CHECK: cond_br {{%.*}}, [[F_TRUE:bb[0-9]+]], [[F_FALSE:bb[0-9]+]]
// CHECK: [[F_TRUE]]:
// CHECK: [[BINDING:%.*]] = copy_value [[ORIG:%.*]] :
// CHECK: destroy_value [[ORIG]]
// CHECK: br {{bb[0-9]+}}([[BINDING]]
case let x as D where f(x), let x as D: break
default: break
}
}
|
apache-2.0
|
cdec67ee28eee33c4f3aafc40947a235
| 36.634921 | 161 | 0.51188 | 2.858923 | false | false | false | false |
vuchau/iRemind
|
iRemind/ReminderInfoVC.swift
|
2
|
4408
|
//
// ReminderInfoVC.swift
// iRemind
//
// Created by Vijay Subrahmanian on 03/06/15.
// Copyright (c) 2015 Vijay Subrahmanian. All rights reserved.
//
import UIKit
protocol ReminderUpdateProtocol : NSObjectProtocol {
func reminderUpdatedAtIndex(index: Int);
func reminderDeletedAtIndex(index: Int);
func remainderAdded();
}
class ReminderInfoVC: UIViewController {
var delegate: ReminderUpdateProtocol?
var reminderInfo: ReminderInfoModel?
var index: Int?
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var detailsTextView: UITextView!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var deleteReminderButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
if self.reminderInfo == nil {
self.reminderInfo = ReminderInfoModel()
}
if self.index != nil {
let rightBarButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Save, target: self, action: Selector("saveReminder"))
self.navigationItem.rightBarButtonItem = rightBarButton
} else {
let rightBarButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: Selector("addReminder"))
self.navigationItem.rightBarButtonItem = rightBarButton
self.deleteReminderButton.hidden = true
}
// Set the selected values.
self.nameTextField.text = self.reminderInfo?.name
self.detailsTextView.text = self.reminderInfo?.details
self.datePicker.minimumDate = NSDate().dateByAddingTimeInterval(60*2)
if let setDate = self.reminderInfo?.time {
self.datePicker.setDate(setDate, animated: false)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func deleteReminderPressed(sender: UIButton) {
self.deleteReminder()
self.navigationController?.popViewControllerAnimated(true)
}
@IBAction func dismissKeyboard(sender: UITapGestureRecognizer) {
self.nameTextField.resignFirstResponder()
self.detailsTextView.resignFirstResponder()
}
func updateReminderModel() {
if self.datePicker.date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
// If the time is past. Throw an alert.
UIAlertView(title: "Error", message: "Cannot set reminder for an earlier time", delegate: nil, cancelButtonTitle: "OK")
self.datePicker.setDate(NSDate().dateByAddingTimeInterval(60*2), animated: true)
return
}
self.reminderInfo?.name = self.nameTextField.text
self.reminderInfo?.details = self.detailsTextView.text
self.reminderInfo?.time = self.datePicker.date
// Calling local methid from which we are scheduling the notification.
self.scheduleNotification()
}
func addReminder() {
self.updateReminderModel()
(UIApplication.sharedApplication().delegate as! AppDelegate).reminderList.insert(self.reminderInfo!, atIndex: 0)
self.navigationController?.popViewControllerAnimated(true)
}
func saveReminder() {
self.updateReminderModel()
self.navigationController?.popViewControllerAnimated(true)
}
func deleteReminder() {
if self.index != nil {
(UIApplication.sharedApplication().delegate as! AppDelegate).reminderList.removeAtIndex(self.index!)
}
self.navigationController?.popViewControllerAnimated(true)
}
func scheduleNotification() {
// Create reminder by setting a local notification
let localNotification = UILocalNotification()
localNotification.alertTitle = self.reminderInfo?.name
localNotification.alertBody = self.reminderInfo?.details
localNotification.alertAction = "ShowDetails"
localNotification.fireDate = self.reminderInfo?.time
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.applicationIconBadgeNumber = 1
localNotification.category = "reminderCategory"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
}
|
apache-2.0
|
dcc922502b63bea1f99cc11d956f9f9f
| 36.683761 | 145 | 0.685572 | 5.503121 | false | false | false | false |
rajeshmud/CLChart
|
CLApp/CLCharts/CLCharts/Charts/CLAxisValue.swift
|
1
|
8233
|
//
// CLAxisValuesString.swift
// CLCharts
//
// Created by Rajesh Mudaliyar on 11/09/15.
// Copyright © 2015 Rajesh Mudaliyar. All rights reserved.
//
import UIKit
public class CLAxisValue: Equatable {
public var scalar: Double
public var text: String {
fatalError("Override")
}
/**
Labels that will be displayed on the chart. How this is done depends on the implementation of CLAxisLayer.
In the most common case this will be an array with only one element.
*/
public var labels: [CLAxisLabel] {
fatalError("Override")
}
public var hidden: Bool = false {
didSet {
for label in self.labels {
label.hidden = self.hidden
}
}
}
public init(scalar: Double) {
self.scalar = scalar
}
public var copy: CLAxisValue {
return self.copy(self.scalar)
}
public func copy(scalar: Double) -> CLAxisValue {
return CLAxisValue(scalar: self.scalar)
}
public func divideBy(dev:Int) {
scalar = scalar/Double(dev)
}
}
public func ==(lhs: CLAxisValue, rhs: CLAxisValue) -> Bool {
return lhs.scalar == rhs.scalar
}
public func +=(lhs: CLAxisValue, rhs: CLAxisValue) -> CLAxisValue {
lhs.scalar += rhs.scalar
return lhs
}
public func <=(lhs: CLAxisValue, rhs: CLAxisValue) -> Bool {
return lhs.scalar <= rhs.scalar
}
public func >(lhs: CLAxisValue, rhs: CLAxisValue) -> Bool {
return lhs.scalar > rhs.scalar
}
public class CLAxisValueDate: CLAxisValue {
private let formatter: NSDateFormatter
private let labelSettings: CLLabelSettings
public var date: NSDate {
return CLAxisValueDate.dateFromScalar(self.scalar)
}
public init(date: NSDate, formatter: NSDateFormatter, labelSettings: CLLabelSettings = CLLabelSettings()) {
self.formatter = formatter
self.labelSettings = labelSettings
super.init(scalar: CLAxisValueDate.scalarFromDate(date))
}
override public var labels: [CLAxisLabel] {
let axisLabel = CLAxisLabel(text: self.formatter.stringFromDate(self.date), settings: self.labelSettings)
axisLabel.hidden = self.hidden
return [axisLabel]
}
public class func dateFromScalar(scalar: Double) -> NSDate {
return NSDate(timeIntervalSince1970: NSTimeInterval(scalar))
}
public class func scalarFromDate(date: NSDate) -> Double {
return Double(date.timeIntervalSince1970)
}
}
public class CLAxisValueDouble: CLAxisValue {
public let formatter: NSNumberFormatter
let labelSettings: CLLabelSettings
override public var text: String {
return self.formatter.stringFromNumber(self.scalar)!
}
public convenience init(_ int: Int, formatter: NSNumberFormatter = CLAxisValueDouble.defaultFormatter, labelSettings: CLLabelSettings = CLLabelSettings()) {
self.init(Double(int), formatter: formatter, labelSettings: labelSettings)
}
public init(_ double: Double, formatter: NSNumberFormatter = CLAxisValueDouble.defaultFormatter, labelSettings: CLLabelSettings = CLLabelSettings()) {
self.formatter = formatter
self.labelSettings = labelSettings
super.init(scalar: double)
}
override public var labels: [CLAxisLabel] {
let axisLabel = CLAxisLabel(text: self.text, settings: self.labelSettings)
return [axisLabel]
}
override public func copy(scalar: Double) -> CLAxisValueDouble {
return CLAxisValueDouble(scalar, formatter: self.formatter, labelSettings: self.labelSettings)
}
static var defaultFormatter: NSNumberFormatter = {
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 2
return formatter
}()
}
public class CLAxisValueDoubleScreenLoc: CLAxisValueDouble {
private let actualDouble: Double
var screenLocDouble: Double {
return self.scalar
}
override public var text: String {
return self.formatter.stringFromNumber(self.actualDouble)!
}
// screenLocFloat: model value which will be used to calculate screen position
// actualFloat: scalar which this axis value really represents
public init(screenLocDouble: Double, actualDouble: Double, formatter: NSNumberFormatter = CLAxisValueFloat.defaultFormatter, labelSettings: CLLabelSettings = CLLabelSettings()) {
self.actualDouble = actualDouble
super.init(screenLocDouble, formatter: formatter, labelSettings: labelSettings)
}
override public var labels: [CLAxisLabel] {
let axisLabel = CLAxisLabel(text: self.text, settings: self.labelSettings)
return [axisLabel]
}
}
public class CLAxisValueFloat: CLAxisValue {
public let formatter: NSNumberFormatter
let labelSettings: CLLabelSettings
public var float: CGFloat {
return CGFloat(self.scalar)
}
override public var text: String {
return self.formatter.stringFromNumber(self.float)!
}
public init(_ float: CGFloat, formatter: NSNumberFormatter = CLAxisValueFloat.defaultFormatter, labelSettings: CLLabelSettings = CLLabelSettings()) {
self.formatter = formatter
self.labelSettings = labelSettings
super.init(scalar: Double(float))
}
override public var labels: [CLAxisLabel] {
let axisLabel = CLAxisLabel(text: self.text, settings: self.labelSettings)
return [axisLabel]
}
override public func copy(scalar: Double) -> CLAxisValueFloat {
return CLAxisValueFloat(CGFloat(scalar), formatter: self.formatter, labelSettings: self.labelSettings)
}
static var defaultFormatter: NSNumberFormatter = {
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 2
return formatter
}()
}
@available(*, deprecated=0.2.5, message="use CLAxisValueDoubleScreenLoc instead")
public class CLAxisValueFloatScreenLoc: CLAxisValueFloat {
private let actualFloat: CGFloat
var screenLocFloat: CGFloat {
return CGFloat(self.scalar)
}
override public var text: String {
return self.formatter.stringFromNumber(self.actualFloat)!
}
// screenLocFloat: model value which will be used to calculate screen position
// actualFloat: scalar which this axis value really represents
public init(screenLocFloat: CGFloat, actualFloat: CGFloat, formatter: NSNumberFormatter = CLAxisValueFloat.defaultFormatter, labelSettings: CLLabelSettings = CLLabelSettings()) {
self.actualFloat = actualFloat
super.init(screenLocFloat, formatter: formatter, labelSettings: labelSettings)
}
override public var labels: [CLAxisLabel] {
let axisLabel = CLAxisLabel(text: self.text, settings: self.labelSettings)
return [axisLabel]
}
}
public class CLAxisValueInt: CLAxisValue {
public let int: Int
private let labelSettings: CLLabelSettings
override public var text: String {
return "\(self.int)"
}
public init(_ int: Int, labelSettings: CLLabelSettings = CLLabelSettings()) {
self.int = int
self.labelSettings = labelSettings
super.init(scalar: Double(int))
}
override public var labels:[CLAxisLabel] {
let axisLabel = CLAxisLabel(text: self.text, settings: self.labelSettings)
return [axisLabel]
}
override public func copy(scalar: Double) -> CLAxisValueInt {
return CLAxisValueInt(self.int, labelSettings: self.labelSettings)
}
}
public class CLAxisValueString: CLAxisValue {
let string: String
private let labelSettings: CLLabelSettings
public init(_ string: String = "", order: Int, labelSettings: CLLabelSettings = CLLabelSettings()) {
self.string = string
self.labelSettings = labelSettings
super.init(scalar: Double(order))
}
override public var labels: [CLAxisLabel] {
let axisLabel = CLAxisLabel(text: self.string, settings: self.labelSettings)
return [axisLabel]
}
}
|
mit
|
394cc07bf81bbb29286e95d10fc3eaee
| 30.661538 | 182 | 0.676263 | 4.712078 | false | false | false | false |
JGiola/swift-corelibs-foundation
|
Foundation/NSOrderedSet.swift
|
1
|
19662
|
// 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
//
/**************** Immutable Ordered Set ****************/
open class NSOrderedSet : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, ExpressibleByArrayLiteral {
internal var _storage: Set<NSObject>
internal var _orderedStorage: [NSObject]
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
NSUnimplemented()
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
NSUnimplemented()
}
public static var supportsSecureCoding: Bool {
return true
}
open override func isEqual(_ object: Any?) -> Bool {
guard let orderedSet = object as? NSOrderedSet else { return false }
return isEqual(to: orderedSet)
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
for idx in _indices {
aCoder.encode(__SwiftValue.store(self.object(at: idx)), forKey:"NS.object.\(idx)")
}
}
public required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
var idx = 0
var objects : [AnyObject] = []
while aDecoder.containsValue(forKey: ("NS.object.\(idx)")) {
guard let object = aDecoder.decodeObject(forKey: "NS.object.\(idx)") else {
return nil
}
objects.append(object as! NSObject)
idx += 1
}
self.init(array: objects)
}
open var count: Int {
return _storage.count
}
open func object(at idx: Int) -> Any {
_validateSubscript(idx)
return __SwiftValue.fetch(nonOptional: _orderedStorage[idx])
}
open func index(of object: Any) -> Int {
return _orderedStorage.index(of: __SwiftValue.store(object)) ?? NSNotFound
}
public convenience override init() {
self.init(objects: [], count: 0)
}
public init(objects: UnsafePointer<AnyObject>!, count cnt: Int) {
_storage = Set<NSObject>()
_orderedStorage = [NSObject]()
super.init()
_insertObjects(objects, count: cnt)
}
required public convenience init(arrayLiteral elements: Any...) {
self.init(array: elements)
}
public convenience init(objects elements: Any...) {
self.init(array: elements)
}
open subscript (idx: Int) -> Any {
return object(at: idx)
}
fileprivate func _insertObject(_ object: Any) {
let value = __SwiftValue.store(object)
guard !contains(value) else {
return
}
_storage.insert(value)
_orderedStorage.append(value)
}
fileprivate func _insertObjects(_ objects: UnsafePointer<AnyObject>!, count cnt: Int) {
let buffer = UnsafeBufferPointer(start: objects, count: cnt)
for obj in buffer {
_insertObject(obj)
}
}
internal var allObjects: [Any] {
if type(of: self) === NSOrderedSet.self || type(of: self) === NSMutableOrderedSet.self {
return _orderedStorage.map { __SwiftValue.fetch(nonOptional: $0) }
} else {
return _indices.map { idx in
return self[idx]
}
}
}
/// The range of indices that are valid for subscripting the ordered set.
internal var _indices: Range<Int> {
return 0..<count
}
/// Checks that an index is valid for subscripting: 0 ≤ `index` < `count`.
internal func _validateSubscript(_ index: Int, file: StaticString = #file, line: UInt = #line) {
precondition(_indices.contains(index), "\(self): Index out of bounds", file: file, line: line)
}
}
extension NSOrderedSet : Sequence {
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public typealias Iterator = NSEnumerator.Iterator
public func makeIterator() -> Iterator {
return self.objectEnumerator().makeIterator()
}
}
extension NSOrderedSet {
public func getObjects(_ objects: inout [AnyObject], range: NSRange) {
for idx in range.location..<(range.location + range.length) {
objects.append(_orderedStorage[idx])
}
}
/// Returns an array with the objects at the specified indexes in the
/// ordered set.
///
/// - Parameter indexes: The indexes.
/// - Returns: An array of objects in the ascending order of their indexes
/// in `indexes`.
///
/// - Complexity: O(*n*), where *n* is the number of indexes in `indexes`.
/// - Precondition: The indexes in `indexes` are within the
/// bounds of the ordered set.
open func objects(at indexes: IndexSet) -> [Any] {
return indexes.map { object(at: $0) }
}
public var firstObject: Any? {
if let value = _orderedStorage.first {
return __SwiftValue.fetch(nonOptional: value)
} else {
return nil
}
}
public var lastObject: Any? {
if let value = _orderedStorage.last {
return __SwiftValue.fetch(nonOptional: value)
} else {
return nil
}
}
open func isEqual(to other: NSOrderedSet) -> Bool {
if count != other.count {
return false
}
for idx in _indices {
if let value1 = object(at: idx) as? AnyHashable,
let value2 = other.object(at: idx) as? AnyHashable {
if value1 != value2 {
return false
}
}
}
return true
}
open func contains(_ object: Any) -> Bool {
return _storage.contains(__SwiftValue.store(object))
}
open func intersects(_ other: NSOrderedSet) -> Bool {
if count < other.count {
return contains { obj in other.contains(obj) }
} else {
return other.contains { obj in contains(obj) }
}
}
open func intersectsSet(_ set: Set<AnyHashable>) -> Bool {
if count < set.count {
return contains { obj in set.contains(obj) }
} else {
return set.contains { obj in contains(obj) }
}
}
open func isSubset(of other: NSOrderedSet) -> Bool {
// If self is larger then self cannot be a subset of other
if count > other.count {
return false
}
for item in self {
if !other.contains(item) {
return false
}
}
return true
}
open func isSubset(of set: Set<AnyHashable>) -> Bool {
// If self is larger then self cannot be a subset of set
if count > set.count {
return false
}
for item in self {
if !set.contains(item as! AnyHashable) {
return false
}
}
return true
}
public func objectEnumerator() -> NSEnumerator {
guard type(of: self) === NSOrderedSet.self || type(of: self) === NSMutableOrderedSet.self else {
NSRequiresConcreteImplementation()
}
return NSGeneratorEnumerator(_orderedStorage.map { __SwiftValue.fetch(nonOptional: $0) }.makeIterator())
}
public func reverseObjectEnumerator() -> NSEnumerator {
guard type(of: self) === NSOrderedSet.self || type(of: self) === NSMutableOrderedSet.self else {
NSRequiresConcreteImplementation()
}
return NSGeneratorEnumerator(_orderedStorage.map { __SwiftValue.fetch(nonOptional: $0) }.reversed().makeIterator())
}
/*@NSCopying*/
public var reversed: NSOrderedSet {
return NSOrderedSet(array: _orderedStorage.map { __SwiftValue.fetch(nonOptional: $0) }.reversed())
}
// These two methods return a facade object for the receiving ordered set,
// which acts like an immutable array or set (respectively). Note that
// while you cannot mutate the ordered set through these facades, mutations
// to the original ordered set will "show through" the facade and it will
// appear to change spontaneously, since a copy of the ordered set is not
// being made.
public var array: [Any] { NSUnimplemented() }
public var set: Set<AnyHashable> { NSUnimplemented() }
open func enumerateObjects(_ block: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { NSUnimplemented() }
open func enumerateObjects(options opts: NSEnumerationOptions = [], using block: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { NSUnimplemented() }
open func enumerateObjects(at s: IndexSet, options opts: NSEnumerationOptions = [], using block: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { NSUnimplemented() }
open func index(ofObjectPassingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { NSUnimplemented() }
open func index(_ opts: NSEnumerationOptions = [], ofObjectPassingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { NSUnimplemented() }
open func index(ofObjectAt s: IndexSet, options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { NSUnimplemented() }
open func indexes(ofObjectsPassingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet { NSUnimplemented() }
open func indexes(options opts: NSEnumerationOptions = [], ofObjectsPassingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet { NSUnimplemented() }
open func indexes(ofObjectsAt s: IndexSet, options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet { NSUnimplemented() }
open func index(of object: Any, inSortedRange range: NSRange, options opts: NSBinarySearchingOptions = [], usingComparator cmp: (Any, Any) -> ComparisonResult) -> Int { NSUnimplemented() } // binary search
open func sortedArray(comparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] { NSUnimplemented() }
open func sortedArray(options opts: NSSortOptions = [], usingComparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] { NSUnimplemented() }
public func description(withLocale locale: Locale?) -> String { NSUnimplemented() }
public func description(withLocale locale: Locale?, indent level: Int) -> String { NSUnimplemented() }
}
extension NSOrderedSet {
public convenience init(object: Any) {
self.init(array: [object])
}
public convenience init(orderedSet set: NSOrderedSet) {
self.init(orderedSet: set, copyItems: false)
}
public convenience init(orderedSet set: NSOrderedSet, copyItems flag: Bool) {
self.init(orderedSet: set, range: NSRange(location: 0, length: set.count), copyItems: flag)
}
public convenience init(orderedSet set: NSOrderedSet, range: NSRange, copyItems flag: Bool) {
// TODO: Use the array method here when available.
self.init(array: Array(set), range: range, copyItems: flag)
}
public convenience init(array: [Any]) {
let buffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: array.count)
for (idx, element) in array.enumerated() {
buffer.advanced(by: idx).initialize(to: __SwiftValue.store(element))
}
self.init(objects: buffer, count: array.count)
buffer.deinitialize(count: array.count)
buffer.deallocate()
}
public convenience init(array set: [Any], copyItems flag: Bool) {
self.init(array: set, range: NSRange(location: 0, length: set.count), copyItems: flag)
}
public convenience init(array set: [Any], range: NSRange, copyItems flag: Bool) {
var objects = set
if let range = Range(range), range.count != set.count || flag {
objects = [Any]()
for index in range.indices {
let object = set[index]
objects.append(flag ? (object as! NSObject).copy() : object)
}
}
self.init(array: objects)
}
public convenience init(set: Set<AnyHashable>) {
self.init(set: set, copyItems: false)
}
public convenience init(set: Set<AnyHashable>, copyItems flag: Bool) {
self.init(array: Array(set), copyItems: flag)
}
}
/**************** Mutable Ordered Set ****************/
open class NSMutableOrderedSet : NSOrderedSet {
open func insert(_ object: Any, at idx: Int) {
precondition(idx <= count && idx >= 0, "\(self): Index out of bounds")
let value = __SwiftValue.store(object)
if contains(value) {
return
}
_storage.insert(value)
_orderedStorage.insert(value, at: idx)
}
open func removeObject(at idx: Int) {
_validateSubscript(idx)
_storage.remove(_orderedStorage[idx])
_orderedStorage.remove(at: idx)
}
open func replaceObject(at idx: Int, with obj: Any) {
let value = __SwiftValue.store(obj)
let objectToReplace = __SwiftValue.store(object(at: idx))
_orderedStorage[idx] = value
_storage.remove(objectToReplace)
_storage.insert(value)
}
public init(capacity numItems: Int) {
super.init(objects: [], count: 0)
}
required public convenience init(arrayLiteral elements: Any...) {
self.init(capacity: 0)
addObjects(from: elements)
}
public required init?(coder aDecoder: NSCoder) { NSUnimplemented() }
fileprivate func _removeObject(_ object: Any) {
let value = __SwiftValue.store(object)
guard contains(object) else {
return
}
_storage.remove(value)
_orderedStorage.remove(at: index(of: object))
}
open override subscript(idx: Int) -> Any {
get {
return object(at: idx)
}
set {
replaceObject(at: idx, with: newValue)
}
}
}
extension NSMutableOrderedSet {
open func add(_ object: Any) {
_insertObject(object)
}
open func add(_ objects: UnsafePointer<AnyObject>!, count: Int) {
_insertObjects(objects, count: count)
}
open func addObjects(from array: [Any]) {
for object in array {
_insertObject(object)
}
}
open func exchangeObject(at idx1: Int, withObjectAt idx2: Int) {
let object1 = self.object(at: idx1)
let object2 = self.object(at: idx2)
_orderedStorage[idx1] = __SwiftValue.store(object2)
_orderedStorage[idx2] = __SwiftValue.store(object1)
}
open func moveObjects(at indexes: IndexSet, to idx: Int) {
var removedObjects = [Any]()
for index in indexes.lazy.reversed() {
let obj = object(at: index)
removedObjects.append(obj)
removeObject(at: index)
}
for removedObject in removedObjects {
insert(removedObject, at: idx)
}
}
open func insert(_ objects: [Any], at indexes: IndexSet) {
for (indexLocation, index) in indexes.enumerated() {
let object = objects[indexLocation]
insert(object, at: index)
}
}
/// Sets the object at the specified index of the mutable ordered set.
///
/// - Parameters:
/// - obj: The object to be set.
/// - idx: The index. If the index is equal to `count`, then it appends
/// the object. Otherwise it replaces the object at the index with the
/// given object.
open func setObject(_ obj: Any, at idx: Int) {
if idx == count {
insert(obj, at: idx)
} else {
replaceObject(at: idx, with: obj)
}
}
open func replaceObjects(in range: NSRange, with objects: UnsafePointer<AnyObject>!, count: Int) {
if let range = Range(range) {
let buffer = UnsafeBufferPointer(start: objects, count: count)
for (indexLocation, index) in range.indices.lazy.reversed().enumerated() {
let object = buffer[indexLocation]
replaceObject(at: index, with: object)
}
}
}
open func replaceObjects(at indexes: IndexSet, with objects: [Any]) {
for (indexLocation, index) in indexes.enumerated() {
let object = objects[indexLocation]
replaceObject(at: index, with: object)
}
}
open func removeObjects(in range: NSRange) {
if let range = Range(range) {
for index in range.indices.lazy.reversed() {
removeObject(at: index)
}
}
}
open func removeObjects(at indexes: IndexSet) {
for index in indexes.lazy.reversed() {
removeObject(at: index)
}
}
public func removeAllObjects() {
_storage.removeAll()
_orderedStorage.removeAll()
}
open func remove(_ val: Any) {
let object = __SwiftValue.store(val)
_storage.remove(object)
_orderedStorage.remove(at: index(of: val))
}
open func removeObjects(in array: [Any]) {
array.forEach(remove)
}
open func intersect(_ other: NSOrderedSet) {
for item in self where !other.contains(item) {
remove(item)
}
}
open func minus(_ other: NSOrderedSet) {
for item in other where contains(item) {
remove(item)
}
}
open func union(_ other: NSOrderedSet) {
other.forEach(add)
}
open func intersectSet(_ other: Set<AnyHashable>) {
for case let item as AnyHashable in self where !other.contains(item) {
remove(item)
}
}
open func minusSet(_ other: Set<AnyHashable>) {
for item in other where contains(item) {
remove(item)
}
}
open func unionSet(_ other: Set<AnyHashable>) {
other.forEach(add)
}
open func sort(comparator cmptr: (Any, Any) -> ComparisonResult) {
sortRange(NSRange(location: 0, length: count), options: [], usingComparator: cmptr)
}
open func sort(options opts: NSSortOptions = [], usingComparator cmptr: (Any, Any) -> ComparisonResult) {
sortRange(NSRange(location: 0, length: count), options: opts, usingComparator: cmptr)
}
open func sortRange(_ range: NSRange, options opts: NSSortOptions = [], usingComparator cmptr: (Any, Any) -> ComparisonResult) {
// The sort options are not available. We use the Array's sorting algorithm. It is not stable neither concurrent.
guard opts.isEmpty else {
NSUnimplemented()
}
let swiftRange = Range(range)!
_orderedStorage[swiftRange].sort { lhs, rhs in
return cmptr(__SwiftValue.fetch(nonOptional: lhs), __SwiftValue.fetch(nonOptional: rhs)) == .orderedAscending
}
}
}
|
apache-2.0
|
dc8b4a973e246b699acdd630f26a3de7
| 32.83821 | 209 | 0.601322 | 4.530998 | false | false | false | false |
janbiasi/ios-practice
|
InternetBrowser/InternetBrowser/ViewController.swift
|
1
|
2501
|
//
// ViewController.swift
// internetBrowser
//
// Created by Administrator on 06.07.15.
// Copyright (c) 2015 Namics AG. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var inputField: UITextField!
@IBOutlet weak var searchButton: UIButton!
@IBOutlet weak var browserView: UIWebView!
@IBOutlet weak var homeButton: UIBarButtonItem!
@IBOutlet weak var reloadButton: UIBarButtonItem!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
let Debug = Logger(namespace:"ViewController", enable:true);
let google = "http://google.com/";
override func viewDidLoad() {
super.viewDidLoad();
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func updateBrowserWithUrl(requestURL: NSURL) {
let request = NSURLRequest(URL: requestURL)
browserView.loadRequest(request)
}
private func updateBrowserWithAnyInput(input: String) {
var finalUrl: NSURL? = nil;
var trail = input.substringToIndex(advance(input.startIndex, 4, input.endIndex))
if trail == "http" {
finalUrl = NSURL(string:input);
Debug.log("URL is valid -> \(input)")
} else {
let generated = self.generateSearchQuery(input);
finalUrl = NSURL(string: generated);
Debug.log("Generating URL -> \(generated)")
}
self.updateBrowserWithUrl(finalUrl!);
}
private func generateSearchQuery(query:String) -> String {
let str = "\(self.google)search?q=\(self.googleQueryFromString(query))"
return str;
}
private func googleQueryFromString(input:String) -> String {
return input.stringByReplacingOccurrencesOfString(" ", withString: "+");
}
@IBAction func onHome(sender: AnyObject) {
self.updateBrowserWithAnyInput(self.google);
}
@IBAction func onReload() {
browserView.reload()
}
@IBAction func onSearchButton(sender: UIButton) {
self.updateBrowserWithAnyInput(inputField.text);
}
@IBAction func onSearchEnter(sender: UITextField) {
if count(sender.text) > 0 {
self.updateBrowserWithAnyInput(sender.text);
}
}
}
|
gpl-2.0
|
5e1e4a41d476913ba5f7741cbbeb1e33
| 29.13253 | 88 | 0.640144 | 4.754753 | false | false | false | false |
yinhaofrancis/YHAlertView
|
YHKit/YHDrawer.swift
|
1
|
2980
|
//
// YHDrawer.swift
// YHAlertView
//
// Created by Francis on 2017/6/16.
// Copyright © 2017年 yyk. All rights reserved.
//
import UIKit
public class YHDrawView:UIView{
private var views:[UIView] = []
public var offsetY:CGFloat = 200
public let offset:CGFloat = 64
public func append(view:UIView){
view.tag = views.count
views.append(view)
self.addSubview(view)
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOffset = CGSize(width: 0, height: -1)
view.layer.shadowRadius = 3
view.layer.shadowOpacity = 0.3
view.layer.masksToBounds = false
}
public func removeIndex(i:Int)->UIView{
for j in i..<self.views.count{
self.views[j].tag -= 1
}
let v = views.remove(at: i)
v.removeFromSuperview()
return v
}
public func loadViews(){
self.topMaskView.bringSubview(toFront: topMaskView)
var origin = CGPoint(x: 0, y: offsetY)
for i in views{
let point = origin
self.insertSubview(i, at: i.tag)
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseOut], animations: {
i.frame = CGRect(origin: point, size: CGSize(width: self.frame.width, height: self.frame.height - 20))
self.backgroundColor = UIColor.white
}, completion: { (_) in
self.topMaskView.isHidden = false
})
origin.y += offset
}
}
private var topMaskView:UIView = UIView()
public override func didMoveToWindow() {
self.addSubview(topMaskView)
topMaskView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap(tap:))))
}
func handleTap(tap:UITapGestureRecognizer){
let p = tap.location(in: self)
let vs = self.views.filter { (v) -> Bool in
var handle = v.frame
handle.size.height = offset
return handle.contains(p)
}
if let v = vs.first{
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseOut], animations: {
v.frame.origin.y = 20
self.backgroundColor = UIColor.black
}, completion: nil)
self.views.filter({ (o) -> Bool in
return o != v
}).forEach({ (v) in
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseOut], animations: {
v.frame.origin.y = UIScreen.main.bounds.maxY + 10
}, completion: nil)
})
}
self.topMaskView.isHidden = true
DispatchQueue.main.asyncAfter(deadline: .now() + DispatchTimeInterval.seconds(3)) {
self.loadViews()
}
}
public override func layoutSubviews() {
topMaskView.frame = CGRect(x: 0, y: offsetY, width: self.frame.width, height: self.frame.height - offsetY)
}
}
|
mit
|
10a376edfb69efe82abfb4dcf6b9f2b0
| 35.304878 | 118 | 0.577091 | 4.228693 | false | false | false | false |
acort3255/Emby.ApiClient.Swift
|
Emby.ApiClient/iOS/JsonSerializer.swift
|
1
|
2847
|
//
// JsonSerializer.swift
// Emby.ApiClient
//
// Created by Vedran Ozir on 12/10/15.
// Copyright © 2015 Vedran Ozir. All rights reserved.
//
import Foundation
public class JsonSerializer: IJsonSerializer {
public init() {
}
public func DeserializeFromString<T: JSONSerializable>(text: String, type: Any?) throws -> T? {
if let data = text.data(using: String.Encoding.utf8), !text.isEmpty {
let json = try JSONSerialization.jsonObject( with: data, options: [])
if let jsonObject = json as? JSON_Object {
return T(jSON: jsonObject)
} else {
return nil
}
} else {
print("no response: '\(text)'")
return nil
}
}
public func serializeToString(obj: AnyObject) -> String {
if let jsonData = try? JSONSerialization.data(withJSONObject: obj, options: []) {
return String(describing: NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue))
}
return ""
}
}
public class EmbyJson{
static let decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601Full)
return decoder
}()
}
extension DateFormatter {
static let iso8601Full: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
formatter.calendar = Calendar(identifier: .iso8601)
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
}
struct AnyCodingKey : CodingKey {
var stringValue: String
var intValue: Int?
init(_ base: CodingKey) {
self.init(stringValue: base.stringValue, intValue: base.intValue)
}
init(stringValue: String) {
self.stringValue = stringValue
}
init(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
init(stringValue: String, intValue: Int?) {
self.stringValue = stringValue
self.intValue = intValue
}
}
extension JSONDecoder.KeyDecodingStrategy {
static var convertFromUpperCamelCase: JSONDecoder.KeyDecodingStrategy {
return .custom { codingKeys in
var key = AnyCodingKey(codingKeys.last!)
// lowercase first letter
if let firstChar = key.stringValue.first {
let i = key.stringValue.startIndex
key.stringValue.replaceSubrange(
i ... i, with: String(firstChar).lowercased()
)
}
return key
}
}
}
|
mit
|
a32e97eefc735c3816d981593559b68b
| 26.104762 | 104 | 0.577653 | 4.856655 | false | false | false | false |
Zewo/JSONParserMiddleware
|
Sources/JSONParserMiddleware.swift
|
1
|
2235
|
// JSONParserMiddleware.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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 HTTP
import HTTPMiddleware
import JSON
public struct JSONParserMiddleware: RequestMiddlewareType {
public let key = "JSONBody"
public func respond(request: Request) -> RequestMiddlewareResult {
var request = request
guard let mediaType = request.contentType where mediaType.type == "application/json" else {
return .Next(request)
}
guard let JSONBody = try? JSONParser.parse(request.body) else {
return .Next(request)
}
request.context[key] = JSONBody
return .Next(request)
}
}
extension Request {
public var JSONBody: JSON? {
return context["JSONBody"] as? JSON
}
public func getJSONBody() throws -> JSON {
if let JSONBody = JSONBody {
return JSONBody
}
struct Error: ErrorType, CustomStringConvertible {
let description = "JSON body not found in context. Maybe you forgot to apply the JSONParserMiddleware?"
}
throw Error()
}
}
public let parseJSON = JSONParserMiddleware()
|
mit
|
c2ce30d829638462df8853faa428ebd5
| 33.4 | 115 | 0.702461 | 4.675732 | false | false | false | false |
gifsy/Gifsy
|
Frameworks/Bond/Bond/Extensions/OSX/NSControl+Bond.swift
|
15
|
2787
|
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tony Arnold (@tonyarnold)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Cocoa
@objc class NSControlBondHelper: NSObject
{
weak var control: NSControl?
let sink: AnyObject? -> ()
init(control: NSControl, sink: AnyObject? -> ()) {
self.control = control
self.sink = sink
super.init()
control.target = self
control.action = Selector("eventHandler:")
}
func eventHandler(sender: NSControl?) {
sink(sender!.objectValue)
}
deinit {
control?.target = nil
control?.action = nil
}
}
extension NSControl {
private struct AssociatedKeys {
static var ControlEventKey = "bnd_ControlEventKey"
static var ControlBondHelperKey = "bnd_ControlBondHelperKey"
}
public var bnd_enabled: Observable<Bool> {
return bnd_associatedObservableForValueForKey("enabled")
}
public var bnd_controlEvent: EventProducer<AnyObject?> {
if let bnd_controlEvent: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.ControlEventKey) {
return bnd_controlEvent as! EventProducer<AnyObject?>
} else {
var capturedSink: (AnyObject? -> ())! = nil
let bnd_controlEvent = EventProducer<AnyObject?> { sink in
capturedSink = sink
return nil
}
let controlHelper = NSControlBondHelper(control: self, sink: capturedSink)
objc_setAssociatedObject(self, &AssociatedKeys.ControlBondHelperKey, controlHelper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_setAssociatedObject(self, &AssociatedKeys.ControlEventKey, bnd_controlEvent, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return bnd_controlEvent
}
}
}
|
apache-2.0
|
35b0b525e07eb0d8e97c84af370db886
| 33.407407 | 147 | 0.719053 | 4.437898 | false | false | false | false |
bestwpw/RxSwift
|
RxSwift/Observables/Implementations/FlatMap.swift
|
2
|
5995
|
//
// FlatMap.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/11/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// It's value is one because initial source subscription is always in CompositeDisposable
let FlatMapNoIterators = 1
class FlatMapSinkIter<SourceType, S: ObservableType, O: ObserverType where O.E == S.E> : ObserverType {
typealias Parent = FlatMapSink<SourceType, S, O>
typealias DisposeKey = CompositeDisposable.DisposeKey
typealias E = O.E
let parent: Parent
let disposeKey: DisposeKey
init(parent: Parent, disposeKey: DisposeKey) {
self.parent = parent
self.disposeKey = disposeKey
}
func on(event: Event<E>) {
switch event {
case .Next(let value):
parent.lock.performLocked {
parent.observer?.on(.Next(value))
}
case .Error(let error):
parent.lock.performLocked {
parent.observer?.on(.Error(error))
self.parent.dispose()
}
case .Completed:
parent.group.removeDisposable(disposeKey)
// If this has returned true that means that `Completed` should be sent.
// In case there is a race who will sent first completed,
// lock will sort it out. When first Completed message is sent
// it will set observer to nil, and thus prevent further complete messages
// to be sent, and thus preserving the sequence grammar.
if parent.stopped && parent.group.count == FlatMapNoIterators {
parent.lock.performLocked {
parent.observer?.on(.Completed)
self.parent.dispose()
}
}
}
}
}
class FlatMapSink<SourceType, S: ObservableType, O: ObserverType where O.E == S.E> : Sink<O>, ObserverType {
typealias ResultType = O.E
typealias Element = SourceType
typealias Parent = FlatMap<SourceType, S>
let parent: Parent
let lock = NSRecursiveLock()
let group = CompositeDisposable()
let sourceSubscription = SingleAssignmentDisposable()
var stopped = false
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func performMap(element: SourceType) throws -> S {
return abstractMethod()
}
func on(event: Event<SourceType>) {
let observer = super.observer
switch event {
case .Next(let element):
do {
let value = try performMap(element)
subscribeInner(value.asObservable())
}
catch let e {
observer?.on(.Error(e))
self.dispose()
}
case .Error(let error):
lock.performLocked {
observer?.on(.Error(error))
self.dispose()
}
case .Completed:
lock.performLocked {
final()
}
}
}
func final() {
stopped = true
if group.count == FlatMapNoIterators {
lock.performLocked {
observer?.on(.Completed)
dispose()
}
}
else {
self.sourceSubscription.dispose()
}
}
func subscribeInner(source: Observable<O.E>) {
let iterDisposable = SingleAssignmentDisposable()
if let disposeKey = group.addDisposable(iterDisposable) {
let iter = FlatMapSinkIter(parent: self, disposeKey: disposeKey)
let subscription = source.subscribeSafe(iter)
iterDisposable.disposable = subscription
}
}
func run() -> Disposable {
group.addDisposable(sourceSubscription)
let subscription = self.parent.source.subscribeSafe(self)
sourceSubscription.disposable = subscription
return group
}
}
class FlatMapSink1<SourceType, S: ObservableType, O : ObserverType where S.E == O.E> : FlatMapSink<SourceType, S, O> {
override init(parent: Parent, observer: O, cancel: Disposable) {
super.init(parent: parent, observer: observer, cancel: cancel)
}
override func performMap(element: SourceType) throws -> S {
return try self.parent.selector1!(element)
}
}
class FlatMapSink2<SourceType, S: ObservableType, O: ObserverType where S.E == O.E> : FlatMapSink<SourceType, S, O> {
var index = 0
override init(parent: Parent, observer: O, cancel: Disposable) {
super.init(parent: parent, observer: observer, cancel: cancel)
}
override func performMap(element: SourceType) throws -> S {
return try self.parent.selector2!(element, index++)
}
}
class FlatMap<SourceType, S: ObservableType>: Producer<S.E> {
typealias Selector1 = (SourceType) throws -> S
typealias Selector2 = (SourceType, Int) throws -> S
let source: Observable<SourceType>
let selector1: Selector1?
let selector2: Selector2?
init(source: Observable<SourceType>, selector: Selector1) {
self.source = source
self.selector1 = selector
self.selector2 = nil
}
init(source: Observable<SourceType>, selector: Selector2) {
self.source = source
self.selector2 = selector
self.selector1 = nil
}
override func run<O: ObserverType where O.E == S.E>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
if let _ = self.selector1 {
let sink = FlatMapSink1(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
else {
let sink = FlatMapSink2(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
}
}
|
mit
|
4df6c76ca547d99f8e5b62c3de303b47
| 30.557895 | 135 | 0.590826 | 4.724192 | false | false | false | false |
Bouke/HAP
|
Sources/VaporHTTP/Message/HTTPResponse.swift
|
1
|
3216
|
/// An HTTP response from a server back to the client.
///
/// let httpRes = HTTPResponse(status: .ok)
///
/// See `HTTPClient` and `HTTPServer`.
public struct HTTPResponse: HTTPMessage {
/// Internal storage is an NIO `HTTPResponseHead`
internal var head: HTTPResponseHead
// MARK: Properties
/// The HTTP version that corresponds to this response.
public var version: HTTPVersion {
get { head.version }
set { head.version = newValue }
}
/// The HTTP response status.
public var status: HTTPResponseStatus {
get { head.status }
set { head.status = newValue }
}
/// The header fields for this HTTP response.
/// The `"Content-Length"` and `"Transfer-Encoding"` headers will be set automatically
/// when the `body` property is mutated.
public var headers: HTTPHeaders {
get { head.headers }
set { head.headers = newValue }
}
/// The `HTTPBody`. Updating this property will also update the associated transport headers.
///
/// httpRes.body = HTTPBody(string: "Hello, world!")
///
/// Also be sure to set this message's `contentType` property to a `MediaType` that correctly
/// represents the `HTTPBody`.
public var body: HTTPBody {
didSet { updateTransportHeaders() }
}
/// If set, reference to the NIO `Channel` this response came from.
public var channel: Channel?
/// See `CustomStringConvertible`
public var description: String {
var desc: [String] = []
desc.append("HTTP/\(version.major).\(version.minor) \(status.code) \(status.reasonPhrase)")
desc.append(headers.debugDescription)
desc.append(body.description)
return desc.joined(separator: "\n")
}
// MARK: Init
/// Creates a new `HTTPResponse`.
///
/// let httpRes = HTTPResponse(status: .ok)
///
/// - parameters:
/// - status: `HTTPResponseStatus` to use. This defaults to `HTTPResponseStatus.ok`
/// - version: `HTTPVersion` of this response, should usually be (and defaults to) 1.1.
/// - headers: `HTTPHeaders` to include with this response.
/// Defaults to empty headers.
/// The `"Content-Length"` and `"Transfer-Encoding"` headers will be set automatically.
/// - body: `HTTPBody` for this response, defaults to an empty body.
/// See `LosslessHTTPBodyRepresentable` for more information.
public init(
status: HTTPResponseStatus = .ok,
version: HTTPVersion = .init(major: 1, minor: 1),
headers: HTTPHeaders = .init(),
body: LosslessHTTPBodyRepresentable = HTTPBody()
) {
let head = HTTPResponseHead(version: version, status: status, headers: headers)
self.init(
head: head,
body: body.convertToHTTPBody(),
channel: nil
)
updateTransportHeaders()
}
/// Internal init that creates a new `HTTPResponse` without sanitizing headers.
internal init(head: HTTPResponseHead, body: HTTPBody, channel: Channel?) {
self.head = head
self.body = body
self.channel = channel
}
}
|
mit
|
376c53b37b97d49389f8aa15e251becd
| 35.134831 | 106 | 0.61847 | 4.581197 | false | false | false | false |
etchsaleh/Listr
|
Listr/MaterialView.swift
|
1
|
1128
|
//
// MaterialView.swift
// Listr
//
// Created by Hesham Saleh on 1/29/17.
// Copyright © 2017 Hesham Saleh. All rights reserved.
//
import UIKit
private var materialKey = false
extension UIView {
@IBInspectable var materialDesign: Bool {
get {
return materialKey
}
set {
materialKey = newValue
if materialKey {
self.layer.masksToBounds = false
self.layer.cornerRadius = 3
self.layer.shadowOpacity = 0.8
self.layer.shadowRadius = 3
self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
self.layer.shadowColor = UIColor(red: 157/255, green: 157/255, blue: 157/255, alpha: 1.0).cgColor
} else {
self.layer.cornerRadius = 0
self.layer.shadowOpacity = 0
self.layer.shadowRadius = 0
self.layer.shadowColor = nil
}
}
}
}
|
mit
|
a20880dd967d330183f16b583ed5b48f
| 22.978723 | 113 | 0.472937 | 4.83691 | false | false | false | false |
grafiti-io/SwiftCharts
|
SwiftCharts/Axis/ChartAxisLabel.swift
|
1
|
1487
|
//
// ChartAxisLabel.swift
// swift_charts
//
// Created by ischuetz on 01/03/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/// A model of an axis label
open class ChartAxisLabel {
/// Displayed text. Can be truncated.
open let text: String
open let settings: ChartLabelSettings
open fileprivate(set) var originalText: String
var hidden: Bool = false
/// The size of the bounding rectangle for the axis label, taking into account the font and rotation it will be drawn with
open lazy var textSize: CGSize = {
let size = self.text.size(self.settings.font)
if self.settings.rotation =~ 0 {
return size
} else {
return CGRect(x: 0, y: 0, width: size.width, height: size.height).boundingRectAfterRotating(radians: self.settings.rotation * CGFloat(M_PI) / 180.0).size
}
}()
public init(text: String, settings: ChartLabelSettings) {
self.text = text
self.settings = settings
self.originalText = text
}
func copy(_ text: String? = nil, settings: ChartLabelSettings? = nil, originalText: String? = nil, hidden: Bool? = nil) -> ChartAxisLabel {
let label = ChartAxisLabel(
text: text ?? self.text,
settings: settings ?? self.settings
)
label.originalText = originalText ?? self.originalText
label.hidden = hidden ?? self.hidden
return label
}
}
|
apache-2.0
|
05c9aba8e04cafe70c8f63e0905185cd
| 29.979167 | 165 | 0.6308 | 4.373529 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/ViewRelated/Reader/Detail/Views/ReaderDetailLikesView.swift
|
1
|
8396
|
import UIKit
protocol ReaderDetailLikesViewDelegate {
func didTapLikesView()
}
class ReaderDetailLikesView: UIView, NibLoadable {
@IBOutlet weak var avatarStackView: UIStackView!
@IBOutlet weak var summaryLabel: UILabel!
/// The UIImageView used to display the current user's avatar image. This view is hidden by default.
@IBOutlet private weak var selfAvatarImageView: CircularImageView!
static let maxAvatarsDisplayed = 5
var delegate: ReaderDetailLikesViewDelegate?
/// Stores the number of total likes _without_ adding the like from self.
private var totalLikes: Int = 0
/// Convenience property that adds up the total likes and self like for display purposes.
var totalLikesForDisplay: Int {
return displaysSelfAvatar ? totalLikes + 1 : totalLikes
}
/// Convenience property that checks whether or not the self avatar image view is being displayed.
private var displaysSelfAvatar: Bool {
!selfAvatarImageView.isHidden
}
override func awakeFromNib() {
super.awakeFromNib()
applyStyles()
}
func configure(with avatarURLStrings: [String], totalLikes: Int) {
self.totalLikes = totalLikes
updateSummaryLabel()
updateAvatars(with: avatarURLStrings)
addTapGesture()
}
func addSelfAvatar(with urlString: String, animated: Bool = false) {
downloadGravatar(for: selfAvatarImageView, withURL: urlString)
// pre-animation state
// set initial position from the left in LTR, or from the right in RTL.
selfAvatarImageView.alpha = 0
let directionalMultiplier: CGFloat = userInterfaceLayoutDirection() == .leftToRight ? -1.0 : 1.0
selfAvatarImageView.transform = CGAffineTransform(translationX: Constants.animationDeltaX * directionalMultiplier, y: 0)
UIView.animate(withDuration: animated ? Constants.animationDuration : 0) {
// post-animation state
self.selfAvatarImageView.alpha = 1
self.selfAvatarImageView.isHidden = false
self.selfAvatarImageView.transform = .identity
}
updateSummaryLabel()
}
func removeSelfAvatar(animated: Bool = false) {
// pre-animation state
selfAvatarImageView.alpha = 1
self.selfAvatarImageView.transform = .identity
UIView.animate(withDuration: animated ? Constants.animationDuration : 0) {
// post-animation state
// moves to the left in LTR, or to the right in RTL.
self.selfAvatarImageView.alpha = 0
self.selfAvatarImageView.isHidden = true
let directionalMultiplier: CGFloat = self.userInterfaceLayoutDirection() == .leftToRight ? -1.0 : 1.0
self.selfAvatarImageView.transform = CGAffineTransform(translationX: Constants.animationDeltaX * directionalMultiplier, y: 0)
}
updateSummaryLabel()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
applyStyles()
}
}
private extension ReaderDetailLikesView {
func applyStyles() {
// Set border on all the avatar views
for subView in avatarStackView.subviews {
subView.layer.borderWidth = 1
subView.layer.borderColor = UIColor.basicBackground.cgColor
}
}
func updateSummaryLabel() {
switch (displaysSelfAvatar, totalLikes) {
case (true, 0):
summaryLabel.attributedText = highlightedText(SummaryLabelFormats.onlySelf)
case (true, 1):
summaryLabel.attributedText = highlightedText(SummaryLabelFormats.singularWithSelf)
case (true, _) where totalLikes > 1:
summaryLabel.attributedText = highlightedText(String(format: SummaryLabelFormats.pluralWithSelf, totalLikes))
case (false, 1):
summaryLabel.attributedText = highlightedText(SummaryLabelFormats.singular)
default:
summaryLabel.attributedText = highlightedText(String(format: SummaryLabelFormats.plural, totalLikes))
}
}
func updateAvatars(with urlStrings: [String]) {
for (index, subView) in avatarStackView.subviews.enumerated() {
guard let avatarImageView = subView as? UIImageView else {
return
}
if avatarImageView == selfAvatarImageView {
continue
}
if let urlString = urlStrings[safe: index] {
downloadGravatar(for: avatarImageView, withURL: urlString)
} else {
avatarImageView.isHidden = true
}
}
}
func downloadGravatar(for avatarImageView: UIImageView, withURL url: String?) {
// Always reset gravatar
avatarImageView.cancelImageDownload()
avatarImageView.image = .gravatarPlaceholderImage
guard let url = url,
let gravatarURL = URL(string: url) else {
return
}
avatarImageView.downloadImage(from: gravatarURL, placeholderImage: .gravatarPlaceholderImage)
}
func addTapGesture() {
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapView(_:))))
}
@objc func didTapView(_ gesture: UITapGestureRecognizer) {
guard gesture.state == .ended else {
return
}
delegate?.didTapLikesView()
}
struct Constants {
static let animationDuration: TimeInterval = 0.3
static let animationDeltaX: CGFloat = 16.0
}
struct SummaryLabelFormats {
static let onlySelf = NSLocalizedString("_You_ like this.",
comment: "Describes that the current user is the only one liking a post."
+ " The underscores denote underline and is not displayed.")
static let singularWithSelf = NSLocalizedString("_You and another blogger_ like this.",
comment: "Describes that the current user and one other user like a post."
+ " The underscores denote underline and is not displayed.")
static let pluralWithSelf = NSLocalizedString("_You and %1$d bloggers_ like this.",
comment: "Plural format string for displaying the number of post likes, including the like from the current user."
+ " %1$d is the number of likes, excluding the like by current user."
+ " The underscores denote underline and is not displayed.")
static let singular = NSLocalizedString("_One blogger_ likes this.",
comment: "Describes that only one user likes a post. "
+ " The underscores denote underline and is not displayed.")
static let plural = NSLocalizedString("_%1$d bloggers_ like this.",
comment: "Plural format string for displaying the number of post likes."
+ " %1$d is the number of likes. The underscores denote underline and is not displayed.")
}
func highlightedText(_ text: String) -> NSAttributedString {
let labelParts = text.components(separatedBy: "_")
let firstPart = labelParts.first ?? ""
let countPart = labelParts[safe: 1] ?? ""
let lastPart = labelParts.last ?? ""
let foregroundAttributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.secondaryLabel]
let underlineAttributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.primary,
.underlineStyle: NSUnderlineStyle.single.rawValue]
let attributedString = NSMutableAttributedString(string: firstPart, attributes: foregroundAttributes)
attributedString.append(NSAttributedString(string: countPart, attributes: underlineAttributes))
attributedString.append(NSAttributedString(string: lastPart, attributes: foregroundAttributes))
return attributedString
}
}
|
gpl-2.0
|
ffdb2aa9bdfc42a99561d8997f3f1f78
| 41.836735 | 168 | 0.631015 | 5.619813 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios
|
the-blue-alliance-ios/View Controllers/Districts/District/DistrictTeamsViewController.swift
|
1
|
2075
|
import CoreData
import Foundation
import TBAData
import TBAKit
class DistrictTeamsViewController: TeamsViewController {
let district: District
// MARK: Init
init(district: District, dependencies: Dependencies) {
self.district = district
super.init(dependencies: dependencies)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Refreshable
override var refreshKey: String? {
return "\(district.key)_teams"
}
override var automaticRefreshInterval: DateComponents? {
return DateComponents(day: 1)
}
override var automaticRefreshEndDate: Date? {
// Automatically refresh district teams during the year before the selected year (when teams are rolling in)
// Ex: Districts for 2019 will stop automatically refreshing on January 1st, 2019 (should all be set by then)
return Calendar.current.date(from: DateComponents(year: Int(district.year)))
}
@objc override func refresh() {
var operation: TBAKitOperation!
operation = tbaKit.fetchDistrictTeams(key: district.key) { (result, notModified) in
guard case .success(let teams) = result, !notModified else {
return
}
let context = self.persistentContainer.newBackgroundContext()
context.performChangesAndWait({
let district = context.object(with: self.district.objectID) as! District
district.insert(teams)
}, saved: { [unowned self] in
markTBARefreshSuccessful(self.tbaKit, operation: operation)
}, errorRecorder: self.errorRecorder)
}
addRefreshOperations([operation])
}
// MARK: - Stateful
override var noDataText: String? {
return "No teams for district"
}
// MARK: - TeamsViewControllerDataSourceConfiguration
override var fetchRequestPredicate: NSPredicate? {
return Team.districtPredicate(districtKey: district.key)
}
}
|
mit
|
5f5cf9d067d9523bb0501fa7e1557454
| 29.514706 | 117 | 0.658795 | 4.928741 | false | false | false | false |
daviwiki/Gourmet_Swift
|
Gourmet/GourmetToday/TodayViewController.swift
|
1
|
4004
|
//
// TodayViewController.swift
// GourmetToday
//
// Created by David Martinez on 21/12/2016.
// Copyright © 2016 Atenea. All rights reserved.
//
import UIKit
import NotificationCenter
import GourmetModel
class TodayViewController: UIViewController, NCWidgetProviding,
GetBalanceOnlineListener, GetStoredAccountListener {
@IBOutlet weak var loadingView : UIView!
@IBOutlet weak var errorLabel : UILabel!
@IBOutlet weak var balanceView : UIView!
@IBOutlet weak var balanceLabel : UILabel!
@IBOutlet weak var balanceDateLabel : UILabel!
private var lastBalance : Balance?
private var getAccount : GetStoredAccount!
private var getBalance : GetBalanceOnline!
override func viewDidLoad() {
super.viewDidLoad()
configureInteractors()
decorView()
}
private func configureInteractors () {
let balanceParser = BalanceParser()
let service = GourmetServiceDM()
getBalance = GetBalanceOnline(parseBalance: balanceParser, dm: service)
getBalance.setListener(listener: self)
getAccount = GetStoredAccount()
getAccount.setListener(listener: self)
}
private func decorView () {
self.title = Localizable.getString(key: "widget_title")
extensionContext?.widgetLargestAvailableDisplayMode = .compact
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
showLoading()
getAccount.execute()
completionHandler(NCUpdateResult.newData)
}
private func showLoading () {
balanceView.isHidden = true
loadingView.isHidden = false
errorLabel.isHidden = true
}
// MARK: GetStoredAccount
func onFinish(interactor: GetStoredAccount, account: Account?) {
if account != nil {
getBalance.execute(account: account!)
} else {
let message = Localizable.getString(key: "widget_no_account")
showError(message: message)
}
}
// MARK: GetBalanceListener
func onFinish(getBalanceOnline: GetBalanceOnline, balance: Balance?) {
if balance != nil {
lastBalance = balance
showBalance(balance: balance!)
} else if (lastBalance == nil) {
let message = Localizable.getString(key: "widget_load_error")
showError(message: message)
}
// do nothing
}
private func showError (message : String) {
balanceView.isHidden = true
loadingView.isHidden = true
errorLabel.isHidden = false
errorLabel.text = message
}
private func showBalance (balance : Balance) {
balanceView.isHidden = false
loadingView.isHidden = true
errorLabel.isHidden = true
balanceLabel.text = balance.quantity
balanceDateLabel.text = getBalanceDateHumanReadable(balance: balance)
}
private func getBalanceDateHumanReadable (balance : Balance) -> String {
let dateMessageFormat = Localizable.getString(key: "balance_date_request_format")
let dateFormat = "dd/MM/yyyy"
let hourFormat = "HH:mm"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
let dateFormatted = dateFormatter.string(from: balance.requestDate)
dateFormatter.dateFormat = hourFormat
let hourFormatted = dateFormatter.string(from: balance.requestDate)
let dateString = String(format: dateMessageFormat, dateFormatted, hourFormatted)
return dateString
}
}
|
mit
|
c5983625dc3005e07c04071683e27e90
| 32.358333 | 89 | 0.654509 | 5.099363 | false | false | false | false |
ryanglobus/Augustus
|
Augustus/AUEventStoreInEK.swift
|
1
|
7849
|
//
// AUEventStoreInEK.swift
// Augustus
//
// Created by Ryan Globus on 8/7/15.
// Copyright (c) 2015 Ryan Globus. All rights reserved.
//
import Foundation
import EventKit
import Cocoa
class AUEventStoreInEK : AUEventStore {
fileprivate struct AUEventInEK: AUEvent {
let id: String
let description: String
let date: Date
let creationDate: Date?
init(ekEvent: EKEvent) {
self.id = ekEvent.eventIdentifier
self.description = ekEvent.title
self.date = ekEvent.startDate // TODO handle multi-day events
self.creationDate = ekEvent.creationDate
}
var color: NSColor {
get {
if let color = AUCoreData.instance?.colorForAUEvent(self) {
return color
} else {
return NSColor.black
}
}
set {
AUCoreData.instance?.setColor(newValue, forEvent: self)
}
}
}
fileprivate let log = AULog.instance
fileprivate let ekStore: EKEventStore
// TODO below use ekStore?
fileprivate(set) var permission: AUEventStorePermission // TODO listen for changes
fileprivate var ekCalendar_: EKCalendar?
init() {
self.ekStore = EKEventStore()
self.permission = .pending
NotificationCenter.default.addObserver(forName: NSNotification.Name.EKEventStoreChanged, object: nil, queue: nil) { (notification: Notification) in
self.log.debug("Notification from EventKit")
NotificationCenter.default.post(name: Notification.Name(rawValue: AUModel.notificationName), object: self)
}
self.ekStore.requestAccess(to: EKEntityType.event, completion: {(success: Bool, error: Error?) in
// TODO refactor
// TODO test all scenarios (a lot!)
defer {
// notify listeners of model change
self.log.debug("send notification")
NotificationCenter.default.post(name: Notification.Name(rawValue: AUModel.notificationName), object: self)
}
guard success else {
self.permission = .denied
self.log.warn("request to access EKEntityTypeEvents denied")
self.log.warn(error?.localizedDescription)
// TODO gracefully handle this
return
}
self.permission = .granted
self.log.info("request to access EKEntityTypeEvents granted")
// look for calendar
// TODO remember calendar
let calendars = self.ekStore.calendars(for: EKEntityType.event)
// look for calendar
for calendar in calendars {
// TODO make sure iCloud source
if calendar.title == "Augustus" { // TODO or unique identifier?
self.ekCalendar_ = calendar
self.log.info("Found calendar with id \(calendar.calendarIdentifier)")
break
}
}
// if found calendar, can return
guard self.ekCalendar_ == nil else {
return
}
// calendar not found, create it
// get ekSource for new calendar
var ekSource_: EKSource? = nil
for source in self.ekStore.sources {
if source.sourceType.rawValue == EKSourceType.calDAV.rawValue &&
source.title.lowercased() == "icloud"{
// TODO more robust way to get iCloud, since user can edit this
ekSource_ = source
break
}
}
guard let ekSource = ekSource_ else {
self.log.error("Failed to find source to create calendar")
return
}
// actually create the calendar for the ekSource
let calendar = EKCalendar(for: EKEntityType.event, eventStore: self.ekStore)
calendar.title = "Augustus" // TODO dup String
calendar.source = ekSource
do {
try self.ekStore.saveCalendar(calendar, commit: true)
self.ekCalendar_ = calendar
self.log.info("Created calendar with id \(calendar.calendarIdentifier)")
} catch let error as NSError {
self.log.error("Failed to create calendar")
self.log.error(error.debugDescription)
}
})
}
/// returns true upon success, false upon failure
func addEventOnDate(_ date: Date, description: String) -> AUEvent? {
if self.permission != .granted {
return nil
}
if let calendar = self.ekCalendar_ {
let event = EKEvent(eventStore: self.ekStore)
event.startDate = AUModel.beginningOfDate(date)
event.endDate = event.startDate.addingTimeInterval(AUModel.oneHour)
event.isAllDay = true
event.title = description
event.calendar = calendar
do {
try self.ekStore.save(event, span: EKSpan.thisEvent, commit: true)
return AUEventInEK(ekEvent: event)
} catch let error as NSError {
self.log.error(error.debugDescription)
return nil
}
}
return nil
}
/// returns true if an event is removed, false upon failure or if no event is removed
func removeEvent(_ event: AUEvent) -> Bool {
if self.permission != .granted {
return false
}
if let ekEvent = self.ekStore.event(withIdentifier: event.id) {
let success: Bool
do {
try self.ekStore.remove(ekEvent, span: EKSpan.thisEvent, commit: true)
success = true
} catch let error as NSError {
self.log.error(error.debugDescription)
success = false
}
return success
}
return false
}
/// returns true upon success, false upon failure (e.g., event is not in the AUEventStore)
func editEvent(_ event: AUEvent, newDate: Date, newDescription: String) -> Bool {
if self.permission != .granted {
return false
}
if let ekEvent = self.ekStore.event(withIdentifier: event.id) {
// TODO below is dup code
ekEvent.startDate = AUModel.beginningOfDate(newDate)
ekEvent.endDate = ekEvent.startDate.addingTimeInterval(AUModel.oneHour)
ekEvent.isAllDay = true
ekEvent.title = newDescription
let success: Bool
do {
try self.ekStore.save(ekEvent, span: EKSpan.thisEvent, commit: true)
success = true
} catch let error as NSError {
self.log.error(error.debugDescription)
success = false
}
return success
}
return false
}
func eventsForDate(_ date: Date) -> [AUEvent] {
if self.permission != .granted {
return [] // TODO return nil?
}
if let calendar = self.ekCalendar_ {
let start = AUModel.beginningOfDate(date)
let end = start.addingTimeInterval(AUModel.oneDay)
let predicate = self.ekStore.predicateForEvents(withStart: start, end: end, calendars: [calendar])
let ekEvents = self.ekStore.events(matching: predicate)
return ekEvents.map({AUEventInEK(ekEvent: $0)})
}
return []
}
}
|
gpl-2.0
|
263c42243ba02ad857c7a6d3e0ddf023
| 36.37619 | 155 | 0.549115 | 5.028187 | false | false | false | false |
IvanVorobei/RequestPermission
|
Example/SPPermission/SPPermission/Frameworks/SparrowKit/Extension/SPDateExtenshion.swift
|
1
|
1603
|
// The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
extension Date {
func format(mask: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = mask
return dateFormatter.string(from: self)
}
static func create(from value: String) -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy HH:mm"
let date = formatter.date(from: value)
return date
}
}
|
mit
|
32d23168add74058a1551422575682a3
| 41.157895 | 81 | 0.722846 | 4.590258 | false | false | false | false |
mohsinalimat/LocationPicker
|
LocationPicker/SearchHistoryManager.swift
|
2
|
3237
|
//
// SearchHistoryManager.swift
// LocationPicker
//
// Created by Almas Sapargali on 9/6/15.
// Copyright (c) 2015 almassapargali. All rights reserved.
//
import UIKit
import MapKit
struct SearchHistoryManager {
fileprivate let HistoryKey = "RecentLocationsKey"
fileprivate var defaults = UserDefaults.standard
func history() -> [Location] {
let history = defaults.object(forKey: HistoryKey) as? [NSDictionary] ?? []
return history.compactMap(Location.fromDefaultsDic)
}
func addToHistory(_ location: Location) {
guard let dic = location.toDefaultsDic() else { return }
var history = defaults.object(forKey: HistoryKey) as? [NSDictionary] ?? []
let historyNames = history.compactMap { $0[LocationDicKeys.name] as? String }
let alreadyInHistory = location.name.flatMap(historyNames.contains) ?? false
if !alreadyInHistory {
history.insert(dic, at: 0)
defaults.set(history, forKey: HistoryKey)
defaults.synchronize()
}
}
}
struct LocationDicKeys {
static let name = "Name"
static let locationCoordinates = "LocationCoordinates"
static let placemarkCoordinates = "PlacemarkCoordinates"
static let placemarkAddressDic = "PlacemarkAddressDic"
}
struct CoordinateDicKeys {
static let latitude = "Latitude"
static let longitude = "Longitude"
}
extension CLLocationCoordinate2D {
func toDefaultsDic() -> NSDictionary {
return [CoordinateDicKeys.latitude: latitude, CoordinateDicKeys.longitude: longitude]
}
static func fromDefaultsDic(_ dic: NSDictionary) -> CLLocationCoordinate2D? {
guard let latitude = dic[CoordinateDicKeys.latitude] as? NSNumber,
let longitude = dic[CoordinateDicKeys.longitude] as? NSNumber else { return nil }
return CLLocationCoordinate2D(latitude: latitude.doubleValue, longitude: longitude.doubleValue)
}
}
extension Location {
func toDefaultsDic() -> NSDictionary? {
guard let addressDic = placemark.addressDictionary,
let placemarkCoordinatesDic = placemark.location?.coordinate.toDefaultsDic()
else { return nil }
var dic: [String: AnyObject] = [
LocationDicKeys.locationCoordinates: location.coordinate.toDefaultsDic(),
LocationDicKeys.placemarkAddressDic: addressDic as AnyObject,
LocationDicKeys.placemarkCoordinates: placemarkCoordinatesDic
]
if let name = name { dic[LocationDicKeys.name] = name as AnyObject? }
return dic as NSDictionary?
}
class func fromDefaultsDic(_ dic: NSDictionary) -> Location? {
guard let placemarkCoordinatesDic = dic[LocationDicKeys.placemarkCoordinates] as? NSDictionary,
let placemarkCoordinates = CLLocationCoordinate2D.fromDefaultsDic(placemarkCoordinatesDic),
let placemarkAddressDic = dic[LocationDicKeys.placemarkAddressDic] as? [String: AnyObject]
else { return nil }
let coordinatesDic = dic[LocationDicKeys.locationCoordinates] as? NSDictionary
let coordinate = coordinatesDic.flatMap(CLLocationCoordinate2D.fromDefaultsDic)
let location = coordinate.flatMap { CLLocation(latitude: $0.latitude, longitude: $0.longitude) }
return Location(name: dic[LocationDicKeys.name] as? String,
location: location, placemark: MKPlacemark(
coordinate: placemarkCoordinates, addressDictionary: placemarkAddressDic))
}
}
|
mit
|
4d8d2f202786bf34f83e591638d066d4
| 35.370787 | 98 | 0.761816 | 4.001236 | false | false | false | false |
dfortuna/theCraic3
|
SearchTagsTVCell.swift
|
1
|
8300
|
//
// SearchTagsTVCell.swift
// The Craic
//
// Created by Denis Fortuna on 21/6/17.
// Copyright © 2017 Denis. All rights reserved.
//
import UIKit
protocol SearchTagsDelegate: class {
func handleTagsToSearch(sender: SearchTagsTVCell)
}
class SearchTagsTVCell: UITableViewCell {
weak var delegate: SearchTagsDelegate?
var popularTagsBallons = [String]()
var searchedTagsBallons = [String]()
var tagsToSearch = [String]()
func setupCell(searched: [String], popular: [String]) {
popularTagsBallons = popular
searchedTagsBallons = searched
setPopularTagsView()
widthTaken = 0
heightTaken = 0
if !searched.isEmpty {
for tag in searched {
placeBallonSearchingTag(tagText: tag, firstTime: true)
}
}
}
@IBOutlet weak var searchTagsScrollView: UIScrollView!{
didSet{
searchTagsScrollView.layer.borderWidth = 0.3
searchTagsScrollView.layer.borderColor = UIColor.lightGray.cgColor
searchTagsScrollView.layer.cornerRadius = 5
}
}
@IBOutlet weak var popularTags: UIScrollView!{
didSet {
popularTags.layer.borderWidth = 0.3
popularTags.layer.borderColor = UIColor.lightGray.cgColor
popularTags.layer.cornerRadius = 5
}
}
@IBOutlet weak var tagForSearchTextField: UITextField!
var widthTaken: CGFloat = 0
var heightTaken: CGFloat = 0
let marginX: CGFloat = 5
let viewHeight: CGFloat = 26
let caracterWidth = 8
let marginY: CGFloat = 5
var partialWidthTaken: CGFloat = 0
@IBAction func addTagToSearchButton(_ sender: UIButton) {
if (tagForSearchTextField.text?.characters.first != " ") &&
(tagForSearchTextField.text != "") &&
(tagForSearchTextField.text != nil){
placeBallonSearchingTag(tagText: tagForSearchTextField.text!, firstTime: true)
tagForSearchTextField.text = ""
}
}
func placeBallonSearchingTag(tagText: String, firstTime: Bool){
if tagText != " " {
widthNextTag = CGFloat(tagText.characters.count * caracterWidth)
if (widthTaken + widthNextTag) < searchTagsScrollView.frame.width {
partialWidthTaken = addTag(widthTaken: widthTaken, heightTaken: heightTaken, tagText: tagText, parentView: searchTagsScrollView, parentViewString: "SearchTags")
widthTaken += partialWidthTaken + marginX
} else {
widthTaken = 0
heightTaken += viewHeight + marginY
partialWidthTaken = addTag(widthTaken: widthTaken, heightTaken: heightTaken, tagText: tagText, parentView: searchTagsScrollView, parentViewString: "SearchTags")
widthTaken += partialWidthTaken + marginX
}
searchTagsScrollView.contentSize = CGSize(width: widthTaken, height: heightTaken)
}
if firstTime {
tagsToSearch.append(tagText)
delegate?.handleTagsToSearch(sender: self)
}
}
func placeBallonPopularTags (tagText: String) {
if tagText != "" {
widthNextTag = CGFloat(tagText.characters.count * caracterWidth)
if (widthTaken + widthNextTag) < popularTags.frame.width {
partialWidthTaken = addTag(widthTaken: widthTaken, heightTaken: heightTaken, tagText: tagText, parentView: popularTags, parentViewString: "PopularTags")
widthTaken += partialWidthTaken + marginX
} else {
widthTaken = 0
heightTaken += viewHeight + marginY
partialWidthTaken = addTag(widthTaken: widthTaken, heightTaken: heightTaken, tagText: tagText, parentView: popularTags, parentViewString: "PopularTags")
widthTaken += partialWidthTaken + marginX
}
popularTags.contentSize = CGSize(width: widthTaken, height: heightTaken)
}
}
var viewsToDelete = [UIView]()
var viewsSearchTagsToDelete = [UIView]()
var widthNextTag: CGFloat = 0
func setPopularTagsView() {
for tagView in viewsToDelete {
tagView.removeFromSuperview()
}
var isEqual = false
var popularTagsToShow = [String]()
for popularTag in popularTagsBallons {
isEqual = false
for searchedTag in searchedTagsBallons {
if popularTag == searchedTag {
isEqual = true
}
}
if (!isEqual) && (popularTagsToShow.count < 3) {
popularTagsToShow.append(popularTag)
}
}
for tagText in popularTagsToShow {
placeBallonPopularTags(tagText: tagText)
}
}
func addTag(widthTaken: CGFloat, heightTaken: CGFloat, tagText: String, parentView: UIScrollView, parentViewString: String) -> CGFloat {
let tagLabel: UILabel = {
let tagL = UILabel()
let textWidth = tagText.characters.count
tagL.text = tagText
tagL.font = UIFont(name: "Courier New", size: 16)
tagL.textColor = #colorLiteral(red: 0.3084011078, green: 0.5618229508, blue: 0, alpha: 1)
tagL.textAlignment = .center
tagL.frame = CGRect(origin: CGPoint(x: 2.5, y: 2.5), size: CGSize(width: (11 * textWidth), height: 21))
return tagL
}()
let labelSize = tagLabel.frame.size
let tagBallon: UIView = {
let tagB = UIView()
tagB.frame = CGRect(origin: CGPoint(x: widthTaken, y: heightTaken), size: CGSize(width: labelSize.width + 5,
height: labelSize.height + 5))
tagB.layer.borderColor = #colorLiteral(red: 0.3084011078, green: 0.5618229508, blue: 0, alpha: 1).cgColor
tagB.layer.borderWidth = 2
tagB.layer.cornerRadius = 10
tagB.backgroundColor = #colorLiteral(red: 0.5624430776, green: 0.9972921014, blue: 0, alpha: 1)
tagB.addSubview(tagLabel)
return tagB
}()
parentView.addSubview(tagBallon)
if parentViewString == "PopularTags" {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.popularBallonTaped))
gestureRecognizer.delegate = self
tagBallon.addGestureRecognizer(gestureRecognizer)
ballonStringDictionary[tagBallon] = tagText
} else {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.searchBallonTaped))
gestureRecognizer.delegate = self
tagBallon.addGestureRecognizer(gestureRecognizer)
ballonStringDictionary[tagBallon] = tagText
viewsSearchTagsToDelete.append(tagBallon)
}
viewsToDelete.append(tagBallon)
return tagBallon.frame.width
}
var ballonStringDictionary = [ UIView: String ]()
@objc func popularBallonTaped(gestureRecognizer: UIGestureRecognizer) {
if let view = gestureRecognizer.view {
view.removeFromSuperview()
let tagText = ballonStringDictionary[view]
placeBallonSearchingTag(tagText: tagText!, firstTime: true)
}
}
@objc func searchBallonTaped(gestureRecognizer: UIGestureRecognizer) {
if let view = gestureRecognizer.view {
let tagText = ballonStringDictionary[view]
tagsToSearch = tagsToSearch.filter() { $0 != tagText }
delegate?.handleTagsToSearch(sender: self)
redrawSearchingTags()
}
}
func redrawSearchingTags() {
for view in viewsSearchTagsToDelete {
view.removeFromSuperview()
}
widthTaken = 0
heightTaken = 0
for tag in tagsToSearch {
placeBallonSearchingTag(tagText: tag, firstTime: false)
}
}
}
|
apache-2.0
|
b8ed8c7a7935d287341f5829be0356d3
| 33.435685 | 176 | 0.598024 | 4.761331 | false | false | false | false |
Romdeau4/16POOPS
|
Helps_Kitchen_iOS/Help's Kitchen/SeatedTableViewController.swift
|
1
|
4765
|
//
// SeatedTableViewController.swift
// Help's Kitchen
//
// Created by Stephen Ulmer on 3/31/17.
// Copyright © 2017 Stephen Ulmer. All rights reserved.
//
import UIKit
class SeatedTableViewController: UIViewController {
var selectedTable: Table?
let statusLabel: UILabel = {
let sl = UILabel()
//sl.backgroundColor = CustomColor.Yellow500
sl.textColor = CustomColor.UCFGold
sl.translatesAutoresizingMaskIntoConstraints = false
return sl
}()
let tableCapacityLabel: UILabel = {
let psl = UILabel()
//psl.backgroundColor = CustomColor.Yellow500
psl.textColor = CustomColor.UCFGold
psl.translatesAutoresizingMaskIntoConstraints = false
return psl
}()
let reservationNameLabel: UILabel = {
let rnl = UILabel()
rnl.textColor = CustomColor.UCFGold
//rnl.backgroundColor = CustomColor.Yellow500
rnl.translatesAutoresizingMaskIntoConstraints = false
return rnl
}()
let reservationContainer: UIView = {
let view = UIView()
view.backgroundColor = CustomColor.Grey800
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 5
view.layer.masksToBounds = true
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(handleBack))
navigationItem.title = selectedTable?.name
view.backgroundColor = CustomColor.Grey850
setLabelValues()
view.addSubview(reservationContainer)
setupInputsContainer()
}
func handleBack() {
dismiss(animated: true, completion: nil)
}
func setLabelValues() {
statusLabel.text = "Table Status: " + (selectedTable?.status)!
tableCapacityLabel.text = "Table Size: " + String(describing: (selectedTable?.capacity)!)
reservationNameLabel.text = "Reservation Name: " + (selectedTable?.reservationName)!
}
func setupStatusLabel() {
statusLabel.topAnchor.constraint(equalTo: reservationContainer.topAnchor, constant: 50).isActive = true
statusLabel.leftAnchor.constraint(equalTo: reservationContainer.leftAnchor, constant: 30).isActive = true
//statusLabel.widthAnchor.constraint(equalToConstant: 150).isActive = true
statusLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
func setupTableCapacityLabel() {
tableCapacityLabel.topAnchor.constraint(equalTo: statusLabel.bottomAnchor, constant: 50).isActive = true
tableCapacityLabel.leftAnchor.constraint(equalTo: statusLabel.leftAnchor).isActive = true
//tableCapacityLabel.widthAnchor.constraint(equalToConstant: 150).isActive = true
tableCapacityLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
func setupReservationNameLabel() {
reservationNameLabel.topAnchor.constraint(equalTo: tableCapacityLabel.bottomAnchor, constant: 50).isActive = true
reservationNameLabel.leftAnchor.constraint(equalTo: statusLabel.leftAnchor).isActive = true
//reservationNameLabel.widthAnchor.constraint(equalToConstant: 150).isActive = true
reservationNameLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
func setupInputsContainer() {
//x, y, width, height
reservationContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
reservationContainer.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
reservationContainer.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -70).isActive = true
reservationContainer.heightAnchor.constraint(equalTo: view.heightAnchor, constant: -100).isActive = true
//shadows
reservationContainer.layer.masksToBounds = false
reservationContainer.layer.shadowColor = UIColor.black.cgColor
reservationContainer.layer.shadowOpacity = 0.5
reservationContainer.layer.shadowRadius = 10
reservationContainer.layer.shadowOffset = CGSize.zero
view.addSubview(statusLabel)
view.addSubview(tableCapacityLabel)
view.addSubview(reservationNameLabel)
setupStatusLabel()
setupTableCapacityLabel()
setupReservationNameLabel()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
0c2127d565235f987d262268e688b5bb
| 36.809524 | 133 | 0.6822 | 5.346801 | false | false | false | false |
adamfraser/ImageSlideshow
|
Pod/Classes/Core/UIImageView+Tools.swift
|
1
|
1075
|
//
// UIImageView+Tools.swift
// Pods
//
// Created by Aleš Kocur on 20/04/16.
//
//
import UIKit
extension UIImageView {
func aspectToFitFrame() -> CGRect {
guard let image = image else {
assertionFailure("No image found!")
return CGRectZero
}
let imageRatio: CGFloat = image.size.width / image.size.height
let viewRatio: CGFloat = frame.size.width / frame.size.height
if imageRatio < viewRatio {
let scale: CGFloat = frame.size.height / image.size.height
let width: CGFloat = scale * image.size.width
let topLeftX: CGFloat = (frame.size.width - width) * 0.5
return CGRectMake(topLeftX, 0, width, frame.size.height)
} else {
let scale: CGFloat = frame.size.width / image.size.width
let height: CGFloat = scale * image.size.height
let topLeftY: CGFloat = (frame.size.height - height) * 0.5
return CGRectMake(0, topLeftY, frame.size.width, height)
}
}
}
|
mit
|
b1626114b9915d7e1b188d47d86b61ab
| 29.685714 | 70 | 0.581006 | 4.08365 | false | false | false | false |
groue/GRDB.swift
|
GRDB/Core/DatabaseRegionObservation.swift
|
1
|
11949
|
#if canImport(Combine)
import Combine
#endif
import Foundation
/// `DatabaseRegionObservation` tracks transactions that modify a
/// database region.
///
/// For example:
///
/// ```swift
/// // Track the player table
/// let observation = DatabaseRegionObservation(tracking: Player.all())
///
/// let cancellable = try observation.start(in: dbQueue) { error in
/// // handle error
/// } onChange: { (db: Database) in
/// print("A modification of the player table has just been committed.")
/// }
/// ```
///
/// ## Topics
///
/// ### Creating DatabaseRegionObservation
///
/// - ``init(tracking:)-5ldbe``
/// - ``init(tracking:)-2nqjd``
///
/// ### Observing Database Transactions
///
/// - ``publisher(in:)``
/// - ``start(in:onError:onChange:)``
public struct DatabaseRegionObservation {
/// A closure that is evaluated when the observation starts, and returns
/// the observed database region.
var observedRegion: (Database) throws -> DatabaseRegion
}
extension DatabaseRegionObservation {
/// Creates a `DatabaseRegionObservation` that notifies all transactions
/// that modify one of the provided regions.
///
/// For example:
///
/// ```swift
/// // An observation that tracks the 'player' table
/// let observation = DatabaseRegionObservation(tracking: Player.all())
/// ```
///
/// - parameter regions: A list of observed regions.
public init(tracking regions: any DatabaseRegionConvertible...) {
self.init(tracking: regions)
}
/// Creates a `DatabaseRegionObservation` that notifies all transactions
/// that modify one of the provided regions.
///
/// For example:
///
/// ```swift
/// // An observation that tracks the 'player' table
/// let observation = DatabaseRegionObservation(tracking: [Player.all()])
/// ```
///
/// - parameter regions: An array of observed regions.
public init(tracking regions: [any DatabaseRegionConvertible]) {
self.init(observedRegion: DatabaseRegion.union(regions))
}
}
extension DatabaseRegionObservation {
/// The state of a started DatabaseRegionObservation
private enum ObservationState {
case cancelled
case pending
case started(DatabaseRegionObserver)
}
/// Starts observing the database.
///
/// The observation lasts until the returned cancellable is cancelled
/// or deallocated.
///
/// For example:
///
/// ```swift
/// let observation = DatabaseRegionObservation(tracking: Player.all())
///
/// let cancellable = try observation.start(in: dbQueue) { error in
/// // handle error
/// } onChange: { (db: Database) in
/// print("A modification of the player table has just been committed.")
/// }
/// ```
///
/// If this method is called from the writer dispatch queue of `writer` (see
/// ``DatabaseWriter``), the observation starts immediately. Otherwise, it
/// blocks the current thread until a write access can be established.
///
/// Both `onError` and `onChange` closures are executed in the writer
/// dispatch queue, serialized with all database updates performed
/// by `writer`.
///
/// The ``Database`` argument to `onChange` is valid only during the
/// execution of the closure. Do not store or return the database connection
/// for later use.
///
/// - parameter writer: A DatabaseWriter.
/// - parameter onError: The closure to execute when the observation fails.
/// - parameter onChange: The closure to execute when a transaction has
/// modified the observed region.
/// - returns: A DatabaseCancellable that can stop the observation.
public func start(
in writer: some DatabaseWriter,
onError: @escaping (Error) -> Void,
onChange: @escaping (Database) -> Void)
-> AnyDatabaseCancellable
{
@LockedBox var state = ObservationState.pending
// Use unsafeReentrantWrite so that observation can start from any
// dispatch queue.
writer.unsafeReentrantWrite { db in
do {
let region = try observedRegion(db).observableRegion(db)
$state.update {
let observer = DatabaseRegionObserver(region: region, onChange: {
if case .cancelled = state {
return
}
onChange($0)
})
// Use the `.observerLifetime` extent so that we can cancel
// the observation by deallocating the observer. This is
// a simpler way to cancel the observation than waiting for
// *another* write access in order to explicitly remove
// the observer.
db.add(transactionObserver: observer, extent: .observerLifetime)
$0 = .started(observer)
}
} catch {
onError(error)
}
}
return AnyDatabaseCancellable {
// Deallocates the transaction observer. This makes sure that the
// `onChange` callback will never be called again, because the
// observation was started with the `.observerLifetime` extent.
state = .cancelled
}
}
}
#if canImport(Combine)
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension DatabaseRegionObservation {
// MARK: - Publishing Impactful Transactions
/// Returns a publisher that observes the database.
///
/// The publisher publishes ``Database`` connections on the writer dispatch
/// queue of `writer` (see ``DatabaseWriter``). Those connections are valid
/// only when published. Do not store or return them for later use.
///
/// Do not reschedule the publisher with `receive(on:options:)` or any
/// `Publisher` method that schedules publisher elements.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func publisher(in writer: some DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
DatabasePublishers.DatabaseRegion(self, in: writer)
}
}
#endif
private class DatabaseRegionObserver: TransactionObserver {
let region: DatabaseRegion
let onChange: (Database) -> Void
var isChanged = false
init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) {
self.region = region
self.onChange = onChange
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
region.isModified(byEventsOfKind: eventKind)
}
func databaseDidChange(with event: DatabaseEvent) {
if region.isModified(by: event) {
isChanged = true
stopObservingDatabaseChangesUntilNextTransaction()
}
}
func databaseDidCommit(_ db: Database) {
guard isChanged else { return }
isChanged = false
onChange(db)
}
func databaseDidRollback(_ db: Database) {
isChanged = false
}
}
#if canImport(Combine)
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension DatabasePublishers {
/// A publisher that tracks transactions that modify a database region.
///
/// You build such a publisher from ``DatabaseRegionObservation``.
public struct DatabaseRegion: Publisher {
public typealias Output = Database
public typealias Failure = Error
let writer: any DatabaseWriter
let observation: DatabaseRegionObservation
init(_ observation: DatabaseRegionObservation, in writer: some DatabaseWriter) {
self.writer = writer
self.observation = observation
}
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
let subscription = DatabaseRegionSubscription(
writer: writer,
observation: observation,
downstream: subscriber)
subscriber.receive(subscription: subscription)
}
}
private class DatabaseRegionSubscription<Downstream: Subscriber>: Subscription
where Downstream.Failure == Error, Downstream.Input == Database
{
private struct WaitingForDemand {
let downstream: Downstream
let writer: any DatabaseWriter
let observation: DatabaseRegionObservation
}
private struct Observing {
let downstream: Downstream
let writer: any DatabaseWriter // Retain writer until subscription is finished
var remainingDemand: Subscribers.Demand
}
private enum State {
// Waiting for demand, not observing the database.
case waitingForDemand(WaitingForDemand)
// Observing the database.
case observing(Observing)
// Completed or cancelled, not observing the database.
case finished
}
// cancellable is not stored in self.state because we must enter the
// .observing state *before* the observation starts.
private var cancellable: AnyDatabaseCancellable?
private var state: State
private var lock = NSRecursiveLock() // Allow re-entrancy
init(
writer: some DatabaseWriter,
observation: DatabaseRegionObservation,
downstream: Downstream)
{
state = .waitingForDemand(WaitingForDemand(
downstream: downstream,
writer: writer,
observation: observation))
}
func request(_ demand: Subscribers.Demand) {
lock.synchronized {
switch state {
case let .waitingForDemand(info):
guard demand > 0 else {
return
}
state = .observing(Observing(
downstream: info.downstream,
writer: info.writer,
remainingDemand: demand))
cancellable = info.observation.start(
in: info.writer,
onError: { [weak self] in self?.receive(failure: $0) },
onChange: { [weak self] in self?.receive($0) })
case var .observing(info):
info.remainingDemand += demand
state = .observing(info)
case .finished:
break
}
}
}
func cancel() {
lock.synchronized {
cancellable = nil
state = .finished
}
}
private func receive(_ value: Database) {
lock.synchronized {
if case let .observing(info) = state,
info.remainingDemand > .none
{
let additionalDemand = info.downstream.receive(value)
if case var .observing(info) = state {
info.remainingDemand += additionalDemand
info.remainingDemand -= 1
state = .observing(info)
}
}
}
}
private func receive(failure error: Error) {
lock.synchronized {
if case let .observing(info) = state {
state = .finished
info.downstream.receive(completion: .failure(error))
}
}
}
}
}
#endif
|
mit
|
56142a0d13165f70e9dafdc2d7f33d47
| 34.352071 | 108 | 0.573019 | 5.43878 | false | false | false | false |
congncif/IDMCore
|
IDMCore/Classes/DataProviderConverter.swift
|
1
|
5187
|
//
// DataProviderConverter.swift
// IDMCore
//
// Created by FOLY on 12/28/18.
//
import Foundation
extension DataProviderProtocol {
public func convertToIntegrator<M>(modelType: M.Type,
executingType: IntegrationType = .default) -> MagicalIntegrator<Self, M>
where M: ModelProtocol, Self.DataType == M.DataType {
return MagicalIntegrator(dataProvider: self, modelType: M.self, executingType: executingType)
}
public func convertToIntegrator(executingType: IntegrationType = .default) -> AmazingIntegrator<Self> {
return AmazingIntegrator(dataProvider: self, executingType: executingType)
}
public var integrator: AmazingIntegrator<Self> {
return convertToIntegrator()
}
}
public final class IntegratingDataProvider<I: IntegratorProtocol>: DataProviderProtocol {
public private(set) var internalIntegrator: I
public private(set) var queue: IntegrationCallQueue
public init(integrator: I, on requestQueue: IntegrationCallQueue = .main) {
internalIntegrator = integrator
queue = requestQueue
}
public typealias GResultType = SimpleResult<I.GResultType?>
public func request(parameters: I.GParameterType, completionResult: @escaping (GResultType) -> Void) -> CancelHandler? {
return request(parameters: parameters) { success, data, error in
var result: ResultType
if success {
result = .success(data)
} else if let error = error {
result = .failure(error)
} else {
result = .failure(UnknownError.default)
}
completionResult(result)
}
}
private func request(parameters: I.GParameterType,
completion: @escaping (Bool, I.GResultType?, Error?) -> Void) -> CancelHandler? {
internalIntegrator
.prepareCall(parameters: parameters)
.onSuccess { data in
completion(true, data, nil)
}
.onError { error in
completion(false, nil, error)
}
.call(queue: queue)
return { [weak self] in
guard let self = self else { return }
self.internalIntegrator.cancel()
}
}
}
extension IntegratorProtocol {
public func convertToDataProvider(queue: IntegrationCallQueue = .main) -> IntegratingDataProvider<Self> {
return IntegratingDataProvider(integrator: self, on: queue)
}
public var dataProvider: IntegratingDataProvider<Self> {
return convertToDataProvider()
}
}
open class ConvertDataProvider<P1, P2>: DataProviderProtocol {
public typealias ParameterType = P1
public typealias DataType = P2
private var converter: ((P1) throws -> P2)?
private var queue: DispatchQueue?
public convenience init(queue: DispatchQueue? = nil, converter: @escaping ((P1) throws -> P2)) {
self.init(queue: queue)
self.converter = converter
}
public init(queue: DispatchQueue? = nil) {
self.queue = queue
}
public func request(parameters: ParameterType, completionResult: @escaping (ResultType) -> Void) -> CancelHandler? {
let block = { [weak self] in
if let convertFunc = self?.converter {
do {
let outParameter = try convertFunc(parameters)
completionResult(.success(outParameter))
} catch let ex {
completionResult(.failure(ex))
}
} else {
do {
let outParameter = try self?.convert(parameter: parameters)
completionResult(.success(outParameter))
} catch let ex {
completionResult(.failure(ex))
}
}
}
if let queue = self.queue {
queue.async(execute: block)
} else {
block()
}
return nil
}
open func convert(parameter: P1) throws -> P2 {
preconditionFailure("Converter needs an implementation")
}
}
public final class ForwardDataProvider<P>: ConvertDataProvider<P, P> {
private let forwarder: (P) throws -> P
public init(queue: DispatchQueue? = nil, forwarder: @escaping ((P) throws -> P)) {
self.forwarder = forwarder
super.init(queue: queue)
}
public convenience init(queue: DispatchQueue? = nil, sideEffect: @escaping (P) -> Void) {
self.init(queue: queue, forwarder: {
sideEffect($0)
return $0
})
}
override public func convert(parameter: P) throws -> P {
return try forwarder(parameter)
}
}
public final class BridgeDataProvider<P, R: ModelProtocol>: ConvertDataProvider<P, R> where R.DataType == P {
override public init(queue: DispatchQueue? = nil) {
super.init(queue: queue)
}
override public func convert(parameter: P) throws -> R {
do {
let data: R = try R(fromData: parameter)
return data
} catch let ex {
throw ex
}
}
}
|
mit
|
67754eb69f73aef514c43fb22a9dcb54
| 31.217391 | 124 | 0.600154 | 4.602484 | false | false | false | false |
vbudhram/firefox-ios
|
Storage/Logins.swift
|
3
|
22705
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
import Shared
import Deferred
import XCGLogger
private var log = Logger.syncLogger
enum SyncStatus: Int {
// Ordinarily not needed; synced items are removed from the overlay. But they start here when cloned.
case synced = 0
// A material change that we want to upload on next sync.
case changed = 1
// Created locally.
case new = 2
}
public enum CommutativeLoginField {
case timesUsed(increment: Int)
}
public protocol Indexable {
var index: Int { get }
}
public enum NonCommutativeLoginField: Indexable {
case hostname(to: String)
case password(to: String)
case username(to: String?)
case httpRealm(to: String?)
case formSubmitURL(to: String?)
case timeCreated(to: MicrosecondTimestamp) // Should be immutable.
case timeLastUsed(to: MicrosecondTimestamp)
case timePasswordChanged(to: MicrosecondTimestamp)
public var index: Int {
switch self {
case .hostname:
return 0
case .password:
return 1
case .username:
return 2
case .httpRealm:
return 3
case .formSubmitURL:
return 4
case .timeCreated:
return 5
case .timeLastUsed:
return 6
case .timePasswordChanged:
return 7
}
}
static let Entries: Int = 8
}
// We don't care about these, because they're slated for removal at some point --
// we don't really use them for form fill.
// We handle them in the same way as NonCommutative, just broken out to allow us
// flexibility in removing them or reconciling them differently.
public enum NonConflictingLoginField: Indexable {
case usernameField(to: String?)
case passwordField(to: String?)
public var index: Int {
switch self {
case .usernameField:
return 0
case .passwordField:
return 1
}
}
static let Entries: Int = 2
}
public typealias LoginDeltas = (
commutative: [CommutativeLoginField],
nonCommutative: [NonCommutativeLoginField],
nonConflicting: [NonConflictingLoginField]
)
public typealias TimestampedLoginDeltas = (at: Timestamp, changed: LoginDeltas)
/**
* LoginData is a wrapper around NSURLCredential and NSURLProtectionSpace to allow us to add extra fields where needed.
**/
public protocol LoginData: class {
var guid: String { get set } // It'd be nice if this were read-only.
var credentials: URLCredential { get }
var protectionSpace: URLProtectionSpace { get }
var hostname: String { get }
var username: String? { get }
var password: String { get }
var httpRealm: String? { get set }
var formSubmitURL: String? { get set }
var usernameField: String? { get set }
var passwordField: String? { get set }
var isValid: Maybe<()> { get }
// https://bugzilla.mozilla.org/show_bug.cgi?id=1238103
var hasMalformedHostname: Bool { get set }
func toDict() -> [String: String]
func isSignificantlyDifferentFrom(_ login: LoginData) -> Bool
}
public protocol LoginUsageData {
var timesUsed: Int { get set }
var timeCreated: MicrosecondTimestamp { get set }
var timeLastUsed: MicrosecondTimestamp { get set }
var timePasswordChanged: MicrosecondTimestamp { get set }
}
open class Login: CustomStringConvertible, LoginData, LoginUsageData, Equatable {
open var guid: String
open fileprivate(set) var credentials: URLCredential
open let protectionSpace: URLProtectionSpace
open var hostname: String {
if let _ = protectionSpace.`protocol` {
return protectionSpace.urlString()
}
return protectionSpace.host
}
open var hasMalformedHostname: Bool = false
open var username: String? { return credentials.user }
open var password: String { return credentials.password ?? "" }
open var usernameField: String?
open var passwordField: String?
fileprivate var _httpRealm: String?
open var httpRealm: String? {
get { return self._httpRealm ?? protectionSpace.realm }
set { self._httpRealm = newValue }
}
fileprivate var _formSubmitURL: String?
open var formSubmitURL: String? {
get {
return self._formSubmitURL
}
set(value) {
guard let value = value, !value.isEmpty else {
self._formSubmitURL = nil
return
}
let url2 = URL(string: self.hostname)
let url1 = URL(string: value)
if url1?.host != url2?.host {
log.warning("Form submit URL domain doesn't match login's domain.")
}
self._formSubmitURL = value
}
}
// LoginUsageData. These defaults only apply to locally created records.
open var timesUsed = 0
open var timeCreated = Date.nowMicroseconds()
open var timeLastUsed = Date.nowMicroseconds()
open var timePasswordChanged = Date.nowMicroseconds()
// Printable
open var description: String {
return "Login for \(hostname)"
}
open var isValid: Maybe<()> {
// Referenced from https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginManager.js?rev=f76692f0fcf8&mark=280-281#271
// Logins with empty hostnames are not valid.
if hostname.isEmpty {
return Maybe(failure: LoginDataError(description: "Can't add a login with an empty hostname."))
}
// Logins with empty passwords are not valid.
if password.isEmpty {
return Maybe(failure: LoginDataError(description: "Can't add a login with an empty password."))
}
// Logins with both a formSubmitURL and httpRealm are not valid.
if let _ = formSubmitURL, let _ = httpRealm {
return Maybe(failure: LoginDataError(description: "Can't add a login with both a httpRealm and formSubmitURL."))
}
// Login must have at least a formSubmitURL or httpRealm.
if (formSubmitURL == nil) && (httpRealm == nil) {
return Maybe(failure: LoginDataError(description: "Can't add a login without a httpRealm or formSubmitURL."))
}
// All good.
return Maybe(success: ())
}
open func update(password: String, username: String) {
self.credentials =
URLCredential(user: username, password: password, persistence: credentials.persistence)
}
// Essentially: should we sync a change?
// Desktop ignores usernameField and hostnameField.
open func isSignificantlyDifferentFrom(_ login: LoginData) -> Bool {
return login.password != self.password ||
login.hostname != self.hostname ||
login.username != self.username ||
login.formSubmitURL != self.formSubmitURL ||
login.httpRealm != self.httpRealm
}
/* Used for testing purposes since formSubmitURL should be given back to use from the Logins.js script */
open class func createWithHostname(_ hostname: String, username: String, password: String, formSubmitURL: String?) -> LoginData {
let loginData = Login(hostname: hostname, username: username, password: password) as LoginData
loginData.formSubmitURL = formSubmitURL
return loginData
}
open class func createWithHostname(_ hostname: String, username: String, password: String) -> LoginData {
return Login(hostname: hostname, username: username, password: password) as LoginData
}
open class func createWithCredential(_ credential: URLCredential, protectionSpace: URLProtectionSpace) -> LoginData {
return Login(credential: credential, protectionSpace: protectionSpace) as LoginData
}
public init(guid: String, hostname: String, username: String, password: String) {
self.guid = guid
self.credentials = URLCredential(user: username, password: password, persistence: .none)
// Break down the full url hostname into its scheme/protocol and host components
let hostnameURL = hostname.asURL
let host = hostnameURL?.host ?? hostname
let scheme = hostnameURL?.scheme ?? ""
// We should ignore any SSL or normal web ports in the URL.
var port = hostnameURL?.port ?? 0
if port == 443 || port == 80 {
port = 0
}
self.protectionSpace = URLProtectionSpace(host: host, port: port, protocol: scheme, realm: nil, authenticationMethod: nil)
}
convenience init(hostname: String, username: String, password: String) {
self.init(guid: Bytes.generateGUID(), hostname: hostname, username: username, password: password)
}
// Why do we need this initializer to be marked as required? Because otherwise we can't
// use this type in our factory for MirrorLogin and LocalLogin.
// SO: http://stackoverflow.com/questions/26280176/swift-generics-not-preserving-type
// Playground: https://gist.github.com/rnewman/3fb0c4dbd25e7fda7e3d
// Conversation: https://twitter.com/rnewman/status/611332618412359680
required public init(credential: URLCredential, protectionSpace: URLProtectionSpace) {
self.guid = Bytes.generateGUID()
self.credentials = credential
self.protectionSpace = protectionSpace
}
open func toDict() -> [String: String] {
return [
"hostname": hostname,
"formSubmitURL": formSubmitURL ?? "",
"httpRealm": httpRealm ?? "",
"username": username ?? "",
"password": password,
"usernameField": usernameField ?? "",
"passwordField": passwordField ?? ""
]
}
open class func fromScript(_ url: URL, script: [String: Any]) -> LoginData? {
guard let username = script["username"] as? String,
let password = script["password"] as? String else {
return nil
}
guard let origin = getPasswordOrigin(url.absoluteString) else {
return nil
}
let login = Login(hostname: origin, username: username, password: password)
if let formSubmit = script["formSubmitURL"] as? String {
login.formSubmitURL = formSubmit
}
if let passwordField = script["passwordField"] as? String {
login.passwordField = passwordField
}
if let userField = script["usernameField"] as? String {
login.usernameField = userField
}
return login as LoginData
}
fileprivate class func getPasswordOrigin(_ uriString: String, allowJS: Bool = false) -> String? {
var realm: String? = nil
if let uri = URL(string: uriString),
let scheme = uri.scheme, !scheme.isEmpty,
let host = uri.host {
if allowJS && scheme == "javascript" {
return "javascript:"
}
realm = "\(scheme)://\(host)"
// If the URI explicitly specified a port, only include it when
// it's not the default. (We never want "http://foo.com:80")
if let port = uri.port {
realm? += ":\(port)"
}
} else {
// bug 159484 - disallow url types that don't support a hostPort.
// (although we handle "javascript:..." as a special case above.)
log.debug("Couldn't parse origin for \(uriString)")
realm = nil
}
return realm
}
/**
* Produce a delta stream by comparing this record to a source.
* Note that the source might be missing the timestamp and counter fields
* introduced in Bug 555755, so we pay special attention to those, checking for
* and ignoring transitions to zero.
*
* TODO: it's possible that we'll have, say, two iOS clients working with a desktop.
* Each time the desktop changes the password fields, it'll upload a record without
* these extra timestamp fields. We need to make sure the right thing happens.
*
* There are three phases in this process:
* 1. Producing deltas. There is no intrinsic ordering here, but we yield ordered
* arrays for convenience and ease of debugging.
* 2. Comparing deltas. This is done through a kind of array-based Perlish Schwartzian
* transform, where each field has a known index in space to allow for trivial
* comparison; this, of course, is ordered.
* 3. Applying a merged delta stream to a record. Again, this is unordered, but we
* use arrays for convenience.
*/
open func deltas(from: Login) -> LoginDeltas {
let commutative: [CommutativeLoginField]
if self.timesUsed > 0 && self.timesUsed != from.timesUsed {
commutative = [CommutativeLoginField.timesUsed(increment: self.timesUsed - from.timesUsed)]
} else {
commutative = []
}
var nonCommutative = [NonCommutativeLoginField]()
if self.hostname != from.hostname {
nonCommutative.append(NonCommutativeLoginField.hostname(to: self.hostname))
}
if self.password != from.password {
nonCommutative.append(NonCommutativeLoginField.password(to: self.password))
}
if self.username != from.username {
nonCommutative.append(NonCommutativeLoginField.username(to: self.username))
}
if self.httpRealm != from.httpRealm {
nonCommutative.append(NonCommutativeLoginField.httpRealm(to: self.httpRealm))
}
if self.formSubmitURL != from.formSubmitURL {
nonCommutative.append(NonCommutativeLoginField.formSubmitURL(to: self.formSubmitURL))
}
if self.timeCreated > 0 && self.timeCreated != from.timeCreated {
nonCommutative.append(NonCommutativeLoginField.timeCreated(to: self.timeCreated))
}
if self.timeLastUsed > 0 && self.timeLastUsed != from.timeLastUsed {
nonCommutative.append(NonCommutativeLoginField.timeLastUsed(to: self.timeLastUsed))
}
if self.timeLastUsed > 0 && self.timePasswordChanged != from.timePasswordChanged {
nonCommutative.append(NonCommutativeLoginField.timePasswordChanged(to: self.timePasswordChanged))
}
var nonConflicting = [NonConflictingLoginField]()
if self.passwordField != from.passwordField {
nonConflicting.append(NonConflictingLoginField.passwordField(to: self.passwordField))
}
if self.usernameField != from.usernameField {
nonConflicting.append(NonConflictingLoginField.usernameField(to: self.usernameField))
}
return (commutative, nonCommutative, nonConflicting)
}
fileprivate class func mergeDeltaFields<T: Indexable>(_ count: Int, a: [T], b: [T], preferBToA: Bool) -> [T] {
var deltas = Array<T?>(repeating: nil, count: count)
// Let's start with the 'a's.
for f in a {
deltas[f.index] = f
}
// Then detect any conflicts and fill out the rest.
for f in b {
let index = f.index
if deltas[index] != nil {
log.warning("Collision in \(T.self) \(f.index). Using latest.")
if preferBToA {
deltas[index] = f
}
} else {
deltas[index] = f
}
}
return optFilter(deltas)
}
open class func mergeDeltas(a: TimestampedLoginDeltas, b: TimestampedLoginDeltas) -> LoginDeltas {
let (aAt, aChanged) = a
let (bAt, bChanged) = b
let (aCommutative, aNonCommutative, aNonConflicting) = aChanged
let (bCommutative, bNonCommutative, bNonConflicting) = bChanged
// If the timestamps are exactly the same -- an exceedingly rare occurrence -- we default
// to 'b', which is the remote record by convention.
let bLatest = aAt <= bAt
let commutative = aCommutative + bCommutative
let nonCommutative: [NonCommutativeLoginField]
let nonConflicting: [NonConflictingLoginField]
if aNonCommutative.isEmpty {
nonCommutative = bNonCommutative
} else if bNonCommutative.isEmpty {
nonCommutative = aNonCommutative
} else {
nonCommutative = mergeDeltaFields(NonCommutativeLoginField.Entries, a: aNonCommutative, b: bNonCommutative, preferBToA: bLatest)
}
if aNonConflicting.isEmpty {
nonConflicting = bNonConflicting
} else if bNonCommutative.isEmpty {
nonConflicting = aNonConflicting
} else {
nonConflicting = mergeDeltaFields(NonConflictingLoginField.Entries, a: aNonConflicting, b: bNonConflicting, preferBToA: bLatest)
}
return (
commutative: commutative,
nonCommutative: nonCommutative,
nonConflicting: nonConflicting
)
}
/**
* Apply the provided changes to yield a new login.
*/
open func applyDeltas(_ deltas: LoginDeltas) -> Login {
let guid = self.guid
var hostname = self.hostname
var username = self.username
var password = self.password
var usernameField = self.usernameField
var passwordField = self.passwordField
var timesUsed = self.timesUsed
var httpRealm = self.httpRealm
var formSubmitURL = self.formSubmitURL
var timeCreated = self.timeCreated
var timeLastUsed = self.timeLastUsed
var timePasswordChanged = self.timePasswordChanged
for delta in deltas.commutative {
switch delta {
case let .timesUsed(increment):
timesUsed += increment
}
}
for delta in deltas.nonCommutative {
switch delta {
case let .hostname(to):
hostname = to
break
case let .password(to):
password = to
break
case let .username(to):
username = to
break
case let .httpRealm(to):
httpRealm = to
break
case let .formSubmitURL(to):
formSubmitURL = to
break
case let .timeCreated(to):
timeCreated = to
break
case let .timeLastUsed(to):
timeLastUsed = to
break
case let .timePasswordChanged(to):
timePasswordChanged = to
break
}
}
for delta in deltas.nonConflicting {
switch delta {
case let .usernameField(to):
usernameField = to
break
case let .passwordField(to):
passwordField = to
break
}
}
let out = Login(guid: guid, hostname: hostname, username: username ?? "", password: password)
out.timesUsed = timesUsed
out.httpRealm = httpRealm
out.formSubmitURL = formSubmitURL
out.timeCreated = timeCreated
out.timeLastUsed = timeLastUsed
out.timePasswordChanged = timePasswordChanged
out.usernameField = usernameField
out.passwordField = passwordField
return out
}
}
public func ==(lhs: Login, rhs: Login) -> Bool {
return lhs.credentials == rhs.credentials && lhs.protectionSpace == rhs.protectionSpace
}
open class ServerLogin: Login {
var serverModified: Timestamp = 0
public init(guid: String, hostname: String, username: String, password: String, modified: Timestamp) {
self.serverModified = modified
super.init(guid: guid, hostname: hostname, username: username, password: password)
}
required public init(credential: URLCredential, protectionSpace: URLProtectionSpace) {
super.init(credential: credential, protectionSpace: protectionSpace)
}
}
class MirrorLogin: ServerLogin {
var isOverridden: Bool = false
}
class LocalLogin: Login {
var syncStatus: SyncStatus = .synced
var isDeleted: Bool = false
var localModified: Timestamp = 0
}
public protocol BrowserLogins {
func getUsageDataForLoginByGUID(_ guid: GUID) -> Deferred<Maybe<LoginUsageData>>
func getLoginDataForGUID(_ guid: GUID) -> Deferred<Maybe<Login>>
func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>>
func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace, withUsername username: String?) -> Deferred<Maybe<Cursor<LoginData>>>
func getAllLogins() -> Deferred<Maybe<Cursor<Login>>>
func searchLoginsWithQuery(_ query: String?) -> Deferred<Maybe<Cursor<Login>>>
// Add a new login regardless of whether other logins might match some fields. Callers
// are responsible for querying first if they care.
@discardableResult func addLogin(_ login: LoginData) -> Success
@discardableResult func updateLoginByGUID(_ guid: GUID, new: LoginData, significant: Bool) -> Success
// Add the use of a login by GUID.
@discardableResult func addUseOfLoginByGUID(_ guid: GUID) -> Success
func removeLoginByGUID(_ guid: GUID) -> Success
func removeLoginsWithGUIDs(_ guids: [GUID]) -> Success
func removeAll() -> Success
}
public protocol SyncableLogins: AccountRemovalDelegate {
/**
* Delete the login with the provided GUID. Succeeds if the GUID is unknown.
*/
func deleteByGUID(_ guid: GUID, deletedAt: Timestamp) -> Success
func applyChangedLogin(_ upstream: ServerLogin) -> Success
func getModifiedLoginsToUpload() -> Deferred<Maybe<[Login]>>
func getDeletedLoginsToUpload() -> Deferred<Maybe<[GUID]>>
/**
* Chains through the provided timestamp.
*/
func markAsSynchronized<T: Collection>(_: T, modified: Timestamp) -> Deferred<Maybe<Timestamp>> where T.Iterator.Element == GUID
func markAsDeleted<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID
/**
* For inspecting whether we're an active participant in login sync.
*/
func hasSyncedLogins() -> Deferred<Maybe<Bool>>
}
open class LoginDataError: MaybeErrorType {
open let description: String
public init(description: String) {
self.description = description
}
}
|
mpl-2.0
|
d4c906443d890ba4793aaab78194b490
| 35.561997 | 156 | 0.636512 | 4.840119 | false | false | false | false |
MrAdamBoyd/SwiftBus
|
Pod/Classes/SwiftBusRequestURLs.swift
|
1
|
866
|
//
// RequestURLs.swift
// SwiftBus
//
// Created by Adam on 2015-08-29.
// Copyright (c) 2017 Adam Boyd. All rights reserved.
//
import Foundation
let allAgenciesURL = "http://webservices.nextbus.com/service/publicXMLFeed?command=agencyList"
let allRoutesURL = "http://webservices.nextbus.com/service/publicXMLFeed?command=routeList&a="
let routeConfigURL = "http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a="
let vehicleLocationsURL = "http://webservices.nextbus.com/service/publicXMLFeed?command=vehicleLocations&a="
let multiplePredictionsURL = "http://webservices.nextbus.com/service/publicXMLFeed?command=predictionsForMultiStops&a="
let stopPredictionsURL = "http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a="
let routeURLSegment = "&r="
let stopURLSegment = "&s="
let multiStopURLSegment = "&stops="
|
mit
|
bef7ef6e94a4fe9f7e7231318152f839
| 44.578947 | 119 | 0.786374 | 3.267925 | false | true | false | false |
shhuangtwn/ProjectLynla
|
Pods/SwiftCharts/SwiftCharts/Axis/ChartAxisValuesGenerator.swift
|
1
|
8477
|
//
// ChartAxisValuesGenerator.swift
// swift_charts
//
// Created by ischuetz on 12/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public typealias ChartAxisValueGenerator = Double -> ChartAxisValue
/// Dynamic axis values generation
public struct ChartAxisValuesGenerator {
/**
Calculates the axis values that bound some chart points along the X axis
Think of a segment as the "space" between two axis values.
- parameter chartPoints: The chart points to bound.
- parameter minSegmentCount: The minimum number of segments in the range of axis values. This value is prioritized over the maximum in order to prevent a conflict.
- parameter maxSegmentCount: The maximum number of segments in the range of axis values.
- parameter multiple: The desired width of each segment between axis values.
- parameter axisValueGenerator: Function that converts a scalar value to an axis value.
- parameter addPaddingSegmentIfEdge: Whether or not to add an extra value to the start and end if the first and last chart points fall exactly on the axis values.
- returns: An array of axis values.
*/
public static func generateXAxisValuesWithChartPoints(chartPoints: [ChartPoint], minSegmentCount: Double, maxSegmentCount: Double, multiple: Double = 10, axisValueGenerator: ChartAxisValueGenerator, addPaddingSegmentIfEdge: Bool) -> [ChartAxisValue] {
return self.generateAxisValuesWithChartPoints(chartPoints, minSegmentCount: minSegmentCount, maxSegmentCount: maxSegmentCount, multiple: multiple, axisValueGenerator: axisValueGenerator, addPaddingSegmentIfEdge: addPaddingSegmentIfEdge, axisPicker: {$0.x})
}
/**
Calculates the axis values that bound some chart points along the Y axis
Think of a segment as the "space" between two axis values.
- parameter chartPoints: The chart points to bound.
- parameter minSegmentCount: The minimum number of segments in the range of axis values. This value is prioritized over the maximum in order to prevent a conflict.
- parameter maxSegmentCount: The maximum number of segments in the range of axis values.
- parameter multiple: The desired width of each segment between axis values.
- parameter axisValueGenerator: Function that converts a scalar value to an axis value.
- parameter addPaddingSegmentIfEdge: Whether or not to add an extra value to the start and end if the first and last chart points fall exactly on the axis values.
- returns: An array of axis values.
*/
public static func generateYAxisValuesWithChartPoints(chartPoints: [ChartPoint], minSegmentCount: Double, maxSegmentCount: Double, multiple: Double = 10, axisValueGenerator: ChartAxisValueGenerator, addPaddingSegmentIfEdge: Bool) -> [ChartAxisValue] {
return self.generateAxisValuesWithChartPoints(chartPoints, minSegmentCount: minSegmentCount, maxSegmentCount: maxSegmentCount, multiple: multiple, axisValueGenerator: axisValueGenerator, addPaddingSegmentIfEdge: addPaddingSegmentIfEdge, axisPicker: {$0.y})
}
/**
Calculates the axis values that bound some chart points along a particular axis dimension.
Think of a segment as the "space" between two axis values.
- parameter chartPoints: The chart points to bound.
- parameter minSegmentCount: The minimum number of segments in the range of axis values. This value is prioritized over the maximum in order to prevent a conflict.
- parameter maxSegmentCount: The maximum number of segments in the range of axis values.
- parameter multiple: The desired width of each segment between axis values.
- parameter axisValueGenerator: Function that converts a scalar value to an axis value.
- parameter addPaddingSegmentIfEdge: Whether or not to add an extra value to the start and end if the first and last chart points fall exactly on the axis values.
- parameter axisPicker: A function that maps a chart point to its value for a particular axis.
- returns: An array of axis values.
*/
private static func generateAxisValuesWithChartPoints(chartPoints: [ChartPoint], minSegmentCount: Double, maxSegmentCount: Double, multiple: Double = 10, axisValueGenerator: ChartAxisValueGenerator, addPaddingSegmentIfEdge: Bool, axisPicker: (ChartPoint) -> ChartAxisValue) -> [ChartAxisValue] {
let sortedChartPoints = chartPoints.sort {(obj1, obj2) in
return axisPicker(obj1).scalar < axisPicker(obj2).scalar
}
if let first = sortedChartPoints.first, last = sortedChartPoints.last {
return self.generateAxisValuesWithChartPoints(axisPicker(first).scalar, last: axisPicker(last).scalar, minSegmentCount: minSegmentCount, maxSegmentCount: maxSegmentCount, multiple: multiple, axisValueGenerator: axisValueGenerator, addPaddingSegmentIfEdge: addPaddingSegmentIfEdge)
} else {
print("Trying to generate Y axis without datapoints, returning empty array")
return []
}
}
/**
Calculates the axis values that bound two values and have an optimal number of segments between them.
Think of a segment as the "space" between two axis values.
- parameter first: The first scalar value to bound.
- parameter last: The last scalar value to bound.
- parameter minSegmentCount: The minimum number of segments in the range of axis values. This value is prioritized over the maximum in order to prevent a conflict.
- parameter maxSegmentCount: The maximum number of segments in the range of axis values.
- parameter multiple: The desired width of each segment between axis values.
- parameter axisValueGenerator: Function that converts a scalar value to an axis value.
- parameter addPaddingSegmentIfEdge: Whether or not to add an extra value to the start and end if the first and last scalar values fall exactly on the axis values.
- returns: An array of axis values
*/
private static func generateAxisValuesWithChartPoints(first: Double, last lastPar: Double, minSegmentCount: Double, maxSegmentCount: Double, multiple: Double, axisValueGenerator: ChartAxisValueGenerator, addPaddingSegmentIfEdge: Bool) -> [ChartAxisValue] {
guard lastPar >= first else {fatalError("Invalid range generating axis values")}
let last = lastPar == first ? lastPar + 1 : lastPar
// The first axis value will be less than or equal to the first scalar value, aligned with the desired multiple
var firstValue = first - (first % multiple)
// The last axis value will be greater than or equal to the first scalar value, aligned with the desired multiple
var lastValue = last + (abs(multiple - last) % multiple)
var segmentSize = multiple
// If there should be a padding segment added when a scalar value falls on the first or last axis value, adjust the first and last axis values
if firstValue == first && addPaddingSegmentIfEdge {
firstValue = firstValue - segmentSize
}
if lastValue == last && addPaddingSegmentIfEdge {
lastValue = lastValue + segmentSize
}
let distance = lastValue - firstValue
var currentMultiple = multiple
var segmentCount = distance / currentMultiple
// Find the optimal number of segments and segment width
// If the number of segments is greater than desired, make each segment wider
while segmentCount > maxSegmentCount {
currentMultiple *= 2
segmentCount = distance / currentMultiple
}
segmentCount = ceil(segmentCount)
// Increase the number of segments until there are enough as desired
while segmentCount < minSegmentCount {
segmentCount += 1
}
segmentSize = currentMultiple
// Generate axis values from the first value, segment size and number of segments
let offset = firstValue
return (0...Int(segmentCount)).map {segment in
let scalar = offset + (Double(segment) * segmentSize)
return axisValueGenerator(scalar)
}
}
}
|
mit
|
acf33ee02b96fd283c0294047917c4a5
| 57.868056 | 299 | 0.707562 | 5.606481 | false | false | false | false |
piscoTech/Workout
|
WorkoutHelper/SceneDelegate.swift
|
1
|
2579
|
//
// SceneDelegate.swift
// WorkoutHelper
//
// Created by Marco Boschi on 27/10/2019.
// Copyright © 2019 Marco Boschi. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
|
mit
|
e001690683b1abd1b96e709020f5a83a
| 39.28125 | 141 | 0.756012 | 4.67029 | false | false | false | false |
DANaini13/stanford-IOS-Assignments-Calculator-CS193P
|
Assn2/Clacuator/CalculatorBrain.swift
|
1
|
14280
|
//
// CalculatorBrain.swift
// Clacuator
//
// Created by zeyong shan on 10/4/17.
// Copyright © 2017 zeyong shan. All rights reserved.
//
import Foundation
/**
ClaculatorBrain is core of the claculator.
- public functions:
1. func setOperand(_ num: Double)
2. func setOperand(variable named: String)
3. func perfromOperator(_ symbol: String)
4. func undo()
5. func evaluate(using variables: Dictionary<String, Double>? = default) -> (result: Double?, isPending: Bool, description: String)
- public variables
1. result
2. description
*/
public struct ClacualtorBrain {
/**
The variable that generate the description for calculatorBrain
*/
private var descriptionGenerator = DescriptionGenerator()
/**
The abstract data type that stand for different operations:
constant, generate number functions, unary operations,
binaryOperations, and equal sign.
*/
private enum Operation {
case constant(Double)
case unaryOperationPrefix((Double) -> Double)
case unaryOperationPostfix((Double) -> Double)
case binaryOperation((Double, Double) -> Double)
case equal
}
/**
The abstract data type that defien the Operand
- include:
1. Ternimal: value, variable
2. Non-ternimal: resultOfStep
*/
private enum Operand {
case value(Double)
case resultOfStep(Int)
case variable(String)
}
/**
The abstract data type that define the Step.
*/
private enum Step {
case constantGrabing(value: Double, description: DescriptionGenerator)
case unaryOperation(operation: (Double) -> Double, operand: Operand, description: DescriptionGenerator)
case pendingBinaryOperation(operation: (Double, Double) -> Double, operand: Operand, description: DescriptionGenerator)
case performBinaryOperation(pedingStep: (Int), secondOperand: Operand, description: DescriptionGenerator)
}
/**
the variable that store the current Operand.
*/
private var currentOperand: Operand?
/**
the variable that shows if the currentOperand has been reseted.
*/
private var operandSet = false
/**
the variable that shows the pending step if there is a step are pending in the steps.
*/
private var pendingStep: Int?
/**
an array to store every calculation steps
*/
private var steps:[Step] = [] {
didSet {
guard steps.count != 0 else {
descriptionGenerator = DescriptionGenerator()
return
}
if case Step.pendingBinaryOperation = steps.last! {
pendingStep = steps.count - 1
}
switch steps.last! {
case .constantGrabing(_, let context):
descriptionGenerator = context
case .unaryOperation(_, _, let context):
descriptionGenerator = context
case .pendingBinaryOperation(_, _, let context):
descriptionGenerator = context
case .performBinaryOperation(_, _, let context):
descriptionGenerator = context
}
}
}
/**
operators is a dictionary that store the operations that would
used in this calculator brain with string as keys. the operations
include,"π", "e", "cos", "sin", "tan", "^2", "^3", "√", "±", "lg",
"abs", "%", "rand", "+", "-", "×", "÷" and "="
*/
private var operators: Dictionary<String, Operation> = [
"π" : Operation.constant(Double.pi),
"e" : Operation.constant(M_E),
"cos" : Operation.unaryOperationPrefix(cos),
"sin" : Operation.unaryOperationPrefix(sin),
"tan" : Operation.unaryOperationPrefix(tan),
"^2" : Operation.unaryOperationPostfix({pow($0, 2)}),
"^3" : Operation.unaryOperationPostfix({pow($0, 3)}),
"√" : Operation.unaryOperationPrefix(sqrt),
"±" : Operation.unaryOperationPrefix({-$0}),
"lg" : Operation.unaryOperationPrefix({log($0)}),
"abs" : Operation.unaryOperationPrefix(abs),
"%" : Operation.unaryOperationPostfix({$0/100}),
"+" : Operation.binaryOperation(+),
"-" : Operation.binaryOperation(-),
"×" : Operation.binaryOperation(*),
"÷" : Operation.binaryOperation(/),
"=" : Operation.equal
]
/**
The computed properity that return a bool, which
shows that if the current result is being pending
*/
public var resultIsPending: Bool {
return descriptionGenerator.resultIsPending
}
/**
The function that set the operand (Double) to the calculatorBrain,
either the fist or the second.
- parameter num: the number that will replace the accumulator.
- Author:
Zeyong Shan
- Important:
This function will modify the accumulator
- Version:
0.1
*/
public mutating func setOperand(_ num: Double) {
let formattedValue:String
let numberFormatter = NumberFormatter()
if (num < 0 && num > -0.0000001) || (num > 0 && num < 0.0000001) || num > 1000000 || num < -1000000{
numberFormatter.numberStyle = NumberFormatter.Style.scientific
}else {
numberFormatter.numberStyle = NumberFormatter.Style.decimal
}
numberFormatter.maximumFractionDigits = 6
let nsNumber: NSDecimalNumber = NSDecimalNumber(value: num)
formattedValue = numberFormatter.string(from: nsNumber)!
descriptionGenerator.addConstant(currentNum: formattedValue)
currentOperand = Operand.value(num)
operandSet = true
}
/**
The function that set the operand (Double) to the calculatorBrain,
either the fist or the second.
- parameter num: the number that will replace the accumulator.
- Author:
Zeyong Shan
- Important:
This function will modify the accumulator
- Version:
0.1
*/
public mutating func setOperand(variable named: String) {
descriptionGenerator.addConstant(currentNum: named)
currentOperand = Operand.variable(named)
operandSet = true
}
/**
The function will perform the operation that passed in.
The new result would be replaced to public read-only
property result.
- parameter symbol: this parameter sotre the symbol of operation that will be done
for this function.
- Author:
Zeyong Shan
- Important:
This function will modify the internel steps
- Version:
0.1
*/
public mutating func perfromOperator(_ symbol: String) {
guard let myOperator = operators[symbol] else {
return
}
switch myOperator {
case .constant(let value):
descriptionGenerator.addConstant(currentNum: symbol)
steps.append(Step.constantGrabing(value: value, description: descriptionGenerator))
operandSet = true
case .unaryOperationPrefix(let function):
descriptionGenerator.addUnaryOperationToCurrentDescription(operation: symbol, prefix: true)
if operandSet {
steps.append(Step.unaryOperation(operation: function, operand: currentOperand!, description: descriptionGenerator))
} else {
guard steps.count != 0 else {
return
}
steps.append(Step.unaryOperation(operation: function, operand: Operand.resultOfStep(steps.count-1), description: descriptionGenerator))
}
case .unaryOperationPostfix(let function):
descriptionGenerator.addUnaryOperationToCurrentDescription(operation: symbol, prefix: false)
if operandSet {
steps.append(Step.unaryOperation(operation: function, operand: currentOperand!, description: descriptionGenerator))
} else {
guard steps.count != 0 else {
return
}
steps.append(Step.unaryOperation(operation: function, operand: Operand.resultOfStep(steps.count-1), description: descriptionGenerator))
}
case .binaryOperation(let function):
if pendingStep != nil {
perfromOperator("=")
}
descriptionGenerator.addBinaryOperation(operation: symbol)
if operandSet {
steps.append(Step.pendingBinaryOperation(operation: function, operand: currentOperand!, description: descriptionGenerator))
} else {
guard steps.count != 0 else {
return
}
steps.append(Step.pendingBinaryOperation(operation: function, operand: Operand.resultOfStep(steps.count-1), description: descriptionGenerator))
}
pendingStep = steps.count - 1
case .equal:
guard pendingStep != nil && steps.count != 0 else {
return
}
descriptionGenerator.performBinaryOperation()
if operandSet {
steps.append(Step.performBinaryOperation(pedingStep: pendingStep!, secondOperand: currentOperand!, description: descriptionGenerator))
} else {
steps.append(Step.performBinaryOperation(pedingStep: pendingStep!, secondOperand: Operand.resultOfStep(steps.count - 1), description: descriptionGenerator))
}
pendingStep = nil
}
operandSet = false
}
/**
The function will perform the undo operation and update all the current information
include: Description, Result, ResultIsPending
- Author:
Zeyong Shan
- Important:
This function will modify the internal steps.
- Version:
0.1
*/
public mutating func undo() {
guard steps.count != 0 else {
return
}
steps.removeLast()
}
/**
The public read-only property that return the current value of the calculator brain.
*/
public var result: Double {
return calculateResult(stepNum: steps.count - 1) ?? 0
}
/**
The public read-only property that return the current description of the calculator brain.
*/
public var description: String {
return descriptionGenerator.description
}
/**
The function get the result through all the stored operations.
Start from the last step until hit terminals.
- parameter variables: this is a dictionary that stores all the variables. For example ["x":5, "m":-1]
This function will evaluate the result accroding to the dictionary that provided. If it didn't find
the needed variables in the dictionary, then the value of those variabes will be set to zero.
- returns:
it will return a tuple that contains the result, isPending and the newest description.
- Author:
Zeyong Shan
- Version:
0.1
*/
public func evaluate(using variables: Dictionary<String, Double>? = nil) ->
(result: Double?, isPending: Bool, description: String) {
let result = calculateResult(using: variables, stepNum: steps.count - 1)
let isPending = pendingStep != nil
return (result, isPending, description)
}
/**
The function get the result through all the stored operations.
Start from the last step until hit terminals.
- parameter variables: this is a dictionary that stores all the variables. For example ["x":5, "m":-1]
This function will evaluate the result accroding to the dictionary that provided. If it didn't find
the needed variables in the dictionary, then the value of those variabes will be set to zero.
- returns:
it will return an Optional that store the calculated result.
- Author:
Zeyong Shan
- Version:
0.1
*/
private func calculateResult(using variables: Dictionary<String, Double>? = nil, stepNum: Int) -> Double? {
if stepNum >= steps.count || stepNum < 0 {
return nil
}
switch steps[stepNum] {
case .constantGrabing(let value, _):
return value
case .unaryOperation(let function, let operand, _):
return function(calculateOperand(using: variables, operand: operand)!)
case .pendingBinaryOperation:
return calculateOperand(using: variables, operand: currentOperand ?? Operand.value(0))
case .performBinaryOperation(let pendingStepNum, let operandSecond, _):
if case let .pendingBinaryOperation(function, operandFirst, _) = steps[pendingStepNum] {
let first = calculateOperand(using: variables, operand: operandFirst)
let second = calculateOperand(using: variables, operand: operandSecond)
return function(first ?? 0, second ?? 0)
}
return 0
}
}
/**
The function is the helper function for calculateResult(...) This function will see if the operand is
- parameters:
- variables:
this is a dictionary that stores all the variables. For example ["x":5, "m":-1]
This function will evaluate the result accroding to the dictionary that provided. If it didn't find
the needed variables in the dictionary, then the value of those variabes will be set to zero.
- operand:
to store the operand that will be calclated.
- returns:
it will return an Optional that store the calculated result.
- Author:
Zeyong Shan
- Version:
0.1
*/
private func calculateOperand(using variables: Dictionary<String, Double>? = nil, operand: Operand) -> Double? {
switch operand {
case .value(let value):
return value
case .resultOfStep(let stepNum):
return calculateResult(using: variables, stepNum: stepNum)
case .variable(let name):
let value = variables?[name] ?? 0
return value
}
}
}
|
mpl-2.0
|
e8ced3c611aa237cce08c04366255bab
| 35.676093 | 172 | 0.6187 | 4.877607 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Analytics/Tests/AnalyticsKitTests/Events/AnalyticsEventTests.swift
|
1
|
1957
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import XCTest
@testable import AnalyticsKit
final class AnalyticsEventTests: XCTestCase {
enum NabuEvent: AnalyticsEvent {
var type: AnalyticsEventType { .nabu }
case simpleEventWithoutParams
case eventWithParams(nameOfTheParam: String, valueOfTheParam: Double)
case eventWithCustom(custom: CustomEnum)
enum CustomEnum: String, StringRawRepresentable {
case type = "TYPE"
}
}
enum FirebaseEvent: AnalyticsEvent {
case eventWithParams(nameOfTheParam: String, valueOfTheParam: Double)
}
func test_nabuAnalyticsEventReflection_simpleEventTitleAndParams() throws {
let event: NabuEvent = .simpleEventWithoutParams
XCTAssertEqual(event.name, "Simple Event Without Params")
XCTAssertEqual(event.params?.count, 0)
}
func test_nabuAnalyticsEventReflection_advancedEventTitleAndParams() throws {
let event: NabuEvent = .eventWithParams(nameOfTheParam: "The Name", valueOfTheParam: 3)
XCTAssertEqual(event.name, "Event With Params")
XCTAssertEqual(event.params?.count, 2)
XCTAssertEqual(event.params?["name_of_the_param"] as? String, "The Name")
XCTAssertEqual(event.params?["value_of_the_param"] as? Double, 3)
}
func test_nabuAnalyticsEventReflection_advancedEventCustomEnum() throws {
let event: NabuEvent = .eventWithCustom(custom: .type)
XCTAssertEqual(event.name, "Event With Custom")
XCTAssertEqual(event.params?.count, 1)
XCTAssertEqual(event.params?["custom"] as? String, "TYPE")
}
func test_firebaseAnalyticsEventReflection_advancedEventReflectedTitleAndParams() throws {
let event: FirebaseEvent = .eventWithParams(nameOfTheParam: "The Name", valueOfTheParam: 3)
XCTAssertEqual(event.name, "Event With Params")
XCTAssertNil(event.params)
}
}
|
lgpl-3.0
|
c9aaa18d2e0eb80c5071724d62a606f6
| 35.222222 | 99 | 0.705521 | 4.496552 | false | true | false | false |
samwyndham/DictateSRS
|
DictateSRS/Coordinators/CreateDeckCoordinator.swift
|
1
|
2478
|
//
// CreateDeckCoordinator.swift
// DictateSRS
//
// Created by Sam Wyndham on 25/01/2017.
// Copyright © 2017 Sam Wyndham. All rights reserved.
//
import UIKit
import RealmSwift
import ReactiveKit
protocol CreateDeckCoordinatorDelegate: CoordinatorDelegate {}
final class CreateDeckCoordinator: Coordinator {
fileprivate let rootVC: UIViewController
private let store: Store
weak var delegate: CreateDeckCoordinatorDelegate?
init(root: UIViewController, store: Store) {
self.rootVC = root
self.store = store
}
func start() {
let vc = createDeckController()
rootVC.present(vc, animated: true)
}
private func cancel() {
delegate?.coordinatorDidFinish(self)
}
private func createDeck(name: String) {
do {
let deck = RealmDeck(name: name)
try store.main.write {
store.main.add(deck)
}
} catch let error as NSError {
let alert = AlertFactory()
.setTitle(L10n.CreateDeck.Alert.CreateDeckFailed.title)
.setMessage(error.localizedDescription)
.addDefaultAction()
.make()
rootVC.present(alert, animated: true)
}
delegate?.coordinatorDidFinish(self)
}
private func createDeckController() -> UIViewController {
var nameTextField: UITextField!
return AlertFactory()
.setTitle(L10n.CreateDeck.Alert.CreateDeck.title)
.addTextField { (textField) in
textField.placeholder = L10n.CreateDeck.Alert.CreateDeck.NameTextField.placeholder
textField.autocapitalizationType = .sentences
nameTextField = textField
}
.addCancelAction { [unowned self] (_) in
self.cancel()
}
.addAction(title: L10n.CreateDeck.Alert.CreateDeck.CreateButton.title) { [unowned self] (_) in
self.createDeck(name: nameTextField.text ?? "")
}
.make()
}
}
//extension CreateDeckCoordinator: CardListCoordinatorDelegate {
// var importing: AnyProperty<Bool> {
// guard let delegate = delegate else { preconditionFailure("There must be a delegate") }
// return delegate.importing
// }
//
// func importFile(url: URL, deckID: String) {
// delegate?.importFile(url: url, deckID: deckID)
// }
//}
|
mit
|
9938bcb97c7b50294473046b5e587ad4
| 29.207317 | 106 | 0.605571 | 4.656015 | false | false | false | false |
ckjavacoder/JSONExport
|
JSONExport/HeaderFileRepresenter.swift
|
2
|
6898
|
//
// HeaderFileRepresenter.swift
// JSONExport
// Created by Ahmed Ali on 11/23/14.
// Copyright (c) 2014 Ahmed Ali. [email protected].
//
// 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. The name of the contributor can not 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 Foundation
import AddressBook
class HeaderFileRepresenter : FileRepresenter{
/**
Generates the header file content and stores it in the fileContent property
*/
override func toString() -> String{
fileContent = ""
appendCopyrights()
appendStaticImports()
appendImportParentHeader()
appendCustomImports()
//start the model defination
var definition = ""
if lang.headerFileData.modelDefinitionWithParent != nil && count(parentClassName) > 0{
definition = lang.headerFileData.modelDefinitionWithParent.stringByReplacingOccurrencesOfString(modelName, withString: className)
definition = definition.stringByReplacingOccurrencesOfString(modelWithParentClassName, withString: parentClassName)
}else{
definition = lang.headerFileData.modelDefinition.stringByReplacingOccurrencesOfString(modelName, withString: className)
}
fileContent += definition
//start the model content body
fileContent += "\(lang.modelStart)"
appendProperties()
appendInitializers()
appendUtilityMethods()
fileContent += lang.modelEnd
return fileContent
}
/**
Appends the lang.headerFileData.staticImports if any
*/
override func appendStaticImports()
{
if lang.headerFileData.staticImports != nil{
fileContent += lang.headerFileData.staticImports
fileContent += "\n"
}
}
func appendImportParentHeader()
{
if lang.headerFileData.importParentHeaderFile != nil && count(parentClassName) > 0{
fileContent += lang.headerFileData.importParentHeaderFile.stringByReplacingOccurrencesOfString(modelWithParentClassName, withString: parentClassName)
}
}
/**
Tries to access the address book in order to fetch basic information about the author so it can include a nice copyright statment
*/
override func appendCopyrights()
{
if let me = ABAddressBook.sharedAddressBook()?.me(){
fileContent += "//\n//\t\(className).\(lang.headerFileData.headerFileExtension)\n"
if let firstName = me.valueForProperty(kABFirstNameProperty as String) as? String{
fileContent += "//\n//\tCreate by \(firstName)"
if let lastName = me.valueForProperty(kABLastNameProperty as String) as? String{
fileContent += " \(lastName)"
}
}
fileContent += " on \(getTodayFormattedDay())\n//\tCopyright © \(getYear())"
if let organization = me.valueForProperty(kABOrganizationProperty as String) as? String{
fileContent += " \(organization)"
}
fileContent += ". All rights reserved.\n//\n\n"
fileContent += "//\tModel file Generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport\n\n"
}
}
/**
Loops on all properties which has a custom type and appends the custom import from the lang.headerFileData's importForEachCustomType property
*/
override func appendCustomImports()
{
if lang.importForEachCustomType != nil{
for property in properties{
if property.isCustomClass{
fileContent += lang.headerFileData.importForEachCustomType.stringByReplacingOccurrencesOfString(modelName, withString: property.type)
}else if property.isArray{
//if it is an array of custom types
let basicTypes = lang.dataTypes.toDictionary().allValues as! [String]
if find(basicTypes, property.elementsType) == nil{
fileContent += lang.headerFileData.importForEachCustomType.stringByReplacingOccurrencesOfString(modelName, withString: property.elementsType)
}
}
}
}
}
/**
Appends all the properties using the Property.stringPresentation method
*/
override func appendProperties()
{
fileContent += "\n"
for property in properties{
fileContent += property.toString(forHeaderFile: true)
}
}
/**
Appends all the defined constructors (aka initializers) in lang.constructors to the fileContent
*/
override func appendInitializers()
{
if !includeConstructors{
return
}
fileContent += "\n"
for constructorSignature in lang.headerFileData.constructorSignatures{
fileContent += constructorSignature
fileContent = fileContent.stringByReplacingOccurrencesOfString(modelName, withString: className)
}
}
/**
Appends all the defined utility methods in lang.utilityMethods to the fileContent
*/
override func appendUtilityMethods()
{
if !includeUtilities{
return
}
fileContent += "\n"
for methodSignature in lang.headerFileData.utilityMethodSignatures{
fileContent += methodSignature
}
}
}
|
mit
|
7d894a48ad8e8161d8180074c7e40ecb
| 37.752809 | 165 | 0.653907 | 5.297235 | false | false | false | false |
thelukester92/swift-engine
|
swift-engine/Engine/Components/LGPhysicsBody.swift
|
1
|
2239
|
//
// LGPhysicsBody.swift
// swift-engine
//
// Created by Luke Godfrey on 6/7/14.
// Copyright (c) 2014 Luke Godfrey. See LICENSE.
//
import SpriteKit
public final class LGPhysicsBody: LGComponent
{
public class func type() -> String
{
return "LGPhysicsBody"
}
public func type() -> String
{
return LGPhysicsBody.type()
}
public var velocity = LGVector()
public var width: Double
public var height: Double
public var dynamic: Bool
public var trigger = false
// TODO: allow other kinds of directional collisions
public var onlyCollidesVertically = false
public var collidedTop = false
public var collidedBottom = false
public var collidedLeft = false
public var collidedRight = false
public var collidedWith = [Int:LGEntity]()
public init(width: Double, height: Double, dynamic: Bool = true)
{
self.width = width
self.height = height
self.dynamic = dynamic
}
public convenience init(size: LGVector, dynamic: Bool = true)
{
self.init(width: size.x, height: size.y, dynamic: dynamic)
}
public convenience init()
{
self.init(width: 0, height: 0)
}
}
extension LGPhysicsBody: LGDeserializable
{
public class var requiredProps: [String]
{
return [ "width", "height" ]
}
public class var optionalProps: [String]
{
return [ "dynamic", "onlyCollidesVertically", "trigger", "velocity" ]
}
public class func instantiate() -> LGDeserializable
{
return LGPhysicsBody()
}
public func setValue(value: LGJSON, forKey key: String) -> Bool
{
switch key
{
case "width":
width = value.doubleValue!
return true
case "height":
height = value.doubleValue!
return true
case "dynamic":
dynamic = value.boolValue!
return true
case "onlyCollidesVertically":
onlyCollidesVertically = value.boolValue!
return true
case "trigger":
trigger = value.boolValue!
return true
case "velocity":
if let x = value["x"]?.doubleValue
{
velocity.x = x
}
if let y = value["y"]?.doubleValue
{
velocity.y = y
}
return true
default:
break
}
return false
}
public func valueForKey(key: String) -> LGJSON
{
return LGJSON(value: nil)
}
}
|
mit
|
3ab2b13999780e8c8a9620ef77aba662
| 17.203252 | 71 | 0.660116 | 3.321958 | false | false | false | false |
vapor/vapor
|
Sources/Vapor/Routing/Route.swift
|
2
|
989
|
public final class Route: CustomStringConvertible {
public var method: HTTPMethod
public var path: [PathComponent]
public var responder: Responder
public var requestType: Any.Type
public var responseType: Any.Type
public var userInfo: [AnyHashable: Any]
public var description: String {
let path = self.path.map { "\($0)" }.joined(separator: "/")
return "\(self.method.string) /\(path)"
}
public init(
method: HTTPMethod,
path: [PathComponent],
responder: Responder,
requestType: Any.Type,
responseType: Any.Type
) {
self.method = method
self.path = path
self.responder = responder
self.requestType = requestType
self.responseType = responseType
self.userInfo = [:]
}
@discardableResult
public func description(_ string: String) -> Route {
self.userInfo["description"] = string
return self
}
}
|
mit
|
df30dd75844ddcb55ce44b4cbca1eb86
| 27.257143 | 67 | 0.608696 | 4.945 | false | false | false | false |
alessiobrozzi/firefox-ios
|
UITests/ToolbarTests.swift
|
2
|
8210
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
import UIKit
class ToolbarTests: KIFTestCase, UITextFieldDelegate {
fileprivate var webRoot: String!
override func setUp() {
webRoot = SimplePageServer.start()
BrowserUtils.dismissFirstRunUI(tester())
}
/**
* Tests landscape page navigation enablement with the URL bar with tab switching.
*/
func testLandscapeNavigationWithTabSwitch() {
let previousOrientation = UIDevice.current.value(forKey: "orientation") as! Int
// Rotate to landscape.
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
tester().tapView(withAccessibilityIdentifier: "url")
let textView = tester().waitForView(withAccessibilityLabel: "Address and Search") as! UITextField
XCTAssertTrue(textView.text!.isEmpty, "Text is empty")
XCTAssertNotNil(textView.placeholder, "Text view has a placeholder to show when it's empty")
// Navigate to two pages and press back once so that all buttons are enabled in landscape mode.
let url1 = "\(webRoot)/numberedPage.html?page=1"
tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "\(url1)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page 1")
tester().tapView(withAccessibilityIdentifier: "url")
let textView2 = tester().waitForView(withAccessibilityLabel: "Address and Search") as! UITextField
XCTAssertEqual(textView2.text, url1, "Text is url")
let url2 = "\(webRoot)/numberedPage.html?page=2"
tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "\(url2)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page 2")
tester().tapView(withAccessibilityLabel: "Back")
tester().waitForWebViewElementWithAccessibilityLabel("Page 1")
// Open new tab and then go back to previous tab to test navigation buttons.
tester().tapView(withAccessibilityLabel: "Menu")
tester().tapView(withAccessibilityLabel: "New Tab")
tester().waitForView(withAccessibilityLabel: "Web content")
tester().tapView(withAccessibilityLabel: "Show Tabs")
tester().tapView(withAccessibilityLabel: "Page 1")
tester().waitForWebViewElementWithAccessibilityLabel("Page 1")
// Test to see if all the buttons are enabled then close tab.
tester().waitForTappableView(withAccessibilityLabel: "Back")
tester().waitForTappableView(withAccessibilityLabel: "Forward")
tester().waitForTappableView(withAccessibilityLabel: "Reload")
tester().waitForTappableView(withAccessibilityLabel: "Share")
tester().waitForTappableView(withAccessibilityLabel: "Menu")
tester().tapView(withAccessibilityLabel: "Show Tabs")
tester().swipeView(withAccessibilityLabel: "Page 1", in: KIFSwipeDirection.left)
// Go Back to other tab to see if all buttons are disabled.
tester().tapView(withAccessibilityLabel: "home")
tester().waitForView(withAccessibilityLabel: "Web content")
let back = tester().waitForView(withAccessibilityLabel: "Back") as! UIButton
let forward = tester().waitForView(withAccessibilityLabel: "Forward") as! UIButton
let reload = tester().waitForView(withAccessibilityLabel: "Reload") as! UIButton
let share = tester().waitForView(withAccessibilityLabel: "Share") as! UIButton
let menu = tester().waitForView(withAccessibilityLabel: "Menu") as! UIButton
XCTAssertFalse(back.isEnabled, "Back button should be disabled")
XCTAssertFalse(forward.isEnabled, "Forward button should be disabled")
XCTAssertFalse(reload.isEnabled, "Reload button should be disabled")
XCTAssertFalse(share.isEnabled, "Share button should be disabled")
XCTAssertTrue(menu.isEnabled, "Menu button should be enabled")
// Rotates back to previous orientation
UIDevice.current.setValue(previousOrientation, forKey: "orientation")
}
func testURLEntry() {
let textField = tester().waitForView(withAccessibilityIdentifier: "url") as! UITextField
tester().tapView(withAccessibilityIdentifier: "url")
tester().enterText(intoCurrentFirstResponder: "foobar")
tester().tapView(withAccessibilityLabel: "Cancel")
XCTAssertEqual(textField.text, "", "Verify that the URL bar text clears on about:home")
// 127.0.0.1 doesn't cause http:// to be hidden. localhost does. Both will work.
let localhostURL = webRoot.replacingOccurrences(of: "127.0.0.1", with: "localhost", options: NSString.CompareOptions(), range: nil)
let url = "\(localhostURL)/numberedPage.html?page=1"
// URL without "http://".
let displayURL = "\(localhostURL)/numberedPage.html?page=1".substring(from: url.characters.index(url.startIndex, offsetBy: "http://".characters.count))
tester().tapView(withAccessibilityIdentifier: "url")
tester().enterText(intoCurrentFirstResponder: "\(url)\n")
XCTAssertEqual(textField.text, displayURL, "URL matches page URL")
tester().tapView(withAccessibilityIdentifier: "url")
tester().enterText(intoCurrentFirstResponder: "foobar")
tester().tapView(withAccessibilityLabel: "Cancel")
XCTAssertEqual(textField.text, displayURL, "Verify that text reverts to page URL after entering text")
tester().tapView(withAccessibilityIdentifier: "url")
tester().clearTextFromFirstResponder()
tester().tapView(withAccessibilityLabel: "Cancel")
XCTAssertEqual(textField.text, displayURL, "Verify that text reverts to page URL after clearing text")
}
func testClearURLTextUsingBackspace() {
// 127.0.0.1 doesn't cause http:// to be hidden. localhost does. Both will work.
let localhostURL = webRoot.replacingOccurrences(of: "127.0.0.1", with: "localhost", options: NSString.CompareOptions(), range: nil)
let url = "\(localhostURL)/numberedPage.html?page=1"
_ = tester().waitForView(withAccessibilityIdentifier: "url") as! UITextField
tester().tapView(withAccessibilityIdentifier: "url")
tester().enterText(intoCurrentFirstResponder: url+"\n")
tester().waitForAnimationsToFinish()
tester().tapView(withAccessibilityIdentifier: "url")
tester().waitForKeyInputReady()
tester().enterText(intoCurrentFirstResponder: "\u{8}")
let autocompleteField = tester().waitForView(withAccessibilityIdentifier: "address") as! UITextField
XCTAssertEqual(autocompleteField.text, "", "Verify that backspace keypress deletes text when url is highlighted")
}
func testUserInfoRemovedFromURL() {
let hostWithUsername = webRoot.replacingOccurrences(of: "127.0.0.1", with: "username:[email protected]", options: NSString.CompareOptions(), range: nil)
let urlWithUserInfo = "\(hostWithUsername)/numberedPage.html?page=1"
let url = "\(webRoot)/numberedPage.html?page=1"
_ = tester().waitForView(withAccessibilityIdentifier: "url") as! UITextField
tester().tapView(withAccessibilityIdentifier: "url")
tester().enterText(intoCurrentFirstResponder: urlWithUserInfo+"\n")
tester().waitForAnimationsToFinish()
let urlField = tester().waitForView(withAccessibilityIdentifier: "url") as! UITextField
XCTAssertEqual(urlField.text, url)
}
override func tearDown() {
let previousOrientation = UIDevice.current.value(forKey: "orientation") as! Int
if previousOrientation == UIInterfaceOrientation.landscapeLeft.rawValue {
// Rotate back to portrait
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
BrowserUtils.resetToAboutHome(tester())
BrowserUtils.clearPrivateData(tester: tester())
}
}
|
mpl-2.0
|
04f4b2df337766161b714d5c0abdceec
| 51.292994 | 161 | 0.703045 | 5.28314 | false | true | false | false |
akane/Akane
|
Akane/Akane/Binding/Observation/ViewModelObservation.swift
|
1
|
1650
|
//
// This file is part of Akane
//
// Created by JC on 06/12/15.
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code
//
import Foundation
public class ViewModelObservation<ViewModelType: ComponentViewModel> : Observation {
public var value: ViewModelType? = nil
public var next: [((ViewModelType) -> Void)] = []
unowned let container: ComponentContainer
let observer: ViewObserver
public init(value: ViewModelType?, container: ComponentContainer, observer: ViewObserver) {
self.container = container
self.value = value
self.observer = observer
}
}
extension ViewModelObservation {
public func bind<ViewType: Hashable & ComponentDisplayable>(to view: ViewType?) where ViewType.Parameters == ViewModelType {
if let view = view {
self.bind(to: view)
}
}
public func bind<ViewType: Hashable & ComponentDisplayable & Wrapped>(to view: ViewType)
where ViewType.Parameters == ViewModelType, ViewType.Wrapper.Parameters == ViewModelType {
let binding = DisplayObservation(view: view, container: self.container, observer: self.observer)
if let value = self.value {
binding.to(params: value)
}
}
public func bind<ViewType: Hashable & ComponentDisplayable>(to view: ViewType) where ViewType.Parameters == ViewModelType {
let binding = DisplayObservation(view: view, container: self.container, observer: self.observer)
if let value = self.value {
binding.to(params: value)
}
}
}
|
mit
|
739a5cc64b36f6e28a209e60a90f2991
| 32 | 128 | 0.675758 | 4.727794 | false | false | false | false |
OatmealCode/Oatmeal
|
Example/Pods/Carlos/Carlos/ComposedOneWayTransformer.swift
|
2
|
5560
|
import Foundation
import PiedPiper
extension OneWayTransformer {
/**
Composes the transformer with another OneWayTransformer
- parameter transformer: The second OneWayTransformer to apply
- returns: A new OneWayTransformer that is the result of the composition of the two OneWayTransformers
*/
public func compose<A: OneWayTransformer where A.TypeIn == TypeOut>(transformer: A) -> OneWayTransformationBox<TypeIn, A.TypeOut> {
return OneWayTransformationBox(transform: self.transform >>> transformer.transform)
}
/**
Composes the transformer with a transformation closure
- parameter transformerClosure: The transformation closure to apply after
- returns: A new OneWayTransformer that is the result of the composition of the transformer with the transformation closure
*/
@available(*, deprecated=0.7)
public func compose<A>(transformerClosure: TypeOut -> Future<A>) -> OneWayTransformationBox<TypeIn, A> {
return self.compose(wrapClosureIntoOneWayTransformer(transformerClosure))
}
}
/**
Composes two OneWayTransformers
- parameter firstTransformer: The first transformer to apply
- parameter secondTransformer: The second transformer to apply
- returns: A new OneWayTransformer that is the result of the composition of the two OneWayTransformers
*/
@available(*, deprecated=0.5)
public func compose<A: OneWayTransformer, B: OneWayTransformer where B.TypeIn == A.TypeOut>(firstTransformer: A, secondTransformer: B) -> OneWayTransformationBox<A.TypeIn, B.TypeOut> {
return firstTransformer.compose(secondTransformer)
}
/**
Composes a OneWayTransformer with a transformation closure
- parameter transformer: The OneWayTransformer to apply first
- parameter transformerClosure: The transformation closure to apply after
- returns: A new OneWayTransformer that is the result of the composition of the transformer with the transformation closure
*/
@available(*, deprecated=0.5)
public func compose<A: OneWayTransformer, B>(transformer: A, transformerClosure: A.TypeOut -> Future<B>) -> OneWayTransformationBox<A.TypeIn, B> {
return transformer.compose(transformerClosure)
}
/**
Composes two transformation closures
- parameter firstTransformerClosure: The first transformation closure to apply
- parameter secondTransformerClosure: The second transformation closure to apply
- returns: A new OneWayTransformer that is the result of the composition of the two transformation closures
*/
@available(*, deprecated=0.5)
public func compose<A, B, C>(firstTransformerClosure: A -> Future<B>, secondTransformerClosure: B -> Future<C>) -> OneWayTransformationBox<A, C> {
return wrapClosureIntoOneWayTransformer(firstTransformerClosure).compose(secondTransformerClosure)
}
/**
Composes a transformation closure with a OneWayTransformer
- parameter transformerClosure: The transformation closure to apply first
- parameter transformer: The OneWayTransformer to apply after
- returns: A new OneWayTransformer that is the result of the composition of the transformation closure with the transformer
*/
@available(*, deprecated=0.5)
public func compose<A: OneWayTransformer, B>(transformerClosure: B -> Future<A.TypeIn>, transformer: A) -> OneWayTransformationBox<B, A.TypeOut> {
return wrapClosureIntoOneWayTransformer(transformerClosure).compose(transformer)
}
/**
Composes two OneWayTransformers
- parameter firstTransformer: The first transformer to apply
- parameter secondTransformer: The second transformer to apply
- returns: A new OneWayTransformer that is the result of the composition of the two OneWayTransformers
*/
public func >>><A: OneWayTransformer, B: OneWayTransformer where B.TypeIn == A.TypeOut>(firstTransformer: A, secondTransformer: B) -> OneWayTransformationBox<A.TypeIn, B.TypeOut> {
return firstTransformer.compose(secondTransformer)
}
/**
Composes a OneWayTransformer with a transformation closure
- parameter transformer: The OneWayTransformer to apply first
- parameter transformerClosure: The transformation closure to apply after
- returns: A new OneWayTransformer that is the result of the composition of the transformer with the transformation closure
*/
@available(*, deprecated=0.7)
public func >>><A: OneWayTransformer, B>(transformer: A, transformerClosure: A.TypeOut -> Future<B>) -> OneWayTransformationBox<A.TypeIn, B> {
return transformer.compose(transformerClosure)
}
/**
Composes two transformation closures
- parameter firstTransformerClosure: The first transformation closure to apply
- parameter secondTransformerClosure: The second transformation closure to apply
- returns: A new OneWayTransformer that is the result of the composition of the two transformation closures
*/
@available(*, deprecated=0.7)
public func >>><A, B, C>(firstTransformerClosure: A -> Future<B>, secondTransformerClosure: B -> Future<C>) -> OneWayTransformationBox<A, C> {
return wrapClosureIntoOneWayTransformer(firstTransformerClosure).compose(secondTransformerClosure)
}
/**
Composes a transformation closure with a OneWayTransformer
- parameter transformerClosure: The transformation closure to apply first
- parameter transformer: The OneWayTransformer to apply after
- returns: A new OneWayTransformer that is the result of the composition of the transformation closure with the transformer
*/
@available(*, deprecated=0.7)
public func >>><A: OneWayTransformer, B>(transformerClosure: B -> Future<A.TypeIn>, transformer: A) -> OneWayTransformationBox<B, A.TypeOut> {
return wrapClosureIntoOneWayTransformer(transformerClosure).compose(transformer)
}
|
mit
|
9ac61432c8ce61567e39b9381f29e71d
| 41.776923 | 184 | 0.794964 | 4.644946 | false | false | false | false |
parrotbait/CorkWeather
|
CorkWeather/Source/UI/MainViewController+Alerts.swift
|
1
|
3010
|
//
// MainViewController+Alerts.swift
// Cork Weather
//
// Created by Eddie Long on 25/09/2017.
// Copyright © 2017 eddielong. All rights reserved.
//
import Foundation
import UIKit
import Proteus_Core
extension MainViewController : MainAlertProtocol {
func showError(_ errorText : String) {
DispatchQueue.main.async { [weak self] in
let alertController = UIAlertController(title: Strings.get("Error_Title"), message: errorText, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: Strings.get("Grand"), style: .default, handler: nil))
self?.present(alertController, animated: true, completion: nil)
}
}
func showWeatherFetchFailure(reason: WeatherLoadError) {
switch (reason) {
case .backendError:
showError(Strings.get("Backend_Error"))
case .parseError:
showError(Strings.get("Bad_Json_Error"))
}
}
func showWeatherListLoadFailure(reason : DatabaseError, retryCallback: @escaping RetryCallback) {
switch (reason) {
case .noData:
DispatchQueue.main.async { [weak self] in
let alertController = UIAlertController(title: Strings.get("Error_Title"), message: Strings.get("Backend_Error"), preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: Strings.get("Give_Up"), style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: Strings.get("Try_Again"), style: .default) { _ in
retryCallback()
})
self?.present(alertController, animated: true, completion: nil)
}
case .internalError(let error):
DispatchQueue.main.async { [weak self] in
#if DEBUG
let errorText = error.localizedDescription
#else
let errorText = Strings.get("Backend_Error")
#endif
let alertController = UIAlertController(title: Strings.get("Error_Title"), message: errorText, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: Strings.get("Give_Up"), style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: Strings.get("Try_Again"), style: .default) { _ in
retryCallback()
})
self?.present(alertController, animated: true, completion: nil)
}
}
}
func showWeatherPickError(reason : PickError) {
switch (reason) {
case .notIreland:
showError(Strings.get("Not_Even_Ireland"))
case .notCork:
showError(Strings.get("Not_Cork"))
case .jackeen:
showError(Strings.get("Dublin"))
case .backendError:
showError(Strings.get("Backend_Error"))
case .alreadyPresent:
showError(Strings.get("Already_Present"))
}
}
}
|
mit
|
864a0cd7c9d66edbfa314cf1f54eeadf
| 39.12 | 153 | 0.604852 | 4.731132 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceModel/Tests/EurofurenceModelTests/Events/Specifications/TodaysEventsSpecificationTests.swift
|
1
|
3109
|
import EurofurenceModel
import XCTest
import XCTEurofurenceModel
class TodaysEventsSpecificationTests: XCTestCase {
func testEventStartsToday() {
assertEvent(
starting: today,
ending: today,
satisfiesSpec: true,
"Event starting today should satisfy the specification"
)
}
func testEventStartsAndEndsYesterday() {
assertEvent(
starting: yesterday,
ending: yesterday,
satisfiesSpec: false,
"Event starting and ending yesterday should not satisfy the specification"
)
}
func testEventStartedYesterdayAndEndsToday() {
assertEvent(
starting: yesterday,
ending: today,
satisfiesSpec: true,
"Event that runs into the morning from overnight should satisfy the specification"
)
}
func testEventStartsAndEndsTomorrow() {
assertEvent(
starting: tomorrow,
ending: tomorrow,
satisfiesSpec: false,
"Event starting and ending tomorrow should not satisfy the specification"
)
}
func testEventStartsYesterdayAndEndsTomorrow() {
assertEvent(
starting: yesterday,
ending: tomorrow,
satisfiesSpec: true,
"Event that runs throughout the day should satisfy the specification"
)
}
func testEventStartsTodayAndEndsTomorrow_EndOfMonth() {
assertEvent(
starting: today,
ending: firstOfNextMonth,
satisfiesSpec: true,
"Start and end dates should take months into account"
)
}
private func assertEvent(
starting startTime: Date,
ending endTime: Date,
satisfiesSpec expected: Bool,
_ description: String,
_ line: UInt = #line
) {
let event = FakeEvent.random
event.startDate = startTime
event.endDate = endTime
let clock = StubClock()
clock.tickTime(to: today)
let specification = TodaysEventsSpecification(clock: clock)
let actual = specification.isSatisfied(by: event)
XCTAssert(expected == actual, description)
}
private var oneDayInHours: TimeInterval {
3600 * 24
}
private var today: Date {
DateComponents(
calendar: .current,
year: 2019,
month: 9,
day: 29,
hour: 12,
minute: 0,
second: 0
).date.unsafelyUnwrapped
}
private var tomorrow: Date {
today.addingTimeInterval(oneDayInHours)
}
private var firstOfNextMonth: Date {
DateComponents(
calendar: .current,
year: 2019,
month: 10,
day: 1,
hour: 12,
minute: 0,
second: 0
).date.unsafelyUnwrapped
}
private var yesterday: Date {
today.addingTimeInterval(oneDayInHours * -1)
}
}
|
mit
|
423dec19222435a5cb33c86caefa18a2
| 25.57265 | 94 | 0.56256 | 5.360345 | false | true | false | false |
ManueGE/Actions
|
actions/actions/UIControl+Actions.swift
|
1
|
6450
|
//
// UIControl+Actions.swift
// actions
//
// Created by Manu on 1/6/16.
// Copyright © 2016 manuege. All rights reserved.
//
import UIKit
private protocol ControlAction: Action {
var controlEvent: UIControl.Event { get }
}
private class ControlVoidAction: VoidAction, ControlAction {
fileprivate let controlEvent: UIControl.Event
init(event: UIControl.Event, action: @escaping () -> Void) {
controlEvent = event
super.init(action: action)
}
}
private class ControlParametizedAction<T: UIControl>: ParametizedAction<T>, ControlAction {
fileprivate let controlEvent: UIControl.Event
init(event: UIControl.Event, action: @escaping (T) -> Void) {
controlEvent = event
super.init(action: action)
}
}
// Action to manage the two parameters selector allowed in controls
private class EventAction<T: UIControl>: ControlAction {
fileprivate let controlEvent: UIControl.Event
@objc let key = ProcessInfo.processInfo.globallyUniqueString
@objc let selector: Selector = #selector(perform)
let action: (T, UIEvent?) -> Void
@objc func perform(parameter: AnyObject, event: UIEvent?) {
action(parameter as! T, event)
}
init(event: UIControl.Event, action: @escaping (T, UIEvent?) -> Void) {
self.action = action
controlEvent = event
}
}
/// Extension that provides methods to add actions to controls
public extension UIControl {
// MARK: Single event
/**
Adds the given action as response to the given control event.
- parameter event: The event that the control must receive to trigger the closure
- parameter action: The closure that will be called when the gesture is detected
- returns: The added action
*/
@discardableResult
public func add<T: UIControl>(event: UIControl.Event, action: @escaping (T, UIEvent?) -> Void) -> Action {
let action = EventAction(event: event, action: action)
add(event: event, action: action)
return action
}
/**
Adds the given action as response to the given control event.
- parameter event: The event that the control must receive to trigger the closure
- parameter action: The closure that will be called when the gesture is detected
- returns: The added action
*/
@discardableResult
public func add<T: UIControl>(event: UIControl.Event, action: @escaping (T) -> Void) -> Action {
let action = ControlParametizedAction(event: event, action: action)
add(event: event, action: action)
return action
}
/**
Adds the given action as response to the given control event.
- parameter event: The event that the control must receive to trigger the closure
- parameter action: The closure that will be called when the gesture is detected
- returns: The added action
*/
@discardableResult
public func add(event: UIControl.Event, action: @escaping () -> Void) -> Action {
let action = ControlVoidAction(event: event, action: action)
add(event: event, action: action)
return action
}
// MARK: Multiple events
/**
Adds the given action as response to the given control events.
- parameter events: The events that the control must receive to trigger the closure
- parameter action: The closure that will be called when the gesture is detected
- returns: The added actions
*/
@discardableResult
public func add<T: UIControl>(events: [UIControl.Event], action: @escaping (T, UIEvent?) -> Void) -> [Action] {
return events.map { add(event: $0, action: action) }
}
/**
Adds the given action as response to the given control events.
- parameter events: The events that the control must receive to trigger the closure
- parameter action: The closure that will be called when the gesture is detected
- returns: The added actions
*/
@discardableResult
public func addAction<T: UIControl>(events: [UIControl.Event], action: @escaping (T) -> Void) -> [Action] {
return events.map { add(event: $0, action: action) }
}
/**
Adds the given action as response to the given control events.
- parameter events: The events that the control must receive to trigger the closure
- parameter action: The closure that will be called when the gesture is detected
- returns: The added actions
*/
@discardableResult
public func addAction(events: [UIControl.Event], action: @escaping () -> Void) -> [Action] {
return events.map { add(event: $0, action: action) }
}
// MARK: Private
private func add(event: UIControl.Event, action: Action) {
retainAction(action, self)
addTarget(action,
action: action.selector,
for: event)
}
// MARK: Remove
/**
Disable the given action to be launched as response of the received event
- parameter action: The action to disable
- parameter events: The control events that you want to remove for the specified target object
*/
@available(*, deprecated, message: "Use remove(_:for:) instead")
public func remove(action: Action, forControlEvents events: UIControl.Event) {
remove(action, for: events)
}
/**
Disable the given action to be launched as response of the received event
- parameter action: The action to disable
- parameter events: The control events that you want to remove for the specified target object
*/
public func remove(_ action: Action, for events: UIControl.Event) {
removeTarget(action, action: action.selector, for: events)
releaseAction(action, self)
}
/**
Disable all the actions for a given event to be launched as response of the received event.
**NOTE**: Just the actions added using the `Actions` method will be removed!.
- parameter events: The control events that you want to remove for the specified target object
*/
public func removeActions(for events: UIControl.Event) {
for (_, value) in actions {
guard let action = value as? ControlAction,
(action.controlEvent.rawValue & events.rawValue) != 0 else {
continue
}
remove(action, for: events)
}
}
}
|
mit
|
14f14086a49e347922b8f0cc678b87c6
| 35.851429 | 115 | 0.657466 | 4.619628 | false | false | false | false |
r-mckay/montreal-iqa
|
montrealIqaCore/Carthage/Checkouts/realm-cocoa/examples/tvos/swift-3.0/DownloadCache/RepositoriesViewController.swift
|
5
|
4281
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import UIKit
import RealmSwift
class RepositoriesViewController: UICollectionViewController, UITextFieldDelegate {
@IBOutlet weak var sortOrderControl: UISegmentedControl!
@IBOutlet weak var searchField: UITextField!
var results: Results<Repository>?
var token: NotificationToken?
deinit {
token?.stop()
}
override func viewDidLoad() {
super.viewDidLoad()
let realm = try! Realm()
token = realm.addNotificationBlock { [weak self] notification, realm in
self?.reloadData()
}
var components = URLComponents(string: "https://api.github.com/search/repositories")!
components.queryItems = [
URLQueryItem(name: "q", value: "language:objc"),
URLQueryItem(name: "sort", value: "stars"),
URLQueryItem(name: "order", value: "desc")
]
URLSession.shared.dataTask(with: URLRequest(url: components.url!)) { data, response, error in
if let error = error {
print(error)
return
}
do {
let repositories = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]
let items = repositories["items"] as! [[String: AnyObject]]
let realm = try Realm()
try realm.write {
for item in items {
let repository = Repository()
repository.identifier = String(item["id"] as! Int)
repository.name = item["name"] as? String
repository.avatarURL = item["owner"]!["avatar_url"] as? String;
realm.add(repository, update: true)
}
}
} catch {
print(error.localizedDescription)
}
}.resume()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return results?.count ?? 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! RepositoryCell
let repository = results![indexPath.item];
cell.titleLabel.text = repository.name
URLSession.shared.dataTask(with: URLRequest(url: URL(string: repository.avatarURL!)!)) { (data, response, error) -> Void in
if let error = error {
print(error.localizedDescription)
return
}
DispatchQueue.main.async {
let image = UIImage(data: data!)!
cell.avatarImageView!.image = image
}
}.resume()
return cell
}
func reloadData() {
let realm = try! Realm()
results = realm.objects(Repository.self)
if let text = searchField.text, !text.isEmpty {
results = results?.filter("name contains[c] %@", text)
}
results = results?.sorted(byKeyPath: "name", ascending: sortOrderControl!.selectedSegmentIndex == 0)
collectionView?.reloadData()
}
@IBAction func valueChanged(sender: AnyObject) {
reloadData()
}
@IBAction func clearSearchField(sender: AnyObject) {
searchField.text = nil
reloadData()
}
func textFieldDidEndEditing(_ textField: UITextField) {
reloadData()
}
}
|
mit
|
03a4b625cb259e743d4dc4d8efdb024d
| 34.380165 | 131 | 0.582107 | 5.298267 | false | false | false | false |
kences/swift_weibo
|
Swift-SinaWeibo/Classes/Module/NewFeature/Controller/LGWelcomeViewController.swift
|
1
|
5289
|
//
// LGWelcomeViewController.swift
// Swift-SinaWeibo
//
// Created by lu on 15/10/29.
// Copyright © 2015年 lg. All rights reserved.
//
import UIKit
import SDWebImage
class LGWelcomeViewController: UIViewController
{
// 用户头像与屏幕顶部的距离
let iconMargin: CGFloat = 160
// 用户头像的宽度
let iconWidth: CGFloat = 75
// 用户头像底部的约束
var imageViewConstraint: NSLayoutConstraint?
override func viewDidLoad()
{
super.viewDidLoad()
prepareUI()
// 下载头像图片
iconView.sd_setImageWithURL(NSURL(string: (LGUserAccount.loadUserAccount()?.avatar_large)!), placeholderImage: UIImage(named: "avatar_default_big"))
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
// 动画显示头像和欢迎回来
// delay: 延迟多久执行该方法
// usingSpringWithDamping : 0~1,值越小弹簧效果越明显
// initialSpringVelocity : 动画速度
imageViewConstraint?.constant = -UIScreen.mainScreen().bounds.height - imageViewConstraint!.constant
UIView.animateWithDuration(1.0, delay: 0.1, usingSpringWithDamping: 0.7, initialSpringVelocity: 6, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in // 头像动画
// 重新布局子科技:更新约束
self.view.layoutIfNeeded()
// self.view.setNeedsLayout()
}) { (_) -> Void in // 文字动画
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.welcomeLabel.alpha = 1
}, completion: { (_) -> Void in
// 切换window的控制器
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.changeRootViewController(LGMainViewController())
})
}
}
// MARK: - 准备UI
private func prepareUI()
{
// 添加子控件
view.addSubview(backgroundView)
view.addSubview(iconView)
view.addSubview(welcomeLabel)
// 添加约束条件
backgroundView.translatesAutoresizingMaskIntoConstraints = false
iconView.translatesAutoresizingMaskIntoConstraints = false
welcomeLabel.translatesAutoresizingMaskIntoConstraints = false
// 1.背景图片 使用VRF
// H:水平方向,与父控件之间的距离都为0,通过自定义的key:"bkg"对应的视图进行约束
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[bkg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkg":backgroundView]))
// V:垂直方向,与父控件之间的距离都为0
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[bkg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkg":backgroundView]))
// 2.用户头像
// 底部
imageViewConstraint = NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -iconMargin)
view.addConstraint(imageViewConstraint!)
// CenterX
view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
// 宽
view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: iconWidth))
// 高
view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: iconWidth))
// 3.欢迎回来
// CenterX
view.addConstraint(NSLayoutConstraint(item: welcomeLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
// 顶部,与头像距离16
view.addConstraint(NSLayoutConstraint(item: welcomeLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16))
}
// MARK: - 懒加载
// 背景图片
private lazy var backgroundView: UIImageView = UIImageView(image: UIImage(named: "ad_background"))
// 用户头像
private lazy var iconView: UIImageView = {
let iconView = UIImageView(image: UIImage(named: "avatar_default_big"))
iconView.layer.cornerRadius = self.iconWidth * 0.5
iconView.layer.masksToBounds = true
return iconView
}()
// 欢迎回来
private lazy var welcomeLabel: UILabel = {
let label = UILabel()
label.text = "欢迎回来"
label.alpha = 0
label.textColor = UIColor.blackColor()
return label
}()
}
|
apache-2.0
|
12fc93f9f2be4b38bdc69b02ef74eb53
| 43.917431 | 228 | 0.666258 | 4.896 | false | false | false | false |
nkirby/Humber
|
Humber/_src/Theming/Theme.swift
|
1
|
1675
|
// =======================================================
// Humber
// Nathaniel Kirby
// =======================================================
import UIKit
// =======================================================
internal final class Theme: NSObject {
private(set) internal static var themes = [Themable]()
internal static let themeChangedNotification = "HMThemeDidChangeNotification"
internal static func registerThemes(themes themes: [Themable]) {
self.themes = themes
}
internal static func activateTheme(themeName name: String) {
NSUserDefaults.standardUserDefaults().setValue(name, forKey: "HMCurrentThemeName")
NSUserDefaults.standardUserDefaults().synchronize()
NSNotificationCenter.defaultCenter().postNotificationName(self.themeChangedNotification, object: nil)
}
private static func currentTheme() -> Themable {
let themeName = NSUserDefaults.standardUserDefaults().stringForKey("HMCurrentThemeName")
if let theme = self.themes.filter({ $0.name == themeName }).first {
return theme
} else {
return self.themes.first!
}
}
internal static func color(type type: ColorType) -> UIColor {
return self.currentTheme().color(type: type)
}
internal static func font(type type: FontType) -> UIFont {
return self.currentTheme().font(type: type)
}
internal static func currentThemeName() -> String {
return self.currentTheme().name
}
internal static func currentThemeIsDark() -> Bool {
return self.currentTheme().name == "Dark"
}
}
|
mit
|
3874b4456fa09a113ec6dd0405b72762
| 32.5 | 109 | 0.58806 | 5.697279 | false | false | false | false |
christophhagen/Signal-iOS
|
SignalMessaging/attachments/SignalAttachment.swift
|
1
|
39450
|
//
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import MobileCoreServices
import SignalServiceKit
import PromiseKit
import AVFoundation
enum SignalAttachmentError: Error {
case missingData
case fileSizeTooLarge
case invalidData
case couldNotParseImage
case couldNotConvertToJpeg
case couldNotConvertToMpeg4
case invalidFileFormat
}
extension String {
var filenameWithoutExtension: String {
return (self as NSString).deletingPathExtension
}
var fileExtension: String? {
return (self as NSString).pathExtension
}
func appendingFileExtension(_ fileExtension: String) -> String {
guard let result = (self as NSString).appendingPathExtension(fileExtension) else {
owsFail("Failed to append file extension: \(fileExtension) to string: \(self)")
return self
}
return result
}
}
extension SignalAttachmentError: LocalizedError {
public var errorDescription: String {
switch self {
case .missingData:
return NSLocalizedString("ATTACHMENT_ERROR_MISSING_DATA", comment: "Attachment error message for attachments without any data")
case .fileSizeTooLarge:
return NSLocalizedString("ATTACHMENT_ERROR_FILE_SIZE_TOO_LARGE", comment: "Attachment error message for attachments whose data exceed file size limits")
case .invalidData:
return NSLocalizedString("ATTACHMENT_ERROR_INVALID_DATA", comment: "Attachment error message for attachments with invalid data")
case .couldNotParseImage:
return NSLocalizedString("ATTACHMENT_ERROR_COULD_NOT_PARSE_IMAGE", comment: "Attachment error message for image attachments which cannot be parsed")
case .couldNotConvertToJpeg:
return NSLocalizedString("ATTACHMENT_ERROR_COULD_NOT_CONVERT_TO_JPEG", comment: "Attachment error message for image attachments which could not be converted to JPEG")
case .invalidFileFormat:
return NSLocalizedString("ATTACHMENT_ERROR_INVALID_FILE_FORMAT", comment: "Attachment error message for attachments with an invalid file format")
case .couldNotConvertToMpeg4:
return NSLocalizedString("ATTACHMENT_ERROR_COULD_NOT_CONVERT_TO_MP4", comment: "Attachment error message for video attachments which could not be converted to MP4")
}
}
}
@objc
public enum TSImageQualityTier: UInt {
case original
case high
case mediumHigh
case medium
case mediumLow
case low
}
@objc
public enum TSImageQuality: UInt {
case original
case medium
case compact
func imageQualityTier() -> TSImageQualityTier {
switch self {
case .original:
return .original
case .medium:
return .mediumHigh
case .compact:
return .medium
}
}
}
// Represents a possible attachment to upload.
// The attachment may be invalid.
//
// Signal attachments are subject to validation and
// in some cases, file format conversion.
//
// This class gathers that logic. It offers factory methods
// for attachments that do the necessary work.
//
// The return value for the factory methods will be nil if the input is nil.
//
// [SignalAttachment hasError] will be true for non-valid attachments.
//
// TODO: Perhaps do conversion off the main thread?
@objc
public class SignalAttachment: NSObject {
static let TAG = "[SignalAttachment]"
let TAG = "[SignalAttachment]"
// MARK: Properties
@objc
public let dataSource: DataSource
@objc
public var captionText: String?
@objc
public var data: Data {
return dataSource.data()
}
@objc
public var dataLength: UInt {
return dataSource.dataLength()
}
@objc
public var dataUrl: URL? {
return dataSource.dataUrl()
}
@objc
public var sourceFilename: String? {
return dataSource.sourceFilename
}
@objc
public var isValidImage: Bool {
return dataSource.isValidImage()
}
// Attachment types are identified using UTIs.
//
// See: https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
@objc
public let dataUTI: String
var error: SignalAttachmentError? {
didSet {
AssertIsOnMainThread()
assert(oldValue == nil)
Logger.verbose("\(SignalAttachment.TAG) Attachment has error: \(String(describing: error))")
}
}
// To avoid redundant work of repeatedly compressing/uncompressing
// images, we cache the UIImage associated with this attachment if
// possible.
private var cachedImage: UIImage?
private var cachedVideoPreview: UIImage?
@objc
private(set) public var isVoiceMessage = false
// MARK: Constants
/**
* Media Size constraints from Signal-Android
*
* https://github.com/WhisperSystems/Signal-Android/blob/master/src/org/thoughtcrime/securesms/mms/PushMediaConstraints.java
*/
static let kMaxFileSizeAnimatedImage = UInt(25 * 1024 * 1024)
static let kMaxFileSizeImage = UInt(6 * 1024 * 1024)
static let kMaxFileSizeVideo = UInt(100 * 1024 * 1024)
static let kMaxFileSizeAudio = UInt(100 * 1024 * 1024)
static let kMaxFileSizeGeneric = UInt(100 * 1024 * 1024)
// MARK: Constructor
// This method should not be called directly; use the factory
// methods instead.
@objc
private init(dataSource: DataSource, dataUTI: String) {
self.dataSource = dataSource
self.dataUTI = dataUTI
super.init()
}
// MARK: Methods
@objc
public var hasError: Bool {
return error != nil
}
@objc
public var errorName: String? {
guard let error = error else {
// This method should only be called if there is an error.
owsFail("\(TAG) Missing error")
return nil
}
return "\(error)"
}
@objc
public var localizedErrorDescription: String? {
guard let error = self.error else {
// This method should only be called if there is an error.
owsFail("\(TAG) Missing error")
return nil
}
return "\(error.errorDescription)"
}
@objc
public class var missingDataErrorMessage: String {
return SignalAttachmentError.missingData.errorDescription
}
@objc
public func image() -> UIImage? {
if let cachedImage = cachedImage {
return cachedImage
}
guard let image = UIImage(data:dataSource.data()) else {
return nil
}
cachedImage = image
return image
}
@objc
public func videoPreview() -> UIImage? {
if let cachedVideoPreview = cachedVideoPreview {
return cachedVideoPreview
}
guard let mediaUrl = dataUrl else {
return nil
}
do {
let filePath = mediaUrl.path
guard FileManager.default.fileExists(atPath: filePath) else {
owsFail("asset at \(filePath) doesn't exist")
return nil
}
let asset = AVURLAsset(url: mediaUrl)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
let cgImage = try generator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
let image = UIImage(cgImage: cgImage)
cachedVideoPreview = image
return image
} catch let error {
Logger.verbose("\(TAG) Could not generate video thumbnail: \(error.localizedDescription)")
return nil
}
}
// Returns the MIME type for this attachment or nil if no MIME type
// can be identified.
@objc
public var mimeType: String {
if isVoiceMessage {
// Legacy iOS clients don't handle "audio/mp4" files correctly;
// they are written to disk as .mp4 instead of .m4a which breaks
// playback. So we send voice messages as "audio/aac" to work
// around this.
//
// TODO: Remove this Nov. 2016 or after.
return "audio/aac"
}
if let filename = sourceFilename {
let fileExtension = (filename as NSString).pathExtension
if fileExtension.count > 0 {
if let mimeType = MIMETypeUtil.mimeType(forFileExtension:fileExtension) {
// UTI types are an imperfect means of representing file type;
// file extensions are also imperfect but far more reliable and
// comprehensive so we always prefer to try to deduce MIME type
// from the file extension.
return mimeType
}
}
}
if dataUTI == kOversizeTextAttachmentUTI {
return OWSMimeTypeOversizeTextMessage
}
if dataUTI == kUnknownTestAttachmentUTI {
return OWSMimeTypeUnknownForTests
}
guard let mimeType = UTTypeCopyPreferredTagWithClass(dataUTI as CFString, kUTTagClassMIMEType) else {
return OWSMimeTypeApplicationOctetStream
}
return mimeType.takeRetainedValue() as String
}
// Use the filename if known. If not, e.g. if the attachment was copy/pasted, we'll generate a filename
// like: "signal-2017-04-24-095918.zip"
@objc
public var filenameOrDefault: String {
if let filename = sourceFilename {
return filename
} else {
let kDefaultAttachmentName = "signal"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd-HHmmss"
let dateString = dateFormatter.string(from: Date())
let withoutExtension = "\(kDefaultAttachmentName)-\(dateString)"
if let fileExtension = self.fileExtension {
return "\(withoutExtension).\(fileExtension)"
}
return withoutExtension
}
}
// Returns the file extension for this attachment or nil if no file extension
// can be identified.
@objc
public var fileExtension: String? {
if let filename = sourceFilename {
let fileExtension = (filename as NSString).pathExtension
if fileExtension.count > 0 {
return fileExtension
}
}
if dataUTI == kOversizeTextAttachmentUTI {
return kOversizeTextAttachmentFileExtension
}
if dataUTI == kUnknownTestAttachmentUTI {
return "unknown"
}
guard let fileExtension = MIMETypeUtil.fileExtension(forUTIType:dataUTI) else {
return nil
}
return fileExtension
}
// Returns the set of UTIs that correspond to valid _input_ image formats
// for Signal attachments.
//
// Image attachments may be converted to another image format before
// being uploaded.
private class var inputImageUTISet: Set<String> {
// HEIC is valid input, but not valid output. Non-iOS11 clients do not support it.
let heicSet: Set<String> = Set(["public.heic", "public.heif"])
return MIMETypeUtil.supportedImageUTITypes()
.union(animatedImageUTISet)
.union(heicSet)
}
// Returns the set of UTIs that correspond to valid _output_ image formats
// for Signal attachments.
private class var outputImageUTISet: Set<String> {
return MIMETypeUtil.supportedImageUTITypes().union(animatedImageUTISet)
}
private class var outputVideoUTISet: Set<String> {
return Set([kUTTypeMPEG4 as String])
}
// Returns the set of UTIs that correspond to valid animated image formats
// for Signal attachments.
private class var animatedImageUTISet: Set<String> {
return MIMETypeUtil.supportedAnimatedImageUTITypes()
}
// Returns the set of UTIs that correspond to valid video formats
// for Signal attachments.
private class var videoUTISet: Set<String> {
return MIMETypeUtil.supportedVideoUTITypes()
}
// Returns the set of UTIs that correspond to valid audio formats
// for Signal attachments.
private class var audioUTISet: Set<String> {
return MIMETypeUtil.supportedAudioUTITypes()
}
// Returns the set of UTIs that correspond to valid image, video and audio formats
// for Signal attachments.
private class var mediaUTISet: Set<String> {
return audioUTISet.union(videoUTISet).union(animatedImageUTISet).union(inputImageUTISet)
}
@objc
public var isImage: Bool {
return SignalAttachment.outputImageUTISet.contains(dataUTI)
}
@objc
public var isAnimatedImage: Bool {
return SignalAttachment.animatedImageUTISet.contains(dataUTI)
}
@objc
public var isVideo: Bool {
return SignalAttachment.videoUTISet.contains(dataUTI)
}
@objc
public var isAudio: Bool {
return SignalAttachment.audioUTISet.contains(dataUTI)
}
@objc
public class func pasteboardHasPossibleAttachment() -> Bool {
return UIPasteboard.general.numberOfItems > 0
}
@objc
public class func pasteboardHasText() -> Bool {
if UIPasteboard.general.numberOfItems < 1 {
return false
}
let itemSet = IndexSet(integer:0)
guard let pasteboardUTITypes = UIPasteboard.general.types(forItemSet:itemSet) else {
return false
}
let pasteboardUTISet = Set<String>(pasteboardUTITypes[0])
// The pasteboard can be populated with multiple UTI types
// with different payloads. iMessage for example will copy
// an animated GIF to the pasteboard with the following UTI
// types:
//
// * "public.url-name"
// * "public.utf8-plain-text"
// * "com.compuserve.gif"
//
// We want to paste the animated GIF itself, not it's name.
//
// In general, our rule is to prefer non-text pasteboard
// contents, so we return true IFF there is a text UTI type
// and there is no non-text UTI type.
var hasTextUTIType = false
var hasNonTextUTIType = false
for utiType in pasteboardUTISet {
if UTTypeConformsTo(utiType as CFString, kUTTypeText) {
hasTextUTIType = true
} else if mediaUTISet.contains(utiType) {
hasNonTextUTIType = true
}
}
if pasteboardUTISet.contains(kUTTypeURL as String) {
// Treat URL as a textual UTI type.
hasTextUTIType = true
}
if hasNonTextUTIType {
return false
}
return hasTextUTIType
}
// Returns an attachment from the pasteboard, or nil if no attachment
// can be found.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
@objc
public class func attachmentFromPasteboard() -> SignalAttachment? {
guard UIPasteboard.general.numberOfItems >= 1 else {
return nil
}
// If pasteboard contains multiple items, use only the first.
let itemSet = IndexSet(integer:0)
guard let pasteboardUTITypes = UIPasteboard.general.types(forItemSet:itemSet) else {
return nil
}
let pasteboardUTISet = Set<String>(pasteboardUTITypes[0])
for dataUTI in inputImageUTISet {
if pasteboardUTISet.contains(dataUTI) {
guard let data = dataForFirstPasteboardItem(dataUTI:dataUTI) else {
owsFail("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
return nil
}
let dataSource = DataSourceValue.dataSource(with:data, utiType: dataUTI)
// Pasted images _SHOULD _NOT_ be resized, if possible.
return attachment(dataSource : dataSource, dataUTI : dataUTI, imageQuality:.medium)
}
}
for dataUTI in videoUTISet {
if pasteboardUTISet.contains(dataUTI) {
guard let data = dataForFirstPasteboardItem(dataUTI:dataUTI) else {
owsFail("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
return nil
}
let dataSource = DataSourceValue.dataSource(with:data, utiType: dataUTI)
return videoAttachment(dataSource : dataSource, dataUTI : dataUTI)
}
}
for dataUTI in audioUTISet {
if pasteboardUTISet.contains(dataUTI) {
guard let data = dataForFirstPasteboardItem(dataUTI:dataUTI) else {
owsFail("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
return nil
}
let dataSource = DataSourceValue.dataSource(with:data, utiType: dataUTI)
return audioAttachment(dataSource : dataSource, dataUTI : dataUTI)
}
}
let dataUTI = pasteboardUTISet[pasteboardUTISet.startIndex]
guard let data = dataForFirstPasteboardItem(dataUTI:dataUTI) else {
owsFail("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
return nil
}
let dataSource = DataSourceValue.dataSource(with:data, utiType: dataUTI)
return genericAttachment(dataSource : dataSource, dataUTI : dataUTI)
}
// This method should only be called for dataUTIs that
// are appropriate for the first pasteboard item.
private class func dataForFirstPasteboardItem(dataUTI: String) -> Data? {
let itemSet = IndexSet(integer:0)
guard let datas = UIPasteboard.general.data(forPasteboardType:dataUTI, inItemSet:itemSet) else {
owsFail("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
return nil
}
guard datas.count > 0 else {
owsFail("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
return nil
}
guard let data = datas[0] as? Data else {
owsFail("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
return nil
}
return data
}
// MARK: Image Attachments
// Factory method for an image attachment.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
@objc
private class func imageAttachment(dataSource: DataSource?, dataUTI: String, imageQuality: TSImageQuality) -> SignalAttachment {
assert(dataUTI.count > 0)
assert(dataSource != nil)
guard let dataSource = dataSource else {
let attachment = SignalAttachment(dataSource : DataSourceValue.emptyDataSource(), dataUTI: dataUTI)
attachment.error = .missingData
return attachment
}
let attachment = SignalAttachment(dataSource : dataSource, dataUTI: dataUTI)
guard inputImageUTISet.contains(dataUTI) else {
attachment.error = .invalidFileFormat
return attachment
}
guard dataSource.dataLength() > 0 else {
owsFail("\(self.TAG) in \(#function) imageData was empty")
attachment.error = .invalidData
return attachment
}
if animatedImageUTISet.contains(dataUTI) {
guard dataSource.dataLength() <= kMaxFileSizeAnimatedImage else {
attachment.error = .fileSizeTooLarge
return attachment
}
// Never re-encode animated images (i.e. GIFs) as JPEGs.
Logger.verbose("\(TAG) Sending raw \(attachment.mimeType) to retain any animation")
return attachment
} else {
guard let image = UIImage(data:dataSource.data()) else {
attachment.error = .couldNotParseImage
return attachment
}
attachment.cachedImage = image
if isValidOutputImage(image: image, dataSource: dataSource, dataUTI: dataUTI, imageQuality:imageQuality) {
if let sourceFilename = dataSource.sourceFilename,
let sourceFileExtension = sourceFilename.fileExtension,
["heic", "heif"].contains(sourceFileExtension.lowercased()) {
// If a .heic file actually contains jpeg data, update the extension to match.
//
// Here's how that can happen:
// In iOS11, the Photos.app records photos with HEIC UTIType, with the .HEIC extension.
// Since HEIC isn't a valid output format for Signal, we'll detect that and convert to JPEG,
// updating the extension as well. No problem.
// However the problem comes in when you edit an HEIC image in Photos.app - the image is saved
// in the Photos.app as a JPEG, but retains the (now incongruous) HEIC extension in the filename.
assert(dataUTI == kUTTypeJPEG as String)
Logger.verbose("\(self.TAG) changing extension: \(sourceFileExtension) to match jpg uti type")
let baseFilename = sourceFilename.filenameWithoutExtension
dataSource.sourceFilename = baseFilename.appendingFileExtension("jpg")
}
Logger.verbose("\(TAG) Sending raw \(attachment.mimeType)")
return attachment
}
Logger.verbose("\(TAG) Compressing attachment as image/jpeg, \(dataSource.dataLength()) bytes")
return compressImageAsJPEG(image : image, attachment : attachment, filename:dataSource.sourceFilename, imageQuality:imageQuality)
}
}
// If the proposed attachment already conforms to the
// file size and content size limits, don't recompress it.
private class func isValidOutputImage(image: UIImage?, dataSource: DataSource?, dataUTI: String, imageQuality: TSImageQuality) -> Bool {
guard let image = image else {
return false
}
guard let dataSource = dataSource else {
return false
}
guard SignalAttachment.outputImageUTISet.contains(dataUTI) else {
return false
}
if doesImageHaveAcceptableFileSize(dataSource: dataSource, imageQuality: imageQuality) &&
dataSource.dataLength() <= kMaxFileSizeImage {
return true
}
return false
}
// Factory method for an image attachment.
//
// NOTE: The attachment returned by this method may nil or not be valid.
// Check the attachment's error property.
@objc
public class func imageAttachment(image: UIImage?, dataUTI: String, filename: String?, imageQuality: TSImageQuality) -> SignalAttachment {
assert(dataUTI.count > 0)
guard let image = image else {
let dataSource = DataSourceValue.emptyDataSource()
dataSource.sourceFilename = filename
let attachment = SignalAttachment(dataSource:dataSource, dataUTI: dataUTI)
attachment.error = .missingData
return attachment
}
// Make a placeholder attachment on which to hang errors if necessary.
let dataSource = DataSourceValue.emptyDataSource()
dataSource.sourceFilename = filename
let attachment = SignalAttachment(dataSource : dataSource, dataUTI: dataUTI)
attachment.cachedImage = image
Logger.verbose("\(TAG) Writing \(attachment.mimeType) as image/jpeg")
return compressImageAsJPEG(image : image, attachment : attachment, filename:filename, imageQuality:imageQuality)
}
private class func compressImageAsJPEG(image: UIImage, attachment: SignalAttachment, filename: String?, imageQuality: TSImageQuality) -> SignalAttachment {
assert(attachment.error == nil)
var imageUploadQuality = imageQuality.imageQualityTier()
while true {
let maxSize = maxSizeForImage(image: image, imageUploadQuality:imageUploadQuality)
var dstImage: UIImage! = image
if image.size.width > maxSize ||
image.size.height > maxSize {
dstImage = imageScaled(image, toMaxSize: maxSize)
}
guard let jpgImageData = UIImageJPEGRepresentation(dstImage,
jpegCompressionQuality(imageUploadQuality:imageUploadQuality)) else {
attachment.error = .couldNotConvertToJpeg
return attachment
}
guard let dataSource = DataSourceValue.dataSource(with:jpgImageData, fileExtension:"jpg") else {
attachment.error = .couldNotConvertToJpeg
return attachment
}
let baseFilename = filename?.filenameWithoutExtension
let jpgFilename = baseFilename?.appendingFileExtension("jpg")
dataSource.sourceFilename = jpgFilename
if doesImageHaveAcceptableFileSize(dataSource: dataSource, imageQuality: imageQuality) &&
dataSource.dataLength() <= kMaxFileSizeImage {
let recompressedAttachment = SignalAttachment(dataSource : dataSource, dataUTI: kUTTypeJPEG as String)
recompressedAttachment.cachedImage = dstImage
Logger.verbose("\(TAG) Converted \(attachment.mimeType) to image/jpeg, \(jpgImageData.count) bytes")
return recompressedAttachment
}
// If the JPEG output is larger than the file size limit,
// continue to try again by progressively reducing the
// image upload quality.
switch imageUploadQuality {
case .original:
imageUploadQuality = .high
case .high:
imageUploadQuality = .mediumHigh
case .mediumHigh:
imageUploadQuality = .medium
case .medium:
imageUploadQuality = .mediumLow
case .mediumLow:
imageUploadQuality = .low
case .low:
attachment.error = .fileSizeTooLarge
return attachment
}
}
}
private class func imageScaled(_ image: UIImage, toMaxSize size: CGFloat) -> UIImage {
var scaleFactor: CGFloat
let aspectRatio: CGFloat = image.size.height / image.size.width
if aspectRatio > 1 {
scaleFactor = size / image.size.width
} else {
scaleFactor = size / image.size.height
}
let newSize = CGSize(width: CGFloat(image.size.width * scaleFactor), height: CGFloat(image.size.height * scaleFactor))
UIGraphicsBeginImageContext(newSize)
image.draw(in: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(newSize.width), height: CGFloat(newSize.height)))
let updatedImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return updatedImage!
}
private class func doesImageHaveAcceptableFileSize(dataSource: DataSource, imageQuality: TSImageQuality) -> Bool {
switch imageQuality {
case .original:
return true
case .medium:
return dataSource.dataLength() < UInt(1024 * 1024)
case .compact:
return dataSource.dataLength() < UInt(400 * 1024)
}
}
private class func maxSizeForImage(image: UIImage, imageUploadQuality: TSImageQualityTier) -> CGFloat {
switch imageUploadQuality {
case .original:
return max(image.size.width, image.size.height)
case .high:
return 2048
case .mediumHigh:
return 1536
case .medium:
return 1024
case .mediumLow:
return 768
case .low:
return 512
}
}
private class func jpegCompressionQuality(imageUploadQuality: TSImageQualityTier) -> CGFloat {
switch imageUploadQuality {
case .original:
return 1
case .high:
return 0.9
case .mediumHigh:
return 0.8
case .medium:
return 0.7
case .mediumLow:
return 0.6
case .low:
return 0.5
}
}
// MARK: Video Attachments
// Factory method for video attachments.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
private class func videoAttachment(dataSource: DataSource?, dataUTI: String) -> SignalAttachment {
guard let dataSource = dataSource else {
let dataSource = DataSourceValue.emptyDataSource()
let attachment = SignalAttachment(dataSource:dataSource, dataUTI: dataUTI)
attachment.error = .missingData
return attachment
}
if !isValidOutputVideo(dataSource: dataSource, dataUTI: dataUTI) {
owsFail("building video with invalid output, migrate to async API using compressVideoAsMp4")
}
return newAttachment(dataSource: dataSource,
dataUTI: dataUTI,
validUTISet: videoUTISet,
maxFileSize: kMaxFileSizeVideo)
}
public class func copyToVideoTempDir(url fromUrl: URL) throws -> URL {
let baseDir = SignalAttachment.videoTempPath.appendingPathComponent(UUID().uuidString, isDirectory: true)
OWSFileSystem.ensureDirectoryExists(baseDir.path)
let toUrl = baseDir.appendingPathComponent(fromUrl.lastPathComponent)
Logger.debug("\(self.logTag) moving \(fromUrl) -> \(toUrl)")
try FileManager.default.copyItem(at: fromUrl, to: toUrl)
return toUrl
}
private class var videoTempPath: URL {
let videoDir = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("video")
OWSFileSystem.ensureDirectoryExists(videoDir.path)
return videoDir
}
public class func compressVideoAsMp4(dataSource: DataSource, dataUTI: String) -> (Promise<SignalAttachment>, AVAssetExportSession?) {
Logger.debug("\(self.TAG) in \(#function)")
guard let url = dataSource.dataUrl() else {
let attachment = SignalAttachment(dataSource : DataSourceValue.emptyDataSource(), dataUTI: dataUTI)
attachment.error = .missingData
return (Promise(value: attachment), nil)
}
let asset = AVAsset(url: url)
guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetMediumQuality) else {
let attachment = SignalAttachment(dataSource : DataSourceValue.emptyDataSource(), dataUTI: dataUTI)
attachment.error = .couldNotConvertToMpeg4
return (Promise(value: attachment), nil)
}
exportSession.shouldOptimizeForNetworkUse = true
exportSession.outputFileType = AVFileTypeMPEG4
let exportURL = videoTempPath.appendingPathComponent(UUID().uuidString).appendingPathExtension("mp4")
exportSession.outputURL = exportURL
let (promise, fulfill, _) = Promise<SignalAttachment>.pending()
Logger.debug("\(self.TAG) starting video export")
exportSession.exportAsynchronously {
Logger.debug("\(self.TAG) Completed video export")
let baseFilename = dataSource.sourceFilename
let mp4Filename = baseFilename?.filenameWithoutExtension.appendingFileExtension("mp4")
guard let dataSource = DataSourcePath.dataSource(with: exportURL) else {
owsFail("Failed to build data source for exported video URL")
let attachment = SignalAttachment(dataSource : DataSourceValue.emptyDataSource(), dataUTI: dataUTI)
attachment.error = .couldNotConvertToMpeg4
fulfill(attachment)
return
}
dataSource.setShouldDeleteOnDeallocation()
dataSource.sourceFilename = mp4Filename
let attachment = SignalAttachment(dataSource: dataSource, dataUTI: kUTTypeMPEG4 as String)
fulfill(attachment)
}
return (promise, exportSession)
}
@objc
public class VideoCompressionResult: NSObject {
@objc
public let attachmentPromise: AnyPromise
@objc
public let exportSession: AVAssetExportSession?
fileprivate init(attachmentPromise: Promise<SignalAttachment>, exportSession: AVAssetExportSession?) {
self.attachmentPromise = AnyPromise(attachmentPromise)
self.exportSession = exportSession
super.init()
}
}
@objc
public class func compressVideoAsMp4(dataSource: DataSource, dataUTI: String) -> VideoCompressionResult {
let (attachmentPromise, exportSession) = compressVideoAsMp4(dataSource: dataSource, dataUTI: dataUTI)
return VideoCompressionResult(attachmentPromise: attachmentPromise, exportSession: exportSession)
}
public class func isInvalidVideo(dataSource: DataSource, dataUTI: String) -> Bool {
guard videoUTISet.contains(dataUTI) else {
// not a video
return false
}
guard isValidOutputVideo(dataSource: dataSource, dataUTI: dataUTI) else {
// found a video which needs to be converted
return true
}
// It is a video, but it's not invalid
return false
}
private class func isValidOutputVideo(dataSource: DataSource?, dataUTI: String) -> Bool {
guard let dataSource = dataSource else {
return false
}
guard SignalAttachment.outputVideoUTISet.contains(dataUTI) else {
return false
}
if dataSource.dataLength() <= kMaxFileSizeVideo {
return true
}
return false
}
// MARK: Audio Attachments
// Factory method for audio attachments.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
private class func audioAttachment(dataSource: DataSource?, dataUTI: String) -> SignalAttachment {
return newAttachment(dataSource : dataSource,
dataUTI : dataUTI,
validUTISet : audioUTISet,
maxFileSize : kMaxFileSizeAudio)
}
// MARK: Oversize Text Attachments
// Factory method for oversize text attachments.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
private class func oversizeTextAttachment(text: String?) -> SignalAttachment {
let dataSource = DataSourceValue.dataSource(withOversizeText:text)
return newAttachment(dataSource : dataSource,
dataUTI : kOversizeTextAttachmentUTI,
validUTISet : nil,
maxFileSize : kMaxFileSizeGeneric)
}
// MARK: Generic Attachments
// Factory method for generic attachments.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
private class func genericAttachment(dataSource: DataSource?, dataUTI: String) -> SignalAttachment {
return newAttachment(dataSource : dataSource,
dataUTI : dataUTI,
validUTISet : nil,
maxFileSize : kMaxFileSizeGeneric)
}
// MARK: Voice Messages
@objc
public class func voiceMessageAttachment(dataSource: DataSource?, dataUTI: String) -> SignalAttachment {
let attachment = audioAttachment(dataSource : dataSource, dataUTI : dataUTI)
attachment.isVoiceMessage = true
return attachment
}
// MARK: Attachments
// Factory method for attachments of any kind.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
@objc
public class func attachment(dataSource: DataSource?, dataUTI: String) -> SignalAttachment {
if inputImageUTISet.contains(dataUTI) {
owsFail("\(TAG) must specify image quality type")
}
return attachment(dataSource: dataSource, dataUTI: dataUTI, imageQuality: .original)
}
// Factory method for attachments of any kind.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
@objc
public class func attachment(dataSource: DataSource?, dataUTI: String, imageQuality: TSImageQuality) -> SignalAttachment {
if inputImageUTISet.contains(dataUTI) {
return imageAttachment(dataSource : dataSource, dataUTI : dataUTI, imageQuality:imageQuality)
} else if videoUTISet.contains(dataUTI) {
return videoAttachment(dataSource : dataSource, dataUTI : dataUTI)
} else if audioUTISet.contains(dataUTI) {
return audioAttachment(dataSource : dataSource, dataUTI : dataUTI)
} else {
return genericAttachment(dataSource : dataSource, dataUTI : dataUTI)
}
}
@objc
public class func empty() -> SignalAttachment {
return SignalAttachment.attachment(dataSource : DataSourceValue.emptyDataSource(),
dataUTI: kUTTypeContent as String,
imageQuality:.original)
}
// MARK: Helper Methods
private class func newAttachment(dataSource: DataSource?,
dataUTI: String,
validUTISet: Set<String>?,
maxFileSize: UInt) -> SignalAttachment {
assert(dataUTI.count > 0)
assert(dataSource != nil)
guard let dataSource = dataSource else {
let attachment = SignalAttachment(dataSource : DataSourceValue.emptyDataSource(), dataUTI: dataUTI)
attachment.error = .missingData
return attachment
}
let attachment = SignalAttachment(dataSource : dataSource, dataUTI: dataUTI)
if let validUTISet = validUTISet {
guard validUTISet.contains(dataUTI) else {
attachment.error = .invalidFileFormat
return attachment
}
}
guard dataSource.dataLength() > 0 else {
owsFail("\(TAG) Empty attachment")
assert(dataSource.dataLength() > 0)
attachment.error = .invalidData
return attachment
}
guard dataSource.dataLength() <= maxFileSize else {
attachment.error = .fileSizeTooLarge
return attachment
}
// Attachment is valid
return attachment
}
}
|
gpl-3.0
|
58f0ce051d91a12ae4309f0254ce3852
| 36.679083 | 178 | 0.626996 | 5.222399 | false | false | false | false |
ChristianKienle/highway
|
Tests/HWKitTests/HomeBundleTests.swift
|
1
|
2683
|
import XCTest
import HWKit
import HighwayCore
import ZFile
import Url
final class HomeBundleTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testInit() {
let fs = InMemoryFileSystem()
let config = HomeBundle.Configuration.standard
let url = Absolute.root.appending(config.directoryName)
XCTAssertThrowsError(try HomeBundle(url: url, fileSystem: fs, configuration: config))
XCTAssertNoThrow(try fs.createDirectory(at: url))
XCTAssertNoThrow(try HomeBundle(url: url, fileSystem: fs, configuration: config))
}
func testMissingComponents() {
let fs = InMemoryFileSystem()
let config = HomeBundle.Configuration.standard
let url = Absolute.root.appending(config.directoryName)
XCTAssertNoThrow(try fs.createDirectory(at: url))
let binDir = url.appending(HomeBundle.Component.binDir.rawValue)
let highwayCLIUrl = url.appending(HomeBundle.Component.highwayCLI.rawValue)
let cloneUrl = url.appending(HomeBundle.Component.clone.rawValue)
XCTAssertNoThrow(try fs.createDirectory(at: binDir))
XCTAssertNoThrow(try fs.writeData(Data(), to: highwayCLIUrl))
XCTAssertNoThrow(try fs.createDirectory(at: cloneUrl))
let bundle: HomeBundle
do {
bundle = try HomeBundle(url: url, fileSystem: fs, configuration: config)
} catch {
XCTFail(error.localizedDescription)
return
}
// At this point the fs contains a valid home bundle...
// Make sure HomeBundle acks that.
XCTAssertTrue(bundle.missingComponents().isEmpty)
// Now remove the expected components one by one
XCTAssertNoThrow(try fs.deleteItem(at: highwayCLIUrl))
XCTAssertEqual(bundle.missingComponents(), [.highwayCLI])
XCTAssertNoThrow(try fs.deleteItem(at: cloneUrl))
XCTAssertEqual(bundle.missingComponents(), [.highwayCLI, .clone])
XCTAssertNoThrow(try fs.deleteItem(at: binDir))
XCTAssertEqual(bundle.missingComponents(), [.binDir, .highwayCLI, .clone])
// Check we forgot nothing
let all: Set<HomeBundle.Component> = [.binDir, .highwayCLI, .clone]
XCTAssertEqual(bundle.missingComponents(), all)
}
}
|
mit
|
457e2577537de18b36c65315d78830b6
| 36.263889 | 111 | 0.655982 | 4.950185 | false | true | false | false |
codestergit/swift
|
test/SILOptimizer/prespecialize.swift
|
4
|
1573
|
// RUN: %target-swift-frontend %s -Onone -Xllvm -sil-inline-generics=false -emit-sil | %FileCheck %s
// REQUIRES: optimized_stdlib
// FIXME: https://bugs.swift.org/browse/SR-2808
// XFAIL: resilient_stdlib
// Check that pre-specialization works at -Onone.
// This test requires the standard library to be compiled with pre-specializations!
// CHECK-LABEL: sil [noinline] @_T013prespecialize4testySaySiGz_Si4sizetF
//
// function_ref specialized Collection<A where ...>.makeIterator() -> IndexingIterator<A>
// CHECK: function_ref @_T0s10CollectionPssAARzs16IndexingIteratorVyxG0C0RtzlE04makeC0AEyFs14CountableRangeVySiG_Tgq5
//
// function_ref specialized IndexingIterator.next() -> A._Element?
// CHECK: function_ref @_T0s16IndexingIteratorV4next8_ElementQzSgyFs14CountableRangeVySiG_Tgq5
//
// Look for generic specialization <Swift.Int> of Swift.Array.subscript.getter : (Swift.Int) -> A
// CHECK: function_ref {{@_T0Sa9subscriptxSicfgSi_Tgq5|@_TTSg5Si___TFSaap9subscriptFSix}}
// CHECK: return
@inline(never)
public func test(_ a: inout [Int], size: Int) {
for i in 0..<size {
for j in 0..<size {
a[i] = a[j]
}
}
}
// CHECK-LABEL: sil [noinline] @_T013prespecialize3runyyF
// Look for generic specialization <Swift.Int> of Swift.Array.init (repeating : A, count : Swift.Int) -> Swift.Array<A>
// CHECK: function_ref @_T0S2ayxGx9repeating_Si5counttcfCSi_Tgq5
// CHECK: return
@inline(never)
public func run() {
let size = 10000
var p = [Int](repeating: 0, count: size)
for i in 0..<size {
p[i] = i
}
test(&p, size: size)
}
run()
|
apache-2.0
|
f245c90f541515c776e35cf2d9ad1f3e
| 33.195652 | 119 | 0.717101 | 3.146 | false | true | false | false |
DragonCherry/AssetsPickerViewController
|
AssetsPickerViewController/Classes/Picker/AssetsCameraManager.swift
|
1
|
6251
|
//
// AssetsCameraManager.swift
// AssetsPickerViewController
//
// Created by DragonCherry on 2020/07/02.
//
import Foundation
import AVFoundation
import Photos
import UIKit
protocol AssetsPickerManagerDelegate: NSObject {
func assetsPickerManagerSavedAsset(identifier: String)
}
class AssetsPickerManager: NSObject {
fileprivate var successCallback: ((Any?) -> Void)?
fileprivate var cancelCallback: (() -> Void)?
private let allowsEditing: Bool = true
fileprivate var savedLocalIdentifier: String?
var isAutoSave: Bool = true
weak var delegate: AssetsPickerManagerDelegate?
func requestTakePhoto(parent: UIViewController, success: ((Any?) -> Void)? = nil, cancel: (() -> Void)? = nil) {
let controller = UIImagePickerController()
controller.delegate = self
controller.sourceType = .camera
controller.allowsEditing = allowsEditing
self.successCallback = success
self.cancelCallback = cancel
parent.present(controller, animated: true, completion: nil)
}
func requestTake(parent: UIViewController, success: ((Any?) -> Void)? = nil, cancel: (() -> Void)? = nil) {
let controller = UIImagePickerController()
controller.delegate = self
controller.sourceType = .camera
controller.allowsEditing = allowsEditing
controller.mediaTypes = ["public.image", "public.movie"]
self.successCallback = success
self.cancelCallback = cancel
parent.present(controller, animated: true, completion: nil)
}
func requestImage(parent: UIViewController, success: ((Any?) -> Void)? = nil, cancel: (() -> Void)? = nil) {
let controller = UIImagePickerController()
controller.delegate = self
controller.sourceType = .photoLibrary
controller.allowsEditing = allowsEditing
self.successCallback = success
self.cancelCallback = cancel
parent.present(controller, animated: true, completion: nil)
}
}
extension AssetsPickerManager: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// Local variable inserted by Swift 4.2 migrator.
let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)
picker.dismiss(animated: true, completion: { [weak self] in
guard let `self` = self else { return }
var mediaType: PHAssetMediaType = .unknown
if let lowercasedMediaType = (info[convertFromUIImagePickerControllerInfoKey(.mediaType)] as? String)?.lowercased() {
if lowercasedMediaType.contains("image") {
mediaType = .image
} else if lowercasedMediaType.contains("movie") {
mediaType = .video
}
}
switch mediaType {
case .image:
guard let image = (info[convertFromUIImagePickerControllerInfoKey(.editedImage)] as? UIImage) ?? (info[convertFromUIImagePickerControllerInfoKey(.originalImage)] as? UIImage) else {
self.successCallback?(nil)
return
}
if self.isAutoSave {
PHPhotoLibrary.shared().performChanges({
let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
if let identifier = request.placeholderForCreatedAsset?.localIdentifier {
self.savedLocalIdentifier = identifier
self.successCallback?(image)
}
}) { [weak self] (isSuccess, _) in
if let localIdentifier = self?.savedLocalIdentifier, isSuccess {
self?.savedLocalIdentifier = nil
self?.delegate?.assetsPickerManagerSavedAsset(identifier: localIdentifier)
}
self?.successCallback?(image)
}
} else {
self.successCallback?(image)
}
case .video:
guard let videoFileURL = info[convertFromUIImagePickerControllerInfoKey(.mediaURL)] as? URL else {
self.successCallback?(nil)
return
}
if self.isAutoSave {
PHPhotoLibrary.shared().performChanges({
if let request = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoFileURL), let identifier = request.placeholderForCreatedAsset?.localIdentifier {
self.savedLocalIdentifier = identifier
self.successCallback?(videoFileURL)
} else {
self.successCallback?(videoFileURL)
}
}) { [weak self] (isSuccess, _) in
if let localIdentifier = self?.savedLocalIdentifier, isSuccess {
self?.savedLocalIdentifier = nil
self?.delegate?.assetsPickerManagerSavedAsset(identifier: localIdentifier)
}
self?.successCallback?(videoFileURL)
}
} else {
self.successCallback?(videoFileURL)
}
default:
self.successCallback?(nil)
}
})
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: { [weak self] in
self?.cancelCallback?()
})
}
}
fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] {
return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)})
}
fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
return input.rawValue
}
|
mit
|
dd89feadc1ea38eafbd86d38ba4b9bb1
| 42.409722 | 197 | 0.597504 | 6.146509 | false | false | false | false |
awind/Pixel
|
Pixel/Account.swift
|
1
|
651
|
//
// Account.swift
// Pixel
//
// Created by SongFei on 16/1/4.
// Copyright © 2016年 SongFei. All rights reserved.
//
import Foundation
class Account {
static func checkIsLogin() -> Bool {
let oauthToken = getOauthToken()
if oauthToken.isEmpty {
return false
}
return true
}
static func getOauthToken() -> String {
let userDefaults = NSUserDefaults.standardUserDefaults()
var oauthToken: String = ""
if let accessToken = userDefaults.valueForKey("accessToken") {
oauthToken = accessToken as! String
}
return oauthToken
}
}
|
apache-2.0
|
8b911988333186f6600343acf4823f08
| 21.344828 | 70 | 0.600309 | 4.595745 | false | false | false | false |
VirrageS/TDL
|
TDL/SlideAnimationSlide.swift
|
1
|
2243
|
import UIKit
class SlideNavigationControllerAnimatorSlide {
let slideMovement: CGFloat = 100.0
var _instance: SlideNavigationController?
init() {
}
func prepareMenuForAnimation() {
let menuViewController: UIViewController = _instance!.menu!
let orientation: UIDeviceOrientation = UIDevice.currentDevice().orientation
var rect: CGRect = menuViewController.view.frame
if orientation.isLandscape {
if !orientation.isLandscape {
rect.origin.y = self.slideMovement*(-1)
} else {
rect.origin.y = self.slideMovement
}
} else {
if !orientation.isPortrait {
rect.origin.x = self.slideMovement*(-1)
} else {
rect.origin.x = self.slideMovement;
}
}
menuViewController.view.frame = rect;
}
func animateMenu(progress: CGFloat) {
let menuViewController: UIViewController = _instance!.menu!
let orientation: UIDeviceOrientation = UIDevice.currentDevice().orientation
var location: CGFloat = CGFloat(self.slideMovement*(-1)) + CGFloat(self.slideMovement*progress)
location = (location > 0) ? 0 : location;
var rect: CGRect = menuViewController.view.frame;
if orientation.isLandscape {
rect.origin.y = orientation.isLandscape ? location : location*(-1);
} else {
rect.origin.x = orientation.isPortrait ? location : location*(-1);
}
menuViewController.view.frame = rect;
}
func clear() {
self.clearMenu()
}
func clearMenu() {
let menuViewController: UIViewController = _instance!.menu!
let orientation: UIDeviceOrientation = UIDevice.currentDevice().orientation
var rect: CGRect = menuViewController.view.frame;
if orientation.isLandscape {
rect.origin.y = 0;
} else {
rect.origin.x = 0;
}
menuViewController.view.frame = rect;
}
func setInstance(instance: SlideNavigationController?) {
_instance = instance?.sharedInstance()
}
}
|
mit
|
20440079617672833460185e80f95f98
| 29.726027 | 104 | 0.589835 | 5.132723 | false | false | false | false |
tilltue/TLPhotoPicker
|
TLPhotoPicker/Classes/TLAssetsCollection.swift
|
1
|
18350
|
//
// TLAssetsCollection.swift
// TLPhotosPicker
//
// Created by wade.hawk on 2017. 4. 18..
// Copyright © 2017년 wade.hawk. All rights reserved.
//
import Foundation
import Photos
import PhotosUI
import MobileCoreServices
public struct TLPHAsset {
enum CloudDownloadState {
case ready, progress, complete, failed
}
public enum AssetType {
case photo, video, livePhoto
}
public enum ImageExtType: String {
case png, jpg, gif, heic
}
var state = CloudDownloadState.ready
public var phAsset: PHAsset? = nil
//Bool to check if TLPHAsset returned is created using camera.
public var isSelectedFromCamera = false
public var selectedOrder: Int = 0
public var type: AssetType {
get {
guard let phAsset = self.phAsset else { return .photo }
if phAsset.mediaSubtypes.contains(.photoLive) {
return .livePhoto
}else if phAsset.mediaType == .video {
return .video
}else {
return .photo
}
}
}
public var fullResolutionImage: UIImage? {
get {
guard let phAsset = self.phAsset else { return nil }
return TLPhotoLibrary.fullResolutionImageData(asset: phAsset)
}
}
public func extType(defaultExt: ImageExtType = .png) -> ImageExtType {
guard let fileName = self.originalFileName,
let encodedFileName = fileName.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let extention = URL(string: encodedFileName)?.pathExtension.lowercased() else {
return defaultExt
}
return ImageExtType(rawValue: extention) ?? defaultExt
}
@discardableResult
public func cloudImageDownload(progressBlock: @escaping (Double) -> Void, completionBlock:@escaping (UIImage?)-> Void ) -> PHImageRequestID? {
guard let phAsset = self.phAsset else { return nil }
return TLPhotoLibrary.cloudImageDownload(asset: phAsset, progressBlock: progressBlock, completionBlock: completionBlock)
}
public var originalFileName: String? {
get {
guard let phAsset = self.phAsset,let resource = PHAssetResource.assetResources(for: phAsset).first else { return nil }
return resource.originalFilename
}
}
public func photoSize(options: PHImageRequestOptions? = nil ,completion: @escaping ((Int)->Void), livePhotoVideoSize: Bool = false) {
guard let phAsset = self.phAsset, self.type == .photo || self.type == .livePhoto else { completion(-1); return }
var resource: PHAssetResource? = nil
if phAsset.mediaSubtypes.contains(.photoLive) == true, livePhotoVideoSize {
resource = PHAssetResource.assetResources(for: phAsset).filter { $0.type == .pairedVideo }.first
}else {
resource = PHAssetResource.assetResources(for: phAsset).filter { $0.type == .photo }.first
}
if let fileSize = resource?.value(forKey: "fileSize") as? Int {
completion(fileSize)
}else {
PHImageManager.default().requestImageData(for: phAsset, options: nil) { (data, uti, orientation, info) in
var fileSize = -1
if let data = data {
let bcf = ByteCountFormatter()
bcf.countStyle = .file
fileSize = data.count
}
DispatchQueue.main.async {
completion(fileSize)
}
}
}
}
public func videoSize(options: PHVideoRequestOptions? = nil, completion: @escaping ((Int)->Void)) {
guard let phAsset = self.phAsset, self.type == .video else { completion(-1); return }
let resource = PHAssetResource.assetResources(for: phAsset).filter { $0.type == .video }.first
if let fileSize = resource?.value(forKey: "fileSize") as? Int {
completion(fileSize)
}else {
PHImageManager.default().requestAVAsset(forVideo: phAsset, options: options) { (avasset, audioMix, info) in
func fileSize(_ url: URL?) -> Int? {
do {
guard let fileSize = try url?.resourceValues(forKeys: [.fileSizeKey]).fileSize else { return nil }
return fileSize
}catch { return nil }
}
var url: URL? = nil
if let urlAsset = avasset as? AVURLAsset {
url = urlAsset.url
}else if let sandboxKeys = info?["PHImageFileSandboxExtensionTokenKey"] as? String, let path = sandboxKeys.components(separatedBy: ";").last {
url = URL(fileURLWithPath: path)
}
let size = fileSize(url) ?? -1
DispatchQueue.main.async {
completion(size)
}
}
}
}
func MIMEType(_ url: URL?) -> String? {
guard let ext = url?.pathExtension else { return nil }
if !ext.isEmpty {
let UTIRef = UTTypeCreatePreferredIdentifierForTag("public.filename-extension" as CFString, ext as CFString, nil)
let UTI = UTIRef?.takeUnretainedValue()
UTIRef?.release()
if let UTI = UTI {
guard let MIMETypeRef = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType) else { return nil }
let MIMEType = MIMETypeRef.takeUnretainedValue()
MIMETypeRef.release()
return MIMEType as String
}
}
return nil
}
private func tempCopyLivePhotos(phAsset: PHAsset,
livePhotoRequestOptions: PHLivePhotoRequestOptions? = nil,
localURL: URL,
completionBlock:@escaping (() -> Void)) -> PHImageRequestID? {
var requestOptions = PHLivePhotoRequestOptions()
if let options = livePhotoRequestOptions {
requestOptions = options
}else {
requestOptions.isNetworkAccessAllowed = true
}
return PHImageManager.default().requestLivePhoto(for: phAsset,
targetSize: UIScreen.main.bounds.size,
contentMode: .default,
options: requestOptions)
{ (livePhotos, infoDict) in
if let livePhotos = livePhotos {
let assetResources = PHAssetResource.assetResources(for: livePhotos)
assetResources.forEach { (resource) in
if resource.type == .pairedVideo {
PHAssetResourceManager.default().writeData(for: resource, toFile: localURL, options: nil) { (error) in
DispatchQueue.main.async {
completionBlock()
}
}
}
}
}
}
}
@discardableResult
//convertLivePhotosToJPG
// false : If you want mov file at live photos
// true : If you want png file at live photos ( HEIC )
public func tempCopyMediaFile(videoRequestOptions: PHVideoRequestOptions? = nil,
imageRequestOptions: PHImageRequestOptions? = nil,
livePhotoRequestOptions: PHLivePhotoRequestOptions? = nil,
exportPreset: String = AVAssetExportPresetHighestQuality,
convertLivePhotosToJPG: Bool = false,
progressBlock:((Double) -> Void)? = nil,
completionBlock:@escaping ((URL,String) -> Void)) -> PHImageRequestID? {
guard let phAsset = self.phAsset else { return nil }
var type: PHAssetResourceType? = nil
if phAsset.mediaSubtypes.contains(.photoLive) == true, convertLivePhotosToJPG == false {
type = .pairedVideo
}else {
type = phAsset.mediaType == .video ? .video : .photo
}
guard let resource = (PHAssetResource.assetResources(for: phAsset).filter{ $0.type == type }).first else { return nil }
let fileName = resource.originalFilename
var writeURL: URL? = nil
if #available(iOS 10.0, *) {
writeURL = FileManager.default.temporaryDirectory.appendingPathComponent("\(fileName)")
} else {
writeURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("\(fileName)")
}
guard var localURL = writeURL,var mimetype = MIMEType(writeURL) else { return nil }
if type == .pairedVideo {
return tempCopyLivePhotos(phAsset: phAsset,
livePhotoRequestOptions: livePhotoRequestOptions,
localURL: localURL,
completionBlock: { completionBlock(localURL, mimetype) })
}
switch phAsset.mediaType {
case .video:
var requestOptions = PHVideoRequestOptions()
if let options = videoRequestOptions {
requestOptions = options
}else {
requestOptions.isNetworkAccessAllowed = true
}
//iCloud download progress
requestOptions.progressHandler = { (progress, error, stop, info) in
DispatchQueue.main.async {
progressBlock?(progress)
}
}
return PHImageManager.default().requestExportSession(forVideo: phAsset,
options: requestOptions,
exportPreset: exportPreset)
{ (session, infoDict) in
session?.outputURL = localURL
session?.outputFileType = AVFileType.mov
session?.exportAsynchronously(completionHandler: {
DispatchQueue.main.async {
completionBlock(localURL, mimetype)
}
})
}
case .image:
var requestOptions = PHImageRequestOptions()
if let options = imageRequestOptions {
requestOptions = options
}else {
requestOptions.isNetworkAccessAllowed = true
}
//iCloud download progress
requestOptions.progressHandler = { (progress, error, stop, info) in
DispatchQueue.main.async {
progressBlock?(progress)
}
}
return PHImageManager.default().requestImageData(for: phAsset,
options: requestOptions)
{ (data, uti, orientation, info) in
do {
var data = data
let needConvertLivePhotoToJPG = phAsset.mediaSubtypes.contains(.photoLive) == true && convertLivePhotosToJPG == true
if needConvertLivePhotoToJPG {
let name = localURL.deletingPathExtension().lastPathComponent
localURL.deleteLastPathComponent()
localURL.appendPathComponent("\(name).jpg")
mimetype = "image/jpeg"
}
if needConvertLivePhotoToJPG, let imgData = data, let rawImage = UIImage(data: imgData)?.upOrientationImage() {
data = rawImage.jpegData(compressionQuality: 1)
}
try data?.write(to: localURL)
DispatchQueue.main.async {
completionBlock(localURL, mimetype)
}
}catch { }
}
default:
return nil
}
}
private func videoFilename(phAsset: PHAsset) -> URL? {
guard let resource = (PHAssetResource.assetResources(for: phAsset).filter{ $0.type == .video }).first else {
return nil
}
var writeURL: URL?
let fileName = resource.originalFilename
if #available(iOS 10.0, *) {
writeURL = FileManager.default.temporaryDirectory.appendingPathComponent("\(fileName)")
} else {
writeURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("\(fileName)")
}
return writeURL
}
//Apparently, This is not the only way to export video.
//There is many way that export a video.
//This method was one of them.
public func exportVideoFile(options: PHVideoRequestOptions? = nil,
outputURL: URL? = nil,
outputFileType: AVFileType = .mov,
progressBlock:((Double) -> Void)? = nil,
completionBlock:@escaping ((URL,String) -> Void)) {
guard
let phAsset = self.phAsset,
phAsset.mediaType == .video,
let writeURL = outputURL ?? videoFilename(phAsset: phAsset),
let mimetype = MIMEType(writeURL)
else {
return
}
var requestOptions = PHVideoRequestOptions()
if let options = options {
requestOptions = options
}else {
requestOptions.isNetworkAccessAllowed = true
}
requestOptions.progressHandler = { (progress, error, stop, info) in
DispatchQueue.main.async {
progressBlock?(progress)
}
}
PHImageManager.default().requestAVAsset(forVideo: phAsset, options: requestOptions) { (avasset, avaudioMix, infoDict) in
guard let avasset = avasset else {
return
}
let exportSession = AVAssetExportSession.init(asset: avasset, presetName: AVAssetExportPresetHighestQuality)
exportSession?.outputURL = writeURL
exportSession?.outputFileType = outputFileType
exportSession?.exportAsynchronously(completionHandler: {
completionBlock(writeURL, mimetype)
})
}
}
init(asset: PHAsset?) {
self.phAsset = asset
}
public static func asset(with localIdentifier: String) -> TLPHAsset? {
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [localIdentifier], options: nil)
return TLPHAsset(asset: fetchResult.firstObject)
}
}
extension TLPHAsset: Equatable {
public static func ==(lhs: TLPHAsset, rhs: TLPHAsset) -> Bool {
guard let lphAsset = lhs.phAsset, let rphAsset = rhs.phAsset else { return false }
return lphAsset.localIdentifier == rphAsset.localIdentifier
}
}
extension Array {
subscript (safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
public struct TLAssetsCollection {
var phAssetCollection: PHAssetCollection? = nil
var fetchResult: PHFetchResult<PHAsset>? = nil
var useCameraButton: Bool = false
var recentPosition: CGPoint = CGPoint.zero
var title: String
var localIdentifier: String
public var sections: [(title: String, assets: [TLPHAsset])]? = nil
var count: Int {
get {
guard let count = self.fetchResult?.count, count > 0 else { return self.useCameraButton ? 1 : 0 }
return count + (self.useCameraButton ? 1 : 0)
}
}
init(collection: PHAssetCollection) {
self.phAssetCollection = collection
self.title = collection.localizedTitle ?? ""
self.localIdentifier = collection.localIdentifier
}
func getAsset(at index: Int) -> PHAsset? {
if self.useCameraButton && index == 0 { return nil }
let index = index - (self.useCameraButton ? 1 : 0)
guard let result = self.fetchResult, index < result.count else { return nil }
return result.object(at: max(index,0))
}
func getTLAsset(at indexPath: IndexPath) -> TLPHAsset? {
let isCameraRow = self.useCameraButton && indexPath.section == 0 && indexPath.row == 0
if isCameraRow {
return nil
}
if let sections = self.sections {
let index = indexPath.row - ((self.useCameraButton && indexPath.section == 0) ? 1 : 0)
let result = sections[safe: indexPath.section]
return result?.assets[safe: index]
}else {
var index = indexPath.row
index = index - (self.useCameraButton ? 1 : 0)
guard let result = self.fetchResult, index < result.count else { return nil }
return TLPHAsset(asset: result.object(at: max(index,0)))
}
}
func findIndex(phAsset: PHAsset) -> IndexPath? {
guard let sections = self.sections else {
return nil
}
for (offset, section) in sections.enumerated() {
if let index = section.assets.firstIndex(where: { $0.phAsset == phAsset }) {
return IndexPath(row: index, section: offset)
}
}
return nil
}
mutating func reloadSection(groupedBy: PHFetchedResultGroupedBy) {
var groupedSections = self.section(groupedBy: groupedBy)
if self.useCameraButton {
groupedSections.insert(("camera",[TLPHAsset(asset: nil)]), at: 0)
}
self.sections = groupedSections
}
static func ==(lhs: TLAssetsCollection, rhs: TLAssetsCollection) -> Bool {
return lhs.localIdentifier == rhs.localIdentifier
}
}
extension UIImage {
func upOrientationImage() -> UIImage? {
switch imageOrientation {
case .up:
return self
default:
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(in: CGRect(origin: .zero, size: size))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}
}
|
mit
|
aeb4862385b4bb40ca194b5510f63143
| 41.667442 | 158 | 0.56358 | 5.483264 | false | false | false | false |
airbnb/lottie-ios
|
Sources/Private/Model/ShapeItems/Merge.swift
|
3
|
1215
|
//
// Merge.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
import Foundation
// MARK: - MergeMode
enum MergeMode: Int, Codable {
case none
case merge
case add
case subtract
case intersect
case exclude
}
// MARK: - Merge
final class Merge: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Merge.CodingKeys.self)
mode = try container.decode(MergeMode.self, forKey: .mode)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let modeRawType: Int = try dictionary.value(for: CodingKeys.mode)
guard let mode = MergeMode(rawValue: modeRawType) else {
throw InitializableError.invalidInput
}
self.mode = mode
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The mode of the merge path
let mode: MergeMode
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(mode, forKey: .mode)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case mode = "mm"
}
}
|
apache-2.0
|
7f374eebc0426cafd4cb141774b61838
| 19.948276 | 73 | 0.683951 | 3.796875 | false | false | false | false |
Vespen/SimpleJson
|
Sources/Features/Json+Date.swift
|
1
|
3614
|
//
// Json+Date.swift
//
// Copyright (c) 2017 Anton Lagutin
//
// 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
/// `DateFormat` enum.
public enum DateFormat {
/// String.
case string(DateFormatter)
/// Timestamp.
case timestamp
/// Timestamp in milliseconds.
case timestampInMs
}
/// `Date` based methods.
public extension Json {
/// Returns the `Date` value.
///
/// - Parameter format: Date format.
/// - Throws: `JsonError`.
/// - Returns: `Date`.
public func asDate(_ format: DateFormat) throws -> Date {
switch format {
case .string(let formatter):
guard let string = root as? String, let date = formatter.date(from: string) else {
throw JsonError.componentTypeMismatch(absolutePath, Date.self)
}
return date
case .timestamp:
guard let number = root as? NSNumber else {
throw JsonError.componentTypeMismatch(absolutePath, Date.self)
}
return Date(timeIntervalSince1970: number.doubleValue)
case .timestampInMs:
guard let number = root as? NSNumber else {
throw JsonError.componentTypeMismatch(absolutePath, Date.self)
}
return Date(timeIntervalSince1970: number.doubleValue * 0.001)
}
}
/// Returns the `Date` value identified by a given path.
///
/// - Parameters:
/// - path: Path.
/// - format: Date format.
/// - Throws: `JsonError`.
/// - Returns: The `Date` value identified by `path`.
public func date(at path: JsonPath, format: DateFormat) throws -> Date {
let value = try self.value(at: path)
switch format {
case .string(let formatter):
guard let string = value as? String, let date = formatter.date(from: string) else {
throw JsonError.componentTypeMismatch(absolutePath.appending(path), Date.self)
}
return date
case .timestamp:
guard let number = value as? NSNumber else {
throw JsonError.componentTypeMismatch(absolutePath.appending(path), Date.self)
}
return Date(timeIntervalSince1970: number.doubleValue)
case .timestampInMs:
guard let number = value as? NSNumber else {
throw JsonError.componentTypeMismatch(absolutePath.appending(path), Date.self)
}
return Date(timeIntervalSince1970: number.doubleValue * 0.001)
}
}
}
|
mit
|
2787e7c3285105d0004b5ef2e406e1ee
| 35.505051 | 95 | 0.643608 | 4.597964 | false | false | false | false |
ldjhust/BeautifulPhotos-Swift2.0
|
BeautifulPhotos(Swift2.0)/ListPhotos/Views/MyTitleView.swift
|
1
|
3401
|
//
// MyTitleView.swift
// BeautifulPhotos(Swift2.0)
//
// Created by ldjhust on 15/9/19.
// Copyright © 2015年 example. All rights reserved.
//
import UIKit
import KxMenu
class MyTitleView: UIView {
var titleLabelLeft: UILabel!
var titleLabelRight: UILabel!
var titleImageView: UIImageView!
var menuButton: UIButton!
var backgroundImageView: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
self.titleLabelLeft = UILabel(frame: CGRectMake(0, 10, bounds.width/2 - 16, 37))
self.titleLabelLeft.font = UIFont.boldSystemFontOfSize(20)
self.titleLabelLeft.text = "Bai"
self.titleLabelLeft.textAlignment = NSTextAlignment.Right
self.titleLabelLeft.textColor = UIColor.redColor()
self.titleImageView = UIImageView(frame: CGRectMake((bounds.width-30)/2, 7, 30, 30))
self.titleImageView.image = UIImage(named: "baidu_logo")
self.titleLabelRight = UILabel(frame: CGRectMake(bounds.width/2 + 16, 10, bounds.width/2 - 16, 37))
self.titleLabelRight.font = UIFont.boldSystemFontOfSize(20)
self.titleLabelRight.text = "图片"
self.titleLabelRight.textAlignment = NSTextAlignment.Left
self.titleLabelRight.textColor = UIColor.redColor()
self.menuButton = UIButton(frame: CGRectMake(UIScreen.mainScreen().bounds.width - 75, 10, 70, 30))
self.menuButton.setTitle("分类", forState: UIControlState.Normal)
self.menuButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
self.menuButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted)
self.menuButton.layer.borderColor = UIColor.blueColor().CGColor
self.menuButton.layer.borderWidth = 1
self.menuButton.addTarget(self, action: "showMenu:", forControlEvents: UIControlEvents.TouchUpInside)
self.backgroundImageView = UIImageView()
self.backgroundImageView.frame.size = self.frame.size
self.backgroundImageView.center = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
self.backgroundImageView.image = UIImage(named: "titile_bg")
self.addSubview(self.backgroundImageView)
self.addSubview(self.titleLabelLeft)
self.addSubview(self.titleImageView)
self.addSubview(self.titleLabelRight)
self.addSubview(self.menuButton)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Event Response
func showMenu(sender: UIButton) {
KxMenu.showMenuInView(self.superview, fromRect: sender.frame, menuItems: [
KxMenuItem("明星", image: nil, target: self, action: "pushMenuItem:"),
KxMenuItem("美女", image: nil, target: self, action: "pushMenuItem:"),
KxMenuItem("动漫", image: nil, target: self, action: "pushMenuItem:"),
KxMenuItem("壁纸", image: nil, target: self, action: "pushMenuItem:"),
KxMenuItem("摄影", image: nil, target: self, action: "pushMenuItem:"),
KxMenuItem("设计", image: nil, target: self, action: "pushMenuItem:"),
KxMenuItem("宠物", image: nil, target: self, action: "pushMenuItem:"),
KxMenuItem("汽车", image: nil, target: self, action: "pushMenuItem:")]
)
}
func pushMenuItem(sender: KxMenuItem) {
// 改变类别
(UIApplication.sharedApplication().keyWindow?.rootViewController as? MyCollectionViewController)?.kingImageString = sender.title
}
}
|
mit
|
fe9d4ff9fc6ad51418a0e2a136549b99
| 38.411765 | 132 | 0.713731 | 4.002389 | false | false | false | false |
ftdjsxo/SNOperation
|
Example/SNOperation/ViewController.swift
|
1
|
1646
|
//
// ViewController.swift
// SNOperation
//
// Created by ftdjsxo on 06/23/2017.
// Copyright (c) 2017 ftdjsxo. All rights reserved.
//
import UIKit
import SNOperation
class ViewController: UIViewController {
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var textArea: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textArea.text = "Making Request"
SimpleNetworkOperation(url: "http://www.mocky.io/v2/594d20e1110000a723a3d280").operation(requestMethodType: .get,
completion: completion,
headerParams: nil, queryStringParameters: [String : String]())
}
func completion(jsonData :Any?, stausCode : Int?, error :Error?){
DispatchQueue.main.async {
self.resultLabel.text = self.resultLabel.text?.appending(" [CODE]: ").appending(stausCode!.description)
let newValue = ""
if let dict = jsonData as? [String : Any]{
for entry in dict{
self.textArea.text = newValue.appending("Key: ").appending(entry.key).appending(" Value: ").appending((entry.value as? String)!)
}
}else{
self.textArea.text = "Unparsable response"
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
2a53da8b5b61d4540e2a7918df4c26ba
| 32.591837 | 159 | 0.537667 | 5.04908 | false | false | false | false |
sersoft-gmbh/AutoLayout_Macoun16
|
AutoLayoutTricks/AutoLayout Subviews/BadView.swift
|
1
|
1059
|
//
// BadView.swift
// AutoLayoutTricks
//
// Created by Florian Friedrich on 28/06/16.
// Copyright © 2016 ser.soft GmbH. All rights reserved.
//
import UIKit
import FFFoundation
class BadView: UIView {
let textLabel: UILabel = {
let label = UILabel()
label.enableAutoLayout()
label.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.title1)
label.text = "Hallo Macoun!"
return label
}()
init() {
super.init(frame: CGRect.zero)
preinitialize()
initialize()
}
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
override func awakeFromNib() {
super.awakeFromNib()
initialize()
}
func preinitialize() {
}
private final func initialize() {
addSubview(textLabel)
let constraints = [
"H:|-[label]-|",
"V:|-[label]-|"
].constraints(with: ["label": textLabel])
constraints.activate()
layoutIfNeeded()
}
}
|
mit
|
16084611bee7450326d5662e7224e68d
| 21.510638 | 79 | 0.568998 | 4.483051 | false | false | false | false |
mfikes/replete
|
Replete/ReplViewController.swift
|
1
|
24674
|
import UIKit
let messageFontSize: CGFloat = 14
let toolBarMinHeight: CGFloat = 44
let textViewMaxHeight: (portrait: CGFloat, landscape: CGFloat) = (portrait: 272, landscape: 90)
class ReplViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate {
let history: History
var tableView: UITableView!
var toolBar: UIToolbar!
var textView: UITextView!
var evalButton: UIButton!
var rotating = false
var textFieldHeightLayoutConstraint: NSLayoutConstraint!
var currentKeyboardHeight: CGFloat!
var initialized = false;
var enterPressed = false;
var scrollToBottom = false;
override var inputAccessoryView: UIView! {
get {
if toolBar == nil {
toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 0, height: toolBarMinHeight-0.5))
toolBar.layoutIfNeeded() // see SO answer re: iOS 11 and UIToolbar - https://bit.ly/2wIPF5n
textView = InputTextView(frame: CGRect.zero)
textView.backgroundColor = UIColor(white: 250/255, alpha: 1)
textView.font = UIFont(name: "Fira Code", size: messageFontSize)
textView.layer.borderColor = UIColor(red: 200/255, green: 200/255, blue: 205/255, alpha:1).cgColor
textView.layer.borderWidth = 0.5
textView.layer.cornerRadius = 5
textView.scrollsToTop = false
textView.isScrollEnabled = false
textView.textContainerInset = UIEdgeInsetsMake(3, 6, 3, 6)
textView.autocorrectionType = UITextAutocorrectionType.no;
textView.autocapitalizationType = UITextAutocapitalizationType.none;
textView.keyboardType = UIKeyboardType.asciiCapable;
textView.delegate = self
toolBar.addSubview(textView)
evalButton = UIButton(type: .system)
evalButton.isEnabled = false
evalButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
evalButton.setTitle("Eval", for: UIControlState())
evalButton.setTitleColor(UIColor(red: 142/255, green: 142/255, blue: 147/255, alpha: 1), for: .disabled)
evalButton.setTitleColor(UIColor(red: 1/255, green: 122/255, blue: 255/255, alpha: 1), for: UIControlState())
evalButton.contentEdgeInsets = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 8)
evalButton.addTarget(self, action: #selector(ReplViewController.sendAction), for: UIControlEvents.touchUpInside)
toolBar.addSubview(evalButton)
toolBar.translatesAutoresizingMaskIntoConstraints = false
textView.translatesAutoresizingMaskIntoConstraints = false
evalButton.translatesAutoresizingMaskIntoConstraints = false
textFieldHeightLayoutConstraint = NSLayoutConstraint(item: textView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 1)
toolBar.addConstraint(textFieldHeightLayoutConstraint)
toolBar.addConstraint(NSLayoutConstraint(item: textView, attribute: .left, relatedBy: .equal, toItem: toolBar, attribute: .left, multiplier: 1, constant: 8))
toolBar.addConstraint(NSLayoutConstraint(item: textView, attribute: .top, relatedBy: .equal, toItem: toolBar, attribute: .top, multiplier: 1, constant: 7.5))
toolBar.addConstraint(NSLayoutConstraint(item: textView, attribute: .trailing, relatedBy: .equal, toItem: evalButton, attribute: .leading, multiplier: 1, constant: -2))
toolBar.addConstraint(NSLayoutConstraint(item: textView, attribute: .bottom, relatedBy: .equal, toItem: toolBar, attribute: .bottom, multiplier: 1, constant: -8))
toolBar.addConstraint(NSLayoutConstraint(item: evalButton, attribute: .right, relatedBy: .equal, toItem: toolBar, attribute: .right, multiplier: 1, constant: 0))
toolBar.addConstraint(NSLayoutConstraint(item: evalButton, attribute: .bottom, relatedBy: .equal, toItem: toolBar, attribute: .bottom, multiplier: 1, constant: -4.5))
evalButton.setContentCompressionResistancePriority(UILayoutPriority.required, for: .horizontal)
evalButton.setContentHuggingPriority(UILayoutPriority.required, for: .horizontal)
}
return toolBar
}
}
required init?(coder aDecoder: NSCoder) {
self.history = History()
super.init(nibName: nil, bundle: nil)
//hidesBottomBarWhenPushed = true
self.currentKeyboardHeight = 0.0;
}
override var canBecomeFirstResponder : Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
history.loadedMessages = [
]
let whiteColor = UIColor.white
view.backgroundColor = whiteColor
if #available(iOS 11.0, *) {
let safeAreaInsets = UIApplication.shared.delegate?.window??.safeAreaInsets;
tableView = UITableView(frame: CGRect(x: safeAreaInsets!.left,
y: max(safeAreaInsets!.top, 20),
width: view.bounds.width - safeAreaInsets!.left - safeAreaInsets!.right,
height: view.bounds.height - max(safeAreaInsets!.top, 20) - safeAreaInsets!.bottom),
style: .plain)
} else {
tableView = UITableView(frame: CGRect(x: 0,
y: 20,
width: view.bounds.width,
height: view.bounds.height - 20),
style: .plain)
}
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView.backgroundColor = whiteColor
let edgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: toolBarMinHeight, right: 0)
tableView.contentInset = edgeInsets
tableView.dataSource = self
tableView.delegate = self
tableView.keyboardDismissMode = .interactive
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = .none
view.addSubview(tableView)
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(ReplViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(ReplViewController.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(ReplViewController.menuControllerWillHide(_:)), name: NSNotification.Name.UIMenuControllerWillHideMenu, object: nil) // #CopyMessage
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.setPrintCallback { (incoming: Bool, message: String!) -> Void in
DispatchQueue.main.async {
self.loadMessage(incoming, text: message)
}
}
DispatchQueue.main.async {
let version = appDelegate.getClojureScriptVersion()
let masthead = "\nClojureScript \(version!)\n" +
" Docs: (doc function-name)\n" +
" (find-doc \"part-of-name\")\n" +
" Source: (source function-name)\n" +
" Results: Stored in *1, *2, *3,\n" +
" an exception in *e\n";
self.loadMessage(false, text: masthead)
};
NSLog("Initializing...");
DispatchQueue.global(qos: .background).async {
appDelegate.initializeJavaScriptEnvironment()
self.initialized = true;
DispatchQueue.main.async {
// mark ready
NSLog("Ready");
let hasText = self.textView.hasText
self.evalButton.isEnabled = hasText
if (hasText) {
self.runParinfer()
}
}
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//tableView.flashScrollIndicators()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//chat.draft = textView.text
}
// This gets called a lot. Perhaps there's a better way to know when `view.window` has been set?
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if true {
//textView.text = chat.draft
//chat.draft = ""
textViewDidChange(textView)
textView.becomeFirstResponder()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return history.loadedMessages.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return history.loadedMessages[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = NSStringFromClass(HistoryTableViewCell.self)
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! HistoryTableViewCell?
if cell == nil {
cell = HistoryTableViewCell(style: .default, reuseIdentifier: cellIdentifier)
// Add gesture recognizers #CopyMessage
let action: Selector = #selector(ReplViewController.messageShowMenuAction(_:))
let doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: action)
doubleTapGestureRecognizer.numberOfTapsRequired = 2
cell?.messageLabel.addGestureRecognizer(doubleTapGestureRecognizer)
cell?.messageLabel.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: action))
}
let message = history.loadedMessages[indexPath.section][indexPath.row]
cell?.configureWithMessage(message)
return cell!
}
// Reserve row selection #CopyMessage
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return nil
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
// Disable default keyboard shortcut where two spaces inserts a '.'
let currentText = textView.text
if (range.location > 0 &&
text == " " &&
currentText![currentText!.index(currentText!.startIndex, offsetBy: range.location-1)..<currentText!.index(currentText!.startIndex, offsetBy: range.location)] == " ") {
textView.text = (textView.text as NSString).replacingCharacters(in: range, with: " ")
textView.selectedRange = NSMakeRange(range.location+1, 0);
return false;
}
if (text == "\n") {
enterPressed = true;
}
if (enterPressed && range.location == currentText!.count) {
enterPressed = false
while (!self.initialized) {
Thread.sleep(forTimeInterval: 0.1);
}
sendAction()
return false;
}
if (textView.intrinsicContentSize.width >= textView.frame.width - evalButton.frame.width - 12){ // the magic number is inset widths summed
textView.isScrollEnabled = true
}
else{
textView.isScrollEnabled = false
}
return true;
}
func runParinfer() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let currentText = textView.text
let currentSelectedRange = textView.selectedRange
if (currentText != "") {
let result: Array = appDelegate.parinferFormat(currentText, pos:Int32(currentSelectedRange.location), enterPressed:enterPressed)
textView.text = result[0] as! String
textView.selectedRange = NSMakeRange(result[1] as! Int, 0)
}
enterPressed = false;
}
// This is a native profile of Parinfer, meant for use when
// ClojureScript hasn't yet initialized, but yet the user
// is already typing. It covers extremely simple cases that
// could be typed immediately.
func runPoorMansParinfer() {
let currentText = textView.text
let currentSelectedRange = textView.selectedRange
if (currentText != "") {
if (currentSelectedRange.location == 1) {
if (currentText == "(") {
textView.text = "()";
} else if (currentText == "[") {
textView.text = "[]";
} else if (currentText == "{") {
textView.text = "{}";
}
textView.selectedRange = currentSelectedRange;
}
}
}
func textViewDidChange(_ textView: UITextView) {
if (initialized) {
runParinfer()
} else {
runPoorMansParinfer()
}
updateTextViewHeight()
evalButton.isEnabled = self.initialized && textView.hasText
}
@objc func keyboardWillShow(_ notification: Notification) {
let userInfo = notification.userInfo as NSDictionary?
let frameNew = (userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let insetNewBottom = tableView.convert(frameNew, from: nil).height
let insetOld = tableView.contentInset
let insetChange = insetNewBottom - insetOld.bottom
let overflow = tableView.contentSize.height - (tableView.frame.height-insetOld.top-insetOld.bottom)
let duration = (userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let animations: (() -> Void) = {
if !(self.tableView.isTracking || self.tableView.isDecelerating) {
// Move content with keyboard
if overflow > 0 { // scrollable before
self.tableView.contentOffset.y += insetChange
if self.tableView.contentOffset.y < -insetOld.top {
self.tableView.contentOffset.y = -insetOld.top
}
} else if insetChange > -overflow { // scrollable after
self.tableView.contentOffset.y += insetChange + overflow
}
}
}
if duration > 0 {
let options = UIViewAnimationOptions(rawValue: UInt((userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16)) // http://stackoverflow.com/a/18873820/242933
UIView.animate(withDuration: duration, delay: 0, options: options, animations: animations, completion: nil)
} else {
animations()
}
}
@objc func keyboardDidShow(_ notification: Notification) {
let userInfo = notification.userInfo as NSDictionary?
let frameNew = (userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let insetNewBottom = tableView.convert(frameNew, from: nil).height
self.currentKeyboardHeight = frameNew.height
// Inset `tableView` with keyboard
let contentOffsetY = tableView.contentOffset.y
tableView.contentInset.bottom = insetNewBottom
tableView.scrollIndicatorInsets.bottom = insetNewBottom
// Prevents jump after keyboard dismissal
if self.tableView.isTracking || self.tableView.isDecelerating {
tableView.contentOffset.y = contentOffsetY
}
}
func updateTextViewHeight() {
let oldHeight = textView.frame.height
let newText = textView.text
let newSize = (newText! as NSString).boundingRect(with: CGSize(width: textView.frame.width - textView.textContainerInset.right - textView.textContainerInset.left - 10, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: textView.font!], context: nil)
let heightChange = newSize.height + textView.textContainerInset.top + textView.textContainerInset.bottom - oldHeight
let containerInsetsSum = textView.textContainerInset.top + textView.textContainerInset.bottom
let maxHeightDeltas = toolBar.frame.height
- self.topLayoutGuide.length
- currentKeyboardHeight
- containerInsetsSum
- 20
let maxHeight = self.view.frame.height - maxHeightDeltas
if !(textFieldHeightLayoutConstraint.constant + heightChange > maxHeight){
//ceil because of small irregularities in heightChange
self.textFieldHeightLayoutConstraint.constant = ceil(heightChange + oldHeight)
//In order to ensure correct placement of text inside the textfield:
self.textView.setContentOffset(CGPoint.zero, animated: false)
//To ensure update of placement happens immediately
self.textView.layoutIfNeeded()
}
else{
self.textFieldHeightLayoutConstraint.constant = maxHeight
}
}
func markString(_ s: NSMutableAttributedString) -> Bool {
if (s.string.contains("\u{001b}[")) {
let text = s.string;
let range : Range<String.Index> = text.range(of: "\u{001b}[")!;
let index: Int = text.distance(from: text.startIndex, to: range.lowerBound);
let index2 = text.index(text.startIndex, offsetBy: index + 2);
var color : UIColor = UIColor.black;
if (text[index2...].hasPrefix("34m")){
color = UIColor.blue;
} else if (text[index2...].hasPrefix("32m")){
color = UIColor(red: 0.0, green: 0.75, blue: 0.0, alpha: 1.0);
} else if (text[index2...].hasPrefix("35m")){
color = UIColor(red: 0.75, green: 0.0, blue: 0.75, alpha: 1.0);
} else if (text[index2...].hasPrefix("31m")){
color = UIColor(red: 1, green: 0.33, blue: 0.33, alpha: 1.0);
}
s.replaceCharacters(in: NSMakeRange(index, 5), with: "");
s.addAttribute(NSAttributedStringKey.foregroundColor,
value: color,
range: NSMakeRange(index, s.length-index));
return true;
}
return false;
}
func loadMessage(_ incoming: Bool, text: String) {
let s = prepareMessageForDisplay(text)
addPreparedMessageToDisplay(incoming, text: s)
let delayTime = DispatchTime.now() + Double(Int64(50 * Double(NSEC_PER_MSEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
if (self.scrollToBottom) {
self.scrollToBottom = false;
self.tableViewScrollToBottomAnimated(false)
}
}
}
func prepareMessageForDisplay(_ text: String) -> NSMutableAttributedString? {
if (text != "\n") {
let s = NSMutableAttributedString(string:text);
while (markString(s)) {};
return s
}
return nil
}
func addPreparedMessageToDisplay(_ incoming: Bool, text: NSMutableAttributedString?) {
guard let text = text else {
return
}
history.loadedMessages.append([Message(incoming: incoming, text: text)])
if (history.loadedMessages.count > 64) {
history.loadedMessages.remove(at: 0);
tableView.reloadData();
} else {
let lastSection = tableView.numberOfSections
tableView.beginUpdates()
tableView.insertSections(IndexSet(integer: lastSection), with: .automatic)
tableView.insertRows(at: [
IndexPath(row: 0, section: lastSection)
], with: .automatic)
tableView.endUpdates()
}
scrollToBottom = true;
}
@objc func sendAction() {
// Autocomplete text before sending #hack
//textView.resignFirstResponder()
//textView.becomeFirstResponder()
let textToEvaluate = textView.text
loadMessage(false, text: textToEvaluate!)
textView.text = nil
updateTextViewHeight()
evalButton.isEnabled = false
// Dispatch to be evaluated
let delayTime = DispatchTime.now() + Double(Int64(50 * Double(NSEC_PER_MSEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.evaluate(textToEvaluate)
}
}
func tableViewScrollToBottomAnimated(_ animated: Bool) {
let numberOfSections = tableView.numberOfSections;
let numberOfRows = tableView.numberOfRows(inSection: numberOfSections-1)
if numberOfRows > 0 {
tableView.scrollToRow(at: IndexPath(row: numberOfRows-1, section: numberOfSections-1), at: .bottom, animated: animated)
}
}
// Handle actions #CopyMessage
// 1. Select row and show "Copy" menu
@objc func messageShowMenuAction(_ gestureRecognizer: UITapGestureRecognizer) {
let twoTaps = (gestureRecognizer.numberOfTapsRequired == 2)
let doubleTap = (twoTaps && gestureRecognizer.state == .ended)
let longPress = (!twoTaps && gestureRecognizer.state == .began)
if doubleTap || longPress {
let pressedIndexPath = tableView.indexPathForRow(at: gestureRecognizer.location(in: tableView))!
tableView.selectRow(at: pressedIndexPath, animated: false, scrollPosition: .none)
let menuController = UIMenuController.shared
let bubbleImageView = gestureRecognizer.view!
menuController.setTargetRect(bubbleImageView.frame, in: bubbleImageView.superview!)
menuController.menuItems = [UIMenuItem(title: "Copy", action: #selector(ReplViewController.messageCopyTextAction(_:)))]
menuController.setMenuVisible(true, animated: true)
}
}
// 2. Copy text to pasteboard
@objc func messageCopyTextAction(_ menuController: UIMenuController) {
let selectedIndexPath = tableView.indexPathForSelectedRow
let selectedMessage = history.loadedMessages[selectedIndexPath!.section][selectedIndexPath!.row]
UIPasteboard.general.string = selectedMessage.text.string
}
// 3. Deselect row
@objc func menuControllerWillHide(_ notification: Notification) {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: selectedIndexPath, animated: false)
}
(notification.object as! UIMenuController).menuItems = nil
}
override var keyCommands: [UIKeyCommand]? {
get {
let commandEnter = UIKeyCommand(input: "\r", modifierFlags: .command, action: #selector(ReplViewController.sendAction))
return [commandEnter]
}
}
}
// Only show "Copy" when editing `textView` #CopyMessage
class InputTextView: UITextView {
override func canPerformAction(_ action: Selector, withSender sender: Any!) -> Bool {
if (delegate as! ReplViewController).tableView.indexPathForSelectedRow != nil {
return action == #selector(InputTextView.messageCopyTextAction(_:))
} else {
return super.canPerformAction(action, withSender: sender)
}
}
// More specific than implementing `nextResponder` to return `delegate`, which might cause side effects?
@objc func messageCopyTextAction(_ menuController: UIMenuController) {
(delegate as! ReplViewController).messageCopyTextAction(menuController)
}
}
|
epl-1.0
|
b8134b94cf566ccab84cef30d912d04b
| 44.608133 | 323 | 0.613561 | 5.347638 | false | false | false | false |
Ben21hao/edx-app-ios-new
|
Libraries/SnapKit/Source/View+SnapKit.swift
|
3
|
8443
|
//
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// 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 os(iOS)
import UIKit
public typealias View = UIView
#else
import AppKit
public typealias View = NSView
#endif
/**
Used to expose public API on views
*/
public extension View {
/// left edge
public var snp_left: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Left) }
/// top edge
public var snp_top: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Top) }
/// right edge
public var snp_right: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Right) }
/// bottom edge
public var snp_bottom: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Bottom) }
/// leading edge
public var snp_leading: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Leading) }
/// trailing edge
public var snp_trailing: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Trailing) }
/// width dimension
public var snp_width: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Width) }
/// height dimension
public var snp_height: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Height) }
/// centerX position
public var snp_centerX: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterX) }
/// centerY position
public var snp_centerY: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterY) }
/// baseline position
public var snp_baseline: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Baseline) }
/// first baseline position
@available(iOS 8.0, *)
public var snp_firstBaseline: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.FirstBaseline) }
/// left margin
@available(iOS 8.0, *)
public var snp_leftMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.LeftMargin) }
/// right margin
@available(iOS 8.0, *)
public var snp_rightMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.RightMargin) }
/// top margin
@available(iOS 8.0, *)
public var snp_topMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.TopMargin) }
/// bottom margin
@available(iOS 8.0, *)
public var snp_bottomMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.BottomMargin) }
/// leading margin
@available(iOS 8.0, *)
public var snp_leadingMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.LeadingMargin) }
/// trailing margin
@available(iOS 8.0, *)
public var snp_trailingMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.TrailingMargin) }
/// centerX within margins
@available(iOS 8.0, *)
public var snp_centerXWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterXWithinMargins) }
/// centerY within margins
@available(iOS 8.0, *)
public var snp_centerYWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterYWithinMargins) }
// top + left + bottom + right edges
public var snp_edges: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Edges) }
// width + height dimensions
public var snp_size: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Size) }
// centerX + centerY positions
public var snp_center: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Center) }
// top + left + bottom + right margins
@available(iOS 8.0, *)
public var snp_margins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Margins) }
// centerX + centerY within margins
@available(iOS 8.0, *)
public var snp_centerWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterWithinMargins) }
/**
Prepares constraints with a `ConstraintMaker` and returns the made constraints but does not install them.
:param: closure that will be passed the `ConstraintMaker` to make the constraints with
:returns: the constraints made
*/
public func snp_prepareConstraints(file: String = #file, line: UInt = #line, @noescape closure: (make: ConstraintMaker) -> Void) -> [Constraint] {
return ConstraintMaker.prepareConstraints(view: self, file: file, line: line, closure: closure)
}
/**
Makes constraints with a `ConstraintMaker` and installs them along side any previous made constraints.
:param: closure that will be passed the `ConstraintMaker` to make the constraints with
*/
public func snp_makeConstraints(file: String = #file, line: UInt = #line, @noescape closure: (make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.makeConstraints(view: self, file: file, line: line, closure: closure)
}
/**
Updates constraints with a `ConstraintMaker` that will replace existing constraints that match and install new ones.
For constraints to match only the constant can be updated.
:param: closure that will be passed the `ConstraintMaker` to update the constraints with
*/
public func snp_updateConstraints(file: String = #file, line: UInt = #line, @noescape closure: (make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.updateConstraints(view: self, file: file, line: line, closure: closure)
}
/**
Remakes constraints with a `ConstraintMaker` that will first remove all previously made constraints and make and install new ones.
:param: closure that will be passed the `ConstraintMaker` to remake the constraints with
*/
public func snp_remakeConstraints(file: String = #file, line: UInt = #line, @noescape closure: (make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.remakeConstraints(view: self, file: file, line: line, closure: closure)
}
/**
Removes all previously made constraints.
*/
public func snp_removeConstraints() {
ConstraintMaker.removeConstraints(view: self)
}
internal var snp_installedLayoutConstraints: [LayoutConstraint] {
get {
if let constraints = objc_getAssociatedObject(self, &installedLayoutConstraintsKey) as? [LayoutConstraint] {
return constraints
}
return []
}
set {
objc_setAssociatedObject(self, &installedLayoutConstraintsKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
private var installedLayoutConstraintsKey = ""
|
apache-2.0
|
2792dce49977e41deae9f69a2975ace2
| 45.136612 | 150 | 0.712543 | 5.031585 | false | false | false | false |
maxadamski/swift-corelibs-foundation
|
TestFoundation/TestNSGeometry.swift
|
1
|
16592
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSGeometry : XCTestCase {
var allTests : [(String, () -> ())] {
return [
("test_CGFloat_BasicConstruction", test_CGFloat_BasicConstruction),
("test_CGFloat_Equality", test_CGFloat_Equality),
("test_CGFloat_LessThanOrEqual", test_CGFloat_LessThanOrEqual),
("test_CGFloat_GreaterThanOrEqual", test_CGFloat_GreaterThanOrEqual),
("test_CGPoint_BasicConstruction", test_CGPoint_BasicConstruction),
("test_CGSize_BasicConstruction", test_CGSize_BasicConstruction),
("test_CGRect_BasicConstruction", test_CGRect_BasicConstruction),
("test_NSMakePoint", test_NSMakePoint),
("test_NSMakeSize", test_NSMakeSize),
("test_NSMakeRect", test_NSMakeRect),
("test_NSUnionRect", test_NSUnionRect),
("test_NSIntersectionRect", test_NSIntersectionRect),
("test_NSOffsetRect", test_NSOffsetRect),
("test_NSPointInRect", test_NSPointInRect),
("test_NSMouseInRect", test_NSMouseInRect),
("test_NSContainsRect", test_NSContainsRect),
("test_NSIntersectsRect", test_NSIntersectsRect),
("test_NSIntegralRect", test_NSIntegralRect),
("test_NSIntegralRectWithOptions", test_NSIntegralRectWithOptions),
]
}
func test_CGFloat_BasicConstruction() {
XCTAssertEqual(CGFloat().native, 0.0)
XCTAssertEqual(CGFloat(Double(3.0)).native, 3.0)
}
func test_CGFloat_Equality() {
XCTAssertEqual(CGFloat(), CGFloat())
XCTAssertEqual(CGFloat(1.0), CGFloat(1.0))
XCTAssertEqual(CGFloat(-42.0), CGFloat(-42.0))
XCTAssertNotEqual(CGFloat(1.0), CGFloat(1.4))
XCTAssertNotEqual(CGFloat(37.3), CGFloat(-42.0))
XCTAssertNotEqual(CGFloat(1.345), CGFloat())
}
func test_CGFloat_LessThanOrEqual() {
let w = CGFloat(-4.5)
let x = CGFloat(1.0)
let y = CGFloat(2.2)
XCTAssertLessThanOrEqual(CGFloat(), CGFloat())
XCTAssertLessThanOrEqual(w, w)
XCTAssertLessThanOrEqual(y, y)
XCTAssertLessThan(w, x)
XCTAssertLessThanOrEqual(w, x)
XCTAssertLessThan(x, y)
XCTAssertLessThanOrEqual(x, y)
XCTAssertLessThan(w, y)
XCTAssertLessThanOrEqual(w, y)
}
func test_CGFloat_GreaterThanOrEqual() {
let w = CGFloat(-4.5)
let x = CGFloat(1.0)
let y = CGFloat(2.2)
XCTAssertGreaterThanOrEqual(CGFloat(), CGFloat())
XCTAssertGreaterThanOrEqual(w, w)
XCTAssertGreaterThanOrEqual(y, y)
XCTAssertGreaterThan(x, w)
XCTAssertGreaterThanOrEqual(x, w)
XCTAssertGreaterThan(y, x)
XCTAssertGreaterThanOrEqual(y, x)
XCTAssertGreaterThan(y, w)
XCTAssertGreaterThanOrEqual(y, w)
}
func test_CGPoint_BasicConstruction() {
let p1 = CGPoint()
XCTAssertEqual(p1.x, CGFloat(0.0))
XCTAssertEqual(p1.y, CGFloat(0.0))
let p2 = CGPoint(x: CGFloat(3.6), y: CGFloat(4.5))
XCTAssertEqual(p2.x, CGFloat(3.6))
XCTAssertEqual(p2.y, CGFloat(4.5))
}
func test_CGSize_BasicConstruction() {
let s1 = CGSize()
XCTAssertEqual(s1.width, CGFloat(0.0))
XCTAssertEqual(s1.height, CGFloat(0.0))
let s2 = CGSize(width: CGFloat(3.6), height: CGFloat(4.5))
XCTAssertEqual(s2.width, CGFloat(3.6))
XCTAssertEqual(s2.height, CGFloat(4.5))
}
func test_CGVector_BasicConstruction() {
let v1 = CGVector()
XCTAssertEqual(v1.dx, CGFloat(0.0))
XCTAssertEqual(v1.dy, CGFloat(0.0))
let v2 = CGVector(dx: CGFloat(3.6), dy: CGFloat(4.5))
XCTAssertEqual(v2.dx, CGFloat(3.6))
XCTAssertEqual(v2.dy, CGFloat(4.5))
}
func test_CGRect_BasicConstruction() {
let r1 = CGRect()
XCTAssertEqual(r1.origin.x, CGFloat(0.0))
XCTAssertEqual(r1.origin.y, CGFloat(0.0))
XCTAssertEqual(r1.size.width, CGFloat(0.0))
XCTAssertEqual(r1.size.height, CGFloat(0.0))
let p = CGPoint(x: CGFloat(2.2), y: CGFloat(3.0))
let s = CGSize(width: CGFloat(5.0), height: CGFloat(5.0))
let r2 = CGRect(origin: p, size: s)
XCTAssertEqual(r2.origin.x, p.x)
XCTAssertEqual(r2.origin.y, p.y)
XCTAssertEqual(r2.size.width, s.width)
XCTAssertEqual(r2.size.height, s.height)
}
func test_NSMakePoint() {
let p2 = NSMakePoint(CGFloat(3.6), CGFloat(4.5))
XCTAssertEqual(p2.x, CGFloat(3.6))
XCTAssertEqual(p2.y, CGFloat(4.5))
}
func test_NSMakeSize() {
let s2 = NSMakeSize(CGFloat(3.6), CGFloat(4.5))
XCTAssertEqual(s2.width, CGFloat(3.6))
XCTAssertEqual(s2.height, CGFloat(4.5))
}
func test_NSMakeRect() {
let r2 = NSMakeRect(CGFloat(2.2), CGFloat(3.0), CGFloat(5.0), CGFloat(5.0))
XCTAssertEqual(r2.origin.x, CGFloat(2.2))
XCTAssertEqual(r2.origin.y, CGFloat(3.0))
XCTAssertEqual(r2.size.width, CGFloat(5.0))
XCTAssertEqual(r2.size.height, CGFloat(5.0))
}
func test_NSUnionRect() {
let r1 = NSMakeRect(CGFloat(1.2), CGFloat(3.1), CGFloat(10.0), CGFloat(10.0))
let r2 = NSMakeRect(CGFloat(10.2), CGFloat(2.5), CGFloat(5.0), CGFloat(5.0))
XCTAssertTrue(NSIsEmptyRect(NSUnionRect(NSZeroRect, NSZeroRect)))
XCTAssertTrue(NSEqualRects(r1, NSUnionRect(r1, NSZeroRect)))
XCTAssertTrue(NSEqualRects(r2, NSUnionRect(NSZeroRect, r2)))
let r3 = NSUnionRect(r1, r2)
XCTAssertEqual(r3.origin.x, CGFloat(1.2))
XCTAssertEqual(r3.origin.y, CGFloat(2.5))
XCTAssertEqual(r3.size.width, CGFloat(14.0))
XCTAssertEqual(r3.size.height, CGFloat(10.6))
}
func test_NSIntersectionRect() {
let r1 = NSMakeRect(CGFloat(1.2), CGFloat(3.1), CGFloat(10.0), CGFloat(10.0))
let r2 = NSMakeRect(CGFloat(-2.3), CGFloat(-1.5), CGFloat(1.0), CGFloat(1.0))
let r3 = NSMakeRect(CGFloat(10.2), CGFloat(2.5), CGFloat(5.0), CGFloat(5.0))
XCTAssertTrue(NSIsEmptyRect(NSIntersectionRect(r1, r2)))
let r4 = NSIntersectionRect(r1, r3)
XCTAssertEqual(r4.origin.x, CGFloat(10.2))
XCTAssertEqual(r4.origin.y, CGFloat(3.1))
XCTAssertEqual(r4.size.width, CGFloat(1.0))
XCTAssertEqual(r4.size.height, CGFloat(4.4))
}
func test_NSOffsetRect() {
let r1 = NSMakeRect(CGFloat(1.2), CGFloat(3.1), CGFloat(10.0), CGFloat(10.0))
let r2 = NSOffsetRect(r1, CGFloat(2.0), CGFloat(-5.0))
let expectedRect = NSMakeRect(CGFloat(3.2), CGFloat(-1.9), CGFloat(10.0), CGFloat(10.0))
XCTAssertTrue(NSEqualRects(r2, expectedRect))
}
func test_NSPointInRect() {
let p1 = NSMakePoint(CGFloat(2.2), CGFloat(5.3))
let p2 = NSMakePoint(CGFloat(1.2), CGFloat(3.1))
let p3 = NSMakePoint(CGFloat(1.2), CGFloat(5.3))
let p4 = NSMakePoint(CGFloat(5.2), CGFloat(3.1))
let p5 = NSMakePoint(CGFloat(11.2), CGFloat(13.1))
let r1 = NSMakeRect(CGFloat(1.2), CGFloat(3.1), CGFloat(10.0), CGFloat(10.0))
let r2 = NSMakeRect(CGFloat(-2.3), CGFloat(-1.5), CGFloat(1.0), CGFloat(1.0))
XCTAssertFalse(NSPointInRect(NSZeroPoint, NSZeroRect))
XCTAssertFalse(NSPointInRect(p1, r2))
XCTAssertTrue(NSPointInRect(p1, r1))
XCTAssertTrue(NSPointInRect(p2, r1))
XCTAssertTrue(NSPointInRect(p3, r1))
XCTAssertTrue(NSPointInRect(p4, r1))
XCTAssertFalse(NSPointInRect(p5, r1))
}
func test_NSMouseInRect() {
let p1 = NSMakePoint(CGFloat(2.2), CGFloat(5.3))
let r1 = NSMakeRect(CGFloat(1.2), CGFloat(3.1), CGFloat(10.0), CGFloat(10.0))
let r2 = NSMakeRect(CGFloat(-2.3), CGFloat(-1.5), CGFloat(1.0), CGFloat(1.0))
XCTAssertFalse(NSMouseInRect(NSZeroPoint, NSZeroRect, true))
XCTAssertFalse(NSMouseInRect(p1, r2, true))
XCTAssertTrue(NSMouseInRect(p1, r1, true))
let p2 = NSMakePoint(NSMinX(r1), NSMaxY(r1))
XCTAssertFalse(NSMouseInRect(p2, r1, true))
XCTAssertTrue(NSMouseInRect(p2, r1, false))
let p3 = NSMakePoint(NSMinX(r1), NSMinY(r1))
XCTAssertFalse(NSMouseInRect(p3, r1, false))
XCTAssertTrue(NSMouseInRect(p3, r1, true))
}
func test_NSContainsRect() {
let r1 = NSMakeRect(CGFloat(1.2), CGFloat(3.1), CGFloat(10.0), CGFloat(10.0))
let r2 = NSMakeRect(CGFloat(-2.3), CGFloat(-1.5), CGFloat(1.0), CGFloat(1.0))
let r3 = NSMakeRect(CGFloat(10.2), CGFloat(5.5), CGFloat(0.5), CGFloat(5.0))
XCTAssertFalse(NSContainsRect(r1, NSZeroRect))
XCTAssertFalse(NSContainsRect(r1, r2))
XCTAssertFalse(NSContainsRect(r2, r1))
XCTAssertTrue(NSContainsRect(r1, r3))
}
func test_NSIntersectsRect() {
let r1 = NSMakeRect(CGFloat(1.2), CGFloat(3.1), CGFloat(10.0), CGFloat(10.0))
let r2 = NSMakeRect(CGFloat(-2.3), CGFloat(-1.5), CGFloat(1.0), CGFloat(1.0))
let r3 = NSMakeRect(CGFloat(10.2), CGFloat(2.5), CGFloat(5.0), CGFloat(5.0))
XCTAssertFalse(NSIntersectsRect(NSZeroRect, NSZeroRect))
XCTAssertFalse(NSIntersectsRect(r1, NSZeroRect))
XCTAssertFalse(NSIntersectsRect(NSZeroRect, r2))
XCTAssertFalse(NSIntersectsRect(r1, r2))
XCTAssertTrue(NSIntersectsRect(r1, r3))
}
func test_NSIntegralRect() {
let referenceNegativeRect = NSMakeRect(CGFloat(-0.6), CGFloat(-5.4), CGFloat(-105.7), CGFloat(-24.3))
XCTAssertEqual(NSIntegralRect(referenceNegativeRect), NSZeroRect)
let referenceRect = NSMakeRect(CGFloat(0.6), CGFloat(5.4), CGFloat(105.7), CGFloat(24.3))
let referenceNegativeOriginRect = NSMakeRect(CGFloat(-0.6), CGFloat(-5.4), CGFloat(105.7), CGFloat(24.3))
var expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(5.0), CGFloat(107.0), CGFloat(25.0))
var result = NSIntegralRect(referenceRect)
XCTAssertEqual(result, expectedResult)
expectedResult = NSMakeRect(CGFloat(-1.0), CGFloat(-6.0), CGFloat(107.0), CGFloat(25.0))
result = NSIntegralRect(referenceNegativeOriginRect)
XCTAssertEqual(result, expectedResult)
}
func test_NSIntegralRectWithOptions() {
let referenceRect = NSMakeRect(CGFloat(0.6), CGFloat(5.4), CGFloat(105.7), CGFloat(24.3))
let referenceNegativeRect = NSMakeRect(CGFloat(-0.6), CGFloat(-5.4), CGFloat(-105.7), CGFloat(-24.3))
let referenceNegativeOriginRect = NSMakeRect(CGFloat(-0.6), CGFloat(-5.4), CGFloat(105.7), CGFloat(24.3))
var options: NSAlignmentOptions = [.AlignMinXInward, .AlignMinYInward, .AlignHeightInward, .AlignWidthInward]
var expectedResult = NSMakeRect(CGFloat(1.0), CGFloat(6.0), CGFloat(105.0), CGFloat(24.0))
var result = NSIntegralRectWithOptions(referenceRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMinXOutward, .AlignMinYOutward, .AlignHeightOutward, .AlignWidthOutward]
expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(5.0), CGFloat(106.0), CGFloat(25.0))
result = NSIntegralRectWithOptions(referenceRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMinXInward, .AlignMinYInward, .AlignHeightInward, .AlignWidthInward]
expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(-5.0), CGFloat(0.0), CGFloat(0.0))
result = NSIntegralRectWithOptions(referenceNegativeRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMinXInward, .AlignMinYInward, .AlignHeightInward, .AlignWidthInward]
expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(-5.0), CGFloat(105.0), CGFloat(24.0))
result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMinXOutward, .AlignMinYOutward, .AlignHeightOutward, .AlignWidthOutward]
expectedResult = NSMakeRect(CGFloat(-1.0), CGFloat(-6.0), CGFloat(106.0), CGFloat(25.0))
result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMaxXOutward, .AlignMaxYOutward, .AlignHeightOutward, .AlignWidthOutward]
expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(-6.0), CGFloat(106.0), CGFloat(25.0))
result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMinXOutward, .AlignMaxXOutward, .AlignMinYOutward, .AlignMaxYOutward]
expectedResult = NSMakeRect(CGFloat(-1.0), CGFloat(-6.0), CGFloat(107.0), CGFloat(25.0))
result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMaxXOutward, .AlignMaxYOutward, .AlignHeightOutward, .AlignWidthOutward]
expectedResult = NSMakeRect(CGFloat(1.0), CGFloat(5.0), CGFloat(106.0), CGFloat(25.0))
result = NSIntegralRectWithOptions(referenceRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMaxXInward, .AlignMaxYInward, .AlignHeightOutward, .AlignWidthOutward]
expectedResult = NSMakeRect(CGFloat(-1.0), CGFloat(-7.0), CGFloat(106.0), CGFloat(25.0))
result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMaxXInward, .AlignMaxYInward, .AlignHeightOutward, .AlignWidthOutward]
expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(4.0), CGFloat(106.0), CGFloat(25.0))
result = NSIntegralRectWithOptions(referenceRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMinXNearest, .AlignMinYNearest, .AlignHeightNearest, .AlignWidthNearest]
expectedResult = NSMakeRect(CGFloat(1.0), CGFloat(5.0), CGFloat(106.0), CGFloat(24.0))
result = NSIntegralRectWithOptions(referenceRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMinXNearest, .AlignMinYNearest, .AlignHeightNearest, .AlignWidthNearest]
expectedResult = NSMakeRect(CGFloat(-1.0), CGFloat(-5.0), CGFloat(106.0), CGFloat(24.0))
result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMaxXNearest, .AlignMaxYNearest, .AlignHeightNearest, .AlignWidthNearest]
expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(6.0), CGFloat(106.0), CGFloat(24.0))
result = NSIntegralRectWithOptions(referenceRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMaxXNearest, .AlignMaxYNearest, .AlignHeightNearest, .AlignWidthNearest]
expectedResult = NSMakeRect(CGFloat(-1.0), CGFloat(-5.0), CGFloat(106.0), CGFloat(24.0))
result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMinXInward, .AlignMaxXInward, .AlignMinYInward, .AlignMaxYInward]
expectedResult = NSMakeRect(CGFloat(1.0), CGFloat(6.0), CGFloat(105.0), CGFloat(23.0))
result = NSIntegralRectWithOptions(referenceRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMinXInward, .AlignMaxXInward, .AlignMinYInward, .AlignMaxYInward]
expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(-5.0), CGFloat(105.0), CGFloat(23.0))
result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
XCTAssertEqual(result, expectedResult)
options = [.AlignMinXNearest, .AlignMaxXInward, .AlignMinYInward, .AlignMaxYNearest]
expectedResult = NSMakeRect(CGFloat(-1.0), CGFloat(-5.0), CGFloat(106.0), CGFloat(24.0))
result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
XCTAssertEqual(result, expectedResult)
}
}
|
apache-2.0
|
b1f3f0ebd9f5719373f9ae38a6f91004
| 44.333333 | 117 | 0.66291 | 3.789858 | false | true | false | false |
sharath-cliqz/browser-ios
|
Client/Frontend/Home/HomePanels.swift
|
2
|
3055
|
/* 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
/**
* Data for identifying and constructing a HomePanel.
*/
struct HomePanelDescriptor {
let makeViewController: (_ profile: Profile) -> UIViewController
let imageName: String
let accessibilityLabel: String
let accessibilityIdentifier: String
}
class HomePanels {
let enabledPanels = [
HomePanelDescriptor(
makeViewController: { profile in
TopSitesPanel(profile: profile)
},
imageName: "TopSites",
accessibilityLabel: NSLocalizedString("Top sites", comment: "Panel accessibility label"),
accessibilityIdentifier: "HomePanels.TopSites"),
HomePanelDescriptor(
makeViewController: { profile in
let bookmarks = BookmarksPanel()
bookmarks.profile = profile
let controller = UINavigationController(rootViewController: bookmarks)
controller.setNavigationBarHidden(true, animated: false)
// this re-enables the native swipe to pop gesture on UINavigationController for embedded, navigation bar-less UINavigationControllers
// don't ask me why it works though, I've tried to find an answer but can't.
// found here, along with many other places:
// http://luugiathuy.com/2013/11/ios7-interactivepopgesturerecognizer-for-uinavigationcontroller-with-hidden-navigation-bar/
controller.interactivePopGestureRecognizer?.delegate = nil
return controller
},
imageName: "Bookmarks",
accessibilityLabel: NSLocalizedString("Bookmarks", comment: "Panel accessibility label"),
accessibilityIdentifier: "HomePanels.Bookmarks"),
HomePanelDescriptor(
makeViewController: { profile in
let history = HistoryPanel()
history.profile = profile
let controller = UINavigationController(rootViewController: history)
controller.setNavigationBarHidden(true, animated: false)
controller.interactivePopGestureRecognizer?.delegate = nil
return controller
},
imageName: "History",
accessibilityLabel: NSLocalizedString("History", comment: "Panel accessibility label"),
accessibilityIdentifier: "HomePanels.History"),
HomePanelDescriptor(
makeViewController: { profile in
let controller = ReadingListPanel()
controller.profile = profile
return controller
},
imageName: "ReadingList",
accessibilityLabel: NSLocalizedString("Reading list", comment: "Panel accessibility label"),
accessibilityIdentifier: "HomePanels.ReadingList"),
]
}
|
mpl-2.0
|
0bfe85d85916bb5f8bd1cae3e8e689ed
| 43.926471 | 150 | 0.643863 | 6.122244 | false | false | false | false |
benlangmuir/swift
|
test/SILGen/pointer_conversion.swift
|
2
|
27936
|
// RUN: %target-swift-emit-silgen -module-name pointer_conversion -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -enable-objc-interop | %FileCheck %s
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// REQUIRES: objc_interop
import Foundation
func sideEffect1() -> Int { return 1 }
func sideEffect2() -> Int { return 2 }
func takesMutablePointer(_ x: UnsafeMutablePointer<Int>) {}
func takesConstPointer(_ x: UnsafePointer<Int>) {}
func takesOptConstPointer(_ x: UnsafePointer<Int>?, and: Int) {}
func takesOptOptConstPointer(_ x: UnsafePointer<Int>??, and: Int) {}
func takesMutablePointer(_ x: UnsafeMutablePointer<Int>, and: Int) {}
func takesConstPointer(_ x: UnsafePointer<Int>, and: Int) {}
func takesMutableVoidPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstVoidPointer(_ x: UnsafeRawPointer) {}
func takesMutableRawPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstRawPointer(_ x: UnsafeRawPointer) {}
func takesOptConstRawPointer(_ x: UnsafeRawPointer?, and: Int) {}
func takesOptOptConstRawPointer(_ x: UnsafeRawPointer??, and: Int) {}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion0A9ToPointeryySpySiG_SPySiGSvtF
// CHECK: bb0([[MP:%.*]] : $UnsafeMutablePointer<Int>, [[CP:%.*]] : $UnsafePointer<Int>, [[MRP:%.*]] : $UnsafeMutableRawPointer):
func pointerToPointer(_ mp: UnsafeMutablePointer<Int>,
_ cp: UnsafePointer<Int>, _ mrp: UnsafeMutableRawPointer) {
// There should be no conversion here
takesMutablePointer(mp)
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[MP]])
takesMutableVoidPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: [[TAKES_MUTABLE_VOID_POINTER:%.*]] = function_ref @$s18pointer_conversion23takesMutableVoidPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_VOID_POINTER]]
takesMutableRawPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion22takesMutableRawPointeryySvF :
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]
takesConstPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafePointer<Int>>
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @$s18pointer_conversion17takesConstPointeryySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]
takesConstVoidPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @$s18pointer_conversion21takesConstVoidPointeryySVF
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySVF :
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstPointer(cp)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @$s18pointer_conversion17takesConstPointeryySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]([[CP]])
takesConstVoidPointer(cp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @$s18pointer_conversion21takesConstVoidPointeryySVF
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(cp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySVF
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstRawPointer(mrp)
// CHECK: [[CONVERT:%.*]] = function_ref @$ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySVF
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion14arrayToPointeryyF
func arrayToPointer() {
var ints = [1,2,3]
takesMutablePointer(&ints)
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @$ss37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutablePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutablePointer<Int> on [[OWNER]]
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstPointer(ints)
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @$s18pointer_conversion17takesConstPointeryySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesMutableRawPointer(&ints)
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @$ss37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutableRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutableRawPointer on [[OWNER]]
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion22takesMutableRawPointeryySvF :
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(ints)
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySVF :
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesOptConstPointer(ints, and: sideEffect1())
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt, [[DEPENDENT]]
// CHECK: [[TAKES_OPT_CONST_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesOptConstPointer_3andySPySiGSg_SitF :
// CHECK: apply [[TAKES_OPT_CONST_POINTER]]([[OPTPTR]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion15stringToPointeryySSF
func stringToPointer(_ s: String) {
takesConstVoidPointer(s)
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @$s18pointer_conversion21takesConstVoidPointeryySV{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(s)
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion20takesConstRawPointeryySV{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesOptConstRawPointer(s, and: sideEffect1())
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt, [[DEPENDENT]]
// CHECK: [[TAKES_OPT_CONST_RAW_POINTER:%.*]] = function_ref @$s18pointer_conversion23takesOptConstRawPointer_3andySVSg_SitF :
// CHECK: apply [[TAKES_OPT_CONST_RAW_POINTER]]([[OPTPTR]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion14inoutToPointeryyF
func inoutToPointer() {
var int = 0
// CHECK: [[INT:%.*]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[INT]]
takesMutablePointer(&int)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [stack_protection] [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
var logicalInt: Int {
get { return 0 }
set { }
}
takesMutablePointer(&logicalInt)
// CHECK: [[GETTER:%.*]] = function_ref @$s18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivg
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @$s18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivs
// CHECK: apply [[SETTER]]
takesMutableRawPointer(&int)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [stack_protection] [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
takesMutableRawPointer(&logicalInt)
// CHECK: [[GETTER:%.*]] = function_ref @$s18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivg
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @$s18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivs
// CHECK: apply [[SETTER]]
}
class C {}
func takesPlusOnePointer(_ x: UnsafeMutablePointer<C>) {}
func takesPlusZeroPointer(_ x: AutoreleasingUnsafeMutablePointer<C>) {}
func takesPlusZeroOptionalPointer(_ x: AutoreleasingUnsafeMutablePointer<C?>) {}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion19classInoutToPointeryyF
func classInoutToPointer() {
var c = C()
// CHECK: [[VAR:%.*]] = alloc_box ${ var C }
// CHECK: [[LIFETIME:%[^,]+]] = begin_borrow [lexical] [[VAR]]
// CHECK: [[PB:%.*]] = project_box [[LIFETIME]]
takesPlusOnePointer(&c)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [stack_protection] [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_PLUS_ONE:%.*]] = function_ref @$s18pointer_conversion19takesPlusOnePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_PLUS_ONE]]
takesPlusZeroPointer(&c)
// CHECK: [[WRITE2:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[WRITEBACK:%.*]] = alloc_stack $@sil_unmanaged C
// CHECK: [[OWNED:%.*]] = load_borrow [[WRITE2]]
// CHECK: [[UNOWNED:%.*]] = ref_to_unmanaged [[OWNED]]
// CHECK: store [[UNOWNED]] to [trivial] [[WRITEBACK]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [stack_protection] [[WRITEBACK]]
// CHECK: [[CONVERT:%.*]] = function_ref @$ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<AutoreleasingUnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_PLUS_ZERO:%.*]] = function_ref @$s18pointer_conversion20takesPlusZeroPointeryySAyAA1CCGF
// CHECK: apply [[TAKES_PLUS_ZERO]]
// CHECK: [[UNOWNED_OUT:%.*]] = load [trivial] [[WRITEBACK]]
// CHECK: [[OWNED_OUT:%.*]] = unmanaged_to_ref [[UNOWNED_OUT]]
// CHECK: [[OWNED_OUT_COPY:%.*]] = copy_value [[OWNED_OUT]]
// CHECK: assign [[OWNED_OUT_COPY]] to [[WRITE2]]
var cq: C? = C()
takesPlusZeroOptionalPointer(&cq)
}
// Check that pointer types don't bridge anymore.
@objc class ObjCMethodBridging : NSObject {
// CHECK-LABEL: sil private [thunk] [ossa] @$s18pointer_conversion18ObjCMethodBridgingC0A4Args{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (UnsafeMutablePointer<Int>, UnsafePointer<Int>, AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>, ObjCMethodBridging)
@objc func pointerArgs(_ x: UnsafeMutablePointer<Int>,
y: UnsafePointer<Int>,
z: AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>) {}
}
// rdar://problem/21505805
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion22functionInoutToPointeryyF
func functionInoutToPointer() {
// CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_guaranteed () -> () }
var f: () -> () = {}
// CHECK: [[REABSTRACT_BUF:%.*]] = alloc_stack $@callee_guaranteed @substituted <τ_0_0> () -> @out τ_0_0 for <()>
// CHECK: address_to_pointer [stack_protection] [[REABSTRACT_BUF]]
takesMutableVoidPointer(&f)
}
// rdar://problem/31781386
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion20inoutPointerOrderingyyF
func inoutPointerOrdering() {
// CHECK: [[ARRAY_BOX:%.*]] = alloc_box ${ var Array<Int> }
// CHECK: [[ARRAY_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[ARRAY_BOX]]
// CHECK: [[ARRAY:%.*]] = project_box [[ARRAY_LIFETIME]] :
// CHECK: store {{.*}} to [init] [[ARRAY]]
var array = [Int]()
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[SIDE2:%.*]] = function_ref @$s18pointer_conversion11sideEffect2SiyF
// CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[ARRAY]] : $*Array<Int>
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$s18pointer_conversion19takesMutablePointer_3andySpySiG_SitF
// CHECK: apply [[TAKES_MUTABLE]]({{.*}}, [[RESULT2]])
// CHECK: end_access [[ACCESS]]
takesMutablePointer(&array[sideEffect1()], and: sideEffect2())
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[SIDE2:%.*]] = function_ref @$s18pointer_conversion11sideEffect2SiyF
// CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[ARRAY]] : $*Array<Int>
// CHECK: [[TAKES_CONST:%.*]] = function_ref @$s18pointer_conversion17takesConstPointer_3andySPySiG_SitF
// CHECK: apply [[TAKES_CONST]]({{.*}}, [[RESULT2]])
// CHECK: end_access [[ACCESS]]
takesConstPointer(&array[sideEffect1()], and: sideEffect2())
}
// rdar://problem/31542269
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion20optArrayToOptPointer5arrayySaySiGSg_tF
func optArrayToOptPointer(array: [Int]?) {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: switch_enum [[COPY]] : $Optional<Array<Int>>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[SOME_VALUE:%.*]] :
// CHECK: [[CONVERT:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgumentyyXlSg_q_tSayxGs01_E0R_r0_lF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$s18pointer_conversion20takesOptConstPointer_3andySPySiGSg_SitF
// CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK-NOT: destroy_value %0
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptConstPointer(array, and: sideEffect1())
}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion013optOptArrayTodD7Pointer5arrayySaySiGSgSg_tF
func optOptArrayToOptOptPointer(array: [Int]??) {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: switch_enum [[COPY]] : $Optional<Optional<Array<Int>>>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[SOME_VALUE:%.*]] :
// CHECK: switch_enum [[SOME_VALUE]] : $Optional<Array<Int>>, case #Optional.some!enumelt: [[SOME_SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[SOME_NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_SOME_BB]]([[SOME_SOME_VALUE:%.*]] :
// CHECK: [[CONVERT:%.*]] = function_ref @$ss35_convertConstArrayToPointerArgumentyyXlSg_q_tSayxGs01_E0R_r0_lF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]]
// CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.some!enumelt, [[OPTDEP]]
// CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$s18pointer_conversion08takesOptD12ConstPointer_3andySPySiGSgSg_SitF
// CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK-NOT: destroy_value %0
// CHECK: [[SOME_NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>)
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafePointer<Int>>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptOptConstPointer(array, and: sideEffect1())
}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion21optStringToOptPointer6stringySSSg_tF
func optStringToOptPointer(string: String?) {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: switch_enum [[COPY]] : $Optional<String>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[SOME_VALUE:%.*]] :
// CHECK: [[CONVERT:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgumentyyXlSg_xtSSs01_F0RzlF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$s18pointer_conversion23takesOptConstRawPointer_3andySVSg_SitF
// CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK-NOT: destroy_value %0
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptConstRawPointer(string, and: sideEffect1())
}
// CHECK-LABEL: sil hidden [ossa] @$s18pointer_conversion014optOptStringTodD7Pointer6stringySSSgSg_tF
func optOptStringToOptOptPointer(string: String??) {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[SIDE1:%.*]] = function_ref @$s18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// FIXME: this should really go somewhere that will make nil, not some(nil)
// CHECK: switch_enum [[COPY]] : $Optional<Optional<String>>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[SOME_VALUE:%.*]] :
// CHECK: switch_enum [[SOME_VALUE]] : $Optional<String>, case #Optional.some!enumelt: [[SOME_SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[SOME_NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_SOME_BB]]([[SOME_SOME_VALUE:%.*]] :
// CHECK: [[CONVERT:%.*]] = function_ref @$ss40_convertConstStringToUTF8PointerArgumentyyXlSg_xtSSs01_F0RzlF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]]
// CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.some!enumelt, [[OPTDEP]]
// CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER:%.*]] : @owned $Optional<AnyObject>):
// CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$s18pointer_conversion08takesOptD15ConstRawPointer_3andySVSgSg_SitF
// CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK-NOT: destroy_value %0
// CHECK: [[SOME_NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>)
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafeRawPointer>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptOptConstRawPointer(string, and: sideEffect1())
}
|
apache-2.0
|
61e42ff66112dbe3aa6de8fe32b9d1f5
| 61.773034 | 267 | 0.650569 | 3.694485 | false | false | false | false |
lemonkey/iOS
|
WatchKit/_Apple/ListerforAppleWatchiOSandOSX/Swift/ListerKit/ListsController.swift
|
2
|
21591
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `ListsController` and `ListsControllerDelegate` infrastructure provide a mechanism for other objects within the application to be notified of inserts, removes, and updates to `ListInfo` objects. In addition, it also provides a way for parts of the application to present errors that occured when creating or removing lists.
*/
import Foundation
/**
The `ListsControllerDelegate` protocol enables a `ListsController` object to notify other objects of changes
to available `ListInfo` objects. This includes "will change content" events, "did change content"
events, inserts, removes, updates, and errors. Note that the `ListsController` can call these methods
on an aribitrary queue. If the implementation in these methods require UI manipulations, you should
respond to the changes on the main queue.
*/
@objc public protocol ListsControllerDelegate {
/**
Notifies the receiver of this method that the lists controller will change it's contents in
some form. This method is *always* called before any insert, remove, or update is received.
In this method, you should prepare your UI for making any changes related to the changes
that you will need to reflect once they are received. For example, if you have a table view
in your UI that needs to respond to changes to a newly inserted `ListInfo` object, you would
want to call your table view's `beginUpdates()` method. Once all of the updates are performed,
your `listsControllerDidChangeContent(_:)` method will be called. This is where you would to call
your table view's `endUpdates()` method.
:param: listsController The `ListsController` instance that will change its content.
*/
optional func listsControllerWillChangeContent(listsController: ListsController)
/**
Notifies the receiver of this method that the lists controller is tracking a new `ListInfo`
object. Receivers of this method should update their UI accordingly.
:param: listsController The `ListsController` instance that inserted the new `ListInfo`.
:param: listInfo The new `ListInfo` object that has been inserted at `index`.
:param: index The index that `listInfo` was inserted at.
*/
optional func listsController(listsController: ListsController, didInsertListInfo listInfo: ListInfo, atIndex index: Int)
/**
Notifies the receiver of this method that the lists controller received a message that `listInfo`
has updated its content. Receivers of this method should update their UI accordingly.
:param: listsController The `ListsController` instance that was notified that `listInfo` has been updated.
:param: listInfo The `ListInfo` object that has been updated.
:param: index The index of `listInfo`, the updated `ListInfo`.
*/
optional func listsController(listsController: ListsController, didRemoveListInfo listInfo: ListInfo, atIndex index: Int)
/**
Notifies the receiver of this method that the lists controller is no longer tracking `listInfo`.
Receivers of this method should update their UI accordingly.
:param: listsController The `ListsController` instance that removed `listInfo`.
:param: listInfo The removed `ListInfo` object.
:param: index The index that `listInfo` was removed at.
*/
optional func listsController(listsController: ListsController, didUpdateListInfo listInfo: ListInfo, atIndex index: Int)
/**
Notifies the receiver of this method that the lists controller did change it's contents in
some form. This method is *always* called after any insert, remove, or update is received.
In this method, you should finish off changes to your UI that were related to any insert, remove,
or update. For an example of how you might handle a "did change" contents call, see
the discussion for `listsControllerWillChangeContent(_:)`.
:param: listsController The `ListsController` instance that did change its content.
*/
optional func listsControllerDidChangeContent(listsController: ListsController)
/**
Notifies the receiver of this method that an error occured when creating a new `ListInfo` object.
In implementing this method, you should present the error to the user. Do not rely on the
`ListInfo` instance to be valid since an error occured in creating the object.
:param: listsController The `ListsController` that is notifying that a failure occured.
:param: listInfo The `ListInfo` that represents the list that couldn't be created.
:param: error The error that occured.
*/
optional func listsController(listsController: ListsController, didFailCreatingListInfo listInfo: ListInfo, withError error: NSError)
/**
Notifies the receiver of this method that an error occured when removing an existing `ListInfo`
object. In implementing this method, you should present the error to the user.
:param: listsController The `ListsController` that is notifying that a failure occured.
:param: listInfo The `ListInfo` that represents the list that couldn't be removed.
:param: error The error that occured.
*/
optional func listsController(listsController: ListsController, didFailRemovingListInfo listInfo: ListInfo, withError error: NSError)
}
/**
The `ListsController` class is responsible for tracking `ListInfo` objects that are found through
lists controller's `ListCoordinator` object. `ListCoordinator` objects are responsible for notifying
the lists controller of inserts, removes, updates, and errors when interacting with a list's URL.
Since the work of searching, removing, inserting, and updating `ListInfo` objects is done by the list
controller's coordinator, the lists controller serves as a way to avoid the need to interact with a single
`ListCoordinator` directly throughout the application. It also allows the rest of the application
to deal with `ListInfo` objects rather than dealing with their `NSURL` instances directly. In essence,
the work of a lists controller is to "front" its current coordinator. All changes that the coordinator
relays to the `ListsController` object will be relayed to the lists controller's delegate. This ability to
front another object is particularly useful when the underlying coordinator changes. As an example,
this could happen when the user changes their storage option from using local documents to using
cloud documents. If the coordinator property of the lists controller changes, other objects throughout
the application are unaffected since the lists controller will notify them of the appropriate
changes (removes, inserts, etc.).
*/
final public class ListsController: NSObject, ListCoordinatorDelegate {
// MARK: Properties
/// The `ListsController`'s delegate who is responsible for responding to `ListsController` updates.
public weak var delegate: ListsControllerDelegate?
/// :returns: The number of tracked `ListInfo` objects.
public var count: Int {
var listInfosCount: Int!
dispatch_sync(listInfoQueue) {
listInfosCount = self.listInfos.count
}
return listInfosCount
}
/// The current `ListCoordinator` that the lists controller manages.
public var listCoordinator: ListCoordinator {
didSet(oldListCoordinator) {
oldListCoordinator.stopQuery()
// Map the listInfo objects protected by listInfoQueue.
var allURLs: [NSURL]!
dispatch_sync(listInfoQueue) {
allURLs = self.listInfos.map { $0.URL }
}
self.processContentChanges(insertedURLs: [], removedURLs: allURLs, updatedURLs: [])
self.listCoordinator.delegate = self
oldListCoordinator.delegate = nil
self.listCoordinator.startQuery()
}
}
/**
The `ListInfo` objects that are cached by the `ListsController` to allow for users of the
`ListsController` class to easily subscript the controller.
*/
private var listInfos = [ListInfo]()
/**
:returns: A private, local queue to the `ListsController` that is used to perform updates on
`listInfos`.
*/
private let listInfoQueue = dispatch_queue_create("com.example.apple-samplecode.lister.listscontroller", DISPATCH_QUEUE_SERIAL)
/**
The sort predicate that's set in initialization. The sort predicate ensures a strict sort ordering
of the `listInfos` array. If `sortPredicate` is nil, the sort order is ignored.
*/
private let sortPredicate: ((lhs: ListInfo, rhs: ListInfo) -> Bool)?
/// The queue on which the `ListsController` object invokes delegate messages.
private var delegateQueue: NSOperationQueue
// MARK: Initializers
/**
Initializes a `ListsController` instance with an initial `ListCoordinator` object and a sort
predicate (if any). If no sort predicate is provided, the controller ignores sort order.
:param: listCoordinator The `ListsController`'s initial `ListCoordinator`.
:param: delegateQueue The queue on which the `ListsController` object invokes delegate messages.
:param: sortPredicate The predicate that determines the strict sort ordering of the `listInfos` array.
*/
public init(listCoordinator: ListCoordinator, delegateQueue: NSOperationQueue, sortPredicate: ((lhs: ListInfo, rhs: ListInfo) -> Bool)? = nil) {
self.listCoordinator = listCoordinator
self.delegateQueue = delegateQueue
self.sortPredicate = sortPredicate
super.init()
self.listCoordinator.delegate = self
}
// MARK: Subscripts
/**
:returns: The `ListInfo` instance at a specific index. This method traps if the index is out
of bounds.
*/
public subscript(idx: Int) -> ListInfo {
// Fetch the appropriate list info protected by `listInfoQueue`.
var listInfo: ListInfo!
dispatch_sync(listInfoQueue) {
listInfo = self.listInfos[idx]
}
return listInfo
}
// MARK: Convenience
/**
Begin listening for changes to the tracked `ListInfo` objects. This is managed by the `listCoordinator`
object. Be sure to balance each call to `startSearching()` with a call to `stopSearching()`.
*/
public func startSearching() {
listCoordinator.startQuery()
}
/**
Stop listening for changes to the tracked `ListInfo` objects. This is managed by the `listCoordinator`
object. Each call to `startSearching()` should be balanced with a call to this method.
*/
public func stopSearching() {
listCoordinator.stopQuery()
}
// MARK: Inserting / Removing / Managing / Updating `ListInfo` Objects
/**
Removes `listInfo` from the tracked `ListInfo` instances. This method forwards the remove
operation directly to the list coordinator. The operation can be performed asynchronously
so long as the underlying `ListCoordinator` instance sends the `ListsController` the correct
delegate messages: either a `listCoordinatorDidUpdateContents(insertedURLs:removedURLs:updatedURLs:)`
call with the removed `ListInfo` object, or with an error callback.
:param: listInfo The `ListInfo` to remove from the list of tracked `ListInfo` instances.
*/
public func removeListInfo(listInfo: ListInfo) {
listCoordinator.removeListAtURL(listInfo.URL)
}
/**
Attempts to create `ListInfo` representing `list` with the given name. If the method is succesful,
the lists controller adds it to the list of tracked `ListInfo` instances. This method forwards
the create operation directly to the list coordinator. The operation can be performed asynchronously
so long as the underlying `ListCoordinator` instance sends the `ListsController` the correct
delegate messages: either a `listCoordinatorDidUpdateContents(insertedURLs:removedURLs:updatedURLs:)`
call with the newly inserted `ListInfo`, or with an error callback.
Note: it's important that before calling this method, a call to `canCreateListWithName(_:)`
is performed to make sure that the name is a valid list name. Doing so will decrease the errors
that you see when you actually create a list.
:param: list The `List` object that should be used to save the initial list.
:param: name The name of the new list.
*/
public func createListInfoForList(list: List, withName name: String) {
listCoordinator.createURLForList(list, withName: name)
}
/**
Determines whether or not a list can be created with a given name. This method delegates to
`listCoordinator` to actually check to see if the list can be created with the given name. This
method should be called before `createListInfoForList(_:withName:)` is called to ensure to minimize
the number of errors that can occur when creating a list.
:param: name The name to check to see if it's valid or not.
:returns: `true` if the list can be created with the given name, `false` otherwise.
*/
public func canCreateListInfoWithName(name: String) -> Bool {
return listCoordinator.canCreateListWithName(name)
}
/**
Lets the `ListsController` know that `listInfo` has been udpdated. Once the change is reflected
in `listInfos` array, a didUpdateListInfo message is sent.
:param: listInfo The `ListInfo` instance that has new content.
*/
public func setListInfoHasNewContents(listInfo: ListInfo) {
dispatch_async(listInfoQueue) {
// Remove the old list info and replace it with the new one.
let indexOfListInfo = find(self.listInfos, listInfo)!
self.listInfos[indexOfListInfo] = listInfo
if let delegate = self.delegate {
self.delegateQueue.addOperationWithBlock {
delegate.listsControllerWillChangeContent?(self)
delegate.listsController?(self, didUpdateListInfo: listInfo, atIndex: indexOfListInfo)
delegate.listsControllerDidChangeContent?(self)
}
}
}
}
// MARK: ListCoordinatorDelegate
/**
Receives changes from `listCoordinator` about inserted, removed, and/or updated `ListInfo`
objects. When any of these changes occurs, these changes are processed and forwarded along
to the `ListsController` object's delegate. This implementation determines where each of these
URLs were located so that the controller can forward the new / removed / updated indexes
as well. For more information about this method, see the method description for this method
in the `ListCoordinator` class.
:param: insertedURLs The `NSURL` instances that should be tracekd.
:param: removedURLs The `NSURL` instances that should be untracked.
:param: updatedURLs The `NSURL` instances that have had their underlying model updated.
*/
public func listCoordinatorDidUpdateContents(#insertedURLs: [NSURL], removedURLs: [NSURL], updatedURLs: [NSURL]) {
processContentChanges(insertedURLs: insertedURLs, removedURLs: removedURLs, updatedURLs: updatedURLs)
}
/**
Forwards the "create" error from the `ListCoordinator` to the `ListsControllerDelegate`. For more
information about when this method can be called, see the description for this method in the
`ListCoordinatorDelegate` protocol description.
:param: URL The `NSURL` instances that was failed to be created.
:param: error The error the describes why the create failed.
*/
public func listCoordinatorDidFailCreatingListAtURL(URL: NSURL, withError error: NSError) {
let listInfo = ListInfo(URL: URL)
delegateQueue.addOperationWithBlock {
self.delegate?.listsController?(self, didFailCreatingListInfo: listInfo, withError: error)
return
}
}
/**
Forwards the "remove" error from the `ListCoordinator` to the `ListsControllerDelegate`. For
more information about when this method can be called, see the description for this method in
the `ListCoordinatorDelegate` protocol description.
:param: URL The `NSURL` instance that failed to be removed
:param: error The error that describes why the remove failed.
*/
public func listCoordinatorDidFailRemovingListAtURL(URL: NSURL, withError error: NSError) {
let listInfo = ListInfo(URL: URL)
delegateQueue.addOperationWithBlock {
self.delegate?.listsController?(self, didFailRemovingListInfo: listInfo, withError: error)
return
}
}
// MARK: Change Processing
/**
Processes changes to the `ListsController` object's `ListInfo` collection. This implementation
performs the updates and determines where each of these URLs were located so that the controller can
forward the new / removed / updated indexes as well.
:param: insertedURLs The `NSURL` instances that are newly tracked.
:param: removedURLs The `NSURL` instances that have just been untracked.
:param: updatedURLs The `NSURL` instances that have had their underlying model updated.
*/
private func processContentChanges(#insertedURLs: [NSURL], removedURLs: [NSURL], updatedURLs: [NSURL]) {
let insertedListInfos = insertedURLs.map { ListInfo(URL: $0) }
let removedListInfos = removedURLs.map { ListInfo(URL: $0) }
let updatedListInfos = updatedURLs.map { ListInfo(URL: $0) }
delegateQueue.addOperationWithBlock {
// Filter out all lists that are already included in the tracked lists.
var trackedRemovedListInfos: [ListInfo]!
var untrackedInsertedListInfos: [ListInfo]!
dispatch_sync(self.listInfoQueue) {
trackedRemovedListInfos = removedListInfos.filter { contains(self.listInfos, $0) }
untrackedInsertedListInfos = insertedListInfos.filter { !contains(self.listInfos, $0) }
}
if untrackedInsertedListInfos.isEmpty && trackedRemovedListInfos.isEmpty && updatedListInfos.isEmpty {
return
}
self.delegate?.listsControllerWillChangeContent?(self)
// Remove
for trackedRemovedListInfo in trackedRemovedListInfos {
var trackedRemovedListInfoIndex: Int!
dispatch_sync(self.listInfoQueue) {
trackedRemovedListInfoIndex = find(self.listInfos, trackedRemovedListInfo)!
self.listInfos.removeAtIndex(trackedRemovedListInfoIndex)
}
self.delegate?.listsController?(self, didRemoveListInfo: trackedRemovedListInfo, atIndex: trackedRemovedListInfoIndex)
}
// Sort the untracked inserted list infos
if let sortPredicate = self.sortPredicate {
untrackedInsertedListInfos.sort(sortPredicate)
}
// Insert
for untrackedInsertedListInfo in untrackedInsertedListInfos {
var untrackedInsertedListInfoIndex: Int!
dispatch_sync(self.listInfoQueue) {
self.listInfos += [untrackedInsertedListInfo]
if let sortPredicate = self.sortPredicate {
self.listInfos.sort(sortPredicate)
}
untrackedInsertedListInfoIndex = find(self.listInfos, untrackedInsertedListInfo)!
}
self.delegate?.listsController?(self, didInsertListInfo: untrackedInsertedListInfo, atIndex: untrackedInsertedListInfoIndex)
}
// Update
for updatedListInfo in updatedListInfos {
var updatedListInfoIndex: Int?
dispatch_sync(self.listInfoQueue) {
updatedListInfoIndex = find(self.listInfos, updatedListInfo)
// Track the new list info instead of the old one.
if let updatedListInfoIndex = updatedListInfoIndex {
self.listInfos[updatedListInfoIndex] = updatedListInfo
}
}
if let updatedListInfoIndex = updatedListInfoIndex {
self.delegate?.listsController?(self, didUpdateListInfo: updatedListInfo, atIndex: updatedListInfoIndex)
}
}
self.delegate?.listsControllerDidChangeContent?(self)
}
}
}
|
mit
|
f9e37ed6f3535f47f174fd62cc09b9bd
| 48.402746 | 331 | 0.676456 | 5.350434 | false | false | false | false |
DoubleSha/BitcoinSwift
|
BitcoinSwift/PeerConnection.swift
|
1
|
22096
|
//
// PeerConnection.swift
// BitcoinSwift
//
// Created by Kevin Greene on 6/27/14.
// Copyright (c) 2014 DoubleSha. All rights reserved.
//
import Foundation
/// Conform to this protocol if you want to be notified of the low-level P2P messages received from
/// the connected peer.
public protocol PeerConnectionDelegate: class {
/// Called when a connection is successfully established with the remote peer.
/// peerVersion is the version message received from the peer during the version handshake.
func peerConnection(peerConnection: PeerConnection,
didConnectWithPeerVersion peerVersion: VersionMessage)
/// Called when the connection to the remote peer is closed for any reason.
/// If the connection was closed due to an error, then error will be non-nil.
func peerConnection(peerConnection: PeerConnection, didDisconnectWithError error: NSError?)
/// Called when a message is received. Switch on message to handle the actual message.
func peerConnection(peerConnection: PeerConnection,
didReceiveMessage message: PeerConnectionMessage)
}
public enum PeerConnectionMessage {
case PeerAddressMessage(BitcoinSwift.PeerAddressMessage)
case InventoryMessage(BitcoinSwift.InventoryMessage)
case GetDataMessage(BitcoinSwift.GetDataMessage)
case NotFoundMessage(BitcoinSwift.NotFoundMessage)
case GetBlocksMessage(BitcoinSwift.GetBlocksMessage)
case GetHeadersMessage(BitcoinSwift.GetHeadersMessage)
case Transaction(BitcoinSwift.Transaction)
case Block(BitcoinSwift.Block)
case HeadersMessage(BitcoinSwift.HeadersMessage)
case GetPeerAddressMessage(BitcoinSwift.GetPeerAddressMessage)
case MemPoolMessage(BitcoinSwift.MemPoolMessage)
case PingMessage(BitcoinSwift.PingMessage)
case PongMessage(BitcoinSwift.PongMessage)
case RejectMessage(BitcoinSwift.RejectMessage)
case FilterLoadMessage(BitcoinSwift.FilterLoadMessage)
case FilterAddMessage(BitcoinSwift.FilterAddMessage)
case FilterClearMessage(BitcoinSwift.FilterClearMessage)
case FilteredBlock(BitcoinSwift.FilteredBlock)
case AlertMessage(BitcoinSwift.AlertMessage)
}
/// A PeerConnection handles the low-level socket connection to a peer and serializing/deserializing
/// messages to/from the Bitcoin p2p wire format.
///
/// Use PeerConnection to send messages and receive notifications when new messages are received.
/// For higher-level peer state management, such as downloading the blockchain, managing bloom
/// filters, etc, use the PeerController class.
///
/// All message sending, receiving, and serialization is done on a dedicated background thread.
/// By default, delegate methods are dispatched on the main queue. A different queue may be used by
/// passing a delegateQueue to the constructor.
public class PeerConnection: NSObject, NSStreamDelegate, MessageParserDelegate {
public enum Status { case NotConnected, Connecting, Connected, Disconnecting }
/// The current status of the connection.
public var status: Status { return _status }
private var _status: Status = .NotConnected
public weak var delegate: PeerConnectionDelegate?
private var delegateQueue: NSOperationQueue
private let peerHostname: String?
private let peerPort: UInt16
private let network: NetworkMagicNumber
// Parses raw data received off the wire into Message objects.
private let messageParser: MessageParser
// Streams used to read and write data from the connected peer.
private var inputStream: NSInputStream!
private var outputStream: NSOutputStream!
// Messages that are queued to be sent to the connected peer.
private var messageSendQueue: [Message] = []
// Sometimes we aren't able to send the whole message because the buffer is full. When that
// happens, we must stash the remaining bytes and try again when we receive a
// NSStreamEvent.HasBytesAvailable event from the outputStream.
private var pendingSendBytes: [UInt8] = []
private var readBuffer = [UInt8](count: 1024, repeatedValue: 0)
private let networkThread = Thread()
private var connectionTimeoutTimer: NSTimer? = nil
// The version message received by the peer in response to our version message.
private var peerVersion: VersionMessage? = nil
// Indicates if the peer has ack'd our version message yet.
private var receivedVersionAck = false
public init(hostname: String,
port: UInt16,
network: NetworkMagicNumber,
delegate: PeerConnectionDelegate? = nil,
delegateQueue: NSOperationQueue = NSOperationQueue.mainQueue()) {
self.delegate = delegate
self.peerHostname = hostname
self.peerPort = port
self.network = network
self.delegateQueue = delegateQueue
self.messageParser = MessageParser(network: network)
super.init()
self.messageParser.delegate = self
}
/// Attempts to open a connection to the remote peer.
/// Once the socket is successfully opened, versionMessage is sent to the remote peer.
/// The connection is considered "open" after the peer responds to the versionMessage with its
/// own VersionMessage and a VersionAck confirming it is compatible.
public func connectWithVersionMessage(versionMessage: VersionMessage,
timeout: NSTimeInterval = 5) {
precondition(status == .NotConnected)
precondition(!networkThread.executing)
precondition(!receivedVersionAck)
precondition(connectionTimeoutTimer == nil)
setStatus(.Connecting)
Logger.info("Attempting to connect to peer \(peerHostname!):\(peerPort)")
connectionTimeoutTimer =
NSTimer.scheduledTimerWithTimeInterval(timeout,
target: self,
selector: "connectionTimerDidTimeout:",
userInfo: nil,
repeats: false)
networkThread.startWithCompletion {
self.networkThread.addOperationWithBlock {
if let (inputStream, outputStream) =
self.streamsToPeerWithHostname(self.peerHostname!, port: self.peerPort) {
self.inputStream = inputStream
self.outputStream = outputStream
self.inputStream.delegate = self
self.outputStream.delegate = self
self.inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(),
forMode: NSDefaultRunLoopMode)
self.outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(),
forMode: NSDefaultRunLoopMode)
self.inputStream.open()
self.outputStream.open()
self.sendMessageWithPayload(versionMessage)
}
}
}
}
/// Closes the connection with the remote peer. Should only be called if status is .Connected.
public func disconnect() {
disconnectWithError(nil)
}
/// Queues the provided message to be sent to the connected peer.
/// If status is not yet Connected, the message will be queued and sent once the connection is
/// established.
/// This method is thread-safe. It can be called from any thread. Messages are sent on a
/// dedicated background thread.
public func sendMessageWithPayload(payload: MessagePayload) {
let message = Message(network: network, payload: payload)
networkThread.addOperationWithBlock {
self.messageSendQueue.append(message)
self.send()
}
}
// MARK: - NSStreamDelegate
public func stream(stream: NSStream, handleEvent event: NSStreamEvent) {
precondition(NSThread.currentThread() == networkThread)
switch event {
case NSStreamEvent.None:
break
case NSStreamEvent.OpenCompleted:
break
case NSStreamEvent.HasBytesAvailable:
self.receive()
case NSStreamEvent.HasSpaceAvailable:
self.send()
case NSStreamEvent.ErrorOccurred:
disconnectWithError(errorWithCode(.StreamError))
case NSStreamEvent.EndEncountered:
disconnectWithError(errorWithCode(.StreamEndEncountered))
default:
Logger.error("Invalid NSStreamEvent \(event)")
assert(false, "Invalid NSStreamEvent")
}
}
// MARK: - MessageParserDelegate
// Parses the payload from payloadData given the provided header, and notifies the delegate if
// parsing was successful. For some message types (e.g. VersionAck), payloadData is expected to
// have a length of 0.
public func didParseMessage(message: Message) {
Logger.debug("Received \(message.header.command.rawValue) message")
let payloadStream = NSInputStream(data: message.payload)
payloadStream.open()
switch message.header.command {
case .Version:
if peerVersion != nil {
Logger.warn("Received extraneous VersionMessage. Ignoring")
break
}
assert(status == .Connecting)
let versionMessage = VersionMessage.fromBitcoinStream(payloadStream)
if versionMessage == nil {
disconnectWithError(errorWithCode(.Unknown))
break
}
if !isPeerVersionSupported(versionMessage!) {
disconnectWithError(errorWithCode(.UnsupportedPeerVersion))
break
}
peerVersion = versionMessage!
sendVersionAck()
if receivedVersionAck {
didConnect()
}
case .VersionAck:
if status != .Connecting {
// The connection might have been cancelled, or it might have failed. For example,
// the connection can fail if we received an invalid VersionMessage from the peer.
Logger.warn("Ignoring VersionAck message because not in Connecting state")
break
}
receivedVersionAck = true
if peerVersion != nil {
didConnect()
}
case .Address:
if let peerAddressMessage = PeerAddressMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.PeerAddressMessage(peerAddressMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .Inventory:
if let inventoryMessage = InventoryMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.InventoryMessage(inventoryMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .GetData:
if let getDataMessage = GetDataMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.GetDataMessage(getDataMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .NotFound:
if let notFoundMessage = NotFoundMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.NotFoundMessage(notFoundMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .GetBlocks:
if let getBlocksMessage = GetBlocksMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.GetBlocksMessage(getBlocksMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .GetHeaders:
if let getHeadersMessage = GetHeadersMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.GetHeadersMessage(getHeadersMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .Transaction:
if let transaction = Transaction.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.Transaction(transaction)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .Block:
if let block = Block.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.Block(block)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .Headers:
if let headersMessage = HeadersMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.HeadersMessage(headersMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .GetAddress:
if let getPeerAddressMessage = GetPeerAddressMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.GetPeerAddressMessage(getPeerAddressMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .MemPool:
if let memPoolMessage = MemPoolMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.MemPoolMessage(memPoolMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .Ping:
if let pingMessage = PingMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.PingMessage(pingMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .Pong:
if let pongMessage = PongMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.PongMessage(pongMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .Reject:
if let rejectMessage = RejectMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.RejectMessage(rejectMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .FilterLoad:
if let filterLoadMessage = FilterLoadMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.FilterLoadMessage(filterLoadMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .FilterAdd:
if let filterAddMessage = FilterAddMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.FilterAddMessage(filterAddMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .FilterClear:
if let filterClearMessage = FilterClearMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.FilterClearMessage(filterClearMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .FilteredBlock:
if let filteredBlock = FilteredBlock.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.FilteredBlock(filteredBlock)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
case .Alert:
if let alertMessage = AlertMessage.fromBitcoinStream(payloadStream) {
self.delegateQueue.addOperationWithBlock {
let message = PeerConnectionMessage.AlertMessage(alertMessage)
self.delegate?.peerConnection(self, didReceiveMessage: message)
}
}
}
payloadStream.close()
}
// MARK: - Private Methods
// Exposed for testing. Override this method to mock out the streams.
// Initializes the socket connection and returns an NSInputStream and NSOutputStream for
// sending and receiving raw data.
public func streamsToPeerWithHostname(hostname: String, port: UInt16) ->
(inputStream: NSInputStream, outputStream: NSOutputStream)? {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(nil,
hostname as NSString,
UInt32(port),
&readStream,
&writeStream);
if readStream == nil || writeStream == nil {
Logger.info("Connection failed to peer \(self.peerHostname!):\(self.peerPort)")
self.setStatus(.NotConnected)
return nil
}
return (readStream!.takeUnretainedValue(), writeStream!.takeUnretainedValue())
}
// Dequeues a message from the messageSendQueue and tries to send it. This should be called
// whenever a new message is added to messageSendQueue, or while there are still bytes left
// to send in pendingSendBytes.
private func send() {
precondition(NSThread.currentThread() == networkThread)
if let outputStream = outputStream {
sendWithStream(outputStream)
}
}
// Helper method for send(). Do not call directly.
private func sendWithStream(outputStream: NSOutputStream) {
if !outputStream.hasSpaceAvailable {
return
}
if messageSendQueue.count > 0 && pendingSendBytes.count == 0 {
let message = messageSendQueue.removeAtIndex(0)
Logger.debug("Sending \(message.header.command.rawValue) message")
pendingSendBytes += message.bitcoinData.UInt8Array
}
if pendingSendBytes.count > 0 {
let bytesWritten = outputStream.write(pendingSendBytes, maxLength: pendingSendBytes.count)
if bytesWritten > 0 {
pendingSendBytes.removeRange(0..<bytesWritten)
}
if messageSendQueue.count > 0 || pendingSendBytes.count > 0 {
networkThread.addOperationWithBlock {
self.send()
}
}
}
}
// Reads from the inputStream until it no longer has bytes available and parses as much as it can.
// This should be called whenever inputStream has new bytes available.
// Notifies the delegate for messages that are parsed.
private func receive() {
precondition(NSThread.currentThread() == networkThread)
if let inputStream = inputStream {
receiveWithStream(inputStream)
}
}
// Helper method for receive(). Do not call directly.
private func receiveWithStream(inputStream: NSInputStream) {
if !inputStream.hasBytesAvailable {
return
}
let bytesRead = inputStream.read(&readBuffer, maxLength: readBuffer.count)
if bytesRead > 0 {
messageParser.parseBytes([UInt8](readBuffer[0..<bytesRead]))
if inputStream.hasBytesAvailable {
networkThread.addOperationWithBlock {
self.receive()
}
}
}
}
private func disconnectWithError(error: NSError?) {
if status == .Disconnecting || status == .NotConnected {
return
}
if let error = error {
Logger.warn("Socket error \(error)")
}
setStatus(.Disconnecting)
connectionTimeoutTimer?.invalidate()
connectionTimeoutTimer = nil
networkThread.addOperationWithBlock {
self.inputStream?.close()
self.outputStream?.close()
self.inputStream?.removeFromRunLoop(NSRunLoop.currentRunLoop(),
forMode: NSDefaultRunLoopMode)
self.outputStream?.removeFromRunLoop(NSRunLoop.currentRunLoop(),
forMode: NSDefaultRunLoopMode)
self.peerVersion = nil
self.receivedVersionAck = false
self.setStatus(.NotConnected)
self.delegateQueue.addOperationWithBlock {
// For some reason, using self.delegate? within a block doesn't compile... Xcode bug?
if let delegate = self.delegate {
delegate.peerConnection(self, didDisconnectWithError: error)
}
}
self.networkThread.cancel()
}
}
private func didConnect() {
precondition(status == .Connecting)
precondition(self.peerVersion != nil)
precondition(receivedVersionAck)
Logger.info("Connected to peer \(peerHostname!):\(peerPort)")
connectionTimeoutTimer?.invalidate()
connectionTimeoutTimer = nil
setStatus(.Connected)
let peerVersion = self.peerVersion!
self.delegateQueue.addOperationWithBlock {
// For some reason, using self.delegate? within a block doesn't compile... Xcode bug?
if let delegate = self.delegate {
delegate.peerConnection(self, didConnectWithPeerVersion: peerVersion)
}
}
}
private func sendVersionAck() {
sendMessageWithPayload(VersionAckMessage())
}
private func errorWithCode(code: ErrorCode) -> NSError {
return NSError(domain: ErrorDomain, code: code.rawValue, userInfo: nil)
}
private func isPeerVersionSupported(versionMessage: VersionMessage) -> Bool {
// TODO: Make this a real check.
return true
}
private func setStatus(newStatus: Status) {
_status = newStatus
}
func connectionTimerDidTimeout(timer: NSTimer) {
connectionTimeoutTimer?.invalidate()
connectionTimeoutTimer = nil
if status == .Connecting {
disconnectWithError(errorWithCode(.ConnectionTimeout))
}
}
}
extension PeerConnection {
public var ErrorDomain: String { return "BitcoinSwift.PeerConnection" }
public enum ErrorCode: Int {
case Unknown = 0,
ConnectionTimeout,
UnsupportedPeerVersion,
StreamError,
StreamEndEncountered
}
}
|
apache-2.0
|
fb27758c1a04e7d8860d91d1b848a148
| 40.147114 | 100 | 0.689672 | 5.33076 | false | false | false | false |
iqingchen/DouYuZhiBo
|
DY/DY/Classes/Main/Controller/BaseViewController.swift
|
1
|
1425
|
//
// BaseViewController.swift
// DY
//
// Created by zhang on 16/12/6.
// Copyright © 2016年 zhang. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
var contentView : UIView?
fileprivate lazy var animImageView : UIImageView = {[unowned self] in
let animImageV = UIImageView(image: UIImage(named: "img_loading_1"))
animImageV.center = self.view.center
animImageV.animationImages = [UIImage(named: "img_loading_1")!, UIImage(named: "img_loading_2")!]
animImageV.animationDuration = 0.5
animImageV.animationRepeatCount = LONG_MAX
animImageV.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin]
return animImageV
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
//MARK: - 设置UI
extension BaseViewController {
func setupUI() {
contentView?.isHidden = true
//添加加载动画
view.addSubview(animImageView)
//执行动画
animImageView.startAnimating()
//背景颜色
view.backgroundColor = UIColor(r: 250, g: 250, b: 250)
}
func loadDataFinished() {
// 1.停止动画
animImageView.stopAnimating()
// 2.隐藏animImageView
animImageView.isHidden = true
// 3.显示内容的View
contentView?.isHidden = false
}
}
|
mit
|
ea764f490f5aba3465139a4ac2c03751
| 25.307692 | 105 | 0.622807 | 4.412903 | false | false | false | false |
tristanhimmelman/HidingNavigationBar
|
HidingNavigationBarSample/HidingNavigationBarSample/MasterViewController.swift
|
1
|
3604
|
//
// MasterViewController.swift
// HidingNavigationBarSample
//
// Created by Tristan Himmelman on 2015-05-01.
// Copyright (c) 2015 Tristan Himmelman. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
let rows = ["Hiding Nav Bar", "Hiding Nav Bar + Extension View", "Hiding Nav Bar + Toolbar", "Hiding Nav Bar + TabBar", "Hidden Shows NavBar + InteractivePopGestureRecognizer"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let navController = navigationController {
styleNavigationController(navController)
}
}
func styleNavigationController(_ navigationController: UINavigationController){
navigationController.navigationBar.isTranslucent = true
navigationController.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
navigationController.navigationBar.tintColor = UIColor.white
navigationController.navigationBar.barTintColor = UIColor(red: 41/255, green: 141/255, blue: 250/255, alpha: 1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rows.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.font = UIFont.systemFont(ofSize: 16)
cell.textLabel?.text = rows[(indexPath as NSIndexPath).row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if (indexPath as NSIndexPath).row == 0 {
let controller = HidingNavViewController()
navigationController?.pushViewController(controller, animated: true)
} else if (indexPath as NSIndexPath).row == 1 {
let controller = HidingNavExtensionViewController()
navigationController?.pushViewController(controller, animated: true)
} else if (indexPath as NSIndexPath).row == 2 {
let controller = HidingNavToolbarViewController()
navigationController?.pushViewController(controller, animated: true)
} else if (indexPath as NSIndexPath).row == 3 {
let controller1 = HidingNavTabViewController()
let navController1 = UINavigationController(rootViewController: controller1)
navController1.tabBarItem = UITabBarItem(tabBarSystemItem: .mostRecent, tag: 0)
styleNavigationController(navController1)
let controller2 = HidingNavTabViewController()
let navController2 = UINavigationController(rootViewController: controller2)
navController2.tabBarItem = UITabBarItem(tabBarSystemItem: .favorites, tag: 1)
styleNavigationController(navController2)
let tabBarController = UITabBarController()
tabBarController.viewControllers = [navController1, navController2]
navigationController?.present(tabBarController, animated: true, completion: nil)
} else {
let controller = HiddenNavViewController()
let navController = UINavigationController(rootViewController: controller)
navController.interactivePopGestureRecognizer?.delegate = InteractivePopGestureRecognizerDelegate()
styleNavigationController(navController)
navigationController?.present(navController, animated: true, completion: nil)
}
}
}
|
mit
|
f37cf6f3a308c796d64466411dc5fd8a
| 38.604396 | 177 | 0.776082 | 4.87027 | false | false | false | false |
BackNotGod/localizationCommand
|
Sources/commandService/commandTool.swift
|
1
|
7589
|
//
// commandProtocol.swift
// localizationCommand
//
// Created by BackNotGod on 2017/3/14.
//
//
import Foundation
import PathKit
import Progress
protocol StringsSearcher {
func search(in content: String)
}
protocol RegexStringsSearcher: StringsSearcher {
var patterns: [String] { get }
}
extension RegexStringsSearcher {
func search(in path: Path) {
for pattern in patterns {
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
print("Failed to create regular expression: \(pattern)".red)
continue
}
let content = parsePathToContent(with: path)
let matches = regex.matches(in: content, options: [], range: content.fullRange)
var extracts : [Values] = []
var errors : [Values] = []
for checkingResult in matches {
let range = checkingResult.rangeAt(0)
let extracted = NSString(string: content).substring(with: range)
guard let strRegex = try? NSRegularExpression(pattern: LOCAL_ERGEX, options: []) else {
print("Failed to create regular expression: \(pattern)".red)
continue
}
let strMatches = strRegex.matches(in: extracted, options: [], range: extracted.fullRange)
let localizedString = NSString(string: extracted).substring(with: strMatches[0].rangeAt(0))
if localizedString.characters.count == 0 {
continue
}
var commont = ""
if strMatches.count > 1 {
commont = NSString(string: extracted).substring(with: strMatches[1].rangeAt(0))
}
let value = Values.init(value: localizedString, comment: "\(commont)")
value.appendClassComent(className: path.lastComponentWithoutExtension, comStr: commont)
guard duplicateRemoval(path: path, value: value,className:path.lastComponentWithoutExtension) else {continue}
let judge = !extracts.contains{isSameValues($0, value2: value)}
guard judge else {continue}
/// over here, if localizedString is isAmbiguous,we analysis error
if localizedString.isAmbiguous {
errors.append(value)
}else{
extracts.append(value)
}
}
if extracts.count > 0 {
if path.lastComponent.contains("swift") {
DataHandleManager.defaltManager.swift_listNode?.insert(values: extracts, className: path.lastComponent, path: path.description)
}else{
DataHandleManager.defaltManager.oc_listNode?.insert(values: extracts, className: path.lastComponent, path: path.description)
}
}
if errors.count > 0 {
DataHandleManager.defaltManager.error_listNode?.insert(values: errors, className: path.lastComponent, path: path.description)
}
}
}
}
/**
Duplicate removal
- parameter value
- returns: if there is no same value return true
*/
func duplicateRemoval(path:Path,value:Values,className:String) -> Bool{
if path.lastComponent.contains("swift") {
return searchSame(link: DataHandleManager.defaltManager.swift_listNode!.head, value: value,className: className)
}
return searchSame(link: DataHandleManager.defaltManager.oc_listNode!.head, value: value,className:className)
}
// if there is no same value return true
func searchSame(link:linkNode?,value:Values,className:String) -> Bool{
guard let _link = link else {return true}
let judge = _link.values.contains{isSameValues($0, value2:value)}
if judge {
_link.values.forEach({ (v) in
if isSameValues(v, value2: value){
v.appendClassComent(className: className, comStr: v.comment)
}
})
return false
}
return searchSame(link: _link.next, value: value,className: className)
}
protocol RegexStringsWriter : StringsSearcher{
func writeToLocalizable (to path:Path)
}
extension RegexStringsWriter {
func writeToLocalizable (to path:Path) {
var content = !writeAppend ? "" : {
return try? path.read(.utf16)
}() ?? ""
let contentArr = contentRegex(content: content)
content += "//-------------------swfit-------------------"
let swift = DataHandleManager.defaltManager.swift_listNode?.head
DataHandleManager.defaltManager.outPutLinkNode(root: swift, action: { valuesOptial in
if let values = valuesOptial {
for value in values {
if !contentArr.contains(value.localizedString){
content += "\n\(value.outPutStr)\n\(value.localizedString) = \(value.localizedString);\n"
}
}
}
})
content += "\n//\(NSDate())\n"
content += "//-------------------objc-------------------"
let objc = DataHandleManager.defaltManager.oc_listNode?.head
DataHandleManager.defaltManager.outPutLinkNode(root: objc, action: { valuesOptial in
if let values = valuesOptial {
for value in values {
if !contentArr.contains(value.localizedString){
content += "\n\(value.outPutStr)\n\(value.localizedString) = \(value.localizedString);\n"
}
}
}
})
content += "\n//\(NSDate())\n"
try? path.write(content, encoding: .utf16)
}
}
func contentRegex(content:String)->[String]{
guard let regex = try? NSRegularExpression(pattern: "\".+?\"", options: []) else {
print("Failed to create regular expression.".red)
return []
}
let matches = regex.matches(in: content, options: [], range: content.fullRange)
return matches.map{NSString(string: content).substring(with: $0.rangeAt(0))}
}
func findAllLocalizable(with path:Path,excluded:[Path]) -> [Path]{
if !path.exists {
print("path is not exists!".yellow)
return []
}
if !path.isWritable {
print("path is not writable!".yellow)
return []
}
let optonalPaths = try? path.recursiveChildren()
guard let paths = optonalPaths else {return []}
var results : [Path] = []
for itemPath in Progress(pathsFilter(paths: paths, except: excluded)){
let strings = itemPath.glob("*.strings")
if strings.count > 0 {
results = results + strings
}
}
return results
}
func pathsFilter(paths:[Path],except:[Path])->[Path]{
if paths.count == 0 {
print("error: the vailable path is covered by your except path.".red)
exit(EX_USAGE)
}
if except.count == 0 {
return paths
}
var excepts = except
excepts.removeLast()
return pathsFilter(paths: paths.filter{!$0.description.contains(except.last!.description)}, except: excepts)
}
func parsePathToContent(with path:Path)->String{
return (try? path.read()) ?? "read error , this path may be empty."
}
|
mit
|
c3f4fecb8362ff724ffaa0f5b9d217cb
| 32.728889 | 147 | 0.5674 | 4.652974 | false | false | false | false |
LYM-mg/DemoTest
|
其他功能/SwiftyDemo/SwiftyDemo/MessageNetwork.swift
|
1
|
27379
|
//
// MessageNetwork.swift
// message
//
// Created by jiali on 2019/7/22.
// Copyright © 2019 italki. All rights reserved.
//
import UIKit
enum VersionPrefix: String {
case v2
case v3
}
// MARK: - 请求工具类
class MessageNetWork <T: Decodable>: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate, URLSessionDownloadDelegate {
var type = ApiType.api
var method: SYSHTTPMethod = .post
var parameters: [String: Any] = [:]
var versionPerfix = VersionPrefix.v2
//上传进度回调
var onProgress: ((Float) -> Void)?
var downLoadProgress: ((Float) -> Void)?
var completionHandlerBlock: ((URL?, Error?) -> Void)?
var completionSuccessBlock: ((_ result: T?, _ response: [String: Any]?, _ error: Error?) -> Swift.Void)?
var completionFailureBlock: ((_ error: Error?) -> Swift.Void)?
var tempPath: String?
fileprivate var requestCacheArr = [String: URLSessionDataTask]()
private var dataForUpData: Data = Data()
private var urlString: String = ""
private var contentType = "application/x-www-form-urlencoded; charset=utf-8"
weak var dataTask: URLSessionDataTask?
weak var session: URLSession?
var downLoadedPath: String? = ""
var downLoadingPath: String? = ""
weak var downLoadTask: URLSessionDownloadTask?
var outputStream: OutputStream?
var tmpSize: Int64 = 0
var totalSize: Int64 = 0
convenience init(wholePath: String, method: SYSHTTPMethod, parameters: [String: Any], versionPerfix: VersionPrefix, type: ApiType) {
self.init()
self.method = method
self.parameters = parameters
self.type = type
self.versionPerfix = versionPerfix
urlString = getComponentsPath(path: wholePath)
}
var baseUrl: String {
return ITChatRommModel.shared.host
}
lazy var jsonDecoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .iso8601
return decoder
}()
private var defaultHeaders: [String: String] {
return [
"X-Device": "23",
"X-Token": iToken,
"X-InstallSource": "appstore",
"User-Agent": "italki/\(appVersion);\(appId);\(osVersion);Apple;\(deviceVersion);iOS",
"X-Browser-Key": browserId]
}
private func getComponentsPath(path: String) -> String {
var urlStr = ""
if path.hasPrefix("https://") {
urlStr = "\(versionPerfix.rawValue)" + path
} else {
urlStr = "\(baseUrl)/\(versionPerfix.rawValue)/\(path)"
}
return urlStr
}
// 普通请求
func request(
path: String,
method: SYSHTTPMethod,
versionPerfix: VersionPrefix = .v2,
parameters: [String: Any],
encoding: MYURLEncoding? = nil) -> MessageNetWork {
return MessageNetWork(wholePath: path, method: method, parameters: parameters, versionPerfix: versionPerfix, type: .api)
}
lazy var appVersion: String = {
if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
return version
}
return ""
}()
var iToken: String {
return ITChatRommModel.shared.token ?? ""
}
lazy var appName: String = {
if let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
return appName
}
return "unknown"
}()
lazy var appId: String = {
return Bundle.main.bundleIdentifier ?? "unknown"
}()
lazy var osVersion: String = {
return "\(UIDevice.current.systemName)\(UIDevice.current.systemVersion)"
}()
lazy var browserId: String = {
if let id = UserDefaults.standard.string(forKey: "X-Browser-Key") {
return id
} else {
let id = UUID.init().uuidString
UserDefaults.standard.set(id, forKey: "X-Browser-Key")
return id
}
}()
lazy var deviceVersion: String = {
return UIDevice.current.model
}()
// 上传请求
func uploadRequest(
path: String,
data: Data,
contentType: String,
method: SYSHTTPMethod,
versionPerfix: VersionPrefix = .v2,
parameters: [String: Any]) -> MessageNetWork {
let urlStr = getComponentsPath(path: path)
let request = MessageNetWork(wholePath: urlStr, method: method, parameters: parameters, versionPerfix: versionPerfix, type: .upData)
request.dataForUpData = data
request.contentType = contentType
return request
}
//请求成功时需要调用的代码封装为一个嵌套的方法,以便复用
//同理请求失败需要执行的代码
// MARK: - 外部控制器的方法
/**
通用请求方法
- parameter succeed: 请求成功回调
- parameter failure: 请求失败回调
- parameter error: 错误信息
*/
func perform(progress: ((_ pregressValue: Float) -> Swift.Void)?, _ successBlock: ((_ result: T?, _ response: [String: Any]?, _ error: Error?) -> Swift.Void)?, _ failureBlock: ((_ error: Error?) -> Swift.Void)?) {
//HTTP头部需要传入的信息,如果没有可以省略 headers:
// 1.生成session
onProgress = progress
completionSuccessBlock = successBlock
completionFailureBlock = failureBlock
guard let trueURL = URL(string: urlString) else {return}
var request = URLRequest(url: trueURL, method: method, headers: defaultHeaders)
if type == .upData { // 上传
request = getUpdataRequest(url: trueURL)
let mData = getUpdataDate()
let task = uploadTask(request: request, mData: mData)
requestCacheArr[urlString] = task
task.resume()
self.dataTask = task
return
}
// 普通请求
//构造请求体
if method == .post {
var s = ""
for (key, value) in parameters {
s = "\(s)&\(key)=\(value)"
}
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
request.httpBody = s.data(using: .utf8)
} else if method == .get {
var compinents = URLComponents(string: urlString)
var items = [URLQueryItem]()
for (key, value) in parameters {
items.append(URLQueryItem(name: key, value: "\(value)"))
}
items = items.filter {!$0.name.isEmpty}
if !items.isEmpty {
compinents?.queryItems = items
}
guard let getUrl = compinents?.url else { return }
request = URLRequest(url: getUrl, method: method, headers: defaultHeaders)
}
// 3.生成一个dataTask
let dataTask = dateTack(request: request)
// 5.开始请求
requestCacheArr[urlString] = dataTask
dataTask.resume()
self.dataTask = dataTask
}
// MARK: - 上传相关
// 构造请求体
let boundary = "italkiitalkiitalki"
private func getPart(key: String, value: Any, isString: Bool) -> Data {
var muData = Data()
var data: Data = Data()
let s = "\(value)"
if value is String {
data = s.data(using: .utf8)!
} else if value is Data {
data = value as! Data
} else if value is Int || value is Float || value is Double {
var value: Int = value as? Int ?? 0
data = NSData(bytes: &value, length: 4) as Data
} else if value is UIImage {
data = (value as! UIImage).jpegData(compressionQuality: 1.0) ?? Data()
}
let part = "--\(boundary)\r\nContent-Disposition: form-data; name=\"\(key)\"\r\n"
muData.append(part.data(using: .utf8)!)
muData.append("\r\n".data(using: .utf8)!)
muData.append(data)
muData.append("\r\n".data(using: .utf8)!)
return muData
}
//上传代理方法,监听上传进度
func urlSession(_ session: URLSession, task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64) {
//获取进度
let written = (Float)(totalBytesSent)
let total = (Float)(totalBytesExpectedToSend)
let pro = written/total
if let onProgress = onProgress {
onProgress(pro)
}
}
//上传代理方法,传输完毕后服务端返回结果
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
// let str = String(data: data, encoding: String.Encoding.utf8)
// debugprint("服务端返回结果:\(str)")
var buffer = [UInt8](repeating: 0, count: data.count)
data.copyBytes(to: &buffer, count: data.count)
self.outputStream?.write(buffer, maxLength: data.count)
}
//上传代理方法,上传结束
func urlSession(_ session: URLSession, task: URLSessionTask,
didCompleteWithError error: Error?) {
if error == nil {
// 不一定是成功
// 数据是肯定可以请求完毕
// 判断, 本地缓存 == 文件总大小 {filename: filesize: md5:xxx}
// 如果等于 => 验证, 是否文件完整(file md5 )
} else {
if let completionHandler = completionHandlerBlock {
completionHandler(nil, error)
}
}
// self.outputStream?.close()
}
private func responseDecodableObject(session: URLSession, data: Data?, response: URLResponse?, error: Error?) {
for tempTask in self.requestCacheArr.values {
if tempTask == self.requestCacheArr[self.urlString] {
self.requestCacheArr.removeValue(forKey: self.urlString)
}
}
session.finishTasksAndInvalidate()
// 4.下面是回调部分,需要手动切换线程
DispatchQueue.main.async {
// 5.下面的几种情况参照了responseJSON方法的实现
guard error == nil else {
if let completionFailureBlock = self.completionFailureBlock {
completionFailureBlock(error)
}
return
}
guard let validData = data, validData.count > 0 else {
if let completionFailureBlock = self.completionFailureBlock {
completionFailureBlock(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
}
return
}
if let response = response as? HTTPURLResponse {
if self.versionPerfix == .v3 {
self.responseV3DecodableObject(response: response, data: validData)
} else {
self.responseV2DecodableObject(response: response, data: validData)
}
} else { // 其他,
if let completionFailureBlock = self.completionFailureBlock {
completionFailureBlock(error)
}
}
}
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
let resp = response as? HTTPURLResponse
let string = resp?.allHeaderFields["Content-Length"] as? String
let stri = string?.components(separatedBy: "/").last
self.totalSize = Int64(stri ?? "") ?? 0
// 比对本地大小, 和 总大小
if self.tmpSize == self.totalSize {
// 1. 移动到下载完成文件夹
// DiskCacheManager.moveFile(self.downLoadingPath!, self.downLoadedPath!)
// 2. 取消本次请求
completionHandler(URLSession.ResponseDisposition.cancel)
return
}
if self.tmpSize > self.totalSize {
// 1. 删除临时缓存
// DiskCacheManager.deleteFile(self.downLoadingPath!)
// 2. 从0 开始下载
// 3. 取消请求
completionHandler(URLSession.ResponseDisposition.cancel)
return
}
// 继续接受数据
// 确定开始下载数据
self.outputStream = OutputStream(toFileAtPath: self.downLoadingPath!, append: true)
self.outputStream?.open()
completionHandler(URLSession.ResponseDisposition.allow)
}
func cancelAllHttpRequest() {
for task in requestCacheArr.values {
task.cancel()
}
requestCacheArr.removeAll()
}
func downloadFile(tempPath: String, progress: ((_ pregressValue: Float) -> Swift.Void)?, completionHandler: ((URL?, Error?) -> Void)?) {
// 1.生成session
self.tempPath = tempPath
downLoadProgress = progress
completionHandlerBlock = completionHandler
// self.tmpSize = DiskCacheManager.fileSize(downLoadingPath ?? "")
guard let trueURL = URL(string: urlString) else {return}
var request = URLRequest(url: trueURL, method: method, headers: defaultHeaders)
// 普通请求
//构造请求体
var compinents = URLComponents(string: urlString)
var items = [URLQueryItem]()
for (key, value) in parameters {
items.append(URLQueryItem(name: key, value: "\(value)"))
}
items = items.filter {!$0.name.isEmpty}
if !items.isEmpty {
compinents?.queryItems?.append(contentsOf: items)
}
guard let getUrl = compinents?.url else { return }
request = URLRequest(url: getUrl, method: method, headers: defaultHeaders)
// 3.生成一个downloadTask
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
self.session = session
let dataTask = session.downloadTask(with: request)
// 5.开始请求
dataTask.resume()
self.downLoadTask = dataTask
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
//获取进度
let written = (Float)(totalBytesWritten)
let total = (Float)(totalBytesExpectedToWrite)
let pro = written/total
if let downLoadProgress = downLoadProgress {
downLoadProgress(pro)
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
if let completionHandler = completionHandlerBlock {
var tempError: Error?
do {
try FileManager.default.moveItem(atPath: location.path, toPath: tempPath ?? downloadTask.response?.suggestedFilename ?? "*.text")
} catch {
tempError = error
}
//完成任务,
session.finishTasksAndInvalidate()
//清空Session
self.session = nil
completionHandler(location, tempError)
}
}
}
extension MessageNetWork {
//暂停
// func pauseCurrentTask() {
// self.dataTask.suspend()
// }
// // 继续任务
// func resumeCurrentTask() {
// self.dataTask.resume()
// }
// 取消
func cancelCurrentTask() {
self.session?.invalidateAndCancel()
self.session = nil
}
func cancelDownLoadFile() {
downLoadTask?.cancel(byProducingResumeData: { [weak self] (_) in
self?.downLoadTask = nil
})
}
private func getUpdataRequest(url: URL) -> URLRequest {
var request = URLRequest(url: url, method: method, headers: defaultHeaders)
request.addValue("text/html", forHTTPHeaderField: "Accept")
request.addValue(" gzip;q=1.0, compress;q=0.5", forHTTPHeaderField: "Accept-Encoding")
request.addValue(" zh-Hans-Ch;q=1.0", forHTTPHeaderField: "Accept-Language")
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
return request
}
private func getUpdataDate() -> Data {
var mData = Data()
for (key, value) in parameters {
let data = getPart(key: key, value: value as AnyObject, isString: true)
mData.append(data)
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMddHHmmss"
formatter.locale = NSLocale(localeIdentifier: "en") as Locale
let str = formatter.string(from: Date())
let fileName = "\(str)" + "." + "\(dataForUpData.getImageFormat())"
let dataStr = "--\(boundary)\r\nContent-Disposition: form-data; name=file;filename=\"\(fileName)\"\r\nContent-Type: \(contentType)\r\n\r\n"
mData.append(dataStr.data(using: .utf8)!)
mData.append(dataForUpData)
let endStr = "\r\n--\(boundary)--\r\n"
mData.append(endStr.data(using: .utf8)!)
return mData
}
private func uploadTask(request: URLRequest, mData: Data) -> URLSessionDataTask {
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
self.session = session
let uploadTask = session.uploadTask(with: request, from: mData) {[weak self] (data, response, error) in
guard let `self` = self else { return }
self.responseDecodableObject(session: session, data: data, response: response, error: error)
}
return uploadTask
}
private func dateTack(request: URLRequest) -> URLSessionDataTask {
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
self.session = session
let dataTask = session.dataTask(with: request) {[weak self] (data, response, error) in
guard let `self` = self else { return }
self.responseDecodableObject(session: session, data: data, response: response, error: error)
}
return dataTask
}
func responseV2DecodableObject(response: HTTPURLResponse, data: Data) {
do {
guard let dict: [String: Any] = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: Any] else {
if let completionFailureBlock = self.completionFailureBlock {
completionFailureBlock(AFError.ResponseSerializationFailureReason.inputDataNil as? Error)
}
return
}
guard let successed = dict["success"] as? Int else {
if let completionFailureBlock = self.completionFailureBlock {
completionFailureBlock(AFError.ResponseSerializationFailureReason.inputDataNil as? Error)
}
return
}
if successed == 1 {
guard let dataObject = dict["data"] else {
if let completionFailureBlock = self.completionFailureBlock {
completionFailureBlock(AFError.ResponseSerializationFailureReason.inputDataNil as? Error)
}
return
}
let dataDict = try JSONSerialization.data(withJSONObject: dataObject, options: JSONSerialization.WritingOptions.prettyPrinted)
let object = try jsonDecoder.decode(T.self, from: dataDict)
if let completionSuccessBlock = self.completionSuccessBlock {
completionSuccessBlock(object, dict, nil)
}
} else {
reporterError(dict: dict)
}
} catch {
if let completionFailureBlock = self.completionFailureBlock {
completionFailureBlock(error)
}
}
}
func responseV3DecodableObject(response: HTTPURLResponse, data: Data) {
do {
if [200, 201, 204, 205, 304].contains(response.statusCode) {
if let dict = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: Any], dict["error"] != nil {
reporterError(dict: dict)
return
}
let object = try jsonDecoder.decode(T.self, from: data)
if let completionSuccessBlock = self.completionSuccessBlock {
completionSuccessBlock(object, nil, nil)
}
} else {
reporterError(dict: nil)
}
} catch {
if let completionFailureBlock = self.completionFailureBlock {
completionFailureBlock(error)
}
}
}
func reporterError(dict: [String: Any]?) {
guard let errorObject = dict?["error"] as? [String: Any] else {
if let completionFailureBlock = self.completionFailureBlock {
completionFailureBlock(AFError.ResponseSerializationFailureReason.inputDataNil as? Error)
}
return
}
let textCode = errorObject["text_code"] as? String
let textList = errorObject["text_list"] as? [String]
let err: Error = BaseError((errorObject["msg"] as? String) ?? "")
ITChatRommModel.shared.errorReporter?(getTranslation(textCode: textCode, textList: textList) ?? "error", nil)
if let completionFailureBlock = self.completionFailureBlock {
completionFailureBlock(err)
}
}
}
// MARK: - 请求枚举
enum SYSHTTPMethod: String {
case options = "OPTIONS"
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case trace = "TRACE"
case connect = "CONNECT"
}
enum ApiType: String {
case api // 普通接口类型
case upData
}
// MARK: - AFError
struct BaseError: Error {
var desc = ""
var localizedDescription: String {
return desc
}
init(_ desc: String) {
self.desc = desc
}
}
enum AFError: Error {
enum ParameterEncodingFailureReason {
case missingURL
case jsonEncodingFailed(error: Error)
case propertyListEncodingFailed(error: Error)
}
enum ResponseSerializationFailureReason {
case inputDataNil
case inputDataNilOrZeroLength
case inputFileNil
case inputFileReadFailed(at: URL)
case stringSerializationFailed(encoding: String.Encoding)
case jsonSerializationFailed(error: Error)
case propertyListSerializationFailed(error: Error)
}
case invalidURL(url: URL)
case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
case responseSerializationFailed(reason: ResponseSerializationFailureReason)
}
// MARK: - MYURLEncoding
struct MYURLEncoding {
typealias Parameters = [String: Any]
func escape(_ string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
}
func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: Any] {
for (nestedKey, value) in dictionary {
components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
}
} else if let array = value as? [Any] {
for value in array {
components += queryComponents(fromKey: "\(key)[]", value: value)
}
} else if let value = value as? NSNumber {
if value.isBool {
components.append((escape(key), escape((value.boolValue ? "1" : "0"))))
} else {
components.append((escape(key), escape("\(value)")))
}
} else if let bool = value as? Bool {
components.append((escape(key), escape((bool ? "1" : "0"))))
} else {
components.append((escape(key), escape("\(value)")))
}
return components
}
func query(_ parameters: [String: Any]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key]!
components += queryComponents(fromKey: key, value: value)
}
return components.map { "\($0)=\($1)" }.joined(separator: "&")
}
func encodesParametersInURL(with method: SYSHTTPMethod) -> Bool {
switch method {
case .get, .head, .delete:
return true
default:
return false
}
}
func encode(_ urlRequest: URLRequest, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = urlRequest
guard let parameters = parameters else { return urlRequest }
if let method = SYSHTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) {
guard let url = urlRequest.url else {
throw AFError.parameterEncodingFailed(reason: .missingURL)
}
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
urlComponents.percentEncodedQuery = percentEncodedQuery
urlRequest.url = urlComponents.url
}
} else {
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false)
}
return urlRequest
}
}
// MARK: - other
extension NSNumber {
fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) }
}
extension URLRequest {
init(url: URL, method: SYSHTTPMethod, headers: [String: String]? = nil) {
self.init(url: url, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 60)
self.httpMethod = method.rawValue
if let headers = headers {
for (headerField, headerValue) in headers {
setValue(headerValue, forHTTPHeaderField: headerField)
}
}
}
}
|
mit
|
238a9a8e8352f4cc19405233bac1072e
| 36.632768 | 218 | 0.596194 | 4.760407 | false | false | false | false |
cozkurt/coframework
|
COFramework/COFramework/Swift/Extentions/CKAsset+Additions.swift
|
1
|
773
|
//
// CKAsset+Additions.swift
// FuzFuz
//
// Created by Cenker Ozkurt on 10/21/19.
// Copyright © 2019 FuzFuz. All rights reserved.
//
import Foundation
import UIKit
import CloudKit
extension CKAsset {
public convenience init(image: UIImage, size: CGFloat, compression: CGFloat) {
let image = image.resizeWithScaleAspectFitMode(to: size, resizeFramework: .accelerate) ?? UIImage()
let fileURL = ImageHelper.saveToDisk(image: image, compression: compression)
self.init(fileURL: fileURL)
}
public var image: UIImage? {
guard let fileURL = fileURL, let data = try? Data(contentsOf: fileURL),
let image = UIImage(data: data) else {
return nil
}
return image
}
}
|
gpl-3.0
|
0c92746fcdbece6c9aa8c79d3b66637e
| 25.62069 | 107 | 0.642487 | 4.172973 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/CallRatingModalViewController.swift
|
1
|
6908
|
//
// CallRatingModalViewController.swift
// Telegram
//
// Created by keepcoder on 12/05/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import SwiftSignalKit
import Postbox
private enum CallRatingState {
case stars
}
private class CallRatingModalView: View {
let rating:View = View()
let textView = TextView()
var starsChangeHandler:((Int32?)->Void)? = nil
private(set) var stars:Int32? = nil
var state:CallRatingState = .stars {
didSet {
if oldValue != state {
updateState(state, animated: true)
}
}
}
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
var x:CGFloat = 0
for i in 0 ..< 5 {
let star = ImageButton()
star.set(image: #imageLiteral(resourceName: "Icon_CallStar").precomposed(theme.colors.accent), for: .Normal)
star.sizeToFit()
star.setFrameOrigin(x, 0)
rating.addSubview(star)
x += floorToScreenPixels(backingScaleFactor, star.frame.width) + 10
star.set(handler: { [weak self] current in
for j in 0 ... i {
(self?.rating.subviews[j] as? ImageButton)?.set(image: #imageLiteral(resourceName: "Icon_CallStar_Highlighted").precomposed(theme.colors.accent), for: .Normal)
}
for j in i + 1 ..< 5 {
(self?.rating.subviews[j] as? ImageButton)?.set(image: #imageLiteral(resourceName: "Icon_CallStar").precomposed(theme.colors.accent), for: .Normal)
}
self?.state = .stars
delay(0.15, closure: {
self?.starsChangeHandler?( Int32(i + 1) )
})
}, for: .Click)
}
rating.setFrameSize(x - 10, floorToScreenPixels(backingScaleFactor, rating.subviews[0].frame.height))
addSubview(rating)
addSubview(textView)
textView.isSelectable = false
textView.userInteractionEnabled = false
updateState(.stars)
let layout = TextViewLayout(.initialize(string: strings().callRatingModalText, color: theme.colors.text, font: .medium(.text)), alignment: .center)
layout.measure(width: frame.width - 60)
textView.update(layout)
needsLayout = true
}
override func layout() {
super.layout()
rating.centerX(y: frame.midY + 5)
textView.centerX(y: frame.midY - textView.frame.height - 5)
}
private func updateState(_ state:CallRatingState, animated: Bool = false) {
switch state {
case .stars:
rating.change(pos: focus(rating.frame.size).origin, animated: animated)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func makeRatingView(_ rating:Int) {
}
}
class CallRatingModalViewController: ModalViewController {
private let context:AccountContext
private let callId:CallId
private var starsCount:Int32? = nil
private let isVideo: Bool
private let userInitiated: Bool
init(_ context: AccountContext, callId:CallId, userInitiated: Bool, isVideo: Bool) {
self.context = context
self.callId = callId
self.isVideo = isVideo
self.userInitiated = userInitiated
super.init(frame: NSMakeRect(0, 0, 260, 100))
bar = .init(height: 0)
}
private var genericView:CallRatingModalView {
return view as! CallRatingModalView
}
override func viewClass() -> AnyClass {
return CallRatingModalView.self
}
override var modalInteractions: ModalInteractions? {
return ModalInteractions(acceptTitle: strings().callRatingModalNotNow, drawBorder: true, height: 50, singleButton: true)
}
override func becomeFirstResponder() -> Bool? {
return true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
genericView.starsChangeHandler = { [weak self] stars in
if let stars = stars {
self?.saveRating(Int(stars))
}
}
readyOnce()
}
private func saveRating(_ starsCount: Int) {
self.close()
if starsCount < 4, let window = self.window {
showModal(with: CallFeedbackController(context: context, callId: callId, starsCount: starsCount, userInitiated: userInitiated, isVideo: isVideo), for: window)
} else {
let _ = rateCallAndSendLogs(context: context, callId: self.callId, starsCount: starsCount, comment: "", userInitiated: userInitiated, includeLogs: false).start()
}
}
}
func rateCallAndSendLogs(context: AccountContext, callId: CallId, starsCount: Int, comment: String, userInitiated: Bool, includeLogs: Bool) -> Signal<Void, NoError> {
let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(4244000))
let rate = context.engine.calls.rateCall(callId: callId, starsCount: Int32(starsCount), comment: comment, userInitiated: userInitiated)
if includeLogs {
let id = arc4random64()
let name = "\(callId.id)_\(callId.accessHash).log.json"
let path = callLogsPath(account: context.account) + "/" + name
let file = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: id), partialReference: nil, resource: LocalFileReferenceMediaResource(localFilePath: path, randomId: id), previewRepresentations: [], videoThumbnails: [], immediateThumbnailData: nil, mimeType: "application/text", size: nil, attributes: [.FileName(fileName: name)])
let message = EnqueueMessage.message(text: comment, attributes: [], inlineStickers: [:], mediaReference: .standalone(media: file), replyToMessageId: nil, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: [])
return rate
|> then(enqueueMessages(account: context.account, peerId: peerId, messages: [message])
|> mapToSignal({ _ -> Signal<Void, NoError> in
return .single(Void())
}))
} else if !comment.isEmpty {
return rate
|> then(enqueueMessages(account: context.account, peerId: peerId, messages: [.message(text: comment, attributes: [], inlineStickers: [:], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: [])])
|> mapToSignal({ _ -> Signal<Void, NoError> in
return .single(Void())
}))
} else {
return rate
}
}
|
gpl-2.0
|
dd9e96d2d4c244d3af9586f668a09306
| 36.743169 | 361 | 0.622412 | 4.589369 | false | false | false | false |
mohitathwani/swift-corelibs-foundation
|
Foundation/NSAffineTransform.swift
|
1
|
14804
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
private let ε: CGFloat = CGFloat(2.22045e-16)
/**
AffineTransform represents an affine transformation matrix of the following form:
[ m11 m12 0 ]
[ m21 m22 0 ]
[ tX tY 1 ]
*/
public struct AffineTransform : ReferenceConvertible, Hashable, CustomStringConvertible {
public typealias ReferenceType = NSAffineTransform
public var m11: CGFloat
public var m12: CGFloat
public var m21: CGFloat
public var m22: CGFloat
public var tX: CGFloat
public var tY: CGFloat
public init() {
self.init(m11: CGFloat(), m12: CGFloat(), m21: CGFloat(), m22: CGFloat(), tX: CGFloat(), tY: CGFloat())
}
public init(m11: CGFloat, m12: CGFloat, m21: CGFloat, m22: CGFloat, tX: CGFloat, tY: CGFloat) {
(self.m11, self.m12, self.m21, self.m22) = (m11, m12, m21, m22)
(self.tX, self.tY) = (tX, tY)
}
private init(reference: NSAffineTransform) {
self = reference.transformStruct
}
private var reference : NSAffineTransform {
let ref = NSAffineTransform()
ref.transformStruct = self
return ref
}
/**
Creates an affine transformation matrix from translation values.
The matrix takes the following form:
[ 1 0 0 ]
[ 0 1 0 ]
[ x y 1 ]
*/
public init(translationByX x: CGFloat, byY y: CGFloat) {
self.init(m11: CGFloat(1.0), m12: CGFloat(0.0),
m21: CGFloat(0.0), m22: CGFloat(1.0),
tX: x, tY: y)
}
/**
Creates an affine transformation matrix from scaling values.
The matrix takes the following form:
[ x 0 0 ]
[ 0 y 0 ]
[ 0 0 1 ]
*/
public init(scaleByX x: CGFloat, byY y: CGFloat) {
self.init(m11: x, m12: CGFloat(0.0),
m21: CGFloat(0.0), m22: y,
tX: CGFloat(0.0), tY: CGFloat(0.0))
}
/**
Creates an affine transformation matrix from scaling a single value.
The matrix takes the following form:
[ f 0 0 ]
[ 0 f 0 ]
[ 0 0 1 ]
*/
public init(scale factor: CGFloat) {
self.init(scaleByX: factor, byY: factor)
}
/**
Creates an affine transformation matrix from rotation value (angle in radians).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
public init(rotationByRadians angle: CGFloat) {
let sine = sin(angle)
let cosine = cos(angle)
self.init(m11: cosine, m12: sine, m21: -sine, m22: cosine, tX: CGFloat(0.0), tY: CGFloat(0.0))
}
/**
Creates an affine transformation matrix from a rotation value (angle in degrees).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
public init(rotationByDegrees angle: CGFloat) {
let α = angle * .pi / 180.0
self.init(rotationByRadians: α)
}
/**
An identity affine transformation matrix
[ 1 0 0 ]
[ 0 1 0 ]
[ 0 0 1 ]
*/
public static let identity = AffineTransform(m11: CGFloat(1.0), m12: CGFloat(0.0), m21: CGFloat(0.0), m22: CGFloat(1.0), tX: CGFloat(0.0), tY: CGFloat(0.0))
// Translating
public mutating func translate(x: CGFloat, y: CGFloat) {
tX += m11 * x + m21 * y
tY += m12 * x + m22 * y
}
/**
Mutates an affine transformation matrix from a rotation value (angle α in degrees).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
public mutating func rotate(byDegrees angle: CGFloat) {
let α = angle * .pi / 180.0
return rotate(byRadians: α)
}
/**
Mutates an affine transformation matrix from a rotation value (angle α in radians).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
public mutating func rotate(byRadians angle: CGFloat) {
let sine = sin(angle)
let cosine = cos(angle)
m11 = cosine
m12 = sine
m21 = -sine
m22 = cosine
}
/**
Creates an affine transformation matrix by combining the receiver with `transformStruct`.
That is, it computes `T * M` and returns the result, where `T` is the receiver's and `M` is
the `transformStruct`'s affine transformation matrix.
The resulting matrix takes the following form:
[ m11_T m12_T 0 ] [ m11_M m12_M 0 ]
T * M = [ m21_T m22_T 0 ] [ m21_M m22_M 0 ]
[ tX_T tY_T 1 ] [ tX_M tY_M 1 ]
[ (m11_T*m11_M + m12_T*m21_M) (m11_T*m12_M + m12_T*m22_M) 0 ]
= [ (m21_T*m11_M + m22_T*m21_M) (m21_T*m12_M + m22_T*m22_M) 0 ]
[ (tX_T*m11_M + tY_T*m21_M + tX_M) (tX_T*m12_M + tY_T*m22_M + tY_M) 1 ]
*/
internal func concatenated(_ other: AffineTransform) -> AffineTransform {
let (t, m) = (self, other)
// this could be optimized with a vector version
return AffineTransform(
m11: (t.m11 * m.m11) + (t.m12 * m.m21), m12: (t.m11 * m.m12) + (t.m12 * m.m22),
m21: (t.m21 * m.m11) + (t.m22 * m.m21), m22: (t.m21 * m.m12) + (t.m22 * m.m22),
tX: (t.tX * m.m11) + (t.tY * m.m21) + m.tX,
tY: (t.tX * m.m12) + (t.tY * m.m22) + m.tY
)
}
// Scaling
public mutating func scale(_ scale: CGFloat) {
self.scale(x: scale, y: scale)
}
public mutating func scale(x: CGFloat, y: CGFloat) {
m11 = CGFloat(m11.native * x.native)
m12 = CGFloat(m12.native * x.native)
m21 = CGFloat(m21.native * y.native)
m22 = CGFloat(m22.native * y.native)
}
/**
Inverts the transformation matrix if possible. Matrices with a determinant that is less than
the smallest valid representation of a double value greater than zero are considered to be
invalid for representing as an inverse. If the input AffineTransform can potentially fall into
this case then the inverted() method is suggested to be used instead since that will return
an optional value that will be nil in the case that the matrix cannot be inverted.
D = (m11 * m22) - (m12 * m21)
D < ε the inverse is undefined and will be nil
*/
public mutating func invert() {
guard let inverse = inverted() else {
fatalError("Transform has no inverse")
}
self = inverse
}
public func inverted() -> AffineTransform? {
let determinant = (m11 * m22) - (m12 * m21)
if fabs(determinant.native) <= ε.native {
return nil
}
var inverse = AffineTransform()
inverse.m11 = m22 / determinant
inverse.m12 = -m12 / determinant
inverse.m21 = -m21 / determinant
inverse.m22 = m11 / determinant
inverse.tX = (m21 * tY - m22 * tX) / determinant
inverse.tY = (m12 * tX - m11 * tY) / determinant
return inverse
}
// Transforming with transform
public mutating func append(_ transform: AffineTransform) {
self = concatenated(transform)
}
public mutating func prepend(_ transform: AffineTransform) {
self = transform.concatenated(self)
}
// Transforming points and sizes
public func transform(_ point: NSPoint) -> NSPoint {
var newPoint = NSPoint()
newPoint.x = (m11 * point.x) + (m21 * point.y) + tX
newPoint.y = (m12 * point.x) + (m22 * point.y) + tY
return newPoint
}
public func transform(_ size: NSSize) -> NSSize {
var newSize = NSSize()
newSize.width = (m11 * size.width) + (m21 * size.height)
newSize.height = (m12 * size.width) + (m22 * size.height)
return newSize
}
public var hashValue : Int {
return Int((m11 + m12 + m21 + m22 + tX + tY).native)
}
public var description: String {
return "{m11:\(m11), m12:\(m12), m21:\(m21), m22:\(m22), tX:\(tX), tY:\(tY)}"
}
public var debugDescription: String {
return description
}
public static func ==(lhs: AffineTransform, rhs: AffineTransform) -> Bool {
return lhs.m11 == rhs.m11 && lhs.m12 == rhs.m12 &&
lhs.m21 == rhs.m21 && lhs.m22 == rhs.m22 &&
lhs.tX == rhs.tX && lhs.tY == rhs.tY
}
}
open class NSAffineTransform : NSObject, NSCopying, NSSecureCoding {
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let array = [
Float(transformStruct.m11),
Float(transformStruct.m12),
Float(transformStruct.m21),
Float(transformStruct.m22),
Float(transformStruct.tX),
Float(transformStruct.tY),
]
array.withUnsafeBytes { pointer in
aCoder.encodeValue(ofObjCType: "[6f]", at: UnsafeRawPointer(pointer.baseAddress!))
}
}
open func copy(with zone: NSZone? = nil) -> Any {
return NSAffineTransform(transform: self)
}
// Necessary because `NSObject.copy()` returns `self`.
open override func copy() -> Any {
return copy(with: nil)
}
public required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let pointer = UnsafeMutableRawPointer.allocate(bytes: MemoryLayout<Float>.stride * 6, alignedTo: 1)
defer {
pointer.deallocate(bytes: MemoryLayout<Float>.stride * 6, alignedTo: 1)
}
aDecoder.decodeValue(ofObjCType: "[6f]", at: pointer)
let floatPointer = pointer.bindMemory(to: Float.self, capacity: 6)
let m11 = floatPointer[0]
let m12 = floatPointer[1]
let m21 = floatPointer[2]
let m22 = floatPointer[3]
let tX = floatPointer[4]
let tY = floatPointer[5]
self.transformStruct = AffineTransform(m11: CGFloat(m11), m12: CGFloat(m12),
m21: CGFloat(m21), m22: CGFloat(m22),
tX: CGFloat(tX), tY: CGFloat(tY))
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSAffineTransform else { return false }
return other === self
|| (other.transformStruct == self.transformStruct)
}
public static var supportsSecureCoding: Bool {
return true
}
// Initialization
public convenience init(transform: NSAffineTransform) {
self.init()
transformStruct = transform.transformStruct
}
public override init() {
transformStruct = AffineTransform(
m11: CGFloat(1.0), m12: CGFloat(),
m21: CGFloat(), m22: CGFloat(1.0),
tX: CGFloat(), tY: CGFloat()
)
}
// Translating
open func translateX(by deltaX: CGFloat, yBy deltaY: CGFloat) {
let translation = AffineTransform(translationByX: deltaX, byY: deltaY)
transformStruct = translation.concatenated(transformStruct)
}
// Rotating
open func rotate(byDegrees angle: CGFloat) {
let rotation = AffineTransform(rotationByDegrees: angle)
transformStruct = rotation.concatenated(transformStruct)
}
open func rotate(byRadians angle: CGFloat) {
let rotation = AffineTransform(rotationByRadians: angle)
transformStruct = rotation.concatenated(transformStruct)
}
// Scaling
open func scale(by scale: CGFloat) {
scaleX(by: scale, yBy: scale)
}
open func scaleX(by scaleX: CGFloat, yBy scaleY: CGFloat) {
let scale = AffineTransform(scaleByX: scaleX, byY: scaleY)
transformStruct = scale.concatenated(transformStruct)
}
// Inverting
open func invert() {
if let inverse = transformStruct.inverted() {
transformStruct = inverse
}
else {
preconditionFailure("NSAffineTransform: Transform has no inverse")
}
}
// Transforming with transform
open func append(_ transform: NSAffineTransform) {
transformStruct = transformStruct.concatenated(transform.transformStruct)
}
open func prepend(_ transform: NSAffineTransform) {
transformStruct = transform.transformStruct.concatenated(transformStruct)
}
// Transforming points and sizes
open func transform(_ aPoint: NSPoint) -> NSPoint {
return transformStruct.transform(aPoint)
}
open func transform(_ aSize: NSSize) -> NSSize {
return transformStruct.transform(aSize)
}
// Transform Struct
open var transformStruct: AffineTransform
}
extension AffineTransform : _ObjectTypeBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return NSAffineTransform.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSAffineTransform {
let t = NSAffineTransform()
t.transformStruct = self
return t
}
public static func _forceBridgeFromObjectiveC(_ x: NSAffineTransform, result: inout AffineTransform?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge type")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSAffineTransform, result: inout AffineTransform?) -> Bool {
result = x.transformStruct
return true // Can't fail
}
public static func _unconditionallyBridgeFromObjectiveC(_ x: NSAffineTransform?) -> AffineTransform {
var result: AffineTransform?
_forceBridgeFromObjectiveC(x!, result: &result)
return result!
}
}
extension NSAffineTransform : _StructTypeBridgeable {
public typealias _StructType = AffineTransform
public func _bridgeToSwift() -> AffineTransform {
return AffineTransform._unconditionallyBridgeFromObjectiveC(self)
}
}
|
apache-2.0
|
6640bc7771db0e900d9cbb6204bd3869
| 31.339168 | 160 | 0.593748 | 4.032469 | false | false | false | false |
huangboju/Moots
|
Examples/Lumia/Lumia/Component/SafeArea/Views/TableView/TableViewCell.swift
|
1
|
982
|
//
// TableViewCell.swift
// SafeAreaExample
//
// Created by Evgeny Mikhaylov on 05/10/2017.
// Copyright © 2017 Rosberry. All rights reserved.
//
import UIKit
class TableViewCell: UITableViewCell {
lazy var customLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16.0)
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(customLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
customLabel.frame.origin.x = 5.0
customLabel.frame.origin.y = 0.0
customLabel.frame.size.width = contentView.bounds.width - 10.0
customLabel.frame.size.height = contentView.bounds.height
}
}
|
mit
|
def2ced5fa2040bbe4874586e02d10d4
| 26.25 | 79 | 0.655454 | 4.379464 | false | false | false | false |
Czajnikowski/TrainTrippin
|
Pods/RxCocoa/RxCocoa/CocoaUnits/SharedSequence/SharedSequence+Operators.swift
|
3
|
27515
|
//
// SharedSequence+Operators.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 9/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
// MARK: map
extension SharedSequenceConvertibleType {
/**
Projects each element of an observable sequence into a new form.
- parameter selector: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func map<R>(_ selector: @escaping (E) -> R) -> SharedSequence<SharingStrategy, R> {
let source = self
.asObservable()
.map(selector)
return SharedSequence<SharingStrategy, R>(source)
}
}
// MARK: filter
extension SharedSequenceConvertibleType {
/**
Filters the elements of an observable sequence based on a predicate.
- parameter predicate: A function to test each source element for a condition.
- returns: An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func filter(_ predicate: @escaping (E) -> Bool) -> SharedSequence<SharingStrategy, E> {
let source = self
.asObservable()
.filter(predicate)
return SharedSequence(source)
}
}
// MARK: switchLatest
extension SharedSequenceConvertibleType where E : SharedSequenceConvertibleType, E.SharingStrategy == SharingStrategy {
/**
Transforms an observable sequence of observable sequences into an observable sequence
producing values only from the most recent observable sequence.
Each time a new inner observable sequence is received, unsubscribe from the
previous inner observable sequence.
- returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func switchLatest() -> SharedSequence<SharingStrategy, E.E> {
let source: Observable<E.E> = self
.asObservable()
.map { $0.asSharedSequence() }
.switchLatest()
return SharedSequence<SharingStrategy, E.E>(source)
}
}
// MARK: flatMapLatest
extension SharedSequenceConvertibleType {
/**
Projects each element of an observable sequence into a new sequence of observable sequences and then
transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
It is a combination of `map` + `switchLatest` operator
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an
Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func flatMapLatest<R>(_ selector: @escaping (E) -> SharedSequence<SharingStrategy, R>)
-> SharedSequence<SharingStrategy, R> {
let source: Observable<R> = self
.asObservable()
.flatMapLatest(selector)
return SharedSequence<SharingStrategy, R>(source)
}
}
// MARK: flatMapFirst
extension SharedSequenceConvertibleType {
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
If element is received while there is some projected observable sequence being merged it will simply be ignored.
- parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func flatMapFirst<R>(_ selector: @escaping (E) -> SharedSequence<SharingStrategy, R>)
-> SharedSequence<SharingStrategy, R> {
let source: Observable<R> = self
.asObservable()
.flatMapFirst(selector)
return SharedSequence<SharingStrategy, R>(source)
}
}
// MARK: doOn
extension SharedSequenceConvertibleType {
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- parameter eventHandler: Action to invoke for each event in the observable sequence.
- returns: The source sequence with the side-effecting behavior applied.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "do(onNext:onError:onCompleted:)")
public func doOn(_ eventHandler: @escaping (Event<E>) -> Void)
-> SharedSequence<SharingStrategy, E> {
let source = self.asObservable()
.doOn(eventHandler)
return SharedSequence(source)
}
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence. This callback will never be invoked since driver can't error out.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- returns: The source sequence with the side-effecting behavior applied.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "do(onNext:onError:onCompleted:)")
public func doOn(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil)
-> SharedSequence<SharingStrategy, E> {
let source = self.asObservable()
.doOn(onNext: onNext, onError: onError, onCompleted: onCompleted)
return SharedSequence(source)
}
/**
Invokes an action for each Next event in the observable sequence, and propagates all observer messages through the result sequence.
- parameter onNext: Action to invoke for each element in the observable sequence.
- returns: The source sequence with the side-effecting behavior applied.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "do(onNext:)")
public func doOnNext(_ onNext: @escaping (E) -> Void)
-> SharedSequence<SharingStrategy, E> {
return self.do(onNext: onNext)
}
/**
Invokes an action for the Completed event in the observable sequence, and propagates all observer messages through the result sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- returns: The source sequence with the side-effecting behavior applied.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "do(onCompleted:)")
public func doOnCompleted(_ onCompleted: @escaping () -> Void)
-> SharedSequence<SharingStrategy, E> {
return self.do(onCompleted: onCompleted)
}
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence. This callback will never be invoked since driver can't error out.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func `do`(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onSubscribe: (() -> ())? = nil, onDispose: (() -> ())? = nil)
-> SharedSequence<SharingStrategy, E> {
let source = self.asObservable()
.do(onNext: onNext, onError: onError, onCompleted: onCompleted, onSubscribe: onSubscribe, onDispose: onDispose)
return SharedSequence(source)
}
}
// MARK: debug
extension SharedSequenceConvertibleType {
/**
Prints received events for all observers on standard output.
- parameter identifier: Identifier that is printed together with event description to standard output.
- returns: An observable sequence whose events are printed to standard output.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func debug(_ identifier: String? = nil, file: String = #file, line: UInt = #line, function: String = #function) -> SharedSequence<SharingStrategy, E> {
let source = self.asObservable()
.debug(identifier, file: file, line: line, function: function)
return SharedSequence(source)
}
}
// MARK: distinctUntilChanged
extension SharedSequenceConvertibleType where E: Equatable {
/**
Returns an observable sequence that contains only distinct contiguous elements according to equality operator.
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func distinctUntilChanged()
-> SharedSequence<SharingStrategy, E> {
let source = self.asObservable()
.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) })
return SharedSequence(source)
}
}
extension SharedSequenceConvertibleType {
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`.
- parameter keySelector: A function to compute the comparison key for each element.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func distinctUntilChanged<K: Equatable>(_ keySelector: @escaping (E) -> K) -> SharedSequence<SharingStrategy, E> {
let source = self.asObservable()
.distinctUntilChanged(keySelector, comparer: { $0 == $1 })
return SharedSequence(source)
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`.
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func distinctUntilChanged(_ comparer: @escaping (E, E) -> Bool) -> SharedSequence<SharingStrategy, E> {
let source = self.asObservable()
.distinctUntilChanged({ $0 }, comparer: comparer)
return SharedSequence<SharingStrategy, E>(source)
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
- parameter keySelector: A function to compute the comparison key for each element.
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func distinctUntilChanged<K>(_ keySelector: @escaping (E) -> K, comparer: @escaping (K, K) -> Bool) -> SharedSequence<SharingStrategy, E> {
let source = self.asObservable()
.distinctUntilChanged(keySelector, comparer: comparer)
return SharedSequence<SharingStrategy, E>(source)
}
}
// MARK: flatMap
extension SharedSequenceConvertibleType {
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func flatMap<R>(_ selector: @escaping (E) -> SharedSequence<SharingStrategy, R>) -> SharedSequence<SharingStrategy, R> {
let source = self.asObservable()
.flatMap(selector)
return SharedSequence(source)
}
}
// MARK: merge
extension SharedSequenceConvertibleType where E : SharedSequenceConvertibleType, E.SharingStrategy == SharingStrategy {
/**
Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence.
- parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func merge() -> SharedSequence<SharingStrategy, E.E> {
let source = self.asObservable()
.map { $0.asSharedSequence() }
.merge()
return SharedSequence<SharingStrategy, E.E>(source)
}
/**
Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences.
- returns: The observable sequence that merges the elements of the inner sequences.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func merge(maxConcurrent: Int)
-> SharedSequence<SharingStrategy, E.E> {
let source = self.asObservable()
.map { $0.asSharedSequence() }
.merge(maxConcurrent: maxConcurrent)
return SharedSequence<SharingStrategy, E.E>(source)
}
}
// MARK: throttle
extension SharedSequenceConvertibleType {
/**
Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration.
This operator makes sure that no two elements are emitted in less then dueTime.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted.
- returns: The throttled sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func throttle(_ dueTime: RxTimeInterval)
-> SharedSequence<SharingStrategy, E> {
let source = self.asObservable()
.throttle(dueTime, scheduler: SharingStrategy.scheduler)
return SharedSequence(source)
}
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
- parameter dueTime: Throttling duration for each element.
- returns: The throttled sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func debounce(_ dueTime: RxTimeInterval)
-> SharedSequence<SharingStrategy, E> {
let source = self.asObservable()
.debounce(dueTime, scheduler: SharingStrategy.scheduler)
return SharedSequence(source)
}
}
// MARK: scan
extension SharedSequenceConvertibleType {
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func scan<A>(_ seed: A, accumulator: @escaping (A, E) -> A)
-> SharedSequence<SharingStrategy, A> {
let source = self.asObservable()
.scan(seed, accumulator: accumulator)
return SharedSequence<SharingStrategy, A>(source)
}
}
// MARK: concat
extension SharedSequence {
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func concat<S: Sequence>(_ sequence: S) -> SharedSequence<SharingStrategy, Element>
where S.Iterator.Element == SharedSequence<SharingStrategy, Element> {
let source = Observable.concat(sequence.lazy.map { $0.asObservable() })
return SharedSequence<SharingStrategy, Element>(source)
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func concat<C: Collection>(_ collection: C) -> SharedSequence<SharingStrategy, Element>
where C.Iterator.Element == SharedSequence<SharingStrategy, Element> {
let source = Observable.concat(collection.map { $0.asObservable() })
return SharedSequence<SharingStrategy, Element>(source)
}
}
extension Sequence where Iterator.Element : SharedSequenceConvertibleType {
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "SharingSequence.concat()")
public func concat()
-> SharedSequence<Iterator.Element.SharingStrategy, Iterator.Element.E> {
let source = self.lazy.map { $0.asSharedSequence().asObservable() }.concat()
return SharedSequence<Iterator.Element.SharingStrategy, Iterator.Element.E>(source)
}
}
extension Collection where Iterator.Element : SharedSequenceConvertibleType {
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "SharingSequence.concat()")
public func concat()
-> SharedSequence<Iterator.Element.SharingStrategy, Iterator.Element.E> {
let source = self.map { $0.asSharedSequence().asObservable() }.concat()
return SharedSequence<Iterator.Element.SharingStrategy, Iterator.Element.E>(source)
}
}
// MARK: zip
extension SharedSequence {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<C: Collection, R>(_ collection: C, _ resultSelector: @escaping ([Element]) throws -> R) -> SharedSequence<SharingStrategy, R>
where C.Iterator.Element == SharedSequence<SharingStrategy, Element> {
let source = Observable.zip(collection.map { $0.asSharedSequence().asObservable() }, resultSelector)
return SharedSequence<SharingStrategy, R>(source)
}
}
extension Collection where Iterator.Element : SharedSequenceConvertibleType {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "SharedSequence.zip()")
public func zip<R>(_ resultSelector: @escaping ([Generator.Element.E]) throws -> R) -> SharedSequence<Generator.Element.SharingStrategy, R> {
let source = self.map { $0.asSharedSequence().asObservable() }.zip(resultSelector)
return SharedSequence<Generator.Element.SharingStrategy, R>(source)
}
}
// MARK: combineLatest
extension SharedSequence {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
- parameter resultSelector: Function to invoke whenever any of the sources produces an element.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func combineLatest<C: Collection, R>(_ collection: C, _ resultSelector: @escaping ([Element]) throws -> R) -> SharedSequence<SharingStrategy, R>
where C.Iterator.Element == SharedSequence<SharingStrategy, Element> {
let source = Observable.combineLatest(collection.map { $0.asObservable() }, resultSelector)
return SharedSequence<SharingStrategy, R>(source)
}
}
extension Collection where Iterator.Element : SharedSequenceConvertibleType {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
- parameter resultSelector: Function to invoke whenever any of the sources produces an element.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "SharingSequence.combineLatest()")
public func combineLatest<R>(_ resultSelector: @escaping ([Generator.Element.E]) throws -> R) -> SharedSequence<Generator.Element.SharingStrategy, R> {
let source = self.map { $0.asSharedSequence().asObservable() }.combineLatest(resultSelector)
return SharedSequence<Generator.Element.SharingStrategy, R>(source)
}
}
// MARK: withLatestFrom
extension SharedSequenceConvertibleType {
/**
Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any.
- parameter second: Second observable source.
- parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<SecondO: SharedSequenceConvertibleType, ResultType>(_ second: SecondO, resultSelector: @escaping (E, SecondO.E) -> ResultType) -> SharedSequence<SharingStrategy, ResultType> where SecondO.SharingStrategy == SecondO.SharingStrategy {
let source = self.asObservable()
.withLatestFrom(second.asSharedSequence(), resultSelector: resultSelector)
return SharedSequence<SharingStrategy, ResultType>(source)
}
/**
Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emitts an element.
- parameter second: Second observable source.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<SecondO: SharedSequenceConvertibleType>(_ second: SecondO) -> SharedSequence<SharingStrategy, SecondO.E> {
let source = self.asObservable()
.withLatestFrom(second.asSharedSequence())
return SharedSequence<SharingStrategy, SecondO.E>(source)
}
}
// MARK: skip
extension SharedSequenceConvertibleType {
/**
Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
- seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html)
- parameter count: The number of elements to skip before returning the remaining elements.
- returns: An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func skip(_ count: Int)
-> SharedSequence<SharingStrategy, E> {
let source = self.asObservable()
.skip(count)
return SharedSequence(source)
}
}
// MARK: startWith
extension SharedSequenceConvertibleType {
/**
Prepends a value to an observable sequence.
- seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html)
- parameter element: Element to prepend to the specified sequence.
- returns: The source sequence prepended with the specified values.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func startWith(_ element: E)
-> SharedSequence<SharingStrategy, E> {
let source = self.asObservable()
.startWith(element)
return SharedSequence(source)
}
}
|
mit
|
ff8eb39f42dc37b45d176291a621665e
| 46.519862 | 263 | 0.711492 | 5.055862 | false | false | false | false |
krin-san/SwiftCalc
|
SwiftCalc/Model/SCCore.swift
|
1
|
4590
|
//
// SCCore.swift
// SwiftCalc
//
// Created by Krin-San on 30.10.14.
//
import Foundation
public class SCCore {
// Singleton
class func sharedInstance() -> SCCore {
struct _Singleton {
static let instance = SCCore()
}
return _Singleton.instance
}
var expression: [SCEquationObject] = []
var result: Double = 0.0 {
didSet {
notify()
}
}
private func parseExpression() -> String {
var description = ""
if (expression.count == 0) {
description = "0"
} else {
for item in expression {
description += item.stringValue
}
}
return description
}
private func notify(_ error: String? = nil) {
var userInfo: [String: String] = [
kCoreValueExpression: parseExpression(),
kCoreValueResult: result.toString(),
]
if error != nil {
userInfo[kCoreValueError] = error!
// Prepare for next expression
expression.removeAll()
}
NSNotificationCenter.defaultCenter().postNotificationName(kCoreValuesChangedNotification, object: self, userInfo: userInfo)
}
func reset() {
expression.removeAll()
result = 0.0
}
func input(part: Any) {
if let obj = part as? SCEquationObject {
expression.append(obj)
}
else if let obj = part as? String {
if let operand = expression.last as? SCOperand {
// Append new part to existing operand
if !operand.input(obj) {
expression.removeLast()
}
}
else {
// Append part to newly created operand
var operand = SCOperand()
if operand.input(obj) {
expression.append(operand)
}
}
}
else {
assert(false, "Unhandled class of equation part <\(part)>")
}
notify()
}
func calculate() {
// Translate to reverse polish notation
var opn: [SCEquationObject] = []
var opStack: [SCEquationObject] = []
println("INPUT = \(expression)")
for operand in expression {
// println("<\(operand.stringValue)>")
if (operand is SCOperand) {
// println("<\(operand.stringValue)> ADD >> OPN")
opn.append(operand)
} else if (operand is SCOperation) {
while !opStack.isEmpty && (opStack.last is SCOperation) && ((opStack.last as SCOperation).priority.rawValue >= (operand as SCOperation).priority.rawValue) {
// println("<\(operand.stringValue)> POP \(opStack.last!.stringValue) >> OPN")
opn.append(opStack.last!)
opStack.removeLast()
}
// println("<\(operand.stringValue)> PUSH")
opStack.append(operand)
} else {
if (operand.stringValue == specialOperators[.OpeningBracket]?.stringValue) {
// println("<\(operand.stringValue)> PUSH")
opStack.append(operand)
} else if (operand.stringValue == specialOperators[.ClosingBracket]?.stringValue) {
var isFoundOpeningBracket: Bool = false
for obj in opStack.reverse() {
if (obj.stringValue == specialOperators[.OpeningBracket]?.stringValue) {
// println("<\(operand.stringValue)> POP")
isFoundOpeningBracket = true
} else {
// println("<\(operand.stringValue)> POP >> OPN")
opn.append(obj)
}
opStack.removeLast()
if (isFoundOpeningBracket) {
break
}
}
if (!isFoundOpeningBracket) {
notify("Unbalanced brackets!")
return
}
} else {
assert(false, "Unhandled operand <\(operand.stringValue)>")
}
}
}
for operand in opStack.reverse() {
// println("<\(operand.stringValue)> MOVE >> OPN")
opn.append(operand)
}
opStack.removeAll()
println("OPN = \(opn)")
// Calculate
var variables: [Double] = []
for operand in opn {
if (operand is SCOperand) {
// println("<\(operand.stringValue)> PUSH")
variables.append(operand.stringValue.toDouble(unsafe: true)!)
} else if let operation = operand as? SCOperation {
if (variables.count < operation.operandsCount) {
println("<\(operand.stringValue)> CALC = nil (Failed)")
notify("Operation <\(operand.stringValue)> failed")
return
}
var range = (variables.count - operation.operandsCount)..<variables.count
var slice = Array(variables[range])
if let ans = operation.perform(slice) {
println("<\(operand.stringValue)> CALC \(slice) = \(ans)")
variables.removeRange(range)
variables.append(ans)
} else {
println("<\(operand.stringValue)> CALC = nil (Failed)")
notify("Operation <\(operand.stringValue)> failed")
return
}
} else {
assert(false, "Unexpected operand <\(operand.stringValue)>")
}
}
result = (variables.first != nil) ? variables.first! : 0.0
// Prepare for next expression
expression.removeAll()
}
}
|
gpl-3.0
|
39f3351e89e99b2949e4f295d98bafb1
| 22.90625 | 160 | 0.638126 | 3.506494 | false | false | false | false |
evgeny-emelyanov/if-park-safe
|
ParkSafe/FirstViewController.swift
|
1
|
6876
|
//
// FirstViewController.swift
// ParkSafe
//
// Created by Eugene on 11/20/16.
// Copyright © 2016 IF. All rights reserved.
//
import UIKit
import GoogleMaps
import UserNotifications
class FirstViewController: UIViewController, UNUserNotificationCenterDelegate {
var notificationManager: NotificationManager?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if notificationManager == nil{
notificationManager = (UIApplication.shared.delegate as! AppDelegate).notificationManager
if #available(iOS 10.0, *) {
notificationManager?.setDelegate(delegate: self)
} else {
// Fallback on earlier versions
}
}
let camera = GMSCameraPosition.camera(withLatitude: 56.9516026,
longitude: 24.119115, zoom: 12)
let mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera)
mapView.isMyLocationEnabled = true;
self.view = mapView
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(56.9516026, 24.119115)
marker.title = "Riga"
marker.snippet = "Latvia"
marker.map = mapView
addAlfa(mapView: mapView)
addMarupe(mapView: mapView)
addSpice(mapView: mapView)
}
func addMarupe(mapView: GMSMapView) {
let path = GMSMutablePath()
path.add(CLLocationCoordinate2DMake(56.904067, 23.993930))
path.add(CLLocationCoordinate2DMake(56.915782, 23.981742))
path.add(CLLocationCoordinate2DMake(56.927400, 23.997535))
path.add(CLLocationCoordinate2DMake(56.926557, 24.038905))
path.add(CLLocationCoordinate2DMake(56.912216, 24.044989))
path.add(CLLocationCoordinate2DMake(56.905848, 24.081306))
path.add(CLLocationCoordinate2DMake(56.892911, 24.074611))
path.add(CLLocationCoordinate2DMake(56.881002, 24.037189))
path.add(CLLocationCoordinate2DMake(56.887660, 24.032897))
path.add(CLLocationCoordinate2DMake(56.885785, 24.010581))
path.add(CLLocationCoordinate2DMake(56.889629, 24.008693))
path.add(CLLocationCoordinate2DMake(56.897505, 24.033927))
path.add(CLLocationCoordinate2DMake(56.908285, 24.022597))
path.add(CLLocationCoordinate2DMake(56.904067, 23.993930))
let rectangle = GMSPolyline(path: path)
rectangle.strokeWidth = 2
let solidRed = GMSStrokeStyle.solidColor(UIColor.red)
rectangle.spans = [GMSStyleSpan(style: solidRed)]
rectangle.map = mapView
notificationManager?.scheduleNotification(identifier: "Marupe", title: "Car theft risk is high in Mārupe!", subtitle: "", body: "You are parking in Mārupe. Car theft risk is extremely high in this area, so do not leave your car unattended especially overnight. Based on our data 25 vehicles has been stolen here during last 12 months mostly to be split apart and sold in Lithuania.", latitude: 56.916645, longitude: 24.011521, radius: 500, areaIdentifier: "Marupe", repeats: true)
}
func addAlfa(mapView: GMSMapView){
let path = GMSMutablePath()
path.add(CLLocationCoordinate2DMake(56.982832, 24.201361))
path.add(CLLocationCoordinate2DMake(56.983393, 24.200846))
path.add(CLLocationCoordinate2DMake(56.984404, 24.205030))
path.add(CLLocationCoordinate2DMake(56.982935, 24.206042))
path.add(CLLocationCoordinate2DMake(56.982836, 24.205141))
path.add(CLLocationCoordinate2DMake(56.983666, 24.204358))
path.add(CLLocationCoordinate2DMake(56.982832, 24.201361))
let rectangle = GMSPolyline(path: path)
rectangle.strokeWidth = 2
let solidRed = GMSStrokeStyle.solidColor(UIColor.red)
rectangle.spans = [GMSStyleSpan(style: solidRed)]
rectangle.map = mapView
notificationManager?.scheduleNotification(identifier: "Alfa", title: "Dear Līga, your BMW is at risk near Alfa!", subtitle: "", body: "Rear-view mirrors of BMWs are likely to be stolen here. A set of rear-view mirrors for BMW can cost up to 2000 EUR. So, try to avoid this parking area at best. If you decide to stay, please prefer outdoor parking area since CTV cameras are operating there.", latitude: 56.982832, longitude: 24.201361, radius: 500, areaIdentifier: "Alfa", repeats: true)
}
func addSpice(mapView: GMSMapView){
var path = GMSMutablePath()
let solidRed = GMSStrokeStyle.solidColor(UIColor.red)
path.add(CLLocationCoordinate2DMake(56.929469, 24.033065))
path.add(CLLocationCoordinate2DMake(56.930897, 24.035565))
path.add(CLLocationCoordinate2DMake(56.930452, 24.036402))
path.add(CLLocationCoordinate2DMake(56.929351, 24.034181))
path.add(CLLocationCoordinate2DMake(56.929469, 24.033065))
var rectangle = GMSPolyline(path: path)
rectangle.strokeWidth = 2
rectangle.spans = [GMSStyleSpan(style: solidRed)]
rectangle.map = mapView
path = GMSMutablePath()
path.add(CLLocationCoordinate2DMake(56.930258, 24.037121))
path.add(CLLocationCoordinate2DMake(56.930849, 24.038301))
path.add(CLLocationCoordinate2DMake(56.930217, 24.039395))
path.add(CLLocationCoordinate2DMake(56.929392, 24.039009))
path.add(CLLocationCoordinate2DMake(56.930258, 24.037121))
rectangle = GMSPolyline(path: path)
rectangle.strokeWidth = 2
rectangle.spans = [GMSStyleSpan(style: solidRed)]
rectangle.map = mapView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func goToArea1(_ sender: UIButton) {
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let title = response.notification.request.content.title
let text = response.notification.request.content.body
let alert = UIAlertController(title: title, message: text, preferredStyle: UIAlertControllerStyle.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
|
apache-2.0
|
11a094080d2bfdf2ae383a6b4015a11f
| 40.39759 | 496 | 0.659488 | 4.35488 | false | false | false | false |
jopamer/swift
|
test/decl/inherit/initializer.swift
|
1
|
3906
|
// RUN: %target-typecheck-verify-swift
class A {
init(int i: Int) { }
init(double d: Double) { }
convenience init(float f: Float) {
self.init(double: Double(f))
}
}
// Implicit overriding of subobject initializers
class B : A {
var x = "Hello"
var (y, z) = (1, 2)
}
func testB() {
_ = B(int: 5)
_ = B(double: 2.71828)
_ = B(float: 3.14159)
}
// Okay to have nothing
class C : B {
}
func testC() {
_ = C(int: 5)
_ = C(double: 2.71828)
_ = C(float: 3.14159)
}
// Okay to add convenience initializers.
class D : C {
convenience init(string s: String) {
self.init(int: Int(s)!)
}
}
func testD() {
_ = D(int: 5)
_ = D(double: 2.71828)
_ = D(float: 3.14159)
_ = D(string: "3.14159")
}
// Adding a subobject initializer prevents inheritance of subobject
// initializers.
class NotInherited1 : D {
override init(int i: Int) {
super.init(int: i)
}
convenience init(float f: Float) {
self.init(int: Int(f))
}
}
func testNotInherited1() {
var n1 = NotInherited1(int: 5)
var n2 = NotInherited1(double: 2.71828) // expected-error{{incorrect argument label in call (have 'double:', expected 'float:')}}
}
class NotInherited1Sub : NotInherited1 {
override init(int i: Int) {
super.init(int: i)
}
}
func testNotInherited1Sub() {
var n1 = NotInherited1Sub(int: 5)
var n2 = NotInherited1Sub(float: 3.14159)
var n3 = NotInherited1Sub(double: 2.71828) // expected-error{{incorrect argument label in call (have 'double:', expected 'float:')}}
}
// Having a stored property without an initial value prevents
// inheritance of initializers.
class NotInherited2 : D { // expected-error{{class 'NotInherited2' has no initializers}}
var a: Int // expected-note{{stored property 'a' without initial value prevents synthesized initializers}}{{13-13= = 0}}
var b: Int // expected-note{{stored property 'b' without initial value prevents synthesized initializers}}{{13-13= = 0}}
, c: Int // expected-note{{stored property 'c' without initial value prevents synthesized initializers}}{{13-13= = 0}}
var (d, e): (Int, String) // expected-note{{stored properties 'd' and 'e' without initial values prevent synthesized initializers}}{{28-28= = (0, "")}}
var (f, (g, h)): (Int?, (Float, String)) // expected-note{{stored properties 'f', 'g', and 'h' without initial values prevent synthesized initializers}}{{43-43= = (nil, (0.0, ""))}}
var (w, i, (j, k)): (Int?, Float, (String, D)) // expected-note{{stored properties 'w', 'i', 'j', and others without initial values prevent synthesized initializers}}
}
func testNotInherited2() {
var n1 = NotInherited2(int: 5) // expected-error{{'NotInherited2' cannot be constructed because it has no accessible initializers}}
var n2 = NotInherited2(double: 2.72828) // expected-error{{'NotInherited2' cannot be constructed because it has no accessible initializers}}
}
// FIXME: <rdar://problem/16331406> Implement inheritance of variadic designated initializers
class SuperVariadic {
init(ints: Int...) { } // expected-note{{variadic superclass initializer defined here}}
init(_ : Double...) { } // expected-note{{variadic superclass initializer defined here}}
init(s: String, ints: Int...) { } // expected-note{{variadic superclass initializer defined here}}
init(s: String, _ : Double...) { } // expected-note{{variadic superclass initializer defined here}}
}
class SubVariadic : SuperVariadic { } // expected-warning 4{{synthesizing a variadic inherited initializer for subclass 'SubVariadic' is unsupported}}
// Don't crash with invalid nesting of class in generic function
func testClassInGenericFunc<T>(t: T) {
class A { init(t: T) {} } // expected-error {{type 'A' cannot be nested in generic function 'testClassInGenericFunc(t:)'}}
class B : A {} // expected-error {{type 'B' cannot be nested in generic function 'testClassInGenericFunc(t:)'}}
_ = B(t: t)
}
|
apache-2.0
|
2196b026c10325ffb31562550d7c87e5
| 33.875 | 183 | 0.677163 | 3.541251 | false | true | false | false |
overtake/TelegramSwift
|
Telegram-Mac/VoiceChatActionButton.swift
|
1
|
39223
|
//
// VoiceChatActionButton.swift
// Telegram
//
// Created by Mikhail Filimonov on 14.12.2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import SwiftSignalKit
private let white = NSColor(rgb: 0xffffff)
private let greyColor = GroupCallTheme.speakDisabledColor
private let secondaryGreyColor = NSColor(rgb: 0x1c1c1e)
private let blue = NSColor(rgb: 0x0078ff)
private let lightBlue = NSColor(rgb: 0x59c7f8)
private let green = NSColor(rgb: 0x33c659)
private let activeBlue = NSColor(rgb: 0x00a0b9)
private let purple = NSColor(rgb: 0x766EE9)
private let lightPurple = NSColor(rgb: 0xF05459)
private let areaSize = CGSize(width: 360, height: 360)
private let blobSize = CGSize(width: 190, height: 190)
private let progressLineWidth: CGFloat = 3.0 + 1
private let buttonSize = CGSize(width: 110, height: 110)
private let radius = buttonSize.width / 2.0
final class VoiceChatActionButtonBackgroundView: View {
enum State: Equatable {
case connecting
case disabled
case blob(Bool)
}
private var state: State
private var hasState = false
private var transition: State?
var audioLevel: CGFloat = 0.0 {
didSet {
self.maskBlobLayer.updateLevel(audioLevel)
}
}
var updatedActive: ((Bool) -> Void)?
var updatedOuterColor: ((NSColor?) -> Void)?
private let backgroundCircleLayer = CAShapeLayer()
private let foregroundCircleLayer = CAShapeLayer()
private let growingForegroundCircleLayer = CAShapeLayer()
private let foregroundLayer = CALayer()
private let foregroundGradientLayer = CAGradientLayer()
private let maskLayer = CALayer()
private let maskGradientLayer = CAGradientLayer()
private let maskBlobLayer: VoiceChatBlobLayer
private let maskCircleLayer = CAShapeLayer()
fileprivate let maskProgressLayer = CAShapeLayer()
private let maskMediumBlobLayer = CAShapeLayer()
private let maskBigBlobLayer = CAShapeLayer()
override init() {
self.state = .connecting
self.maskBlobLayer = VoiceChatBlobLayer(frame: CGRect(origin: .zero, size: blobSize), maxLevel: 1.5, mediumBlobRange: (0.69, 0.87), bigBlobRange: (0.71, 1.0))
self.maskBlobLayer.setColor(white)
self.maskBlobLayer.isHidden = true
super.init()
let circlePath = CGMutablePath()
circlePath.addRoundedRect(in: CGRect(origin: CGPoint(), size: buttonSize), cornerWidth: buttonSize.width / 2, cornerHeight: buttonSize.height / 2)
self.backgroundCircleLayer.fillColor = greyColor.cgColor
self.backgroundCircleLayer.path = circlePath
let smallerCirclePath = CGMutablePath()
let smallerRect = CGRect(origin: CGPoint(), size: CGSize(width: buttonSize.width - progressLineWidth, height: buttonSize.height - progressLineWidth))
smallerCirclePath.addRoundedRect(in: smallerRect, cornerWidth: smallerRect.width / 2, cornerHeight: smallerRect.height / 2)
self.foregroundCircleLayer.fillColor = greyColor.cgColor
self.foregroundCircleLayer.path = smallerCirclePath
self.foregroundCircleLayer.transform = CATransform3DMakeScale(0.0, 0.0, 1)
self.foregroundCircleLayer.isHidden = true
self.growingForegroundCircleLayer.fillColor = greyColor.cgColor
self.growingForegroundCircleLayer.path = smallerCirclePath
self.growingForegroundCircleLayer.transform = CATransform3DMakeScale(1.0, 1.0, 1)
self.growingForegroundCircleLayer.isHidden = true
self.foregroundGradientLayer.type = .radial
self.foregroundGradientLayer.colors = [lightBlue.cgColor, blue.cgColor]
self.foregroundGradientLayer.startPoint = CGPoint(x: 1.0, y: 0.0)
self.foregroundGradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)
self.maskLayer.backgroundColor = .clear
self.maskGradientLayer.type = .radial
self.maskGradientLayer.colors = [NSColor(rgb: 0xffffff, alpha: 0.4).cgColor, NSColor(rgb: 0xffffff, alpha: 0.0).cgColor]
self.maskGradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5)
self.maskGradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
self.maskGradientLayer.transform = CATransform3DMakeScale(0.3, 0.3, 1.0)
self.maskGradientLayer.isHidden = true
let path = CGMutablePath()
path.addArc(center: CGPoint(x: (buttonSize.width + 6.0) / 2.0, y: (buttonSize.height + 6.0) / 2.0), radius: radius, startAngle: 0.0, endAngle: CGFloat.pi * 2.0, clockwise: true)
self.maskProgressLayer.strokeColor = white.cgColor
self.maskProgressLayer.fillColor = NSColor.clear.cgColor
self.maskProgressLayer.lineWidth = progressLineWidth
self.maskProgressLayer.lineCap = .round
self.maskProgressLayer.path = path
let largerCirclePath = CGMutablePath()
let largerCircleRect = CGRect(origin: CGPoint(), size: CGSize(width: buttonSize.width + progressLineWidth, height: buttonSize.height + progressLineWidth))
largerCirclePath.addRoundedRect(in: largerCircleRect, cornerWidth: largerCircleRect.width / 2, cornerHeight: largerCircleRect.height / 2)
self.maskCircleLayer.fillColor = white.cgColor
self.maskCircleLayer.path = largerCirclePath
self.maskCircleLayer.isHidden = true
self.layer?.addSublayer(self.backgroundCircleLayer)
self.layer?.addSublayer(self.foregroundLayer)
self.layer?.addSublayer(self.foregroundCircleLayer)
// self.layer?.addSublayer(self.growingForegroundCircleLayer)
self.foregroundLayer.addSublayer(self.foregroundGradientLayer)
self.foregroundLayer.mask = self.maskLayer
self.maskLayer.addSublayer(self.maskGradientLayer)
self.maskLayer.addSublayer(self.maskProgressLayer)
self.maskLayer.addSublayer(self.maskBlobLayer)
self.maskLayer.addSublayer(self.maskCircleLayer)
self.maskBlobLayer.scaleUpdated = { [weak self] scale in
if let strongSelf = self {
strongSelf.updateGlowScale(strongSelf.isActive == true ? scale : nil)
}
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
private let occlusionDisposable = MetaDisposable()
private var isCurrentlyInHierarchy: Bool = false {
didSet {
updateAnimations()
}
}
deinit {
occlusionDisposable.dispose()
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
// isCurrentlyInHierarchy = window != nil
if let window = window as? Window {
occlusionDisposable.set(window.takeOcclusionState.start(next: { [weak self] value in
self?.isCurrentlyInHierarchy = true
}))
} else {
occlusionDisposable.set(nil)
isCurrentlyInHierarchy = false
}
}
private func setupGradientAnimations() {
if let _ = self.foregroundGradientLayer.animation(forKey: "movement") {
} else {
let previousValue = self.foregroundGradientLayer.startPoint
let newValue: CGPoint
if self.maskBlobLayer.presentationAudioLevel > 0.22 {
newValue = CGPoint(x: CGFloat.random(in: 0.9 ..< 1.0), y: CGFloat.random(in: 0.1 ..< 0.35))
} else if self.maskBlobLayer.presentationAudioLevel > 0.01 {
newValue = CGPoint(x: CGFloat.random(in: 0.77 ..< 0.95), y: CGFloat.random(in: 0.1 ..< 0.35))
} else {
newValue = CGPoint(x: CGFloat.random(in: 0.65 ..< 0.85), y: CGFloat.random(in: 0.1 ..< 0.45))
}
self.foregroundGradientLayer.startPoint = newValue
CATransaction.begin()
let animation = CABasicAnimation(keyPath: "startPoint")
animation.duration = Double.random(in: 0.8 ..< 1.4)
animation.fromValue = previousValue
animation.toValue = newValue
CATransaction.setCompletionBlock { [weak self] in
if let isCurrentlyInHierarchy = self?.isCurrentlyInHierarchy, isCurrentlyInHierarchy {
self?.setupGradientAnimations()
}
}
self.foregroundGradientLayer.add(animation, forKey: "movement")
CATransaction.commit()
}
}
private func setupProgressAnimations() {
if let _ = self.maskProgressLayer.animation(forKey: "progressRotation") {
} else {
self.maskProgressLayer.isHidden = false
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
animation.duration = 1.0
animation.fromValue = NSNumber(value: Float(0.0))
animation.toValue = NSNumber(value: Float.pi * 2.0)
animation.repeatCount = Float.infinity
animation.beginTime = 0.0
self.maskProgressLayer.add(animation, forKey: "progressRotation")
let shrinkAnimation = CABasicAnimation(keyPath: "strokeEnd")
shrinkAnimation.fromValue = 1.0
shrinkAnimation.toValue = 0.0
shrinkAnimation.duration = 1.0
shrinkAnimation.beginTime = 0.0
let growthAnimation = CABasicAnimation(keyPath: "strokeEnd")
growthAnimation.fromValue = 0.0
growthAnimation.toValue = 1.0
growthAnimation.duration = 1.0
growthAnimation.beginTime = 1.0
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat.pi * 2
rotateAnimation.isAdditive = true
rotateAnimation.duration = 1.0
rotateAnimation.beginTime = 1.0
let groupAnimation = CAAnimationGroup()
groupAnimation.repeatCount = Float.infinity
groupAnimation.animations = [shrinkAnimation, growthAnimation, rotateAnimation]
groupAnimation.duration = 2.0
self.maskProgressLayer.add(groupAnimation, forKey: "progressGrowth")
}
}
var glowHidden: Bool = false {
didSet {
if self.glowHidden != oldValue {
let initialAlpha = CGFloat(self.maskProgressLayer.opacity)
let targetAlpha: CGFloat = self.glowHidden ? 0.0 : 1.0
self.maskGradientLayer.opacity = Float(targetAlpha)
self.maskGradientLayer.animateAlpha(from: initialAlpha, to: targetAlpha, duration: 0.2)
}
}
}
var disableGlowAnimations = false
func updateGlowScale(_ scale: CGFloat?) {
if self.disableGlowAnimations {
return
}
if let scale = scale {
self.maskGradientLayer.transform = CATransform3DMakeScale(0.89 + 0.11 * scale, 0.89 + 0.11 * scale, 1.0)
} else {
let initialScale: CGFloat = ((self.maskGradientLayer.value(forKeyPath: "presentationLayer.transform.scale.x") as? NSNumber)?.floatValue).flatMap({ CGFloat($0) }) ?? (((self.maskGradientLayer.value(forKeyPath: "transform.scale.x") as? NSNumber)?.floatValue).flatMap({ CGFloat($0) }) ?? (0.89))
let targetScale: CGFloat = self.isActive == true ? 0.89 : 0.85
if abs(targetScale - initialScale) > 0.03 {
self.maskGradientLayer.transform = CATransform3DMakeScale(targetScale, targetScale, 1.0)
self.maskGradientLayer.animateScale(from: initialScale, to: targetScale, duration: 0.3)
}
}
}
func updateGlowAndGradientAnimations(active: Bool?, previousActive: Bool? = nil) {
let effectivePreviousActive = previousActive ?? false
let initialScale: CGFloat = ((self.maskGradientLayer.value(forKeyPath: "presentationLayer.transform.scale.x") as? NSNumber)?.floatValue).flatMap({ CGFloat($0) }) ?? (((self.maskGradientLayer.value(forKeyPath: "transform.scale.x") as? NSNumber)?.floatValue).flatMap({ CGFloat($0) }) ?? (effectivePreviousActive ? 0.95 : 0.8))
let initialColors = self.foregroundGradientLayer.colors
let outerColor: NSColor?
let targetColors: [CGColor]
let targetScale: CGFloat
if let active = active {
if active {
targetColors = [activeBlue.cgColor, green.cgColor]
targetScale = 0.89
outerColor = NSColor(rgb: 0x21674f)
} else {
targetColors = [lightBlue.cgColor, blue.cgColor]
targetScale = 0.85
outerColor = NSColor(rgb: 0x1d588d)
}
} else {
targetColors = [purple.cgColor, lightPurple.cgColor]
targetScale = 0.3
outerColor = nil
}
self.updatedOuterColor?(outerColor)
self.maskGradientLayer.transform = CATransform3DMakeScale(targetScale, targetScale, 1.0)
if let _ = previousActive {
self.maskGradientLayer.animateScale(from: initialScale, to: targetScale, duration: 0.3)
} else {
self.maskGradientLayer.animateSpring(from: initialScale as NSNumber, to: targetScale as NSNumber, keyPath: "transform.scale", duration: 0.45)
}
self.foregroundGradientLayer.colors = targetColors
self.foregroundGradientLayer.animate(from: initialColors as AnyObject, to: targetColors as AnyObject, keyPath: "colors", timingFunction: .linear, duration: 0.3)
}
private func playConnectionDisappearanceAnimation() {
let initialRotation: CGFloat = CGFloat((self.maskProgressLayer.value(forKeyPath: "presentationLayer.transform.rotation.z") as? NSNumber)?.floatValue ?? 0.0)
let initialStrokeEnd: CGFloat = CGFloat((self.maskProgressLayer.value(forKeyPath: "presentationLayer.strokeEnd") as? NSNumber)?.floatValue ?? 1.0)
let maskProgressLayer = self.maskProgressLayer
maskProgressLayer.removeAnimation(forKey: "progressGrowth")
maskProgressLayer.removeAnimation(forKey: "progressRotation")
let duration: Double = (1.0 - Double(initialStrokeEnd)) * 0.6
let growthAnimation = CABasicAnimation(keyPath: "strokeEnd")
growthAnimation.fromValue = initialStrokeEnd
growthAnimation.toValue = 0.0
growthAnimation.duration = duration
growthAnimation.isRemovedOnCompletion = false
growthAnimation.timingFunction = CAMediaTimingFunction(name: .easeIn)
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotateAnimation.fromValue = initialRotation
rotateAnimation.toValue = initialRotation + CGFloat.pi * 2
rotateAnimation.isAdditive = true
rotateAnimation.duration = duration
rotateAnimation.isRemovedOnCompletion = false
rotateAnimation.timingFunction = CAMediaTimingFunction(name: .easeIn)
let groupAnimation = CAAnimationGroup()
groupAnimation.animations = [growthAnimation, rotateAnimation]
groupAnimation.duration = duration
groupAnimation.isRemovedOnCompletion = false
CATransaction.begin()
self.maskProgressLayer.animateAlpha(from: 1, to: 0, duration: duration, removeOnCompletion: false)
CATransaction.setCompletionBlock {
maskProgressLayer.isHidden = true
maskProgressLayer.removeAllAnimations()
}
self.maskProgressLayer.add(groupAnimation, forKey: "progressDisappearance")
CATransaction.commit()
}
var animatingDisappearance = false
private func playBlobsDisappearanceAnimation(wasActive: Bool? = nil) {
if self.animatingDisappearance {
return
}
self.animatingDisappearance = true
CATransaction.begin()
CATransaction.setDisableActions(true)
self.growingForegroundCircleLayer.isHidden = false
CATransaction.commit()
self.disableGlowAnimations = true
self.maskGradientLayer.removeAllAnimations()
self.updateGlowAndGradientAnimations(active: wasActive, previousActive: nil)
self.maskBlobLayer.startAnimating()
CATransaction.begin()
self.maskBlobLayer.animateScale(from: 1.0, to: 0, duration: 0.15, removeOnCompletion: false)
CATransaction.setCompletionBlock {
self.maskBlobLayer.isHidden = true
self.maskBlobLayer.stopAnimating()
self.maskBlobLayer.removeAllAnimations()
}
CATransaction.commit()
CATransaction.begin()
let growthAnimation = CABasicAnimation(keyPath: "transform.scale")
growthAnimation.fromValue = 0.0
growthAnimation.toValue = 1.0
growthAnimation.duration = 0.15
growthAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
growthAnimation.isRemovedOnCompletion = false
CATransaction.setCompletionBlock {
CATransaction.begin()
CATransaction.setDisableActions(true)
self.disableGlowAnimations = false
self.maskGradientLayer.isHidden = true
self.maskCircleLayer.isHidden = true
self.growingForegroundCircleLayer.isHidden = true
self.growingForegroundCircleLayer.removeAllAnimations()
self.animatingDisappearance = false
CATransaction.commit()
}
self.growingForegroundCircleLayer.add(growthAnimation, forKey: "insideGrowth")
CATransaction.commit()
}
private func playBlobsAppearanceAnimation(active: Bool) {
CATransaction.begin()
CATransaction.setDisableActions(true)
self.foregroundCircleLayer.isHidden = false
self.maskCircleLayer.isHidden = false
self.maskProgressLayer.isHidden = true
self.maskGradientLayer.isHidden = false
CATransaction.commit()
self.disableGlowAnimations = true
self.maskGradientLayer.removeAllAnimations()
self.updateGlowAndGradientAnimations(active: active, previousActive: nil)
self.maskBlobLayer.isHidden = false
self.maskBlobLayer.startAnimating()
self.maskBlobLayer.animateSpring(from: 0.1 as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: 0.45)
CATransaction.begin()
let shrinkAnimation = CABasicAnimation(keyPath: "transform.scale")
shrinkAnimation.fromValue = 1.0
shrinkAnimation.toValue = 0.0
shrinkAnimation.duration = 0.15
shrinkAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn)
CATransaction.setCompletionBlock {
CATransaction.begin()
CATransaction.setDisableActions(true)
self.disableGlowAnimations = false
self.foregroundCircleLayer.isHidden = true
CATransaction.commit()
}
self.foregroundCircleLayer.add(shrinkAnimation, forKey: "insideShrink")
CATransaction.commit()
}
private func setDisabledBlobWithoutAnimation() {
CATransaction.begin()
CATransaction.disableActions()
self.foregroundCircleLayer.isHidden = false
self.maskCircleLayer.isHidden = false
self.maskProgressLayer.isHidden = true
self.maskGradientLayer.isHidden = false
self.updateGlowAndGradientAnimations(active: self.isActive, previousActive: nil)
self.maskBlobLayer.isHidden = false
self.maskBlobLayer.startAnimating()
CATransaction.commit()
}
private func playConnectionAnimation(active: Bool?, completion: @escaping () -> Void) {
CATransaction.begin()
let initialRotation: CGFloat = CGFloat((self.maskProgressLayer.value(forKeyPath: "presentationLayer.transform.rotation.z") as? NSNumber)?.floatValue ?? 0.0)
let initialStrokeEnd: CGFloat = CGFloat((self.maskProgressLayer.value(forKeyPath: "presentationLayer.strokeEnd") as? NSNumber)?.floatValue ?? 1.0)
self.maskProgressLayer.removeAnimation(forKey: "progressGrowth")
self.maskProgressLayer.removeAnimation(forKey: "progressRotation")
let duration: Double = (1.0 - Double(initialStrokeEnd)) * 0.3
let growthAnimation = CABasicAnimation(keyPath: "strokeEnd")
growthAnimation.fromValue = initialStrokeEnd
growthAnimation.toValue = 1.0
growthAnimation.duration = duration
growthAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn)
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotateAnimation.fromValue = initialRotation
rotateAnimation.toValue = initialRotation + CGFloat.pi * 2
rotateAnimation.isAdditive = true
rotateAnimation.duration = duration
rotateAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn)
let groupAnimation = CAAnimationGroup()
groupAnimation.animations = [growthAnimation, rotateAnimation]
groupAnimation.duration = duration
CATransaction.setCompletionBlock {
CATransaction.begin()
CATransaction.setDisableActions(true)
self.foregroundCircleLayer.isHidden = false
self.maskCircleLayer.isHidden = false
self.maskProgressLayer.isHidden = true
self.maskGradientLayer.isHidden = false
CATransaction.commit()
completion()
self.updateGlowAndGradientAnimations(active: self.isActive, previousActive: nil)
self.maskBlobLayer.isHidden = false
self.maskBlobLayer.startAnimating()
self.maskBlobLayer.animateSpring(from: 0.1 as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: 0.45)
self.updatedActive?(true)
CATransaction.begin()
let shrinkAnimation = CABasicAnimation(keyPath: "transform.scale")
shrinkAnimation.fromValue = 1.0
shrinkAnimation.toValue = 0.0
shrinkAnimation.duration = 0.15
shrinkAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn)
CATransaction.setCompletionBlock {
CATransaction.begin()
CATransaction.setDisableActions(true)
self.foregroundCircleLayer.isHidden = true
CATransaction.commit()
}
self.foregroundCircleLayer.add(shrinkAnimation, forKey: "insideShrink")
CATransaction.commit()
}
self.maskProgressLayer.add(groupAnimation, forKey: "progressCompletion")
CATransaction.commit()
}
var isActive: Bool? = nil {
didSet {
}
}
func updateAnimations() {
if !self.isCurrentlyInHierarchy {
self.foregroundGradientLayer.removeAllAnimations()
self.maskGradientLayer.removeAllAnimations()
self.maskProgressLayer.removeAllAnimations()
self.maskBlobLayer.stopAnimating()
return
} else {
self.maskBlobLayer.startAnimating()
}
self.setupGradientAnimations()
switch self.state {
case .connecting:
self.updatedActive?(false)
if let transition = self.transition {
self.updateGlowScale(nil)
if case let .blob(active) = transition {
playBlobsDisappearanceAnimation(wasActive: active)
} else if case .disabled = transition {
playBlobsDisappearanceAnimation(wasActive: nil)
}
self.transition = nil
}
self.setupProgressAnimations()
self.isActive = false
case let .blob(newActive):
if let transition = self.transition {
if transition == .connecting {
self.playConnectionAnimation(active: newActive) { [weak self] in
if self?.transition == transition {
self?.isActive = newActive
}
}
} else if transition == .disabled {
updateGlowAndGradientAnimations(active: newActive, previousActive: nil)
self.transition = nil
self.isActive = newActive
self.updatedActive?(true)
} else if case let .blob(previousActive) = transition {
updateGlowAndGradientAnimations(active: newActive, previousActive: previousActive)
self.transition = nil
self.isActive = newActive
}
self.transition = nil
} else {
self.maskBlobLayer.startAnimating()
}
case .disabled:
self.updatedActive?(true)
self.isActive = nil
if let transition = self.transition {
if case .connecting = transition {
self.playConnectionAnimation(active: nil) { [weak self] in
self?.isActive = nil
}
} else if case let .blob(previousActive) = transition {
updateGlowAndGradientAnimations(active: nil, previousActive: previousActive)
}
self.transition = nil
} else {
setDisabledBlobWithoutAnimation()
}
break
}
}
var isDark: Bool = false {
didSet {
if self.isDark != oldValue {
self.updateColors()
}
}
}
var isSnap: Bool = false {
didSet {
if self.isSnap != oldValue {
self.updateColors()
}
}
}
var connectingColor: NSColor = NSColor(rgb: 0xb6b6bb) {
didSet {
if self.connectingColor.rgb != oldValue.rgb {
self.updateColors()
}
}
}
func updateColors() {
let previousColor: CGColor = self.backgroundCircleLayer.fillColor ?? greyColor.cgColor
let targetColor: CGColor
if self.isSnap {
targetColor = self.connectingColor.cgColor
} else if self.isDark {
targetColor = secondaryGreyColor.cgColor
} else {
targetColor = greyColor.cgColor
}
self.backgroundCircleLayer.fillColor = targetColor
self.foregroundCircleLayer.fillColor = targetColor
self.growingForegroundCircleLayer.fillColor = targetColor
self.backgroundCircleLayer.animate(from: previousColor, to: targetColor, keyPath: "fillColor", timingFunction: .linear, duration: 0.3)
self.foregroundCircleLayer.animate(from: previousColor, to: targetColor, keyPath: "fillColor", timingFunction: .linear, duration: 0.3)
self.growingForegroundCircleLayer.animate(from: previousColor, to: targetColor, keyPath: "fillColor", timingFunction: .linear, duration: 0.3)
}
func update(state: State, animated: Bool) {
var animated = animated
var hadState = true
if !self.hasState {
hadState = false
self.hasState = true
animated = false
}
if state != self.state || !hadState {
if animated {
self.transition = self.state
}
self.state = state
self.updateAnimations()
}
}
override func layout() {
super.layout()
let center = CGPoint(x: self.bounds.width / 2.0, y: self.bounds.height / 2.0)
let circleFrame = CGRect(origin: CGPoint(x: (self.bounds.width - buttonSize.width) / 2.0, y: (self.bounds.height - buttonSize.height) / 2.0), size: buttonSize)
self.backgroundCircleLayer.frame = circleFrame
self.foregroundCircleLayer.position = center
self.foregroundCircleLayer.bounds = CGRect(origin: CGPoint(), size: CGSize(width: circleFrame.width - progressLineWidth, height: circleFrame.height - progressLineWidth))
self.growingForegroundCircleLayer.position = center
self.growingForegroundCircleLayer.bounds = self.foregroundCircleLayer.bounds
self.maskCircleLayer.frame = circleFrame.insetBy(dx: -progressLineWidth / 2.0, dy: -progressLineWidth / 2.0)
self.maskProgressLayer.frame = circleFrame.insetBy(dx: -3.0, dy: -3.0)
self.foregroundLayer.frame = self.bounds
self.foregroundGradientLayer.frame = self.bounds
self.maskGradientLayer.position = center
self.maskGradientLayer.bounds = NSMakeRect(0, 0, bounds.width - 80, bounds.height - 80)
self.maskLayer.frame = self.bounds
let point = CGPoint(x: (bounds.width - (bounds.width - 170)) / 2.0, y: (bounds.height - (bounds.height - 170)) / 2.0)
self.maskBlobLayer.frame = .init(origin: point, size: NSMakeSize((bounds.width - 170), (bounds.height - 170)))
}
}
final class VoiceChatBlobLayer: SimpleLayer {
private let mediumBlob: BlobLayer
private let bigBlob: BlobLayer
private let maxLevel: CGFloat
private var displayLinkAnimator: ConstantDisplayLinkAnimator?
private var audioLevel: CGFloat = 0.0
var presentationAudioLevel: CGFloat = 0.0
var scaleUpdated: ((CGFloat) -> Void)? {
didSet {
self.bigBlob.scaleUpdated = self.scaleUpdated
}
}
private(set) var isAnimating = false
public typealias BlobRange = (min: CGFloat, max: CGFloat)
public init(
frame: CGRect,
maxLevel: CGFloat,
mediumBlobRange: BlobRange,
bigBlobRange: BlobRange
) {
self.maxLevel = maxLevel
self.mediumBlob = BlobLayer(
pointsCount: 8,
minRandomness: 1,
maxRandomness: 1,
minSpeed: 0.9,
maxSpeed: 4.0,
minScale: mediumBlobRange.min,
maxScale: mediumBlobRange.max
)
self.bigBlob = BlobLayer(
pointsCount: 8,
minRandomness: 1,
maxRandomness: 1,
minSpeed: 1.0,
maxSpeed: 4.4,
minScale: bigBlobRange.min,
maxScale: bigBlobRange.max
)
super.init()
addSublayer(bigBlob)
addSublayer(mediumBlob)
self.frame = frame
displayLinkAnimator = ConstantDisplayLinkAnimator() { [weak self] in
guard let strongSelf = self else { return }
strongSelf.presentationAudioLevel = strongSelf.presentationAudioLevel * 0.9 + strongSelf.audioLevel * 0.1
strongSelf.mediumBlob.level = strongSelf.presentationAudioLevel
strongSelf.bigBlob.level = strongSelf.presentationAudioLevel
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func setColor(_ color: NSColor) {
mediumBlob.setColor(color.withAlphaComponent(0.55))
bigBlob.setColor(color.withAlphaComponent(0.35))
}
public func updateLevel(_ level: CGFloat) {
let normalizedLevel = min(1, max(level / maxLevel, 0))
mediumBlob.updateSpeedLevel(to: normalizedLevel)
bigBlob.updateSpeedLevel(to: normalizedLevel)
audioLevel = normalizedLevel
}
public func startAnimating() {
guard !isAnimating else { return }
isAnimating = true
updateBlobsState()
displayLinkAnimator?.isPaused = false
}
public func stopAnimating() {
self.stopAnimating(duration: 0.15)
}
public func stopAnimating(duration: Double) {
guard isAnimating else { return }
isAnimating = false
updateBlobsState()
displayLinkAnimator?.isPaused = true
}
private func updateBlobsState() {
if isAnimating {
if mediumBlob.frame.size != .zero {
mediumBlob.startAnimating()
bigBlob.startAnimating()
}
} else {
mediumBlob.stopAnimating()
bigBlob.stopAnimating()
}
}
override var frame: CGRect {
didSet {
CATransaction.begin()
CATransaction.disableActions()
mediumBlob.frame = bounds
bigBlob.frame = bounds
updateBlobsState()
CATransaction.commit()
}
}
}
final class BlobLayer: SimpleShapeLayer {
let pointsCount: Int
let smoothness: CGFloat
let minRandomness: CGFloat
let maxRandomness: CGFloat
let minSpeed: CGFloat
let maxSpeed: CGFloat
let minScale: CGFloat
let maxScale: CGFloat
var scaleUpdated: ((CGFloat) -> Void)?
private var blobAnimation: DisplayLinkAnimator?
private let shapeLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.strokeColor = nil
return layer
}()
var level: CGFloat = 0 {
didSet {
CATransaction.begin()
CATransaction.setDisableActions(true)
let lv = minScale + (maxScale - minScale) * level
shapeLayer.transform = CATransform3DMakeScale(lv, lv, 1)
if level != oldValue {
self.scaleUpdated?(level)
}
CATransaction.commit()
}
}
private var speedLevel: CGFloat = 0
private var lastSpeedLevel: CGFloat = 0
private var transition: CGFloat = 0 {
didSet {
guard let currentPoints = currentPoints else { return }
let width = self.bounds.width
let smoothness = self.smoothness
let signal: Signal<CGPath, NoError> = Signal { subscriber in
subscriber.putNext(.smoothCurve(through: currentPoints, length: width, smoothness: smoothness))
subscriber.putCompletion()
return EmptyDisposable
}
|> runOn(resourcesQueue)
|> deliverOnMainQueue
_ = signal.start(next: { [weak self] path in
self?.shapeLayer.path = path
})
}
}
private var fromPoints: [CGPoint]?
private var toPoints: [CGPoint]?
private var currentPoints: [CGPoint]? {
guard let fromPoints = fromPoints, let toPoints = toPoints else { return nil }
return fromPoints.enumerated().map { offset, fromPoint in
let toPoint = toPoints[offset]
return CGPoint(
x: fromPoint.x + (toPoint.x - fromPoint.x) * transition,
y: fromPoint.y + (toPoint.y - fromPoint.y) * transition
)
}
}
init(
pointsCount: Int,
minRandomness: CGFloat,
maxRandomness: CGFloat,
minSpeed: CGFloat,
maxSpeed: CGFloat,
minScale: CGFloat,
maxScale: CGFloat
) {
self.pointsCount = pointsCount
self.minRandomness = minRandomness
self.maxRandomness = maxRandomness
self.minSpeed = minSpeed
self.maxSpeed = maxSpeed
self.minScale = minScale
self.maxScale = maxScale
let angle = (CGFloat.pi * 2) / CGFloat(pointsCount)
self.smoothness = ((4 / 3) * tan(angle / 4)) / sin(angle / 2) / 2
super.init()
self.addSublayer(shapeLayer)
shapeLayer.transform = CATransform3DMakeScale(minScale, minScale, 1)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setColor(_ color: NSColor) {
shapeLayer.fillColor = color.cgColor
}
func updateSpeedLevel(to newSpeedLevel: CGFloat) {
speedLevel = max(speedLevel, newSpeedLevel)
}
func startAnimating() {
animateToNewShape()
}
func stopAnimating() {
fromPoints = currentPoints
toPoints = nil
blobAnimation = nil
}
private func animateToNewShape() {
if blobAnimation != nil {
fromPoints = currentPoints
toPoints = nil
blobAnimation = nil
}
if fromPoints == nil {
fromPoints = generateNextBlob(for: bounds.size)
}
if toPoints == nil {
toPoints = generateNextBlob(for: bounds.size)
}
let duration = CGFloat(1 / (minSpeed + (maxSpeed - minSpeed) * speedLevel))
let fromValue: CGFloat = 0
let toValue: CGFloat = 1
let animation = DisplayLinkAnimator(duration: Double(duration), from: fromValue, to: toValue, update: { [weak self] value in
self?.transition = value
}, completion: { [weak self] in
guard let `self` = self else {
return
}
self.fromPoints = self.currentPoints
self.toPoints = nil
self.blobAnimation = nil
self.animateToNewShape()
})
self.blobAnimation = animation
lastSpeedLevel = speedLevel
speedLevel = 0
}
private func generateNextBlob(for size: CGSize) -> [CGPoint] {
let randomness = minRandomness + (maxRandomness - minRandomness) * speedLevel
return blob(pointsCount: pointsCount, randomness: randomness)
.map {
return CGPoint(
x: $0.x * CGFloat(size.width),
y: $0.y * CGFloat(size.height)
)
}
}
func blob(pointsCount: Int, randomness: CGFloat) -> [CGPoint] {
let angle = (CGFloat.pi * 2) / CGFloat(pointsCount)
let rgen = { () -> CGFloat in
let accuracy: UInt32 = 1000
let random = arc4random_uniform(accuracy)
return CGFloat(random) / CGFloat(accuracy)
}
let rangeStart: CGFloat = 1 / (1 + randomness / 10)
let startAngle = angle * CGFloat(arc4random_uniform(100)) / CGFloat(100)
let points = (0 ..< pointsCount).map { i -> CGPoint in
let randPointOffset = (rangeStart + CGFloat(rgen()) * (1 - rangeStart)) / 2
let angleRandomness: CGFloat = angle * 0.1
let randAngle = angle + angle * ((angleRandomness * CGFloat(arc4random_uniform(100)) / CGFloat(100)) - angleRandomness * 0.5)
let pointX = sin(startAngle + CGFloat(i) * randAngle)
let pointY = cos(startAngle + CGFloat(i) * randAngle)
return CGPoint(
x: pointX * randPointOffset,
y: pointY * randPointOffset
)
}
return points
}
override var frame: CGRect {
didSet {
shapeLayer.position = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
}
}
}
|
gpl-2.0
|
42e3a4515d335d892e75911c01bee9e4
| 36.497132 | 332 | 0.629443 | 4.861428 | false | false | false | false |
forgot/FAAlertController
|
Source/Views/FAAlertControllerBackdropView.swift
|
1
|
2668
|
//
// FAAlertControllerBackdropView.swift
// FAPlacemarkPicker
//
// Created by Jesse Cox on 8/21/16.
// Copyright © 2016 Apprhythmia LLC. All rights reserved.
//
import UIKit
class FAAlertControllerBackdropView: UIView {
let backdrop = BlendableBackdropView(frame: .zero, target: nil, blendMode: FAAlertControllerAppearanceManager.sharedInstance.backdropBlendMode)
let effectView = UIVisualEffectView(effect: FAAlertControllerAppearanceManager.sharedInstance.blurEffect)
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
backdrop.translatesAutoresizingMaskIntoConstraints = false
addSubview(backdrop)
backdrop.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
backdrop.heightAnchor.constraint(equalTo: heightAnchor).isActive = true
backdrop.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
backdrop.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
effectView.translatesAutoresizingMaskIntoConstraints = false
addSubview(effectView)
effectView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
effectView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
effectView.topAnchor.constraint(equalTo: topAnchor).isActive = true
effectView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
override func layoutSubviews() {
super.layoutSubviews()
backdrop.setNeedsDisplay()
FAAlertControllerAppearanceManager.sharedInstance.backdropView = self
}
}
class BlendableBackdropView: BlendableView {
var blendColor: UIColor = FAAlertControllerAppearanceManager.sharedInstance.backdropColor
override func draw(_ rect: CGRect) {
super.draw(rect)
let context = UIGraphicsGetCurrentContext()!
context.saveGState()
let _rect = CGRect(x: 0, y: 0, width: rect.width, height: rect.height)
// Draw and fill dimming path
let dimmingPath = UIBezierPath(rect: _rect)
let color = UIColor(white: 0, alpha: 0.4)
color.setFill()
dimmingPath.fill()
context.setBlendMode(blendMode)
// Draw and fill overlay path
let overlayPath = UIBezierPath(rect: _rect)
blendColor.setFill()
overlayPath.fill()
context.restoreGState()
}
}
|
mit
|
032fa568df11379884aac05b1096b631
| 31.52439 | 147 | 0.676415 | 5.281188 | false | false | false | false |
tjw/swift
|
test/decl/protocol/special/coding/enum_coding_key.swift
|
4
|
4082
|
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown
// Enums with no raw type conforming to CodingKey should get implicit derived
// conformance of methods.
enum NoRawTypeKey : CodingKey {
case a, b, c
}
let _ = NoRawTypeKey.a.stringValue
let _ = NoRawTypeKey(stringValue: "a")
let _ = NoRawTypeKey.a.intValue
let _ = NoRawTypeKey(intValue: 0)
// Enums with raw type of String conforming to CodingKey should get implicit
// derived conformance of methods.
enum StringKey : String, CodingKey {
case a = "A", b, c = "Foo"
}
let _ = StringKey.a.stringValue
let _ = StringKey(stringValue: "A")
let _ = StringKey.a.intValue
let _ = StringKey(intValue: 0)
// Enums with raw type of Int conforming to CodingKey should get implicit
// derived conformance of methods.
enum IntKey : Int, CodingKey {
case a = 3, b, c = 1
}
let _ = IntKey.a.stringValue
let _ = IntKey(stringValue: "a")
let _ = IntKey.a.intValue
let _ = IntKey(intValue: 3)
// Enums with a different raw value conforming to CodingKey should not get
// implicit derived conformance.
enum Int8Key : Int8, CodingKey { // expected-error {{type 'Int8Key' does not conform to protocol 'CodingKey'}}
case a = -1, b = 0, c = 1
}
// Structs conforming to CodingKey should not get implicit derived conformance.
struct StructKey : CodingKey { // expected-error {{type 'StructKey' does not conform to protocol 'CodingKey'}}
// expected-note@-1 {{candidate has non-matching type '()'}}
// expected-note@-2 {{candidate has non-matching type '()'}}
}
// Classes conforming to CodingKey should not get implict derived conformance.
class ClassKey : CodingKey { //expected-error {{type 'ClassKey' does not conform to protocol 'CodingKey'}}
// expected-note@-1 {{candidate has non-matching type '()'}}
// expected-note@-2 {{candidate has non-matching type '()'}}
}
// Types which are valid for CodingKey derived conformance should not get that
// derivation unless they explicitly conform to CodingKey.
enum X { case a }
enum Y : String { case a } // expected-note {{property 'rawValue' is implicitly declared}}
enum Z : Int { case a } // expected-note {{property 'rawValue' is implicitly declared}}
let _ = X.a.stringValue // expected-error {{value of type 'X' has no member 'stringValue'}}
let _ = Y.a.stringValue // expected-error {{value of type 'Y' has no member 'stringValue'}}
let _ = Z.a.stringValue // expected-error {{value of type 'Z' has no member 'stringValue'}}
let _ = X(stringValue: "a") // expected-error {{'X' cannot be constructed because it has no accessible initializers}}
let _ = Y(stringValue: "a") // expected-error {{incorrect argument label in call (have 'stringValue:', expected 'rawValue:')}}
let _ = Z(stringValue: "a") // expected-error {{incorrect argument label in call (have 'stringValue:', expected 'rawValue:')}}
let _ = X.a.intValue // expected-error {{value of type 'X' has no member 'intValue'}}
let _ = Y.a.intValue // expected-error {{value of type 'Y' has no member 'intValue'; did you mean 'rawValue'?}}
let _ = Z.a.intValue // expected-error {{value of type 'Z' has no member 'intValue'; did you mean 'rawValue'?}}
let _ = X(intValue: 0) // expected-error {{'X' cannot be constructed because it has no accessible initializers}}
let _ = Y(intValue: 0) // expected-error {{incorrect argument label in call (have 'intValue:', expected 'rawValue:')}}
let _ = Z(intValue: 0) // expected-error {{incorrect argument label in call (have 'intValue:', expected 'rawValue:')}}
// Types which are valid for CodingKey derived conformance should get derivation
// through extensions.
enum X2 { case a }
enum Y2 : String { case a }
enum Z2 : Int { case a }
extension X2 : CodingKey {}
extension Y2 : CodingKey {}
extension Z2 : CodingKey {}
let _ = X2.a.stringValue
let _ = Y2.a.stringValue
let _ = Z2.a.stringValue
let _ = X2(stringValue: "a")
let _ = Y2(stringValue: "a")
let _ = Z2(stringValue: "a")
let _ = X2.a.intValue
let _ = Y2.a.intValue
let _ = Z2.a.intValue
let _ = X2(intValue: 0)
let _ = Y2(intValue: 0)
let _ = Z2(intValue: 0)
|
apache-2.0
|
f3dae2148f81d4e25440a83af0994421
| 40.232323 | 126 | 0.693533 | 3.644643 | false | false | false | false |
aiwalle/LiveProject
|
LiveProject/Home/View/HomeViewCell.swift
|
1
|
3271
|
//
// HomeViewCell.swift
// LiveProject
//
// Created by liang on 2017/8/3.
// Copyright © 2017年 liang. All rights reserved.
//
import UIKit
class HomeViewCell: UICollectionViewCell {
var anchorModel : AnchorModel? {
didSet {
// work
// albumImageView.setImage(anchorModel!.isEvenIndex ? anchorModel?.pic74 : anchorModel?.pic51, "home_pic_default")
liveImageView.isHidden = anchorModel?.live == 0
nickNameLabel.text = anchorModel?.name
onlinePeopleLabel.setTitle("\(anchorModel?.focus ?? 0)", for: .normal)
}
}
fileprivate lazy var albumImageView: UIImageView = {
let albumImageView = UIImageView()
albumImageView.image = UIImage(named: "home_pic_default")
return albumImageView
}()
fileprivate lazy var liveImageView: UIImageView = {
let liveImageView = UIImageView()
liveImageView.image = UIImage(named: "home_icon_live")
return liveImageView
}()
fileprivate lazy var nickNameLabel: UILabel = {
let nickNameLabel = UILabel()
nickNameLabel.textColor = .white
nickNameLabel.font = UIFont.systemFont(ofSize: 12.0)
nickNameLabel.text = "这里是一只猪的直播间"
return nickNameLabel
}()
fileprivate lazy var onlinePeopleLabel: UIButton = {
let onlinePeopleLabel = UIButton()
onlinePeopleLabel.setImage(UIImage(named: "home_icon_people"), for: .normal)
onlinePeopleLabel.setTitle("4311", for: .normal)
onlinePeopleLabel.titleLabel?.font = UIFont.systemFont(ofSize: 10.0)
return onlinePeopleLabel
}()
class func cellWithCollectionView(_ collectionView : UICollectionView, indexPath : NSIndexPath) -> HomeViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kAnchorControllerCellID, for: indexPath as IndexPath) as! HomeViewCell
return cell
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
albumImageView.frame = self.bounds
let liveImageSize = UIImage(named: "home_icon_live")?.size
liveImageView.frame = CGRect(x: self.bounds.width - kAnchorCellSubviewMargin - liveImageSize!.width, y: kAnchorCellSubviewMargin, width: liveImageSize!.width, height: liveImageSize!.height)
nickNameLabel.frame = CGRect(x: kAnchorCellSubviewMargin, y: self.bounds.height - 30, width: self.bounds.width * 0.6, height: 22)
onlinePeopleLabel.frame = CGRect(x: self.nickNameLabel.frame.maxX + kAnchorCellSubviewMargin, y: self.bounds.height - 30, width: self.bounds.width * 0.3, height: 22)
onlinePeopleLabel.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0)
}
}
extension HomeViewCell {
fileprivate func setupUI() {
contentView.addSubview(albumImageView)
contentView.addSubview(liveImageView)
contentView.addSubview(nickNameLabel)
contentView.addSubview(onlinePeopleLabel)
}
}
|
mit
|
88115fd308abda8697789eb0dd572223
| 35.088889 | 197 | 0.661022 | 4.64 | false | false | false | false |
devlucky/Kakapo
|
Examples/NewsFeed/Pods/Fakery/Source/Generators/Generator.swift
|
1
|
2043
|
import Foundation
open class Generator {
public struct Constants {
public static let uppercaseLetters = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters)
public static let letters = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".characters)
public static let numbers = Array("0123456789".characters)
}
let parser: Parser
let dateFormatter: DateFormatter
public required init(parser: Parser) {
self.parser = parser
dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
}
open func generate(_ key: String) -> String {
return parser.fetch(key)
}
// MARK: - Filling
open func numerify(_ string: String) -> String {
let count = UInt32(Constants.numbers.count)
return String(string.characters.enumerated().map {
(index, item) in
let numberIndex = index == 0 ? arc4random_uniform(count - 1) :
arc4random_uniform(count)
let char = Constants.numbers[Int(numberIndex)]
return String(item) == "#" ? char : item
})
}
open func letterify(_ string: String) -> String {
return String(string.characters.enumerated().map {
(index, item) in
let count = UInt32(Constants.uppercaseLetters.count)
let char = Constants.uppercaseLetters[Int(arc4random_uniform(count))]
return String(item) == "?" ? char : item
})
}
open func bothify(_ string: String) -> String {
return letterify(numerify(string))
}
open func alphaNumerify(_ string: String) -> String {
return string.replacingOccurrences(of: "[^A-Za-z0-9_]",
with: "",
options: NSString.CompareOptions.regularExpression,
range: nil)
}
open func randomWordsFromKey(_ key: String) -> String {
var string = ""
var list = [String]()
if let wordsList = parser.fetchRaw(key)?.arrayObject {
for words in wordsList {
if let item = (words as! [String]).random() {
list.append(item)
}
}
string = list.joined(separator: " ")
}
return string
}
}
|
mit
|
2615f551ae61d3466d42dbcabda54d3a
| 26.24 | 104 | 0.652472 | 4.229814 | false | false | false | false |
trupin/Beaver
|
BeaverTestKit/Type/StateMock.swift
|
2
|
684
|
import Beaver
public struct StateMock: State {
public var name: String
public init() {
self.name = "SuccessStateMock"
}
public init(name: String) {
self.name = name
}
public static func ==(lhs: StateMock, rhs: StateMock) -> Bool {
return lhs.name == rhs.name
}
}
public struct AppStateMock: State {
public var childState: StateMock?
public init() {
self.childState = StateMock()
}
public init(childState: StateMock?) {
self.childState = childState
}
public static func ==(lhs: AppStateMock, rhs: AppStateMock) -> Bool {
return lhs.childState == rhs.childState
}
}
|
mit
|
2489dc16b56256419b4a3856c0d5329e
| 19.727273 | 73 | 0.602339 | 3.976744 | false | false | false | false |
swift-lang/swift-k
|
tests/stress/internals/x_recursion.swift
|
2
|
1453
|
/*
Linear tail recursion.
Expect linear growth only, so usual loop numbers match
as for earlier scripts.
stats: 1K -> 25s real (i5 8gb)
10K -> (10% ram 8gb in use by java)
Uncaught exception: java.lang.StackOverflowError in vdl:unitstart @ x_recursion.kml, line: 45
java.lang.StackOverflowError
at java.lang.String.valueOf(String.java:2959)
at org.globus.cog.karajan.util.ThreadingContext.toString(ThreadingContext.java:87)
at org.globus.cog.karajan.util.ThreadingContext.toString(ThreadingContext.java:87)
...
Exception is: java.lang.StackOverflowError
Near Karajan line: vdl:unitstart @ x_recursion.kml, line: 45
Another uncaught exception while handling an uncaught exception.
java.lang.StackOverflowError
at org.globus.cog.karajan.workflow.nodes.FlowNode.failImmediately(FlowNode.java:77)
at org.globus.cog.karajan.workflow.nodes.FlowNode.failed(FlowNode.java:245)
...
The initial exception was
java.lang.StackOverflowError
at java.lang.String.valueOf(String.java:2959)
at org.globus.cog.karajan.util.ThreadingContext.toString(ThreadingContext.java:87)
at org.globus.cog.karajan.util.ThreadingContext.toString(ThreadingContext.java:87)
100K -> ?
#NIGHTLY 1000 10000
#WEEKLY 1000 10000 100000
*/
int limit = @toint(@arg("loops"));
(int out) sum (int n){
if ( n == 0 ){
out = 0;
}else{
out = n + sum( n-1 );
}
}
int result = sum(limit);
tracef("Sum(%i) = %i \n", limit, result);
|
apache-2.0
|
53bbf0e7c55e3ece3f36f10149c1b654
| 31.311111 | 93 | 0.734343 | 2.995876 | false | false | false | false |
uber/rides-ios-sdk
|
source/UberRidesTests/RequestLayerTests.swift
|
1
|
15432
|
//
// RequestLayerTests.swift
// UberRidesTests
//
// Copyright © 2016 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import OHHTTPStubs
import UberCore
@testable import UberRides
class RequestLayerTests: XCTestCase {
var client: RidesClient!
var headers: [AnyHashable: Any]!
let timeout: Double = 10
override func setUp() {
super.setUp()
Configuration.plistName = "testInfo"
Configuration.restoreDefaults()
Configuration.shared.isSandbox = true
headers = ["Content-Type": "application/json"]
client = RidesClient()
}
override func tearDown() {
OHHTTPStubs.removeAllStubs()
Configuration.restoreDefaults()
super.tearDown()
}
/**
Test 200 success response
*/
func test200Response() {
stub(condition: isHost("sandbox-api.uber.com")) { _ in
return OHHTTPStubsResponse(fileAtPath:OHPathForFile("getProductID.json", type(of: self))!, statusCode:200, headers:self.headers)
}
let expectation = self.expectation(description: "200 success response")
let endpoint = Products.getProduct(productID: productID)
guard let request = Request(session: client.session, endpoint: endpoint) else {
XCTFail("Unable to create request")
return
}
request.execute({ response in
XCTAssertEqual(response.statusCode, 200)
XCTAssertNil(response.error)
expectation.fulfill()
})
waitForExpectations(timeout: timeout, handler: { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
request.cancelTasks()
})
}
/**
Test 401 authorization error response.
*/
func test401Error() {
let message = "Invalid OAuth 2.0 credentials provided."
let code = "unauthorized"
stub(condition: isHost("sandbox-api.uber.com")) { _ in
let json = ["message": message, "code": code]
return OHHTTPStubsResponse(jsonObject: json, statusCode: 401, headers: self.headers)
}
let expectation = self.expectation(description: "401 error response")
let endpoint = Products.getProduct(productID: productID)
guard let request = Request(session: client.session, endpoint: endpoint) else {
XCTFail("Unable to create request")
return
}
request.execute({ response in
XCTAssertEqual(response.statusCode, 401)
XCTAssertNotNil(response.error)
XCTAssertTrue(response.error is UberClientError)
XCTAssertEqual(response.error!.title, message)
XCTAssertEqual(response.error!.code, code)
XCTAssertNil(response.error!.meta)
expectation.fulfill()
})
waitForExpectations(timeout: timeout, handler: { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
request.cancelTasks()
})
}
/**
Test 409 surge error response.
*/
func test409Error() {
stub(condition: isHost("sandbox-api.uber.com")) { _ in
let json = ["meta": ["surge_confirmation": ["href": "api.uber.com/v1/surge-confirmations/abc", "surge_confirmation_id": "abc"]]]
return OHHTTPStubsResponse(jsonObject: json, statusCode: 409, headers: self.headers)
}
let expectation = self.expectation(description: "409 error response")
let endpoint = Products.getProduct(productID: productID)
guard let request = Request(session: client.session, endpoint: endpoint) else {
XCTFail("Unable to create request")
return
}
request.execute({ response in
XCTAssertEqual(response.statusCode, 409)
XCTAssertNotNil(response.error)
XCTAssertTrue(response.error is UberClientError)
XCTAssertNotNil(response.error!.meta)
let meta = response.error!.meta! as! [String: [String: String]]
XCTAssertEqual(meta["surge_confirmation"]!["href"], "api.uber.com/v1/surge-confirmations/abc")
XCTAssertEqual(meta["surge_confirmation"]!["surge_confirmation_id"], "abc")
expectation.fulfill()
})
waitForExpectations(timeout: timeout, handler: { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
request.cancelTasks()
})
}
/**
Test 422 lat/long validation error response.
*/
func test422ValidationError() {
let message = "Invalid request."
let code = "validation_failed"
let fields = ["latitude": ["Must be between -90.0 and 90.0"], "longitude": ["Must be between -90.0 and 90.0"]]
stub(condition: isHost("sandbox-api.uber.com")) { _ in
let json = ["message": message, "code": code, "fields": fields] as [String : Any]
return OHHTTPStubsResponse(jsonObject: json, statusCode: 422, headers: self.headers)
}
let expectation = self.expectation(description: "422 error response")
let endpoint = Products.getProduct(productID: productID)
guard let request = Request(session: client.session, endpoint: endpoint) else {
XCTFail("Unable to create request")
return
}
request.execute({ response in
XCTAssertEqual(response.statusCode, 422)
XCTAssertNotNil(response.error)
XCTAssertTrue(response.error is UberClientError)
XCTAssertEqual(response.error!.title, message)
XCTAssertEqual(response.error!.code, code)
let fields = response.error!.meta! as! [String: [String]]
XCTAssertEqual(fields.count, 2)
XCTAssertEqual(fields["latitude"]![0], "Must be between -90.0 and 90.0")
XCTAssertEqual(fields["longitude"]![0], "Must be between -90.0 and 90.0")
expectation.fulfill()
})
waitForExpectations(timeout: timeout, handler: { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
request.cancelTasks()
})
}
/**
Test 422 distance exceeded error response.
*/
func test422DistanceExceededError() {
let message = "Distance between two points exceeds 100 miles."
let code = "distance_exceeded"
let fields = ["start_latitude": [message], "end_latitude": [message], "start_longitude": [message], "end_longitude": [message]]
stub(condition: isHost("sandbox-api.uber.com")) { _ in
let json = ["message": message, "code": code, "fields": fields] as [String : Any]
return OHHTTPStubsResponse(jsonObject: json, statusCode: 422, headers: self.headers)
}
let expectation = self.expectation(description: "422 error response")
let endpoint = Products.getProduct(productID: productID)
guard let request = Request(session: client.session, endpoint: endpoint) else {
XCTFail("Unable to create request")
return
}
request.execute({ response in
XCTAssertEqual(response.statusCode, 422)
XCTAssertNotNil(response.error)
XCTAssertTrue(response.error is UberClientError)
XCTAssertEqual(response.error!.title, message)
XCTAssertEqual(response.error!.code, code)
let fields = response.error!.meta! as! [String: [String]]
XCTAssertEqual(fields.count, 4)
XCTAssertEqual(fields["start_latitude"]![0], message)
XCTAssertEqual(fields["start_longitude"]![0], message)
XCTAssertEqual(fields["end_latitude"]![0], message)
XCTAssertEqual(fields["end_longitude"]![0], message)
expectation.fulfill()
})
waitForExpectations(timeout: timeout, handler: { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
request.cancelTasks()
})
}
/**
Test 422 same pickup and dropoff error response.
*/
func test422SamePickupDropoffError() {
let code = "same_pickup_dropoff"
let message = "Pickup and Dropoff can't be the same."
stub(condition: isHost("sandbox-api.uber.com")) { _ in
let json = ["meta": [], "errors": [["status": 422, "code": code, "title": message]]]
return OHHTTPStubsResponse(jsonObject: json, statusCode: 409, headers: self.headers)
}
let expectation = self.expectation(description: "422 error response")
let endpoint = Products.getProduct(productID: productID)
guard let request = Request(session: client.session, endpoint: endpoint) else {
XCTFail("Unable to create request")
return
}
request.execute({ response in
XCTAssertEqual(response.statusCode, 409)
XCTAssertNotNil(response.error)
XCTAssertTrue(response.error is UberClientError)
XCTAssertNil(response.error!.meta)
XCTAssertEqual(response.error!.errors!.count, 1)
let error = response.error!.errors![0]
XCTAssertEqual(error.status, 422)
XCTAssertEqual(error.code, code)
XCTAssertEqual(error.title, message)
expectation.fulfill()
})
waitForExpectations(timeout: timeout, handler: { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
request.cancelTasks()
})
}
/**
Test 500 internal server error response.
*/
func test500Error() {
let message = "Unexpected internal server error occurred."
let code = "internal_server_error"
stub(condition: isHost("sandbox-api.uber.com")) { _ in
let json = ["message": message, "code": code]
return OHHTTPStubsResponse(jsonObject: json, statusCode: 500, headers: self.headers)
}
let expectation = self.expectation(description: "500 error response")
let endpoint = Products.getProduct(productID: productID)
guard let request = Request(session: client.session, endpoint: endpoint) else {
XCTFail("Unable to create request")
return
}
request.execute({ response in
XCTAssertEqual(response.statusCode, 500)
XCTAssertNotNil(response.error)
XCTAssertTrue(response.error is UberServerError)
XCTAssertEqual(response.error!.title, message)
XCTAssertEqual(response.error!.code, code)
XCTAssertNil(response.error!.meta)
expectation.fulfill()
})
waitForExpectations(timeout: timeout, handler: { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
request.cancelTasks()
})
}
/**
Test 503 service unavailable error response.
*/
func test503Error() {
let message = "Service temporarily unavailable."
let code = "service_unavailable"
stub(condition: isHost("sandbox-api.uber.com")) { _ in
let json = ["message": message, "code": code]
return OHHTTPStubsResponse(jsonObject: json, statusCode: 503, headers: self.headers)
}
let expectation = self.expectation(description: "503 error response")
let endpoint = Products.getProduct(productID: productID)
guard let request = Request(session: client.session, endpoint: endpoint) else {
XCTFail("Unable to create request")
return
}
request.execute({ response in
XCTAssertEqual(response.statusCode, 503)
XCTAssertNotNil(response.error)
XCTAssertTrue(response.error is UberServerError)
XCTAssertEqual(response.error!.title, message)
XCTAssertEqual(response.error!.code, code)
XCTAssertNil(response.error!.meta)
expectation.fulfill()
})
waitForExpectations(timeout: timeout, handler: { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
request.cancelTasks()
})
}
/**
* Test no network error response - unknown error.
*/
func testNoNetworkError() {
stub(condition: isHost("sandbox-api.uber.com")) { _ in
let notConnectedError = NSError(domain: NSURLErrorDomain, code: Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue), userInfo: nil)
return OHHTTPStubsResponse(error:notConnectedError)
}
let expectation = self.expectation(description: "No network error response")
let endpoint = Products.getProduct(productID: productID)
guard let request = Request(session: client.session, endpoint: endpoint) else {
XCTFail("Unable to create request")
return
}
request.execute({ response in
XCTAssertEqual(response.statusCode, 0)
XCTAssertNotNil(response.error)
XCTAssertTrue(response.error is UberUnknownError)
XCTAssertEqual(response.error!.title, NSURLErrorDomain)
XCTAssertEqual(response.error!.status, Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue))
XCTAssertNil(response.error!.meta)
expectation.fulfill()
})
waitForExpectations(timeout: timeout, handler: { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
request.cancelTasks()
})
}
}
|
mit
|
435c80cf2674d957a695b3fe85068abf
| 38.976684 | 154 | 0.603914 | 5.118076 | false | true | false | false |
dcutting/song
|
Sources/Song/Interpreter/Expression+Evaluation.swift
|
1
|
13805
|
var _stdIn: StdIn = DefaultStdIn()
var _stdOut: StdOut = DefaultStdOut()
var _stdErr: StdOut = DefaultStdErr()
public let rootContext: Context = [
"Eq": .builtIn(evaluateEq),
"Neq": .builtIn(evaluateNeq),
"Not": .builtIn(evaluateNot),
"And": .builtIn(evaluateAnd),
"Or": .builtIn(evaluateOr),
"number": .builtIn(evaluateNumberConstructor),
"string": .builtIn(evaluateStringConstructor),
"truncate": .builtIn(evaluateTruncateConstructor),
"+": .builtIn(evaluatePlus),
"-": .builtIn(evaluateMinus),
"*": .builtIn(evaluateTimes),
"/": .builtIn(evaluateDividedBy),
"Mod": .builtIn(evaluateMod),
"Div": .builtIn(evaluateDiv),
"<": .builtIn(evaluateLessThan),
">": .builtIn(evaluateGreaterThan),
"<=": .builtIn(evaluateLessThanOrEqual),
">=": .builtIn(evaluateGreaterThanOrEqual),
"in": .builtIn(evaluateIn),
"out": .builtIn(evaluateOut),
"err": .builtIn(evaluateErr),
]
extension Expression {
public func evaluate(context: Context = rootContext) throws -> Expression {
let result: Expression
do {
result = try evaluate(expression: self, context: context)
} catch let error as EvaluationError {
throw EvaluationError.cannotEvaluate(self, error)
}
return result
}
private func evaluate(expression: Expression, context: Context) throws -> Expression {
switch expression {
case .bool, .number, .char, .ignore, .closure, .tailEval, .builtIn:
return expression
case let .list(exprs):
let evaluated = try exprs.map { try $0.evaluate(context: context) }
return .list(evaluated)
case let .cons(heads, tail):
let evaluatedHeads = try heads.map { try $0.evaluate(context: context) }
let evaluatedTail = try tail.evaluate(context: context)
guard case var .list(items) = evaluatedTail else { throw EvaluationError.notAList(evaluatedTail) }
items.insert(contentsOf: evaluatedHeads, at: 0)
return .list(items)
case let .name(variable):
return try evaluateVariable(variable: variable, context)
case let .function(function):
return try evaluate(expression: expression, function: function, context: context)
case let .assign(variable, value):
return .assign(variable: variable, value: try value.evaluate(context: context))
case let .scope(statements):
return try evaluateScope(statements: statements, context: context)
case let .call(name, arguments):
let evalArgs = try evaluate(arguments: arguments, context: context)
var intermediate = try evaluateCall(name: name, arguments: evalArgs, context: context)
// Trampoline tail calls.
while case let .tailEval(tailExpr, tailArgs) = intermediate {
intermediate = try evaluateCallAnonymous(closure: tailExpr, arguments: tailArgs, callingContext: context)
}
return intermediate
case let .eval(function, arguments):
let evalArgs = try evaluate(arguments: arguments, context: context)
return try evaluateCallAnonymous(closure: function, arguments: evalArgs, callingContext: context)
}
}
private func evaluate(arguments: [Expression], context: Context) throws -> [Expression] {
return try arguments.map { try $0.evaluate(context: context) }
}
private func evaluate(expression: Expression, function: Function, context: Context) throws -> Expression {
try validatePatterns(function)
var finalContext = context
let name = function.name
var existingClauses = [Expression]()
var existingContext = Context()
if let name = name, let existingClosure = context[name] {
guard case let .closure(_, clauses, closureContext) = existingClosure else {
throw EvaluationError.notAClosure(expression)
}
existingClauses = clauses
existingContext = closureContext
finalContext.removeValue(forKey: name)
}
existingClauses.append(expression)
finalContext.merge(existingContext) { l, r in l }
return .closure(name, existingClauses, finalContext)
}
private func validatePatterns(_ function: Function) throws {
try function.patterns.forEach { pattern in
if case .number(Number.float) = pattern {
throw EvaluationError.patternsCannotBeFloats(pattern)
}
}
}
private func evaluateVariable(variable: String, _ context: Context) throws -> Expression {
guard
let value = context[variable]
else { throw EvaluationError.symbolNotFound(variable) }
return value
}
private func evaluateCallAnonymous(closure: Expression, arguments: [Expression], callingContext: Context) throws -> Expression {
let evaluatedClosure = try closure.evaluate(context: callingContext)
switch evaluatedClosure {
case let .closure(_, functions, closureContext):
for function in functions {
do {
return try evaluateCallFunction(function: function, closureContext: closureContext, arguments: arguments, callingContext: callingContext, closure: evaluatedClosure)
} catch EvaluationError.signatureMismatch {}
}
throw EvaluationError.signatureMismatch(arguments)
case let .builtIn(builtIn):
return try builtIn(arguments, callingContext)
default:
throw EvaluationError.notAFunction(closure)
}
}
private func evaluateCallFunction(function: Expression, closureContext: Context, arguments: [Expression], callingContext: Context, closure: Expression) throws -> Expression {
switch function {
case let .function(function):
let extendedContext = try matchParameters(closureContext: closureContext, parameters: function.patterns, arguments: arguments)
let finalContext = callingContext.merging(extendedContext) { l, r in r }
let whenEvaluated = try function.when.evaluate(context: finalContext)
guard case .bool = whenEvaluated else { throw EvaluationError.notABoolean(function.when) }
guard case .yes = whenEvaluated else { throw EvaluationError.signatureMismatch(arguments) }
let body = function.body
// Detect tail calls if present.
if case let .call(name, arguments) = body {
let evalArgs = try evaluate(arguments: arguments, context: finalContext)
let expr = try evaluateVariable(variable: name, finalContext)
return .tailEval(expr, evalArgs)
} else if case let .scope(statements) = body {
let (last, scopeContext) = try semiEvaluateScope(statements: statements, context: finalContext)
let result: Expression
if case let .call(name, arguments) = last {
let evalArgs = try evaluate(arguments: arguments, context: finalContext)
let expr = try evaluateVariable(variable: name, finalContext)
result = .tailEval(expr, evalArgs)
} else {
result = try last.evaluate(context: scopeContext)
}
return result
} else {
return try body.evaluate(context: finalContext)
}
default:
throw EvaluationError.notAFunction(closure)
}
}
private func matchParameters(closureContext: Context, parameters: [Expression], arguments: [Expression]) throws -> Context {
guard parameters.count <= arguments.count else { throw EvaluationError.signatureMismatch(arguments) }
guard arguments.count <= parameters.count else { throw EvaluationError.signatureMismatch(arguments) }
var extendedContext = closureContext
var patternEqualityContext = Context()
for (p, a) in zip(parameters, arguments) {
(extendedContext, patternEqualityContext) = try matchAndExtend(context: extendedContext, parameter: p, value: a, patternEqualityContext: patternEqualityContext)
}
return extendedContext
}
private func matchAndExtend(context: Context, parameter: Expression, value: Expression, patternEqualityContext: Context) throws -> (Context, Context) {
var extendedContext = context
var patternEqualityContext = patternEqualityContext
switch parameter {
case .ignore:
() // Do nothing
case .name(let name):
if let existingValue = patternEqualityContext[name] {
if case .number(let numberValue) = existingValue {
if case .float = numberValue {
throw EvaluationError.patternsCannotBeFloats(value)
}
}
if existingValue != value {
throw EvaluationError.signatureMismatch([value])
}
}
patternEqualityContext[name] = value
extendedContext = extendContext(context: extendedContext, name: name, value: value)
case .cons(var paramHeads, let paramTail):
guard case var .list(argItems) = value else { throw EvaluationError.signatureMismatch([value]) }
guard argItems.count >= paramHeads.count else { throw EvaluationError.signatureMismatch([value]) }
while paramHeads.count > 0 {
let paramHead = paramHeads.removeFirst()
let argHead = argItems.removeFirst()
(extendedContext, patternEqualityContext) = try matchAndExtend(context: extendedContext, parameter: paramHead, value: argHead, patternEqualityContext: patternEqualityContext)
}
let argTail = Expression.list(argItems)
(extendedContext, patternEqualityContext) = try matchAndExtend(context: extendedContext, parameter: paramTail, value: argTail, patternEqualityContext: patternEqualityContext)
case .list(let paramItems):
guard case let .list(argItems) = value else { throw EvaluationError.signatureMismatch([value]) }
guard paramItems.count == argItems.count else { throw EvaluationError.signatureMismatch([value]) }
for (p, a) in zip(paramItems, argItems) {
(extendedContext, patternEqualityContext) = try matchAndExtend(context: extendedContext, parameter: p, value: a, patternEqualityContext: patternEqualityContext)
}
default:
if parameter != value { // NOTE: should this use Eq operator instead of Swift equality?
throw EvaluationError.signatureMismatch([value])
}
}
return (extendedContext, patternEqualityContext)
}
private func evaluateCall(name: String, arguments: [Expression], context: Context) throws -> Expression {
guard
let expr = context[name]
else { throw EvaluationError.symbolNotFound(name) }
return try evaluateCallAnonymous(closure: expr, arguments: arguments, callingContext: context)
}
// TODO: this code needs to be merged with the REPL code in main somehow.
private func evaluateScope(statements: [Expression], context: Context) throws -> Expression {
let (last, scopeContext) = try semiEvaluateScope(statements: statements, context: context)
let result: Expression
if case let .call(name, arguments) = last {
let evalArgs = try evaluate(arguments: arguments, context: scopeContext)
let expr = try evaluateVariable(variable: name, scopeContext)
result = try evaluateCallAnonymous(closure: expr, arguments: evalArgs, callingContext: context)
} else {
result = try last.evaluate(context: scopeContext)
}
return result
}
private func semiEvaluateScope(statements: [Expression], context: Context) throws -> (Expression, Context) {
guard statements.count > 0 else { throw EvaluationError.emptyScope }
var allStatements = statements
let last = allStatements.removeLast()
var scopeContext = context
var shadowedFunctions = Set<String>()
for statement in allStatements {
if case .function(let function) = statement {
if let name = function.name {
if !shadowedFunctions.contains(name) {
scopeContext.removeValue(forKey: name)
}
shadowedFunctions.insert(name)
}
}
let result: Expression
if case let .call(name, arguments) = statement {
let evalArgs = try evaluate(arguments: arguments, context: scopeContext)
let expr = try evaluateVariable(variable: name, scopeContext)
result = try evaluateCallAnonymous(closure: expr, arguments: evalArgs, callingContext: context)
} else {
result = try statement.evaluate(context: scopeContext)
}
if case .closure(let name, _, _) = result {
if let name = name {
scopeContext = extendContext(context: scopeContext, name: name, value: result)
}
}
if case .assign(let variable, let value) = result {
if case .name(let name) = variable {
scopeContext = extendContext(context: scopeContext, name: name, value: value)
}
}
}
return (last, scopeContext)
}
}
|
mit
|
eecba0aeb22d9e4f5fedace5c11f503d
| 45.79661 | 190 | 0.633901 | 5 | false | false | false | false |
relayr/apple-sdk
|
Sources/common/services/Database/DBUsers.swift
|
1
|
2884
|
import ReactiveSwift
import Foundation
extension DB {
/// Struct wrapping the user information to feed/retrieve-from the database.
struct User: JSONable {
/// relayr user's unique identifier.
let identifier: String
/// User's given name.
let name: String
/// Email owned by this user.
let email: String
}
/// Request information to the database about a specific User.
/// - parameter identifier: relayr user unique identifier.
static func user(withIdentifier identifier: String) -> SignalProducer<DB.User,DB.Error> {
let url = DB.fileURL(relativeTo: DB.User.directoryURL, withName: identifier)
return DB.getEntry(fromFileURL: url)
}
/// Sets the database information of the user passed as argument.
/// - parameter info: Database user representantion instance to be stored.
static func set(user info: DB.User) -> SignalProducer<(),DB.Error> {
let url = DB.fileURL(relativeTo: DB.User.directoryURL, withName: info.identifier)
return DB.setEntry(info, toFileURL: url)
}
/// Removes the user entry on the database.
/// - parameter identifier: relayr user unique identifier to be removed from the database.
static func remove(userWithIdentifier identifier: String) {
let url = DB.fileURL(relativeTo: DB.User.directoryURL, withName: identifier)
let _ = try? DB.remove(jsonFromURL: url)
}
}
extension DB.User {
typealias JSONType = [String:Any]
/// Designated initializer specifying every single property of the type.
init(_ identifier: String, name: String, email: String) {
self.identifier = identifier
self.name = name
self.email = email
}
init(fromJSON json: JSONType) throws {
guard let identifier = json[Keys.identifier] as? String,
let name = json[Keys.name] as? String,
let email = json[Keys.email] as? String else {
throw DB.Error.invalidFormat(json)
}
self.identifier = identifier
self.name = name
self.email = email
}
var json: JSONType {
return [Keys.identifier: identifier, Keys.name: name, Keys.email: email]
}
/// Absolute path for the *users* folder.
fileprivate static let directoryURL: URL = {
let url = DB.rootURL.appendingPathComponent("users", isDirectory: true)
try! DB.create(directoryAtURL: url)
return url
}()
/// List of keys specifying user properties
private struct Keys {
static let identifier = "identifier"
static let name = "name"
static let email = "email"
static let publishers = "publishers"
static let groups = "groups"
static let devices = "devices"
static let authorizedProjects = "authorizedProjects"
}
}
|
mit
|
0be31da20bf1cfecaece452e3fbed095
| 35.506329 | 94 | 0.641817 | 4.592357 | false | false | false | false |
TJ-93/TestKitchen
|
TestKitchen/TestKitchen/classes/common/Const.swift
|
1
|
10746
|
//
// Const.swift
// TestKitchen
//
// Created by qianfeng on 2016/10/21.
// Copyright © 2016年 陶杰. All rights reserved.
//
import Foundation
import UIKit
//定义一些常量和接口
//屏幕的宽度和高度
let screenW=UIScreen.mainScreen().bounds.size.width
let screenH=UIScreen.mainScreen().bounds.size.height
//首页推荐点击事件的类型
//接口
//大部分是Post请求
public let kHostUrl = "http://api.izhangchu.com/?appVersion=4.5&sysVersion=9.3.2&devModel=iPhone"
//一、食谱
//1、推荐
//首页推荐参数
//methodName=SceneHome&token=&user_id=&version=4.5
//1)广告
//广告详情
//methodName=CourseSeriesView&series_id=22&token=&user_id=&version=4.32
//广告分享
//methodName=AppShare&shareID=&shareModule=course&token=&user_id=&version=4.32
//评论
//methodName=CommentList&page=1&relate_id=22&size=10&token=&type=2&user_id=&version=4.32
//methodName=CommentList&page=2&relate_id=22&size=10&token=&type=2&user_id=&version=4.32
//评论发送
//content=%E5%AD%A6%E4%B9%A0%E4%BA%86&methodName=CommentInsert&parent_id=0&relate_id=23&token=8ABD36C80D1639D9E81130766BE642B7&type=2&user_id=1386387&version=4.32
//content="学习了"
//2)基本类型
//新手入门
//食材搭配
//material_ids=45%2C47&methodName=SearchMix&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//material_ids=45%2C47&methodName=SearchMix&page=2&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//场景菜谱
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//methodName=SceneList&page=1&size=18&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//methodName=SceneList&page=2&size=18&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//点击进详情
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//methodName=AppShare&shareID=105&shareModule=scene&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//methodName=SceneInfo&scene_id=105&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//再点击列表进详情
//做法
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//dishes_id=14528&methodName=DishesView&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//食材
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//dishes_id=14528&methodName=DishesMaterial&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//相关常识
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//dishes_id=14528&methodName=DishesCommensense&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//相宜相克
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//dishes_id=14528&methodName=DishesSuitable&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//评论数
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//dishes_id=14528&methodName=DishesViewnew&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//发布
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//收藏
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//ids=14528&methodName=UserUpdatelikes&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32
//dishes_id=14528&methodName=DishesViewnew&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//评论
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//methodName=CommentList&page=1&relate_id=14528&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32
//发送评论
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//content=%E5%AD%A6%E4%B9%A0%E4%B8%80%E4%B8%8B&methodName=CommentInsert&parent_id=0&relate_id=14528&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32
//content=@"学习一下"
//dishes_id=14528&methodName=DishesViewnew&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//上传照片
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//methodName=ShequTopic&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//activity_id=&content=%E5%BE%88%E5%A5%BD%E5%90%83&image=1457877114055_8928429596.jpg&methodName=ShequPostadd&token=8ABD36C80D1639D9E81130766BE642B7&topics=%5B%7B%22topic_id%22%3A%226%22%2C%22topic_name%22%3A%22%E4%B8%80%E4%BA%BA%E9%A3%9F%22%2C%22locx%22%3A%22160%22%2C%22locy%22%3A%22160%22%2C%22width%22%3A%22320%22%7D%5D&user_id=1386387&version=4.32&video=
//content = @“很好吃”
//猜你喜欢
//methodName=UserLikes&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//口味有变
//methodName=LbsProvince&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//baidu_city=%E6%B7%B1%E5%9C%B3%E5%B8%82&baidu_province=%E5%B9%BF%E4%B8%9C%E7%9C%81&effect=312&like=230&methodName=UserDraw&province=3&taste=316&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//点击一个标签进入搜索列表
//cat_id=252&methodName=CategorySearch&page=1&size=6&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32
//搜索
//keyword=%E6%97%A9%E9%A4%90&methodName=SearchDishes&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//keyword=早餐
//日食记
//methodName=AppShare&shareID=&shareModule=course&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//methodName=CourseSeriesView&series_id=18&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//methodName=CommentList&page=1&relate_id=18&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=2&user_id=1386387&version=4.32
//台湾食记
//methodName=AppShare&shareID=&shareModule=course&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//methodName=CourseSeriesView&series_id=12&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//methodName=CommentList&page=1&relate_id=12&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=2&user_id=1386387&version=4.32
//3)今日食谱推荐
//进列表
//methodName=AppShare&shareID=51&shareModule=scene&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//methodName=SceneInfo&scene_id=51&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//相关场景
//methodName=SceneInfo&scene_id=112&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//4)春季养生肝为先
//methodName=AppShare&shareID=127&shareModule=scene&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//methodName=SceneInfo&scene_id=127&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//5)场景菜谱
//methodName=SceneList&page=1&size=18&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//methodName=SceneInfo&scene_id=134&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//6)推荐达人
//methodName=TalentRecommend&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//关注
//ids=1249795&methodName=UpdateFollow&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32
//取消关注
//ids=1249795&methodName=UpdateFollow&token=8ABD36C80D1639D9E81130766BE642B7&type=0&user_id=1386387&version=4.32
//达人详情页
//
//7)精选作品
//is_marrow=1&methodName=ShequList&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//作品详情
//methodName=CommentList&page=1&relate_id=35282&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=3&user_id=1386387&version=4.32
//methodName=AppShare&shareID=35282&shareModule=shequ&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//methodName=ShequPostview&post_id=35282&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//8)美食专题
//methodName=TopicList&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32
//专题详情
//methodName=TopicView&version=1.0&user_id=1386387&topic_id=175&_time=1457878578&_signature=0ba3640c73c17441b675a7dd968a66e8
//http://h5.izhangchu.com/topic_view/index.html?&topic_id=134&user_id=1386387&token=8ABD36C80D1639D9E81130766BE642B7&app_exitpage=
//2、食材
//methodName=MaterialSubtype&token=&user_id=&version=4.32
//详情
//material_id=62&methodName=MaterialView&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//相关菜例
//material_id=62&methodName=MaterialDishes&page=1&size=6&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//选购要诀
//营养功效
//实用百科
//material_id=62&methodName=MaterialDishes&page=2&size=6&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//3、分类
//methodName=CategoryIndex&token=&user_id=&version=4.32
//进列表
//cat_id=316&methodName=CategorySearch&page=1&size=6&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32
//4、搜索
//热门搜索
//methodName=SearchHot&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//二、社区
//推荐
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//methodName=ShequRecommend&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.33
//最新
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//last_id=0&methodName=ShequList&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//关注
//http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone
//methodName=ShequFollow&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//三、商城
//四、食课
//methodName=CourseIndex&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//五、我的
//注册
//获取验证码
//device_id=021fc7f7528&methodName=UserLogin&mobile=13716422377&token=&user_id=&version=4.32
//code=173907&device_id=021fc7f7528&methodName=UserAuth&mobile=13716422377&token=&user_id=&version=4.32
//
//GET : http://182.92.228.160:80/zhangchu/onlinezhangchu/users/1386387
//注册
//methodName=UserPwd&nickname=sh%E6%8E%8C%E5%8E%A8&password=9745b090734f44cdd7b2ef1d88c26b1f&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
//sh掌厨 05513867720
|
mit
|
97876eee9e0bf78f081809d60b5a1703
| 35.170819 | 359 | 0.800551 | 2.381209 | false | false | false | false |
lzpfmh/actor-platform
|
actor-apps/app-ios/ActorApp/Controllers/Group/Cells/GroupMemberCell.swift
|
1
|
3039
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class GroupMemberCell: UATableViewCell {
// Views
var nameLabel = UILabel(style: "members.name")
var onlineLabel = UILabel(style: "members.online")
var avatarView = AvatarView(style: "avatar.round.small")
var adminLabel = UILabel(style: "members.admin")
// Binder
var binder = Binder()
// Contstructors
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(cellStyle: "members.cell", reuseIdentifier: reuseIdentifier)
adminLabel.text = localized("GroupMemberAdmin")
adminLabel.sizeToFit()
contentView.addSubview(avatarView)
contentView.addSubview(nameLabel)
contentView.addSubview(onlineLabel)
contentView.addSubview(adminLabel)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Binding
func setUsername(username: String) {
nameLabel.text = username
}
func bind(user: ACUserVM, isAdmin: Bool) {
// Bind name and avatar
let name = user.getNameModel().get()
nameLabel.text = name
avatarView.bind(name, id: user.getId(), avatar: user.getAvatarModel().get())
// Bind admin flag
adminLabel.hidden = !isAdmin
// Bind onlines
binder.bind(user.getPresenceModel()) { (value: ACUserPresence?) -> () in
if value != nil {
self.onlineLabel.showView()
self.onlineLabel.text = Actor.getFormatter().formatPresence(value!, withSex: user.getSex())
if value!.state.ordinal() == jint(ACUserPresence_State.ONLINE.rawValue) {
self.onlineLabel.applyStyle("user.online")
} else {
self.onlineLabel.applyStyle("user.offline")
}
} else {
self.onlineLabel.alpha = 0
self.onlineLabel.text = ""
}
}
}
override func prepareForReuse() {
super.prepareForReuse()
binder.unbindAll()
}
// Layouting
override func layoutSubviews() {
super.layoutSubviews()
let userAvatarViewFrameSize: CGFloat = CGFloat(avatarView.frameSize)
avatarView.frame = CGRect(x: 14.0, y: (contentView.bounds.size.height - userAvatarViewFrameSize) / 2.0, width: userAvatarViewFrameSize, height: userAvatarViewFrameSize)
var w: CGFloat = contentView.bounds.size.width - 65.0 - 8.0
if !adminLabel.hidden {
adminLabel.frame = CGRect(x: contentView.width - adminLabel.width - 8, y: 5, width: adminLabel.width, height: 42)
w -= adminLabel.width + 8
}
nameLabel.frame = CGRect(x: 65.0, y: 5, width: w, height: 22)
onlineLabel.frame = CGRect(x: 65.0, y: 27, width: w, height: 16)
}
}
|
mit
|
ed994ccbd0551250d7c8f05aeabb508b
| 30.65625 | 176 | 0.587364 | 4.508902 | false | false | false | false |
Johnykutty/SwiftLint
|
Source/SwiftLintFramework/Rules/LegacyNSGeometryFunctionsRule.swift
|
4
|
6287
|
//
// LegacyNSGeometryFunctionsRule.swift
// SwiftLint
//
// Created by David Rönnqvist on 01/08/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct LegacyNSGeometryFunctionsRule: CorrectableRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "legacy_nsgeometry_functions",
name: "Legacy NSGeometry Functions",
description: "Struct extension properties and methods are preferred over legacy functions",
nonTriggeringExamples: [
"rect.width",
"rect.height",
"rect.minX",
"rect.midX",
"rect.maxX",
"rect.minY",
"rect.midY",
"rect.maxY",
"rect.isEmpty",
"rect.integral",
"rect.insetBy(dx: 5.0, dy: -7.0)",
"rect.offsetBy(dx: 5.0, dy: -7.0)",
"rect1.union(rect2)",
"rect1.intersect(rect2)",
// "rect.divide(atDistance: 10.2, fromEdge: edge)", No correction available for divide
"rect1.contains(rect2)",
"rect.contains(point)",
"rect1.intersects(rect2)"
],
triggeringExamples: [
"↓NSWidth(rect)",
"↓NSHeight(rect)",
"↓NSMinX(rect)",
"↓NSMidX(rect)",
"↓NSMaxX(rect)",
"↓NSMinY(rect)",
"↓NSMidY(rect)",
"↓NSMaxY(rect)",
"↓NSEqualRects(rect1, rect2)",
"↓NSEqualSizes(size1, size2)",
"↓NSEqualPoints(point1, point2)",
"↓NSEdgeInsetsEqual(insets2, insets2)",
"↓NSIsEmptyRect(rect)",
"↓NSIntegralRect(rect)",
"↓NSInsetRect(rect, 10, 5)",
"↓NSOffsetRect(rect, -2, 8.3)",
"↓NSUnionRect(rect1, rect2)",
"↓NSIntersectionRect(rect1, rect2)",
"↓NSContainsRect(rect1, rect2)",
"↓NSPointInRect(rect, point)",
"↓NSIntersectsRect(rect1, rect2)"
],
corrections: [
"↓NSWidth( rect )\n": "rect.width\n",
"↓NSHeight(rect )\n": "rect.height\n",
"↓NSMinX( rect)\n": "rect.minX\n",
"↓NSMidX( rect)\n": "rect.midX\n",
"↓NSMaxX( rect)\n": "rect.maxX\n",
"↓NSMinY(rect )\n": "rect.minY\n",
"↓NSMidY(rect )\n": "rect.midY\n",
"↓NSMaxY( rect )\n": "rect.maxY\n",
"↓NSEqualPoints( point1 , point2)\n": "point1 == point2\n",
"↓NSEqualSizes(size1,size2 )\n": "size1 == size2\n",
"↓NSEqualRects( rect1, rect2)\n": "rect1 == rect2\n",
"↓NSEdgeInsetsEqual(insets1, insets2)\n": "insets1 == insets2\n",
"↓NSIsEmptyRect( rect )\n": "rect.isEmpty\n",
"↓NSIntegralRect(rect )\n": "rect.integral\n",
"↓NSInsetRect(rect, 5.0, -7.0)\n": "rect.insetBy(dx: 5.0, dy: -7.0)\n",
"↓NSOffsetRect(rect, -2, 8.3)\n": "rect.offsetBy(dx: -2, dy: 8.3)\n",
"↓NSUnionRect(rect1, rect2)\n": "rect1.union(rect2)\n",
"↓NSIntersectionRect( rect1 ,rect2)\n": "rect1.intersect(rect2)\n",
"↓NSContainsRect( rect1,rect2 )\n": "rect1.contains(rect2)\n",
"↓NSPointInRect(point ,rect)\n": "rect.contains(point)\n", // note order of arguments
"↓NSIntersectsRect( rect1,rect2 )\n": "rect1.intersects(rect2)\n",
"↓NSIntersectsRect(rect1, rect2 )\n↓NSWidth(rect )\n":
"rect1.intersects(rect2)\nrect.width\n"
]
)
public func validate(file: File) -> [StyleViolation] {
let functions = ["NSWidth", "NSHeight", "NSMinX", "NSMidX",
"NSMaxX", "NSMinY", "NSMidY", "NSMaxY",
"NSEqualRects", "NSEqualSizes", "NSEqualPoints", "NSEdgeInsetsEqual",
"NSIsEmptyRect", "NSIntegralRect", "NSInsetRect",
"NSOffsetRect", "NSUnionRect", "NSIntersectionRect",
"NSContainsRect", "NSPointInRect", "NSIntersectsRect"]
let pattern = "\\b(" + functions.joined(separator: "|") + ")\\b"
return file.match(pattern: pattern, with: [.identifier]).map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
public func correct(file: File) -> [Correction] {
let varName = RegexHelpers.varNameGroup
let twoVars = RegexHelpers.twoVars
let twoVariableOrNumber = RegexHelpers.twoVariableOrNumber
let patterns: [String: String] = [
"NSWidth\\(\(varName)\\)": "$1.width",
"NSHeight\\(\(varName)\\)": "$1.height",
"NSMinX\\(\(varName)\\)": "$1.minX",
"NSMidX\\(\(varName)\\)": "$1.midX",
"NSMaxX\\(\(varName)\\)": "$1.maxX",
"NSMinY\\(\(varName)\\)": "$1.minY",
"NSMidY\\(\(varName)\\)": "$1.midY",
"NSMaxY\\(\(varName)\\)": "$1.maxY",
"NSEqualRects\\(\(twoVars)\\)": "$1 == $2",
"NSEqualSizes\\(\(twoVars)\\)": "$1 == $2",
"NSEqualPoints\\(\(twoVars)\\)": "$1 == $2",
"NSEdgeInsetsEqual\\(\(twoVars)\\)": "$1 == $2",
"NSIsEmptyRect\\(\(varName)\\)": "$1.isEmpty",
"NSIntegralRect\\(\(varName)\\)": "$1.integral",
"NSInsetRect\\(\(varName),\(twoVariableOrNumber)\\)": "$1.insetBy(dx: $2, dy: $3)",
"NSOffsetRect\\(\(varName),\(twoVariableOrNumber)\\)": "$1.offsetBy(dx: $2, dy: $3)",
"NSUnionRect\\(\(twoVars)\\)": "$1.union($2)",
"NSIntersectionRect\\(\(twoVars)\\)": "$1.intersect($2)",
"NSContainsRect\\(\(twoVars)\\)": "$1.contains($2)",
"NSPointInRect\\(\(twoVars)\\)": "$2.contains($1)", // note order of arguments
"NSIntersectsRect\\(\(twoVars)\\)": "$1.intersects($2)"
]
return file.correct(legacyRule: self, patterns: patterns)
}
}
|
mit
|
1862201ae1269f4166d415dcf190cd60
| 44.233577 | 99 | 0.523479 | 3.783272 | false | false | false | false |
Minecodecraft/50DaysOfSwift
|
Day 12 - LrcShareTool/LrcShareTool/LrcShareTool/MCLrcCell.swift
|
1
|
1825
|
//
// MCLrcCell.swift
// LrcShareTool
//
// Created by Minecode on 2017/12/5.
// Copyright © 2017年 Minecode. All rights reserved.
//
import UIKit
class MCLrcCell: UITableViewCell {
// UI控件
@IBOutlet weak var iconImage: UIImageView!
@IBOutlet weak var lrcLabel: UILabel!
@IBOutlet weak var imageConstrains: NSLayoutConstraint!
// 属性, 使用计算属性观察者
var lrcSelecting = false {
didSet {
self.didChangeLrcSelecting()
}
}
var lrcSelected = false {
didSet {
self.didChangedLrcSelected()
}
}
var lrc: String = "" {
didSet {
self.lrcLabel.text = lrc
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.clear
self.reset()
}
func reset() {
// 重置selecting选项
self.lrcSelecting = false;
// 重置selected选项
self.lrcSelected = false;
// FIXME:
}
// MARK: - 私有方法API
let IMG_CONSTRAIN_SELE: CGFloat = 8
let IMG_CONSTRAIN_NONSELE: CGFloat = -28
private func didChangeLrcSelecting() {
// 设置约束
if (self.lrcSelecting) {
self.imageConstrains.constant = IMG_CONSTRAIN_SELE
}
else {
self.imageConstrains.constant = IMG_CONSTRAIN_NONSELE
}
}
private func didChangedLrcSelected() {
self.iconImage.image = self.lrcSelected ? #imageLiteral(resourceName: "img_selected") : #imageLiteral(resourceName: "img_nonselected")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
1f28d2be1130fd5115fc1c523087cbf8
| 23.164384 | 142 | 0.586168 | 4.210024 | false | false | false | false |
xiaoyouPrince/WeiBo
|
WeiBo/WeiBo/Classes/Home/HomeViewCell.swift
|
1
|
8556
|
//
// HomeViewCell.swift
// WeiBo
//
// Created by 渠晓友 on 2017/5/27.
// Copyright © 2017年 xiaoyouPrince. All rights reserved.
//
import UIKit
import SDWebImage
private let edgeMargin : CGFloat = 15
private let itemMargin : CGFloat = 10
class HomeViewCell: UITableViewCell {
// MARK: - 控件属性
var statusVM : StatusViewModel?
{
didSet{
if let viewModel = statusVM {
// iconImage.sd_setImage(with: URL(string : (viewModel.status.user?.profile_image_url)!))
iconImage.sd_setImage(with: statusVM?.profileURL)
vertifyIcon.image = viewModel.verifiedImage
vipIcon.image = viewModel.vipImage
userNameLabel.text = viewModel.status.user?.screen_name
creatAtLabel.text = viewModel.creatTimeStr
sourceLabel.text = viewModel.sourceText
// contentLabel.text = viewModel.status.text
let statusText = viewModel.status.text
contentLabel.attributedText = FindEmotion.shareIntance.findAttrString(statusText: statusText, font: UIFont.systemFont(ofSize: 14))
userNameLabel.textColor = vipIcon.image == nil ? UIColor.black : UIColor.orange // 设置用户名文字颜色
// 计算picView的宽度和高度
picViewHcons.constant = self.calculatePicViewSize(count: (statusVM?.picURLs.count ?? 0)! ).height
picVIewWcons.constant = self.calculatePicViewSize(count: (statusVM?.picURLs.count ?? 0)! ).width
picView.picUrls = (statusVM?.picURLs)!
// 设置转发微博的内容
if let retweetText = statusVM?.status.retweeted_status?.text , let screenName = statusVM?.status.retweeted_status?.user?.screen_name{
retweetContentLabel.text = "@" + "\(screenName):" + retweetText
// 设置装发微博背景
retweetStatusBGView.isHidden = false
// 设置转发正文的约束
retweetContentBottomCons.constant = 10
}else{
retweetContentLabel.text = nil
retweetStatusBGView.isHidden = true
// 设置转发正文的约束
retweetContentBottomCons.constant = 0
}
// 手动计算cell高度
if viewModel.cellHeight == 0 {
// 1.强制布局
self.layoutIfNeeded()
// 2.计算并保存cell高度
viewModel.cellHeight = self.bottomToolBar.frame.maxY
}
// MARK: - RELabel监听点击
// 监听用户的点击
contentLabel.userTapHandler = { (label, user, range) in
print(label)
print(user)
print(range)
}
// 监听链接的点击
contentLabel.linkTapHandler = { (label, link, range) in
print(label)
print(link)
print(range)
}
// 监听话题的点击
contentLabel.topicTapHandler = { (label, topic, range) in
print(label)
print(topic)
print(range)
}
// 监听用户的点击
retweetContentLabel.userTapHandler = { (label, user, range) in
print(label)
print(user)
print(range)
}
// 监听链接的点击
retweetContentLabel.linkTapHandler = { (label, link, range) in
print(label)
print(link)
print(range)
}
// 监听话题的点击
retweetContentLabel.topicTapHandler = { (label, topic, range) in
print(label)
print(topic)
print(range)
}
}
}
}
/// 正文宽度约束
@IBOutlet weak var contentLabelWidthConstraint: NSLayoutConstraint!
/// picView 的高度约束
@IBOutlet weak var picViewHcons: NSLayoutConstraint!
/// picView 的宽度约束
@IBOutlet weak var picVIewWcons: NSLayoutConstraint!
@IBOutlet weak var picViewBottomCons: NSLayoutConstraint!
@IBOutlet weak var retweetContentBottomCons: NSLayoutConstraint!
/// 用户头像
@IBOutlet weak var iconImage: UIImageView!
/// 认证图标
@IBOutlet weak var vertifyIcon: UIImageView!
/// 会员图标
@IBOutlet weak var vipIcon: UIImageView!
/// 用户昵称
@IBOutlet weak var userNameLabel: UILabel!
/// 创建时间
@IBOutlet weak var creatAtLabel: UILabel!
/// 微博来源
@IBOutlet weak var sourceLabel: UILabel!
/// 微博正文
@IBOutlet weak var contentLabel: RELabel!
/// 微博图片内容
@IBOutlet weak var picView: PicCollectionView!
/// 转发微博内容
@IBOutlet weak var retweetContentLabel: RELabel!
/// 转发微博背景
@IBOutlet weak var retweetStatusBGView: UIView!
/// 底部工具栏
@IBOutlet weak var bottomToolBar: UIView!
// MARK: - 系统回调
override func awakeFromNib() {
super.awakeFromNib()
// 一次性设置内容Label的宽度,来以此准确的自动计算内容Label的高度。
contentLabelWidthConstraint.constant = kScreenW - 2 * 15
// 设置 picView 的 itemLayout
// let layout = picView.collectionViewLayout as! UICollectionViewFlowLayout
// let imageViewWH : CGFloat = (kScreenW - 2 * edgeMargin - 2 * itemMargin) / 3
// layout.itemSize = CGSize(width: imageViewWH, height: imageViewWH)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
extension HomeViewCell{
/// 计算picView 的Size
///
/// - Parameter count: 图片数量
/// - Returns: Size
fileprivate func calculatePicViewSize(count : Int) -> CGSize {
// 1.没有配图
if count == 0 {
// 修改picView底部约束
picViewBottomCons.constant = 0
return CGSize.zero
}
// 修改picView底部约束
picViewBottomCons.constant = 10
// 2.取到collectionView的layout
let layout = picView.collectionViewLayout as! UICollectionViewFlowLayout
// 3.单张配图
if count == 1 {
// 3.1取出缓存图片,根据该图片的Size进行返回
let imageurl = self.statusVM?.picURLs.first?.absoluteString
let imageCache: SDImageCache = SDWebImageManager.shared.imageCache as! SDImageCache
let image = imageCache.imageFromCache(forKey: imageurl)
if let image = image
{
// 3.2 设置单张配图的layout.itemSize
layout.itemSize = CGSize(width: ((image.size.width) * 2) > 150 ? 150 : ((image.size.width) * 2 ), height: (image.size.height) * 2 > 100 ? 100 : (image.size.height) * 2)
// 3.3.返回对应的size
return layout.itemSize
}
}
// 4.计算多张配图imageView的WH
let imageViewWH : CGFloat = (kScreenW - 2 * edgeMargin - 2 * itemMargin) / 3
layout.itemSize = CGSize(width: imageViewWH, height: imageViewWH)
// 5.张配图
if count == 4 {
let picViewWH = imageViewWH * 2 + itemMargin + 1
return CGSize(width: picViewWH, height: picViewWH)
}
// 6.其他张数配图
let rows = CGFloat((count - 1) / 3 + 1 )
let picViewH = rows * imageViewWH + (rows - 1) * itemMargin
let picViewW = kScreenW - 2 * edgeMargin
return CGSize(width: picViewW, height: picViewH)
}
}
|
mit
|
aa85b40129f7de6440ae9d833190e017
| 32.57384 | 184 | 0.520548 | 5.180339 | false | false | false | false |
0416354917/FeedMeIOS
|
FeedMeIOS/Address.swift
|
1
|
1587
|
//
// Address.swift
// FeedMeIOS
//
// Created by Jun Chen on 28/03/2016.
// Copyright © 2016 FeedMe. All rights reserved.
//
import Foundation
class Address: EVObject {
var userName: String?
var addressLine1: String?
var addressLine2: String?
var suburb: String! = "Canberra"
var state: String! = "ACT"
var postcode: String?
var phone: String?
var selected: Bool! = false
required init() {
}
init(userName: String?, addressLine1: String?, addressLine2: String?, postcode: String?, phone: String?, suburb: String?, state: String?, selected: Bool?) {
self.userName = userName
self.addressLine1 = addressLine1
self.addressLine2 = addressLine2
self.postcode = postcode
self.phone = phone
self.suburb = suburb
self.state = state
}
func toSimpleAddressString() -> String {
return addressLine1! + " " + addressLine2! + ", " + suburb + " " + state + " " + postcode!
}
func toFormattedString() -> String {
var formattedAddressString = userName!
formattedAddressString += ("\n" + addressLine1!)
formattedAddressString += ("\n" + addressLine2! + ", " + suburb + ", " + state + " " + postcode!)
formattedAddressString += ("\n" + phone!)
return formattedAddressString
}
func isSelected() -> Bool {
return self.selected
}
func setAsSelected() {
self.selected = true
}
func setAsDeselected() {
self.selected = false
}
}
|
bsd-3-clause
|
7a263b08cebec061fbec7aa9ddff6744
| 25.433333 | 160 | 0.583228 | 4.173684 | false | false | false | false |
huangxinping/XPKit-swift
|
Source/XPKit/XPPassword.swift
|
1
|
5480
|
//
// XPPassword.swift
// XPKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2016 Fabrizio Brancati. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
/// This class adds some useful functions to manage passwords
public class XPPassword {
// MARK: - Enums -
/**
Password strength level enum, from 0 (min) to 6 (max)
- VeryWeak: Password strength very weak
- Weak: Password strength weak
- Average: Password strength average
- Strong: Password strength strong
- VeryStrong: Password strength very strong
- Secure: Password strength secure
- VerySecure: Password strength very secure
*/
public enum PasswordStrengthLevel: Int {
case VeryWeak
case Weak
case Average
case Strong
case VeryStrong
case Secure
case VerySecure
}
// MARK: - Class functions -
/**
Check the password strength level
- parameter password: Password string
- returns: Returns the password strength level with value from enum PasswordStrengthLevel
*/
public static func checkPasswordStrength(password: String) -> PasswordStrengthLevel {
let lenght = password.length
let lowercase = self.countLowercaseLetters(password)
let uppercase = self.countUppercaseLetters(password)
let numbers = self.countNumbers(password)
let symbols = self.countSymbols(password)
var score = 0
if lenght < 5 {
score += 5
} else {
if lenght > 4 && lenght < 8 {
score += 10
} else {
if lenght > 7 {
score += 20
}
}
}
if numbers == 1 {
score += 10
} else {
if numbers == 2 {
score += 15
} else {
if numbers > 2 {
score += 20
}
}
}
if symbols == 1 {
score += 10
} else {
if symbols == 2 {
score += 15
} else {
if symbols > 2 {
score += 20
}
}
}
if lowercase == 1 {
score += 10
} else {
if lowercase == 2 {
score += 15
} else {
if lowercase > 2 {
score += 20
}
}
}
if uppercase == 1 {
score += 10
} else {
if uppercase == 2 {
score += 15
} else {
if uppercase > 2 {
score += 20
}
}
}
if score == 100 {
return .VerySecure
} else {
if score >= 90 {
return .Secure
} else {
if score >= 80 {
return .VeryStrong
} else {
if score >= 70 {
return .Strong
} else {
if score >= 60 {
return .Average
} else {
if score >= 50 {
return .Weak
} else {
return .VeryWeak
}
}
}
}
}
}
}
/**
Private, count the number of lowercase letters
- parameter password: Password string
- returns: Number of lowercase letters
*/
private static func countLowercaseLetters(password: String) -> Int {
var countChar = 0
for i in 0 ..< password.length {
let isLowercase = NSCharacterSet.lowercaseLetterCharacterSet().characterIsMember((String(password) as NSString).characterAtIndex(i))
if isLowercase {
countChar += 1
}
}
return countChar
}
/**
Private, count the number of uppercase letters
- parameter password: Password string
- returns: Number of uppercase letters
*/
private static func countUppercaseLetters(password: String) -> Int {
var countChar = 0
for i in 0 ..< password.length {
let isUppercase = NSCharacterSet.lowercaseLetterCharacterSet().characterIsMember((String(password) as NSString).characterAtIndex(i))
if isUppercase {
countChar += 1
}
}
return countChar
}
/**
Private, count the number of numbers
- parameter password: Password string
- returns: Number of numbers
*/
private static func countNumbers(password: String) -> Int {
var countNumber = 0
for i in 0 ..< password.length {
let isNumber = NSCharacterSet(charactersInString: "0123456789").characterIsMember((String(password) as NSString).characterAtIndex(i))
if isNumber {
countNumber += 1
}
}
return countNumber
}
/**
Private, count the number of symbols
- parameter password: Password string
- returns: Number of symbols
*/
private static func countSymbols(password: String) -> Int {
var countSymbol = 0
for i in 0 ..< password.length {
let isSymbol = NSCharacterSet(charactersInString: "`~!?@#$€£¥§%^&*()_+-={}[]:\";.,<>'•\\|/").characterIsMember((String(password) as NSString).characterAtIndex(i))
if isSymbol {
countSymbol += 1
}
}
return countSymbol
}
}
|
mit
|
da5ccfea57ef574e3e29d32438c04560
| 22.388889 | 165 | 0.653024 | 3.771881 | false | false | false | false |
miles-github/UAP
|
UAP Original/UAP2/ViewController.swift
|
1
|
1815
|
//
// ViewController.swift
// UAP2
//
// Created by Miles on 7/27/15.
// Copyright (c) 2015 Miles. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AudioPlayer()
// var audioPlayer = AudioPlayer(currentAudio:"")
var currentAudioPath:NSURL!
@IBOutlet var audioTitle : UILabel!
@IBOutlet weak var playButton: UIButton! {
didSet {
playButton.setTitle("Play", forState: UIControlState.Normal)
}
}
// override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// print("tap")
// if playButton.titleLabel?.text == "Pause" {
// audioPlayer.Pause()
// playButton.setTitle("Play", forState: UIControlState.Normal)
// }
// }
//
@IBAction func tapGesture(sender: UITapGestureRecognizer) {
print(sender.numberOfTouches())
if sender.numberOfTouches() == 1 {
print("one tap")
audioPlayer.Pause()
playButton.setTitle("Play", forState: UIControlState.Normal)
}
}
@IBAction func playAudio () {
if playButton.titleLabel?.text == "Play" {
audioTitle.text = audioPlayer.Play()
playButton.setTitle("Pause", forState: UIControlState.Normal)
} else {
audioPlayer.Pause()
playButton.setTitle("Play", forState: UIControlState.Normal)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
9a359d0db1673d5fca9b07a4653ac0d2
| 26.5 | 84 | 0.6 | 4.84 | false | false | false | false |
andrucuna/ios
|
Swiftris/Swiftris/GameScene.swift
|
1
|
10995
|
//
// GameScene.swift
// Swiftris
//
// Created by Andrés Ruiz on 9/24/14.
// Copyright (c) 2014 Andrés Ruiz. All rights reserved.
//
import SpriteKit
// We simply define the point size of each block sprite - in our case 20.0 x 20.0 - the lower of the
// available resolution options for each block image. We also declare a layer position which will give us an
// offset from the edge of the screen.
let BlockSize:CGFloat = 20.0
// This variable will represent the slowest speed at which our shapes will travel.
let TickLengthLevelOne = NSTimeInterval(600)
class GameScene: SKScene
{
// #2
let gameLayer = SKNode()
let shapeLayer = SKNode()
let LayerPosition = CGPoint(x: 6, y: -6)
// In tick, its type is (() -> ())? which means that it's a closure which takes no parameters and
// returns nothing. Its question mark indicates that it is optional and therefore may be nil.
var tick: (() ->())?
var tickLengthMillis = TickLengthLevelOne
var lastTick: NSDate?
var textureCache = Dictionary<String, SKTexture>()
required init( coder aDecoder: (NSCoder!) )
{
fatalError( "NSCoder not supported" )
}
override init( size: CGSize )
{
super.init( size: size )
anchorPoint = CGPoint( x: 0, y: 1.0 )
let background = SKSpriteNode( imageNamed: "background" )
background.position = CGPoint( x: 0, y: 0 )
background.anchorPoint = CGPoint( x: 0, y: 1.0 )
addChild( background )
addChild(gameLayer)
let gameBoardTexture = SKTexture(imageNamed: "gameboard")
let gameBoard = SKSpriteNode(texture: gameBoardTexture, size: CGSizeMake(BlockSize * CGFloat(NumColumns), BlockSize * CGFloat(NumRows)))
gameBoard.anchorPoint = CGPoint(x:0, y:1.0)
gameBoard.position = LayerPosition
shapeLayer.position = LayerPosition
shapeLayer.addChild(gameBoard)
gameLayer.addChild(shapeLayer)
// We set up a looping sound playback action of our theme song.
runAction(SKAction.repeatActionForever(SKAction.playSoundFileNamed("theme.mp3", waitForCompletion: true)))
}
// We added a method which GameViewController may use to play any sound file on demand.
func playSound(sound:String)
{
runAction(SKAction.playSoundFileNamed(sound, waitForCompletion: false))
}
override func update(currentTime: CFTimeInterval)
{
/* Called before each frame is rendered */
// If lastTick is missing, we are in a paused state, not reporting elapsed ticks to anyone,
// therefore we simply return.
if lastTick == nil
{
return
}
var timePassed = lastTick!.timeIntervalSinceNow * -1000.0
if timePassed > tickLengthMillis
{
lastTick = NSDate.date()
tick?()
}
}
// We provide accessor methods to let external classes stop and start the ticking process.
func startTicking() {
lastTick = NSDate.date()
}
func stopTicking() {
lastTick = nil
}
// The math here looks funky but just know that each sprite will be anchored at its center, therefore we
// need to find its center coordinate before placing it in our shapeLayer object.
func pointForColumn(column: Int, row: Int) -> CGPoint
{
let x: CGFloat = LayerPosition.x + (CGFloat(column) * BlockSize) + (BlockSize / 2)
let y: CGFloat = LayerPosition.y - ((CGFloat(row) * BlockSize) + (BlockSize / 2))
return CGPointMake(x, y)
}
func addPreviewShapeToScene(shape:Shape, completion:() -> ())
{
for (idx, block) in enumerate(shape.blocks)
{
// We've created a method which will add a shape for the first time to the scene as a preview
// shape. We use a dictionary to store copies of re-usable SKTexture objects since each shape
// will require multiple copies of the same image.
var texture = textureCache[block.spriteName]
if texture == nil
{
texture = SKTexture(imageNamed: block.spriteName)
textureCache[block.spriteName] = texture
}
let sprite = SKSpriteNode(texture: texture)
// We use our convenient pointForColumn(Int, Int) method to place each block's sprite in the
// proper location. We start it at row - 2, such that the preview piece animates smoothly into
// place from a higher location.
sprite.position = pointForColumn(block.column, row:block.row - 2)
shapeLayer.addChild(sprite)
block.sprite = sprite
// Animation
sprite.alpha = 0
// We introduce SKAction objects which are responsible for visually manipulating SKNode objects.
// Each block will fade and move into place as it appears as part of the next piece. It will
// move two rows down and fade from complete transparency to 70% opacity.
let moveAction = SKAction.moveTo(pointForColumn(block.column, row: block.row), duration: NSTimeInterval(0.2))
moveAction.timingMode = .EaseOut
let fadeInAction = SKAction.fadeAlphaTo(0.7, duration: 0.4)
fadeInAction.timingMode = .EaseOut
sprite.runAction(SKAction.group([moveAction, fadeInAction]))
}
runAction(SKAction.waitForDuration(0.4), completion: completion)
}
func movePreviewShape(shape:Shape, completion:() -> ())
{
for (idx, block) in enumerate(shape.blocks)
{
let sprite = block.sprite!
let moveTo = pointForColumn(block.column, row:block.row)
let moveToAction:SKAction = SKAction.moveTo(moveTo, duration: 0.2)
moveToAction.timingMode = .EaseOut
sprite.runAction(
SKAction.group([moveToAction, SKAction.fadeAlphaTo(1.0, duration: 0.2)]), completion:nil)
}
runAction(SKAction.waitForDuration(0.2), completion: completion)
}
func redrawShape(shape:Shape, completion:() -> ())
{
for (idx, block) in enumerate(shape.blocks)
{
let sprite = block.sprite!
let moveTo = pointForColumn(block.column, row:block.row)
let moveToAction:SKAction = SKAction.moveTo(moveTo, duration: 0.05)
moveToAction.timingMode = .EaseOut
sprite.runAction(moveToAction, completion: nil)
}
runAction(SKAction.waitForDuration(0.05), completion: completion)
}
// You can see that we take in precisely the tuple data which Swiftris returns each time a line is
// removed. This will ensure that GameViewController need only pass those elements to GameScene in order
// for them to animate properly.
func animateCollapsingLines(linesToRemove: Array<Array<Block>>, fallenBlocks: Array<Array<Block>>, completion:() -> ())
{
var longestDuration: NSTimeInterval = 0
// We also established a longestDuration variable which will determine precisely how long we should
// wait before calling the completion closure.
for (columnIdx, column) in enumerate(fallenBlocks)
{
for (blockIdx, block) in enumerate(column)
{
let newPosition = pointForColumn(block.column, row: block.row)
let sprite = block.sprite!
// We wrote code which will produce this pleasing effect for eye balls to enjoy. Based on
// the block and column indices, we introduce a directly proportional delay.
let delay = (NSTimeInterval(columnIdx) * 0.05) + (NSTimeInterval(blockIdx) * 0.05)
let duration = NSTimeInterval(((sprite.position.y - newPosition.y) / BlockSize) * 0.1)
let moveAction = SKAction.moveTo(newPosition, duration: duration)
moveAction.timingMode = .EaseOut
sprite.runAction(
SKAction.sequence([
SKAction.waitForDuration(delay),
moveAction]))
longestDuration = max(longestDuration, duration + delay)
}
}
for (rowIdx, row) in enumerate(linesToRemove)
{
for (blockIdx, block) in enumerate(row)
{
// We make their blocks shoot off the screen like explosive debris. In order to accomplish
// this we will employ UIBezierPath. Our arch requires a radius and we've chosen to generate
// one randomly in order to introduce a natural variance among the explosive paths.
// Furthermore, we've randomized whether the block flies left or right.
let randomRadius = CGFloat(UInt(arc4random_uniform(400) + 100))
let goLeft = arc4random_uniform(100) % 2 == 0
var point = pointForColumn(block.column, row: block.row)
point = CGPointMake(point.x + (goLeft ? -randomRadius : randomRadius), point.y)
let randomDuration = NSTimeInterval(arc4random_uniform(2)) + 0.5
// We choose beginning and starting angles, these are clearly in radians
// When going left, we begin at 0 radians and end at π. When going right, we go from π to
// 2π. Math FTW!
var startAngle = CGFloat(M_PI)
var endAngle = startAngle * 2
if goLeft
{
endAngle = startAngle
startAngle = 0
}
let archPath = UIBezierPath(arcCenter: point, radius: randomRadius, startAngle: startAngle, endAngle: endAngle, clockwise: goLeft)
let archAction = SKAction.followPath(archPath.CGPath, asOffset: false, orientToPath: true, duration: randomDuration)
archAction.timingMode = .EaseIn
let sprite = block.sprite!
// We place the block sprite above the others such that they animate above the other blocks
// and begin the sequence of actions which concludes with the sprite being removed from the
// scene.
sprite.zPosition = 100
sprite.runAction(
SKAction.sequence(
[SKAction.group([archAction, SKAction.fadeOutWithDuration(NSTimeInterval(randomDuration))]),
SKAction.removeFromParent()]))
}
}
// We run the completion action after a duration matching the time it will take to drop the last
// block to its new resting place.
runAction(SKAction.waitForDuration(longestDuration), completion:completion)
}
}
|
gpl-2.0
|
e15e3283b7d09287f97266f75bbabeda
| 44.040984 | 146 | 0.612739 | 4.923835 | false | false | false | false |
spacedrabbit/100-days
|
One00Days/One00Days/HexShapes.swift
|
1
|
6830
|
//
// HexShapes.swift
// One00Days
//
// Created by Louis Tur on 3/6/16.
// Copyright © 2016 SRLabs. All rights reserved.
//
import Foundation
import UIKit
typealias HexPoints = [CGPoint]
typealias HexColors = (leftColor: UIColor, rightColor: UIColor, topColor: UIColor)
typealias PrismColors = (leftColor: UIColor, rightColor: UIColor, bottomColor: UIColor)
class HexCube {
// TODO: need to map this enum to their CGPoints
enum HexPlacement {
case toTheLeft
case toTheRight
case above
case below
case infront
case behind
}
static let numberOfVertices: Int = 6
var vertexPoints: HexPoints = []
var leftSidePoints: HexPoints = []
var frontSidePoints: HexPoints = []
var topSidePoints: HexPoints = []
var bottomSidePoints: HexPoints = []
var rightSidePoints: HexPoints = []
var backSidePoints: HexPoints = []
var prismLeftSidePoints: HexPoints = []
var prismFrontSidePoints: HexPoints = []
var centerPoint: CGPoint = CGPoint(x: 0.0, y: 0.0)
var prismApexPoint: CGPoint = CGPoint(x: 0.0, y: 0.0)
var originPointForHexPlacedAbove: CGPoint = CGPoint(x: 0.0, y: 0.0)
var originPointForHexPlacedBelow: CGPoint = CGPoint(x: 0.0, y: 0.0)
var originPointForHexToTheLeft: CGPoint = CGPoint(x: 0.0, y: 0.0)
var originPointForHexToTheRight: CGPoint = CGPoint(x: 0.0, y: 0.0)
var originPointForHexInFront: CGPoint = CGPoint(x: 0.0, y: 0.0)
var originPointForHexPlacedBehind: CGPoint = CGPoint(x: 0.0, y: 0.0)
let defaultHexColorPalette: HexColors = (ColorSwatch.sr_coolWhite, ColorSwatch.sr_darkChalkGreen, ColorSwatch.sr_mintGreen)
let defaultPrismColorPalette: PrismColors = (ColorSwatch.sr_darkTeal, ColorSwatch.sr_mediumTeal, ColorSwatch.sr_coolWhite)
// TODO: this is getting all a little too messy
// 1. This doesn't need to return the points, it's of no use to anyone other than this class. Make private
// alternatively, keep this, and have drawHexCube(inView:colors:) call this directly
internal func vertexPointsForHexCube(withOrigin origin: CGPoint, radius: CGFloat) -> HexPoints{
var points: HexPoints = []
let center: CGPoint = origin
let radius: CGFloat = radius
let angleSize: CGFloat = deg2Rad((360.0 / CGFloat(HexCube.numberOfVertices)))
let rotationAdjustment: CGFloat = deg2Rad(90.0) // rotates hex a bit for stylistic purpose
for vertex in 1...HexCube.numberOfVertices {
let dx: CGFloat = center.x - radius * cos(CGFloat(vertex) * angleSize + rotationAdjustment)
let dy: CGFloat = center.y - radius * sin(CGFloat(vertex) * angleSize + rotationAdjustment)
points.append(CGPoint(x: dx, y: dy))
}
self.vertexPoints = points;
self.leftSidePoints = [points[2], points[3], points[4]]
self.frontSidePoints = [points[0], points[1], points[2]]
self.topSidePoints = [points[4], points[5], points[0]]
self.bottomSidePoints = [points[1], points[2], points[3]]
self.rightSidePoints = [points[5], points[0], points[1]]
self.backSidePoints = [points[3], points[4], points[5]]
self.centerPoint = center
self.originPointForHexPlacedAbove = points[5]
self.originPointForHexPlacedBelow = points[2]
self.originPointForHexToTheLeft = points[3]
self.originPointForHexToTheRight = points[0]
self.originPointForHexInFront = points[1]
self.originPointForHexPlacedBehind = points[4]
self.prismApexPoint = self.midPointOf(points[4], b: points[0])
self.prismLeftSidePoints = [self.prismApexPoint, points[2], points[3]]
self.prismFrontSidePoints = [self.prismApexPoint, points[1], points[2]]
return points
}
/// Drawing functions
// TODO: - this is probably better returning a view or layer than adding to it internally
internal func drawHexCube(inView view: UIView, colors: HexColors) {
let leftsideLayer: CAShapeLayer = self.drawLeftSideOfHex(self.leftSidePoints, color: colors.leftColor)
let frontSideLayer: CAShapeLayer = self.drawFrontSideOfHex(self.frontSidePoints, color: colors.rightColor)
let topsideLayer: CAShapeLayer = self.drawTopSideOfHex(self.topSidePoints, color: colors.topColor)
view.layer.addSublayer(leftsideLayer)
view.layer.addSublayer(frontSideLayer)
view.layer.addSublayer(topsideLayer)
}
internal func drawDefaultHexCube(inView view: UIView) {
self.drawHexCube(inView: view, colors: self.defaultHexColorPalette)
}
// TODO: - "on top of" and not "on" the cube
internal func drawPrismOnCube(inView view: UIView, colors: PrismColors) {
let prismLeftLayer: CAShapeLayer = self.drawLeftSideOfPrism(self.prismLeftSidePoints, color: colors.leftColor)
let prismFrontLayer: CAShapeLayer = self.drawFrontSideOfPrism(self.prismFrontSidePoints, color: colors.rightColor)
view.layer.addSublayer(prismLeftLayer)
view.layer.addSublayer(prismFrontLayer)
}
internal func drawDefaultPrismOnCube(inView view: UIView) {
self.drawPrismOnCube(inView: view, colors: self.defaultPrismColorPalette)
}
/// Helper Drawing Functions
fileprivate func drawLeftSideOfHex(_ points: HexPoints, color: UIColor) -> CAShapeLayer {
let path: UIBezierPath = UIBezierPath()
path.move(to: points[0])
path.addLine(to: points[1])
path.addLine(to: points[2])
path.addLine(to: self.centerPoint)
path.close()
let layer: CAShapeLayer = CAShapeLayer()
layer.path = path.cgPath
layer.fillColor = color.cgColor
layer.strokeColor = color.cgColor
layer.lineWidth = 2.0
path.stroke()
return layer
}
fileprivate func drawFrontSideOfHex(_ points: HexPoints, color: UIColor) -> CAShapeLayer {
return self.drawLeftSideOfHex(points, color: color)
}
fileprivate func drawTopSideOfHex(_ points: HexPoints, color: UIColor) -> CAShapeLayer {
return self.drawLeftSideOfHex(points, color: color)
}
fileprivate func drawLeftSideOfPrism(_ points: HexPoints, color: UIColor) -> CAShapeLayer {
let path: UIBezierPath = UIBezierPath()
path.move(to: points[0])
path.addLine(to: points[1])
path.addLine(to: points[2])
path.close()
let layer: CAShapeLayer = CAShapeLayer()
layer.path = path.cgPath
layer.fillColor = color.cgColor
layer.strokeColor = color.cgColor
layer.lineWidth = 1.0
layer.lineJoin = kCALineCapRound
path.stroke()
return layer
}
fileprivate func drawFrontSideOfPrism(_ points: HexPoints, color: UIColor) -> CAShapeLayer {
return self.drawLeftSideOfPrism(points, color: color)
}
/// Helpers
fileprivate func deg2Rad(_ degrees: CGFloat) -> CGFloat {
return CGFloat(M_PI) * degrees/180.0
}
fileprivate func midPointOf(_ a: CGPoint, b: CGPoint) -> CGPoint {
return CGPoint(x: (a.x + b.x) / 2.0, y: (a.y + b.y) / 2.0)
}
}
|
mit
|
429413dcf5b433b3e5c77df0d1a08a55
| 36.31694 | 125 | 0.709621 | 3.636315 | false | false | false | false |
seandavidmcgee/HumanKontactBeta
|
src/HumanKontact Extension/ExtensionDelegate.swift
|
1
|
6080
|
//
// ExtensionDelegate.swift
// HumanKontact Extension
//
// Created by Sean McGee on 10/5/15.
// Copyright © 2015 Kannuu. All rights reserved.
//
import WatchKit
import WatchConnectivity
var lookupWatchController : KannuuIndexController? = nil
class ExtensionDelegate: NSObject, WKExtensionDelegate, WCSessionDelegate {
var session : WCSession!
var fileCount = 0
var recentsDelegate: SearchController?
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
if (WCSession.isSupported()) {
session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}
if session.reachable == false {
print("not reachable")
return
}
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let docsDir = dirPaths[0] as String
let filemgr = NSFileManager.defaultManager()
let indexFilePath = self.indexFile
if filemgr.fileExistsAtPath(docsDir + "/default.realm") {
lookupWatchController = KannuuIndexController(controllerMode: .Lookup, indexFilePath: indexFilePath, numberOfOptions: 26, numberOfBranchSelections: 999)
}
}
func applicationDidBecomeActive() {
}
func applicationWillResignActive() {
// 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, etc.
}
internal var indexFile : String {
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let hkIndexPath = documentsURL.path!.stringByAppendingPathComponent("HKIndex")
return hkIndexPath
}
// Received message from iPhone
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
// Reply handler, received message
let recentValue = message["recent"]
if recentValue != nil {
let recordKey = recentValue as? String
self.addRecent(recordKey!)
// Send a reply
replyHandler(["reply": "Recent added"])
}
let value = message["complete"] as? String
if value == "Realm" {
print(value!)
// Send a reply
replyHandler(["reply": "Realm added"])
}
}
func addRecent(key: String) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.addRecentSubTask(key)
})
}
func addRecentSubTask(key: String) {
let person = peopleRealm.objectForPrimaryKey(HKPerson.self, key: key)
var recentIndexCount = Int()
if People.contacts.count > 0 {
recentIndexCount = People.contacts.first!.recentIndex
} else {
recentIndexCount = 0
}
do {
let realm = ABWatchManager.peopleRealm()
realm.beginWrite()
person!.recent = true
person!.recentIndex = recentIndexCount + 1
try realm.commitWrite()
recentsDelegate?.reloadTableData(false)
} catch let error as NSError {
print("Error moving file: \(error.description)")
}
}
func sendRecentToPhone(record: String) {
let msg = ["recent": record]
session.sendMessage(msg, replyHandler: { (replyMessage) -> Void in
// Reply handler - present the reply message on screen
let value = replyMessage["reply"] as? String
if value == "Recent added" {
print(value!)
}
}) { (error:NSError) -> Void in
print(error.localizedDescription)
}
}
func requestToPhone() {
let msg = ["request": "Realm"]
session.sendMessage(msg, replyHandler: { (replyMessage) -> Void in
// Reply handler - present the reply message on screen
let value = replyMessage["reply"] as? String
if value == "Realm sent" {
print(value!)
}
}) { (error:NSError) -> Void in
print(error.localizedDescription)
}
}
// Received file from iPhone
func session(session: WCSession, didReceiveFile file: WCSessionFile) {
print("Received File: \(file)")
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let docsDir = dirPaths[0] as String
let filemgr = NSFileManager.defaultManager()
let fileName = file.fileURL.pathComponents!.last!
print(fileName)
do {
if !filemgr.fileExistsAtPath(docsDir + "/\(fileName)") {
try filemgr.moveItemAtPath(file.fileURL.path!, toPath: docsDir + "/\(fileName)")
fileCount++
continueToSearch()
} else {
try filemgr.removeItemAtPath(docsDir + "/\(fileName)")
try filemgr.moveItemAtPath(file.fileURL.path!, toPath: docsDir + "/\(fileName)")
fileCount++
continueToSearch()
}
} catch let error as NSError {
print("Error moving file: \(error.description)")
}
}
func continueToSearch() {
if fileCount >= 7 {
let indexFilePath = self.indexFile
lookupWatchController = KannuuIndexController(controllerMode: .Lookup, indexFilePath: indexFilePath, numberOfOptions: 26, numberOfBranchSelections: 999)
WKExtension.sharedExtension().rootInterfaceController!.pushControllerWithName("Search", context: nil)
}
}
}
|
mit
|
24044a7abc1cb1d23f84e86ab8f45331
| 36.294479 | 285 | 0.605363 | 5.240517 | false | false | false | false |
wordpress-mobile/WordPress-Aztec-iOS
|
Aztec/Classes/TextKit/TextStorage.swift
|
1
|
18144
|
import Foundation
import UIKit
/// Implemented by a class taking care of handling attachments for the storage.
///
protocol TextStorageAttachmentsDelegate: class {
/// Provides images for attachments that are part of the storage
///
/// - Parameters:
/// - storage: The storage that is requesting the image.
/// - attachment: The attachment that is requesting the image.
/// - url: url for the image.
/// - success: Callback block to be invoked with the image fetched from the url.
/// - failure: Callback block to be invoked when an error occurs when fetching the image.
///
func storage(
_ storage: TextStorage,
attachment: NSTextAttachment,
imageFor url: URL,
onSuccess success: @escaping (UIImage) -> (),
onFailure failure: @escaping () -> ())
/// Provides an image placeholder for a specified attachment.
///
/// - Parameters:
/// - storage: The storage that is requesting the image.
/// - attachment: The attachment that is requesting the image.
///
/// - Returns: An Image placeholder to be rendered onscreen.
///
func storage(_ storage: TextStorage, placeholderFor attachment: NSTextAttachment) -> UIImage
/// Called when an image is about to be added to the storage as an attachment, so that the
/// delegate can specify an URL where that image is available.
///
/// - Parameters:
/// - storage: The storage that is requesting the image.
/// - imageAttachment: The image that was added to the storage.
///
/// - Returns: the requested `URL` where the image is stored, or nil if it's not yet available.
///
func storage(_ storage: TextStorage, urlFor imageAttachment: ImageAttachment) -> URL?
/// Called when a attachment is removed from the storage.
///
/// - Parameters:
/// - textView: The textView where the attachment was removed.
/// - attachment: The media attachment that was removed.
///
func storage(_ storage: TextStorage, deletedAttachment: MediaAttachment)
/// Provides the Bounds required to represent a given attachment, within a specified line fragment.
///
/// - Parameters:
/// - storage: The storage that is requesting the bounds.
/// - attachment: NSTextAttachment about to be rendered.
/// - lineFragment: Line Fragment in which the glyph would be rendered.
///
/// - Returns: Rect specifying the Bounds for the attachment
///
func storage(_ storage: TextStorage, boundsFor attachment: NSTextAttachment, with lineFragment: CGRect) -> CGRect
/// Provides the (Optional) Image Representation of the specified size, for a given Attachment.
///
/// - Parameters:
/// - storage: The storage that is requesting the bounds.
/// - attachment: NSTextAttachment about to be rendered.
/// - size: Expected Image Size
///
/// - Returns: (Optional) UIImage representation of the attachment.
///
func storage(_ storage: TextStorage, imageFor attachment: NSTextAttachment, with size: CGSize) -> UIImage?
}
/// Custom NSTextStorage
///
open class TextStorage: NSTextStorage {
// MARK: - HTML Conversion
public let htmlConverter = HTMLConverter()
// MARK: - PluginManager
var pluginManager: PluginManager {
get {
return htmlConverter.pluginManager
}
}
// MARK: - Storage
fileprivate var textStore = NSMutableAttributedString(string: "", attributes: nil)
fileprivate var textStoreString = ""
// MARK: - Delegates
/// NOTE:
/// `attachmentsDelegate` is an optional property. On purpose. During a Drag and Drop OP, the
/// LayoutManager may instantiate an entire TextKit stack. Since there is absolutely no entry point
/// in which we may set this delegate, we need to set it as optional.
///
/// Ref. https://github.com/wordpress-mobile/AztecEditor-iOS/issues/727
///
weak var attachmentsDelegate: TextStorageAttachmentsDelegate?
// MARK: - Calculated Properties
override open var string: String {
return textStoreString
}
open var mediaAttachments: [MediaAttachment] {
let range = NSMakeRange(0, length)
var attachments = [MediaAttachment]()
enumerateAttribute(.attachment, in: range, options: []) { (object, range, stop) in
if let attachment = object as? MediaAttachment {
attachments.append(attachment)
}
}
return attachments
}
// MARK: - Range Methods
func range<T : NSTextAttachment>(for attachment: T) -> NSRange? {
var range: NSRange?
textStore.enumerateAttachmentsOfType(T.self) { (currentAttachment, currentRange, stop) in
if attachment == currentAttachment {
range = currentRange
stop.pointee = true
}
}
return range
}
// MARK: - NSAttributedString preprocessing
private func preprocessAttributesForInsertion(_ attributedString: NSAttributedString) -> NSAttributedString {
let stringWithAttachments = preprocessAttachmentsForInsertion(attributedString)
return stringWithAttachments
}
/// Preprocesses an attributed string's attachments for insertion in the storage.
///
/// - Important: This method takes care of removing any non-image attachments too. This may
/// change in future versions.
///
/// - Parameters:
/// - attributedString: the string we need to preprocess.
///
/// - Returns: the preprocessed string.
///
fileprivate func preprocessAttachmentsForInsertion(_ attributedString: NSAttributedString) -> NSAttributedString {
// Ref. https://github.com/wordpress-mobile/AztecEditor-iOS/issues/727:
// If the delegate is not set, we *Explicitly* do not want to crash here.
//
guard let delegate = attachmentsDelegate else {
return attributedString
}
let fullRange = NSRange(location: 0, length: attributedString.length)
let finalString = NSMutableAttributedString(attributedString: attributedString)
attributedString.enumerateAttribute(.attachment, in: fullRange, options: []) { (object, range, stop) in
guard let object = object else {
return
}
guard let textAttachment = object as? NSTextAttachment else {
assertionFailure("We expected a text attachment object.")
return
}
switch textAttachment {
case _ as LineAttachment:
break
case let attachment as MediaAttachment:
attachment.delegate = self
case let attachment as RenderableAttachment:
attachment.delegate = self
default:
guard let image = textAttachment.image else {
// We only suppot image attachments for now. All other attachment types are
// stripped for safety.
//
finalString.removeAttribute(.attachment, range: range)
return
}
let replacementAttachment = ImageAttachment(identifier: NSUUID().uuidString)
replacementAttachment.delegate = self
replacementAttachment.image = image
replacementAttachment.size = .full
let imageURL = delegate.storage(self, urlFor: replacementAttachment)
replacementAttachment.updateURL(imageURL)
finalString.addAttribute(.attachment, value: replacementAttachment, range: range)
}
}
return finalString
}
fileprivate func detectAttachmentRemoved(in range: NSRange) {
// Ref. https://github.com/wordpress-mobile/AztecEditor-iOS/issues/727:
// If the delegate is not set, we *Explicitly* do not want to crash here.
//
guard let delegate = attachmentsDelegate else {
return
}
textStore.enumerateAttachmentsOfType(MediaAttachment.self, range: range) { (attachment, range, stop) in
delegate.storage(self, deletedAttachment: attachment)
}
}
// MARK: - Overriden Methods
/// Retrieves the attributes for the requested character location.
///
/// - Important: please note that this method returns the style at the character location, and
/// NOT at the caret location. For N characters we always have N+1 character locations.
///
override open func attributes(at location: Int, effectiveRange range: NSRangePointer?) -> [NSAttributedString.Key : Any] {
guard textStore.length > 0 else {
return [:]
}
return textStore.attributes(at: location, effectiveRange: range)
}
private func replaceTextStoreString(_ range: NSRange, with string: String) {
let utf16String = textStoreString.utf16
let startIndex = utf16String.index(utf16String.startIndex, offsetBy: range.location)
let endIndex = utf16String.index(startIndex, offsetBy: range.length)
textStoreString.replaceSubrange(startIndex..<endIndex, with: string)
}
override open func replaceCharacters(in range: NSRange, with str: String) {
beginEditing()
detectAttachmentRemoved(in: range)
textStore.replaceCharacters(in: range, with: str)
replaceTextStoreString(range, with: str)
edited(.editedCharacters, range: range, changeInLength: str.count - range.length)
endEditing()
}
override open func replaceCharacters(in range: NSRange, with attrString: NSAttributedString) {
let preprocessedString = preprocessAttributesForInsertion(attrString)
beginEditing()
detectAttachmentRemoved(in: range)
textStore.replaceCharacters(in: range, with: preprocessedString)
replaceTextStoreString(range, with: attrString.string)
edited([.editedAttributes, .editedCharacters], range: range, changeInLength: attrString.length - range.length)
endEditing()
}
override open func setAttributes(_ attrs: [NSAttributedString.Key: Any]?, range: NSRange) {
beginEditing()
let fixedAttributes = ensureMatchingFontAndParagraphHeaderStyles(beforeApplying: attrs ?? [:], at: range)
textStore.setAttributes(fixedAttributes, range: range)
edited(.editedAttributes, range: range, changeInLength: 0)
endEditing()
}
// MARK: - Styles: Toggling
@discardableResult
func toggle(formatter: AttributeFormatter, at range: NSRange) -> NSRange {
let applicationRange = formatter.applicationRange(for: range, in: self)
guard applicationRange.length > 0 else {
return applicationRange
}
return formatter.toggle(in: self, at: applicationRange)
}
// MARK: - Attachments
/// Return the attachment, if any, corresponding to the id provided
///
/// - Parameter id: the unique id of the attachment
/// - Returns: the attachment object
///
func attachment(withId id: String) -> MediaAttachment? {
var foundAttachment: MediaAttachment? = nil
enumerateAttachmentsOfType(MediaAttachment.self) { (attachment, range, stop) in
if attachment.identifier == id {
foundAttachment = attachment
stop.pointee = true
}
}
return foundAttachment
}
/// Return the range of an attachment with the specified identifier if any
///
/// - Parameter attachmentID: the id of the attachment
/// - Returns: the range of the attachment
///
open func rangeFor(attachmentID: String) -> NSRange? {
var foundRange: NSRange?
enumerateAttachmentsOfType(MediaAttachment.self) { (attachment, range, stop) in
if attachment.identifier == attachmentID {
foundRange = range
stop.pointee = true
}
}
return foundRange
}
/// Removes all of the MediaAttachments from the storage
///
open func removeMediaAttachments() {
var ranges = [NSRange]()
enumerateAttachmentsOfType(MediaAttachment.self) { (attachment, range, _) in
ranges.append(range)
}
var delta = 0
for range in ranges {
let corrected = NSRange(location: range.location - delta, length: range.length)
replaceCharacters(in: corrected, with: NSAttributedString(string: ""))
delta += range.length
}
}
private func enumerateRenderableAttachments(in text: NSAttributedString, range: NSRange? = nil, block: ((RenderableAttachment, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void)) {
let range = range ?? NSMakeRange(0, length)
text.enumerateAttribute(.attachment, in: range, options: []) { (object, range, stop) in
if let object = object as? RenderableAttachment {
block(object, range, stop)
}
}
}
// MARK: - HTML Interaction
open func getHTML(prettify: Bool = false) -> String {
return htmlConverter.html(from: self, prettify: prettify)
}
open func getHTML(prettify: Bool = false, range: NSRange) -> String {
return htmlConverter.html(from: self.attributedSubstring(from: range), prettify: prettify)
}
open func getHTML(prettify: Bool = false, from attributedString: NSAttributedString) -> String {
return htmlConverter.html(from: attributedString, prettify: prettify)
}
func setHTML(_ html: String, defaultAttributes: [NSAttributedString.Key: Any]) {
let originalLength = length
let attrString = htmlConverter.attributedString(from: html, defaultAttributes: defaultAttributes)
textStore = NSMutableAttributedString(attributedString: attrString)
textStoreString = textStore.string
setupAttachmentDelegates()
edited([.editedAttributes, .editedCharacters], range: NSRange(location: 0, length: originalLength), changeInLength: textStore.length - originalLength)
}
private func setupAttachmentDelegates() {
textStore.enumerateAttachmentsOfType(MediaAttachment.self) { [weak self] (attachment, _, _) in
attachment.delegate = self
}
enumerateRenderableAttachments(in: textStore, block: { [weak self] (attachment, _, _) in
attachment.delegate = self
})
}
}
// MARK: - Header Font Attribute Fixes
//
private extension TextStorage {
/// Ensures the font style is consistent with the paragraph header style that's about to be applied.
///
/// - Parameters:
/// - attrs: NSAttributedString attributes that are about to be applied.
/// - range: Range that's about to be affected by the new Attributes collection.
///
/// - Returns: Collection of attributes with the Font Attribute corrected, if needed.
///
func ensureMatchingFontAndParagraphHeaderStyles(beforeApplying attrs: [NSAttributedString.Key: Any], at range: NSRange) -> [NSAttributedString.Key: Any] {
let newStyle = attrs[.paragraphStyle] as? ParagraphStyle
let oldStyle = textStore.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? ParagraphStyle
let newLevel = newStyle?.headers.last?.level ?? .none
let oldLevel = oldStyle?.headers.last?.level ?? .none
guard oldLevel != newLevel && newLevel != .none else {
return attrs
}
return fixFontAttribute(in: attrs, headerLevel: newLevel)
}
/// This helper re-applies the HeaderFormatter to the specified collection of attributes, so that the Font Attribute is explicitly set,
/// and it matches the target HeaderLevel.
///
/// - Parameters:
/// - attrs: NSAttributedString attributes that are about to be applied.
/// - headerLevel: HeaderLevel specified by the ParagraphStyle, associated to the application range.
///
/// - Returns: Collection of attributes with the Font Attribute corrected, so that it matches the specified HeaderLevel.
///
private func fixFontAttribute(in attrs: [NSAttributedString.Key: Any], headerLevel: Header.HeaderType) -> [NSAttributedString.Key: Any] {
let formatter = HeaderFormatter(headerLevel: headerLevel)
return formatter.apply(to: attrs)
}
}
// MARK: - TextStorage: MediaAttachmentDelegate Methods
//
extension TextStorage: MediaAttachmentDelegate {
func mediaAttachmentPlaceholder(for attachment: MediaAttachment) -> UIImage {
guard let delegate = attachmentsDelegate else {
fatalError()
}
return delegate.storage(self, placeholderFor: attachment)
}
func mediaAttachment(
_ mediaAttachment: MediaAttachment,
imageFor url: URL,
onSuccess success: @escaping (UIImage) -> (),
onFailure failure: @escaping () -> ())
{
guard let delegate = attachmentsDelegate else {
fatalError()
}
delegate.storage(self, attachment: mediaAttachment, imageFor: url, onSuccess: success, onFailure: failure)
}
}
// MARK: - TextStorage: RenderableAttachmentDelegate Methods
//
extension TextStorage: RenderableAttachmentDelegate {
public func attachment(_ attachment: NSTextAttachment, imageForSize size: CGSize) -> UIImage? {
guard let delegate = attachmentsDelegate else {
fatalError()
}
return delegate.storage(self, imageFor: attachment, with: size)
}
public func attachment(_ attachment: NSTextAttachment, boundsForLineFragment fragment: CGRect) -> CGRect {
guard let delegate = attachmentsDelegate else {
fatalError()
}
return delegate.storage(self, boundsFor: attachment, with: fragment)
}
}
|
gpl-2.0
|
c8ba8e9de76160a551c3c5f006b61fae
| 36.104294 | 183 | 0.647817 | 5.16041 | false | false | false | false |
maxbilbow/iOS-8-SceneKit-Globe-Test
|
SceneKitTest/GlobeScene.swift
|
2
|
3878
|
//
// GlobeScene.swift
// SceneKitTest
//
// Created by Jonathan Wight on 6/6/14.
// Copyright (c) 2014 schwa.io. All rights reserved.
//
import SceneKit
import QuartzCore
class GlobeScene: SCNScene {
var camera: SCNCamera
var cameraNode: SCNNode
var ambientLightNode: SCNNode
var globeNode: SCNNode
override init() {
self.camera = SCNCamera()
self.camera.zNear = 0.01
self.cameraNode = SCNNode()
self.cameraNode.position = SCNVector3(x: 0.0, y: 0.0, z: 1.5)
self.cameraNode.camera = self.camera
self.camera.focalBlurRadius = 0;
// CABasicAnimation *theFocusAnimation = [CABasicAnimation animationWithKeyPath:"focalBlurRadius"];
// theFocusAnimation.fromValue = @(100);
// theFocusAnimation.toValue = @(0);
// theFocusAnimation.duration = 2.0;
// theFocusAnimation.removedOnCompletion = YES;
// [self.camera addAnimation:theFocusAnimation forKey:@"focus"];
let theAmbientLight = SCNLight()
theAmbientLight.type = SCNLightTypeAmbient
theAmbientLight.color = UIColor(white: 0.5, alpha: 1.0)
self.ambientLightNode = SCNNode()
self.ambientLightNode.light = theAmbientLight
self.globeNode = SCNNode()
let theGlobeGeometry = SCNSphere(radius: 0.5)
theGlobeGeometry.firstMaterial?.diffuse.contents = UIImage(named:"earth_diffuse.jpg")
theGlobeGeometry.firstMaterial?.ambient.contents = UIImage(named:"earth_ambient2.jpeg")
// theGlobeGeometry.firstMaterial?.ambient.contents = UIImage(named:"earth_ambient.jpg")
theGlobeGeometry.firstMaterial?.specular.contents = UIImage(named:"earth_specular.jpg")
theGlobeGeometry.firstMaterial?.emission.contents = nil
theGlobeGeometry.firstMaterial?.transparent.contents = nil
theGlobeGeometry.firstMaterial?.reflective.contents = nil
theGlobeGeometry.firstMaterial?.multiply.contents = nil
theGlobeGeometry.firstMaterial?.normal.contents = UIImage(named:"earth_normal.jpg")
let theGlobeModelNode = SCNNode(geometry: theGlobeGeometry)
self.globeNode.addChildNode(theGlobeModelNode)
let theCloudGeometry = SCNSphere(radius:0.505)
theCloudGeometry.firstMaterial?.diffuse.contents = nil
theCloudGeometry.firstMaterial?.ambient.contents = nil
theCloudGeometry.firstMaterial?.specular.contents = nil
theCloudGeometry.firstMaterial?.emission.contents = nil
theCloudGeometry.firstMaterial?.transparent.contents = UIImage(named:"earth_clouds.png")
theCloudGeometry.firstMaterial?.reflective.contents = nil
theCloudGeometry.firstMaterial?.multiply.contents = nil
theCloudGeometry.firstMaterial?.normal.contents = nil
let theCloudModelNode = SCNNode(geometry: theCloudGeometry)
self.globeNode.addChildNode(theCloudModelNode)
// animate the 3d object
let animation: CABasicAnimation = CABasicAnimation(keyPath: "rotation")
animation.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 1, z: 0, w: Float(M_PI)*2))
animation.duration = 500
animation.repeatCount = MAXFLOAT //repeat forever
self.globeNode.addAnimation(animation, forKey: nil)
// animate the 3d object
let cloudAnimation: CABasicAnimation = CABasicAnimation(keyPath: "rotation")
cloudAnimation.toValue = NSValue(SCNVector4: SCNVector4(x: -1, y: 2, z: 0, w: Float(M_PI)*2))
cloudAnimation.duration = 1050
cloudAnimation.repeatCount = .infinity //repeat forever
theCloudModelNode.addAnimation(cloudAnimation, forKey: nil)
super.init()
self.rootNode.addChildNode(self.cameraNode)
self.rootNode.addChildNode(self.ambientLightNode)
self.rootNode.addChildNode(self.globeNode)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
bsd-2-clause
|
b4c3e70ebb916efa9e93751fb8b87d3b
| 39.395833 | 106 | 0.715317 | 4.206074 | false | false | false | false |
phimage/MomXML
|
Sources/Model/MomUniquenessConstraints.swift
|
1
|
1215
|
//
// MomUniquenessConstraints.swift
// MomXML
//
// Created by Eric Marchand on 01/07/2020.
// Copyright © 2020 phimage. All rights reserved.
//
import Foundation
public struct MomUniquenessConstraints {
public var constraints: [MomUniquenessConstraint] = []
public mutating func add(constraint: MomUniquenessConstraint) {
self.constraints.append(constraint)
}
public var isEmpty: Bool {
return constraints.isEmpty
}
public init(uniquenessConstraints: [[Any]] = []) {
self.constraints = uniquenessConstraints.compactMap { MomUniquenessConstraint(constraints: $0) }
}
}
public struct MomUniquenessConstraint {
public var constraints: [MomConstraint] = []
public init() {}
public init?(constraints: [Any]) {
self.constraints = constraints.compactMap { MomConstraint(any: $0) }
if self.constraints.isEmpty {
return nil
}
}
}
public struct MomConstraint {
public var value: String
public init(value: String) {
self.value = value
}
public init?(any: Any) {
guard let value = any as? String else {
return nil
}
self.value = value
}
}
|
mit
|
6e6eee20c76b88f4e080239828e3f851
| 21.481481 | 104 | 0.640033 | 4.171821 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.