hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
db91afb4026f6e622807b696c2c3a7c0db496242 | 1,652 | //
// CombinationSumTests.swift
// LeetCodeTests
//
// Created by William Boles on 23/02/2022.
//
import XCTest
@testable import LeetCode
class CombinationSumTests: XCTestCase {
// MARK: - Tests
func test_A() {
let candidates = [2, 3, 6, 7]
let target = 7
let combinations = CombinationSum.combinationSum(candidates, target)
let expectedCombinations = [[2, 2, 3], [7]]
//order isn't important
for combination in combinations {
XCTAssertTrue(expectedCombinations.contains(combination))
}
XCTAssertEqual(combinations.count, expectedCombinations.count)
}
func test_B() {
let candidates = [2, 3, 5]
let target = 8
let combinations = CombinationSum.combinationSum(candidates, target)
let expectedCombinations = [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
//order isn't important
for combination in combinations {
XCTAssertTrue(expectedCombinations.contains(combination))
}
XCTAssertEqual(combinations.count, expectedCombinations.count)
}
func test_C() {
let candidates = [2]
let target = 1
let combinations = CombinationSum.combinationSum(candidates, target)
let expectedCombinations = [[Int]]()
//order isn't important
for combination in combinations {
XCTAssertTrue(expectedCombinations.contains(combination))
}
XCTAssertEqual(combinations.count, expectedCombinations.count)
}
}
| 25.8125 | 76 | 0.590799 |
1647e7f005a0f434ecaaec05c46c56a53c243b15 | 707 | //
// SplashListener.swift
// TogetherAd
//
// Created by 徐佳吉 on 2021/11/8.
//
import Foundation
public protocol SplashListener : BaseListener {
/**
* 请求到了广告
*/
func onAdLoaded(providerType: String)
/**
* 广告被点击了
*/
func onAdClicked(providerType: String)
/**
* 广告曝光了
*/
func onAdExposure(providerType: String)
/**
* 广告消失了( 点击跳过或者倒计时结束 )
*/
func onAdDismissed(providerType: String)
}
extension SplashListener {
public func onAdLoaded(providerType: String) {}
public func onAdClicked(providerType: String) {}
public func onAdExposure(providerType: String) {}
public func onAdDismissed(providerType: String) {}
}
| 18.128205 | 54 | 0.64215 |
46013a3e59ab56f4672c36594096fbdfc3c7c84e | 1,211 | import UIKit
//Queue - 프로그래머스 다리건너는 트럭문제
struct Truck {
var myTime = 0
var myWeight:Int
}
func solution(_ bridge_length:Int, _ weight:Int, _ truck_weights:[Int]) -> Int {
var trucks:[Int] = truck_weights
var queue:[Truck] = []
var totalWeight = 0
var time = 0
while !trucks.isEmpty || !queue.isEmpty {
time += 1
if !queue.isEmpty && time - queue[0].myTime == bridge_length {
let arrivedTruck = queue.remove(at: 0)
totalWeight -= arrivedTruck.myWeight
if queue.isEmpty && trucks.isEmpty {
// print("여기 들어오면 끝인데? ",time)
return time
}
}
guard !trucks.isEmpty && (totalWeight + trucks[0]) <= weight else { continue }
let truckWeight = trucks.remove(at: 0)
queue.append(Truck.init(myTime: time, myWeight: truckWeight))
// print("--------------------------------------------")
// for x in queue {
// print("truck weight :",x.myWeight, "time :",x.myTime)
// }
totalWeight += truckWeight
}
return time
}
//solution(2, 10, [7,4,5,6])
solution(100, 100, [10])
solution(100,100, [10,10,10,10,10,10,10,10,10,10])
| 28.162791 | 86 | 0.545004 |
db5795b4506f9cdbe66d53ac5bc038acf566448d | 3,889 | //
// Size.swift
// GR
//
// Created by Wolf McNally on 11/15/20.
//
import Foundation
import Interpolate
public struct Size: Equatable, Hashable {
public var width: Double
public var height: Double
@inlinable public init<N: BinaryInteger>(width: N, height: N) {
self.width = Double(width)
self.height = Double(height)
}
@inlinable public init<N: BinaryFloatingPoint>(width: N, height: N) {
self.width = Double(width)
self.height = Double(height)
}
@inlinable public init(_ s: SIMD2<Double>) {
self.width = s.x
self.height = s.y
}
@inlinable public init(_ s: IntSize) {
self.width = Double(s.width)
self.height = Double(s.height)
}
public var simd: SIMD2<Double> {
[width, height]
}
@inlinable public var rangeX: ClosedRange<Double> { 0 ... width }
@inlinable public var rangeY: ClosedRange<Double> { 0 ... height }
public static let none = -1.0
public static let zero = Size(width: 0, height: 0)
public static let infinite = Size(width: Double.infinity, height: Double.infinity)
}
extension Size : ExpressibleByArrayLiteral {
public init(arrayLiteral a: Double...) {
if a.isEmpty {
self.width = 0
self.height = 0
} else {
assert(a.count == 2)
self.width = a[0]
self.height = a[1]
}
}
}
extension Size {
@inlinable public init(both n: Double) {
self.init(width: n, height: n)
}
@inlinable public init(_ vector: Vector) {
self.width = vector.dx
self.height = vector.dy
}
@inlinable public var bounds: Rect {
Rect(origin: .zero, size: self)
}
@inlinable public var max: Double {
Swift.max(width, height)
}
@inlinable public var min: Double {
Swift.min(width, height)
}
}
extension Size {
@inlinable public var aspect: Double {
width / height
}
public func scaleForAspectFit(within size: Size) -> Double {
if size.width != Size.none && size.height != Size.none {
return Swift.min(size.width / width, size.height / height)
} else if size.width != Size.none {
return size.width / width
} else {
return size.height / height
}
}
public func scaleForAspectFill(within size: Size) -> Double {
if size.width != Size.none && size.height != Size.none {
return Swift.max(size.width / width, size.height / height)
} else if size.width != Size.none {
return size.width / width
} else {
return size.height / height
}
}
public func aspectFit(within size: Size) -> Size {
let scale = scaleForAspectFit(within: size)
return Size(Vector(self) * scale)
}
public func aspectFill(within size: Size) -> Size {
let scale = scaleForAspectFill(within: size)
return Size(Vector(self) * scale)
}
}
extension Size: CustomDebugStringConvertible {
public var debugDescription: String {
return("Size(\(width), \(height))")
}
}
extension Size {
@inlinable public var isEmpty: Bool { width == 0.0 || height == 0.0 }
}
@inlinable public func * (lhs: Size, rhs: Double) -> Size {
Size(lhs.simd * rhs)
}
@inlinable public func / (lhs: Size, rhs: Double) -> Size {
Size(lhs.simd / rhs)
}
extension Size: ForwardInterpolable {
public func interpolate(to other: Size, at frac: Frac) -> Size {
Size(width: width.interpolate(to: other.width, at: frac),
height: height.interpolate(to: other.height, at: frac))
}
}
#if canImport(CoreGraphics)
import CoreGraphics
extension CGSize {
public init(_ s: Size) {
self.init(width: CGFloat(s.width), height: CGFloat(s.height))
}
}
#endif
| 25.418301 | 86 | 0.592954 |
ff77135b3d877bebc5451057a2eac6acd3dd5d91 | 2,735 | //
// MemoryGame.swift
// Memorize
//
// Created by Nick Yang on 2022/1/23.
//
import Foundation
// Model: data + logic
struct MemoryGame<CardContent> where CardContent: Equatable { // generic over CardContent
private(set) var cards: Array<Card>
private var indexOfTheOneAndOnlyFaceUpCard: Int?
// HINT: struct default is immutable
mutating func choose(_ card: Card) {
// if let chosenIndex = index(of: card) { // indexOf is readable
// if let chosenIndex = cards.firstIndex(where: { aCardInTheCardsArray in aCardInTheCardsArray.id == card.id }) { // more Englishy
if let chosenIndex = cards.firstIndex(where: { $0.id == card.id }),
!cards[chosenIndex].isFaceUp,
!cards[chosenIndex].isMatched
{
// var chosenCard = cards[chosenIndex]
// card.isFaceUp = !card.isFaceUp
// chosenCard.isFaceUp.toggle()
if let potentialMatchIndex = indexOfTheOneAndOnlyFaceUpCard {
if cards[chosenIndex].content == cards[potentialMatchIndex].content {
cards[chosenIndex].isMatched = true
cards[potentialMatchIndex].isMatched = true
}
indexOfTheOneAndOnlyFaceUpCard = nil
} else {
// for index in 0..<cards.count {
for index in cards.indices {
cards[index].isFaceUp = false
}
indexOfTheOneAndOnlyFaceUpCard = chosenIndex
}
cards[chosenIndex].isFaceUp.toggle()
// `print` is a good way for debugging
// automatically display console: Xcode -> Preferences -> Behaviors -> Generates Outputs
// print("chosenCard = \(chosenCard)")
}
print("\(cards)")
}
func index(of card: Card) -> Int? {
for index in 0..<cards.count {
if cards[index].id == card.id {
return index
}
}
return nil
}
init (numberOfPairsOfCards: Int, createCardContent: (Int) -> CardContent) {
cards = Array<Card>()
// add numberOfPairsOfCards x 2 cards to array
for pairIndex in 0..<numberOfPairsOfCards {
let content: CardContent = createCardContent(pairIndex)
cards.append(Card(content: content, id: pairIndex*2))
cards.append(Card(content: content, id: pairIndex*2+1))
}
}
struct Card: Identifiable { // make struct can be identifiable
var isFaceUp: Bool = false
var isMatched: Bool = false
var content: CardContent
var id: Int
}
}
| 35.519481 | 137 | 0.565631 |
f426b3bc7e0a8088e336ce3475bca025129278cd | 14,093 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOConcurrencyHelpers
import Dispatch
/// `NonBlockingFileIO` is a helper that allows you to read files without blocking the calling thread.
///
/// It is worth noting that `kqueue`, `epoll` or `poll` returning claiming a file is readable does not mean that the
/// data is already available in the kernel's memory. In other words, a `read` from a file can still block even if
/// reported as readable. This behaviour is also documented behaviour:
///
/// - [`poll`](http://pubs.opengroup.org/onlinepubs/009695399/functions/poll.html): "Regular files shall always poll TRUE for reading and writing."
/// - [`epoll`](http://man7.org/linux/man-pages/man7/epoll.7.html): "epoll is simply a faster poll(2), and can be used wherever the latter is used since it shares the same semantics."
/// - [`kqueue`](https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2): "Returns when the file pointer is not at the end of file."
///
/// `NonBlockingFileIO` helps to work around this issue by maintaining its own thread pool that is used to read the data
/// from the files into memory. It will then hand the (in-memory) data back which makes it available without the possibility
/// of blocking.
public struct NonBlockingFileIO {
/// The default and recommended size for `NonBlockingFileIO`'s thread pool.
public static let defaultThreadPoolSize = 2
/// The default and recommended chunk size.
public static let defaultChunkSize = 128*1024
/// `NonBlockingFileIO` errors.
public enum Error: Swift.Error {
/// `NonBlockingFileIO` is meant to be used with file descriptors that are set to the default (blocking) mode.
/// It doesn't make sense to use it with a file descriptor where `O_NONBLOCK` is set therefore this error is
/// raised when that was requested.
case descriptorSetToNonBlocking
}
private let threadPool: BlockingIOThreadPool
/// Initialize a `NonBlockingFileIO` which uses the `BlockingIOThreadPool`.
///
/// - parameters:
/// - threadPool: The `BlockingIOThreadPool` that will be used for all the IO.
public init(threadPool: BlockingIOThreadPool) {
self.threadPool = threadPool
}
/// Read a `FileRegion` in chunks of `chunkSize` bytes on `NonBlockingFileIO`'s private thread
/// pool which is separate from any `EventLoop` thread.
///
/// `chunkHandler` will be called on `eventLoop` for every chunk that was read. Assuming `fileRegion.readableBytes` is greater than
/// zero and there are enough bytes available `chunkHandler` will be called `1 + |_ fileRegion.readableBytes / chunkSize _|`
/// times, delivering `chunkSize` bytes each time. If less than `fileRegion.readableBytes` bytes can be read from the file,
/// `chunkHandler` will be called less often with the last invocation possibly being of less than `chunkSize` bytes.
///
/// The allocation and reading of a subsequent chunk will only be attempted when `chunkHandler` succeeds.
///
/// - parameters:
/// - fileRegion: The file region to read.
/// - chunkSize: The size of the individual chunks to deliver.
/// - allocator: A `ByteBufferAllocator` used to allocate space for the chunks.
/// - eventLoop: The `EventLoop` to call `chunkHandler` on.
/// - chunkHandler: Called for every chunk read. The next chunk will be read upon successful completion of the returned `EventLoopFuture`. If the returned `EventLoopFuture` fails, the overall operation is aborted.
/// - returns: An `EventLoopFuture` which is the result of the overall operation. If either the reading of `fileHandle` or `chunkHandler` fails, the `EventLoopFuture` will fail too. If the reading of `fileHandle` as well as `chunkHandler` always succeeded, the `EventLoopFuture` will succeed too.
public func readChunked(fileRegion: FileRegion,
chunkSize: Int = NonBlockingFileIO.defaultChunkSize,
allocator: ByteBufferAllocator,
eventLoop: EventLoop,
chunkHandler: @escaping (ByteBuffer) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> {
do {
let readableBytes = fileRegion.readableBytes
try fileRegion.fileHandle.withUnsafeFileDescriptor { descriptor in
_ = try Posix.lseek(descriptor: descriptor, offset: off_t(fileRegion.readerIndex), whence: SEEK_SET)
}
return self.readChunked(fileHandle: fileRegion.fileHandle,
byteCount: readableBytes,
chunkSize: chunkSize,
allocator: allocator,
eventLoop: eventLoop,
chunkHandler: chunkHandler)
} catch {
return eventLoop.newFailedFuture(error: error)
}
}
/// Read `byteCount` bytes in chunks of `chunkSize` bytes from `fileHandle` in `NonBlockingFileIO`'s private thread
/// pool which is separate from any `EventLoop` thread.
///
/// `chunkHandler` will be called on `eventLoop` for every chunk that was read. Assuming `byteCount` is greater than
/// zero and there are enough bytes available `chunkHandler` will be called `1 + |_ byteCount / chunkSize _|`
/// times, delivering `chunkSize` bytes each time. If less than `byteCount` bytes can be read from `descriptor`,
/// `chunkHandler` will be called less often with the last invocation possibly being of less than `chunkSize` bytes.
///
/// The allocation and reading of a subsequent chunk will only be attempted when `chunkHandler` succeeds.
///
/// - note: `readChunked(fileRegion:chunkSize:allocator:eventLoop:chunkHandler:)` should be preferred as it uses `FileRegion` object instead of raw `FileHandle`s.
///
/// - parameters:
/// - fileHandle: The `FileHandle` to read from.
/// - byteCount: The number of bytes to read from `fileHandle`.
/// - chunkSize: The size of the individual chunks to deliver.
/// - allocator: A `ByteBufferAllocator` used to allocate space for the chunks.
/// - eventLoop: The `EventLoop` to call `chunkHandler` on.
/// - chunkHandler: Called for every chunk read. The next chunk will be read upon successful completion of the returned `EventLoopFuture`. If the returned `EventLoopFuture` fails, the overall operation is aborted.
/// - returns: An `EventLoopFuture` which is the result of the overall operation. If either the reading of `fileHandle` or `chunkHandler` fails, the `EventLoopFuture` will fail too. If the reading of `fileHandle` as well as `chunkHandler` always succeeded, the `EventLoopFuture` will succeed too.
public func readChunked(fileHandle: FileHandle,
byteCount: Int,
chunkSize: Int = NonBlockingFileIO.defaultChunkSize,
allocator: ByteBufferAllocator,
eventLoop: EventLoop, chunkHandler: @escaping (ByteBuffer) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> {
precondition(chunkSize > 0, "chunkSize must be > 0 (is \(chunkSize))")
var remainingReads = 1 + (byteCount / chunkSize)
let lastReadSize = byteCount % chunkSize
func _read(remainingReads: Int) -> EventLoopFuture<Void> {
if remainingReads > 1 || (remainingReads == 1 && lastReadSize > 0) {
let readSize = remainingReads > 1 ? chunkSize : lastReadSize
assert(readSize > 0)
return self.read(fileHandle: fileHandle, byteCount: readSize, allocator: allocator, eventLoop: eventLoop).then { buffer in
chunkHandler(buffer).then { () -> EventLoopFuture<Void> in
assert(eventLoop.inEventLoop)
return _read(remainingReads: remainingReads - 1)
}
}
} else {
return eventLoop.newSucceededFuture(result: ())
}
}
return _read(remainingReads: remainingReads)
}
/// Read a `FileRegion` in `NonBlockingFileIO`'s private thread pool which is separate from any `EventLoop` thread.
///
/// The returned `ByteBuffer` will not have less than `fileRegion.readableBytes` unless we hit end-of-file in which
/// case the `ByteBuffer` will contain the bytes available to read.
///
/// - note: Only use this function for small enough `FileRegion`s as it will need to allocate enough memory to hold `fileRegion.readableBytes` bytes.
/// - note: In most cases you should prefer one of the `readChunked` functions.
///
/// - parameters:
/// - fileRegion: The file region to read.
/// - allocator: A `ByteBufferAllocator` used to allocate space for the returned `ByteBuffer`.
/// - eventLoop: The `EventLoop` to create the returned `EventLoopFuture` from.
/// - returns: An `EventLoopFuture` which delivers a `ByteBuffer` if the read was successful or a failure on error.
public func read(fileRegion: FileRegion, allocator: ByteBufferAllocator, eventLoop: EventLoop) -> EventLoopFuture<ByteBuffer> {
do {
let readableBytes = fileRegion.readableBytes
try fileRegion.fileHandle.withUnsafeFileDescriptor { descriptor in
_ = try Posix.lseek(descriptor: descriptor, offset: off_t(fileRegion.readerIndex), whence: SEEK_SET)
}
return self.read(fileHandle: fileRegion.fileHandle,
byteCount: readableBytes,
allocator: allocator,
eventLoop: eventLoop)
} catch {
return eventLoop.newFailedFuture(error: error)
}
}
/// Read `byteCount` bytes from `fileHandle` in `NonBlockingFileIO`'s private thread pool which is separate from any `EventLoop` thread.
///
/// The returned `ByteBuffer` will not have less than `byteCount` bytes unless we hit end-of-file in which
/// case the `ByteBuffer` will contain the bytes available to read.
///
/// - note: Only use this function for small enough `byteCount`s as it will need to allocate enough memory to hold `byteCount` bytes.
/// - note: `read(fileRegion:allocator:eventLoop:)` should be preferred as it uses `FileRegion` object instead of raw `FileHandle`s.
///
/// - parameters:
/// - fileHandle: The `FileHandle` to read.
/// - byteCount: The number of bytes to read from `fileHandle`.
/// - allocator: A `ByteBufferAllocator` used to allocate space for the returned `ByteBuffer`.
/// - eventLoop: The `EventLoop` to create the returned `EventLoopFuture` from.
/// - returns: An `EventLoopFuture` which delivers a `ByteBuffer` if the read was successful or a failure on error.
public func read(fileHandle: FileHandle, byteCount: Int, allocator: ByteBufferAllocator, eventLoop: EventLoop) -> EventLoopFuture<ByteBuffer> {
guard byteCount > 0 else {
return eventLoop.newSucceededFuture(result: allocator.buffer(capacity: 0))
}
var buf = allocator.buffer(capacity: byteCount)
return self.threadPool.runIfActive(eventLoop: eventLoop) { () -> ByteBuffer in
var bytesRead = 0
while bytesRead < byteCount {
let n = try buf.writeWithUnsafeMutableBytes { ptr in
let res = try fileHandle.withUnsafeFileDescriptor { descriptor in
try Posix.read(descriptor: descriptor,
pointer: ptr.baseAddress!,
size: byteCount - bytesRead)
}
switch res {
case .processed(let n):
assert(n >= 0, "read claims to have read a negative number of bytes \(n)")
return n
case .wouldBlock:
throw Error.descriptorSetToNonBlocking
}
}
if n == 0 {
// EOF
break
} else {
bytesRead += n
}
}
return buf
}
}
/// Open the file at `path` on a private thread pool which is separate from any `EventLoop` thread.
///
/// This function will return (a future) of the `FileHandle` associated with the file opened and a `FileRegion`
/// comprising of the whole file. The caller must close the returned `FileHandle` when its no longer needed.
///
/// - note: The reason this returns the `FileHandle` and the `FileRegion` is that both the opening of a file as well as the querying of its size are blocking.
///
/// - parameters:
/// - path: The path of the file to be opened.
/// - eventLoop: The `EventLoop` on which the returned `EventLoopFuture` will fire.
/// - returns: An `EventLoopFuture` containing the `FileHandle` and the `FileRegion` comprising the whole file.
public func openFile(path: String, eventLoop: EventLoop) -> EventLoopFuture<(FileHandle, FileRegion)> {
return self.threadPool.runIfActive(eventLoop: eventLoop) {
let fh = try FileHandle(path: path)
do {
let fr = try FileRegion(fileHandle: fh)
return (fh, fr)
} catch {
_ = try? fh.close()
throw error
}
}
}
}
| 58.235537 | 300 | 0.635422 |
761ec927dab785e0c81bcad9c83fc97aa703f0b2 | 70,319 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
import UIKit
// MARK: TableViewCellAccessoryType
@available(*, deprecated, renamed: "TableViewCellAccessoryType")
public typealias MSTableViewCellAccessoryType = TableViewCellAccessoryType
@objc(MSFTableViewCellAccessoryType)
public enum TableViewCellAccessoryType: Int {
case none
case disclosureIndicator
case detailButton
case checkmark
private struct Constants {
static let horizontalSpacing: CGFloat = 16
static let height: CGFloat = 44
}
var icon: UIImage? {
let icon: UIImage?
switch self {
case .none:
icon = nil
case .disclosureIndicator:
icon = UIImage.staticImageNamed("iOS-chevron-right-20x20")
case .detailButton:
icon = UIImage.staticImageNamed("more-24x24")
case .checkmark:
icon = UIImage.staticImageNamed("checkmark-24x24")
}
return icon
}
func iconColor(for window: UIWindow) -> UIColor? {
switch self {
case .none:
return nil
case .disclosureIndicator:
return Colors.Table.Cell.accessoryDisclosureIndicator
case .detailButton:
return Colors.Table.Cell.accessoryDetailButton
case .checkmark:
return Colors.primary(for: window)
}
}
var size: CGSize {
if self == .none {
return .zero
}
// Horizontal spacing includes 16pt spacing from content to icon and 16pt spacing from icon to trailing edge of cell
let horizontalSpacing: CGFloat = Constants.horizontalSpacing * 2
let iconWidth: CGFloat = icon?.size.width ?? 0
return CGSize(width: horizontalSpacing + iconWidth, height: Constants.height)
}
}
// MARK: - Table Colors
public extension Colors {
struct Table {
public struct Cell {
public static var background: UIColor = surfacePrimary
public static var backgroundGrouped = UIColor(light: surfacePrimary, dark: surfaceSecondary)
public static var backgroundSelected: UIColor = surfaceTertiary
public static var image: UIColor = iconSecondary
public static var title: UIColor = textPrimary
public static var subtitle: UIColor = textSecondary
public static var footer: UIColor = textSecondary
public static var accessoryDisclosureIndicator: UIColor = iconSecondary
public static var accessoryDetailButton: UIColor = iconSecondary
public static var selectionIndicatorOff: UIColor = iconSecondary
}
public struct ActionCell {
public static var textDestructive: UIColor = error
public static var textDestructiveHighlighted: UIColor = error.withAlphaComponent(0.4)
public static var textCommunication: UIColor = communicationBlue
public static var textCommunicationHighlighted: UIColor = communicationBlue.withAlphaComponent(0.4)
}
public struct HeaderFooter {
public static var accessoryButtonText: UIColor = textSecondary
public static var background: UIColor = .clear
public static var backgroundDivider: UIColor = surfaceSecondary
public static var text: UIColor = textSecondary
public static var textDivider: UIColor = textSecondary
public static var textLink = UIColor(light: Palette.communicationBlueShade10.color, dark: communicationBlue)
}
public static var background: UIColor = surfacePrimary
public static var backgroundGrouped = UIColor(light: surfaceSecondary, dark: surfacePrimary)
}
// Objective-C support
@objc static var tableBackground: UIColor { return Table.background }
@objc static var tableBackgroundGrouped: UIColor { return Table.backgroundGrouped }
@objc static var tableCellBackground: UIColor { return Table.Cell.background }
@objc static var tableCellBackgroundGrouped: UIColor { return Table.Cell.backgroundGrouped }
@objc static var tableCellBackgroundSelected: UIColor { return Table.Cell.backgroundSelected }
@objc static var tableCellImage: UIColor { return Table.Cell.image }
}
// MARK: - TableViewCell
@available(*, deprecated, renamed: "TableViewCell")
public typealias MSTableViewCell = TableViewCell
/**
`TableViewCell` is used to present a cell with one, two, or three lines of text with an optional custom view and an accessory.
The `title` is displayed as the first line of text with the `subtitle` as the second line and the `footer` the third line.
If a `subtitle` and `footer` are not provided the cell will be configured as a "small" size cell showing only the `title` line of text and a smaller custom view.
If a `subtitle` is provided and a `footer` is not provided the cell will display two lines of text and will leave space for the `title` if it is not provided.
If a `footer` is provided the cell will display three lines of text and will leave space for the `subtitle` and `title` if they are not provided.
If a `customView` is not provided the `customView` will be hidden and the displayed text will take up the empty space left by the hidden `customView`.
Specify `accessoryType` on setup to show either a disclosure indicator or a `detailButton`. The `detailButton` will display a button with an ellipsis icon which can be configured by passing in a closure to the cell's `onAccessoryTapped` property or by implementing UITableViewDelegate's `accessoryButtonTappedForRowWith` method.
NOTE: This cell implements its own custom separator. Make sure to remove the UITableViewCell built-in separator by setting `separatorStyle = .none` on your table view. To remove the cell's custom separator set `bottomSeparatorType` to `.none`.
*/
@objc(MSFTableViewCell)
open class TableViewCell: UITableViewCell {
@objc(MSFTableViewCellCustomViewSize)
public enum CustomViewSize: Int {
case `default`
case zero
case small
case medium
var size: CGSize {
switch self {
case .zero:
return .zero
case .small:
return CGSize(width: 24, height: 24)
case .medium, .default:
return CGSize(width: 40, height: 40)
}
}
var trailingMargin: CGFloat {
switch self {
case .zero:
return 0
case .small:
return 16
case .medium, .default:
return 12
}
}
fileprivate func validateLayoutTypeForHeightCalculation(_ layoutType: inout LayoutType) {
if self == .medium && layoutType == .oneLine {
layoutType = .twoLines
}
}
}
@objc(MSFTableViewCellSeparatorType)
public enum SeparatorType: Int {
case none
case inset
case full
}
fileprivate enum LayoutType {
case oneLine
case twoLines
case threeLines
var customViewSize: CustomViewSize { return self == .oneLine ? .small : .medium }
var subtitleTextStyle: TextStyle {
switch self {
case .oneLine, .twoLines:
return TextStyles.subtitleTwoLines
case .threeLines:
return TextStyles.subtitleThreeLines
}
}
var labelVerticalMargin: CGFloat {
switch self {
case .oneLine, .threeLines:
return labelVerticalMarginForOneAndThreeLines
case .twoLines:
return labelVerticalMarginForTwoLines
}
}
}
struct TextStyles {
static let title: TextStyle = .body
static let subtitleTwoLines: TextStyle = .footnote
static let subtitleThreeLines: TextStyle = .subhead
static let footer: TextStyle = .footnote
}
private struct Constants {
static let labelAccessoryViewMarginLeading: CGFloat = 8
static let labelAccessoryViewMarginTrailing: CGFloat = 8
static let customAccessoryViewMarginLeading: CGFloat = 8
static let customAccessoryViewMinVerticalMargin: CGFloat = 6
static let labelVerticalMarginForOneAndThreeLines: CGFloat = 11
static let labelVerticalMarginForTwoLines: CGFloat = 12
static let labelVerticalSpacing: CGFloat = 0
static let minHeight: CGFloat = 48
static let selectionImageMarginTrailing: CGFloat = horizontalSpacing
static let selectionImageOff = UIImage.staticImageNamed("selection-off")
static let selectionImageOn = UIImage.staticImageNamed("selection-on")
static let selectionImageSize = CGSize(width: 24, height: 24)
static let selectionModeAnimationDuration: TimeInterval = 0.2
static let textAreaMinWidth: CGFloat = 100
static let enabledAlpha: CGFloat = 1
static let disabledAlpha: CGFloat = 0.35
}
/**
The height for the cell based on the text provided. Useful when `numberOfLines` of `title`, `subtitle`, `footer` is 1.
`smallHeight` - Height for the cell when only the `title` is provided in a single line of text.
`mediumHeight` - Height for the cell when only the `title` and `subtitle` are provided in 2 lines of text.
`largeHeight` - Height for the cell when the `title`, `subtitle`, and `footer` are provided in 3 lines of text.
*/
@objc public static var smallHeight: CGFloat { return height(title: "", customViewSize: .small) }
@objc public static var mediumHeight: CGFloat { return height(title: "", subtitle: " ") }
@objc public static var largeHeight: CGFloat { return height(title: "", subtitle: " ", footer: " ") }
@objc public static var identifier: String { return String(describing: self) }
/// A constant representing the number of lines for a label in which no change will be made when the `preferredContentSizeCategory` returns a size greater than `.large`.
@objc public static let defaultNumberOfLinesForLargerDynamicType: Int = -1
/// The default horizontal spacing in the cell.
@objc public static let horizontalSpacing: CGFloat = 16
/// The default leading padding in the cell.
@objc public static let defaultPaddingLeading: CGFloat = horizontalSpacing
/// The default trailing padding in the cell.
@objc public static let defaultPaddingTrailing: CGFloat = horizontalSpacing
/// The vertical margins for cells with one or three lines of text
class var labelVerticalMarginForOneAndThreeLines: CGFloat { return Constants.labelVerticalMarginForOneAndThreeLines }
/// The vertical margins for cells with two lines of text
class var labelVerticalMarginForTwoLines: CGFloat { return Constants.labelVerticalMarginForTwoLines }
private var separatorLeadingInsetForSmallCustomView: CGFloat {
return paddingLeading + CustomViewSize.small.size.width + CustomViewSize.small.trailingMargin
}
private var separatorLeadingInsetForMediumCustomView: CGFloat {
return paddingLeading + CustomViewSize.medium.size.width + CustomViewSize.medium.trailingMargin
}
private var separatorLeadingInsetForNoCustomView: CGFloat {
return paddingLeading
}
/// The height of the cell based on the height of its content.
///
/// - Parameters:
/// - title: The title string
/// - subtitle: The subtitle string
/// - footer: The footer string
/// - titleLeadingAccessoryView: The accessory view on the leading edge of the title
/// - titleTrailingAccessoryView: The accessory view on the trailing edge of the title
/// - subtitleLeadingAccessoryView: The accessory view on the leading edge of the subtitle
/// - subtitleTrailingAccessoryView: The accessory view on the trailing edge of the subtitle
/// - footerLeadingAccessoryView: The accessory view on the leading edge of the footer
/// - footerTrailingAccessoryView: The accessory view on the trailing edge of the footer
/// - customViewSize: The custom view size for the cell based on `TableViewCell.CustomViewSize`
/// - customAccessoryView: The custom accessory view that appears near the trailing edge of the cell
/// - accessoryType: The `TableViewCellAccessoryType` that the cell should display
/// - titleNumberOfLines: The number of lines that the title should display
/// - subtitleNumberOfLines: The number of lines that the subtitle should display
/// - footerNumberOfLines: The number of lines that the footer should display
/// - customAccessoryViewExtendsToEdge: Boolean defining whether custom accessory view is extended to the trailing edge of the cell or not (ignored when accessory type is not `.none`)
/// - containerWidth: The width of the cell's super view (e.g. the table view's width)
/// - isInSelectionMode: Boolean describing if the cell is in multi-selection mode which shows/hides a checkmark image on the leading edge
/// - paddingLeading: The cell's leading padding
/// - paddingTrailing: The cell's trailing padding
/// - Returns: a value representing the calculated height of the cell
@objc public class func height(title: String,
subtitle: String = "",
footer: String = "",
titleLeadingAccessoryView: UIView? = nil,
titleTrailingAccessoryView: UIView? = nil,
subtitleLeadingAccessoryView: UIView? = nil,
subtitleTrailingAccessoryView: UIView? = nil,
footerLeadingAccessoryView: UIView? = nil,
footerTrailingAccessoryView: UIView? = nil,
customViewSize: CustomViewSize = .default,
customAccessoryView: UIView? = nil,
accessoryType: TableViewCellAccessoryType = .none,
titleNumberOfLines: Int = 1,
subtitleNumberOfLines: Int = 1,
footerNumberOfLines: Int = 1,
customAccessoryViewExtendsToEdge: Bool = false,
containerWidth: CGFloat = .greatestFiniteMagnitude,
isInSelectionMode: Bool = false,
paddingLeading: CGFloat = defaultPaddingLeading,
paddingTrailing: CGFloat = defaultPaddingTrailing) -> CGFloat {
var layoutType = self.layoutType(subtitle: subtitle, footer: footer, subtitleLeadingAccessoryView: subtitleLeadingAccessoryView, subtitleTrailingAccessoryView: subtitleTrailingAccessoryView, footerLeadingAccessoryView: footerLeadingAccessoryView, footerTrailingAccessoryView: footerTrailingAccessoryView)
customViewSize.validateLayoutTypeForHeightCalculation(&layoutType)
let customViewSize = self.customViewSize(from: customViewSize, layoutType: layoutType)
let textAreaLeadingOffset = self.textAreaLeadingOffset(customViewSize: customViewSize, isInSelectionMode: isInSelectionMode, paddingLeading: paddingLeading)
let textAreaTrailingOffset = self.textAreaTrailingOffset(customAccessoryView: customAccessoryView, customAccessoryViewExtendsToEdge: customAccessoryViewExtendsToEdge, accessoryType: accessoryType, paddingTrailing: paddingTrailing)
var textAreaWidth = containerWidth - (textAreaLeadingOffset + textAreaTrailingOffset)
if textAreaWidth < Constants.textAreaMinWidth, let customAccessoryView = customAccessoryView {
let oldAccessoryViewWidth = customAccessoryView.frame.width
let availableWidth = oldAccessoryViewWidth - (Constants.textAreaMinWidth - textAreaWidth)
customAccessoryView.frame.size = customAccessoryView.systemLayoutSizeFitting(CGSize(width: availableWidth, height: .infinity))
textAreaWidth += oldAccessoryViewWidth - customAccessoryView.frame.width
}
let textAreaHeight = self.textAreaHeight(
layoutType: layoutType,
titleHeight: labelSize(text: title, font: TextStyles.title.font, numberOfLines: titleNumberOfLines, textAreaWidth: textAreaWidth, leadingAccessoryView: titleLeadingAccessoryView, trailingAccessoryView: titleTrailingAccessoryView).height,
subtitleHeight: labelSize(text: subtitle, font: layoutType.subtitleTextStyle.font, numberOfLines: subtitleNumberOfLines, textAreaWidth: textAreaWidth, leadingAccessoryView: subtitleLeadingAccessoryView, trailingAccessoryView: subtitleTrailingAccessoryView).height,
footerHeight: labelSize(text: footer, font: TextStyles.footer.font, numberOfLines: footerNumberOfLines, textAreaWidth: textAreaWidth, leadingAccessoryView: footerLeadingAccessoryView, trailingAccessoryView: footerTrailingAccessoryView).height
)
let labelVerticalMargin = layoutType == .twoLines ? labelVerticalMarginForTwoLines : labelVerticalMarginForOneAndThreeLines
var minHeight = Constants.minHeight
if let customAccessoryView = customAccessoryView {
minHeight = max(minHeight, customAccessoryView.frame.height + 2 * Constants.customAccessoryViewMinVerticalMargin)
}
return max(labelVerticalMargin * 2 + textAreaHeight, minHeight)
}
/// The preferred width of the cell based on the width of its content.
///
/// - Parameters:
/// - title: The title string
/// - subtitle: The subtitle string
/// - footer: The footer string
/// - titleLeadingAccessoryView: The accessory view on the leading edge of the title
/// - titleTrailingAccessoryView: The accessory view on the trailing edge of the title
/// - subtitleLeadingAccessoryView: The accessory view on the leading edge of the subtitle
/// - subtitleTrailingAccessoryView: The accessory view on the trailing edge of the subtitle
/// - footerLeadingAccessoryView: The accessory view on the leading edge of the footer
/// - footerTrailingAccessoryView: The accessory view on the trailing edge of the footer
/// - customViewSize: The custom view size for the cell based on `TableViewCell.CustomViewSize`
/// - customAccessoryView: The custom accessory view that appears near the trailing edge of the cell
/// - accessoryType: The `TableViewCellAccessoryType` that the cell should display
/// - customAccessoryViewExtendsToEdge: Boolean defining whether custom accessory view is extended to the trailing edge of the cell or not (ignored when accessory type is not `.none`)
/// - isInSelectionMode: Boolean describing if the cell is in multi-selection mode which shows/hides a checkmark image on the leading edge
/// - paddingLeading: The cell's leading padding
/// - paddingTrailing: The cell's trailing padding
/// - Returns: a value representing the preferred width of the cell
@objc public class func preferredWidth(title: String,
subtitle: String = "",
footer: String = "",
titleLeadingAccessoryView: UIView? = nil,
titleTrailingAccessoryView: UIView? = nil,
subtitleLeadingAccessoryView: UIView? = nil,
subtitleTrailingAccessoryView: UIView? = nil,
footerLeadingAccessoryView: UIView? = nil,
footerTrailingAccessoryView: UIView? = nil,
customViewSize: CustomViewSize = .default,
customAccessoryView: UIView? = nil,
accessoryType: TableViewCellAccessoryType = .none,
customAccessoryViewExtendsToEdge: Bool = false,
isInSelectionMode: Bool = false,
paddingLeading: CGFloat = defaultPaddingLeading,
paddingTrailing: CGFloat = defaultPaddingTrailing) -> CGFloat {
let layoutType = self.layoutType(subtitle: subtitle, footer: footer, subtitleLeadingAccessoryView: subtitleLeadingAccessoryView, subtitleTrailingAccessoryView: subtitleTrailingAccessoryView, footerLeadingAccessoryView: footerLeadingAccessoryView, footerTrailingAccessoryView: footerTrailingAccessoryView)
let customViewSize = self.customViewSize(from: customViewSize, layoutType: layoutType)
var textAreaWidth = labelPreferredWidth(text: title, font: TextStyles.title.font, leadingAccessoryView: titleLeadingAccessoryView, trailingAccessoryView: titleTrailingAccessoryView)
if layoutType == .twoLines || layoutType == .threeLines {
let subtitleWidth = labelPreferredWidth(text: subtitle, font: layoutType.subtitleTextStyle.font, leadingAccessoryView: subtitleLeadingAccessoryView, trailingAccessoryView: subtitleTrailingAccessoryView)
textAreaWidth = max(textAreaWidth, subtitleWidth)
if layoutType == .threeLines {
let footerWidth = labelPreferredWidth(text: footer, font: TextStyles.footer.font, leadingAccessoryView: footerLeadingAccessoryView, trailingAccessoryView: footerTrailingAccessoryView)
textAreaWidth = max(textAreaWidth, footerWidth)
}
}
return textAreaLeadingOffset(customViewSize: customViewSize, isInSelectionMode: isInSelectionMode, paddingLeading: paddingLeading) +
textAreaWidth +
textAreaTrailingOffset(customAccessoryView: customAccessoryView, customAccessoryViewExtendsToEdge: customAccessoryViewExtendsToEdge, accessoryType: accessoryType, paddingTrailing: paddingTrailing)
}
private static func labelSize(text: String, font: UIFont, numberOfLines: Int, textAreaWidth: CGFloat, leadingAccessoryView: UIView?, trailingAccessoryView: UIView?) -> CGSize {
let leadingAccessoryViewWidth = labelAccessoryViewSize(for: leadingAccessoryView).width
let leadingAccessoryAreaWidth = labelLeadingAccessoryAreaWidth(viewWidth: leadingAccessoryViewWidth)
let trailingAccessoryViewWidth = labelAccessoryViewSize(for: trailingAccessoryView).width
let trailingAccessoryAreaWidth = labelTrailingAccessoryAreaWidth(viewWidth: trailingAccessoryViewWidth, text: text)
let availableWidth = textAreaWidth - (leadingAccessoryAreaWidth + trailingAccessoryAreaWidth)
return text.preferredSize(for: font, width: availableWidth, numberOfLines: numberOfLines)
}
private static func labelPreferredWidth(text: String, font: UIFont, leadingAccessoryView: UIView?, trailingAccessoryView: UIView?) -> CGFloat {
var labelWidth = text.preferredSize(for: font).width
labelWidth += labelLeadingAccessoryAreaWidth(viewWidth: leadingAccessoryView?.frame.width ?? 0) + labelTrailingAccessoryAreaWidth(viewWidth: trailingAccessoryView?.frame.width ?? 0, text: text)
return labelWidth
}
private static func layoutType(subtitle: String, footer: String, subtitleLeadingAccessoryView: UIView?, subtitleTrailingAccessoryView: UIView?, footerLeadingAccessoryView: UIView?, footerTrailingAccessoryView: UIView?) -> LayoutType {
if footer == "" && footerLeadingAccessoryView == nil && footerTrailingAccessoryView == nil {
if subtitle == "" && subtitleLeadingAccessoryView == nil && subtitleTrailingAccessoryView == nil {
return .oneLine
}
return .twoLines
} else {
return .threeLines
}
}
private static func selectionModeAreaWidth(isInSelectionMode: Bool) -> CGFloat {
return isInSelectionMode ? Constants.selectionImageSize.width + Constants.selectionImageMarginTrailing : 0
}
private static func customViewSize(from size: CustomViewSize, layoutType: LayoutType) -> CustomViewSize {
return size == .default ? layoutType.customViewSize : size
}
private static func customViewLeadingOffset(isInSelectionMode: Bool, paddingLeading: CGFloat) -> CGFloat {
return paddingLeading + selectionModeAreaWidth(isInSelectionMode: isInSelectionMode)
}
private static func textAreaLeadingOffset(customViewSize: CustomViewSize, isInSelectionMode: Bool, paddingLeading: CGFloat) -> CGFloat {
var textAreaLeadingOffset = customViewLeadingOffset(isInSelectionMode: isInSelectionMode, paddingLeading: paddingLeading)
if customViewSize != .zero {
textAreaLeadingOffset += customViewSize.size.width + customViewSize.trailingMargin
}
return textAreaLeadingOffset
}
private static func textAreaTrailingOffset(customAccessoryView: UIView?, customAccessoryViewExtendsToEdge: Bool, accessoryType: TableViewCellAccessoryType, paddingTrailing: CGFloat) -> CGFloat {
let customAccessoryViewAreaWidth: CGFloat
if let customAccessoryView = customAccessoryView {
customAccessoryViewAreaWidth = customAccessoryView.frame.width + Constants.customAccessoryViewMarginLeading
} else {
customAccessoryViewAreaWidth = 0
}
return customAccessoryViewAreaWidth + TableViewCell.customAccessoryViewTrailingOffset(customAccessoryView: customAccessoryView, customAccessoryViewExtendsToEdge: customAccessoryViewExtendsToEdge, accessoryType: accessoryType, paddingTrailing: paddingTrailing)
}
private static func textAreaHeight(layoutType: TableViewCell.LayoutType, titleHeight: @autoclosure () -> CGFloat, subtitleHeight: @autoclosure () -> CGFloat, footerHeight: @autoclosure () -> CGFloat) -> CGFloat {
var textAreaHeight = titleHeight()
if layoutType == .twoLines || layoutType == .threeLines {
textAreaHeight += Constants.labelVerticalSpacing + subtitleHeight()
if layoutType == .threeLines {
textAreaHeight += Constants.labelVerticalSpacing + footerHeight()
}
}
return textAreaHeight
}
private static func customAccessoryViewTrailingOffset(customAccessoryView: UIView?, customAccessoryViewExtendsToEdge: Bool, accessoryType: TableViewCellAccessoryType, paddingTrailing: CGFloat) -> CGFloat {
if accessoryType != .none {
return accessoryType.size.width
}
if customAccessoryView != nil && customAccessoryViewExtendsToEdge {
return 0
}
return paddingTrailing
}
private static func labelTrailingAccessoryMarginLeading(text: String) -> CGFloat {
return text == "" ? 0 : Constants.labelAccessoryViewMarginLeading
}
private static func labelLeadingAccessoryAreaWidth(viewWidth: CGFloat) -> CGFloat {
return viewWidth != 0 ? viewWidth + Constants.labelAccessoryViewMarginTrailing : 0
}
private static func labelTrailingAccessoryAreaWidth(viewWidth: CGFloat, text: String) -> CGFloat {
return viewWidth != 0 ? labelTrailingAccessoryMarginLeading(text: text) + viewWidth : 0
}
private static func labelAccessoryViewSize(for accessoryView: UIView?) -> CGSize {
return accessoryView?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) ?? .zero
}
/// Text that appears as the first line of text
@objc public var title: String { return titleLabel.text ?? "" }
/// Text that appears as the second line of text
@objc public var subtitle: String { return subtitleLabel.text ?? "" }
/// Text that appears as the third line of text
@objc public var footer: String { return footerLabel.text ?? "" }
/// The leading padding.
@objc public var paddingLeading: CGFloat = defaultPaddingLeading {
didSet {
if oldValue != paddingLeading {
setNeedsLayout()
invalidateIntrinsicContentSize()
}
}
}
/// The trailing padding.
@objc public var paddingTrailing: CGFloat = defaultPaddingTrailing {
didSet {
if oldValue != paddingTrailing {
setNeedsLayout()
invalidateIntrinsicContentSize()
}
}
}
/// The maximum number of lines to be shown for `title`
@objc open var titleNumberOfLines: Int {
get {
if titleNumberOfLinesForLargerDynamicType != TableViewCell.defaultNumberOfLinesForLargerDynamicType && preferredContentSizeIsLargerThanDefault {
return titleNumberOfLinesForLargerDynamicType
}
return _titleNumberOfLines
}
set {
_titleNumberOfLines = newValue
updateTitleNumberOfLines()
}
}
private var _titleNumberOfLines: Int = 1
/// The maximum number of lines to be shown for `subtitle`
@objc open var subtitleNumberOfLines: Int {
get {
if subtitleNumberOfLinesForLargerDynamicType != TableViewCell.defaultNumberOfLinesForLargerDynamicType && preferredContentSizeIsLargerThanDefault {
return subtitleNumberOfLinesForLargerDynamicType
}
return _subtitleNumberOfLines
}
set {
_subtitleNumberOfLines = newValue
updateSubtitleNumberOfLines()
}
}
private var _subtitleNumberOfLines: Int = 1
/// The maximum number of lines to be shown for `footer`
@objc open var footerNumberOfLines: Int {
get {
if footerNumberOfLinesForLargerDynamicType != TableViewCell.defaultNumberOfLinesForLargerDynamicType && preferredContentSizeIsLargerThanDefault {
return footerNumberOfLinesForLargerDynamicType
}
return _footerNumberOfLines
}
set {
_footerNumberOfLines = newValue
updateFooterNumberOfLines()
}
}
private var _footerNumberOfLines: Int = 1
/// The number of lines to show for the `title` if `preferredContentSizeCategory` is set to a size greater than `.large`. The default value indicates that no change will be made to the `title` and `titleNumberOfLines` will be used for all content sizes.
@objc open var titleNumberOfLinesForLargerDynamicType: Int = defaultNumberOfLinesForLargerDynamicType {
didSet {
updateTitleNumberOfLines()
}
}
/// The number of lines to show for the `subtitle` if `preferredContentSizeCategory` is set to a size greater than `.large`. The default value indicates that no change will be made to the `subtitle` and `subtitleNumberOfLines` will be used for all content sizes.
@objc open var subtitleNumberOfLinesForLargerDynamicType: Int = defaultNumberOfLinesForLargerDynamicType {
didSet {
updateSubtitleNumberOfLines()
}
}
/// The number of lines to show for the `footer` if `preferredContentSizeCategory` is set to a size greater than `.large`. The default value indicates that no change will be made to the `footer` and `footerNumberOfLines` will be used for all content sizes.
@objc open var footerNumberOfLinesForLargerDynamicType: Int = defaultNumberOfLinesForLargerDynamicType {
didSet {
updateFooterNumberOfLines()
}
}
/// Updates the lineBreakMode of the `title`
@objc open var titleLineBreakMode: NSLineBreakMode = .byTruncatingTail {
didSet {
titleLabel.lineBreakMode = titleLineBreakMode
}
}
/// Updates the lineBreakMode of the `subtitle`
@objc open var subtitleLineBreakMode: NSLineBreakMode = .byTruncatingTail {
didSet {
subtitleLabel.lineBreakMode = subtitleLineBreakMode
}
}
/// Updates the lineBreakMode of the `footer`
@objc open var footerLineBreakMode: NSLineBreakMode = .byTruncatingTail {
didSet {
footerLabel.lineBreakMode = footerLineBreakMode
}
}
/// The accessory view on the leading edge of the title
@objc open var titleLeadingAccessoryView: UIView? {
didSet {
updateLabelAccessoryView(oldValue: oldValue, newValue: titleLeadingAccessoryView, size: &titleLeadingAccessoryViewSize)
}
}
/// The accessory view on the trailing edge of the title
@objc open var titleTrailingAccessoryView: UIView? {
didSet {
updateLabelAccessoryView(oldValue: oldValue, newValue: titleTrailingAccessoryView, size: &titleTrailingAccessoryViewSize)
}
}
/// The accessory view on the leading edge of the subtitle
@objc open var subtitleLeadingAccessoryView: UIView? {
didSet {
updateLabelAccessoryView(oldValue: oldValue, newValue: subtitleLeadingAccessoryView, size: &subtitleLeadingAccessoryViewSize)
}
}
/// The accessory view on the trailing edge of the subtitle
@objc open var subtitleTrailingAccessoryView: UIView? {
didSet {
updateLabelAccessoryView(oldValue: oldValue, newValue: subtitleTrailingAccessoryView, size: &subtitleTrailingAccessoryViewSize)
}
}
/// The accessory view on the leading edge of the footer
@objc open var footerLeadingAccessoryView: UIView? {
didSet {
updateLabelAccessoryView(oldValue: oldValue, newValue: footerLeadingAccessoryView, size: &footerLeadingAccessoryViewSize)
}
}
/// The accessory view on the trailing edge of the footer
@objc open var footerTrailingAccessoryView: UIView? {
didSet {
updateLabelAccessoryView(oldValue: oldValue, newValue: footerTrailingAccessoryView, size: &footerTrailingAccessoryViewSize)
}
}
/// Override to set a specific `CustomViewSize` on the `customView`
@objc open var customViewSize: CustomViewSize {
get {
if customView == nil {
return .zero
}
return _customViewSize == .default ? layoutType.customViewSize : _customViewSize
}
set {
if _customViewSize == newValue {
return
}
_customViewSize = newValue
setNeedsLayout()
invalidateIntrinsicContentSize()
}
}
private var _customViewSize: CustomViewSize = .default
@objc open private(set) var customAccessoryView: UIView? = nil {
didSet {
oldValue?.removeFromSuperview()
if let customAccessoryView = customAccessoryView {
if customAccessoryView is UISwitch {
customAccessoryView.isAccessibilityElement = false
customAccessoryView.accessibilityElementsHidden = true
}
contentView.addSubview(customAccessoryView)
}
}
}
/// Extends custom accessory view to the trailing edge of the cell. Ignored when accessory type is not `.none` since in this case the built-in accessory is placed at the edge of the cell preventing custom accessory view from extending.
@objc open var customAccessoryViewExtendsToEdge: Bool = false {
didSet {
if customAccessoryViewExtendsToEdge == oldValue {
return
}
setNeedsLayout()
invalidateIntrinsicContentSize()
}
}
/// Style describing whether or not the cell's top separator should be visible and how wide it should extend
@objc open var topSeparatorType: SeparatorType = .none {
didSet {
if topSeparatorType != oldValue {
updateSeparator(topSeparator, with: topSeparatorType)
}
}
}
/// Style describing whether or not the cell's bottom separator should be visible and how wide it should extend
@objc open var bottomSeparatorType: SeparatorType = .inset {
didSet {
if bottomSeparatorType != oldValue {
updateSeparator(bottomSeparator, with: bottomSeparatorType)
}
}
}
/// When `isEnabled` is `false`, disables ability for a user to interact with a cell and dims cell's contents
@objc open var isEnabled: Bool = true {
didSet {
contentView.alpha = isEnabled ? Constants.enabledAlpha : Constants.disabledAlpha
isUserInteractionEnabled = isEnabled
initAccessoryTypeView()
updateAccessibility()
}
}
/// Enables / disables multi-selection mode by showing / hiding a checkmark selection indicator on the leading edge
@objc open var isInSelectionMode: Bool {
get { return _isInSelectionMode }
set { setIsInSelectionMode(newValue, animated: false) }
}
private var _isInSelectionMode: Bool = false
/// `onAccessoryTapped` is called when `detailButton` accessory view is tapped
@objc open var onAccessoryTapped: (() -> Void)?
open override var intrinsicContentSize: CGSize {
return CGSize(
width: type(of: self).preferredWidth(
title: titleLabel.text ?? "",
subtitle: subtitleLabel.text ?? "",
footer: footerLabel.text ?? "",
titleLeadingAccessoryView: titleLeadingAccessoryView,
titleTrailingAccessoryView: titleTrailingAccessoryView,
subtitleLeadingAccessoryView: subtitleLeadingAccessoryView,
subtitleTrailingAccessoryView: subtitleTrailingAccessoryView,
footerLeadingAccessoryView: footerLeadingAccessoryView,
footerTrailingAccessoryView: footerTrailingAccessoryView,
customViewSize: customViewSize,
customAccessoryView: customAccessoryView,
accessoryType: _accessoryType,
customAccessoryViewExtendsToEdge: customAccessoryViewExtendsToEdge,
isInSelectionMode: isInSelectionMode
),
height: type(of: self).height(
title: titleLabel.text ?? "",
subtitle: subtitleLabel.text ?? "",
footer: footerLabel.text ?? "",
titleLeadingAccessoryView: titleLeadingAccessoryView,
titleTrailingAccessoryView: titleTrailingAccessoryView,
subtitleLeadingAccessoryView: subtitleLeadingAccessoryView,
subtitleTrailingAccessoryView: subtitleTrailingAccessoryView,
footerLeadingAccessoryView: footerLeadingAccessoryView,
footerTrailingAccessoryView: footerTrailingAccessoryView,
customViewSize: customViewSize,
customAccessoryView: customAccessoryView,
accessoryType: _accessoryType,
titleNumberOfLines: titleNumberOfLines,
subtitleNumberOfLines: subtitleNumberOfLines,
footerNumberOfLines: footerNumberOfLines,
customAccessoryViewExtendsToEdge: customAccessoryViewExtendsToEdge,
containerWidth: .infinity,
isInSelectionMode: isInSelectionMode
)
)
}
open override var bounds: CGRect {
didSet {
if bounds.width != oldValue.width {
invalidateIntrinsicContentSize()
}
}
}
open override var frame: CGRect {
didSet {
if frame.width != oldValue.width {
invalidateIntrinsicContentSize()
}
}
}
open override var accessibilityHint: String? {
get {
if isInSelectionMode && isEnabled {
return "Accessibility.MultiSelect.Hint".localized
}
if let customSwitch = customAccessoryView as? UISwitch {
if isEnabled && customSwitch.isEnabled {
return "Accessibility.TableViewCell.Switch.Hint".localized
} else {
return nil
}
}
return super.accessibilityHint
}
set { super.accessibilityHint = newValue }
}
open override var accessibilityValue: String? {
get {
if let customAccessoryView = customAccessoryView as? UISwitch {
return (customAccessoryView.isOn ? "Accessibility.TableViewCell.Switch.On" : "Accessibility.TableViewCell.Switch.Off").localized
}
return super.accessibilityValue
}
set { super.accessibilityValue = newValue }
}
open override var accessibilityActivationPoint: CGPoint {
get {
if let customAccessoryView = customAccessoryView as? UISwitch {
return contentView.convert(customAccessoryView.center, to: nil)
}
return super.accessibilityActivationPoint
}
set { super.accessibilityActivationPoint = newValue }
}
// swiftlint:disable identifier_name
var _accessoryType: TableViewCellAccessoryType = .none {
didSet {
if _accessoryType == oldValue {
return
}
accessoryTypeView = _accessoryType == .none ? nil : TableViewCellAccessoryView(type: _accessoryType)
initAccessibilityForAccessoryType()
setNeedsLayout()
invalidateIntrinsicContentSize()
}
}
// swiftlint:enable identifier_name
private var layoutType: LayoutType = .oneLine {
didSet {
subtitleLabel.isHidden = layoutType == .oneLine
footerLabel.isHidden = layoutType != .threeLines
subtitleLabel.style = layoutType.subtitleTextStyle
setNeedsLayout()
invalidateIntrinsicContentSize()
}
}
private var preferredContentSizeIsLargerThanDefault: Bool {
switch traitCollection.preferredContentSizeCategory {
case .unspecified, .extraSmall, .small, .medium, .large:
return false
default:
return true
}
}
private var textAreaWidth: CGFloat {
let textAreaLeadingOffset = TableViewCell.textAreaLeadingOffset(customViewSize: customViewSize, isInSelectionMode: isInSelectionMode, paddingLeading: paddingLeading)
let textAreaTrailingOffset = TableViewCell.textAreaTrailingOffset(customAccessoryView: customAccessoryView, customAccessoryViewExtendsToEdge: customAccessoryViewExtendsToEdge, accessoryType: _accessoryType, paddingTrailing: paddingTrailing)
return contentView.frame.width - (textAreaLeadingOffset + textAreaTrailingOffset)
}
private(set) var customView: UIView? {
didSet {
oldValue?.removeFromSuperview()
if let customView = customView {
contentView.addSubview(customView)
customView.accessibilityElementsHidden = true
}
}
}
let titleLabel: Label = {
let label = Label(style: TextStyles.title)
label.lineBreakMode = .byTruncatingTail
return label
}()
let subtitleLabel: Label = {
let label = Label(style: TextStyles.subtitleTwoLines)
label.lineBreakMode = .byTruncatingTail
label.isHidden = true
return label
}()
let footerLabel: Label = {
let label = Label(style: TextStyles.footer)
label.lineBreakMode = .byTruncatingTail
label.isHidden = true
return label
}()
private func updateLabelAccessoryView(oldValue: UIView?, newValue: UIView?, size: inout CGSize) {
if newValue == oldValue {
return
}
oldValue?.removeFromSuperview()
if let newValue = newValue {
contentView.addSubview(newValue)
}
size = TableViewCell.labelAccessoryViewSize(for: newValue)
updateLayoutType()
}
private var titleLeadingAccessoryViewSize: CGSize = .zero
private var titleTrailingAccessoryViewSize: CGSize = .zero
private var subtitleLeadingAccessoryViewSize: CGSize = .zero
private var subtitleTrailingAccessoryViewSize: CGSize = .zero
private var footerLeadingAccessoryViewSize: CGSize = .zero
private var footerTrailingAccessoryViewSize: CGSize = .zero
internal var accessoryTypeView: TableViewCellAccessoryView? {
didSet {
oldValue?.removeFromSuperview()
if let accessoryTypeView = accessoryTypeView {
contentView.addSubview(accessoryTypeView)
initAccessoryTypeView()
}
}
}
private var selectionImageView: UIImageView = {
let imageView = UIImageView()
imageView.isHidden = true
return imageView
}()
internal let topSeparator = Separator(style: .default, orientation: .horizontal)
internal let bottomSeparator = Separator(style: .default, orientation: .horizontal)
private var superTableView: UITableView? {
return findSuperview(of: UITableView.self) as? UITableView
}
@objc public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
open func initialize() {
textLabel?.text = ""
updateTextColors()
contentView.addSubview(titleLabel)
contentView.addSubview(subtitleLabel)
contentView.addSubview(footerLabel)
contentView.addSubview(selectionImageView)
addSubview(topSeparator)
addSubview(bottomSeparator)
setupBackgroundColors()
hideSystemSeparator()
updateSeparator(topSeparator, with: topSeparatorType)
updateSeparator(bottomSeparator, with: bottomSeparatorType)
updateAccessibility()
NotificationCenter.default.addObserver(self, selector: #selector(handleContentSizeCategoryDidChange), name: UIContentSizeCategory.didChangeNotification, object: nil)
}
/// Sets up the cell with text, a custom view, a custom accessory view, and an accessory type
///
/// - Parameters:
/// - title: Text that appears as the first line of text
/// - subtitle: Text that appears as the second line of text
/// - footer: Text that appears as the third line of text
/// - customView: The custom view that appears near the leading edge next to the text
/// - customAccessoryView: The view acting as an accessory view that appears on the trailing edge, next to the accessory type if provided
/// - accessoryType: The type of accessory that appears on the trailing edge: a disclosure indicator or a details button with an ellipsis icon
@objc open func setup(title: String, subtitle: String = "", footer: String = "", customView: UIView? = nil, customAccessoryView: UIView? = nil, accessoryType: TableViewCellAccessoryType = .none) {
titleLabel.text = title
subtitleLabel.text = subtitle
footerLabel.text = footer
self.customView = customView
self.customAccessoryView = customAccessoryView
_accessoryType = accessoryType
updateLayoutType()
setNeedsLayout()
invalidateIntrinsicContentSize()
}
/// Allows to change the accessory type without doing a full `setup`.
@objc open func changeAccessoryType(to accessoryType: TableViewCellAccessoryType) {
_accessoryType = accessoryType
}
/// Sets the multi-selection state of the cell, optionally animating the transition between states.
///
/// - Parameters:
/// - isInSelectionMode: true to set the cell as in selection mode, false to set it as not in selection mode. The default is false.
/// - animated: true to animate the transition in / out of selection mode, false to make the transition immediate.
@objc open func setIsInSelectionMode(_ isInSelectionMode: Bool, animated: Bool) {
if _isInSelectionMode == isInSelectionMode {
return
}
_isInSelectionMode = isInSelectionMode
if !isInSelectionMode {
selectionImageView.isHidden = true
isSelected = false
}
let completion = { (_: Bool) in
if self.isInSelectionMode {
self.updateSelectionImageView()
self.selectionImageView.isHidden = false
}
}
setNeedsLayout()
invalidateIntrinsicContentSize()
if animated {
UIView.animate(withDuration: Constants.selectionModeAnimationDuration, delay: 0, options: [.layoutSubviews], animations: layoutIfNeeded, completion: completion)
} else {
completion(true)
}
initAccessoryTypeView()
selectionStyle = isInSelectionMode ? .none : .default
}
private var isUsingCustomTextColors: Bool = false
public func updateTextColors() {
if !isUsingCustomTextColors {
titleLabel.textColor = Colors.Table.Cell.title
subtitleLabel.textColor = Colors.Table.Cell.subtitle
footerLabel.textColor = Colors.Table.Cell.footer
}
}
/// To set color for title label
/// - Parameter color: UIColor to set
public func setTitleLabelTextColor(color: UIColor) {
titleLabel.textColor = color
isUsingCustomTextColors = true
}
/// To set color for subTitle label
/// - Parameter color: UIColor to set
public func setSubTitleLabelTextColor(color: UIColor) {
subtitleLabel.textColor = color
isUsingCustomTextColors = true
}
/// To set color for footer label
/// - Parameter color: UIColor to set
public func setFooterLabelTextColor(color: UIColor) {
footerLabel.textColor = color
isUsingCustomTextColors = true
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutContentSubviews()
contentView.flipSubviewsForRTL()
layoutSeparator(topSeparator, with: topSeparatorType, at: 0)
layoutSeparator(bottomSeparator, with: bottomSeparatorType, at: frame.height - bottomSeparator.frame.height)
}
open func layoutContentSubviews() {
if isInSelectionMode {
let selectionImageViewYOffset = UIScreen.main.roundToDevicePixels((contentView.frame.height - Constants.selectionImageSize.height) / 2)
selectionImageView.frame = CGRect(
origin: CGPoint(x: paddingLeading, y: selectionImageViewYOffset),
size: Constants.selectionImageSize
)
}
if let customView = customView {
let customViewYOffset = UIScreen.main.roundToDevicePixels((contentView.frame.height - customViewSize.size.height) / 2)
let customViewXOffset = TableViewCell.customViewLeadingOffset(isInSelectionMode: isInSelectionMode, paddingLeading: paddingLeading)
customView.frame = CGRect(
origin: CGPoint(x: customViewXOffset, y: customViewYOffset),
size: customViewSize.size
)
}
layoutLabelViews(label: titleLabel, numberOfLines: titleNumberOfLines, topOffset: 0, leadingAccessoryView: titleLeadingAccessoryView, leadingAccessoryViewSize: titleLeadingAccessoryViewSize, trailingAccessoryView: titleTrailingAccessoryView, trailingAccessoryViewSize: titleTrailingAccessoryViewSize)
if layoutType == .twoLines || layoutType == .threeLines {
layoutLabelViews(label: subtitleLabel, numberOfLines: subtitleNumberOfLines, topOffset: titleLabel.frame.maxY + Constants.labelVerticalSpacing, leadingAccessoryView: subtitleLeadingAccessoryView, leadingAccessoryViewSize: subtitleLeadingAccessoryViewSize, trailingAccessoryView: subtitleTrailingAccessoryView, trailingAccessoryViewSize: subtitleTrailingAccessoryViewSize)
if layoutType == .threeLines {
layoutLabelViews(label: footerLabel, numberOfLines: footerNumberOfLines, topOffset: subtitleLabel.frame.maxY + Constants.labelVerticalSpacing, leadingAccessoryView: footerLeadingAccessoryView, leadingAccessoryViewSize: footerLeadingAccessoryViewSize, trailingAccessoryView: footerTrailingAccessoryView, trailingAccessoryViewSize: footerTrailingAccessoryViewSize)
}
}
let textAreaHeight = TableViewCell.textAreaHeight(layoutType: layoutType, titleHeight: titleLabel.frame.height, subtitleHeight: subtitleLabel.frame.height, footerHeight: footerLabel.frame.height)
let textAreaTopOffset = UIScreen.main.roundToDevicePixels((contentView.frame.height - textAreaHeight) / 2)
adjustLabelViewsTop(by: textAreaTopOffset, label: titleLabel, leadingAccessoryView: titleLeadingAccessoryView, trailingAccessoryView: titleTrailingAccessoryView)
adjustLabelViewsTop(by: textAreaTopOffset, label: subtitleLabel, leadingAccessoryView: subtitleLeadingAccessoryView, trailingAccessoryView: subtitleTrailingAccessoryView)
adjustLabelViewsTop(by: textAreaTopOffset, label: footerLabel, leadingAccessoryView: footerLeadingAccessoryView, trailingAccessoryView: footerTrailingAccessoryView)
if let customAccessoryView = customAccessoryView {
let trailingOffset = TableViewCell.customAccessoryViewTrailingOffset(customAccessoryView: customAccessoryView, customAccessoryViewExtendsToEdge: customAccessoryViewExtendsToEdge, accessoryType: _accessoryType, paddingTrailing: paddingTrailing)
let xOffset = contentView.frame.width - customAccessoryView.frame.width - trailingOffset
let yOffset = UIScreen.main.roundToDevicePixels((contentView.frame.height - customAccessoryView.frame.height) / 2)
customAccessoryView.frame = CGRect(origin: CGPoint(x: xOffset, y: yOffset), size: customAccessoryView.frame.size)
}
if let accessoryTypeView = accessoryTypeView {
let xOffset = contentView.frame.width - TableViewCell.customAccessoryViewTrailingOffset(customAccessoryView: customAccessoryView, customAccessoryViewExtendsToEdge: customAccessoryViewExtendsToEdge, accessoryType: _accessoryType, paddingTrailing: paddingTrailing)
let yOffset = UIScreen.main.roundToDevicePixels((contentView.frame.height - _accessoryType.size.height) / 2)
accessoryTypeView.frame = CGRect(origin: CGPoint(x: xOffset, y: yOffset), size: _accessoryType.size)
}
}
private func layoutLabelViews(label: UILabel, numberOfLines: Int, topOffset: CGFloat, leadingAccessoryView: UIView?, leadingAccessoryViewSize: CGSize, trailingAccessoryView: UIView?, trailingAccessoryViewSize: CGSize) {
let textAreaLeadingOffset = TableViewCell.textAreaLeadingOffset(customViewSize: customViewSize, isInSelectionMode: isInSelectionMode, paddingLeading: paddingLeading)
let text = label.text ?? ""
let size = text.preferredSize(for: label.font, width: textAreaWidth, numberOfLines: numberOfLines)
if let leadingAccessoryView = leadingAccessoryView {
let yOffset = UIScreen.main.roundToDevicePixels(topOffset + (size.height - leadingAccessoryViewSize.height) / 2)
leadingAccessoryView.frame = CGRect(
x: textAreaLeadingOffset,
y: yOffset,
width: leadingAccessoryViewSize.width,
height: leadingAccessoryViewSize.height
)
}
let leadingAccessoryAreaWidth = TableViewCell.labelLeadingAccessoryAreaWidth(viewWidth: leadingAccessoryViewSize.width)
let labelSize = TableViewCell.labelSize(text: text, font: label.font, numberOfLines: numberOfLines, textAreaWidth: textAreaWidth, leadingAccessoryView: leadingAccessoryView, trailingAccessoryView: trailingAccessoryView)
label.frame = CGRect(
x: textAreaLeadingOffset + leadingAccessoryAreaWidth,
y: topOffset,
width: labelSize.width,
height: labelSize.height
)
if let trailingAccessoryView = trailingAccessoryView {
let yOffset = UIScreen.main.roundToDevicePixels(topOffset + (labelSize.height - trailingAccessoryViewSize.height) / 2)
let availableWidth = textAreaWidth - labelSize.width - leadingAccessoryAreaWidth
let leadingMargin = TableViewCell.labelTrailingAccessoryMarginLeading(text: text)
trailingAccessoryView.frame = CGRect(
x: label.frame.maxX + leadingMargin,
y: yOffset,
width: availableWidth - leadingMargin,
height: trailingAccessoryViewSize.height
)
}
}
private func adjustLabelViewsTop(by offset: CGFloat, label: UILabel, leadingAccessoryView: UIView?, trailingAccessoryView: UIView?) {
label.frame.origin.y += offset
leadingAccessoryView?.frame.origin.y += offset
trailingAccessoryView?.frame.origin.y += offset
}
private func layoutSeparator(_ separator: Separator, with type: SeparatorType, at verticalOffset: CGFloat) {
separator.frame = CGRect(
x: separatorLeadingInset(for: type),
y: verticalOffset,
width: frame.width - separatorLeadingInset(for: type),
height: separator.frame.height
)
separator.flipForRTL()
}
func separatorLeadingInset(for type: SeparatorType) -> CGFloat {
guard type == .inset else {
return 0
}
let baseOffset = safeAreaInsets.left + TableViewCell.selectionModeAreaWidth(isInSelectionMode: isInSelectionMode)
switch customViewSize {
case .zero:
return baseOffset + separatorLeadingInsetForNoCustomView
case .small:
return baseOffset + separatorLeadingInsetForSmallCustomView
case .medium, .default:
return baseOffset + separatorLeadingInsetForMediumCustomView
}
}
open override func prepareForReuse() {
super.prepareForReuse()
titleNumberOfLines = 1
subtitleNumberOfLines = 1
footerNumberOfLines = 1
titleNumberOfLinesForLargerDynamicType = Self.defaultNumberOfLinesForLargerDynamicType
subtitleNumberOfLinesForLargerDynamicType = Self.defaultNumberOfLinesForLargerDynamicType
footerNumberOfLinesForLargerDynamicType = Self.defaultNumberOfLinesForLargerDynamicType
titleLineBreakMode = .byTruncatingTail
subtitleLineBreakMode = .byTruncatingTail
footerLineBreakMode = .byTruncatingTail
titleLeadingAccessoryView = nil
titleTrailingAccessoryView = nil
subtitleLeadingAccessoryView = nil
subtitleTrailingAccessoryView = nil
footerLeadingAccessoryView = nil
footerTrailingAccessoryView = nil
customViewSize = .default
customAccessoryViewExtendsToEdge = false
topSeparatorType = .none
bottomSeparatorType = .inset
isEnabled = true
isInSelectionMode = false
onAccessoryTapped = nil
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
let maxWidth = size.width != 0 ? size.width : .infinity
return CGSize(
width: min(
type(of: self).preferredWidth(
title: titleLabel.text ?? "",
subtitle: subtitleLabel.text ?? "",
footer: footerLabel.text ?? "",
titleLeadingAccessoryView: titleLeadingAccessoryView,
titleTrailingAccessoryView: titleTrailingAccessoryView,
subtitleLeadingAccessoryView: subtitleLeadingAccessoryView,
subtitleTrailingAccessoryView: subtitleTrailingAccessoryView,
footerLeadingAccessoryView: footerLeadingAccessoryView,
footerTrailingAccessoryView: footerTrailingAccessoryView,
customViewSize: customViewSize,
customAccessoryView: customAccessoryView,
accessoryType: _accessoryType,
customAccessoryViewExtendsToEdge: customAccessoryViewExtendsToEdge,
isInSelectionMode: isInSelectionMode
),
maxWidth
),
height: type(of: self).height(
title: titleLabel.text ?? "",
subtitle: subtitleLabel.text ?? "",
footer: footerLabel.text ?? "",
titleLeadingAccessoryView: titleLeadingAccessoryView,
titleTrailingAccessoryView: titleTrailingAccessoryView,
subtitleLeadingAccessoryView: subtitleLeadingAccessoryView,
subtitleTrailingAccessoryView: subtitleTrailingAccessoryView,
footerLeadingAccessoryView: footerLeadingAccessoryView,
footerTrailingAccessoryView: footerTrailingAccessoryView,
customViewSize: customViewSize,
customAccessoryView: customAccessoryView,
accessoryType: _accessoryType,
titleNumberOfLines: titleNumberOfLines,
subtitleNumberOfLines: subtitleNumberOfLines,
footerNumberOfLines: footerNumberOfLines,
customAccessoryViewExtendsToEdge: customAccessoryViewExtendsToEdge,
containerWidth: maxWidth,
isInSelectionMode: isInSelectionMode
)
)
}
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
// If using cell within a superview other than UITableView override setSelected()
if superTableView == nil && !isInSelectionMode {
setSelected(true, animated: false)
}
}
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
let oldIsSelected = isSelected
super.touchesCancelled(touches, with: event)
// If using cell within a superview other than UITableView override setSelected()
if superTableView == nil {
if isInSelectionMode {
// Cell unselects itself in super.touchesCancelled which is not what we want in multi-selection mode - restore selection back
setSelected(oldIsSelected, animated: false)
} else {
setSelected(false, animated: true)
}
}
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
if superTableView == nil && _isInSelectionMode {
setSelected(!isSelected, animated: true)
}
selectionDidChange()
// If using cell within a superview other than UITableView override setSelected()
if superTableView == nil && !isInSelectionMode {
setSelected(false, animated: true)
}
}
open override func didMoveToWindow() {
super.didMoveToWindow()
updateSelectionImageColor()
}
open func selectionDidChange() { }
open override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
updateSelectionImageView()
}
private func updateLayoutType() {
layoutType = TableViewCell.layoutType(
subtitle: subtitleLabel.text ?? "",
footer: footerLabel.text ?? "",
subtitleLeadingAccessoryView: subtitleLeadingAccessoryView,
subtitleTrailingAccessoryView: subtitleTrailingAccessoryView,
footerLeadingAccessoryView: footerLeadingAccessoryView,
footerTrailingAccessoryView: footerTrailingAccessoryView
)
}
private func updateTitleNumberOfLines() {
titleLabel.numberOfLines = titleNumberOfLines
setNeedsLayout()
invalidateIntrinsicContentSize()
}
private func updateSubtitleNumberOfLines() {
subtitleLabel.numberOfLines = subtitleNumberOfLines
setNeedsLayout()
invalidateIntrinsicContentSize()
}
private func updateFooterNumberOfLines() {
footerLabel.numberOfLines = footerNumberOfLines
setNeedsLayout()
invalidateIntrinsicContentSize()
}
@objc private func handleDetailButtonTapped() {
onAccessoryTapped?()
if let tableView = superTableView, let indexPath = tableView.indexPath(for: self) {
tableView.delegate?.tableView?(tableView, accessoryButtonTappedForRowWith: indexPath)
}
}
private func initAccessoryTypeView() {
guard let accessoryTypeView = accessoryTypeView else {
return
}
if accessoryTypeView.type == .detailButton {
accessoryTypeView.isUserInteractionEnabled = isEnabled && !isInSelectionMode
accessoryTypeView.onTapped = handleDetailButtonTapped
}
}
private func setupBackgroundColors() {
backgroundColor = Colors.Table.Cell.background
let selectedStateBackgroundView = UIView()
selectedStateBackgroundView.backgroundColor = Colors.Table.Cell.backgroundSelected
selectedBackgroundView = selectedStateBackgroundView
}
private func initAccessibilityForAccessoryType() {
if _accessoryType == .checkmark || isSelected {
accessibilityTraits.insert(.selected)
} else {
accessibilityTraits.remove(.selected)
}
}
private func updateAccessibility() {
accessibilityTraits.insert(.button)
if isEnabled {
accessibilityTraits.remove(.notEnabled)
} else {
accessibilityTraits.insert(.notEnabled)
}
}
private func updateSelectionImageView() {
selectionImageView.image = isSelected ? Constants.selectionImageOn : Constants.selectionImageOff
updateSelectionImageColor()
}
private func updateSelectionImageColor() {
if let window = window {
selectionImageView.tintColor = isSelected ? Colors.primary(for: window) : Colors.Table.Cell.selectionIndicatorOff
}
}
private func updateSeparator(_ separator: Separator, with type: SeparatorType) {
separator.isHidden = type == .none
setNeedsLayout()
}
@objc private func handleContentSizeCategoryDidChange() {
updateTitleNumberOfLines()
updateSubtitleNumberOfLines()
updateFooterNumberOfLines()
titleLeadingAccessoryViewSize = TableViewCell.labelAccessoryViewSize(for: titleLeadingAccessoryView)
titleTrailingAccessoryViewSize = TableViewCell.labelAccessoryViewSize(for: titleTrailingAccessoryView)
subtitleLeadingAccessoryViewSize = TableViewCell.labelAccessoryViewSize(for: subtitleLeadingAccessoryView)
subtitleTrailingAccessoryViewSize = TableViewCell.labelAccessoryViewSize(for: subtitleTrailingAccessoryView)
footerLeadingAccessoryViewSize = TableViewCell.labelAccessoryViewSize(for: footerLeadingAccessoryView)
footerTrailingAccessoryViewSize = TableViewCell.labelAccessoryViewSize(for: footerTrailingAccessoryView)
setNeedsLayout()
invalidateIntrinsicContentSize()
}
}
// MARK: - TableViewCellAccessoryView
internal class TableViewCellAccessoryView: UIView {
override var accessibilityElementsHidden: Bool { get { return !isUserInteractionEnabled } set { } }
override var intrinsicContentSize: CGSize { return type.size }
let type: TableViewCellAccessoryType
var iconView: UIImageView?
/// `onTapped` is called when `detailButton` is tapped
var onTapped: (() -> Void)?
var customTintColor: UIColor? {
didSet {
if let iconView = iconView {
iconView.tintColor = customTintColor
}
}
}
init(type: TableViewCellAccessoryType) {
self.type = type
super.init(frame: .zero)
switch type {
case .none:
break
case .disclosureIndicator, .checkmark:
addIconView(type: type)
case .detailButton:
addSubview(detailButton)
detailButton.fitIntoSuperview()
}
}
required init?(coder aDecoder: NSCoder) {
preconditionFailure("init(coder:) has not been implemented")
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return type.size
}
override func didMoveToWindow() {
super.didMoveToWindow()
updateWindowSpecificColors()
}
private func addIconView(type: TableViewCellAccessoryType) {
iconView = UIImageView(image: type.icon)
if let iconView = iconView {
iconView.frame.size = type.size
iconView.contentMode = .center
addSubview(iconView)
iconView.fitIntoSuperview()
}
}
@objc private func handleOnAccessoryTapped() {
onTapped?()
}
private lazy var detailButton: UIButton = {
let button = UIButton(type: .custom)
button.setImage(type.icon, for: .normal)
button.frame.size = type.size
button.contentMode = .center
button.accessibilityLabel = "Accessibility.TableViewCell.MoreActions.Label".localized
button.accessibilityHint = "Accessibility.TableViewCell.MoreActions.Hint".localized
button.addTarget(self, action: #selector(handleOnAccessoryTapped), for: .touchUpInside)
if #available(iOS 13.4, *) {
// Workaround check for beta iOS versions missing the Pointer Interactions API
if arePointerInteractionAPIsAvailable() {
button.isPointerInteractionEnabled = true
}
}
return button
}()
private func updateWindowSpecificColors() {
if let window = window {
let iconColor = type.iconColor(for: window)
iconView?.tintColor = customTintColor ?? iconColor
if type == .detailButton {
detailButton.tintColor = iconColor
}
}
}
}
| 46.445839 | 383 | 0.677413 |
201fbd716897c0d5da6ca17f3d61db95734081b8 | 2,957 | //
// MainViewModel.swift
// MoneyExchange
//
// Created by Chien on 2021/1/4.
// Copyright © 2021 Chien. All rights reserved.
//
import Foundation
enum RequestError: Error {
// Error of Reqeust
case URLFail(thisURLStr: String)
case RequestFail
case DataIsNil
case DecodeFail
}
class MainViewModel {
// Add USD first because all exchange rates are based on USD
private var countryList: [String] = ["USD"]
private var exchangeRateDict: [String: Double] = ["USD": 1]
func fetchExchangeRateAPI(completion: @escaping (_ countryList: [String], _ exchangeRateDict: [String: Double], _ error: RequestError?) -> Void) {
/*
{
"USDUAH": {
"Exrate": 24.75109,
"UTC": "2019-10-19 09:00:00"
},
.
.
.
"USDAWG": {
"Exrate": 1.8,
"UTC": "2019-10-19 09:00:00"
},
.
.
.
}
*/
let requestURLStr = "https://tw.rter.info/capi.php"
guard let requestURL = URL(string: requestURLStr) else { completion([], [:], .URLFail(thisURLStr: requestURLStr)) ; return }
URLSession.shared.dataTask(with: requestURL) { (data, response, error) in
guard error == nil else { completion([], [:], .RequestFail) ; return }
guard let thisData = data else { completion([], [:], .DataIsNil) ; return }
guard let jsonObject = try? JSONSerialization.jsonObject(with: thisData, options: []) as? NSDictionary else {
completion([], [:], .DecodeFail)
return
}
for eachObject in jsonObject.allKeys {
guard let key = eachObject as? String else { return completion([], [:], .DecodeFail) }
// Only focus on USD to others
if key.contains("USD") {
guard let valueDict = jsonObject.value(forKey: key) as? NSDictionary else { return completion([], [:], .DecodeFail) }
guard let exchangeRate = valueDict["Exrate"] as? Double else { return completion([], [:], .DecodeFail) }
let filterArray = key.components(separatedBy: "USD")
let thisCountryName = filterArray[1]
if thisCountryName.count > 0 {
self.countryList.append(thisCountryName)
self.exchangeRateDict[thisCountryName] = exchangeRate
}
}
}
self.countryList.sort()
completion(self.countryList, self.exchangeRateDict, nil)
}.resume()
}
}
| 33.988506 | 150 | 0.490024 |
5bc2f43205100596dd96799df03c9fbeb3808fe0 | 1,124 | //
// DemoViewController.swift
// FormsDemo
//
// Created by Konrad on 4/2/20.
// Copyright © 2020 Limbo. All rights reserved.
//
import Forms
import FormsAnchor
import UIKit
// MARK: DemoViewViewController
class DemoViewController: FormsViewController {
private let centerView = Components.container.view()
.with(backgroundColor: Theme.Colors.red)
.with(height: 44)
private let bottomView = Components.container.gradient()
.with(gradientColors: [Theme.Colors.green, Theme.Colors.red])
.with(height: 44)
override func setupContent() {
super.setupContent()
self.setupCenterView()
self.setupBottomView()
}
private func setupCenterView() {
self.view.addSubview(self.centerView, with: [
Anchor.to(self.view).center(300, 44)
])
}
private func setupBottomView() {
self.view.addSubview(self.bottomView, with: [
Anchor.to(self.centerView).topToBottom.offset(16),
Anchor.to(self.centerView).horizontal,
Anchor.to(self.centerView).height
])
}
}
| 26.761905 | 69 | 0.641459 |
67b5a93d682007ffe4d55f8cfe52999136c52410 | 664 | //
// AdaptiveController.swift
// AdaptiveTabBarControllerSample
//
// Created by Arcilite on 17.09.14.
// Copyright (c) 2014 Ramotion. All rights reserved.
//
import UIKit
public let kDefaultAdaptiveState: String = "DefaultAdaptiveState"
public class AdaptiveState: NSObject {
var currentItemState: String = kDefaultAdaptiveState
var buttonStates: [String] = [String]()
public override init() {
super.init()
addNewCustomAdaptiveStates(customAdaptiveStates: [kDefaultAdaptiveState])
}
internal func addNewCustomAdaptiveStates(customAdaptiveStates: Array<String>) {
buttonStates += customAdaptiveStates
}
}
| 24.592593 | 83 | 0.728916 |
50ab01ccd695667a8fde6586170b7cff4f2425d6 | 757 | //
// RoundedCorner.swift
// BricksUI
//
// Created by Micaela Cavallo on 01/05/2020.
// Copyright © 2020 Fabio Staiano. All rights reserved.
//
import SwiftUI
extension View {
// function for CornerRadius struct
func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
clipShape( RoundedCorner(radius: radius, corners: corners) )
}
}
/// Custom shape with independently rounded corners
struct RoundedCorner: Shape {
var radius: CGFloat = .infinity
var corners: UIRectCorner = .allCorners
func path(in rect: CGRect) -> Path {
let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
return Path(path.cgPath)
}
}
| 26.103448 | 130 | 0.693527 |
e9135b73c4da06fc9aca2552d85d5d5d095ca349 | 535 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
protocol P {
associatedtype T
func foo(t: inout T)
}
struct S: P {
func foo(t: inout () -> Void) {
t()
t = { print("new") }
}
}
func doTheFoo<SomeP: P>(_ p: SomeP, _ value: SomeP.T) -> SomeP.T {
var mutableValue = value
p.foo(t: &mutableValue)
return mutableValue
}
print("START")
let newClosure = doTheFoo(S(), { print("old") })
newClosure()
print("DONE")
// CHECK: START
// CHECK-NEXT: old
// CHECK-NEXT: new
// CHECK-NEXT: DONE
| 17.833333 | 66 | 0.62243 |
d50a9e09046f66cbb8588fbd6e06893ddb96f63f | 508 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol d
let f{
class n{
struct Q<T where g:U{class A<T{
func a:d
func a
struct c{{
}
func d{
a
typealias e
| 25.4 | 79 | 0.740157 |
6465f4470e1768745a36f3f2009ac7032b5be705 | 285 | /**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Cocoa
// Dummy NvimView class for FontUtils.
class NvimView {
static let defaultFont = NSFont.userFixedPitchFont(ofSize: 12)!
static let minFontSize = CGFloat(9)
static let maxFontSize = CGFloat(128)
}
| 20.357143 | 65 | 0.708772 |
5dd80018951c32896fc8e725a9e7feed20d630cf | 803 | extension Color: CustomStringConvertible {
public var description: String {
return hexString
}
}
extension Color: ExpressibleByStringLiteral {
public init(extendedGraphemeClusterLiteral value: String) {
if let color = Color(hexString: value) {
self = color
} else {
fatalError("Invalid color hex-string")
}
}
public init(unicodeScalarLiteral value: String) {
if let color = Color(hexString: value) {
self = color
} else {
fatalError("Invalid color hex-string")
}
}
public init(stringLiteral value: String) {
if let color = Color(hexString: value) {
self = color
} else {
fatalError("Invalid color hex-string")
}
}
}
| 25.09375 | 63 | 0.576588 |
09cf24937dbf7ddc5ae7faf8a7c3d1e1952ef70d | 396 | //
// Series.swift
// marvel-universe
//
// Created by Sibagatov Ildar on 10/1/16.
// Copyright © 2016 Sibagatov Ildar. All rights reserved.
//
import ObjectMapper
class Series: Mappable {
var name: String?
var resourceURI: String?
required init?(map: Map) { }
func mapping(map: Map) {
name <- map["name"]
resourceURI <- map["resourceURI"]
}
}
| 18 | 58 | 0.606061 |
1d0837b34745ab00e7f14b53e51ffc3e9b414ada | 1,928 | //
// FCJSONDecoder.swift
// FirebaseCodable
//
// Created by hasegawa-yusuke on 2019/08/01.
//
import Foundation
import FirebaseFirestore
public protocol FCJsonDecoderProtocol: AnyObject {
func decode<T>(_ type: T.Type, json: Any) throws -> T where T: Decodable
func decode<T>(_ type: T.Type, json: [String: Any], id: String) throws -> T where T: FirestoreCodable
}
public extension FCJsonDecoderProtocol where Self: JSONDecoder {
/// Decode JSON object to Type which confirms Decodable
/// - Parameters:
/// - type: Type
/// - json: JSON object
func decode<T: Decodable>(_ type: T.Type, json: Any) throws -> T {
var input = json
if var list = input as? [String: Any] {
convertTimestampToJson(&list)
input = list
}
let data = try JSONSerialization.data(withJSONObject: input, options: [])
return try self.decode(T.self, from: data)
}
/// Decode JSON object to Type which confirms FirestoreCodable
/// - Parameters:
/// - type: Type
/// - json: JSON object
/// - id: Document ID
func decode<T: FirestoreCodable>(_ type: T.Type, json: [String: Any], id: String) throws -> T {
var input = json
input["id"] = id
convertTimestampToJson(&input)
let data = try JSONSerialization.data(withJSONObject: input, options: [])
return try self.decode(T.self, from: data)
}
}
private extension FCJsonDecoderProtocol {
/// Convert top-level Timestamp to JSON
/// - Parameter json: JSON object
func convertTimestampToJson(_ json: inout [String: Any]) {
json.forEach { key, value in
if let timestamp = value as? Timestamp {
json[key] = ["seconds": timestamp.seconds, "nanoseconds": timestamp.nanoseconds]
}
}
}
}
| 28.776119 | 105 | 0.596992 |
110326c5b34cd2b177e52eeceeac5975814a2b78 | 502 | //
// AppDelegate.swift
// FirebaseRequester
//
// Created by Richard Frank on 23/07/2018.
// Copyright © 2018 Richard Frank. All rights reserved.
//
import UIKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
return true
}
}
| 20.916667 | 101 | 0.719124 |
67a36b98cea82059762439860426fec6ee23b994 | 470 | // UIDatePickerExtensions.swift - Copyright 2020 SwifterSwift
#if canImport(UIKit) && os(iOS)
import UIKit
// MARK: - Properties
public extension UIDatePicker {
#if !targetEnvironment(macCatalyst)
/// SwifterSwift: Text color of UIDatePicker.
var textColor: UIColor? {
get {
value(forKeyPath: "textColor") as? UIColor
}
set {
setValue(newValue, forKeyPath: "textColor")
}
}
#endif
}
#endif
| 20.434783 | 61 | 0.623404 |
7263a0c60127ded75333b978799e1021e20bd187 | 10,798 | //
// RegisterAccount4ViewController.swift
// Cosmostation
//
// Created by 정용주 on 2020/10/30.
// Copyright © 2020 wannabit. All rights reserved.
//
import UIKit
import Alamofire
import BitcoinKit
import SwiftKeychainWrapper
class RegisterAccount4ViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, PasswordViewDelegate {
@IBOutlet weak var btnBack: UIButton!
@IBOutlet weak var btnConfirm: UIButton!
@IBOutlet weak var resigter4Tableview: UITableView!
var pageHolderVC: StepGenTxViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.account = BaseData.instance.selectAccountById(id: BaseData.instance.getRecentAccountId())
self.chainType = WUtils.getChainType(account!.account_base_chain)
self.pageHolderVC = self.parent as? StepGenTxViewController
self.resigter4Tableview.delegate = self
self.resigter4Tableview.dataSource = self
self.resigter4Tableview.separatorStyle = UITableViewCell.SeparatorStyle.none
self.resigter4Tableview.register(UINib(nibName: "RegistAccountCheckCell", bundle: nil), forCellReuseIdentifier: "RegistAccountCheckCell")
}
override func enableUserInteraction() {
self.resigter4Tableview.reloadData()
self.btnBack.isUserInteractionEnabled = true
self.btnConfirm.isUserInteractionEnabled = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:RegistAccountCheckCell? = tableView.dequeueReusableCell(withIdentifier:"RegistAccountCheckCell") as? RegistAccountCheckCell
let starnameFee = BaseData.instance.mStarNameFee!.getAccountFee("open")
cell?.feeAmountLabel.attributedText = WUtils.displayAmount2((pageHolderVC.mFee?.amount[0].amount)!, cell!.feeAmountLabel.font, 6, 6)
cell?.starnameFeeAmount.attributedText = WUtils.displayAmount2(starnameFee.stringValue, cell!.starnameFeeAmount.font, 6, 6)
cell?.starnameLabel.text = pageHolderVC.mStarnameAccount! + "*iov"
let extendTime = BaseData.instance.mStarNameConfig!.getRegisterDomainExpireTime()
cell?.expireDate.text = WUtils.longTimetoString(input: Date().millisecondsSince1970 + extendTime)
cell?.memoLabel.text = pageHolderVC.mMemo
let resources = pageHolderVC.mStarnameResources
if (resources.count == 0) {
cell?.connectedAddressesLabel.text = ""
} else {
var resourceString = ""
for resource in resources {
resourceString.append(resource.uri + "\n" + resource.resource + "\n\n")
}
cell?.connectedAddressesLabel.text = resourceString
}
return cell!
}
@IBAction func onClickBack(_ sender: UIButton) {
self.btnBack.isUserInteractionEnabled = false
self.btnConfirm.isUserInteractionEnabled = false
pageHolderVC.onBeforePage()
}
@IBAction func onClickConfirm(_ sender: UIButton) {
let passwordVC = UIStoryboard(name: "Password", bundle: nil).instantiateViewController(withIdentifier: "PasswordViewController") as! PasswordViewController
self.navigationItem.title = ""
self.navigationController!.view.layer.add(WUtils.getPasswordAni(), forKey: kCATransition)
passwordVC.mTarget = PASSWORD_ACTION_CHECK_TX
passwordVC.resultDelegate = self
self.navigationController?.pushViewController(passwordVC, animated: false)
}
func passwordResponse(result: Int) {
if (result == PASSWORD_RESUKT_OK) {
self.onFetchAccountInfo(pageHolderVC.mAccount!)
}
}
func onFetchAccountInfo(_ account: Account) {
self.showWaittingAlert()
var url: String?
if (pageHolderVC.chainType! == ChainType.IOV_MAIN) {
url = IOV_ACCOUNT_INFO + account.account_address
} else if (pageHolderVC.chainType! == ChainType.IOV_TEST) {
url = IOV_TEST_ACCOUNT_INFO + account.account_address
}
let request = Alamofire.request(url!, method: .get, parameters: [:], encoding: URLEncoding.default, headers: [:]);
request.responseJSON { (response) in
switch response.result {
case .success(let res):
guard let responseData = res as? NSDictionary,
let info = responseData.object(forKey: "result") as? [String : Any] else {
_ = BaseData.instance.deleteBalance(account: account)
self.hideWaittingAlert()
self.onShowToast(NSLocalizedString("error_network", comment: ""))
return
}
let accountInfo = AccountInfo.init(info)
_ = BaseData.instance.updateAccount(WUtils.getAccountWithAccountInfo(account, accountInfo))
BaseData.instance.updateBalances(account.account_id, WUtils.getBalancesWithAccountInfo(account, accountInfo))
self.onGenRegistAccountTx()
case .failure( _):
self.hideWaittingAlert()
self.onShowToast(NSLocalizedString("error_network", comment: ""))
}
}
}
func onGenRegistAccountTx() {
DispatchQueue.global().async {
var stdTx:StdTx!
guard let words = KeychainWrapper.standard.string(forKey: self.pageHolderVC.mAccount!.account_uuid.sha1())?.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: " ") else {
return
}
do {
let pKey = WKey.getHDKeyFromWords(words, self.pageHolderVC.mAccount!)
let msg = MsgGenerator.genRegisterAccountMsg(self.pageHolderVC.mStarnameDomain!,
self.pageHolderVC.mStarnameAccount!,
self.pageHolderVC.mAccount!.account_address,
self.pageHolderVC.mAccount!.account_address,
self.pageHolderVC.mStarnameResources,
self.pageHolderVC.chainType!)
var msgList = Array<Msg>()
msgList.append(msg)
let stdMsg = MsgGenerator.getToSignMsg(WUtils.getChainId(self.pageHolderVC.mAccount!.account_base_chain),
String(self.pageHolderVC.mAccount!.account_account_numner),
String(self.pageHolderVC.mAccount!.account_sequence_number),
msgList,
self.pageHolderVC.mFee!,
self.pageHolderVC.mMemo!)
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let data = try? encoder.encode(stdMsg)
let rawResult = String(data:data!, encoding:.utf8)?.replacingOccurrences(of: "\\/", with: "/")
let rawData: Data? = rawResult!.data(using: .utf8)
let hash = Crypto.sha256(rawData!)
let signedData: Data? = try Crypto.sign(hash, privateKey: pKey.privateKey())
var genedSignature = Signature.init()
var genPubkey = PublicKey.init()
genPubkey.type = COSMOS_KEY_TYPE_PUBLIC
genPubkey.value = pKey.privateKey().publicKey().raw.base64EncodedString()
genedSignature.pub_key = genPubkey
genedSignature.signature = WKey.convertSignature(signedData!)
genedSignature.account_number = String(self.pageHolderVC.mAccount!.account_account_numner)
genedSignature.sequence = String(self.pageHolderVC.mAccount!.account_sequence_number)
var signatures: Array<Signature> = Array<Signature>()
signatures.append(genedSignature)
stdTx = MsgGenerator.genSignedTx(msgList, self.pageHolderVC.mFee!, self.pageHolderVC.mMemo!, signatures)
} catch {
if (SHOW_LOG) { print(error) }
}
DispatchQueue.main.async(execute: {
let postTx = PostTx.init("sync", stdTx.value)
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let data = try? encoder.encode(postTx)
do {
let params = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
var url: String?
if (self.pageHolderVC.chainType! == ChainType.IOV_MAIN) {
url = IOV_BORAD_TX
} else if (self.pageHolderVC.chainType! == ChainType.IOV_TEST) {
url = IOV_TEST_BORAD_TX
}
let request = Alamofire.request(url!, method: .post, parameters: params, encoding: JSONEncoding.default, headers: [:])
request.validate().responseJSON { response in
var txResult = [String:Any]()
switch response.result {
case .success(let res):
if(SHOW_LOG) { print("onGenRenewStarnameTx ", res) }
if let result = res as? [String : Any] {
txResult = result
}
case .failure(let error):
if(SHOW_LOG) {
print("onGenRenewStarnameTx error ", error)
}
if (response.response?.statusCode == 500) {
txResult["net_error"] = 500
}
}
if (self.waitAlert != nil) {
self.waitAlert?.dismiss(animated: true, completion: {
self.onStartTxDetail(txResult)
})
}
}
} catch {
if (SHOW_LOG) { print(error) }
}
});
}
}
}
| 48.859729 | 203 | 0.567235 |
f5deddde3e56eec9e170083343c8690c087f12b8 | 2,183 | //
// AppDelegate.swift
// solid-snake-test
//
// Created by Ganesha Danu on 27/02/19.
// Copyright © 2019 Ganesha Danu. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.446809 | 285 | 0.754924 |
7a023ea22574676fddbfc346854378c87b027c12 | 1,706 | //
// ViewController.swift
// SMSLocalization
//
// Created by Macuser on 5/19/16.
// Copyright © 2016 Macuser. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var userNameTxtField: UITextField!
@IBOutlet weak var passwordTxtField: UITextField!
@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var pwdLbl: UILabel!
@IBOutlet weak var loginBtn: UIButton!
var bundle: Bundle = Bundle(){
didSet{
localizeString()
}
}
func localizeString(){
userNameTxtField.placeholder = NSLocalizedString("KUserName", bundle: bundle, comment: "hello")
passwordTxtField.placeholder = NSLocalizedString("KPassword", bundle: bundle, comment: "hello")
nameLbl.text = NSLocalizedString("KName", bundle: bundle, comment: "hello")
pwdLbl.text = NSLocalizedString("KPwd", bundle: bundle, comment: "hello")
loginBtn.setTitle(NSLocalizedString("KLogin", bundle: bundle, comment: "hello"), for: UIControlState())
}
override func viewDidLoad() {
super.viewDidLoad()
bundle = LanguageManager.sharedInstance.getCurrentBundle()
}
@IBAction func showAlertInEnglishActn(_ sender: AnyObject) {
LanguageManager.sharedInstance.setLocale("en")
bundle = LanguageManager.sharedInstance.getCurrentBundle()
}
@IBAction func showAlertInFinishActn(_ sender: AnyObject) {
LanguageManager.sharedInstance.setLocale("fi")
bundle = LanguageManager.sharedInstance.getCurrentBundle()
}
}
| 26.246154 | 111 | 0.637749 |
64ce156661a6cff21de8878b1b00172a824b16cb | 592 | import wickedData
public extension Dictionary where Key == String, Value == String {
var asOpenKEReversedIdMapping: [String] {
var mapping = ["\(count)"]
for (id, name) in self {
mapping.append("\(name)\t\(id)")
}
return mapping
}
}
public extension Array where Element == Triple {
var asOpenKETriples: [String] {
var triples = ["\(count)"]
for triple in self {
triples.append("\(triple.head.value)\t\(triple.tail.value)\t\(triple.relationship.name)")
}
return triples
}
}
| 21.925926 | 101 | 0.565878 |
4ac8216f049dca7dbaee5d6b3da002552267e6d4 | 3,171 | import XCTest
import CoreLocation
@testable import MapboxCoreNavigation
let oneMile: CLLocationDistance = metersPerMile
let oneFeet: CLLocationDistance = 0.3048
class DistanceFormatterTests: XCTestCase {
var distanceFormatter = DistanceFormatter(approximate: true)
override func setUp() {
super.setUp()
}
func assertDistance(_ distance: CLLocationDistance, displayed: String) {
let displayedString = distanceFormatter.string(from: distance)
XCTAssert(displayedString.contains(displayed), "Displayed: '\(displayedString)' should be equal to \(displayed)")
}
func testDistanceFormatters_US() {
distanceFormatter.numberFormatter.locale = Locale(identifier: "en-US")
assertDistance(0, displayed: "0 ft")
assertDistance(oneFeet*50, displayed: "50 ft")
assertDistance(oneFeet*100, displayed: "100 ft")
assertDistance(oneFeet*249, displayed: "250 ft")
assertDistance(oneFeet*305, displayed: "300 ft")
assertDistance(oneMile*0.1, displayed: "0.1 mi")
assertDistance(oneMile*0.24, displayed: "0.2 mi")
assertDistance(oneMile*0.251, displayed: "0.3 mi")
assertDistance(oneMile*0.75, displayed: "0.8 mi")
assertDistance(oneMile, displayed: "1 mi")
assertDistance(oneMile*2.5, displayed: "2.5 mi")
assertDistance(oneMile*2.9, displayed: "2.9 mi")
assertDistance(oneMile*3, displayed: "3 mi")
assertDistance(oneMile*3.5, displayed: "4 mi")
assertDistance(oneMile*5.4, displayed: "5 mi")
}
func testDistanceFormatters_DE() {
distanceFormatter.numberFormatter.locale = Locale(identifier: "de-DE")
assertDistance(0, displayed: "0 m")
assertDistance(4, displayed: "5 m")
assertDistance(11, displayed: "10 m")
assertDistance(15, displayed: "15 m")
assertDistance(24, displayed: "25 m")
assertDistance(89, displayed: "100 m")
assertDistance(226, displayed: "250 m")
assertDistance(275, displayed: "300 m")
assertDistance(500, displayed: "500 m")
assertDistance(949, displayed: "950 m")
assertDistance(951, displayed: "950 m")
assertDistance(1000, displayed: "1 km")
assertDistance(1001, displayed: "1 km")
assertDistance(2_500, displayed: "2.5 km")
assertDistance(2_900, displayed: "2.9 km")
assertDistance(3_000, displayed: "3 km")
assertDistance(3_500, displayed: "4 km")
}
func testDistanceFormatters_GB() {
distanceFormatter.numberFormatter.locale = Locale(identifier: "en-GB")
assertDistance(0, displayed: "0 ft")
assertDistance(oneMile/2, displayed: "0.5 mi")
assertDistance(oneMile, displayed: "1 mi")
assertDistance(oneMile*2.5, displayed: "2.5 mi")
assertDistance(oneMile*3, displayed: "3 mi")
assertDistance(oneMile*3.5, displayed: "4 mi")
}
}
| 42.851351 | 121 | 0.615579 |
8782806d9370ceaefec41d8bde8abaab91561101 | 730 | //
// Date+String.swift
// MotelPos
//
// Created by Amir Kamali on 6/6/18.
// Copyright © 2018 mx51. All rights reserved.
//
import Foundation
extension Date {
func toString(includeTime: Bool = false) -> String {
var format = ""
if (includeTime) {
format = "dd/MM/yyyy hh:mm a"
} else {
format = "dd/MM/yyyy"
}
return toString(format: format)
}
func toString(format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
extension Bool {
func toString() -> String {
return self ? "true" : "false"
}
}
| 19.210526 | 56 | 0.554795 |
23d01cf01c450512bf3e8024889360aafd7fc837 | 3,381 | import Foundation
public extension KeyedDecodingContainerProtocol {
/// Returns a Boolean value indicating whether the decoder contains a value
/// associated with the any of the given keys.
///
/// The values associated with the given keys may be a null value as
/// appropriate for the data format.
///
/// The keys are queried in the order given, with the first matching
/// key/value being returned.
///
/// - parameter keys: The keys to search for.
/// - returns: Whether the `Decoder` has an entry for any of the keys.
func contains(_ keys: [Key]) -> Bool {
for key in keys {
if contains(key) {
return true
}
}
return false
}
/// Decodes a value of the given type for any of the given keys.
///
/// This method will attempt to decode data in the order the keys are given.
/// The first matching key to have valid data will be returned.
///
/// - parameter type: Tye type of value to decode
/// - parameter keys: the keys that the given value may be associate with.
/// - returns: A value of the request type, if present for the first valid key.
/// - throws: `DecodingError.dataCorrupted` if no keys are specified.
/// - throws: `DecodingError.typeMismatch` if an encountered encoded value for
/// one of the keys is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for all
/// of the given keys.
func decode<T>(_ type: T.Type, forKeys keys: [Key]) throws -> T where T: Decodable {
guard keys.count > 0 else {
let context = DecodingError.Context(codingPath: [], debugDescription: "No Keys Specified")
throw DecodingError.dataCorrupted(context)
}
for key in keys {
if let value = try decodeIfPresent(type, forKey: key) {
return value
}
}
let context = DecodingError.Context(codingPath: keys, debugDescription: "Value Not Found")
throw DecodingError.valueNotFound(type, context)
}
/// Decodes a value of the given type for any of the given keys, if present.
///
/// This method will attempt to decode data in the order the keys are given.
/// The first matching key to have valid data will be returned. If no values
/// are found, than `nil` will be returned.
///
/// - parameter type: Tye type of value to decode
/// - parameter keys: the keys that the given value may be associate with.
/// - returns: A value of the request type, if present for the first valid key.
/// - throws: `DecodingError.dataCorrupted` if no keys are specified.
/// - throws: `DecodingError.typeMismatch` if an encountered encoded value for
/// one of the keys is not convertible to the requested type.
func decodeIfPresent<T: Decodable>(_ type: T.Type, forKeys keys: [Key]) throws -> T? {
guard keys.count > 0 else {
let context = DecodingError.Context(codingPath: [], debugDescription: "No Keys Specified")
throw DecodingError.dataCorrupted(context)
}
for key in keys {
if let value = try self.decodeIfPresent(type, forKey: key) {
return value
}
}
return nil
}
}
| 41.740741 | 102 | 0.628217 |
22b9433c5a632599309ea6683bd48badb7994425 | 813 | //
// KKXMobile.swift
// Demo
//
// Created by ming on 2021/9/8.
//
import UIKit
public struct KKX {
}
internal class _KKXMobile_ {
static let shared = _KKXMobile_()
internal var languageBundle: Bundle? {
if _languageBundle == nil {
var language = defaultConfiguration.languageCode
if language == nil {
language = Locale.preferredLanguages.first
}
if language?.contains("zh-Hans") == true {
language = "zh-Hans"
} else {
language = "en"
}
_languageBundle = Bundle(path: Bundle.kkxMobileBundle.path(forResource: language, ofType: "lproj")!)
}
return _languageBundle
}
internal var _languageBundle: Bundle?
}
| 22.583333 | 112 | 0.551046 |
6ac4de57ca27590067535daee43f82f1f080830d | 925 | //
// MHPhoneModel.swift
// MegaHack2018
//
// Created by Vlad Bonta on 10/11/2018.
// Copyright © 2018 Vlad Bonta. All rights reserved.
//
import Foundation
class MHPhoneModel: NSObject {
var name: String = ""
var phoneDescription: String = ""
var capacity: MHCapacityModel = MHCapacityModel()
var display: MHDisplayModel = MHDisplayModel()
var size: MHSizeModel = MHSizeModel()
var frontCamera: MHFrontCameraModel = MHFrontCameraModel()
var backCamera: MHBackCameraModel = MHBackCameraModel()
var connections: MHConnectionsModel = MHConnectionsModel()
var chip: MHChipModel = MHChipModel()
var authentications: MHAuthenticationModel = MHAuthenticationModel()
var battery: MHBatteryModel = MHBatteryModel()
var sensors: MHSensorsModel = MHSensorsModel()
var simCard: MHSimCardModel = MHSimCardModel()
var connectors: MHConnectorModel = MHConnectorModel()
}
| 33.035714 | 72 | 0.732973 |
1ed08d8b19e61b90e7686b7eca9fadd51f7d06ac | 998 | //
// FirebaseJokesTests.swift
// FirebaseJokesTests
//
// Created by Matthew Maher on 1/23/16.
// Copyright © 2016 Matt Maher. All rights reserved.
//
import XCTest
@testable import FirebaseJokes
class FirebaseJokesTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 26.972973 | 111 | 0.642285 |
d928b26d27cb1a453e85e4ebacd907d6f754536d | 7,295 | //
// UIImageView+SBUIKit.swift
// SendBirdUIKit
//
// Created by Harry Kim on 2020/02/25.
// Copyright © 2020 Sendbird, Inc. All rights reserved.
//
import UIKit
import AVFoundation
public extension UIImageView {
enum ImageOption {
case imageToThumbnail
case original
case videoUrlToImage
}
@discardableResult
func loadImage(urlString: String,
placeholder: UIImage? = nil,
errorImage: UIImage? = nil,
option: ImageOption = .original,
thumbnailSize: CGSize? = nil,
completion: ((Bool) -> Void)? = nil) -> URLSessionTask? {
self.setImage(placeholder)
if urlString.isEmpty {
if let errorImage = errorImage {
self.image = errorImage
}
return nil
}
switch option {
case .original:
return self.loadOriginalImage(
urlString: urlString,
errorImage: errorImage,
completion: completion
)
case .imageToThumbnail:
return self.loadThumbnailImage(
urlString: urlString,
errorImage: errorImage,
thumbnailSize: thumbnailSize,
completion: completion
)
case .videoUrlToImage:
return self.loadVideoThumbnailImage(
urlString: urlString,
errorImage: errorImage,
completion: completion
)
}
}
}
internal extension UIImageView {
// When failed, return error, like failure?(error)
static let error = NSError(
domain: SBUConstant.bundleIdentifier,
code: -1,
userInfo: nil
)
func loadOriginalImage(urlString: String,
errorImage: UIImage? = nil,
completion: ((Bool) -> Void)? = nil) -> URLSessionTask? {
let fileName = SBUCacheManager.createHashName(urlString: urlString)
if let image = SBUCacheManager.getImage(fileName: fileName) {
self.setImage(image, completion: completion)
return nil
}
guard let url = URL(string: urlString), url.absoluteURL.host != nil else {
self.setImage(errorImage) { _ in
completion?(false)
}
return nil
}
let task = URLSession(configuration: .default).dataTask(with: url) { [weak self] data, response, error in
guard let self = self else {
completion?(false)
return
}
guard let data = data, error == nil else {
self.setImage(errorImage) { _ in
completion?(false)
}
return
}
let image = SBUCacheManager.savedImage(fileName: fileName, data: data)
self.setImage(image, completion: completion)
}
task.resume()
return task
}
func loadVideoThumbnailImage(urlString: String,
errorImage: UIImage? = nil,
completion: ((Bool) -> Void)? = nil) -> URLSessionTask? {
let fileName = SBUCacheManager.createHashName(urlString: urlString)
if let image = SBUCacheManager.getImage(fileName: fileName) {
self.setImage(image, completion: completion)
return nil
}
guard let url = URL(string: urlString) else {
self.setImage(errorImage) { _ in
completion?(false)
}
return nil
}
let task = URLSession(configuration: .default).dataTask(with: url) { [weak self] data, response, error in
guard let self = self, let asset = data?.getAVAsset() else {
completion?(false)
return
}
let avAssetImageGenerator = AVAssetImageGenerator(asset: asset)
avAssetImageGenerator.appliesPreferredTrackTransform = true
let cmTime = CMTimeMake(value: 2, timescale: 1)
guard let cgImage = try? avAssetImageGenerator
.copyCGImage(at: cmTime, actualTime: nil) else {
completion?(false)
return
}
let image = UIImage(cgImage: cgImage)
if let data = image.pngData() {
SBUCacheManager.savedImage(fileName: fileName, data: data)
}
self.setImage(image, completion: completion)
}
task.resume()
return task
}
func loadThumbnailImage(urlString: String,
errorImage: UIImage? = nil,
thumbnailSize: CGSize? = SBUConstant.thumbnailSize,
completion: ((Bool) -> Void)? = nil) -> URLSessionTask? {
let fileName = SBUCacheManager.createHashName(urlString: urlString)
let thumbnailFileName = "thumb_" + fileName
// Load thumbnail cacheImage
if let thumbnailImage = SBUCacheManager.getImage(fileName: thumbnailFileName) {
let image = thumbnailImage.isAnimatedImage() ? thumbnailImage.images?.first : thumbnailImage
self.setImage(image, completion: completion)
return nil
}
// Load or Download image
guard let url = URL(string: urlString) else {
self.setImage(errorImage) { _ in
completion?(false)
}
return nil
}
let task = URLSession(configuration: .default).dataTask(with: url) { [weak self] data, response, error in
guard let self = self else { return }
guard let data = data, error == nil, let image = UIImage.createImage(from: data) else {
self.setImage(errorImage) { _ in completion?(false) }
return
}
if image.isAnimatedImage() {
SBUCacheManager.savedImage(fileName: fileName, data: data)
SBUCacheManager.savedImage(fileName: thumbnailFileName, data: data)
self.setImage(image.images?.first ?? image, completion: completion)
} else {
let thumbnailSize: CGSize = thumbnailSize ?? SBUConstant.thumbnailSize
let thumbnailImage = image.resize(with: thumbnailSize)
SBUCacheManager.savedImage(fileName: fileName, image: image)
SBUCacheManager.savedImage(fileName: thumbnailFileName, image: thumbnailImage)
self.setImage(thumbnailImage, completion: completion)
}
}
task.resume()
return task
}
private func setImage(_ image: UIImage?, completion: ((Bool) -> Void)? = nil) {
if let image = image {
if Thread.isMainThread {
self.image = image
} else {
DispatchQueue.main.async {
self.image = image
}
}
}
completion?(image != nil)
}
}
| 35.072115 | 113 | 0.532968 |
2132fe3a2347b6f0ffd315affab8ad96b46cd05b | 741 | import UIKit
import ResultSugar
/**
* Callback signatures
*/
extension CamView {
/**
* Default callback for photo capture
*/
public static let defaultPhotoCaptureCompleted: PhotoCaptureCompleted = {
let imageAndURL: (image: UIImage, url: URL)? = $0.value()
Swift.print("CamView.defaultPhotoCaptureComplete image: \(String(describing: imageAndURL?.image)) path:\(String(describing: imageAndURL?.url)) error: \($0.errorStr)")
}
/**
* Default callback for video capture
*/
public static let defaultVideoCaptureCompleted: VideoCaptureCompleted = {
let url: URL? = $0.value()
Swift.print("CamView.defaultVideoCaptureComplete path:\(String(describing: url)) error: \($0.errorStr)")
}
}
| 33.681818 | 173 | 0.692308 |
09446b3e84dca5b2d733a63fc1acd97abb040116 | 17,451 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Crypto
import NIO
@testable import NIOSSH
import XCTest
final class ExplodingAuthDelegate: NIOSSHClientUserAuthenticationDelegate {
enum Error: Swift.Error {
case kaboom
}
func nextAuthenticationType(availableMethods: NIOSSHAvailableUserAuthenticationMethods, nextChallengePromise: EventLoopPromise<NIOSSHUserAuthenticationOffer?>) {
XCTFail("Next Authentication Type must not be called")
nextChallengePromise.fail(Error.kaboom)
}
}
final class SSHConnectionStateMachineTests: XCTestCase {
private func assertSuccessfulConnection(client: inout SSHConnectionStateMachine, server: inout SSHConnectionStateMachine, allocator: ByteBufferAllocator, loop: EmbeddedEventLoop) throws {
var clientMessage: SSHMultiMessage? = client.start()
var serverMessage: SSHMultiMessage? = server.start()
var clientBuffer = allocator.buffer(capacity: 1024)
var serverBuffer = allocator.buffer(capacity: 1024)
var waitingForClientMessage = false
var waitingForServerMessage = false
while clientMessage != nil || serverMessage != nil {
if let clientMessage = clientMessage {
for message in clientMessage {
XCTAssertNoThrow(try client.processOutboundMessage(message, buffer: &clientBuffer, allocator: allocator, loop: loop))
}
}
if let serverMessage = serverMessage {
for message in serverMessage {
XCTAssertNoThrow(try server.processOutboundMessage(message, buffer: &serverBuffer, allocator: allocator, loop: loop))
}
}
if clientBuffer.readableBytes > 0 {
server.bufferInboundData(&clientBuffer)
clientBuffer.clear()
}
if serverBuffer.readableBytes > 0 {
client.bufferInboundData(&serverBuffer)
serverBuffer.clear()
}
switch try assertNoThrowWithValue(client.processInboundMessage(allocator: allocator, loop: loop)) {
case .some(.emitMessage(let message)):
clientMessage = message
case .some(.noMessage), .none:
clientMessage = nil
case .some(.possibleFutureMessage(let futureMessage)):
waitingForClientMessage = true
clientMessage = nil
futureMessage.whenComplete { result in
waitingForClientMessage = false
switch result {
case .failure(let err):
XCTFail("Unexpected error in delayed message production: \(err)")
case .success(let message):
if clientMessage != nil {
XCTFail("Produced extra client message!")
} else {
clientMessage = message
}
}
}
case .some(.forwardToMultiplexer), .some(.globalRequest), .some(.globalRequestResponse), .some(.disconnect):
fatalError("Currently unsupported")
}
switch try assertNoThrowWithValue(server.processInboundMessage(allocator: allocator, loop: loop)) {
case .some(.emitMessage(let message)):
serverMessage = message
case .some(.noMessage), .none:
serverMessage = nil
case .some(.possibleFutureMessage(let futureMessage)):
waitingForServerMessage = true
serverMessage = nil
futureMessage.whenComplete { result in
waitingForServerMessage = false
switch result {
case .failure(let err):
XCTFail("Unexpected error in delayed message production: \(err)")
case .success(let message):
if serverMessage != nil {
XCTFail("Produced extra server message!")
} else {
serverMessage = message
}
}
}
case .some(.forwardToMultiplexer), .some(.globalRequest), .some(.globalRequestResponse), .some(.disconnect):
fatalError("Currently unsupported")
}
// Bottom of the loop, run the event loop to fire any futures we might need.
loop.run()
}
XCTAssertFalse(waitingForClientMessage, "Loop exited while waiting for a client message")
XCTAssertFalse(waitingForServerMessage, "Loop exited while waiting for a server message")
}
private func assertForwardsToMultiplexer(_ message: SSHMessage, sender: inout SSHConnectionStateMachine, receiver: inout SSHConnectionStateMachine, allocator: ByteBufferAllocator, loop: EmbeddedEventLoop) throws {
var tempBuffer = allocator.buffer(capacity: 1024)
XCTAssertNoThrow(try sender.processOutboundMessage(message, buffer: &tempBuffer, allocator: allocator, loop: loop))
XCTAssert(tempBuffer.readableBytes > 0)
receiver.bufferInboundData(&tempBuffer)
let result = try assertNoThrowWithValue(receiver.processInboundMessage(allocator: allocator, loop: loop))
switch result {
case .some(.forwardToMultiplexer(let forwardedMessage)):
XCTAssertEqual(forwardedMessage, message)
case .some(.emitMessage), .some(.possibleFutureMessage), .some(.noMessage), .some(.globalRequest), .some(.globalRequestResponse), .some(.disconnect), .none:
XCTFail("Unexpected result: \(String(describing: result))")
}
}
private func assertSendingIsProtocolError(_ message: SSHMessage, sender: inout SSHConnectionStateMachine, allocator: ByteBufferAllocator, loop: EmbeddedEventLoop) throws {
var tempBuffer = allocator.buffer(capacity: 1024)
XCTAssertThrowsError(try sender.processOutboundMessage(message, buffer: &tempBuffer, allocator: allocator, loop: loop)) { error in
XCTAssertEqual((error as? NIOSSHError)?.type, .protocolViolation)
}
XCTAssertEqual(tempBuffer.readableBytes, 0)
}
private func assertDisconnects(_ message: SSHMessage, sender: inout SSHConnectionStateMachine, receiver: inout SSHConnectionStateMachine, allocator: ByteBufferAllocator, loop: EmbeddedEventLoop) throws {
var tempBuffer = allocator.buffer(capacity: 1024)
XCTAssertNoThrow(try sender.processOutboundMessage(message, buffer: &tempBuffer, allocator: allocator, loop: loop))
XCTAssert(tempBuffer.readableBytes > 0)
receiver.bufferInboundData(&tempBuffer)
let result = try assertNoThrowWithValue(receiver.processInboundMessage(allocator: allocator, loop: loop))
switch result {
case .some(.disconnect):
// Good
break
case .some(.forwardToMultiplexer), .some(.emitMessage), .some(.possibleFutureMessage), .some(.noMessage), .some(.globalRequest), .some(.globalRequestResponse), .none:
XCTFail("Unexpected result: \(String(describing: result))")
}
}
private func assertTriggersGlobalRequest(_ message: SSHMessage, sender: inout SSHConnectionStateMachine, receiver: inout SSHConnectionStateMachine, allocator: ByteBufferAllocator, loop: EmbeddedEventLoop) throws {
var tempBuffer = allocator.buffer(capacity: 1024)
XCTAssertNoThrow(try sender.processOutboundMessage(message, buffer: &tempBuffer, allocator: allocator, loop: loop))
XCTAssert(tempBuffer.readableBytes > 0)
receiver.bufferInboundData(&tempBuffer)
let result = try assertNoThrowWithValue(receiver.processInboundMessage(allocator: allocator, loop: loop))
switch result {
case .some(.globalRequest(let receivedMessage)):
// Good
XCTAssertEqual(.globalRequest(receivedMessage), message)
case .some(.forwardToMultiplexer), .some(.emitMessage), .some(.possibleFutureMessage), .some(.noMessage), .some(.globalRequestResponse), .some(.disconnect), .none:
XCTFail("Unexpected result: \(String(describing: result))")
}
}
private func assertTriggersGlobalRequestResponse(_ message: SSHMessage, sender: inout SSHConnectionStateMachine, receiver: inout SSHConnectionStateMachine, allocator: ByteBufferAllocator, loop: EmbeddedEventLoop) throws -> SSHConnectionStateMachine.StateMachineInboundProcessResult.GlobalRequestResponse? {
var tempBuffer = allocator.buffer(capacity: 1024)
XCTAssertNoThrow(try sender.processOutboundMessage(message, buffer: &tempBuffer, allocator: allocator, loop: loop))
XCTAssert(tempBuffer.readableBytes > 0)
receiver.bufferInboundData(&tempBuffer)
let result = try assertNoThrowWithValue(receiver.processInboundMessage(allocator: allocator, loop: loop))
switch result {
case .some(.globalRequestResponse(let response)):
// Good
return response
case .some(.forwardToMultiplexer), .some(.emitMessage), .some(.possibleFutureMessage), .some(.noMessage), .some(.globalRequest), .some(.disconnect), .none:
XCTFail("Unexpected result: \(String(describing: result))")
return nil
}
}
func testBasicConnectionDance() throws {
let allocator = ByteBufferAllocator()
let loop = EmbeddedEventLoop()
var client = SSHConnectionStateMachine(role: .client(.init(userAuthDelegate: InfinitePasswordDelegate())))
var server = SSHConnectionStateMachine(role: .server(.init(hostKeys: [NIOSSHPrivateKey(ed25519Key: .init())], userAuthDelegate: DenyThenAcceptDelegate(messagesToDeny: 1))))
try assertSuccessfulConnection(client: &client, server: &server, allocator: allocator, loop: loop)
XCTAssertTrue(client.isActive)
XCTAssertTrue(server.isActive)
}
// Messages that are usable once child channels are allowed.
let channelMessages: [SSHMessage] = [
.channelOpen(.init(type: .session, senderChannel: 0, initialWindowSize: 0, maximumPacketSize: 12)),
.channelOpenConfirmation(.init(recipientChannel: 0, senderChannel: 0, initialWindowSize: 0, maximumPacketSize: 12)),
.channelOpenFailure(.init(recipientChannel: 0, reasonCode: 0, description: "foo", language: "bar")),
.channelEOF(.init(recipientChannel: 0)),
.channelClose(.init(recipientChannel: 0)),
.channelWindowAdjust(.init(recipientChannel: 0, bytesToAdd: 1)),
.channelData(.init(recipientChannel: 0, data: ByteBufferAllocator().buffer(capacity: 0))),
.channelExtendedData(.init(recipientChannel: 0, dataTypeCode: .stderr, data: ByteBufferAllocator().buffer(capacity: 0))),
.channelRequest(.init(recipientChannel: 0, type: .exec("uname"), wantReply: false)),
.channelSuccess(.init(recipientChannel: 0)),
.channelFailure(.init(recipientChannel: 0)),
]
func testReceivingChannelMessagesGetForwardedOnceConnectionMade() throws {
let allocator = ByteBufferAllocator()
let loop = EmbeddedEventLoop()
var client = SSHConnectionStateMachine(role: .client(.init(userAuthDelegate: InfinitePasswordDelegate())))
var server = SSHConnectionStateMachine(role: .server(.init(hostKeys: [NIOSSHPrivateKey(ed25519Key: .init())], userAuthDelegate: DenyThenAcceptDelegate(messagesToDeny: 1))))
try assertSuccessfulConnection(client: &client, server: &server, allocator: allocator, loop: loop)
for message in self.channelMessages {
XCTAssertNoThrow(try self.assertForwardsToMultiplexer(message, sender: &client, receiver: &server, allocator: allocator, loop: loop))
}
}
func testDisconnectMessageCausesImmediateConnectionClose() throws {
let allocator = ByteBufferAllocator()
let loop = EmbeddedEventLoop()
var client = SSHConnectionStateMachine(role: .client(.init(userAuthDelegate: InfinitePasswordDelegate())))
var server = SSHConnectionStateMachine(role: .server(.init(hostKeys: [NIOSSHPrivateKey(ed25519Key: .init())], userAuthDelegate: DenyThenAcceptDelegate(messagesToDeny: 1))))
try assertSuccessfulConnection(client: &client, server: &server, allocator: allocator, loop: loop)
XCTAssertFalse(client.disconnected)
XCTAssertFalse(server.disconnected)
// Have the client send and the server receive a disconnection message.
try self.assertDisconnects(.disconnect(.init(reason: 0, description: "", tag: "")), sender: &client, receiver: &server, allocator: allocator, loop: loop)
XCTAssertTrue(client.disconnected)
XCTAssertTrue(server.disconnected)
// Further messages are not sent.
for message in self.channelMessages {
XCTAssertNoThrow(try self.assertSendingIsProtocolError(message, sender: &client, allocator: allocator, loop: loop))
}
}
func testDisconnectedReturnsNil() throws {
let allocator = ByteBufferAllocator()
let loop = EmbeddedEventLoop()
var client = SSHConnectionStateMachine(role: .client(.init(userAuthDelegate: InfinitePasswordDelegate())))
var server = SSHConnectionStateMachine(role: .server(.init(hostKeys: [NIOSSHPrivateKey(ed25519Key: .init())], userAuthDelegate: DenyThenAcceptDelegate(messagesToDeny: 1))))
try assertSuccessfulConnection(client: &client, server: &server, allocator: allocator, loop: loop)
try self.assertDisconnects(.disconnect(.init(reason: 0, description: "", tag: "")), sender: &client, receiver: &server, allocator: allocator, loop: loop)
// Ok, in disconnected state. At this time, any attempt to process the connection should return nil.
var junkBuffer = allocator.buffer(capacity: 1024)
junkBuffer.writeBytes(0 ... 255)
server.bufferInboundData(&junkBuffer)
XCTAssertNoThrow(try XCTAssertNil(server.processInboundMessage(allocator: allocator, loop: loop)))
}
func testGlobalRequestCanBeSent() throws {
let allocator = ByteBufferAllocator()
let loop = EmbeddedEventLoop()
var client = SSHConnectionStateMachine(role: .client(.init(userAuthDelegate: InfinitePasswordDelegate())))
var server = SSHConnectionStateMachine(role: .server(.init(hostKeys: [NIOSSHPrivateKey(ed25519Key: .init())], userAuthDelegate: DenyThenAcceptDelegate(messagesToDeny: 1))))
try assertSuccessfulConnection(client: &client, server: &server, allocator: allocator, loop: loop)
var message = SSHMessage.GlobalRequestMessage(wantReply: true, type: .tcpipForward("foo", 66))
try self.assertTriggersGlobalRequest(.globalRequest(message), sender: &client, receiver: &server, allocator: allocator, loop: loop)
message = SSHMessage.GlobalRequestMessage(wantReply: false, type: .cancelTcpipForward("foo", 66))
try self.assertTriggersGlobalRequest(.globalRequest(message), sender: &client, receiver: &server, allocator: allocator, loop: loop)
}
func testGlobalRequestResponsesTriggerResponse() throws {
let allocator = ByteBufferAllocator()
let loop = EmbeddedEventLoop()
var client = SSHConnectionStateMachine(role: .client(.init(userAuthDelegate: InfinitePasswordDelegate())))
var server = SSHConnectionStateMachine(role: .server(.init(hostKeys: [NIOSSHPrivateKey(ed25519Key: .init())], userAuthDelegate: DenyThenAcceptDelegate(messagesToDeny: 1))))
try assertSuccessfulConnection(client: &client, server: &server, allocator: allocator, loop: loop)
// Deliver a request success message.
var response = try self.assertTriggersGlobalRequestResponse(
.requestSuccess(.init(boundPort: 6)), sender: &server, receiver: &client, allocator: allocator, loop: loop
)
guard case .some(.success(let firstResponse)) = response, firstResponse.boundPort == 6 else {
XCTFail("Unexpected response: \(String(describing: response))")
return
}
// Now without a port.
response = try self.assertTriggersGlobalRequestResponse(
.requestSuccess(.init(boundPort: nil)), sender: &server, receiver: &client, allocator: allocator, loop: loop
)
guard case .some(.success(let secondResponse)) = response, secondResponse.boundPort == nil else {
XCTFail("Unexpected response: \(String(describing: response))")
return
}
// Now a failure.
response = try self.assertTriggersGlobalRequestResponse(
.requestFailure, sender: &server, receiver: &client, allocator: allocator, loop: loop
)
guard case .some(.failure) = response else {
XCTFail("Unexpected response: \(String(describing: response))")
return
}
}
}
| 52.722054 | 310 | 0.670506 |
de298d3f66cf0b7b4a8ad31851ef26f66bfdec93 | 17,090 | import CoreLocation
import UIKit
import MapboxDirections
import MapboxCoreNavigation
import Turf
import MapboxMaps
extension NavigationMapView {
struct RoutePoints {
var nestedList: [[[CLLocationCoordinate2D]]]
var flatList: [CLLocationCoordinate2D]
}
struct RouteLineGranularDistances {
var distance: Double
var distanceArray: [RouteLineDistancesIndex]
}
struct RouteLineDistancesIndex {
var point: CLLocationCoordinate2D
var distanceRemaining: Double
}
// MARK: - Vanishing route line methods
func initPrimaryRoutePoints(route: Route) {
routePoints = parseRoutePoints(route: route)
routeLineGranularDistances = calculateGranularDistances(routePoints?.flatList ?? [])
}
/**
Tranform the route data into nested arrays of legs -> steps -> coordinates.
The first and last point of adjacent steps overlap and are duplicated.
*/
func parseRoutePoints(route: Route) -> RoutePoints {
let nestedList = route.legs.map { (routeLeg: RouteLeg) -> [[CLLocationCoordinate2D]] in
return routeLeg.steps.map { (routeStep: RouteStep) -> [CLLocationCoordinate2D] in
if let routeShape = routeStep.shape {
if !routeShape.coordinates.isEmpty {
return routeShape.coordinates
} else { return [] }
} else {
return []
}
}
}
let flatList = nestedList.flatMap { $0.flatMap { $0.compactMap { $0 } } }
return RoutePoints(nestedList: nestedList, flatList: flatList)
}
/**
Find and cache the index of the upcoming [RouteLineDistancesIndex].
*/
public func updateUpcomingRoutePointIndex(routeProgress: RouteProgress) {
guard let completeRoutePoints = routePoints else {
routeRemainingDistancesIndex = nil
return
}
let currentLegProgress = routeProgress.currentLegProgress
let currentStepProgress = routeProgress.currentLegProgress.currentStepProgress
/**
Find the count of remaining points in the current step.
*/
var allRemainingPoints = getSlicedLinePointsCount(currentLegProgress: currentLegProgress, currentStepProgress: currentStepProgress)
/**
Add to the count of remaining points all of the remaining points on the current leg, after the current step.
*/
let currentLegSteps = completeRoutePoints.nestedList[routeProgress.legIndex]
let startIndex = currentLegProgress.stepIndex + 1
let endIndex = currentLegSteps.count - 1
if startIndex < endIndex {
allRemainingPoints += currentLegSteps.prefix(endIndex).suffix(from: startIndex).flatMap{ $0.compactMap{ $0 } }.count
}
/**
Add to the count of remaining points all of the remaining legs.
*/
for index in stride(from: routeProgress.legIndex + 1, to: completeRoutePoints.nestedList.count, by: 1) {
allRemainingPoints += completeRoutePoints.nestedList[index].flatMap{ $0 }.count
}
/**
After calculating the number of remaining points and the number of all points, calculate the index of the upcoming point.
*/
let allPoints = completeRoutePoints.flatList.count
routeRemainingDistancesIndex = allPoints - allRemainingPoints - 1
}
func getSlicedLinePointsCount(currentLegProgress: RouteLegProgress, currentStepProgress: RouteStepProgress) -> Int {
let startDistance = currentStepProgress.distanceTraveled
let stopDistance = currentStepProgress.step.distance
/**
Implement the Turf.lineSliceAlong(lineString, startDistance, stopDistance) to return a sliced lineString.
*/
if let lineString = currentStepProgress.step.shape,
let midPoint = lineString.coordinateFromStart(distance: startDistance),
let slicedLine = lineString.trimmed(from: midPoint, distance: stopDistance - startDistance) {
return slicedLine.coordinates.count - 1
}
return 0
}
func calculateGranularDistances(_ coordinates: [CLLocationCoordinate2D]) -> RouteLineGranularDistances? {
if coordinates.isEmpty { return nil }
var distance = 0.0
var indexArray = [RouteLineDistancesIndex?](repeating: nil, count: coordinates.count)
for index in stride(from: coordinates.count - 1, to: 0, by: -1) {
let curr = coordinates[index]
let prev = coordinates[index - 1]
distance += curr.projectedDistance(to: prev)
indexArray[index - 1] = RouteLineDistancesIndex(point: prev, distanceRemaining: distance)
}
indexArray[coordinates.count - 1] = RouteLineDistancesIndex(point: coordinates[coordinates.count - 1], distanceRemaining: 0.0)
return RouteLineGranularDistances(distance: distance, distanceArray: indexArray.compactMap{ $0 })
}
/**
Updates the fractionTraveled along the route line from the origin point to the indicated point.
- parameter coordinate: Current position of the user location.
*/
func updateFractionTraveled(coordinate: CLLocationCoordinate2D) {
guard let granularDistances = routeLineGranularDistances,let index = routeRemainingDistancesIndex else { return }
guard index < granularDistances.distanceArray.endIndex else { return }
let traveledIndex = granularDistances.distanceArray[index]
let upcomingPoint = traveledIndex.point
/**
Take the remaining distance from the upcoming point on the route and extends it by the exact position of the puck.
*/
let remainingDistance = traveledIndex.distanceRemaining + upcomingPoint.projectedDistance(to: coordinate)
/**
Calculate the percentage of the route traveled.
*/
if granularDistances.distance >= remainingDistance {
let offSet = (1.0 - remainingDistance / granularDistances.distance)
if offSet >= 0 {
fractionTraveled = offSet
}
}
}
/**
Updates the route style layer and its casing style layer to gradually disappear as the user location puck travels along the displayed route.
- parameter coordinate: Current position of the user location.
*/
public func travelAlongRouteLine(to coordinate: CLLocationCoordinate2D?) {
guard let route = routes?.first else { return }
guard pendingCoordinateForRouteLine != coordinate,
let preCoordinate = pendingCoordinateForRouteLine,
let currentCoordinate = coordinate else { return }
let distance = preCoordinate.distance(to: currentCoordinate)
let meterPerPixel = getMetersPerPixelAtLatitude(currentCoordinate.latitude, Double(mapView.cameraState.zoom))
guard distance >= meterPerPixel else { return }
updateFractionTraveled(coordinate: currentCoordinate)
let mainRouteLayerIdentifier = route.identifier(.route(isMainRoute: true))
let mainRouteCasingLayerIdentifier = route.identifier(.routeCasing(isMainRoute: true))
if fractionTraveled >= 1.0 {
// In case if route was fully travelled - remove main route and its casing.
do {
try mapView.mapboxMap.style.removeLayer(withId: mainRouteLayerIdentifier)
try mapView.mapboxMap.style.removeLayer(withId: mainRouteCasingLayerIdentifier)
} catch {
print("Failed to remove main route line layer.")
}
fractionTraveled = 0.0
return
}
let mainRouteLayerGradient = updateRouteLineGradientStops(fractionTraveled: fractionTraveled, gradientStops: currentLineGradientStops)
let mainRouteLayerGradientExpression = Expression.routeLineGradientExpression(mainRouteLayerGradient, lineBaseColor: trafficUnknownColor)
setLayerLineGradient(for: mainRouteLayerIdentifier, exp: mainRouteLayerGradientExpression)
let mainRouteCasingLayerGradient = routeLineGradient(fractionTraveled: fractionTraveled)
let mainRouteCasingLayerGradientExpression = Expression.routeLineGradientExpression(mainRouteCasingLayerGradient, lineBaseColor: routeCasingColor)
setLayerLineGradient(for: mainRouteCasingLayerIdentifier, exp: mainRouteCasingLayerGradientExpression)
pendingCoordinateForRouteLine = coordinate
}
func setLayerLineGradient(for layerId: String, exp: Expression) {
if let data = try? JSONEncoder().encode(exp.self),
let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) {
do {
try mapView.mapboxMap.style.setLayerProperty(for: layerId,
property: "line-gradient",
value: jsonObject)
} catch {
print("Failed to update route line gradient.")
}
}
}
func updateRouteLineGradientStops(fractionTraveled: Double, gradientStops: [Double: UIColor]) -> [Double: UIColor] {
var filteredGradientStops = gradientStops.filter { key, value in
return key >= fractionTraveled
}
filteredGradientStops[0.0] = traversedRouteColor
let nextDownFractionTraveled = Double(CGFloat(fractionTraveled).nextDown)
if nextDownFractionTraveled >= 0.0 {
filteredGradientStops[nextDownFractionTraveled] = traversedRouteColor
}
// Find the nearest smaller stop than the `fractionTraveled` and apply its color to the `fractionTraveled` till the next stop.
let sortedStops = gradientStops.keys.sorted()
if let minStop = sortedStops.last(where: { $0 <= fractionTraveled }),
minStop != 0.0 {
filteredGradientStops[fractionTraveled] = gradientStops[minStop]
} else {
filteredGradientStops[fractionTraveled] = trafficUnknownColor
}
return filteredGradientStops
}
func routeLineGradient(_ congestionFeatures: [Turf.Feature]? = nil, fractionTraveled: Double, isMain: Bool = true) -> [Double: UIColor] {
var gradientStops = [Double: UIColor]()
var distanceTraveled = fractionTraveled
if let congestionFeatures = congestionFeatures {
let routeDistance = congestionFeatures.compactMap({ ($0.geometry.value as? LineString)?.distance() }).reduce(0, +)
var minimumSegment: (Double, UIColor) = (Double.greatestFiniteMagnitude, .clear)
for (index, feature) in congestionFeatures.enumerated() {
var associatedFeatureColor = routeCasingColor
let congestionLevel = feature.properties?[CongestionAttribute] as? String
if let isCurrentLeg = feature.properties?[CurrentLegAttribute] as? Bool, isCurrentLeg {
associatedFeatureColor = congestionColor(for: congestionLevel, isMain: isMain)
}
let lineString = feature.geometry.value as? LineString
guard let distance = lineString?.distance() else { return gradientStops }
if index == congestionFeatures.startIndex {
distanceTraveled = distanceTraveled + distance
let segmentEndPercentTraveled = CGFloat(distanceTraveled / routeDistance)
let currentGradientStop = Double(segmentEndPercentTraveled.nextDown)
if currentGradientStop >= fractionTraveled {
gradientStops[currentGradientStop] = associatedFeatureColor
if currentGradientStop < minimumSegment.0 {
minimumSegment = (currentGradientStop, associatedFeatureColor)
}
if index + 1 < congestionFeatures.count {
let currentGradientStop = Double(segmentEndPercentTraveled.nextUp)
let currentColor = congestionColor(for: congestionFeatures[index + 1].properties?["congestion"] as? String, isMain: isMain)
gradientStops[currentGradientStop] = currentColor
if currentGradientStop < minimumSegment.0 {
minimumSegment = (currentGradientStop, currentColor)
}
}
}
continue
}
if index == congestionFeatures.endIndex - 1 {
let lastGradientStop: Double = 1.0
gradientStops[lastGradientStop] = associatedFeatureColor
if lastGradientStop < minimumSegment.0 {
minimumSegment = (lastGradientStop, associatedFeatureColor)
}
continue
}
let segmentStartPercentTraveled = CGFloat(distanceTraveled / routeDistance)
if Double(segmentStartPercentTraveled.nextUp) >= fractionTraveled {
let currentGradientStop = Double(segmentStartPercentTraveled.nextUp)
gradientStops[currentGradientStop] = associatedFeatureColor
if currentGradientStop < minimumSegment.0 {
minimumSegment = (currentGradientStop, associatedFeatureColor)
}
}
distanceTraveled = distanceTraveled + distance
let segmentEndPercentTraveled = CGFloat(distanceTraveled / routeDistance)
if Double(segmentEndPercentTraveled.nextDown) >= fractionTraveled {
let currentGradientStop = Double(segmentEndPercentTraveled.nextDown)
gradientStops[currentGradientStop] = associatedFeatureColor
if currentGradientStop < minimumSegment.0 {
minimumSegment = (currentGradientStop, associatedFeatureColor)
}
}
if index + 1 < congestionFeatures.count && Double(segmentEndPercentTraveled.nextUp) >= fractionTraveled {
let currentGradientStop = Double(segmentEndPercentTraveled.nextUp)
let nextCongestionLevel = congestionFeatures[index + 1].properties?[CongestionAttribute] as? String
var currentColor = routeCasingColor
if let isCurrentLeg = congestionFeatures[index + 1].properties?[CurrentLegAttribute] as? Bool, isCurrentLeg {
currentColor = congestionColor(for: nextCongestionLevel, isMain: isMain)
}
gradientStops[currentGradientStop] = currentColor
if currentGradientStop < minimumSegment.0 {
minimumSegment = (currentGradientStop, currentColor)
}
}
}
gradientStops[0.0] = traversedRouteColor
let currentGradientStop = Double(CGFloat(fractionTraveled).nextDown)
if currentGradientStop >= 0.0 {
gradientStops[currentGradientStop] = traversedRouteColor
}
gradientStops[fractionTraveled] = minimumSegment.1
} else {
let percentTraveled = CGFloat(fractionTraveled)
gradientStops[0.0] = traversedRouteColor
if percentTraveled.nextDown >= 0.0 {
gradientStops[Double(percentTraveled.nextDown)] = traversedRouteColor
}
gradientStops[Double(percentTraveled)] = routeCasingColor
}
return gradientStops
}
/**
Given a congestion level, return its associated color.
*/
func congestionColor(for congestionLevel: String?, isMain: Bool) -> UIColor {
switch congestionLevel {
case "low":
return isMain ? trafficLowColor : alternativeTrafficLowColor
case "moderate":
return isMain ? trafficModerateColor : alternativeTrafficModerateColor
case "heavy":
return isMain ? trafficHeavyColor : alternativeTrafficHeavyColor
case "severe":
return isMain ? trafficSevereColor : alternativeTrafficSevereColor
default:
return isMain ? trafficUnknownColor : alternativeTrafficUnknownColor
}
}
}
| 47.73743 | 154 | 0.62282 |
eb0a58c4f49f2352f4e7754173e57835d4cbbb62 | 2,558 | //
// customOverlayView.swift
// SwiftyOnboard
//
// Created by Jay on 3/26/17.
// Copyright © 2017 Juan Pablo Fernandez. All rights reserved.
//
import UIKit
open class SwiftyOnboardOverlay: UIView {
open var pageControl: CHIPageControlChimayo = {
let pageControl = CHIPageControlChimayo()
pageControl.tintColor = .themeColor
pageControl.padding = 6
pageControl.radius = 4
return pageControl
}()
open var continueButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Continue", for: .normal)
button.contentHorizontalAlignment = .center
return button
}()
open var skipButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Skip", for: .normal)
button.contentHorizontalAlignment = .right
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
for subview in subviews {
if !subview.isHidden && subview.alpha > 0 && subview.isUserInteractionEnabled && subview.point(inside: convert(point, to: subview), with: event) {
return true
}
}
return false
}
open func set(style: SwiftyOnboardStyle) {
switch style {
case .light:
continueButton.setTitleColor(.white, for: .normal)
skipButton.setTitleColor(.white, for: .normal)
case .dark:
continueButton.setTitleColor(.black, for: .normal)
skipButton.setTitleColor(.black, for: .normal)
}
}
open func page(count: Int) {
pageControl.numberOfPages = count
}
open func currentPage(index: Int) {
pageControl.set(progress: index, animated: true)
}
func setUp() {
self.addSubview(pageControl)
pageControl.translatesAutoresizingMaskIntoConstraints = false
pageControl.heightAnchor.constraint(equalToConstant: 15).isActive = true
pageControl.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -170).isActive = true
pageControl.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10).isActive = true
pageControl.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
}
}
| 30.819277 | 158 | 0.626271 |
7142c1ebd302b4a388317163f8912a80bd871620 | 1,183 | //
// OnBoardingScreenUITests.swift
// OnBoardingScreenUITests
//
// Created by Olar's Mac on 3/14/19.
// Copyright © 2019 Adie Olami. All rights reserved.
//
import XCTest
class OnBoardingScreenUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.8 | 182 | 0.694844 |
5dc60b07d74baebf074c6e5141213c9fa0ffdc86 | 728 | //
// CoreGraphics+Z.swift
// ZKit
//
// Created by Kaz Yoshikawa on 12/12/16.
// Copyright © 2016 Electricwoods LLC. All rights reserved.
//
import Foundation
import CoreGraphics
extension CGRect {
func transform(to rect: CGRect) -> CGAffineTransform {
var t = CGAffineTransform.identity
t = t.translatedBy(x: -self.minX, y: -self.minY)
t = t.scaledBy(x: 1 / self.width, y: 1 / self.height)
t = t.scaledBy(x: rect.width, y: rect.height)
t = t.translatedBy(x: rect.minX * self.width / rect.width, y: rect.minY * self.height / rect.height)
return t
}
}
extension CGAffineTransform {
static func * (lhs: CGAffineTransform, rhs: CGAffineTransform) -> CGAffineTransform {
return lhs.concatenating(rhs)
}
}
| 22.060606 | 102 | 0.697802 |
48f53b1c2dd4db6d4a019683f5ee1668884e2cb1 | 32,907 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
extension JSONSerialization {
public struct ReadingOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let mutableContainers = ReadingOptions(rawValue: 1 << 0)
public static let mutableLeaves = ReadingOptions(rawValue: 1 << 1)
public static let allowFragments = ReadingOptions(rawValue: 1 << 2)
}
public struct WritingOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let prettyPrinted = WritingOptions(rawValue: 1 << 0)
}
}
/* A class for converting JSON to Foundation/Swift objects and converting Foundation/Swift objects to JSON.
An object that may be converted to JSON must have the following properties:
- Top level object is a `Swift.Array` or `Swift.Dictionary`
- All objects are `Swift.String`, `Foundation.NSNumber`, `Swift.Array`, `Swift.Dictionary`,
or `Foundation.NSNull`
- All dictionary keys are `Swift.String`s
- `NSNumber`s are not NaN or infinity
*/
open class JSONSerialization : NSObject {
/* Determines whether the given object can be converted to JSON.
Other rules may apply. Calling this method or attempting a conversion are the definitive ways
to tell if a given object can be converted to JSON data.
- parameter obj: The object to test.
- returns: `true` if `obj` can be converted to JSON, otherwise `false`.
*/
open class func isValidJSONObject(_ obj: Any) -> Bool {
// TODO: - revisit this once bridging story gets fully figured out
func isValidJSONObjectInternal(_ obj: Any) -> Bool {
// object is Swift.String or NSNull
if obj is String || obj is NSNull {
return true
}
// object is NSNumber and is not NaN or infinity
if let number = _SwiftValue.store(obj) as? NSNumber {
let invalid = number.doubleValue.isInfinite || number.doubleValue.isNaN
return !invalid
}
// object is Swift.Array
if let array = obj as? [Any] {
for element in array {
guard isValidJSONObjectInternal(element) else {
return false
}
}
return true
}
// object is Swift.Dictionary
if let dictionary = obj as? [String: Any] {
for (_, value) in dictionary {
guard isValidJSONObjectInternal(value) else {
return false
}
}
return true
}
// invalid object
return false
}
// top level object must be an Swift.Array or Swift.Dictionary
guard obj is [Any] || obj is [String: Any] else {
return false
}
return isValidJSONObjectInternal(obj)
}
/* Generate JSON data from a Foundation object. If the object will not produce valid JSON then an exception will be thrown. Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated. If an error occurs, the error parameter will be set and the return value will be nil. The resulting data is a encoded in UTF-8.
*/
internal class func _data(withJSONObject value: Any, options opt: WritingOptions, stream: Bool) throws -> Data {
var result = Data()
var writer = JSONWriter(
pretty: opt.contains(.prettyPrinted),
writer: { (str: String?) in
if let str = str {
let count = str.lengthOfBytes(using: .utf8)
result.append(UnsafeRawPointer(str.cString(using: .utf8)!).bindMemory(to: UInt8.self, capacity: count), count: count)
}
}
)
if let container = value as? NSArray {
try writer.serializeJSON(container._bridgeToSwift())
} else if let container = value as? NSDictionary {
try writer.serializeJSON(container._bridgeToSwift())
} else if let container = value as? Array<Any> {
try writer.serializeJSON(container)
} else if let container = value as? Dictionary<AnyHashable, Any> {
try writer.serializeJSON(container)
} else {
if stream {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Top-level object was not NSArray or NSDictionary"
])
} else {
fatalError("Top-level object was not NSArray or NSDictionary") // This is a fatal error in objective-c too (it is an NSInvalidArgumentException)
}
}
return result
}
open class func data(withJSONObject value: Any, options opt: WritingOptions = []) throws -> Data {
return try _data(withJSONObject: value, options: opt, stream: false)
}
/* Create a Foundation object from JSON data. Set the NSJSONReadingAllowFragments option if the parser should allow top-level objects that are not an NSArray or NSDictionary. Setting the NSJSONReadingMutableContainers option will make the parser generate mutable NSArrays and NSDictionaries. Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects. If an error occurs during the parse, then the error parameter will be set and the result will be nil.
The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.
*/
/// - Experiment: Note that the return type of this function is different than on Darwin Foundation (Any instead of AnyObject). This is likely to change once we have a more complete story for bridging in place.
open class func jsonObject(with data: Data, options opt: ReadingOptions = []) throws -> Any {
return try data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Any in
let encoding: String.Encoding
let buffer: UnsafeBufferPointer<UInt8>
if let detected = parseBOM(bytes, length: data.count) {
encoding = detected.encoding
buffer = UnsafeBufferPointer(start: bytes.advanced(by: detected.skipLength), count: data.count - detected.skipLength)
}
else {
encoding = detectEncoding(bytes, data.count)
buffer = UnsafeBufferPointer(start: bytes, count: data.count)
}
let source = JSONReader.UnicodeSource(buffer: buffer, encoding: encoding)
let reader = JSONReader(source: source)
if let (object, _) = try reader.parseObject(0) {
return object
}
else if let (array, _) = try reader.parseArray(0) {
return array
}
else if opt.contains(.allowFragments), let (value, _) = try reader.parseValue(0) {
return value
}
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "JSON text did not start with array or object and option to allow fragments not set."
])
}
}
/* Write JSON data into a stream. The stream should be opened and configured. The return value is the number of bytes written to the stream, or 0 on error. All other behavior of this method is the same as the dataWithJSONObject:options:error: method.
*/
open class func writeJSONObject(_ obj: Any, toStream stream: OutputStream, options opt: WritingOptions) throws -> Int {
let jsonData = try _data(withJSONObject: obj, options: opt, stream: true)
let count = jsonData.count
return jsonData.withUnsafeBytes { (bytePtr) -> Int in
return stream.write(bytePtr, maxLength: count)
}
}
/* Create a JSON object from JSON data stream. The stream should be opened and configured. All other behavior of this method is the same as the JSONObjectWithData:options:error: method.
*/
open class func jsonObject(with stream: InputStream, options opt: ReadingOptions = []) throws -> AnyObject {
NSUnimplemented()
}
}
//MARK: - Encoding Detection
internal extension JSONSerialization {
/// Detect the encoding format of the NSData contents
class func detectEncoding(_ bytes: UnsafePointer<UInt8>, _ length: Int) -> String.Encoding {
if length >= 4 {
switch (bytes[0], bytes[1], bytes[2], bytes[3]) {
case (0, 0, 0, _):
return .utf32BigEndian
case (_, 0, 0, 0):
return .utf32LittleEndian
case (0, _, 0, _):
return .utf16BigEndian
case (_, 0, _, 0):
return .utf16LittleEndian
default:
break
}
}
else if length >= 2 {
switch (bytes[0], bytes[1]) {
case (0, _):
return .utf16BigEndian
case (_, 0):
return .utf16LittleEndian
default:
break
}
}
return .utf8
}
static func parseBOM(_ bytes: UnsafePointer<UInt8>, length: Int) -> (encoding: String.Encoding, skipLength: Int)? {
if length >= 2 {
switch (bytes[0], bytes[1]) {
case (0xEF, 0xBB):
if length >= 3 && bytes[2] == 0xBF {
return (.utf8, 3)
}
case (0x00, 0x00):
if length >= 4 && bytes[2] == 0xFE && bytes[3] == 0xFF {
return (.utf32BigEndian, 4)
}
case (0xFF, 0xFE):
if length >= 4 && bytes[2] == 0 && bytes[3] == 0 {
return (.utf32LittleEndian, 4)
}
return (.utf16LittleEndian, 2)
case (0xFE, 0xFF):
return (.utf16BigEndian, 2)
default:
break
}
}
return nil
}
}
//MARK: - JSONSerializer
private struct JSONWriter {
var indent = 0
let pretty: Bool
let writer: (String?) -> Void
private lazy var _numberformatter: CFNumberFormatter = {
let formatter: CFNumberFormatter
formatter = CFNumberFormatterCreate(nil, CFLocaleCopyCurrent(), kCFNumberFormatterNoStyle)
CFNumberFormatterSetProperty(formatter, kCFNumberFormatterMaxFractionDigits, NSNumber(value: 15))
CFNumberFormatterSetFormat(formatter, "0.###############"._cfObject)
return formatter
}()
init(pretty: Bool = false, writer: @escaping (String?) -> Void) {
self.pretty = pretty
self.writer = writer
}
mutating func serializeJSON(_ obj: Any) throws {
if let str = obj as? String {
try serializeString(str)
} else if let num = _SwiftValue.store(obj) as? NSNumber {
try serializeNumber(num)
} else if let array = obj as? Array<Any> {
try serializeArray(array)
} else if let dict = obj as? Dictionary<AnyHashable, Any> {
try serializeDictionary(dict)
} else if let null = obj as? NSNull {
try serializeNull(null)
} else if let boolVal = obj as? Bool {
try serializeNumber(NSNumber(value: boolVal))
}
else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "Invalid object cannot be serialized"])
}
}
func serializeString(_ str: String) throws {
writer("\"")
for scalar in str.unicodeScalars {
switch scalar {
case "\"":
writer("\\\"") // U+0022 quotation mark
case "\\":
writer("\\\\") // U+005C reverse solidus
// U+002F solidus not escaped
case "\u{8}":
writer("\\b") // U+0008 backspace
case "\u{c}":
writer("\\f") // U+000C form feed
case "\n":
writer("\\n") // U+000A line feed
case "\r":
writer("\\r") // U+000D carriage return
case "\t":
writer("\\t") // U+0009 tab
case "\u{0}"..."\u{f}":
writer("\\u000\(String(scalar.value, radix: 16))") // U+0000 to U+000F
case "\u{10}"..."\u{1f}":
writer("\\u00\(String(scalar.value, radix: 16))") // U+0010 to U+001F
default:
writer(String(scalar))
}
}
writer("\"")
}
mutating func serializeNumber(_ num: NSNumber) throws {
if num.doubleValue.isInfinite || num.doubleValue.isNaN {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "Number cannot be infinity or NaN"])
}
// Cannot detect type information (e.g. bool) as there is no objCType property on NSNumber in Swift
// So, just print the number
writer(_serializationString(for: num))
}
mutating func serializeArray(_ array: [Any]) throws {
writer("[")
if pretty {
writer("\n")
incAndWriteIndent()
}
var first = true
for elem in array {
if first {
first = false
} else if pretty {
writer(",\n")
writeIndent()
} else {
writer(",")
}
try serializeJSON(elem)
}
if pretty {
writer("\n")
decAndWriteIndent()
}
writer("]")
}
mutating func serializeDictionary(_ dict: Dictionary<AnyHashable, Any>) throws {
writer("{")
if pretty {
writer("\n")
incAndWriteIndent()
}
var first = true
for (key, value) in dict {
if first {
first = false
} else if pretty {
writer(",\n")
writeIndent()
} else {
writer(",")
}
if key is String {
try serializeString(key as! String)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "NSDictionary key must be NSString"])
}
pretty ? writer(": ") : writer(":")
try serializeJSON(value)
}
if pretty {
writer("\n")
decAndWriteIndent()
}
writer("}")
}
func serializeNull(_ null: NSNull) throws {
writer("null")
}
let indentAmount = 2
mutating func incAndWriteIndent() {
indent += indentAmount
writeIndent()
}
mutating func decAndWriteIndent() {
indent -= indentAmount
writeIndent()
}
func writeIndent() {
for _ in 0..<indent {
writer(" ")
}
}
//[SR-2151] https://bugs.swift.org/browse/SR-2151
private mutating func _serializationString(for number: NSNumber) -> String {
return CFNumberFormatterCreateStringWithNumber(nil, _numberformatter, number._cfObject)._swiftObject
}
}
//MARK: - JSONDeserializer
private struct JSONReader {
static let whitespaceASCII: [UInt8] = [
0x09, // Horizontal tab
0x0A, // Line feed or New line
0x0D, // Carriage return
0x20, // Space
]
struct Structure {
static let BeginArray: UInt8 = 0x5B // [
static let EndArray: UInt8 = 0x5D // ]
static let BeginObject: UInt8 = 0x7B // {
static let EndObject: UInt8 = 0x7D // }
static let NameSeparator: UInt8 = 0x3A // :
static let ValueSeparator: UInt8 = 0x2C // ,
static let QuotationMark: UInt8 = 0x22 // "
static let Escape: UInt8 = 0x5C // \
}
typealias Index = Int
typealias IndexDistance = Int
struct UnicodeSource {
let buffer: UnsafeBufferPointer<UInt8>
let encoding: String.Encoding
let step: Int
init(buffer: UnsafeBufferPointer<UInt8>, encoding: String.Encoding) {
self.buffer = buffer
self.encoding = encoding
self.step = {
switch encoding {
case String.Encoding.utf8:
return 1
case String.Encoding.utf16BigEndian, String.Encoding.utf16LittleEndian:
return 2
case String.Encoding.utf32BigEndian, String.Encoding.utf32LittleEndian:
return 4
default:
return 1
}
}()
}
func takeASCII(_ input: Index) -> (UInt8, Index)? {
guard hasNext(input) else {
return nil
}
let index: Int
switch encoding {
case String.Encoding.utf8:
index = input
case String.Encoding.utf16BigEndian where buffer[input] == 0:
index = input + 1
case String.Encoding.utf32BigEndian where buffer[input] == 0 && buffer[input+1] == 0 && buffer[input+2] == 0:
index = input + 3
case String.Encoding.utf16LittleEndian where buffer[input+1] == 0:
index = input
case String.Encoding.utf32LittleEndian where buffer[input+1] == 0 && buffer[input+2] == 0 && buffer[input+3] == 0:
index = input
default:
return nil
}
return (buffer[index] < 0x80) ? (buffer[index], input + step) : nil
}
func takeString(_ begin: Index, end: Index) throws -> String {
let byteLength = begin.distance(to: end)
guard let chunk = String(data: Data(bytes: buffer.baseAddress!.advanced(by: begin), count: byteLength), encoding: encoding) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Unable to convert data to a string using the detected encoding. The data may be corrupt."
])
}
return chunk
}
func hasNext(_ input: Index) -> Bool {
return input + step <= buffer.endIndex
}
func distanceFromStart(_ index: Index) -> IndexDistance {
return buffer.startIndex.distance(to: index) / step
}
}
let source: UnicodeSource
func consumeWhitespace(_ input: Index) -> Index? {
var index = input
while let (char, nextIndex) = source.takeASCII(index), JSONReader.whitespaceASCII.contains(char) {
index = nextIndex
}
return index
}
func consumeStructure(_ ascii: UInt8, input: Index) throws -> Index? {
return try consumeWhitespace(input).flatMap(consumeASCII(ascii)).flatMap(consumeWhitespace)
}
func consumeASCII(_ ascii: UInt8) -> (Index) throws -> Index? {
return { (input: Index) throws -> Index? in
switch self.source.takeASCII(input) {
case .none:
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Unexpected end of file during JSON parse."
])
case let (taken, index)? where taken == ascii:
return index
default:
return nil
}
}
}
func consumeASCIISequence(_ sequence: String, input: Index) throws -> Index? {
var index = input
for scalar in sequence.unicodeScalars {
guard let nextIndex = try consumeASCII(UInt8(scalar.value))(index) else {
return nil
}
index = nextIndex
}
return index
}
func takeMatching(_ match: @escaping (UInt8) -> Bool) -> ([Character], Index) -> ([Character], Index)? {
return { input, index in
guard let (byte, index) = self.source.takeASCII(index), match(byte) else {
return nil
}
return (input + [Character(UnicodeScalar(byte))], index)
}
}
//MARK: - String Parsing
func parseString(_ input: Index) throws -> (String, Index)? {
guard let beginIndex = try consumeWhitespace(input).flatMap(consumeASCII(Structure.QuotationMark)) else {
return nil
}
var chunkIndex: Int = beginIndex
var currentIndex: Int = chunkIndex
var output: String = ""
while source.hasNext(currentIndex) {
guard let (ascii, index) = source.takeASCII(currentIndex) else {
currentIndex += source.step
continue
}
switch ascii {
case Structure.QuotationMark:
output += try source.takeString(chunkIndex, end: currentIndex)
return (output, index)
case Structure.Escape:
output += try source.takeString(chunkIndex, end: currentIndex)
if let (escaped, nextIndex) = try parseEscapeSequence(index) {
output += escaped
chunkIndex = nextIndex
currentIndex = nextIndex
continue
}
else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Invalid escape sequence at position \(source.distanceFromStart(currentIndex))"
])
}
default:
currentIndex = index
}
}
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Unexpected end of file during string parse."
])
}
func parseEscapeSequence(_ input: Index) throws -> (String, Index)? {
guard let (byte, index) = source.takeASCII(input) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Early end of unicode escape sequence around character"
])
}
let output: String
switch byte {
case 0x22: output = "\""
case 0x5C: output = "\\"
case 0x2F: output = "/"
case 0x62: output = "\u{08}" // \b
case 0x66: output = "\u{0C}" // \f
case 0x6E: output = "\u{0A}" // \n
case 0x72: output = "\u{0D}" // \r
case 0x74: output = "\u{09}" // \t
case 0x75: return try parseUnicodeSequence(index)
default: return nil
}
return (output, index)
}
func parseUnicodeSequence(_ input: Index) throws -> (String, Index)? {
guard let (codeUnit, index) = parseCodeUnit(input) else {
return nil
}
if !UTF16.isLeadSurrogate(codeUnit) {
return (String(UnicodeScalar(codeUnit)!), index)
}
guard let (trailCodeUnit, finalIndex) = try consumeASCIISequence("\\u", input: index).flatMap(parseCodeUnit) , UTF16.isTrailSurrogate(trailCodeUnit) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Unable to convert unicode escape sequence (no low-surrogate code point) to UTF8-encoded character at position \(source.distanceFromStart(input))"
])
}
let highValue = (UInt32(codeUnit - 0xD800) << 10)
let lowValue = UInt32(trailCodeUnit - 0xDC00)
return (String(UnicodeScalar(highValue + lowValue + 0x10000)!), finalIndex)
}
func isHexChr(_ byte: UInt8) -> Bool {
return (byte >= 0x30 && byte <= 0x39)
|| (byte >= 0x41 && byte <= 0x46)
|| (byte >= 0x61 && byte <= 0x66)
}
func parseCodeUnit(_ input: Index) -> (UTF16.CodeUnit, Index)? {
let hexParser = takeMatching(isHexChr)
guard let (result, index) = hexParser([], input).flatMap(hexParser).flatMap(hexParser).flatMap(hexParser),
let value = Int(String(result), radix: 16) else {
return nil
}
return (UTF16.CodeUnit(value), index)
}
//MARK: - Number parsing
static let numberCodePoints: [UInt8] = [
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, // 0...9
0x2E, 0x2D, 0x2B, 0x45, 0x65, // . - + E e
]
func parseNumber(_ input: Index) throws -> (Any, Index)? {
func parseTypedNumber(_ address: UnsafePointer<UInt8>, count: Int) -> (Any, IndexDistance)? {
let temp_buffer_size = 64
var temp_buffer = [Int8](repeating: 0, count: temp_buffer_size)
return temp_buffer.withUnsafeMutableBufferPointer { (buffer: inout UnsafeMutableBufferPointer<Int8>) -> (Any, IndexDistance)? in
memcpy(buffer.baseAddress!, address, min(count, temp_buffer_size - 1)) // ensure null termination
let startPointer = buffer.baseAddress!
let intEndPointer = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 1)
defer { intEndPointer.deallocate(capacity: 1) }
let doubleEndPointer = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 1)
defer { doubleEndPointer.deallocate(capacity: 1) }
let intResult = strtol(startPointer, intEndPointer, 10)
let intDistance = startPointer.distance(to: intEndPointer[0]!)
let doubleResult = strtod(startPointer, doubleEndPointer)
let doubleDistance = startPointer.distance(to: doubleEndPointer[0]!)
guard intDistance > 0 || doubleDistance > 0 else {
return nil
}
if intDistance == doubleDistance {
return (intResult, intDistance)
}
guard doubleDistance > 0 else {
return nil
}
return (doubleResult, doubleDistance)
}
}
if source.encoding == String.Encoding.utf8 {
return parseTypedNumber(source.buffer.baseAddress!.advanced(by: input), count: source.buffer.count - input).map { return ($0.0, input + $0.1) }
}
else {
var numberCharacters = [UInt8]()
var index = input
while let (ascii, nextIndex) = source.takeASCII(index), JSONReader.numberCodePoints.contains(ascii) {
numberCharacters.append(ascii)
index = nextIndex
}
numberCharacters.append(0)
return numberCharacters.withUnsafeBufferPointer {
parseTypedNumber($0.baseAddress!, count: $0.count)
}.map { return ($0.0, index) }
}
}
//MARK: - Value parsing
func parseValue(_ input: Index) throws -> (Any, Index)? {
if let (value, parser) = try parseString(input) {
return (value, parser)
}
else if let parser = try consumeASCIISequence("true", input: input) {
return (true, parser)
}
else if let parser = try consumeASCIISequence("false", input: input) {
return (false, parser)
}
else if let parser = try consumeASCIISequence("null", input: input) {
return (NSNull(), parser)
}
else if let (object, parser) = try parseObject(input) {
return (object, parser)
}
else if let (array, parser) = try parseArray(input) {
return (array, parser)
}
else if let (number, parser) = try parseNumber(input) {
return (number, parser)
}
return nil
}
//MARK: - Object parsing
func parseObject(_ input: Index) throws -> ([String: Any], Index)? {
guard let beginIndex = try consumeStructure(Structure.BeginObject, input: input) else {
return nil
}
var index = beginIndex
var output: [String: Any] = [:]
while true {
if let finalIndex = try consumeStructure(Structure.EndObject, input: index) {
return (output, finalIndex)
}
if let (key, value, nextIndex) = try parseObjectMember(index) {
output[key] = value
if let finalParser = try consumeStructure(Structure.EndObject, input: nextIndex) {
return (output, finalParser)
}
else if let nextIndex = try consumeStructure(Structure.ValueSeparator, input: nextIndex) {
index = nextIndex
continue
}
else {
return nil
}
}
return nil
}
}
func parseObjectMember(_ input: Index) throws -> (String, Any, Index)? {
guard let (name, index) = try parseString(input) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Missing object key at location \(source.distanceFromStart(input))"
])
}
guard let separatorIndex = try consumeStructure(Structure.NameSeparator, input: index) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Invalid separator at location \(source.distanceFromStart(index))"
])
}
guard let (value, finalIndex) = try parseValue(separatorIndex) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Invalid value at location \(source.distanceFromStart(separatorIndex))"
])
}
return (name, value, finalIndex)
}
//MARK: - Array parsing
func parseArray(_ input: Index) throws -> ([Any], Index)? {
guard let beginIndex = try consumeStructure(Structure.BeginArray, input: input) else {
return nil
}
var index = beginIndex
var output: [Any] = []
while true {
if let finalIndex = try consumeStructure(Structure.EndArray, input: index) {
return (output, finalIndex)
}
if let (value, nextIndex) = try parseValue(index) {
output.append(value)
if let finalIndex = try consumeStructure(Structure.EndArray, input: nextIndex) {
return (output, finalIndex)
}
else if let nextIndex = try consumeStructure(Structure.ValueSeparator, input: nextIndex) {
index = nextIndex
continue
}
}
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Badly formed array at location \(source.distanceFromStart(index))"
])
}
}
}
| 40.130488 | 499 | 0.566749 |
e24e019195d921479534f6c7d23cd657b1fc8fb7 | 9,716 | //
// NodeType.swift
// NodalityThree
//
// Created by Simon Gladman on 13/10/2015.
// Copyright © 2015 Simon Gladman. All rights reserved.
//
// Adding a new node type:
// * Create enum
// * Define input slots
// * Add to `types`
// * Define behaviour in NodeVO.recalculate()
// * If node output is numeric, add to `outputType` and `outputTypeName` in NodeVO
import UIKit
let SNNodeNumberType = NodeValue.Number(nil)
let SNNodeNodeType = NodeValue.Node(nil)
let SNNodeOutputType = NodeValue.Output
let SNNumberTypeName = "Number"
let SNNodeTypeName = "Node"
let SNOutputTypeName = "Output"
enum NodeType: String
{
// Numerics
case Numeric
case NumericDouble
case NumericHalve
// Generators
case Oscillator
case WhiteNoise
case PinkNoise
case FMOscillator
case SawtoothOscillator
case SquareWaveOscillator
case TriangleOscillator
case AudioPlayer
// Filters
case DryWetMixer
case StringResonator
case MoogLadder
case BitCrusher
case Reverb
case CostelloReverb
case Decimator
case Equalizer
case AutoWah
case RingModulator
case VariableDelay
case LowPassFilter
case HighPassFilter
case TB303
// Mandatory output
case Output
var inputSlots: [NodeInputSlot]
{
switch self
{
case .Numeric:
return []
case .NumericDouble, .NumericHalve:
return [ NodeInputSlot(label: "x", type: SNNodeNumberType) ];
case .Output:
return [ NodeInputSlot(label: "Input", type: SNNodeNodeType) ];
case .AudioPlayer:
return [ NodeInputSlot(label: "Volume", type: SNNodeNumberType, defaultValue: 0.5) ];
case .DryWetMixer:
return [
NodeInputSlot(label: "Input 1", type: SNNodeNodeType),
NodeInputSlot(label: "Input 2", type: SNNodeNodeType),
NodeInputSlot(label: "Balance", type: SNNodeNumberType, defaultValue: 0.5)]
case .Oscillator:
return [
NodeInputSlot(label: "Amplitude", type: SNNodeNumberType, defaultValue: 0.5),
NodeInputSlot(label: "Frequency", type: SNNodeNumberType, defaultValue: 440)]
case .WhiteNoise, .PinkNoise:
return [
NodeInputSlot(label: "Amplitude", type: SNNodeNumberType, defaultValue: 0.5)]
case .StringResonator:
return [
NodeInputSlot(label: "Input", type: SNNodeNodeType),
NodeInputSlot(label: "Fundamental Freq.", type: SNNodeNumberType, defaultValue: 100),
NodeInputSlot(label: "Feedback", type: SNNodeNumberType, defaultValue: 0.95)]
case .MoogLadder:
return [
NodeInputSlot(label: "Input", type: SNNodeNodeType),
NodeInputSlot(label: "Cut Off Freq.", type: SNNodeNumberType, defaultValue: 500),
NodeInputSlot(label: "Resonance", type: SNNodeNumberType, defaultValue: 0.5)]
case .TB303:
return [
NodeInputSlot(label: "Input", type: SNNodeNodeType),
NodeInputSlot(label: "Cut Off Freq.", type: SNNodeNumberType, defaultValue: 1000),
NodeInputSlot(label: "Resonance", type: SNNodeNumberType, defaultValue: 0.5),
NodeInputSlot(label: "Resonance Asymmetry", type: SNNodeNumberType, defaultValue: 0.5)]
case .FMOscillator:
return [
NodeInputSlot(label: "Base Freq.", type: SNNodeNumberType, defaultValue: 440),
NodeInputSlot(label: "Carrier Mult.", type: SNNodeNumberType, defaultValue: 1.0),
NodeInputSlot(label: "Mod. Mult.", type: SNNodeNumberType, defaultValue: 1.0),
NodeInputSlot(label: "Mod. Index", type: SNNodeNumberType, defaultValue: 1.0),
NodeInputSlot(label: "Amplitude", type: SNNodeNumberType, defaultValue: 0.5)]
case .SawtoothOscillator:
return [
NodeInputSlot(label: "Frequency", type: SNNodeNumberType, defaultValue: 440),
NodeInputSlot(label: "Amplitude", type: SNNodeNumberType, defaultValue: 0.5),
NodeInputSlot(label: "Detuning Offset", type: SNNodeNumberType, defaultValue: 0),
NodeInputSlot(label: "Detuning Mult.", type: SNNodeNumberType, defaultValue: 1)
]
case .TriangleOscillator:
return [
NodeInputSlot(label: "Frequency", type: SNNodeNumberType, defaultValue: 440),
NodeInputSlot(label: "Amplitude", type: SNNodeNumberType, defaultValue: 0.5),
NodeInputSlot(label: "Detuning Offset", type: SNNodeNumberType, defaultValue: 0),
NodeInputSlot(label: "Detuning Mult.", type: SNNodeNumberType, defaultValue: 1)
]
case .SquareWaveOscillator:
return [
NodeInputSlot(label: "Frequency", type: SNNodeNumberType, defaultValue: 440),
NodeInputSlot(label: "Amplitude", type: SNNodeNumberType, defaultValue: 0.5),
NodeInputSlot(label: "Detuning Offset", type: SNNodeNumberType, defaultValue: 0),
NodeInputSlot(label: "Detuning Mult.", type: SNNodeNumberType, defaultValue: 1),
NodeInputSlot(label: "Pulse Width.", type: SNNodeNumberType, defaultValue: 0.5)
]
case .BitCrusher:
return [
NodeInputSlot(label: "Input", type: SNNodeNodeType),
NodeInputSlot(label: "Bit Depth", type: SNNodeNumberType, defaultValue: 8),
NodeInputSlot(label: "Sample Rate", type: SNNodeNumberType, defaultValue: 10000)
]
case .Reverb:
return [
NodeInputSlot(label: "Input", type: SNNodeNodeType),
NodeInputSlot(label: "Dry Wet Mix", type: SNNodeNumberType, defaultValue: 0.5)
]
case .CostelloReverb:
return [
NodeInputSlot(label: "Input", type: SNNodeNodeType),
NodeInputSlot(label: "Feedback", type: SNNodeNumberType, defaultValue: 0.6),
NodeInputSlot(label: "Cut Off Freq.", type: SNNodeNumberType, defaultValue: 4000),
]
case .Decimator:
return [
NodeInputSlot(label: "Input", type: SNNodeNodeType),
NodeInputSlot(label: "Decimation", type: SNNodeNumberType, defaultValue: 0.5),
NodeInputSlot(label: "Rounding", type: SNNodeNumberType, defaultValue: 0),
NodeInputSlot(label: "Mix", type: SNNodeNumberType, defaultValue: 1),
]
case .Equalizer:
return [
NodeInputSlot(label: "Input", type: SNNodeNodeType),
NodeInputSlot(label: "Center Frequency", type: SNNodeNumberType, defaultValue: 1000),
NodeInputSlot(label: "Bandwidth", type: SNNodeNumberType, defaultValue: 100),
NodeInputSlot(label: "Gain", type: SNNodeNumberType, defaultValue: 10)
]
case .AutoWah:
return [
NodeInputSlot(label: "Input", type: SNNodeNodeType),
NodeInputSlot(label: "Wah", type: SNNodeNumberType, defaultValue: 0),
NodeInputSlot(label: "Mix", type: SNNodeNumberType, defaultValue: 1),
NodeInputSlot(label: "Amplitude", type: SNNodeNumberType, defaultValue: 0.1)
]
case .RingModulator:
return [
NodeInputSlot(label: "Input", type: SNNodeNodeType),
NodeInputSlot(label: "Frequency 1", type: SNNodeNumberType, defaultValue: 220),
NodeInputSlot(label: "Frequency 1", type: SNNodeNumberType, defaultValue: 440),
NodeInputSlot(label: "Balance", type: SNNodeNumberType, defaultValue: 0.5),
NodeInputSlot(label: "Mix", type: SNNodeNumberType, defaultValue: 1.0)]
case .VariableDelay:
return [
NodeInputSlot(label: "Input", type: SNNodeNodeType),
NodeInputSlot(label: "Time", type: SNNodeNumberType, defaultValue:1),
NodeInputSlot(label: "Feedback", type: SNNodeNumberType, defaultValue: 0),
]
case .LowPassFilter, .HighPassFilter:
return [
NodeInputSlot(label: "Input", type: SNNodeNodeType),
NodeInputSlot(label: "Cutoff Freq.", type: SNNodeNumberType, defaultValue: 6900),
NodeInputSlot(label: "Resonance", type: SNNodeNumberType, defaultValue: 0),
NodeInputSlot(label: "Dry Wet Mix", type: SNNodeNumberType, defaultValue: 100)
]
}
}
var numInputSlots: Int
{
return inputSlots.count
}
static let types = [
Numeric, NumericDouble, NumericHalve,
Oscillator, WhiteNoise, PinkNoise,
MoogLadder, DryWetMixer, StringResonator,
FMOscillator, SawtoothOscillator, SquareWaveOscillator, TriangleOscillator,
BitCrusher, Reverb, CostelloReverb, Decimator,
Equalizer, AutoWah, RingModulator, VariableDelay, LowPassFilter, HighPassFilter,
AudioPlayer, TB303
].sort{$1.rawValue > $0.rawValue}
static func createNodeOfType(nodeType: NodeType, model: NodalityModel) -> NodeVO
{
return NodeVO(type: nodeType, model: model)
}
} | 41.699571 | 103 | 0.599115 |
bfbaf591325ceea17b32185513f747463be557a7 | 17,696 | //
// WToast.swift
// WMobileKit
//
// Copyright 2017 Workiva 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 Foundation
import UIKit
import SnapKit
@objc public protocol WToastViewDelegate {
@objc optional func toastWasTapped(_ sender: UITapGestureRecognizer)
@objc optional func toastDidHide(_ toast: WToastView)
}
public enum WToastHideOptions {
case dismissOnTap, dismissesAfterTime
}
public enum WToastPlacementOptions {
case top, bottom
}
public enum WToastFlyInDirectionOptions {
case fromTop, fromRight, fromBottom, fromLeft
}
public let TOAST_DEFAULT_HEIGHT = 64
public let TOAST_DEFAULT_PADDING = 32
public let TOAST_DEFAULT_WIDTH_RATIO = 0.8
public let TOAST_DEFAULT_SHOW_DURATION = 2.0
public let TOAST_DEFAULT_ANIMATION_DURATION = 0.3
open class WToastManager: NSObject, WToastViewDelegate {
open var currentToast: WToastView?
open static let sharedInstance = WToastManager()
// Custom window can be provided. Default to frontmost window.
open var rootWindow: UIWindow? = UIApplication.shared.windows.first
fileprivate override init() {
super.init()
}
open func showToast(_ toast: WToastView) {
NotificationCenter.default.post(name: Notification.Name(rawValue: WConstants.NotificationKey.KillAllToasts), object: nil)
currentToast = toast
currentToast?.delegate = self
toast.show()
}
@objc open func toastWasTapped(_ sender: UITapGestureRecognizer) { }
@objc open func toastDidHide(_ toast: WToastView) {
currentToast = nil
}
}
open class WToastView: UIView {
// Public API
open weak var delegate: WToastViewDelegate?
// If 0 or less, options change to dismiss on tap
open var showDuration: TimeInterval = TOAST_DEFAULT_SHOW_DURATION {
didSet {
hideOptions = showDuration > 0 ? .dismissesAfterTime : .dismissOnTap
}
}
open var hideOptions: WToastHideOptions = .dismissesAfterTime
open var placement: WToastPlacementOptions = .bottom {
didSet {
flyInDirection = placement == .top ? .fromTop : .fromBottom
}
}
open var flyInDirection: WToastFlyInDirectionOptions = .fromBottom
open var animationDuration = TOAST_DEFAULT_ANIMATION_DURATION
open var height = TOAST_DEFAULT_HEIGHT
open var width: Int?
open var widthRatio = TOAST_DEFAULT_WIDTH_RATIO
open var topPadding = TOAST_DEFAULT_PADDING
open var bottomPadding = TOAST_DEFAULT_PADDING
open var leftPadding: Int?
open var rightPadding: Int?
open var heightConstraint: Constraint?
open var message = "" {
didSet {
messageLabel.text = message
}
}
open var rightIcon: UIImage? {
didSet {
rightIconImageView.image = rightIcon
}
}
open var toastColor: UIColor = .black {
didSet {
backgroundView.backgroundColor = toastColor
}
}
open var toastAlpha: CGFloat = 0.7 {
didSet {
backgroundView.alpha = toastAlpha
rightIconImageView.alpha = toastAlpha
}
}
open var messageLabel = UILabel()
open var rightIconImageView = UIImageView()
open var backgroundView = UIView()
// Private API
internal var showTimer: Timer?
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public convenience init(message: String, icon: UIImage? = nil, toastColor: UIColor = .black, toastAlpha: CGFloat = 0.7, showDuration: TimeInterval = TOAST_DEFAULT_SHOW_DURATION) {
self.init(frame: CGRect.zero)
self.message = message
self.toastColor = toastColor
self.backgroundView.alpha = toastAlpha
self.rightIcon = icon
self.showDuration = showDuration
rightIconImageView.alpha = toastAlpha
}
fileprivate func commonInit() {
NotificationCenter.default.addObserver(self, selector: #selector(WToastView.hide), name: NSNotification.Name(rawValue: WConstants.NotificationKey.KillAllToasts), object: nil)
addSubview(backgroundView)
addSubview(messageLabel)
addSubview(rightIconImageView)
let recognizer = UITapGestureRecognizer(target: self, action: #selector(WToastViewDelegate.toastWasTapped(_:)))
addGestureRecognizer(recognizer)
// Set defaults here instead of the setupUI so they will not be
// overwritten by custom user values
messageLabel.numberOfLines = 1
messageLabel.textAlignment = .center
messageLabel.font = UIFont.systemFont(ofSize: 16)
messageLabel.textColor = .white
layer.cornerRadius = 5.0
clipsToBounds = true
backgroundColor = .clear
}
deinit {
NotificationCenter.default.removeObserver(self)
}
open func setupUI() {
// Do not set any defaults here as they will overwrite any custom
// values when the toast is shown.
// Values set by variables should still be set.
backgroundView.snp.remakeConstraints { (make) in
make.left.equalTo(self)
make.right.equalTo(self)
make.bottom.equalTo(self)
make.top.equalTo(self)
}
backgroundView.backgroundColor = toastColor
rightIconImageView.snp.remakeConstraints { (make) in
make.centerY.equalTo(self)
make.right.equalTo(self).offset(-frame.size.width / 10)
make.height.equalTo(14)
make.width.equalTo(14)
}
rightIconImageView.image = rightIcon
messageLabel.snp.remakeConstraints { (make) in
make.centerY.equalTo(self)
make.top.bottom.equalToSuperview().inset(8)
make.left.equalTo(self).offset(frame.size.width / 10)
make.right.equalTo(self).offset(-frame.size.width / 10 - 14)
}
messageLabel.text = message
backgroundView.alpha = toastAlpha
rightIconImageView.alpha = toastAlpha
layoutIfNeeded()
}
internal func toastWasTapped(_ sender: UITapGestureRecognizer) {
delegate?.toastWasTapped?(sender)
hide()
}
open func isVisible() -> Bool {
return (window != nil)
}
open func show() {
WToastManager.sharedInstance.rootWindow!.addSubview(self)
snp.remakeConstraints { (make) in
heightConstraint = make.height.equalTo(height).constraint
if let width = width {
make.width.equalTo(width)
} else {
make.width.equalTo(WToastManager.sharedInstance.rootWindow!).multipliedBy(widthRatio)
}
switch flyInDirection {
case .fromBottom:
make.top.equalTo(WToastManager.sharedInstance.rootWindow!.snp.bottom)
make.centerX.equalTo(WToastManager.sharedInstance.rootWindow!)
case .fromTop:
make.bottom.equalTo(WToastManager.sharedInstance.rootWindow!.snp.top)
make.centerX.equalTo(WToastManager.sharedInstance.rootWindow!)
case .fromLeft:
make.right.equalTo(WToastManager.sharedInstance.rootWindow!.snp.left)
if (placement == .bottom) {
make.bottom.equalTo(WToastManager.sharedInstance.rootWindow!).offset(-bottomPadding)
} else {
make.top.equalTo(WToastManager.sharedInstance.rootWindow!).offset(topPadding)
}
case .fromRight:
make.left.equalTo(WToastManager.sharedInstance.rootWindow!.snp.right)
if (placement == .bottom) {
make.bottom.equalTo(WToastManager.sharedInstance.rootWindow!).offset(-bottomPadding)
} else {
make.top.equalTo(WToastManager.sharedInstance.rootWindow!).offset(topPadding)
}
}
}
WToastManager.sharedInstance.rootWindow!.layoutIfNeeded()
setupUI()
WToastManager.sharedInstance.rootWindow!.layoutIfNeeded()
snp.remakeConstraints { (make) in
heightConstraint = make.height.equalTo(height).constraint
if let width = width {
make.width.equalTo(width)
} else {
make.width.equalTo(WToastManager.sharedInstance.rootWindow!).multipliedBy(widthRatio)
}
if (placement == .bottom) {
make.bottom.equalTo(WToastManager.sharedInstance.rootWindow!).offset(-bottomPadding)
} else {
make.top.equalTo(WToastManager.sharedInstance.rootWindow!).offset(topPadding)
}
if (flyInDirection == .fromLeft && leftPadding != nil) {
make.left.equalTo(WToastManager.sharedInstance.rootWindow!).offset(leftPadding!)
} else if (flyInDirection == .fromRight && rightPadding != nil) {
make.right.equalTo(WToastManager.sharedInstance.rootWindow!).offset(-rightPadding!)
} else {
make.centerX.equalTo(WToastManager.sharedInstance.rootWindow!)
}
}
UIView.animate(withDuration: animationDuration, delay: 0, options: UIViewAnimationOptions(),
animations: {
WToastManager.sharedInstance.rootWindow!.layoutIfNeeded()
},
completion: { finished in
if (self.hideOptions == .dismissesAfterTime) {
self.showTimer = Timer.scheduledTimer(timeInterval: self.showDuration, target: self, selector: #selector(WToastView.hide), userInfo: self, repeats: false)
}
}
)
}
@objc open func hide() {
showTimer?.invalidate()
showTimer = nil
if isVisible() {
NotificationCenter.default.removeObserver(self)
//animate out
snp.remakeConstraints{ (make) in
heightConstraint = make.height.equalTo(height).constraint
if let width = width {
make.width.equalTo(width)
} else {
make.width.equalTo(WToastManager.sharedInstance.rootWindow!).multipliedBy(widthRatio)
}
switch flyInDirection {
case .fromBottom:
make.top.equalTo(WToastManager.sharedInstance.rootWindow!.snp.bottom)
make.centerX.equalTo(WToastManager.sharedInstance.rootWindow!)
case .fromTop:
make.bottom.equalTo(WToastManager.sharedInstance.rootWindow!.snp.top)
make.centerX.equalTo(WToastManager.sharedInstance.rootWindow!)
case .fromLeft:
make.right.equalTo(WToastManager.sharedInstance.rootWindow!.snp.left)
if (placement == .bottom) {
make.bottom.equalTo(WToastManager.sharedInstance.rootWindow!).offset(-bottomPadding)
} else {
make.top.equalTo(WToastManager.sharedInstance.rootWindow!).offset(topPadding)
}
case .fromRight:
make.left.equalTo(WToastManager.sharedInstance.rootWindow!.snp.right)
if (placement == .bottom) {
make.bottom.equalTo(WToastManager.sharedInstance.rootWindow!).offset(-bottomPadding)
} else {
make.top.equalTo(WToastManager.sharedInstance.rootWindow!).offset(topPadding)
}
}
}
UIView.animate(withDuration: animationDuration,
animations: {
WToastManager.sharedInstance.rootWindow!.layoutIfNeeded()
},
completion: { finished in
self.removeFromSuperview()
self.delegate?.toastDidHide?(self)
}
)
}
}
}
public class WToastTwoLineView: WToastView {
public var firstLine = "" {
didSet {
firstLabel.text = message
}
}
public var secondLine = "" {
didSet {
secondLabel.text = message
}
}
public var firstLabel = UILabel()
public var secondLabel = UILabel()
public convenience init(firstLine: String, secondLine: String, icon: UIImage? = nil, toastColor: UIColor = .black,
toastAlpha: CGFloat = 0.7, showDuration: TimeInterval = TOAST_DEFAULT_SHOW_DURATION) {
self.init(frame: CGRect.zero)
self.firstLine = firstLine
self.secondLine = secondLine
self.toastColor = toastColor
self.backgroundView.alpha = toastAlpha
self.rightIcon = icon
self.showDuration = showDuration
rightIconImageView.alpha = toastAlpha
}
fileprivate override func commonInit() {
NotificationCenter.default.addObserver(self, selector: #selector(WToastView.hide), name: NSNotification.Name(rawValue: WConstants.NotificationKey.KillAllToasts), object: nil)
addSubview(backgroundView)
addSubview(firstLabel)
addSubview(secondLabel)
addSubview(rightIconImageView)
let recognizer = UITapGestureRecognizer(target: self, action: #selector(WToastViewDelegate.toastWasTapped(_:)))
addGestureRecognizer(recognizer)
// Set defaults here instead of the setupUI so they will not be
// overwritten by custom user values
firstLabel.numberOfLines = 1
firstLabel.textAlignment = .center
firstLabel.font = UIFont.systemFont(ofSize: 16)
firstLabel.textColor = .white
secondLabel.numberOfLines = 1
secondLabel.textAlignment = .center
secondLabel.font = UIFont.systemFont(ofSize: 16)
secondLabel.textColor = .white
layer.cornerRadius = 5.0
clipsToBounds = true
backgroundColor = .clear
}
deinit {
NotificationCenter.default.removeObserver(self)
}
public override func setupUI() {
// Do not set any defaults here as they will overwrite any custom
// values when the toast is shown.
// Values set by variables should still be set.
backgroundView.snp.remakeConstraints { (make) in
make.left.equalTo(self)
make.right.equalTo(self)
make.bottom.equalTo(self)
make.top.equalTo(self)
}
backgroundView.backgroundColor = toastColor
rightIconImageView.snp.remakeConstraints { (make) in
make.centerY.equalTo(self)
make.right.equalTo(self).offset(-frame.size.width / 10)
make.height.equalTo(14)
make.width.equalTo(14)
}
rightIconImageView.image = rightIcon
firstLabel.snp.remakeConstraints { (make) in
make.top.equalTo(self).offset(8)
make.height.equalTo(frame.size.height/2 - 8)
make.left.equalTo(self).offset(frame.size.width / 10)
make.right.equalTo(self).offset(-frame.size.width / 10 - 14)
}
firstLabel.text = firstLine
secondLabel.snp.remakeConstraints { (make) in
make.bottom.equalTo(self).offset(-8)
make.height.equalTo(frame.size.height/2 - 8)
make.left.equalTo(self).offset(frame.size.width / 10)
make.right.equalTo(self).offset(-frame.size.width / 10 - 14)
}
secondLabel.text = secondLine
backgroundView.alpha = toastAlpha
rightIconImageView.alpha = toastAlpha
layoutIfNeeded()
}
}
public class WToastFlexibleView: WToastView {
public var maxHeight: Int = 2 * TOAST_DEFAULT_HEIGHT
public override func setupUI() {
super.setupUI()
let labelWidth = messageLabel.frame.width
if let text = messageLabel.text {
let toastLabelHeight = text.heightWithConstrainedWidth(labelWidth, font: messageLabel.font)
height = min(Int(toastLabelHeight + 16), maxHeight)
heightConstraint?.deactivate()
snp.makeConstraints { make in
heightConstraint = make.height.equalTo(height).constraint
}
layoutIfNeeded()
}
}
override func commonInit() {
super.commonInit()
messageLabel.numberOfLines = 0
}
}
extension String {
func heightWithConstrainedWidth(_ width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = (self as NSString).boundingRect(
with: constraintRect,
options: .usesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil
)
return ceil(boundingBox.height)
}
}
| 35.392 | 183 | 0.622175 |
eb17aa0336eb8731e13e8a7426f31693a2df32e3 | 2,619 | //
// OPMLFile.swift
// Account
//
// Created by Maurice Parker on 9/12/19.
// Copyright © 2019 Ranchero Software, LLC. All rights reserved.
//
import Foundation
import os.log
import RSCore
import RSParser
final class OPMLFile {
private var log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "opmlFile")
private let fileURL: URL
private let account: Account
private var isDirty = false {
didSet {
queueSaveToDiskIfNeeded()
}
}
private let saveQueue = CoalescingQueue(name: "Save Queue", interval: 0.5)
init(filename: String, account: Account) {
self.fileURL = URL(fileURLWithPath: filename)
self.account = account
}
func markAsDirty() {
isDirty = true
}
func load() {
guard let fileData = opmlFileData(), let opmlItems = parsedOPMLItems(fileData: fileData) else {
return
}
BatchUpdate.shared.perform {
account.loadOPMLItems(opmlItems, parentFolder: nil)
}
}
func save() {
guard !account.isDeleted else { return }
let opmlDocumentString = opmlDocument()
do {
try opmlDocumentString.write(to: fileURL, atomically: true, encoding: .utf8)
} catch let error as NSError {
os_log(.error, log: log, "OPML save to disk failed: %@.", error.localizedDescription)
}
}
}
private extension OPMLFile {
func queueSaveToDiskIfNeeded() {
saveQueue.add(self, #selector(saveToDiskIfNeeded))
}
@objc func saveToDiskIfNeeded() {
if isDirty {
isDirty = false
save()
}
}
func opmlFileData() -> Data? {
var fileData: Data? = nil
do {
fileData = try Data(contentsOf: fileURL)
} catch {
os_log(.error, log: log, "OPML read from disk failed: %@.", error.localizedDescription)
}
return fileData
}
func parsedOPMLItems(fileData: Data) -> [RSOPMLItem]? {
let parserData = ParserData(url: fileURL.absoluteString, data: fileData)
var opmlDocument: RSOPMLDocument?
do {
opmlDocument = try RSOPMLParser.parseOPML(with: parserData)
} catch {
os_log(.error, log: log, "OPML Import failed: %@.", error.localizedDescription)
return nil
}
return opmlDocument?.children
}
func opmlDocument() -> String {
let escapedTitle = account.nameForDisplay.escapingSpecialXMLCharacters
let openingText =
"""
<?xml version="1.0" encoding="UTF-8"?>
<!-- OPML generated by NetNewsWire -->
<opml version="1.1">
<head>
<title>\(escapedTitle)</title>
</head>
<body>
"""
let middleText = account.OPMLString(indentLevel: 0, allowCustomAttributes: true)
let closingText =
"""
</body>
</opml>
"""
let opml = openingText + middleText + closingText
return opml
}
}
| 20.785714 | 97 | 0.684231 |
2f7d63b3e635816abfead2c9b9cc93cde12b428f | 208 | //
// SUT: CatalogService
//
// Collaborators:
// APIClient
// CatalogTranslator
//
import Quick
import Nimble
@testable import YARCH
class CatalogServiceTests: QuickSpec {
override func spec() {
}
}
| 12.235294 | 38 | 0.706731 |
16b616c583d211c8aa6e55a409cd4b4c4803e91f | 10,080 | //
// IOSSecuritySuite.swift
// IOSSecuritySuite
//
// Created by wregula on 23/04/2019.
// Copyright © 2019 wregula. All rights reserved.
//
//swiftlint:disable line_length
import Foundation
import MachO
public class IOSSecuritySuite {
/**
This type method is used to determine the true/false jailbreak status
Usage example
```
let isDeviceJailbroken: Bool = IOSSecuritySuite.amIJailbroken()
```
*/
public static func amIJailbroken() -> Bool {
return JailbreakChecker.amIJailbroken()
}
/**
This type method is used to determine the jailbreak status with a message which jailbreak indicator was detected
Usage example
```
let jailbreakStatus = IOSSecuritySuite.amIJailbrokenWithFailMessage()
if jailbreakStatus.jailbroken {
print("This device is jailbroken")
print("Because: \(jailbreakStatus.failMessage)")
} else {
print("This device is not jailbroken")
}
```
- Returns: Tuple with with the jailbreak status *Bool* labeled *jailbroken* and *String* labeled *failMessage*
to determine check that failed
*/
public static func amIJailbrokenWithFailMessage() -> (jailbroken: Bool, failMessage: String) {
return JailbreakChecker.amIJailbrokenWithFailMessage()
}
/**
This type method is used to determine the jailbreak status with a list of failed checks
Usage example
```
let jailbreakStatus = IOSSecuritySuite.amIJailbrokenWithFailedChecks()
if jailbreakStatus.jailbroken {
print("This device is jailbroken")
print("The following checks failed: \(jailbreakStatus.failedChecks)")
}
```
- Returns: Tuple with with the jailbreak status *Bool* labeled *jailbroken* and *[FailedCheck]* labeled *failedChecks*
for the list of failed checks
*/
public static func amIJailbrokenWithFailedChecks() -> (jailbroken: Bool, failedChecks: [FailedCheck]) {
return JailbreakChecker.amIJailbrokenWithFailedChecks()
}
/**
This type method is used to determine if application is run in emulator
Usage example
```
let runInEmulator: Bool = IOSSecuritySuite.amIRunInEmulator()
```
*/
public static func amIRunInEmulator() -> Bool {
return EmulatorChecker.amIRunInEmulator()
}
/**
This type method is used to determine if application is being debugged
Usage example
```
let amIDebugged: Bool = IOSSecuritySuite.amIDebugged()
```
*/
public static func amIDebugged() -> Bool {
return DebuggerChecker.amIDebugged()
}
/**
This type method is used to deny debugger and improve the application resillency
Usage example
```
IOSSecuritySuite.denyDebugger()
```
*/
public static func denyDebugger() {
return DebuggerChecker.denyDebugger()
}
/**
This type method is used to determine if application has been tampered with
Usage example
```
if IOSSecuritySuite.amITampered([.bundleID("biz.securing.FrameworkClientApp"), .mobileProvision("your-mobile-provision-sha256-value")]).result {
print("I have been Tampered.")
}
else {
print("I have not been Tampered.")
}
```
- Parameter checks: The file Integrity checks you want
- Returns: The file Integrity checker result
*/
public static func amITampered(_ checks: [FileIntegrityCheck]) -> FileIntegrityCheckResult {
return IntegrityChecker.amITampered(checks)
}
/**
This type method is used to determine if there are any popular reverse engineering tools installed on the device
Usage example
```
let amIReverseEngineered: Bool = IOSSecuritySuite.amIReverseEngineered()
```
*/
public static func amIReverseEngineered() -> Bool {
return ReverseEngineeringToolsChecker.amIReverseEngineered()
}
/**
This type method is used to determine if `objc call` has been RuntimeHooked by for example `Flex`
Usage example
```
class SomeClass {
@objc dynamic func someFunction() {
}
}
let dylds = ["IOSSecuritySuite", ...]
let amIRuntimeHook: Bool = amIRuntimeHook(dyldWhiteList: dylds, detectionClass: SomeClass.self, selector: #selector(SomeClass.someFunction), isClassMethod: false)
```
*/
public static func amIRuntimeHooked(dyldWhiteList: [String], detectionClass: AnyClass, selector: Selector, isClassMethod: Bool) -> Bool {
return RuntimeHookChecker.amIRuntimeHook(dyldWhiteList: dyldWhiteList, detectionClass: detectionClass, selector: selector, isClassMethod: isClassMethod)
}
/**
This type method is used to determine if HTTP proxy was set in the iOS Settings.
Usage example
```
let amIProxied: Bool = IOSSecuritySuite.amIProxied()
```
*/
public static func amIProxied() -> Bool {
return ProxyChecker.amIProxied()
}
}
#if arch(arm64)
public extension IOSSecuritySuite {
/**
This type method is used to determine if `function_address` has been hooked by `MSHook`
Usage example
```
func denyDebugger() {
}
typealias FunctionType = @convention(thin) ()->()
let func_denyDebugger: FunctionType = denyDebugger // `: FunctionType` is must
let func_addr = unsafeBitCast(func_denyDebugger, to: UnsafeMutableRawPointer.self)
let amIMSHookFunction: Bool = amIMSHookFunction(func_addr)
```
*/
static func amIMSHooked(_ functionAddress: UnsafeMutableRawPointer) -> Bool {
return MSHookFunctionChecker.amIMSHooked(functionAddress)
}
/**
This type method is used to get original `function_address` which has been hooked by `MSHook`
Usage example
```
func denyDebugger(value: Int) {
}
typealias FunctionType = @convention(thin) (Int)->()
let funcDenyDebugger: FunctionType = denyDebugger
let funcAddr = unsafeBitCast(funcDenyDebugger, to: UnsafeMutableRawPointer.self)
if let originalDenyDebugger = denyMSHook(funcAddr) {
unsafeBitCast(originalDenyDebugger, to: FunctionType.self)(1337) //Call orignal function with 1337 as Int argument
} else {
denyDebugger()
}
```
*/
static func denyMSHook(_ functionAddress: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? {
return MSHookFunctionChecker.denyMSHook(functionAddress)
}
/**
This type method is used to rebind `symbol` which has been hooked by `fishhook`
Usage example
```
denySymbolHook("$s10Foundation5NSLogyySS_s7CVarArg_pdtF") // Foudation's NSlog of Swift
NSLog("Hello Symbol Hook")
denySymbolHook("abort")
abort()
```
*/
static func denySymbolHook(_ symbol: String) {
FishHookChecker.denyFishHook(symbol)
}
/**
This type method is used to rebind `symbol` which has been hooked at one of image by `fishhook`
Usage example
```
for i in 0..<_dyld_image_count() {
if let imageName = _dyld_get_image_name(i) {
let name = String(cString: imageName)
if name.contains("IOSSecuritySuite"), let image = _dyld_get_image_header(i) {
denySymbolHook("dlsym", at: image, imageSlide: _dyld_get_image_vmaddr_slide(i))
break
}
}
}
```
*/
static func denySymbolHook(_ symbol: String, at image: UnsafePointer<mach_header>, imageSlide slide: Int) {
FishHookChecker.denyFishHook(symbol, at: image, imageSlide: slide)
}
/**
This type method is used to get the SHA256 hash value of the executable file in a specified image
**Dylib only.** This means you should set Mach-O type as `Dynamic Library` in your *Build Settings*.
Calculate the hash value of the `__TEXT.__text` data of the specified image Mach-O file.
Usage example
```
// Manually verify SHA256 hash value of a loaded dylib
if let hashValue = IOSSecuritySuite.getMachOFileHashValue(.custom("IOSSecuritySuite")), hashValue == "6d8d460b9a4ee6c0f378e30f137cebaf2ce12bf31a2eef3729c36889158aa7fc" {
print("I have not been Tampered.")
}
else {
print("I have been Tampered.")
}
```
- Parameter target: The target image
- Returns: A hash value of the executable file.
*/
static func getMachOFileHashValue(_ target: IntegrityCheckerImageTarget = .default) -> String? {
return IntegrityChecker.getMachOFileHashValue(target)
}
/**
This type method is used to find all loaded dylibs in the specified image
**Dylib only.** This means you should set Mach-O type as `Dynamic Library` in your *Build Settings*.
Usage example
```
if let loadedDylib = IOSSecuritySuite.findLoadedDylibs() {
print("Loaded dylibs: \(loadedDylib)")
}
```
- Parameter target: The target image
- Returns: An Array with all loaded dylib names
*/
static func findLoadedDylibs(_ target: IntegrityCheckerImageTarget = .default) -> [String]? {
return IntegrityChecker.findLoadedDylibs(target)
}
/**
This type method is used to determine if there are any breakpoints at the function
Usage example
```
func denyDebugger() {
// add a breakpoint at here to test
}
typealias FunctionType = @convention(thin) ()->()
let func_denyDebugger: FunctionType = denyDebugger // `: FunctionType` is a must
let func_addr = unsafeBitCast(func_denyDebugger, to: UnsafeMutableRawPointer.self)
let hasBreakpoint: Bool = IOSSecuritySuite.hasBreakpointAt(func_addr, functionSize: nil)
```
*/
static func hasBreakpointAt(_ functionAddr: UnsafeRawPointer, functionSize: vm_size_t?) -> Bool {
return DebuggerChecker.hasBreakpointAt(functionAddr, functionSize: functionSize)
}
}
#endif
| 32.307692 | 174 | 0.664087 |
1430601e7a3a589987a010d2b48ed1de6baf8544 | 686 | //
// UITableViewCell+RxReusable.swift
// RxReusable
//
// Created by Suyeol Jeon on 29/11/2016.
// Copyright © 2016 Suyeol Jeon. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
#if os(iOS)
extension UITableViewCell: RxReusableType {
public static let initializer: Void = {
swizzle()
}()
static func swizzle() {
guard self === UITableViewCell.self else { return }
UITableViewCell._rxreusable_swizzle(
#selector(UITableViewCell.prepareForReuse),
#selector(UITableViewCell._rxreusable_prepareForReuse)
)
}
@objc func _rxreusable_prepareForReuse() {
self._rxreusable_prepareForReuse()
self.dispose()
}
}
#endif
| 19.055556 | 60 | 0.709913 |
14e391a6bd2c684e0e7ee6cc1aeb471eb112b3da | 797 | //
// AccountLevelStatus.swift
// FintechPlatform
//
// Created by Matteo Stefanini on 29/08/2018.
// Copyright © 2018 Fintech Platform. All rights reserved.
//
import Foundation
public enum AccountLevelStatus: String, Codable {
case LEVEL1_WAITING_CREATION = "LEVEL1_WAITING_CREATION"
case LEVEL1_CREATED = "LEVEL1_CREATED"
case REQUEST_UPGRADE_TO_LEVEL2 = "REQUEST_UPGRADE_TO_LEVEL2"
case LEVEL2_WAITING_UPGRADE = "LEVEL2_WAITING_UPGRADE"
case LEVEL2_UPGRADED = "LEVEL2_UPGRADED"
case LEVEL2_REFUSED_UPGRADE = "LEVEL2_REFUSED_UPGRADE"
case REQUEST_UPGRADE_TO_LEVEL3 = "REQUEST_UPGRADE_TO_LEVEL3"
case LEVEL3_WAITING_UPGRADE = "LEVEL3_WAITING_UPGRADE"
case LEVEL3_UPGRADED = "LEVEL3_UPGRADED"
case LEVEL3_REFUSED_UPGRADE = "LEVEL3_REFUSED_UPGRADE"
}
| 34.652174 | 64 | 0.782936 |
7a412ecc9296f7936c24cd89685af0e4a4296995 | 1,749 | //
// ScrumData.swift
// scrumdinger
//
// Created by An Trinh on 26/12/20.
//
import Foundation
class ScrumData: ObservableObject {
@Published var scrums: [DailyScrum] = []
func load() {
DispatchQueue.global(qos: .background).async { [weak self] in
guard let data = try? Data(contentsOf: Self.fileURL) else {
#if DEBUG
DispatchQueue.main.async {
self?.scrums = DailyScrum.data
}
#endif
return
}
guard let dailyScrums = try? JSONDecoder().decode([DailyScrum].self, from: data) else {
fatalError("Can't decode saved scrum data.")
}
DispatchQueue.main.async {
self?.scrums = dailyScrums
}
}
}
func save() {
DispatchQueue.global(qos: .background).async { [weak self] in
guard let scrums = self?.scrums else { fatalError("Self out of scope") }
guard let data = try? JSONEncoder().encode(scrums) else { fatalError("Error encoding data") }
do {
let outfile = Self.fileURL
try data.write(to: outfile)
} catch {
fatalError("Can't write to file")
}
}
}
// MARK: - Helpers
private static var documentsFolder: URL {
do {
return try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
} catch {
fatalError("Can't find documents directory.")
}
}
private static var fileURL: URL {
documentsFolder.appendingPathComponent("scrums.data")
}
}
| 29.644068 | 128 | 0.533448 |
67a8f0b9298ccf866ef48d7dd10492d6fbdfdc17 | 2,187 | //
// AppDelegate.swift
// HelloTigerProtocol
//
// Created by Sebastian Buys on 3/7/19.
// Copyright © 2019 Sebastian Buys. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.531915 | 285 | 0.756287 |
087a8e861538e97755a25e1117e5d5464ef42ec6 | 610 | //
// RootBoard.swift
// ___VARIABLE_moduleName___
//
// Created by BOARDY on 10/22/21.
//
//
import Boardy
import Foundation
import __DAD__IO
enum ___VARIABLE_moduleName___BoardFactory {
static func make(identifier: BoardID, producer: ActivableBoardProducer) -> ActivatableBoard {
FlowBoard<___VARIABLE_moduleName___Input, ___VARIABLE_moduleName___Output, ___VARIABLE_moduleName___Command, ___VARIABLE_moduleName___Action>(identifier: identifier, producer: producer) { it in
<#register flows#>
} flowActivation: { it, input in
<#activate#>
}
}
}
| 27.727273 | 201 | 0.721311 |
2616c645852a6b6051fe9afbb3ba90e8022ef71d | 55,002 | //////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
// Copyright (c) 2014-2017 Dalton Cherry.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import CoreFoundation
import CommonCrypto
public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification"
public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification"
public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName"
//Standard WebSocket close codes
public enum CloseCode : UInt16 {
case normal = 1000
case goingAway = 1001
case protocolError = 1002
case protocolUnhandledType = 1003
// 1004 reserved.
case noStatusReceived = 1005
//1006 reserved.
case encoding = 1007
case policyViolated = 1008
case messageTooBig = 1009
}
public enum ErrorType: Error {
case outputStreamWriteError //output stream error during write
case compressionError
case invalidSSLError //Invalid SSL certificate
case writeTimeoutError //The socket timed out waiting to be ready to write
case protocolError //There was an error parsing the WebSocket frames
case upgradeError //There was an error during the HTTP upgrade
case closeError //There was an error during the close (socket probably has been dereferenced)
}
public struct WSError: Error {
public let type: ErrorType
public let message: String
public let code: Int
}
//WebSocketClient is setup to be dependency injection for testing
public protocol WebSocketClient: class {
var delegate: WebSocketDelegate? {get set}
var pongDelegate: WebSocketPongDelegate? {get set}
var disableSSLCertValidation: Bool {get set}
var overrideTrustHostname: Bool {get set}
var desiredTrustHostname: String? {get set}
var sslClientCertificate: SSLClientCertificate? {get set}
#if os(Linux)
#else
var security: SSLTrustValidator? {get set}
var enabledSSLCipherSuites: [SSLCipherSuite]? {get set}
#endif
var isConnected: Bool {get}
func connect()
func disconnect(forceTimeout: TimeInterval?, closeCode: UInt16)
func write(string: String, completion: (() -> ())?)
func write(data: Data, completion: (() -> ())?)
func write(ping: Data, completion: (() -> ())?)
func write(pong: Data, completion: (() -> ())?)
}
//implements some of the base behaviors
extension WebSocketClient {
public func write(string: String) {
write(string: string, completion: nil)
}
public func write(data: Data) {
write(data: data, completion: nil)
}
public func write(ping: Data) {
write(ping: ping, completion: nil)
}
public func write(pong: Data) {
write(pong: pong, completion: nil)
}
public func disconnect() {
disconnect(forceTimeout: nil, closeCode: CloseCode.normal.rawValue)
}
}
//SSL settings for the stream
public struct SSLSettings {
public let useSSL: Bool
public let disableCertValidation: Bool
public var overrideTrustHostname: Bool
public var desiredTrustHostname: String?
public let sslClientCertificate: SSLClientCertificate?
#if os(Linux)
#else
public let cipherSuites: [SSLCipherSuite]?
#endif
}
public protocol WSStreamDelegate: class {
func newBytesInStream()
func streamDidError(error: Error?)
}
//This protocol is to allow custom implemention of the underlining stream. This way custom socket libraries (e.g. linux) can be used
public protocol WSStream {
var delegate: WSStreamDelegate? {get set}
func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void))
func write(data: Data) -> Int
func read() -> Data?
func cleanup()
#if os(Linux) || os(watchOS)
#else
func sslTrust() -> (trust: SecTrust?, domain: String?)
#endif
}
open class FoundationStream : NSObject, WSStream, StreamDelegate {
private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: [])
private var inputStream: InputStream?
private var outputStream: OutputStream?
public weak var delegate: WSStreamDelegate?
let BUFFER_MAX = 4096
public var enableSOCKSProxy = false
public func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h = url.host! as NSString
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
if enableSOCKSProxy {
let proxyDict = CFNetworkCopySystemProxySettings()
let socksConfig = CFDictionaryCreateMutableCopy(nil, 0, proxyDict!.takeRetainedValue())
let propertyKey = CFStreamPropertyKey(rawValue: kCFStreamPropertySOCKSProxy)
CFWriteStreamSetProperty(outputStream, propertyKey, socksConfig)
CFReadStreamSetProperty(inputStream, propertyKey, socksConfig)
}
#endif
guard let inStream = inputStream, let outStream = outputStream else { return }
inStream.delegate = self
outStream.delegate = self
if ssl.useSSL {
inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
var settings = [NSObject: NSObject]()
if ssl.disableCertValidation {
settings[kCFStreamSSLValidatesCertificateChain] = NSNumber(value: false)
}
if ssl.overrideTrustHostname {
if let hostname = ssl.desiredTrustHostname {
settings[kCFStreamSSLPeerName] = hostname as NSString
} else {
settings[kCFStreamSSLPeerName] = kCFNull
}
}
if let sslClientCertificate = ssl.sslClientCertificate {
settings[kCFStreamSSLCertificates] = sslClientCertificate.streamSSLCertificates
}
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
#endif
#if os(Linux)
#else
if let cipherSuites = ssl.cipherSuites {
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
completion(WSError(type: .invalidSSLError, message: "Error setting ingoing cypher suites", code: Int(resIn)))
}
if resOut != errSecSuccess {
completion(WSError(type: .invalidSSLError, message: "Error setting outgoing cypher suites", code: Int(resOut)))
}
}
#endif
}
#endif
}
CFReadStreamSetDispatchQueue(inStream, FoundationStream.sharedWorkQueue)
CFWriteStreamSetDispatchQueue(outStream, FoundationStream.sharedWorkQueue)
inStream.open()
outStream.open()
var out = timeout// wait X seconds before giving up
FoundationStream.sharedWorkQueue.async { [weak self] in
while !outStream.hasSpaceAvailable {
usleep(100) // wait until the socket is ready
out -= 100
if out < 0 {
completion(WSError(type: .writeTimeoutError, message: "Timed out waiting for the socket to be ready for a write", code: 0))
return
} else if let error = outStream.streamError {
completion(error)
return // disconnectStream will be called.
} else if self == nil {
completion(WSError(type: .closeError, message: "socket object has been dereferenced", code: 0))
return
}
}
completion(nil) //success!
}
}
public func write(data: Data) -> Int {
guard let outStream = outputStream else {return -1}
let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self)
return outStream.write(buffer, maxLength: data.count)
}
public func read() -> Data? {
guard let stream = inputStream else {return nil}
let buf = NSMutableData(capacity: BUFFER_MAX)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
let length = stream.read(buffer, maxLength: BUFFER_MAX)
if length < 1 {
return nil
}
return Data(bytes: buffer, count: length)
}
public func cleanup() {
if let stream = inputStream {
stream.delegate = nil
CFReadStreamSetDispatchQueue(stream, nil)
stream.close()
}
if let stream = outputStream {
stream.delegate = nil
CFWriteStreamSetDispatchQueue(stream, nil)
stream.close()
}
outputStream = nil
inputStream = nil
}
#if os(Linux) || os(watchOS)
#else
public func sslTrust() -> (trust: SecTrust?, domain: String?) {
guard let outputStream = outputStream else { return (nil, nil) }
let trust = outputStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust?
var domain = outputStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as! String?
if domain == nil,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
var peerNameLen: Int = 0
SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen)
var peerName = Data(count: peerNameLen)
let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer<Int8>) in
SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen)
}
if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 {
domain = peerDomain
}
}
return (trust, domain)
}
#endif
/**
Delegate for the stream methods. Processes incoming bytes
*/
open func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
if eventCode == .hasBytesAvailable {
if aStream == inputStream {
delegate?.newBytesInStream()
}
} else if eventCode == .errorOccurred {
delegate?.streamDidError(error: aStream.streamError)
} else if eventCode == .endEncountered {
delegate?.streamDidError(error: nil)
}
}
}
//WebSocket implementation
//standard delegate you should use
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocketClient)
func websocketDidDisconnect(socket: WebSocketClient, error: Error?)
func websocketDidReceiveMessage(socket: WebSocketClient, text: String)
func websocketDidReceiveData(socket: WebSocketClient, data: Data)
}
//got pongs
public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocketClient, data: Data?)
}
// A Delegate with more advanced info on messages and connection etc.
public protocol WebSocketAdvancedDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: Error?)
func websocketDidReceiveMessage(socket: WebSocket, text: String, response: WebSocket.WSResponse)
func websocketDidReceiveData(socket: WebSocket, data: Data, response: WebSocket.WSResponse)
func websocketHttpUpgrade(socket: WebSocket, request: String)
func websocketHttpUpgrade(socket: WebSocket, response: String)
}
open class WebSocket : NSObject, StreamDelegate, WebSocketClient, WSStreamDelegate {
public enum OpCode : UInt8 {
case continueFrame = 0x0
case textFrame = 0x1
case binaryFrame = 0x2
// 3-7 are reserved.
case connectionClose = 0x8
case ping = 0x9
case pong = 0xA
// B-F reserved.
}
public static let ErrorDomain = "WebSocket"
// Where the callback is executed. It defaults to the main UI thread queue.
public var callbackQueue = DispatchQueue.main
// MARK: - Constants
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSExtensionName = "Sec-WebSocket-Extensions"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 4096
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let RSV1Mask: UInt8 = 0x40
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
let httpSwitchProtocolCode = 101
let supportedSSLSchemes = ["wss", "https"]
public class WSResponse {
var isFin = false
public var code: OpCode = .continueFrame
var bytesLeft = 0
public var frameCount = 0
public var buffer: NSMutableData?
public let firstFrame = {
return Date()
}()
}
// MARK: - Delegates
/// Responds to callback about new messages coming in over the WebSocket
/// and also connection/disconnect messages.
public weak var delegate: WebSocketDelegate?
/// The optional advanced delegate can be used instead of of the delegate
public weak var advancedDelegate: WebSocketAdvancedDelegate?
/// Receives a callback for each pong message recived.
public weak var pongDelegate: WebSocketPongDelegate?
public var onConnect: (() -> Void)?
public var onDisconnect: ((Error?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((Data) -> Void)?
public var onPong: ((Data?) -> Void)?
public var onHttpResponseHeaders: (([String: String]) -> Void)?
public var disableSSLCertValidation = false
public var overrideTrustHostname = false
public var desiredTrustHostname: String? = nil
public var sslClientCertificate: SSLClientCertificate? = nil
public var enableCompression = true
#if os(Linux)
#else
public var security: SSLTrustValidator?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
#endif
public var isConnected: Bool {
mutex.lock()
let isConnected = connected
mutex.unlock()
return isConnected
}
public var request: URLRequest //this is only public to allow headers, timeout, etc to be modified on reconnect
public var currentURL: URL { return request.url! }
public var respondToPingWithPong: Bool = true
// MARK: - Private
private struct CompressionState {
var supportsCompression = false
var messageNeedsDecompression = false
var serverMaxWindowBits = 15
var clientMaxWindowBits = 15
var clientNoContextTakeover = false
var serverNoContextTakeover = false
var decompressor:Decompressor? = nil
var compressor:Compressor? = nil
}
private var stream: WSStream
private var connected = false
private var isConnecting = false
private let mutex = NSLock()
private var compressionState = CompressionState()
private var writeQueue = OperationQueue()
private var readStack = [WSResponse]()
private var inputQueue = [Data]()
private var fragBuffer: Data?
private var certValidated = false
private var didDisconnect = false
private var readyToWrite = false
private var headerSecKey = ""
private var canDispatch: Bool {
mutex.lock()
let canWork = readyToWrite
mutex.unlock()
return canWork
}
/// Used for setting protocols.
public init(request: URLRequest, protocols: [String]? = nil, stream: WSStream = FoundationStream()) {
self.request = request
self.stream = stream
if request.value(forHTTPHeaderField: headerOriginName) == nil {
guard let url = request.url else {return}
var origin = url.absoluteString
if let hostUrl = URL (string: "/", relativeTo: url) {
origin = hostUrl.absoluteString
origin.remove(at: origin.index(before: origin.endIndex))
}
self.request.setValue(origin, forHTTPHeaderField: headerOriginName)
}
if let protocols = protocols, !protocols.isEmpty {
self.request.setValue(protocols.joined(separator: ","), forHTTPHeaderField: headerWSProtocolName)
}
writeQueue.maxConcurrentOperationCount = 1
}
public convenience init(url: URL, protocols: [String]? = nil) {
var request = URLRequest(url: url)
request.timeoutInterval = 5
self.init(request: request, protocols: protocols)
}
// Used for specifically setting the QOS for the write queue.
public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) {
self.init(url: url, protocols: protocols)
writeQueue.qualityOfService = writeQueueQOS
}
/**
Connect to the WebSocket server on a background thread.
*/
open func connect() {
guard !isConnecting else { return }
didDisconnect = false
isConnecting = true
createHTTPRequest()
}
/**
Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed.
If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate.
If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate.
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
- Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket.
*/
open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) {
guard isConnected else { return }
switch forceTimeout {
case .some(let seconds) where seconds > 0:
let milliseconds = Int(seconds * 1_000)
callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in
self?.disconnectStream(nil)
}
fallthrough
case .none:
writeError(closeCode)
default:
disconnectStream(nil)
break
}
}
/**
Write a string to the websocket. This sends it as a text frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter string: The string to write.
- parameter completion: The (optional) completion handler.
*/
open func write(string: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion)
}
/**
Write binary data to the websocket. This sends it as a binary frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
open func write(data: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .binaryFrame, writeCompletion: completion)
}
/**
Write a ping to the websocket. This sends it as a control frame.
Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
*/
open func write(ping: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(ping, code: .ping, writeCompletion: completion)
}
/**
Write a pong to the websocket. This sends it as a control frame.
Respond to a Yodel.
*/
open func write(pong: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(pong, code: .pong, writeCompletion: completion)
}
/**
Private method that starts the connection.
*/
private func createHTTPRequest() {
guard let url = request.url else {return}
var port = url.port
if port == nil {
if supportedSSLSchemes.contains(url.scheme!) {
port = 443
} else {
port = 80
}
}
request.setValue(headerWSUpgradeValue, forHTTPHeaderField: headerWSUpgradeName)
request.setValue(headerWSConnectionValue, forHTTPHeaderField: headerWSConnectionName)
headerSecKey = generateWebSocketKey()
request.setValue(headerWSVersionValue, forHTTPHeaderField: headerWSVersionName)
request.setValue(headerSecKey, forHTTPHeaderField: headerWSKeyName)
if enableCompression {
let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15"
request.setValue(val, forHTTPHeaderField: headerWSExtensionName)
}
let hostValue = request.allHTTPHeaderFields?[headerWSHostName] ?? "\(url.host!):\(port!)"
request.setValue(hostValue, forHTTPHeaderField: headerWSHostName)
var path = url.absoluteString
let offset = (url.scheme?.count ?? 2) + 3
path = String(path[path.index(path.startIndex, offsetBy: offset)..<path.endIndex])
if let range = path.range(of: "/") {
path = String(path[range.lowerBound..<path.endIndex])
} else {
path = "/"
if let query = url.query {
path += "?" + query
}
}
var httpBody = "\(request.httpMethod ?? "GET") \(path) HTTP/1.1\r\n"
if let headers = request.allHTTPHeaderFields {
for (key, val) in headers {
httpBody += "\(key): \(val)\r\n"
}
}
httpBody += "\r\n"
initStreamsWithData(httpBody.data(using: .utf8)!, Int(port!))
advancedDelegate?.websocketHttpUpgrade(socket: self, request: httpBody)
}
/**
Generate a WebSocket key as needed in RFC.
*/
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for _ in 0..<seed {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni!))"
}
let data = key.data(using: String.Encoding.utf8)
let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return baseKey!
}
/**
Start the stream connection and write the data to the output stream.
*/
private func initStreamsWithData(_ data: Data, _ port: Int) {
guard let url = request.url else {
disconnectStream(nil, runDelegate: true)
return
}
// Disconnect and clean up any existing streams before setting up a new pair
disconnectStream(nil, runDelegate: false)
let useSSL = supportedSSLSchemes.contains(url.scheme!)
#if os(Linux)
let settings = SSLSettings(useSSL: useSSL,
disableCertValidation: disableSSLCertValidation,
overrideTrustHostname: overrideTrustHostname,
desiredTrustHostname: desiredTrustHostname),
sslClientCertificate: sslClientCertificate
#else
let settings = SSLSettings(useSSL: useSSL,
disableCertValidation: disableSSLCertValidation,
overrideTrustHostname: overrideTrustHostname,
desiredTrustHostname: desiredTrustHostname,
sslClientCertificate: sslClientCertificate,
cipherSuites: self.enabledSSLCipherSuites)
#endif
certValidated = !useSSL
let timeout = request.timeoutInterval * 1_000_000
stream.delegate = self
stream.connect(url: url, port: port, timeout: timeout, ssl: settings, completion: { [weak self] (error) in
guard let self = self else {return}
if error != nil {
self.disconnectStream(error)
return
}
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
guard let sOperation = operation, let self = self else { return }
guard !sOperation.isCancelled else { return }
// Do the pinning now if needed
#if os(Linux) || os(watchOS)
self.certValidated = false
#else
if let sec = self.security, !self.certValidated {
let trustObj = self.stream.sslTrust()
if let possibleTrust = trustObj.trust {
self.certValidated = sec.isValid(possibleTrust, domain: trustObj.domain)
} else {
self.certValidated = false
}
if !self.certValidated {
self.disconnectStream(WSError(type: .invalidSSLError, message: "Invalid SSL certificate", code: 0))
return
}
}
#endif
let _ = self.stream.write(data: data)
}
self.writeQueue.addOperation(operation)
})
self.mutex.lock()
self.readyToWrite = true
self.mutex.unlock()
}
/**
Delegate for the stream methods. Processes incoming bytes
*/
public func newBytesInStream() {
processInputStream()
}
public func streamDidError(error: Error?) {
disconnectStream(error)
}
/**
Disconnect the stream object and notifies the delegate.
*/
private func disconnectStream(_ error: Error?, runDelegate: Bool = true) {
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
mutex.lock()
cleanupStream()
connected = false
mutex.unlock()
if runDelegate {
doDisconnect(error)
}
}
/**
cleanup the streams.
*/
private func cleanupStream() {
stream.cleanup()
fragBuffer = nil
}
/**
Handles the incoming bytes and sending them to the proper processing method.
*/
private func processInputStream() {
let data = stream.read()
guard let d = data else { return }
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(d)
if process {
dequeueInput()
}
}
/**
Dequeue the incoming input so it is processed in order.
*/
private func dequeueInput() {
while !inputQueue.isEmpty {
autoreleasepool {
let data = inputQueue[0]
var work = data
if let buffer = fragBuffer {
var combine = NSData(data: buffer) as Data
combine.append(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self)
let length = work.count
if !connected {
processTCPHandshake(buffer, bufferLen: length)
} else {
processRawMessagesInBuffer(buffer, bufferLen: length)
}
inputQueue = inputQueue.filter{ $0 != data }
}
}
}
/**
Handle checking the inital connection status
*/
private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) {
let code = processHTTP(buffer, bufferLen: bufferLen)
switch code {
case 0:
break
case -1:
fragBuffer = Data(bytes: buffer, count: bufferLen)
break // do nothing, we are going to collect more data
default:
doDisconnect(WSError(type: .upgradeError, message: "Invalid HTTP upgrade", code: code))
}
}
/**
Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
*/
private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for i in 0..<bufferLen {
if buffer[i] == CRLFBytes[k] {
k += 1
if k == 4 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
let code = validateResponse(buffer, bufferLen: totalSize)
if code != 0 {
return code
}
isConnecting = false
mutex.lock()
connected = true
mutex.unlock()
didDisconnect = false
if canDispatch {
callbackQueue.async { [weak self] in
guard let self = self else { return }
self.onConnect?()
self.delegate?.websocketDidConnect(socket: self)
self.advancedDelegate?.websocketDidConnect(socket: self)
NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self)
}
}
//totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize)
}
return 0 //success
}
return -1 // Was unable to find the full TCP header.
}
/**
Validates the HTTP is a 101 as per the RFC spec.
*/
private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
guard let str = String(data: Data(bytes: buffer, count: bufferLen), encoding: .utf8) else { return -1 }
let splitArr = str.components(separatedBy: "\r\n")
var code = -1
var i = 0
var headers = [String: String]()
for str in splitArr {
if i == 0 {
let responseSplit = str.components(separatedBy: .whitespaces)
guard responseSplit.count > 1 else { return -1 }
if let c = Int(responseSplit[1]) {
code = c
}
} else {
let responseSplit = str.components(separatedBy: ":")
guard responseSplit.count > 1 else { break }
let key = responseSplit[0].trimmingCharacters(in: .whitespaces)
let val = responseSplit[1].trimmingCharacters(in: .whitespaces)
headers[key.lowercased()] = val
}
i += 1
}
advancedDelegate?.websocketHttpUpgrade(socket: self, response: str)
onHttpResponseHeaders?(headers)
if code != httpSwitchProtocolCode {
return code
}
if let extensionHeader = headers[headerWSExtensionName.lowercased()] {
processExtensionHeader(extensionHeader)
}
if let acceptKey = headers[headerWSAcceptName.lowercased()] {
if acceptKey.count > 0 {
if headerSecKey.count > 0 {
let sha = "\(headerSecKey)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64()
if sha != acceptKey as String {
return -1
}
}
return 0
}
}
return -1
}
/**
Parses the extension header, setting up the compression parameters.
*/
func processExtensionHeader(_ extensionHeader: String) {
let parts = extensionHeader.components(separatedBy: ";")
for p in parts {
let part = p.trimmingCharacters(in: .whitespaces)
if part == "permessage-deflate" {
compressionState.supportsCompression = true
} else if part.hasPrefix("server_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.serverMaxWindowBits = val
}
} else if part.hasPrefix("client_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.clientMaxWindowBits = val
}
} else if part == "client_no_context_takeover" {
compressionState.clientNoContextTakeover = true
} else if part == "server_no_context_takeover" {
compressionState.serverNoContextTakeover = true
}
}
if compressionState.supportsCompression {
compressionState.decompressor = Decompressor(windowBits: compressionState.serverMaxWindowBits)
compressionState.compressor = Compressor(windowBits: compressionState.clientMaxWindowBits)
}
}
/**
Read a 16 bit big endian value from a buffer
*/
private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
}
/**
Read a 64 bit big endian value from a buffer
*/
private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
var value = UInt64(0)
for i in 0...7 {
value = (value << 8) | UInt64(buffer[offset + i])
}
return value
}
/**
Write a 16-bit big endian value to a buffer.
*/
private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
buffer[offset + 0] = UInt8(value >> 8)
buffer[offset + 1] = UInt8(value & 0xff)
}
/**
Write a 64-bit big endian value to a buffer.
*/
private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
for i in 0...7 {
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
}
}
/**
Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
*/
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
let response = readStack.last
guard let baseAddress = buffer.baseAddress else {return emptyBuffer}
let bufferLen = buffer.count
if response != nil && bufferLen < 2 {
fragBuffer = Data(buffer: buffer)
return emptyBuffer
}
if let response = response, response.bytesLeft > 0 {
var len = response.bytesLeft
var extra = bufferLen - response.bytesLeft
if response.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
response.bytesLeft -= len
response.buffer?.append(Data(bytes: baseAddress, count: len))
_ = processResponse(response)
return buffer.fromOffset(bufferLen - extra)
} else {
let isFin = (FinMask & baseAddress[0])
let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0])
let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue)
let isMasked = (MaskMask & baseAddress[1])
let payloadLen = (PayloadLenMask & baseAddress[1])
var offset = 2
if compressionState.supportsCompression && receivedOpcode != .continueFrame {
compressionState.messageNeedsDecompression = (RSV1Mask & baseAddress[0]) > 0
}
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong && !compressionState.messageNeedsDecompression {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "masked and rsv data is not currently supported", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping)
if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame &&
receivedOpcode != .textFrame && receivedOpcode != .pong) {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "unknown opcode: \(receivedOpcodeRawValue)", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "control frames can't be fragmented", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
var closeCode = CloseCode.normal.rawValue
if receivedOpcode == .connectionClose {
if payloadLen == 1 {
closeCode = CloseCode.protocolError.rawValue
} else if payloadLen > 1 {
closeCode = WebSocket.readUint16(baseAddress, offset: offset)
if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) {
closeCode = CloseCode.protocolError.rawValue
}
}
if payloadLen < 2 {
doDisconnect(WSError(type: .protocolError, message: "connection closed by server", code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
} else if isControlFrame && payloadLen > 125 {
writeError(CloseCode.protocolError.rawValue)
return emptyBuffer
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
dataLength = WebSocket.readUint64(baseAddress, offset: offset)
offset += MemoryLayout<UInt64>.size
} else if dataLength == 126 {
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
offset += MemoryLayout<UInt16>.size
}
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = Data(bytes: baseAddress, count: bufferLen)
return emptyBuffer
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
if receivedOpcode == .connectionClose && len > 0 {
let size = MemoryLayout<UInt16>.size
offset += size
len -= UInt64(size)
}
let data: Data
if compressionState.messageNeedsDecompression, let decompressor = compressionState.decompressor {
do {
data = try decompressor.decompress(bytes: baseAddress+offset, count: Int(len), finish: isFin > 0)
if isFin > 0 && compressionState.serverNoContextTakeover {
try decompressor.reset()
}
} catch {
let closeReason = "Decompression failed: \(error)"
let closeCode = CloseCode.encoding.rawValue
doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
} else {
data = Data(bytes: baseAddress+offset, count: Int(len))
}
if receivedOpcode == .connectionClose {
var closeReason = "connection closed by server"
if let customCloseReason = String(data: data, encoding: .utf8) {
closeReason = customCloseReason
} else {
closeCode = CloseCode.protocolError.rawValue
}
doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
if receivedOpcode == .pong {
if canDispatch {
callbackQueue.async { [weak self] in
guard let self = self else { return }
let pongData: Data? = data.count > 0 ? data : nil
self.onPong?(pongData)
self.pongDelegate?.websocketDidReceivePong(socket: self, data: pongData)
}
}
return buffer.fromOffset(offset + Int(len))
}
var response = readStack.last
if isControlFrame {
response = nil // Don't append pings.
}
if isFin == 0 && receivedOpcode == .continueFrame && response == nil {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "continue frame before a binary or text frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
var isNew = false
if response == nil {
if receivedOpcode == .continueFrame {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "first frame can't be a continue frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
isNew = true
response = WSResponse()
response!.code = receivedOpcode!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == .continueFrame {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "second and beyond of fragment message must be a continue frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
response!.buffer!.append(data)
}
if let response = response {
response.bytesLeft -= Int(len)
response.frameCount += 1
response.isFin = isFin > 0 ? true : false
if isNew {
readStack.append(response)
}
_ = processResponse(response)
}
let step = Int(offset + numericCast(len))
return buffer.fromOffset(step)
}
}
/**
Process all messages in the buffer if possible.
*/
private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) {
var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen)
repeat {
buffer = processOneRawMessage(inBuffer: buffer)
} while buffer.count >= 2
if buffer.count > 0 {
fragBuffer = Data(buffer: buffer)
}
}
/**
Process the finished response of a buffer.
*/
private func processResponse(_ response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .ping {
if respondToPingWithPong {
let data = response.buffer! // local copy so it is perverse for writing
dequeueWrite(data as Data, code: .pong)
}
} else if response.code == .textFrame {
guard let str = String(data: response.buffer! as Data, encoding: .utf8) else {
writeError(CloseCode.encoding.rawValue)
return false
}
if canDispatch {
callbackQueue.async { [weak self] in
guard let self = self else { return }
self.onText?(str)
self.delegate?.websocketDidReceiveMessage(socket: self, text: str)
self.advancedDelegate?.websocketDidReceiveMessage(socket: self, text: str, response: response)
}
}
} else if response.code == .binaryFrame {
if canDispatch {
let data = response.buffer! // local copy so it is perverse for writing
callbackQueue.async { [weak self] in
guard let self = self else { return }
self.onData?(data as Data)
self.delegate?.websocketDidReceiveData(socket: self, data: data as Data)
self.advancedDelegate?.websocketDidReceiveData(socket: self, data: data as Data, response: response)
}
}
}
readStack.removeLast()
return true
}
return false
}
/**
Write an error to the socket
*/
private func writeError(_ code: UInt16) {
let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
WebSocket.writeUint16(buffer, offset: 0, value: code)
dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose)
}
/**
Used to write things to the stream
*/
private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) {
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
//stream isn't ready, let's wait
guard let self = self else { return }
guard let sOperation = operation else { return }
var offset = 2
var firstByte:UInt8 = self.FinMask | code.rawValue
var data = data
if [.textFrame, .binaryFrame].contains(code), let compressor = self.compressionState.compressor {
do {
data = try compressor.compress(data)
if self.compressionState.clientNoContextTakeover {
try compressor.reset()
}
firstByte |= self.RSV1Mask
} catch {
// TODO: report error? We can just send the uncompressed frame.
}
}
let dataLength = data.count
let frame = NSMutableData(capacity: dataLength + self.MaxFrameSize)
let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self)
buffer[0] = firstByte
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength))
offset += MemoryLayout<UInt16>.size
} else {
buffer[1] = 127
WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength))
offset += MemoryLayout<UInt64>.size
}
buffer[1] |= self.MaskMask
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
_ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey)
offset += MemoryLayout<UInt32>.size
for i in 0..<dataLength {
buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size]
offset += 1
}
var total = 0
while !sOperation.isCancelled {
if !self.readyToWrite {
self.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0))
break
}
let stream = self.stream
let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self)
let len = stream.write(data: Data(bytes: writeBuffer, count: offset-total))
if len <= 0 {
self.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0))
break
} else {
total += len
}
if total >= offset {
if let callback = writeCompletion {
self.callbackQueue.async {
callback()
}
}
break
}
}
}
writeQueue.addOperation(operation)
}
/**
Used to preform the disconnect delegate
*/
private func doDisconnect(_ error: Error?) {
guard !didDisconnect else { return }
didDisconnect = true
isConnecting = false
mutex.lock()
connected = false
mutex.unlock()
guard canDispatch else {return}
callbackQueue.async { [weak self] in
guard let self = self else { return }
self.onDisconnect?(error)
self.delegate?.websocketDidDisconnect(socket: self, error: error)
self.advancedDelegate?.websocketDidDisconnect(socket: self, error: error)
let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] }
NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo)
}
}
// MARK: - Deinit
deinit {
mutex.lock()
readyToWrite = false
cleanupStream()
mutex.unlock()
writeQueue.cancelAllOperations()
}
}
private extension String {
func sha1Base64() -> String {
let data = self.data(using: String.Encoding.utf8)!
var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) }
return Data(bytes: digest).base64EncodedString()
}
}
private extension Data {
init(buffer: UnsafeBufferPointer<UInt8>) {
self.init(bytes: buffer.baseAddress!, count: buffer.count)
}
}
private extension UnsafeBufferPointer {
func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> {
return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset)
}
}
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
#if swift(>=4)
#else
fileprivate extension String {
var count: Int {
return self.characters.count
}
}
#endif
| 40.532056 | 226 | 0.58856 |
906f72d95a49b374bead47ea78f51fc992b11212 | 1,959 | /*
* Copyright (C) 2012-2018 halo https://io.github.com/halo/LinkLiar
*
* 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
@testable import LinkLiar
class LinkLiarTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 43.533333 | 133 | 0.711588 |
f5cb20eae40c5f247f33dd317366d2a2bca1ec20 | 1,458 | //
// Utilities.swift
// SwiftMath
//
//
// Global functions (public in internal) defined by SwiftMath module.
// (c) 2016 Hooman Mehr. Licensed under Apache License v2.0 with Runtime Library Exception
//
/// Utility protocol to help write more readable code.
///
/// One alternative is overloading multiplication / division operators, but it would
/// pollute operator space and lead to ambiguity.
internal protocol Scalable {
/// The type of scale factor supporting by this scalable type.
associatedtype ScaleFactor
/// Returns a new item by scaling the current item to the given factor.
///
/// - Parameter factor: The given scaling factor.
func scaled(by factor: ScaleFactor) -> Self
}
extension Int: Scalable {
typealias ScaleFactor = Double
func scaled(by factor: Double) -> Int {
return Int((Double(self) * factor).rounded())
}
}
extension String {
/// Returns a string with the given key characters replaced with corresponding value characters.
///
/// - Parameter lookupTable: A dictionary that mapps character keys to character values. Each
/// character key in the string is replaced with the corresponding character value from this
/// dictionary.
func mapped(with lookupTable: [Character:Character]) -> String {
return String(self.characters.map{ lookupTable[$0] ?? $0 })
}
}
| 23.901639 | 100 | 0.662551 |
0af26147fa5fdb98d8647b5a9f6f569ab9c5fb73 | 10,823 | //
// Copyright 2021 Guillaume Algis.
// Licensed under the MIT License. See the LICENSE.md file in the project root for more information.
//
@testable import SimpleMDM
import XCTest
/// This class tests whether the exposed API using the SimpleMDM singleton calls to the right Networking instance.
/// We do this by using a networking mock which returns a nonsensical HTTP code, and check in the callback we got
/// this code as expected.
internal class SimpleMDMSingletonTests: XCTestCase {
override static func setUp() {
let session = URLSessionMock(responseCode: 999)
let networking = Networking(urlSession: session)
networking.apiKey = "AGlobalAndRandomAPIKey"
SimpleMDM.shared.networking = networking
}
func testUniqueResourceGetViaSingleton() {
let expectation = self.expectation(description: "Callback called")
UniqueResourceMock.get { result in
guard case let .rejected(error) = result else {
return XCTFail("Expected .error, got \(result)")
}
guard let simpleMDMError = error as? SimpleMDMError else {
return XCTFail("Expected error to be a SimpleMDMError, got \(error)")
}
guard case let .unknown(httpCode) = simpleMDMError else {
return XCTFail("Expected .unknown, got \(simpleMDMError)")
}
XCTAssertEqual(httpCode, 999)
expectation.fulfill()
}
waitForExpectations(timeout: 0.3, handler: nil)
}
func testResourceGetAllViaSingleton() {
let expectation = self.expectation(description: "Callback called")
ResourceMock.getAll { result in
guard case let .rejected(error) = result else {
return XCTFail("Expected .error, got \(result)")
}
guard let simpleMDMError = error as? SimpleMDMError else {
return XCTFail("Expected error to be a SimpleMDMError, got \(error)")
}
guard case let .unknown(httpCode) = simpleMDMError else {
return XCTFail("Expected .unknown, got \(simpleMDMError)")
}
XCTAssertEqual(httpCode, 999)
expectation.fulfill()
}
waitForExpectations(timeout: 0.3, handler: nil)
}
func testResourceGetByIdViaSingleton() {
let expectation = self.expectation(description: "Callback called")
ResourceMock.get(id: 42) { result in
guard case let .rejected(error) = result else {
return XCTFail("Expected .error, got \(result)")
}
guard let simpleMDMError = error as? SimpleMDMError else {
return XCTFail("Expected error to be a SimpleMDMError, got \(error)")
}
guard case let .unknown(httpCode) = simpleMDMError else {
return XCTFail("Expected .unknown, got \(simpleMDMError)")
}
XCTAssertEqual(httpCode, 999)
expectation.fulfill()
}
waitForExpectations(timeout: 0.3, handler: nil)
}
func testResourceGetRelatedToOneViaSingleton() {
let json = loadFixture("ResourceWithRelationsMock_42")
let session = URLSessionMock(data: json, responseCode: 200)
let s = SimpleMDM(sessionMock: session)
let expectation = self.expectation(description: "Callback called")
ResourceWithRelationsMock.get(s.networking, id: 42) { result in
guard case let .fulfilled(resource) = result else {
return XCTFail("Expected .fulfilled, got \(result)")
}
resource.toOne.get { relationResult in
guard case let .rejected(error) = relationResult else {
return XCTFail("Expected .error, got \(relationResult)")
}
guard let simpleMDMError = error as? SimpleMDMError else {
return XCTFail("Expected error to be a SimpleMDMError, got \(error)")
}
guard case let .unknown(httpCode) = simpleMDMError else {
return XCTFail("Expected .unknown, got \(simpleMDMError)")
}
XCTAssertEqual(httpCode, 999)
expectation.fulfill()
}
}
waitForExpectations(timeout: 0.3, handler: nil)
}
func testResourceGetAllRelatedToManyViaSingleton() {
let json = loadFixture("ResourceWithRelationsMock_42")
let session = URLSessionMock(data: json, responseCode: 200)
let s = SimpleMDM(sessionMock: session)
let expectation = self.expectation(description: "Callback called")
ResourceWithRelationsMock.get(s.networking, id: 42) { result in
guard case let .fulfilled(resource) = result else {
return XCTFail("Expected .fulfilled, got \(result)")
}
resource.toMany.getAll { relationResult in
guard case let .rejected(error) = relationResult else {
return XCTFail("Expected .error, got \(relationResult)")
}
guard let simpleMDMError = error as? SimpleMDMError else {
return XCTFail("Expected error to be a SimpleMDMError, got \(error)")
}
guard case let .unknown(httpCode) = simpleMDMError else {
return XCTFail("Expected .unknown, got \(simpleMDMError)")
}
XCTAssertEqual(httpCode, 999)
expectation.fulfill()
}
}
waitForExpectations(timeout: 0.3, handler: nil)
}
func testResourceGetRelatedToManyAtIndexViaSingleton() {
let json = loadFixture("ResourceWithRelationsMock_42")
let session = URLSessionMock(data: json, responseCode: 200)
let s = SimpleMDM(sessionMock: session)
let expectation = self.expectation(description: "Callback called")
ResourceWithRelationsMock.get(s.networking, id: 42) { result in
guard case let .fulfilled(resource) = result else {
return XCTFail("Expected .fulfilled, got \(result)")
}
resource.toMany.get(at: 0) { relationResult in
guard case let .rejected(error) = relationResult else {
return XCTFail("Expected .error, got \(relationResult)")
}
guard let simpleMDMError = error as? SimpleMDMError else {
return XCTFail("Expected error to be a SimpleMDMError, got \(error)")
}
guard case let .unknown(httpCode) = simpleMDMError else {
return XCTFail("Expected .unknown, got \(simpleMDMError)")
}
XCTAssertEqual(httpCode, 999)
expectation.fulfill()
}
}
waitForExpectations(timeout: 0.3, handler: nil)
}
func testResourceGetRelatedToManyByIdViaSingleton() {
let json = loadFixture("ResourceWithRelationsMock_42")
let session = URLSessionMock(data: json, responseCode: 200)
let s = SimpleMDM(sessionMock: session)
let expectation = self.expectation(description: "Callback called")
ResourceWithRelationsMock.get(s.networking, id: 42) { result in
guard case let .fulfilled(resource) = result else {
return XCTFail("Expected .fulfilled, got \(result)")
}
resource.toMany.get(id: 0) { relationResult in
guard case let .rejected(error) = relationResult else {
return XCTFail("Expected .error, got \(relationResult)")
}
guard let simpleMDMError = error as? SimpleMDMError else {
return XCTFail("Expected error to be a SimpleMDMError, got \(error)")
}
guard case let .unknown(httpCode) = simpleMDMError else {
return XCTFail("Expected .unknown, got \(simpleMDMError)")
}
XCTAssertEqual(httpCode, 999)
expectation.fulfill()
}
}
waitForExpectations(timeout: 0.3, handler: nil)
}
func testResourceGetAllRelatedToManyNestedViaSingleton() {
let json = loadFixture("ResourceWithRelationsMock_42")
let session = URLSessionMock(data: json, responseCode: 200)
let s = SimpleMDM(sessionMock: session)
let expectation = self.expectation(description: "Callback called")
ResourceWithRelationsMock.get(s.networking, id: 42) { result in
guard case let .fulfilled(resource) = result else {
return XCTFail("Expected .fulfilled, got \(result)")
}
resource.toManyNested.getAll { relationResult in
guard case let .rejected(error) = relationResult else {
return XCTFail("Expected .error, got \(relationResult)")
}
guard let simpleMDMError = error as? SimpleMDMError else {
return XCTFail("Expected error to be a SimpleMDMError, got \(error)")
}
guard case let .unknown(httpCode) = simpleMDMError else {
return XCTFail("Expected .unknown, got \(simpleMDMError)")
}
XCTAssertEqual(httpCode, 999)
expectation.fulfill()
}
}
waitForExpectations(timeout: 0.3, handler: nil)
}
func testResourceGetRelatedToManyNestedByIdViaSingleton() {
let json = loadFixture("ResourceWithRelationsMock_42")
let session = URLSessionMock(data: json, responseCode: 200)
let s = SimpleMDM(sessionMock: session)
let expectation = self.expectation(description: "Callback called")
ResourceWithRelationsMock.get(s.networking, id: 42) { result in
guard case let .fulfilled(resource) = result else {
return XCTFail("Expected .fulfilled, got \(result)")
}
resource.toManyNested.get(id: 0) { relationResult in
guard case let .rejected(error) = relationResult else {
return XCTFail("Expected .error, got \(relationResult)")
}
guard let simpleMDMError = error as? SimpleMDMError else {
return XCTFail("Expected error to be a SimpleMDMError, got \(error)")
}
guard case let .unknown(httpCode) = simpleMDMError else {
return XCTFail("Expected .unknown, got \(simpleMDMError)")
}
XCTAssertEqual(httpCode, 999)
expectation.fulfill()
}
}
waitForExpectations(timeout: 0.3, handler: nil)
}
}
| 41.626923 | 114 | 0.594844 |
d93ddac10018679ae3239c539d254f447826e2a1 | 2,964 | //
// UIViewController+Povio.swift
// PovioKit
//
// Created by Toni Kocjan on 26/07/2020.
// Copyright © 2021 Povio Inc. All rights reserved.
//
import UIKit
public extension UIViewController {
class BarButton {
let content: Content
let action: Selector?
let target: Any?
required public init(content: Content, action: Selector?, target: Any? = nil) {
self.content = content
self.action = action
self.target = target
}
}
}
public extension UIViewController.BarButton {
enum Content {
case icon(UIImage)
case title(Title)
public static func icon(_ image: UIImage?) -> Content {
.icon(image ?? UIImage())
}
}
}
public extension UIViewController.BarButton.Content {
enum Title {
case `default`(String)
case attributed(normal: NSAttributedString, disabled: NSAttributedString?)
public static func attributed(normal: NSAttributedString) -> Title {
.attributed(normal: normal, disabled: nil)
}
}
}
public extension UIViewController {
@discardableResult
func setLeftBarButton(_ barButton: BarButton) -> UIBarButtonItem {
let button = createButton(using: barButton)
navigationItem.leftBarButtonItem = button
return button
}
@discardableResult
func setRightBarButton(_ barButton: BarButton) -> UIBarButtonItem {
let button = createButton(using: barButton)
navigationItem.rightBarButtonItem = button
return button
}
@discardableResult
func setLeftBarButtons(_ barButtons: [BarButton]) -> [UIBarButtonItem] {
let buttons = barButtons.map(createButton)
navigationItem.leftBarButtonItems = buttons
return buttons
}
@discardableResult
func setRightBarButtons(_ barButtons: [BarButton]) -> [UIBarButtonItem] {
let buttons = barButtons.map(createButton)
navigationItem.rightBarButtonItems = buttons
return buttons
}
}
private extension UIViewController {
func createButton(using barButton: BarButton) -> UIBarButtonItem {
switch barButton.content {
case .title(.default(let title)):
let button = UIButton()
button.setTitle(title, for: .normal)
barButton.action.map {
button.addTarget(barButton.target ?? self, action: $0, for: .touchUpInside)
}
return UIBarButtonItem(customView: button)
case let .title(.attributed(normal, disabled)):
let button = UIButton()
button.setAttributedTitle(normal, for: .normal)
button.setAttributedTitle(disabled, for: .disabled)
barButton.action.map {
button.addTarget(barButton.target ?? self, action: $0, for: .touchUpInside)
}
return UIBarButtonItem(customView: button)
case .icon(let image):
return UIBarButtonItem(image: image.withRenderingMode(.alwaysOriginal),
style: .plain,
target: barButton.target ?? self,
action: barButton.action)
}
}
}
| 28.776699 | 83 | 0.677126 |
892acc267295eff97a329280947040a0617282e4 | 228 | //
// SpringButton.swift
// SpringAnimation
//
// Created by Squid Yu on 20/10/2017.
// Copyright © 2017 SquidYu. All rights reserved.
//
import UIKit
class SpringButton: UIButton {}
extension SpringButton: Springable {}
| 16.285714 | 50 | 0.710526 |
905cc995d93ae850525fac1eecd4048d372228c5 | 765 | //
// QSRootNodeTransform.swift
// QuestShare
//
// Created by Karol Wojtas on 24/10/2021.
//
import Foundation
import CoreLocation
struct QSVector2: Equatable {
var x: Double = 0.0
var y: Double = 0.0
static var zero: QSVector2 {
QSVector2()
}
}
struct QSRootNodeTransform: Equatable {
var position: QSVector2 = .zero
var heading: Double = 0.0
var bearing: Double = 0.0
var distance: Double = 0.0
var coordinate: CLLocationCoordinate2D?
/// deprecated since using .gravityAndHeading
var northRotation: Double {
if abs(heading) == 90.0 || heading == 180.0{
return heading
} else {
return (180.signFrom(heading)) - heading
}
}
}
| 21.857143 | 55 | 0.598693 |
dbdfc6f14991a4b6771c871bf20083667c882ee1 | 687 | class Person {
let name: String
init(name: String) {
self.name = name
}
}
struct Stuff {
var name: String
var owner: Person
}
let yagom = Person(name: "yagom")
let hana = Person(name: "hana")
let macbook = Stuff(name: "MacBook Pro", owner: yagom)
var iMac = Stuff(name: "iMac", owner: yagom)
let iPhone = Stuff(name: "iPhone", owner: hana)
let stuffNameKeyPath = \Stuff.name
let ownerKeyPath = \Stuff.owner
// \Stuff.owner.name
let ownerNameKeyPath = ownerKeyPath.appending(path: \.name)
print(macbook[keyPath: stuffNameKeyPath])
print(macbook[keyPath: ownerNameKeyPath])
iMac[keyPath: stuffNameKeyPath] = "iMac Pro"
iMac[keyPath: ownerKeyPath] = hana
| 22.16129 | 59 | 0.69869 |
61baf38c04adf02156a16d2358812703588e7613 | 20,151 | //
// ResourceObject.swift
// JSONAPI
//
// Created by Mathew Polzin on 7/24/18.
//
/// A JSON API structure within an ResourceObject that contains
/// named properties of types `MetaRelationship`, `ToOneRelationship`
/// and `ToManyRelationship`.
public protocol Relationships: Codable & Equatable {}
/// A JSON API structure within an ResourceObject that contains
/// properties of any types that are JSON encodable.
public protocol Attributes: Codable & Equatable {}
/// CodingKeys must be `CodingKey` and `Equatable` in order
/// to support Sparse Fieldsets.
public typealias SparsableCodingKey = CodingKey & Equatable
/// Attributes containing publicly accessible and `Equatable`
/// CodingKeys are required to support Sparse Fieldsets.
public protocol SparsableAttributes: Attributes {
associatedtype CodingKeys: SparsableCodingKey
}
/// Can be used as `Relationships` Type for Entities that do not
/// have any Relationships.
public struct NoRelationships: Relationships {
public static var none: NoRelationships { return .init() }
}
extension NoRelationships: CustomStringConvertible {
public var description: String { return "No Relationships" }
}
/// Can be used as `Attributes` Type for Entities that do not
/// have any Attributes.
public struct NoAttributes: Attributes {
public static var none: NoAttributes { return .init() }
}
extension NoAttributes: CustomStringConvertible {
public var description: String { return "No Attributes" }
}
/// Something that is JSONTyped provides a String representation
/// of its type.
public protocol JSONTyped {
static var jsonType: String { get }
}
/// A `ResourceObjectProxyDescription` is an `ResourceObjectDescription`
/// without Codable conformance.
public protocol ResourceObjectProxyDescription: JSONTyped {
associatedtype Attributes: Equatable
associatedtype Relationships: Equatable
}
/// A `ResourceObjectDescription` describes a JSON API
/// Resource Object. The Resource Object
/// itself is encoded and decoded as an
/// `ResourceObject`, which gets specialized on an
/// `ResourceObjectDescription`.
public protocol ResourceObjectDescription: ResourceObjectProxyDescription where Attributes: JSONAPI.Attributes, Relationships: JSONAPI.Relationships {}
/// ResourceObjectProxy is a protocol that can be used to create
/// types that _act_ like ResourceObject but cannot be encoded
/// or decoded as ResourceObjects.
@dynamicMemberLookup
public protocol ResourceObjectProxy: Equatable, JSONTyped {
associatedtype Description: ResourceObjectProxyDescription
associatedtype EntityRawIdType: JSONAPI.MaybeRawId
typealias Id = JSONAPI.Id<EntityRawIdType, Self>
typealias Attributes = Description.Attributes
typealias Relationships = Description.Relationships
/// The `Entity`'s Id. This can be of type `Unidentified` if
/// the entity is being created clientside and the
/// server is being asked to create a unique Id. Otherwise,
/// this should be of a type conforming to `IdType`.
var id: Id { get }
/// The JSON API compliant attributes of this `Entity`.
var attributes: Attributes { get }
/// The JSON API compliant relationships of this `Entity`.
var relationships: Relationships { get }
}
extension ResourceObjectProxy {
/// The JSON API compliant "type" of this `ResourceObject`.
public static var jsonType: String { return Description.jsonType }
}
/// A marker protocol.
public protocol AbstractResourceObject {}
/// ResourceObjectType is the protocol that ResourceObject conforms to. This
/// protocol lets other types accept any ResourceObject as a generic
/// specialization.
public protocol ResourceObjectType: AbstractResourceObject, ResourceObjectProxy, CodablePrimaryResource where Description: ResourceObjectDescription {
associatedtype Meta: JSONAPI.Meta
associatedtype Links: JSONAPI.Links
/// Any additional metadata packaged with the entity.
var meta: Meta { get }
/// Links related to the entity.
var links: Links { get }
}
public protocol IdentifiableResourceObjectType: ResourceObjectType, Relatable where EntityRawIdType: JSONAPI.RawIdType {}
/// An `ResourceObject` is a single model type that can be
/// encoded to or decoded from a JSON API
/// "Resource Object."
/// See https://jsonapi.org/format/#document-resource-objects
public struct ResourceObject<Description: JSONAPI.ResourceObjectDescription, MetaType: JSONAPI.Meta, LinksType: JSONAPI.Links, EntityRawIdType: JSONAPI.MaybeRawId>: ResourceObjectType {
public typealias Meta = MetaType
public typealias Links = LinksType
/// The `ResourceObject`'s Id. This can be of type `Unidentified` if
/// the entity is being created clientside and the
/// server is being asked to create a unique Id. Otherwise,
/// this should be of a type conforming to `IdType`.
public let id: JSONAPI.Id<EntityRawIdType, Self>
/// The JSON API compliant attributes of this `ResourceObject`.
public let attributes: Description.Attributes
/// The JSON API compliant relationships of this `ResourceObject`.
public let relationships: Description.Relationships
/// Any additional metadata packaged with the entity.
public let meta: MetaType
/// Links related to the entity.
public let links: LinksType
public init(id: ResourceObject.Id, attributes: Description.Attributes, relationships: Description.Relationships, meta: MetaType, links: LinksType) {
self.id = id
self.attributes = attributes
self.relationships = relationships
self.meta = meta
self.links = links
}
}
// `ResourceObject` is hashable as an identifiable resource which semantically
// means that two different resources with the same ID should yield the same
// hash value.
//
// "equatability" in this context will determine if two resources have _all_ the same
// properties, whereas hash value will determine if two resources have the same Id.
extension ResourceObject: Hashable where EntityRawIdType: RawIdType {
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
extension ResourceObject: JSONAPIIdentifiable, IdentifiableResourceObjectType, Relatable where EntityRawIdType: JSONAPI.RawIdType {
public typealias ID = ResourceObject.Id
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension ResourceObject: Swift.Identifiable where EntityRawIdType: JSONAPI.RawIdType {}
extension ResourceObject: CustomStringConvertible {
public var description: String {
return "ResourceObject<\(ResourceObject.jsonType)>(id: \(String(describing: id)), attributes: \(String(describing: attributes)), relationships: \(String(describing: relationships)))"
}
}
// MARK: - Convenience initializers
extension ResourceObject where EntityRawIdType: CreatableRawIdType {
public init(attributes: Description.Attributes, relationships: Description.Relationships, meta: MetaType, links: LinksType) {
self.id = ResourceObject.Id()
self.attributes = attributes
self.relationships = relationships
self.meta = meta
self.links = links
}
}
extension ResourceObject where EntityRawIdType == Unidentified {
public init(attributes: Description.Attributes, relationships: Description.Relationships, meta: MetaType, links: LinksType) {
self.id = .unidentified
self.attributes = attributes
self.relationships = relationships
self.meta = meta
self.links = links
}
}
// MARK: - Pointer for Relationships use
public extension ResourceObject where EntityRawIdType: JSONAPI.RawIdType {
/// A `ResourceObject.Pointer` is a `ToOneRelationship` with no metadata or links.
/// This is just a convenient way to reference a `ResourceObject` so that
/// other ResourceObjects' Relationships can be built up from it.
typealias Pointer = ToOneRelationship<ResourceObject, NoIdMetadata, NoMetadata, NoLinks>
/// `ResourceObject.Pointers` is a `ToManyRelationship` with no metadata or links.
/// This is just a convenient way to reference a bunch of ResourceObjects so
/// that other ResourceObjects' Relationships can be built up from them.
typealias Pointers = ToManyRelationship<ResourceObject, NoIdMetadata, NoMetadata, NoLinks>
/// Get a pointer to this resource object that can be used as a
/// relationship to another resource object.
var pointer: Pointer {
return Pointer(resourceObject: self)
}
/// Get a pointer (i.e. `ToOneRelationship`) to this resource
/// object with the given metadata and links attached.
func pointer<MType: JSONAPI.Meta, LType: JSONAPI.Links>(withMeta meta: MType, links: LType) -> ToOneRelationship<ResourceObject, NoIdMetadata, MType, LType> {
return ToOneRelationship(resourceObject: self, meta: meta, links: links)
}
}
// MARK: - Identifying Unidentified Entities
public extension ResourceObject where EntityRawIdType == Unidentified {
/// Create a new `ResourceObject` from this one with a newly created
/// unique Id of the given type.
func identified<RawIdType: CreatableRawIdType>(byType: RawIdType.Type) -> ResourceObject<Description, MetaType, LinksType, RawIdType> {
return .init(attributes: attributes, relationships: relationships, meta: meta, links: links)
}
/// Create a new `ResourceObject` from this one with the given Id.
func identified<RawIdType: JSONAPI.RawIdType>(by id: RawIdType) -> ResourceObject<Description, MetaType, LinksType, RawIdType> {
return .init(id: ResourceObject<Description, MetaType, LinksType, RawIdType>.ID(rawValue: id), attributes: attributes, relationships: relationships, meta: meta, links: links)
}
}
public extension ResourceObject where EntityRawIdType: CreatableRawIdType {
/// Create a copy of this `ResourceObject` with a new unique Id.
func withNewIdentifier() -> ResourceObject {
return ResourceObject(attributes: attributes, relationships: relationships, meta: meta, links: links)
}
}
// MARK: - Attribute Access
public extension ResourceObjectProxy {
// MARK: Dynaminc Member Keypath Lookup
/// Access the attribute at the given keypath. This just
/// allows you to write `resourceObject[\.propertyName]` instead
/// of `resourceObject.attributes.propertyName.value`.
subscript<T: AttributeType>(dynamicMember path: KeyPath<Description.Attributes, T>) -> T.ValueType {
return attributes[keyPath: path].value
}
/// Access the attribute at the given keypath. This just
/// allows you to write `resourceObject[\.propertyName]` instead
/// of `resourceObject.attributes.propertyName.value`.
subscript<T: AttributeType>(dynamicMember path: KeyPath<Description.Attributes, T?>) -> T.ValueType? {
return attributes[keyPath: path]?.value
}
/// Access the attribute at the given keypath. This just
/// allows you to write `resourceObject[\.propertyName]` instead
/// of `resourceObject.attributes.propertyName.value`.
subscript<T: AttributeType, U>(dynamicMember path: KeyPath<Description.Attributes, T?>) -> U? where T.ValueType == U? {
return attributes[keyPath: path].flatMap(\.value)
}
// MARK: Direct Keypath Subscript Lookup
/// Access the storage of the attribute at the given keypath. This just
/// allows you to write `resourceObject[direct: \.propertyName]` instead
/// of `resourceObject.attributes.propertyName`.
/// Most of the subscripts dig into an `AttributeType`. This subscript
/// returns the `AttributeType` (or another type, if you are accessing
/// an attribute that is not stored in an `AttributeType`).
subscript<T>(direct path: KeyPath<Description.Attributes, T>) -> T {
// Implementation Note: Handles attributes that are not
// AttributeType. These should only exist as computed properties.
return attributes[keyPath: path]
}
}
// MARK: - Meta-Attribute Access
public extension ResourceObjectProxy {
// MARK: Dynamic Member Keypath Lookup
/// Access an attribute requiring a transformation on the RawValue _and_
/// a secondary transformation on this entity (self).
subscript<T>(dynamicMember path: KeyPath<Description.Attributes, (Self) -> T>) -> T {
return attributes[keyPath: path](self)
}
}
// MARK: - Relationship Access
public extension ResourceObjectProxy {
/// Access to an Id of a `ToOneRelationship`.
/// This allows you to write `resourceObject ~> \.other` instead
/// of `resourceObject.relationships.other.id`.
static func ~><OtherEntity: JSONAPIIdentifiable, IdMType: JSONAPI.Meta, MType: JSONAPI.Meta, LType: JSONAPI.Links>(entity: Self, path: KeyPath<Description.Relationships, ToOneRelationship<OtherEntity, IdMType, MType, LType>>) -> OtherEntity.ID {
return entity.relationships[keyPath: path].id
}
/// Access to an Id of an optional `ToOneRelationship`.
/// This allows you to write `resourceObject ~> \.other` instead
/// of `resourceObject.relationships.other?.id`.
static func ~><OtherEntity: OptionalRelatable, IdMType: JSONAPI.Meta, MType: JSONAPI.Meta, LType: JSONAPI.Links>(entity: Self, path: KeyPath<Description.Relationships, ToOneRelationship<OtherEntity, IdMType, MType, LType>?>) -> OtherEntity.ID {
// Implementation Note: This signature applies to `ToOneRelationship<E?, _, _>?`
// whereas the one below applies to `ToOneRelationship<E, _, _>?`
return entity.relationships[keyPath: path]?.id
}
/// Access to an Id of an optional `ToOneRelationship`.
/// This allows you to write `resourceObject ~> \.other` instead
/// of `resourceObject.relationships.other?.id`.
static func ~><OtherEntity: Relatable, IdMType: JSONAPI.Meta, MType: JSONAPI.Meta, LType: JSONAPI.Links>(entity: Self, path: KeyPath<Description.Relationships, ToOneRelationship<OtherEntity, IdMType, MType, LType>?>) -> OtherEntity.ID? {
// Implementation Note: This signature applies to `ToOneRelationship<E, _, _>?`
// whereas the one above applies to `ToOneRelationship<E?, _, _>?`
return entity.relationships[keyPath: path]?.id
}
/// Access to all Ids of a `ToManyRelationship`.
/// This allows you to write `resourceObject ~> \.others` instead
/// of `resourceObject.relationships.others.ids`.
static func ~><OtherEntity: Relatable, IdMType: JSONAPI.Meta, MType: JSONAPI.Meta, LType: JSONAPI.Links>(entity: Self, path: KeyPath<Description.Relationships, ToManyRelationship<OtherEntity, IdMType, MType, LType>>) -> [OtherEntity.ID] {
return entity.relationships[keyPath: path].ids
}
/// Access to all Ids of an optional `ToManyRelationship`.
/// This allows you to write `resourceObject ~> \.others` instead
/// of `resourceObject.relationships.others?.ids`.
static func ~><OtherEntity: Relatable, IdMType: JSONAPI.Meta, MType: JSONAPI.Meta, LType: JSONAPI.Links>(entity: Self, path: KeyPath<Description.Relationships, ToManyRelationship<OtherEntity, IdMType, MType, LType>?>) -> [OtherEntity.ID]? {
return entity.relationships[keyPath: path]?.ids
}
}
// MARK: - Meta-Relationship Access
public extension ResourceObjectProxy {
/// Access to an Id of a `ToOneRelationship`.
/// This allows you to write `resourceObject ~> \.other` instead
/// of `resourceObject.relationships.other.id`.
static func ~><Identifier: IdType>(entity: Self, path: KeyPath<Description.Relationships, (Self) -> Identifier>) -> Identifier {
return entity.relationships[keyPath: path](entity)
}
/// Access to all Ids of a `ToManyRelationship`.
/// This allows you to write `resourceObject ~> \.others` instead
/// of `resourceObject.relationships.others.ids`.
static func ~><Identifier: IdType>(entity: Self, path: KeyPath<Description.Relationships, (Self) -> [Identifier]>) -> [Identifier] {
return entity.relationships[keyPath: path](entity)
}
}
infix operator ~>
// MARK: - Codable
private enum ResourceObjectCodingKeys: String, CodingKey {
case type = "type"
case id = "id"
case attributes = "attributes"
case relationships = "relationships"
case meta = "meta"
case links = "links"
}
public extension ResourceObject {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: ResourceObjectCodingKeys.self)
try container.encode(ResourceObject.jsonType, forKey: .type)
if EntityRawIdType.self != Unidentified.self {
try container.encode(id, forKey: .id)
}
if Description.Attributes.self != NoAttributes.self {
let nestedEncoder = container.superEncoder(forKey: .attributes)
try attributes.encode(to: nestedEncoder)
}
if Description.Relationships.self != NoRelationships.self {
try container.encode(relationships, forKey: .relationships)
}
if MetaType.self != NoMetadata.self {
try container.encode(meta, forKey: .meta)
}
if LinksType.self != NoLinks.self {
try container.encode(links, forKey: .links)
}
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ResourceObjectCodingKeys.self)
let type: String
do {
type = try container.decode(String.self, forKey: .type)
} catch let error as DecodingError {
throw ResourceObjectDecodingError(error, jsonAPIType: Self.jsonType)
?? error
}
guard ResourceObject.jsonType == type else {
throw ResourceObjectDecodingError(
expectedJSONAPIType: ResourceObject.jsonType,
found: type
)
}
let maybeUnidentified = Unidentified() as? EntityRawIdType
id = try maybeUnidentified.map { ResourceObject.Id(rawValue: $0) } ?? container.decode(ResourceObject.Id.self, forKey: .id)
do {
attributes = try (NoAttributes() as? Description.Attributes)
?? container.decodeIfPresent(Description.Attributes.self, forKey: .attributes)
?? Description.Attributes(from: EmptyObjectDecoder())
} catch let decodingError as DecodingError {
throw ResourceObjectDecodingError(decodingError, jsonAPIType: Self.jsonType)
?? decodingError
} catch _ as EmptyObjectDecodingError {
throw ResourceObjectDecodingError(
subjectName: ResourceObjectDecodingError.entireObject,
cause: .keyNotFound,
location: .attributes,
jsonAPIType: Self.jsonType
)
}
do {
relationships = try (NoRelationships() as? Description.Relationships)
?? container.decodeIfPresent(Description.Relationships.self, forKey: .relationships)
?? Description.Relationships(from: EmptyObjectDecoder())
} catch let decodingError as DecodingError {
throw ResourceObjectDecodingError(decodingError, jsonAPIType: Self.jsonType)
?? decodingError
} catch let decodingError as JSONAPICodingError {
throw ResourceObjectDecodingError(decodingError, jsonAPIType: Self.jsonType)
?? decodingError
} catch _ as EmptyObjectDecodingError {
throw ResourceObjectDecodingError(
subjectName: ResourceObjectDecodingError.entireObject,
cause: .keyNotFound,
location: .relationships,
jsonAPIType: Self.jsonType
)
}
meta = try (NoMetadata() as? MetaType) ?? container.decode(MetaType.self, forKey: .meta)
links = try (NoLinks() as? LinksType) ?? container.decode(LinksType.self, forKey: .links)
}
}
| 44.190789 | 249 | 0.702595 |
466c169a5221bc4a11d6fed2d8758a59dcedef9b | 207 | //
// ColorPalette.swift
// Series
//
// Created by Francisco Depascuali on 20/01/2019.
// Copyright © 2019 depa. All rights reserved.
//
import UIKit
struct ColorPalette {
}
extension UIColor {
}
| 10.894737 | 50 | 0.676329 |
fb3392fb7f3e34a1fdf80ff67cbd7d177312b02d | 950 | //
// File.swift
// Disaster
//
// Created by Mikkel Malmberg on 13/09/14.
// Copyright (c) 2014 BRNBW. All rights reserved.
//
import Foundation
class DRMU {
class var sharedClient : DRMU {
struct Singleton {
static let instance = DRMU()
}
return Singleton.instance
}
let baseURL = NSURL(string: "http://dr.dk")
func GET(path :NSString, completionHandler:((NSURLResponse!, JSONValue!, NSError!) -> Void)!) {
let request = self.requestWithMethod("GET", path: path)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) in
completionHandler(response, JSONValue(data), error)
};
}
func requestWithMethod(method:String, path:String) -> NSURLRequest {
var path = "/mu".stringByAppendingString(path)
var url = NSURL(string: path, relativeToURL: baseURL)
var request = NSURLRequest(URL: url)
return request;
}
} | 26.388889 | 118 | 0.675789 |
61fc6b70946fa4cad79222b1ae2b95c36c49c193 | 1,908 | import XCTest
import XpringKit
class PayIDUtilsTest: XCTestCase {
func testParseValidPayID() {
// GIVEN a Pay ID with a host and a path.
let host = "xpring.money"
let path = "georgewashington"
let rawPayID = "\(path)$\(host)"
// WHEN it is parsed to components.
let payIDComponents = PayIDUtils.parse(payID: rawPayID)
// THEN the host and path are set correctly.
XCTAssertEqual(payIDComponents?.host, host)
XCTAssertEqual(payIDComponents?.path, "/\(path)")
}
func testParsePayIDTooManyDollarSigns() {
// GIVEN a Pay ID with too many '$'.
let host = "xpring$money" // Extra '$'
let path = "georgewashington"
let rawPayID = "\(path)$\(host)"
// WHEN it is parsed to components.
let payIDComponents = PayIDUtils.parse(payID: rawPayID)
// THEN the Pay ID failed to parse.
XCTAssertNil(payIDComponents)
}
func testParsePayIDEmptyHost() {
// GIVEN a Pay ID with an empty host.
let host = ""
let path = "georgewashington"
let rawPayID = "\(path)$\(host)"
// WHEN it is parsed to components.
let payIDComponents = PayIDUtils.parse(payID: rawPayID)
// THEN the Pay ID failed to parse.
XCTAssertNil(payIDComponents)
}
func testParsePayIDEmptyPath() {
// GIVEN a Pay ID with an empty user.
let host = "xpring.money"
let path = ""
let rawPayID = "\(path)$\(host)"
// WHEN it is parsed to components.
let payIDComponents = PayIDUtils.parse(payID: rawPayID)
// THEN the Pay ID failed to parse.
XCTAssertNil(payIDComponents)
}
func testParsePayIDNonASCII() {
// GIVEN a Pay ID with non-ascii characters.
let rawPayID = "ZA̡͊͠͝LGΌIS̯͈͕̹̘̱ͮ$TO͇̹̺ͅƝ̴ȳ̳TH̘Ë͖́̉ ͠P̯͍̭O̚N̐Y̡"
// WHEN it is parsed to components.
let payIDComponents = PayIDUtils.parse(payID: rawPayID)
// THEN the Pay ID failed to parse.
XCTAssertNil(payIDComponents)
}
}
| 27.652174 | 69 | 0.656184 |
fcaef61a23e0c345d6aab5c2b2660798553fc5b2 | 2,193 | //
// AppDelegate.swift
// RPViews
//
// Created by [email protected] on 01/21/2021.
// Copyright (c) 2021 [email protected]. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.659574 | 285 | 0.75513 |
6a3870db3f639e45a71e329844f43f1b40edc5aa | 1,691 | //
// NEP2.swift
// NeoSwift
//
// Created by Luís Silva on 11/10/17.
// Copyright © 2017 drei. All rights reserved.
//
import Foundation
import Neoutils
@objc public class NEP2: NSObject {
public static func decryptKey(_ key: String, passphrase: String) -> (key: [UInt8], hash: [UInt8])? {
guard let encryptedKeyBytes = key.base58CheckDecodedBytes else { return nil }
if encryptedKeyBytes.count != 39 {
return nil
}
let addressHash = [UInt8](encryptedKeyBytes[3..<7])
let encryptedHalf1 = [UInt8](encryptedKeyBytes[7..<23])
let encryptedHalf2 = [UInt8](encryptedKeyBytes[23..<39])
let derived = scrypt().scrypt(passphrase: [UInt8](passphrase.utf8), salt: addressHash, n: 16384, r: 8, p: 8, dkLen: 64)
let derivedHalf1 = [UInt8](derived[0..<32])
let derivedHalf2 = [UInt8](derived[32..<64])
let decryptedHalf1 = AES.decrypt(bytes: encryptedHalf1, key: derivedHalf2, keySize: AES.KeySize.keySize256, pkcs7Padding: false).xor(other: [UInt8](derivedHalf1[0..<16]))
let decryptedHalf2 = AES.decrypt(bytes: encryptedHalf2, key: derivedHalf2, keySize: AES.KeySize.keySize256, pkcs7Padding: false).xor(other: [UInt8](derivedHalf1[16..<32]))
let decryptedKey = decryptedHalf1 + decryptedHalf2
return (key: decryptedKey, hash: addressHash)
}
@objc public static func verify(addressHash: [UInt8], address: String) -> Bool {
let addressHashSource = [UInt8](address.utf8)
let calculatedHash = [UInt8](addressHashSource.sha256.sha256[0..<4])
return calculatedHash == addressHash
}
}
| 40.261905 | 179 | 0.646954 |
62a3c8d6e9c59cbffff893ae39cf9ce6f37e1114 | 4,334 | import XCTest
@testable import MapboxMaps
class MapInitOptionsIntegrationTests: XCTestCase {
private var providerReturnValue: MapInitOptions!
override func tearDown() {
super.tearDown()
providerReturnValue = nil
}
func testOptionsWithCustomCredentialsManager() {
CredentialsManager.default.accessToken = "pk.aaaaaa"
let credentialsManager = CredentialsManager(accessToken: "pk.cccccc")
XCTAssertNotEqual(credentialsManager, CredentialsManager.default)
let mapInitOptions = MapInitOptions(
resourceOptions: ResourceOptions(accessToken: credentialsManager.accessToken))
let mapView = MapView(frame: .zero, mapInitOptions: mapInitOptions)
let resourceOptions = mapView.__map.getResourceOptions()
XCTAssertEqual(resourceOptions, mapInitOptions.resourceOptions)
XCTAssertEqual(resourceOptions.accessToken, credentialsManager.accessToken)
}
func testOptionsAreSetFromNibProvider() {
CredentialsManager.default.accessToken = "pk.aaaaaa"
let credentialsManager = CredentialsManager(accessToken: "pk.dddddd")
// Provider should return a custom MapInitOptions
providerReturnValue = MapInitOptions(
resourceOptions: ResourceOptions(accessToken: credentialsManager.accessToken))
// Load views from a nib, where the map view's provider is the file's owner,
// i.e. this test.
let nib = UINib(nibName: "MapInitOptionsTests", bundle: .mapboxMapsTests)
// Instantiate the map views. The nib contains two MapViews, one has their
// mapInitOptionsProvider outlet connected to this test object (view
// tag == 1), the other is nil (tag == 2)
let objects = nib.instantiate(withOwner: self, options: nil)
let mapViews = objects.compactMap { $0 as? MapView }
// Check MapView 1 -- connected in IB
let mapView = mapViews.first { $0.tag == 1 }!
XCTAssertNotNil(mapView.mapInitOptionsProvider)
let optionsFromProvider = mapView.mapInitOptionsProvider!.mapInitOptions()
// Check that the provider in the MapView is correctly wired, so that the
// expected options are returned
XCTAssertEqual(optionsFromProvider, providerReturnValue)
// Now check the resource options from the initialized MapView
let resourceOptions = mapView.__map.getResourceOptions()
XCTAssertEqual(resourceOptions, providerReturnValue.resourceOptions)
XCTAssertEqual(resourceOptions.accessToken, credentialsManager.accessToken)
}
func testDefaultOptionsAreUsedWhenNibDoesntSetProvider() {
CredentialsManager.default.accessToken = "pk.eeeeee"
// Although this test checks that a MapView (#2) isn't connected to a
// Provider, the first MapView will still be instantiated, so a return
// value is still required.
providerReturnValue = MapInitOptions(
resourceOptions: ResourceOptions(accessToken: "do-not-use"))
// Load view from a nib, where the map view's provider is nil
let nib = UINib(nibName: "MapInitOptionsTests", bundle: .mapboxMapsTests)
// Instantiate the view. The nib contains two MapViews, one has their
// mapInitOptionsProvider outlet connected to this test object (view
// tag == 1), the other is nil (tag == 2)
let objects = nib.instantiate(withOwner: self, options: nil)
// Check MapView 2 -- Not connected in IB
let mapView = objects.compactMap { $0 as? MapView }.first { $0.tag == 2 }!
XCTAssertNil(mapView.mapInitOptionsProvider)
// Now check the resource options from the initialized MapView
let resourceOptions = mapView.__map.getResourceOptions()
// The map should use the default MapInitOptions
XCTAssertEqual(resourceOptions, ResourceOptions(accessToken: CredentialsManager.default.accessToken))
XCTAssertEqual(resourceOptions.accessToken, CredentialsManager.default.accessToken)
}
}
extension MapInitOptionsIntegrationTests: MapInitOptionsProvider {
// This needs to return Any, since MapInitOptions is a struct, and this is
// an objc delegate.
public func mapInitOptions() -> MapInitOptions {
return providerReturnValue
}
}
| 42.910891 | 109 | 0.709275 |
dbecfd078276a0ee528f89dc90db0c293de5a95c | 394 | //
// StorageProtocol.swift
// AnyCache
//
// Created by PAN on 2021/8/16.
//
import Foundation
protocol StorageProtocol {
func removeAll()
func removeAllExpires()
func removeEntity(forKey key: String)
func entity(forKey key: String) -> Entity?
func setEntity(_ entity: Entity, forKey key: String) throws
func containsEntity(forKey key: String) -> Bool
}
| 16.416667 | 63 | 0.677665 |
ddb064316d1e34299f52ff942cb0786835399cb8 | 10,456 | //
// SSTableCell.swift
// SSCellKit
//
// Created by Nishchal Visavadiya on 06/07/21.
//
import UIKit
public protocol SSTableCellDelegate {
func leadingSwipeActions(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> SSSwipeConfiguration?
func trailingSwipeActions(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> SSSwipeConfiguration?
}
open class SSTableCell: UITableViewCell {
// MARK: Public variables
public var delegate: SSTableCellDelegate? {
didSet {
addPanSwipeGestureRecognizer()
}
}
// MARK: Private variables
internal var leadingSwipeActions: [SSSwipeAction]?
internal var trailingSwipeActions: [SSSwipeAction]?
private var tableView: SSTableView?
private var mutliSelectRecognizer: UIPanGestureRecognizer?
private let panDelegate = SSPanController()
private var movingContentView = UIView()
private var leadingMovingView = UIView()
private var trailingMovingView = UIView()
private var bounceBackOnCompletion = CGFloat(8)
private var viewsTobeRemoved = [UIView]()
private var indexPath: IndexPath? {
get {
tableView?.indexPath(for: self)
}
}
private func addPanSwipeGestureRecognizer() {
if let gesture = mutliSelectRecognizer {
self.removeGestureRecognizer(gesture)
}
mutliSelectRecognizer = UIPanGestureRecognizer(target: self, action: #selector(gesture(_:)))
mutliSelectRecognizer?.delegate = panDelegate
panDelegate.delegate = self
if let gesture = mutliSelectRecognizer {
addGestureRecognizer(gesture)
}
}
open override func awakeFromNib() {
super.awakeFromNib()
self.clipsToBounds = true // need this as if table view is in grouped insets then added subvies needs to be clipped to the cell
uninstallMovingView()
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
var view: UIView = self
while let superview = view.superview {
view = superview
if let tableView = view as? SSTableView {
self.tableView = tableView
return
}
}
}
@objc private func gesture(_ gestureRecognizer: UIPanGestureRecognizer) {
tableView?.gesture(gestureRecognizer)
}
internal func slideCellAndActions(leading: Bool, translationX: CGFloat) {
guard let actions = leading ? leadingSwipeActions : trailingSwipeActions else { return }
let totalActions = actions.count
let movingView = leading ? leadingMovingView : trailingMovingView
if totalActions == 0 {
return
}
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 20, initialSpringVelocity: 20, options: .curveEaseOut, animations: {
self.movingContentView.transform = CGAffineTransform(translationX: translationX*CGFloat(totalActions)/2, y: 0)
movingView.transform = CGAffineTransform(translationX: translationX/2, y: 0)
}, completion: {(success) in
})
}
internal func slideActionsBack(leading: Bool) {
guard let actions = leading ? leadingSwipeActions : trailingSwipeActions else { return }
let totalActions = actions.count
let movingView = leading ? leadingMovingView : trailingMovingView
if totalActions < 0 {
return
}
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
self.movingContentView.transform = .identity
movingView.transform = .identity
for action in actions {
action.actionIndicatorView.transform = .identity
action.actionIndicatorView.alpha = 0
}
}, completion: {(success) in
})
}
internal func slideBackActionsWithEfect(leading: Bool, index: Int) {
guard let actions = leading ? leadingSwipeActions : trailingSwipeActions else { return }
let totalActions = actions.count
let movingView = leading ? leadingMovingView : trailingMovingView
if totalActions == 0 {
return
}
UIView.animate(withDuration: 0.5, delay: 0, options: [.curveEaseIn], animations: {
let transformation = CGAffineTransform(translationX: leading ? 2*self.frame.width : -2*self.frame.width, y: 0)
self.movingContentView.transform = transformation
movingView.transform = transformation
}, completion: { _ in
self.movingContentView.transform = .identity
movingView.transform = .identity
actions[index].actionIndicatorView.transform = .identity
actions[index].actionIndicatorView.alpha = 0
movingView.backgroundColor = .none
})
}
internal func spanOneAction(leadingAction: Bool, index: Int, translationX: CGFloat, velocity: CGPoint) {
guard let actions = leadingAction ? leadingSwipeActions : trailingSwipeActions else { return }
let totalActions = actions.count
let movingView = leadingAction ? leadingMovingView : trailingMovingView
var indexToSpan = index
if index > totalActions-1 {
indexToSpan = totalActions-1
}
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
self.movingContentView.transform = CGAffineTransform(translationX: translationX, y: 0)
movingView.transform = CGAffineTransform(translationX: translationX, y: 0)
for i in 0..<totalActions {
if i == indexToSpan {
let actionIndicatorTransformation = leadingAction ? translationX > actions[i].actionIndicatorViewSize+actions[i].actionIndicatorIconOffset ? actions[i].actionIndicatorViewSize+actions[i].actionIndicatorIconOffset : translationX-actions[i].actionIndicatorIconOffset : translationX > -actions[i].actionIndicatorViewSize-actions[i].actionIndicatorIconOffset ? translationX+actions[i].actionIndicatorIconOffset : -actions[i].actionIndicatorViewSize-actions[i].actionIndicatorIconOffset
movingView.backgroundColor = actions[i].backgroundColor
actions[i].actionIndicatorView.transform = CGAffineTransform(translationX: actionIndicatorTransformation, y: 0)
actions[i].actionIndicatorView.alpha = 1
} else {
actions[i].actionIndicatorView.transform = .identity
actions[i].actionIndicatorView.alpha = 0
}
}
}, completion: {(success) in
})
}
internal func completionHandler(indexPaths: Set<IndexPath>,index: Int, leading: Bool) {
guard let actions = leading ? leadingSwipeActions : trailingSwipeActions else { return }
let totalActions = actions.count
if totalActions == 0 || indexPaths.isEmpty {
return
}
var indexToCall = index
if index > totalActions-1 {
indexToCall = totalActions-1
}
actions[indexToCall].completion?(Array(indexPaths).sorted(by: { $0.row > $1.row }))
}
internal func revealSwpieOptions(leading: Bool, velocity: CGPoint) {
let uniformWidthToreveal = 60
let movingView = leading ? leadingMovingView : trailingMovingView
guard let actions = leading ? leadingSwipeActions : trailingSwipeActions else { return }
let totalActions = actions.count
if totalActions == 0 {
return
}
let translationX = CGFloat(totalActions) * CGFloat(uniformWidthToreveal) * (leading ? 1 : -1)
UIView.animate(withDuration: TimeInterval(CGFloat(velocity.x/10000)) + 0.3, delay: 0.1, usingSpringWithDamping: 0.7, initialSpringVelocity: velocity.x/45, options: .curveEaseIn, animations: {
movingView.transform = CGAffineTransform(translationX: translationX + CGFloat( uniformWidthToreveal * 0 * (leading ? -1 : 1) ), y: 0)
self.movingContentView.transform = CGAffineTransform(translationX: translationX, y: 0)
}, completion: {(success) in
})
}
internal func installMovingView() {
guard let delegate = delegate else { return }
guard let indexPath = indexPath else { return }
guard let tableView = tableView else { return }
viewsTobeRemoved = [UIView]()
movingContentView = UIView()
leadingMovingView = UIView()
trailingMovingView = UIView()
movingContentView.addSubview(contentView)
viewsTobeRemoved.append(movingContentView)
addSubview(movingContentView)
if let actions = delegate.leadingSwipeActions(tableView, leadingSwipeActionsConfigurationForRowAt: indexPath)?.actions {
leadingSwipeActions = actions
addSubview(leadingMovingView)
viewsTobeRemoved.append(leadingMovingView)
for i in 0..<actions.count {
let createdView = actions[i].makeView(makeforLeading: true, emptyView: leadingMovingView, for: self)
viewsTobeRemoved.append(createdView)
}
}
if let actions = delegate.trailingSwipeActions(tableView, trailingSwipeActionsConfigurationForRowAt: indexPath)?.actions {
trailingSwipeActions = actions
addSubview(trailingMovingView)
viewsTobeRemoved.append(trailingMovingView)
for i in 0..<actions.count {
let createdView = actions[i].makeView(makeforLeading: false, emptyView: trailingMovingView, for: self)
viewsTobeRemoved.append(createdView)
}
}
}
internal func uninstallMovingView() {
for view in subviews {
if viewsTobeRemoved.contains(view) {
view.removeFromSuperview()
}
}
leadingSwipeActions = nil
trailingSwipeActions = nil
self.addSubview(self.contentView)
}
}
extension SSTableCell: SSPanControllerDelegate {
public func slideRevealedCellsBack() {
self.slideActionsBack(leading: true)
self.slideActionsBack(leading: false)
}
}
| 42.331984 | 501 | 0.652161 |
d97d418763a4bff2c6d0d790c15e2828933717cc | 2,707 | //
// ViewController.swift
// tippy
//
// Created by John Law on 18/12/16.
// Copyright © 2016 John Law. All rights reserved.
//
import UIKit
var tipPercentage = [0.18, 0.2, 0.25]
class ViewController: UIViewController {
// Access UserDefaults
let defaults = UserDefaults.standard
let formatter = NumberFormatter()
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var resultView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Get a string value and provide a default string in the case the string is nil.
let defaultTip = defaults.integer(forKey: "defaultTip")
tipControl.selectedSegmentIndex = defaultTip
billField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
formatter.numberStyle = .currency
tipLabel.text = formatter.string(from: NSNumber(value: 0))
totalLabel.text = formatter.string(from: NSNumber(value: 0))
let firstTip = defaults.string(forKey: "firstTip") ?? "18"
let secondTip = defaults.string(forKey: "secondTip") ?? "20"
let thirdTip = defaults.string(forKey: "thirdTip") ?? "25"
tipPercentage[0] = Double(firstTip)!/100
tipPercentage[1] = Double(secondTip)!/100
tipPercentage[2] = Double(thirdTip)!/100
tipControl.setTitle(firstTip + "%", forSegmentAt: 0)
tipControl.setTitle(secondTip + "%", forSegmentAt: 1)
tipControl.setTitle(thirdTip + "%", forSegmentAt: 2)
if (billField.text != "") {
calculate()
}
}
@IBAction func onTap(_ sender: Any) {
// Force to view the keyboard
view.endEditing(true)
}
@IBAction func calculateTip(_ sender: Any) {
calculate()
}
func calculate() {
let bill = Double(billField.text!) ?? 0
let tip = bill * tipPercentage[tipControl.selectedSegmentIndex]
let total = bill + tip
tipLabel.text = formatter.string(from: NSNumber(value: tip))
totalLabel.text = formatter.string(from: NSNumber(value: total))
}
@IBAction func goBack(segue: UIStoryboardSegue) {
}
@IBAction func reset(_ sender: Any) {
billField.text = ""
calculate()
}
}
| 29.747253 | 89 | 0.637606 |
2038e1226621bea01516fb48671b84a4a07a6a52 | 5,835 | import SwiftUI
public struct PrivacyPolicy: View {
public init() {}
public var body: some View {
ScrollView(.vertical, showsIndicators: true) {
VStack(alignment: HorizontalAlignment.leading, spacing: 12) {
Text("""
**Privacy Policy**
Valentin Knabel built the Puffery app as a Freemium app. This SERVICE is provided by Valentin Knabel at no cost and is intended for use as is.
This page is used to inform visitors regarding my policies with the collection, use, and disclosure of Personal Information if anyone decided to use my Service.
If you choose to use my Service, then you agree to the collection and use of information in relation to this policy. The Personal Information that I collect is used for providing and improving the Service. I will not use or share your information with anyone except as described in this Privacy Policy.
The terms used in this Privacy Policy have the same meanings as in our Terms and Conditions, which is accessible at Puffery unless otherwise defined in this Privacy Policy.
**Information Collection and Use**
For a better experience, while using our Service, I may require you to provide us with certain personally identifiable information, including but not limited to Push Notification Device Tokens, Email Address. The information that I request will be retained on your device and is not collected by me in any way.
The app does use third party services that may collect information used to identify you.
Link to privacy policy of third party service providers used by the app
* Instabug https://instabug.com/privacy
**Log Data**
I want to inform you that whenever you use my Service, in a case of an error in the app I collect data and information (through third party products) on your phone called Log Data. This Log Data may include information such as your device Internet Protocol (“IP”) address, device name, operating system version, the configuration of the app when utilizing my Service, the time and date of your use of the Service, and other statistics.
**Cookies**
Cookies are files with a small amount of data that are commonly used as anonymous unique identifiers. These are sent to your browser from the websites that you visit and are stored on your device's internal memory.
This Service does not use these “cookies” explicitly. However, the app may use third party code and libraries that use “cookies” to collect information and improve their services. You have the option to either accept or refuse these cookies and know when a cookie is being sent to your device. If you choose to refuse our cookies, you may not be able to use some portions of this Service.
**Service Providers**
I may employ third-party companies and individuals due to the following reasons:
* To facilitate our Service;
* To provide the Service on our behalf;
* To perform Service-related services; or
* To assist us in analyzing how our Service is used.
I want to inform users of this Service that these third parties have access to your Personal Information. The reason is to perform the tasks assigned to them on our behalf. However, they are obligated not to disclose or use the information for any other purpose.
**Security**
I value your trust in providing us your Personal Information, thus we are striving to use commercially acceptable means of protecting it. But remember that no method of transmission over the internet, or method of electronic storage is 100% secure and reliable, and I cannot guarantee its absolute security.
**Links to Other Sites**
This Service may contain links to other sites. If you click on a third-party link, you will be directed to that site. Note that these external sites are not operated by me. Therefore, I strongly advise you to review the Privacy Policy of these websites. I have no control over and assume no responsibility for the content, privacy policies, or practices of any third-party sites or services.
**Children’s Privacy**
These Services do not address anyone under the age of 13. I do not knowingly collect personally identifiable information from children under 13. In the case I discover that a child under 13 has provided me with personal information, I immediately delete this from our servers. If you are a parent or guardian and you are aware that your child has provided us with personal information, please contact me so that I will be able to do necessary actions.
**Changes to This Privacy Policy**
I may update our Privacy Policy from time to time. Thus, you are advised to review this page periodically for any changes. I will notify you of any changes by posting the new Privacy Policy on this page.
This policy is effective as of 2020-06-19
**Contact Us**
If you have any questions or suggestions about my Privacy Policy, do not hesitate to contact me at [email protected].
This privacy policy page was created at privacypolicytemplate.net and modified/generated by App Privacy Policy Generator.
""")
}
.lineLimit(nil)
.padding()
}
.navigationBarTitle("PrivacyPolicy.Title")
.record("privacy")
}
}
struct PrivacyPolicy_Previews: PreviewProvider {
static var previews: some View {
PrivacyPolicy()
}
}
| 67.848837 | 467 | 0.698543 |
f876ae0945b6851cdaf48e82280240dbd69037dc | 488 | //
// GymClassInstance.swift
// Uplift
//
// Created by Cornell AppDev on 4/22/18.
// Copyright © 2018 Uplift. All rights reserved.
//
import Foundation
struct GymClassInstance {
let classDescription: String
let classDetailId: String
let className: String
let duration: Double
let endTime: Date
let gymId: String
let imageURL: URL
let instructor: String
let isCancelled: Bool
let location: String
let startTime: Date
let tags: [Tag]
}
| 20.333333 | 49 | 0.684426 |
b9f0d9bc70930eeca3cdd69c734178cbffa2edb2 | 862 | //
// StandardImageView.swift
// UniSpace
//
// Created by KiKan Ng on 11/1/2019.
// Copyright © 2019 KiKan Ng. All rights reserved.
//
import UIKit
class StandardImageView: UIImageView {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(cornerRadius: CGFloat = 0, hasBackground: Bool = false, hasShadow: Bool = false) {
super.init(frame: CGRect.zero)
self.contentMode = .scaleAspectFill
self.clipsToBounds = true
self.backgroundColor = hasBackground ? UIColor(white: 0.95, alpha: 1) : .clear
self.layer.cornerRadius = cornerRadius
self.translatesAutoresizingMaskIntoConstraints = false
}
func setBackground(hasBackground: Bool) {
self.backgroundColor = hasBackground ? UIColor(white: 0.95, alpha: 1) : .clear
}
}
| 27.806452 | 91 | 0.672854 |
2894d639ea0e6e95a50f02ec7de5d5ecc250227a | 5,562 | //
// DotLottieFile.swift
// LottieFiles
//
// Created by Evandro Harrison Hoffmann on 27/06/2020.
// Copyright © 2020 LottieFiles. All rights reserved.
//
import Foundation
import Zip
/// Detailed .lottie file structure
public struct DotLottieFile {
public let remoteUrl: URL
public let localUrl: URL
public static let manifestFileName: String = "manifest.json"
public static let animationsFolderName: String = "animations"
public static let imagesFolderName: String = "images"
/// Manifest.json file loading
public var manifest: DotLottieManifest? {
let path = localUrl.appendingPathComponent(DotLottieFile.manifestFileName)
return try? DotLottieManifest.load(from: path)
}
/// Animation url for main animation
public var animationUrl: URL? {
guard let animationId = manifest?.animations.first?.id else { return nil }
let dotLottieJson = "\(DotLottieFile.animationsFolderName)/\(animationId).json"
return localUrl.appendingPathComponent(dotLottieJson)
}
/// Animations folder url
public var animationsUrl: URL {
localUrl.appendingPathComponent("\(DotLottieFile.animationsFolderName)")
}
/// All files in animations folder
public var animations: [URL] {
FileManager.default.urls(for: animationsUrl) ?? []
}
/// Images folder url
public var imagesUrl: URL {
localUrl.appendingPathComponent("\(DotLottieFile.imagesFolderName)")
}
/// All images in images folder
public var images: [URL] {
FileManager.default.urls(for: imagesUrl) ?? []
}
/// Constructor with url.
/// Returns nil if is not a .lottie file and decompression failed
/// - Parameters:
/// - url: URL to .lottie file
/// - cache: Cache type
public init?(url: URL, cache: DotLottieCache) {
self.remoteUrl = url
self.localUrl = DotLottieUtils.animationsDirectoryURL(for: url)
guard url.isDotLottieFile else { return nil }
guard decompress(from: url, in: localUrl, cache: cache) else { return nil }
}
/// Decompresses .lottie file and saves to local temp folder
/// - Parameters:
/// - url: url to .lottie file
/// - directory: url to destination of decompression contents
/// - cache: Cache type
/// - Returns: success true/false
private func decompress(from url: URL, in directory: URL, cache: DotLottieCache) -> Bool {
guard cache.shouldDecompress(from: url) else {
DotLottieUtils.log("File already decompressed at \(directory.path)")
return true
}
Zip.addCustomFileExtension(DotLottieUtils.dotLottieExtension)
do {
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)
try Zip.unzipFile(url, destination: directory, overwrite: true, password: nil)
DotLottieUtils.log("File decompressed to \(directory.path)")
return true
} catch {
DotLottieUtils.log("Extraction of dotLottie archive failed with error: \(error)")
return false
}
}
/// Creates dotLottieFile from animation json
/// - Parameters:
/// - url: url of JSON lottie animation
/// - directory: directory to save file
/// - loop: loop enabled
/// - themeColor: theme color
/// - Returns: URL of .lottie file
static func compress(jsonLottieAt url: URL, in directory: URL = DotLottieUtils.tempDirectoryURL, loop: Bool = true, themeColor: String = "#ffffff") -> URL? {
Zip.addCustomFileExtension(DotLottieUtils.dotLottieExtension)
do {
let fileName = url.deletingPathExtension().lastPathComponent
let dotLottieDirectory = directory.appendingPathComponent(fileName)
try FileManager.default.createDirectory(at: dotLottieDirectory, withIntermediateDirectories: true, attributes: nil)
let animationsDirectory = dotLottieDirectory.appendingPathComponent("animations")
try FileManager.default.createDirectory(at: animationsDirectory, withIntermediateDirectories: true, attributes: nil)
let animationData = try Data(contentsOf: url)
try animationData.write(to: animationsDirectory.appendingPathComponent(fileName).appendingPathExtension("json"))
let manifest = DotLottieManifest(animations: [
DotLottieAnimation(loop: loop, themeColor: themeColor, speed: 1.0, id: fileName)
], version: "1.0", author: "LottieFiles", generator: "LottieFiles dotLottieLoader-iOS 0.1.4")
let manifestUrl = dotLottieDirectory.appendingPathComponent("manifest").appendingPathExtension("json")
let manifestData = try manifest.encode()
try manifestData.write(to: manifestUrl)
let dotLottieUrl = directory.appendingPathComponent(fileName).appendingPathExtension("lottie")
try Zip.zipFiles(paths: [animationsDirectory, manifestUrl], zipFilePath: dotLottieUrl, password: nil, compression: .DefaultCompression, progress: { progress in
DotLottieUtils.log("Compressing dotLottie file: \(progress)")
})
return dotLottieUrl
} catch {
DotLottieUtils.log("Extraction of dotLottie archive failed with error: \(error)")
return nil
}
}
}
| 41.819549 | 171 | 0.654261 |
0a891a7d2489593a425db276274672041ecfd189 | 334 | //
// UIStoryboard+UIViewController.swift
// NewsiOS
//
// Created by Karen Madoyan on 2021/1/27.
//
import UIKit
extension UIStoryboard {
func instantiateViewController<T: NameDescribable>(_ viewControllerType: T.Type) -> T {
self.instantiateViewController(withIdentifier: viewControllerType.typeName) as! T
}
}
| 22.266667 | 91 | 0.730539 |
64b2f4e0d413d630dd4dfae24c58803c477aecff | 149 | //
// MinuteChart.swift
// GGChart_Swift
//
// Created by 赵海伟 on 2020/4/16.
//
import Foundation
public class MinuteChart: UIView {
}
| 10.642857 | 34 | 0.630872 |
72cf243475f0c7afb18ccdfdb97f8ee3279523ed | 768 | import XCTest
import SwiftUI
@testable import ViewInspector
#if os(iOS)
final class EditButtonTests: XCTestCase {
func testInspect() throws {
XCTAssertNoThrow(try EditButton().inspect())
}
func testExtractionFromSingleViewContainer() throws {
let view = AnyView(EditButton())
XCTAssertNoThrow(try view.inspect().editButton())
}
func testExtractionFromMultipleViewContainer() throws {
let view = HStack { EditButton(); EditButton() }
XCTAssertNoThrow(try view.inspect().editButton(0))
XCTAssertNoThrow(try view.inspect().editButton(1))
}
func testEditMode() throws {
let view = EditButton()
XCTAssertNoThrow(try view.inspect().editMode())
}
}
#endif
| 24.774194 | 59 | 0.661458 |
7903a18cfa2a71eaf89293bbb0ad1dedf2845a3f | 4,408 | import PromiseKit
import XCTest
class Test222: XCTestCase {
// 2.2.2: If `onFulfilled` is a function,
func test2221() {
// 2.2.2.1: it must be called after `promise` is fulfilled,
// with `promise`’s fulfillment value as its first argument.
suiteFulfilled(1) { (promise, exes, sentinel) -> () in
promise.then { value->() in
XCTAssertEqual(value, sentinel)
exes[0].fulfill()
return
}
return
}
}
func test2222() {
// 2.2.2.2: it must not be called before `promise` is fulfilled
let e1 = expectationWithDescription("fulfilled after a delay")
let (p1, f1, _) = Promise<Int>.defer()
var isFulfilled = false
p1.then { _->() in
XCTAssertTrue(isFulfilled)
e1.fulfill()
}
later {
f1(dummy)
isFulfilled = true
}
waitForExpectationsWithTimeout(1, handler: nil)
let e2 = expectationWithDescription("never fulfilled")
let (p2, f2, _) = Promise<Int>.defer()
var onFulfilledCalled = false
p2.then { _->() in
onFulfilledCalled = true
e2.fulfill()
}
later {
XCTAssertFalse(onFulfilledCalled)
e2.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func test22231() {
// 2.2.2.3: it must not be called more than once.
// already-fulfilled
var timesCalled = 0
Promise(dummy).then { _->() in
XCTAssertEqual(++timesCalled, 1)
}
}
func test22232() {
// trying to fulfill a pending promise more than once, immediately
let (promise, fulfiller, _) = Promise<Int>.defer()
var timesCalled = 0
promise.then { _->() in
XCTAssertEqual(++timesCalled, 1)
}
fulfiller(dummy)
fulfiller(dummy)
}
func test22233() {
let (promise, fulfiller, _) = Promise<Int>.defer()
var timesCalled = 0
let e1 = expectationWithDescription("trying to fulfill a pending promise more than once, delayed")
promise.then { _->() in
XCTAssertEqual(++timesCalled, 1)
e1.fulfill()
}
later {
fulfiller(dummy)
fulfiller(dummy)
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func test22234() {
let (promise, fulfiller, _) = Promise<Int>.defer()
var timesCalled = 0
let e1 = expectationWithDescription("trying to fulfill a pending promise more than once, immediately then delayed")
promise.then { _->() in
XCTAssertEqual(++timesCalled, 1)
e1.fulfill()
}
fulfiller(dummy)
later {
fulfiller(dummy)
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func test22235() {
let (promise, fulfiller, _) = Promise<Int>.defer()
var timesCalled = [0, 0, 0]
let desc = "when multiple `then` calls are made, spaced apart in time"
let e1 = expectationWithDescription(desc)
let e2 = expectationWithDescription(desc)
let e3 = expectationWithDescription(desc)
promise.then { _->() in
XCTAssertEqual(++timesCalled[0], 1)
e1.fulfill()
}
later(50.0) {
promise.then { _->() in
XCTAssertEqual(++timesCalled[1], 1)
e2.fulfill()
}
return
}
later(100.0) {
promise.then { _->() in
XCTAssertEqual(++timesCalled[2], 1)
e3.fulfill()
}
return
}
later(150) {
fulfiller(dummy)
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func test2224() {
let (promise, fulfiller, _) = Promise<Int>.defer()
var timesCalled = [0, 0]
let e1 = expectationWithDescription("when `then` is interleaved with fulfillment")
promise.then { _->() in
XCTAssertEqual(++timesCalled[0], 1)
}
fulfiller(dummy)
promise.then { _->() in
XCTAssertEqual(++timesCalled[1], 1)
e1.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
}
| 27.898734 | 123 | 0.533575 |
4b4af8d0651961fb726b39b622cc10125b3749bc | 630 | //
// UIImage+AVFoundation.swift
// BrainKit
//
// Created by Ondřej Hanák on 04. 05. 2020.
// Copyright © 2020 Userbrain. All rights reserved.
//
import AVFoundation
import UIKit
extension UIImage {
public static func makeFromVideo(url: URL, at time: Double = 0) throws -> UIImage {
let asset = AVURLAsset(url: url)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
let timestamp = CMTime(seconds: time, preferredTimescale: 60)
let imageRef = try generator.copyCGImage(at: timestamp, actualTime: nil)
let image = UIImage(cgImage: imageRef)
return image
}
}
| 27.391304 | 84 | 0.738095 |
3a290329a1bff87ecb2c08398774c13691140adb | 10,102 | //
// CalendarSession.swift
// sama
//
// Created by Viktoras Laukevičius on 6/8/21.
//
import Foundation
struct CalendarEventsRequest: ApiRequest {
typealias T = EmptyBody
typealias U = CalendarBlocks
let uri = "/calendar/events"
let logKey = "/calendar/events"
let method: HttpMethod = .get
let query: [URLQueryItem]
}
struct CalendarMetadata: Decodable, Equatable {
let accountId: String
let calendarId: String
let colour: String?
let title: String
let selected: Bool
}
struct CalendarsResponse: Decodable {
let calendars: [CalendarMetadata]
}
struct AccountCalendarId: Hashable {
let accountId: String
let calendarId: String
}
struct CalendarsRequest: ApiRequest {
typealias T = EmptyBody
typealias U = CalendarsResponse
let uri = "/calendar/calendars"
let logKey = "/calendar/calendars"
let method: HttpMethod = .get
}
protocol CalendarContextProvider {
var blocksForDayIndex: [Int: [CalendarBlockedTime]] { get }
}
struct RegisterDeviceRequest: ApiRequest {
typealias U = EmptyBody
let uri = "/user/me/register-device"
let logKey = "/user/me/register-device"
let method: HttpMethod = .post
let body: RegisterDeviceData
}
struct UpdateTimeZoneBody: Encodable {
let timeZone: String
}
struct UpdateTimeZoneRequest: ApiRequest {
typealias U = EmptyBody
let uri = "/user/me/update-time-zone"
let logKey = "/user/me/update-time-zone"
let method: HttpMethod = .post
let body: UpdateTimeZoneBody
}
struct DomainUser: Decodable {
let userId: String
}
struct DomainUserSettings: Decodable {
struct Marketing: Decodable {
let newsletterSubscriptionEnabled: Bool?
}
struct Meeting: Decodable {
let defaultTitle: String?
let blockOutSlots: Bool
}
let marketingPreferences: Marketing
let meetingPreferences: Meeting
}
struct UserDetailsRequest: ApiRequest {
typealias U = DomainUser
let uri = "/user/me/"
let logKey = "/user/me/"
let method: HttpMethod = .get
}
struct UserSettingsRequest: ApiRequest {
typealias U = DomainUserSettings
let uri = "/user/me/settings"
let logKey = "/user/me/settings"
let method: HttpMethod = .get
}
enum DataReadiness<T>: Equatable where T: Equatable {
case idle
case failed
case loading
case ready(T)
var isDisplayable: Bool {
switch self {
case .idle, .loading: return false
case .failed, .ready: return true
}
}
}
struct CalendarUiMetadata: Equatable {
let colours: [AccountCalendarId: Int?]
}
final class CalendarSession: CalendarContextProvider {
var reloadHandler: () -> Void = {}
var userIdUpdateHandler: ((String) -> Void)?
var presentError: (ApiError) -> Void = { _ in }
let currentDayIndex: Int
let blockSize = 5
private(set) var blocksForDayIndex: [Int: [CalendarBlockedTime]] = [:]
private var queuedBlocksForDayIndex: [Int: [CalendarBlockedTime]] = [:]
let api: Api
let refDate = CalendarDateUtils.shared.uiRefDate
private let calendar = Calendar.current
private var isBlockBusy: [Int: Bool] = [:]
private var calendarMetadataReadiness: DataReadiness<CalendarUiMetadata> = .idle
private lazy var dateF: DateFormatter = {
let f = DateFormatter()
f.dateFormat = "YYYY-MM-dd"
return f
}()
private let transformer: BlockedTimesForDaysTransformer
private var lastTimeZoneUpdate = Date(timeIntervalSince1970: 0)
private var isUserUpdated = false
init(api: Api, currentDayIndex: Int) {
self.api = api
self.currentDayIndex = currentDayIndex
self.transformer = BlockedTimesForDaysTransformer(currentDayIndex: currentDayIndex, refDate: refDate, calendar: calendar)
}
func firstFocusDayIndex(centerOffset: Int) -> Int {
let weekday = Calendar.current.component(.weekday, from: CalendarDateUtils.shared.dateNow)
if weekday == 1 || weekday == 7 {
return currentDayIndex + centerOffset
} else {
// 2 monday num
return currentDayIndex - (weekday - 2)
}
}
func focusDay(isSingleDay: Bool, visibleColumnIndices: [Int]) -> Int {
let todayIndex = 5000
if isSingleDay {
return visibleColumnIndices.contains(todayIndex) ? todayIndex : (visibleColumnIndices.first ?? todayIndex)
} else {
return visibleColumnIndices.first ?? todayIndex
}
}
func loadInitial() {
loadCalendar(blockIndices: (-1 ... 1))
}
func loadIfAvailableBlock(at index: Int) {
if !(isBlockBusy[index] ?? false) {
loadCalendar(blockIndices: (index ... index))
}
}
func invalidateAndLoadBlocks(_ indices: ClosedRange<Int>) {
blocksForDayIndex = [:]
isBlockBusy = [:]
loadCalendar(blockIndices: indices)
}
func invalidateCalendarsMetadata() {
calendarMetadataReadiness = .idle
}
func setupNotificationsTokenObserver() {
RemoteNotificationsTokenSync.shared.observer = { [weak self] data in
self?.api.request(for: RegisterDeviceRequest(body: data)) { _ in }
}
RemoteNotificationsTokenSync.shared.syncToken()
}
private func updateTimeZoneIfNeeded() {
let timestamp = CalendarDateUtils.shared.dateNow
guard timestamp.timeIntervalSince(lastTimeZoneUpdate) > 24 * 60 * 60 else { return }
lastTimeZoneUpdate = timestamp
let req = UpdateTimeZoneRequest(body: UpdateTimeZoneBody(timeZone: TimeZone.current.identifier))
api.request(for: req) { _ in }
}
private func updateUserIfNeeded() {
guard !isUserUpdated else { return }
isUserUpdated = true
api.request(for: UserDetailsRequest()) {
switch $0 {
case let .success(user):
self.userIdUpdateHandler?(user.userId)
case .failure:
self.isUserUpdated = false
}
}
}
private func loadCalendarsMetadataIfNeeded() {
guard calendarMetadataReadiness == .idle || calendarMetadataReadiness == .failed else { return }
calendarMetadataReadiness = .loading
api.request(for: CalendarsRequest()) {
switch $0 {
case let .success(response):
var result: [AccountCalendarId: Int] = [:]
let colourBase = 0x6B5844
let redBase = Double((colourBase >> 16) & 0xFF)
let greenBase = Double((colourBase >> 8) & 0xFF)
let blueBase = Double(colourBase & 0xFF)
for calendar in response.calendars {
let id = AccountCalendarId(
accountId: calendar.accountId,
calendarId: calendar.calendarId
)
let externalColour = calendar.colour?.fromHex ?? colourBase
let externalColourRed = Double((externalColour >> 16) & 0xFF)
let externalColourGreen = Double((externalColour >> 8) & 0xFF)
let externalColourBlue = Double(externalColour & 0xFF)
let red = Int((redBase + externalColourRed) / 2)
let green = Int((greenBase + externalColourGreen) / 2)
let blue = Int((blueBase + externalColourBlue) / 2)
let colour = (red << 16) + (green << 8) + blue
result[id] = colour
}
self.calendarMetadataReadiness = .ready(CalendarUiMetadata(colours: result))
case .failure:
self.calendarMetadataReadiness = .failed
}
self.enrichBlocksWithContextAndReload(keys: nil)
}
}
private func enrichBlocksWithContextAndReload(keys: [Int]?) {
switch calendarMetadataReadiness {
case let .ready(metadata):
for key in (keys ?? Array(queuedBlocksForDayIndex.keys)) {
blocksForDayIndex[key] = queuedBlocksForDayIndex[key]?.map {
var r = $0
r.colour = metadata.colours[$0.id] ?? nil
return r
}
}
self.reloadHandler()
default:
self.reloadHandler()
}
}
private func loadCalendar(blockIndices: ClosedRange<Int>) {
updateTimeZoneIfNeeded()
updateUserIfNeeded()
loadCalendarsMetadataIfNeeded()
for idx in blockIndices {
isBlockBusy[idx] = true
}
print("loadCalendar(\(blockIndices))")
let daysBack = blockIndices.lowerBound * blockSize
let daysForward = blockIndices.count * blockSize
let start = calendar.date(byAdding: .day, value: daysBack, to: refDate)!
let end = calendar.date(byAdding: .day, value: daysForward, to: start)!
let req = CalendarEventsRequest(query: [
URLQueryItem(name: "startDate", value: dateF.string(from: start)),
URLQueryItem(name: "endDate", value: dateF.string(from: end)),
URLQueryItem(name: "timezone", value: "UTC")
])
api.request(for: req) {
switch $0 {
case let .success(model):
let daysRange = (daysBack ... (daysBack + daysForward))
let result = self.transformer.transform(model: model, in: daysRange)
let touchedKeys = Array(result.keys)
for (k, v) in result {
self.queuedBlocksForDayIndex[k] = v
}
DispatchQueue.main.async {
if self.calendarMetadataReadiness.isDisplayable {
self.enrichBlocksWithContextAndReload(keys: touchedKeys)
}
}
case let .failure(err):
for idx in blockIndices {
self.isBlockBusy[idx] = false
}
self.presentError(err)
}
}
}
}
| 31.083077 | 129 | 0.609681 |
29b602381c9dfea131d07c07bee8ab8e302935d2 | 1,018 | //
// PhotoPickerImageCountView.swift
// hhh
//
// Created by Zack・Zheng on 2018/2/1.
// Copyright © 2018年 Zack・Zheng. All rights reserved.
//
import UIKit
class PhotoPickerImageCountView: UICollectionReusableView {
let label: UILabel = {
let view = UILabel()
view.textAlignment = NSTextAlignment.center
view.backgroundColor = UIColor.white
view.font = UIFont.systemFont(ofSize: 15)
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
static var reuseIdentifier = "PhotoPickerImageCountView"
override func layoutSubviews() {
super.layoutSubviews()
label.frame = bounds
}
fileprivate func setup() {
addSubview(label)
}
var count: Int = 0 {
didSet {
label.text = "\(count) 张照片"
}
}
}
| 20.77551 | 60 | 0.579568 |
0a8b862fde1761a54afaeaa9174fe823587f9c77 | 687 | //: # Assignment 1
//: ## Swift Programming: First Steps
//:
//: This is the first assignment for CPSC 575 ("iProgramming for Creative Minds"), Fall 2018
//: ## Instructions
//:
//: This assignment is a Swift Playground document. It consists of three (3) pages. Go through each page, read the task descriptions and add your Swift code accordingly.
//: ## Submission
//:
//: This assignment playground needs to be submitted through our D2L course website. See our course website for details about the submission date and time.
//:
//: Should you be late with your submission, then you will incur a **50% penalty** on the points of this assignment.
//: [Let's get started ...](@next)
| 38.166667 | 169 | 0.716157 |
b9cc87bf856a1a77023f6b1cd7434f31dba6a2ab | 3,285 | //
// GraphLabels.swift
// SwiftUIChartsPlayground
//
// Created by Matthew Roche on 25/11/2021.
//
import SwiftUI
struct GraphLabels: View {
@Binding var xMin: Date
@Binding var xMax: Date
@Binding var yMin: CGFloat
@Binding var yMax: CGFloat
var paddingX: CGFloat
var paddingY: CGFloat
var paddingForLabels: CGFloat
var lineLabels: [CGFloat]
var yAxisLabels: Bool
var body: some View {
GeometryReader { geo in
Canvas { context, size in
func adjustCoordinates(_ point: CGPoint) -> CGPoint {
let invertedY = size.height - point.y
return CGPoint(
x: (point.x / size.width * (size.width - (2 * paddingX))) + paddingX,
y: (invertedY / size.height * (size.height - (2 * paddingY + paddingForLabels))) + paddingY
)
}
func labelValueToHeight(_ label: CGFloat) -> CGFloat {
(label - yMin) / (yMax - yMin)
}
if yAxisLabels {
for lineLabel in lineLabels {
context.draw(
Text(lineLabel, format: .number),
at: adjustCoordinates(CGPoint(
x: 0,
y: size.height * labelValueToHeight(lineLabel))
)
)
}
}
context.draw(
Text(xMin.formatted(date: .numeric, time: .omitted))
.font(.caption2),
in: CGRect(
origin: adjustCoordinates(
CGPoint(
x: (paddingForLabels),
y: (-paddingForLabels + 5)
)
),
size: CGSize(width: 70, height: 10)
)
)
context.draw(
Text(xMax.formatted(date: .numeric, time: .omitted))
.font(.caption2),
in: CGRect(
origin: adjustCoordinates(
CGPoint(
x: (size.width - 60),
y: (-paddingForLabels + 5)
)
),
size: CGSize(width: 70, height: 10)
)
)
}
}
}
}
struct GraphLabels_Previews: PreviewProvider {
@State static var xMin: Date = Calendar.current.date(byAdding: .day, value: -15, to: Date())!
@State static var xMax: Date = Date()
@State static var yMin: CGFloat = -2
@State static var yMax: CGFloat = 12
static var previews: some View {
GraphLabels(xMin: $xMin, xMax: $xMax, yMin: $yMin, yMax: $yMax, paddingX: 20, paddingY: 20, paddingForLabels: 20, lineLabels: [0, 5, 10], yAxisLabels: true).frame(width: .infinity, height: 200)
}
}
| 34.21875 | 201 | 0.4207 |
799de11db39ce9fde3e239cd45f688114f696e5a | 700 | import Foundation
import Shared
import PromiseKit
class UpdateSensorsIntentHandler: NSObject, UpdateSensorsIntentHandling {
func handle(intent: UpdateSensorsIntent, completion: @escaping (UpdateSensorsIntentResponse) -> Void) {
Current.Log.info("starting")
firstly {
HomeAssistantAPI.authenticatedAPIPromise
}.then {
$0.UpdateSensors(trigger: .Siri)
}.done {
Current.Log.info("finished successfully")
completion(.init(code: .success, userActivity: nil))
}.catch { error in
Current.Log.error("failed: \(error)")
completion(.init(code: .failure, userActivity: nil))
}
}
}
| 31.818182 | 107 | 0.638571 |
2944e4083432634fd7b11ca485fedaeac3bf03f3 | 340 | //
// ContentView.swift
// MyFirstAppClips
//
// Created by Luan Nguyen on 10/12/2020.
//
import SwiftUI
struct ContentView: View {
// MARK: - BODY
var body: some View {
Home()
}
}
// MARK: - PREVIEW
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 14.782609 | 46 | 0.614706 |
18a9f3a3fdd336fee02dfd61a60a5f6545586959 | 1,116 | //
// JoRefreshFooterControl.swift
// iOS Example
//
// Created by django on 7/20/17.
// Copyright © 2017 django. All rights reserved.
//
import UIKit
import JoRefresh
class JoRefreshFooterControl: JoRefreshControl {
let lable: UILabel = UILabel()
override func updatePercent(_ percent: CGFloat) {
super.updatePercent(percent)
if isRefreshing {
lable.text = "刷新中"
} else {
lable.text = percent == 1 ? "松手刷新" : "上拉刷新"
}
}
override func beginRefreshing() {
super.beginRefreshing()
lable.text = "刷新中"
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(lable)
lable.textColor = .black
lable.textAlignment = .center
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
lable.frame = bounds
backgroundColor = UIColor(white: 1, alpha: 0.5)
layer.borderWidth = 1
}
}
| 22.32 | 59 | 0.582437 |
fee42ae13e19d1a1ab9bd01080a0d2d4db406c2d | 2,873 | //
// CityListCell.swift
// WeatherRx
//
// Created by MacOS on 1.03.2022.
//
import Foundation
import UIKit
import RxCocoa
import RxSwift
class CityListCell: UICollectionViewCell {
var disposeBag: DisposeBag = DisposeBag()
lazy var cityListCellContentView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.layer.cornerRadius = 10
view.clipsToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.masksToBounds = false
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOpacity = 1
view.layer.shadowOffset = .zero
view.layer.shadowRadius = 2
view.layer.shouldRasterize = true
view.layer.rasterizationScale = UIScreen.main.scale
return view
}()
lazy var cityListCellImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.layer.cornerRadius = 10
imageView.layer.masksToBounds = true
imageView.clipsToBounds = true
return imageView
}()
lazy var cityListCellNameLabel: UILabel = {
let label = UILabel()
label.textAlignment = .left
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 35)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var cityListCellAddFavoriteButton: UIButton = {
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "favorite1")?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
button.layer.cornerRadius = 20
button.translatesAutoresizingMaskIntoConstraints = false
button.clipsToBounds = true
return button
}()
lazy var width: NSLayoutConstraint = {
let width = contentView.widthAnchor.constraint(equalToConstant: bounds.size.width)
width.isActive = true
return width
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.translatesAutoresizingMaskIntoConstraints = false
setUpCityListCellContentView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
width.constant = bounds.size.width
return contentView.systemLayoutSizeFitting(CGSize(width: targetSize.width, height: 1))
}
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
}
| 33.022989 | 193 | 0.673512 |
e0f52ed31115c07fc70ef58e800b8392c78f3c79 | 3,464 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension AsyncSequence {
@inlinable
public __consuming func flatMap<SegmentOfResult: AsyncSequence>(
_ transform: @escaping (Element) async throws -> SegmentOfResult
) -> AsyncThrowingFlatMapSequence<Self, SegmentOfResult> {
return AsyncThrowingFlatMapSequence(self, transform: transform)
}
}
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
public struct AsyncThrowingFlatMapSequence<Base: AsyncSequence, SegmentOfResult: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let transform: (Base.Element) async throws -> SegmentOfResult
@usableFromInline
init(
_ base: Base,
transform: @escaping (Base.Element) async throws -> SegmentOfResult
) {
self.base = base
self.transform = transform
}
}
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension AsyncThrowingFlatMapSequence: AsyncSequence {
public typealias Element = SegmentOfResult.Element
public typealias AsyncIterator = Iterator
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
let transform: (Base.Element) async throws -> SegmentOfResult
@usableFromInline
var currentIterator: SegmentOfResult.AsyncIterator?
@usableFromInline
var finished = false
@usableFromInline
init(
_ baseIterator: Base.AsyncIterator,
transform: @escaping (Base.Element) async throws -> SegmentOfResult
) {
self.baseIterator = baseIterator
self.transform = transform
}
@inlinable
public mutating func next() async throws -> SegmentOfResult.Element? {
while !finished {
if var iterator = currentIterator {
do {
guard let element = try await iterator.next() else {
currentIterator = nil
continue
}
// restore the iterator since we just mutated it with next
currentIterator = iterator
return element
} catch {
finished = true
throw error
}
} else {
guard let item = try await baseIterator.next() else {
return nil
}
let segment: SegmentOfResult
do {
segment = try await transform(item)
var iterator = segment.makeAsyncIterator()
guard let element = try await iterator.next() else {
currentIterator = nil
continue
}
currentIterator = iterator
return element
} catch {
finished = true
currentIterator = nil
throw error
}
}
}
return nil
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), transform: transform)
}
}
| 29.862069 | 97 | 0.623268 |
f4304dacaf2febac6759502d5247aed24fee6b37 | 720 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Sworm",
platforms: [
.macOS(.v10_13),
.iOS(.v11),
.tvOS(.v11),
.watchOS(.v4),
],
products: [
.library(
name: "Sworm",
targets: ["Sworm"]
),
.library(
name: "SwormTools",
targets: ["SwormTools"]
),
],
targets: [
.target(name: "Sworm"),
.target(name: "SwormTools"),
.testTarget(
name: "SwormTests",
dependencies: ["Sworm", "SwormTools"]
),
]
)
| 21.818182 | 96 | 0.494444 |
87e40a4e7da44ade4e21d1f8e35ea998be86b2aa | 1,342 | //
// PropertyObserver.swift
// VirtualTourist
//
// Created by Jan Skála on 01/04/2020.
// Copyright © 2020 Jan Skála. All rights reserved.
//
import Foundation
class PropertyObserver{
let id = IdGenerator.shared.generateUniqueId()
private var callbackDisposes = [ObservableProperty.DisposeCallback]()
func observeProperty<T>(_ property: ApiProperty<T>,_ callback: @escaping ApiProperty<T>.ChangeCallback){
callbackDisposes.append(property.addCallback(identifier: id, callback: callback))
}
func observeProperty<T>(_ property: ObservableProperty<T>, _ callback: @escaping ObservableProperty<T>.ChangeCallback){
callbackDisposes.append(property.addCallback(identifier: id, callback: callback))
}
func observeDependent<T, R>(_ property1: ObservableProperty<T>, _ property2: ObservableProperty<R>, callback: @escaping ((T?, R?)->Void?)){
var value1: T? = nil
var value2: R? = nil
observeProperty(property1){ val1 in
value1 = val1
callback(value1, value2)
}
observeProperty(property2){ val2 in
value2 = val2
callback(value1, value2)
}
}
func dispose(){
for dispose in callbackDisposes{
dispose(id)
}
callbackDisposes = []
}
}
| 30.5 | 143 | 0.645306 |
9102a4f66f67f2943206251f95370c1843c2ea06 | 10,548 | import Combine
import Foundation
import Dispatch
extension Publisher where Output: Hashable {
/**
Caches events and replays when latest incoming value equals a previous and the execution of the map took more time than the specified duration else produces new events.
*/
public func cacheMap<T>(
whenExceeding duration: DispatchTimeInterval,
cache: Persisting<Output, T> = .nsCache(),
input: @escaping (Output) -> T
) -> Publishers.CompactMap<Publishers.Scan<Self, (cache: Persisting<Self.Output, T>, key: Optional<Self.Output>, value: Optional<T>)>, T> {
return scan((
cache: cache,
key: Optional<Output>.none,
value: Optional<T>.none
)) {
if let _ = $0.cache.value($1) {
return (
cache: $0.cache,
key: $1,
value: nil
)
} else {
let start = Date()
let result = input($1)
let end = Date()
if duration.seconds.map({ end.timeIntervalSince(start) > $0 }) == true {
return (
cache: Self.adding(
key: $1,
value: result,
cache: $0.cache
),
key: $1,
value: nil
)
} else {
return (
cache: $0.cache,
key: nil,
value: result
)
}
}
}
.compactMap { tuple in
tuple.value ??
tuple.key.flatMap { tuple.cache.value($0) }
}
}
/**
Caches events and replays when latest incoming value equals a previous else produces new events.
*/
public func cacheMap<T>(
cache: Persisting<Output, T> = .nsCache(),
when condition: @escaping (Output) -> Bool = { _ in true },
transform: @escaping (Output) -> T
) -> Publishers.CompactMap<Publishers.Scan<Self, (cache: Persisting<Self.Output, T>, key: Optional<Self.Output>, value: Optional<T>)>, T> {
return scan((
cache: cache,
key: Optional<Output>.none,
value: Optional<T>.none
)) {(
cache: condition($1) == false ? $0.cache : Self.adding(
key: $1,
value: transform($1),
cache: $0.cache
),
key: $1,
value: condition($1) ? nil : transform($1)
)}
.compactMap { tuple in
tuple.value ??
tuple.key.flatMap { tuple.cache.value($0) }
}
}
/**
Caches publishers and replays their events when latest incoming value equals a previous else produces new events.
*/
public func cacheFlatMap<T>(
cache: Persisting<Output, AnyPublisher<T, Failure>> = .nsCache(),
when condition: @escaping (Output) -> Bool = { _ in true },
publisher input: @escaping (Output) -> AnyPublisher<T, Failure>
) -> Publishers.FlatMap<AnyPublisher<T, Self.Failure>, Publishers.CompactMap<Publishers.Scan<Self, (cache: Persisting<Self.Output, AnyPublisher<T, Self.Failure>>, key: Optional<Self.Output>, value: Optional<AnyPublisher<T, Self.Failure>>)>, AnyPublisher<T, Self.Failure>>> {
return cachedReplay(
cache: cache,
when: condition,
publisher: input
)
.flatMap { $0 }
}
/**
Cancels previous Publisher and flatmaps provided Publisher. Exists as a convenience when toggling between `cacheFlatMapLatest` and `flatMapLatest`.
*/
func flatMapLatest<T>(
publisher input: @escaping (Output) -> AnyPublisher<T, Failure>
) -> Publishers.SwitchToLatest<AnyPublisher<T, Self.Failure>, Publishers.Map<Self, AnyPublisher<T, Self.Failure>>> {
map(input).switchToLatest()
}
/**
Caches completed publishers and replays their events when latest incoming value equals a previous else produces new events.
Cancels playback of previous publishers.
*/
public func cacheFlatMapLatest<T>(
cache: Persisting<Output, AnyPublisher<T, Failure>> = .nsCache(),
when condition: @escaping (Output) -> Bool = { _ in true },
publisher input: @escaping (Output) -> AnyPublisher<T, Failure>
) -> Publishers.SwitchToLatest<AnyPublisher<T, Self.Failure>, Publishers.CompactMap<Publishers.Scan<Self, (cache: Persisting<Self.Output, AnyPublisher<T, Self.Failure>>, key: Optional<Self.Output>, value: Optional<AnyPublisher<T, Self.Failure>>)>, AnyPublisher<T, Self.Failure>>> {
return cachedReplay(
cache: cache,
when: condition,
publisher: input
)
.switchToLatest()
}
private func cachedReplay<T>(
cache: Persisting<Output, AnyPublisher<T, Failure>>,
when condition: @escaping (Output) -> Bool = { _ in true },
publisher input: @escaping (Output) -> AnyPublisher<T, Failure>
) -> Publishers.CompactMap<Publishers.Scan<Self, (cache: Persisting<Self.Output, AnyPublisher<T, Self.Failure>>, key: Optional<Self.Output>, value: Optional<AnyPublisher<T, Self.Failure>>)>, AnyPublisher<T, Self.Failure>> {
return scan((
cache: cache,
key: Optional<Output>.none,
value: Optional<AnyPublisher<T, Failure>>.none
)) {(
cache: condition($1) == false ? $0.cache : Self.adding(
key: $1,
value: input($1)
.multicast(subject: UnboundReplaySubject())
.autoconnect()
.eraseToAnyPublisher()
,
cache: $0.cache
),
key: $1,
value: condition($1) ? nil : input($1)
)}
.compactMap { tuple in
tuple.value ??
tuple.key.flatMap { tuple.cache.value($0) }
}
}
/**
Caches publishers and replays their events when latest incoming value equals a previous value and output Date is greater than Date of event else produces new events.
*/
public func cacheFlatMapInvalidatingOn<T>(
when condition: @escaping (Output) -> Bool = { _ in true },
cache: Persisting<Output, AnyPublisher<T, Failure>> = .nsCache(),
publisher input: @escaping (Output) -> AnyPublisher<(T, Date), Failure>
) -> Publishers.FlatMap<AnyPublisher<T, Self.Failure>, Publishers.CompactMap<Publishers.Scan<Self, (cache: Persisting<Self.Output, AnyPublisher<T, Self.Failure>>, key: Optional<Self.Output>, value: Optional<AnyPublisher<T, Self.Failure>>)>, AnyPublisher<T, Self.Failure>>> {
return cachedReplayInvalidatingOn(
when: condition,
cache: cache,
publisher: input
)
.flatMap { $0 }
}
private func cachedReplayInvalidatingOn<T>(
when condition: @escaping (Output) -> Bool = { _ in true },
cache: Persisting<Output, AnyPublisher<T, Failure>>,
publisher input: @escaping (Output) -> AnyPublisher<(T, Date), Failure>
) -> Publishers.CompactMap<Publishers.Scan<Self, (cache: Persisting<Self.Output, AnyPublisher<T, Self.Failure>>, key: Optional<Self.Output>, value: Optional<AnyPublisher<T, Self.Failure>>)>, AnyPublisher<T, Self.Failure>> {
return scan((
cache: cache,
key: Optional<Output>.none,
value: Optional<AnyPublisher<T, Failure>>.none
)) {(
cache: condition($1) == false ? $0.cache : Self.adding(
key: $1,
value: Self.replayingInvalidatingOn(input: input($1)),
cache: $0.cache
),
key: $1,
value: condition($1) ? nil : input($1).map { $0.0 }.eraseToAnyPublisher()
)}
.compactMap { tuple in
tuple.value?.eraseToAnyPublisher() ??
tuple.key.flatMap { tuple.cache.value($0) }
}
}
private static func replayingInvalidatingOn<T>(
input: AnyPublisher<(T, Date), Failure>
) -> AnyPublisher<T, Failure> {
let now = { Date() }
return input
.multicast(subject: UnboundReplaySubject())
.autoconnect()
.flatMap { new, expiration in
expiration >= now()
? Combine.Just(new).setFailureType(to: Failure.self).eraseToAnyPublisher()
: replayingInvalidatingOn(input: input)
}
.eraseToAnyPublisher()
}
private static func adding<Key, Value>(
key: Key,
value: @autoclosure () -> Value,
cache: Persisting<Key, Value>
) -> Persisting<Key, Value> {
if cache.value(key) == nil {
cache.set(
value(),
key
)
return cache
} else {
return cache
}
}
}
private extension DispatchTimeInterval {
var seconds: Double? {
switch self {
case .seconds(let value):
return Double(value)
case .milliseconds(let value):
return Double(value) * 0.001
case .microseconds(let value):
return Double(value) * 0.000001
case .nanoseconds(let value):
return Double(value) * 0.000000001
case .never:
return nil
@unknown default:
return nil
}
}
}
public struct Persisting<Key, Value> {
let set: (Value, Key) -> Void
let value: (Key) -> Value?
public init<Backing>(
backing: Backing,
set: @escaping (Backing, Value, Key) -> Void,
value: @escaping (Backing, Key) -> Value?
) {
self.set = {
set(backing, $0, $1)
}
self.value = {
value(backing, $0)
}
}
}
extension Persisting {
public static func nsCache<K, V>() -> Persisting<K, V> {
return Persisting<K, V>(
backing: NSCache<AnyObject, AnyObject>(),
set: { cache, value, key in
cache.setObject(
value as AnyObject,
forKey: key as AnyObject
)
},
value: { cache, key in
cache
.object(forKey: key as AnyObject)
.flatMap { $0 as? V }
}
)
}
}
| 37.537367 | 285 | 0.542852 |
0a1cda0a6295adf2b8976679ff80403370aaed30 | 20,717 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import struct Foundation.CharacterSet
import struct Foundation.Data
import struct Foundation.Date
import struct Foundation.URL
import struct Foundation.URLComponents
import NIOCore
import NIOHTTP1
import SotoCrypto
import SotoSignerV4
/// Object encapsulating all the information needed to generate a raw HTTP request to AWS
public struct AWSRequest {
public let region: Region
public var url: URL
public let serviceProtocol: ServiceProtocol
public let operation: String
public let httpMethod: HTTPMethod
public var httpHeaders: HTTPHeaders
public var body: Body
/// Create HTTP Client request from AWSRequest.
/// If the signer's credentials are available the request will be signed. Otherwise defaults to an unsigned request
func createHTTPRequest(signer: AWSSigner, serviceConfig: AWSServiceConfig) -> AWSHTTPRequest {
// if credentials are empty don't sign request
if signer.credentials.isEmpty() {
return self.toHTTPRequest(byteBufferAllocator: serviceConfig.byteBufferAllocator)
}
return self.toHTTPRequestWithSignedHeader(signer: signer, serviceConfig: serviceConfig)
}
/// Create HTTP Client request from AWSRequest
func toHTTPRequest(byteBufferAllocator: ByteBufferAllocator) -> AWSHTTPRequest {
return AWSHTTPRequest(url: url, method: httpMethod, headers: httpHeaders, body: body.asPayload(byteBufferAllocator: byteBufferAllocator))
}
/// Create HTTP Client request with signed headers from AWSRequest
func toHTTPRequestWithSignedHeader(signer: AWSSigner, serviceConfig: AWSServiceConfig) -> AWSHTTPRequest {
let payload = self.body.asPayload(byteBufferAllocator: serviceConfig.byteBufferAllocator)
let bodyDataForSigning: AWSSigner.BodyData?
switch payload.payload {
case .byteBuffer(let buffer):
bodyDataForSigning = .byteBuffer(buffer)
case .stream(let reader):
if signer.name == "s3", !serviceConfig.options.contains(.s3DisableChunkedUploads) {
assert(reader.size != nil, "S3 stream requires size")
var headers = httpHeaders
// need to add this header here as it needs to be included in the signed headers
headers.add(name: "x-amz-decoded-content-length", value: reader.size!.description)
let (signedHeaders, seedSigningData) = signer.startSigningChunks(url: url, method: httpMethod, headers: headers, date: Date())
let s3Reader = S3ChunkedStreamReader(
size: reader.size!,
seedSigningData: seedSigningData,
signer: signer,
byteBufferAllocator: serviceConfig.byteBufferAllocator,
read: reader.read
)
let payload = AWSPayload.streamReader(s3Reader)
return AWSHTTPRequest(url: url, method: httpMethod, headers: signedHeaders, body: payload)
} else {
bodyDataForSigning = .unsignedPayload
}
case .empty:
bodyDataForSigning = nil
}
let signedHeaders = signer.signHeaders(url: url, method: httpMethod, headers: httpHeaders, body: bodyDataForSigning, date: Date())
return AWSHTTPRequest(url: url, method: httpMethod, headers: signedHeaders, body: payload)
}
// return new request with middleware applied
func applyMiddlewares(_ middlewares: [AWSServiceMiddleware], config: AWSServiceConfig) throws -> AWSRequest {
var awsRequest = self
// apply middleware to request
let context = AWSMiddlewareContext(options: config.options)
for middleware in middlewares {
awsRequest = try middleware.chain(request: awsRequest, context: context)
}
return awsRequest
}
}
extension AWSRequest {
internal init(operation operationName: String, path: String, httpMethod: HTTPMethod, configuration: AWSServiceConfig) throws {
var headers = HTTPHeaders()
guard let url = URL(string: "\(configuration.endpoint)\(path)"), let _ = url.host else {
throw AWSClient.ClientError.invalidURL
}
// set x-amz-target header
if let target = configuration.amzTarget {
headers.replaceOrAdd(name: "x-amz-target", value: "\(target).\(operationName)")
}
self.region = configuration.region
self.url = url
self.serviceProtocol = configuration.serviceProtocol
self.operation = operationName
self.httpMethod = httpMethod
self.httpHeaders = headers
// Query and EC2 protocols require the Action and API Version in the body
switch configuration.serviceProtocol {
case .query, .ec2:
let params = ["Action": operationName, "Version": configuration.apiVersion]
self.body = try .text(QueryEncoder().encode(params)!)
default:
self.body = .empty
}
addStandardHeaders()
}
internal init<Input: AWSEncodableShape>(
operation operationName: String,
path: String,
httpMethod: HTTPMethod,
input: Input,
hostPrefix: String? = nil,
configuration: AWSServiceConfig
) throws {
var headers = HTTPHeaders()
var path = path
var hostPrefix = hostPrefix
var body: Body = .empty
var queryParams: [(key: String, value: Any)] = []
// validate input parameters
try input.validate()
// set x-amz-target header
if let target = configuration.amzTarget {
headers.replaceOrAdd(name: "x-amz-target", value: "\(target).\(operationName)")
}
// TODO: should replace with Encodable
let mirror = Mirror(reflecting: input)
var memberVariablesCount = mirror.children.count - Input._encoding.count
// extract header, query and uri params
for encoding in Input._encoding {
if let value = mirror.getAttribute(forKey: encoding.label) {
switch encoding.location {
case .header(let location):
switch value {
case let string as AWSRequestEncodableString:
string.encoded.map { headers.replaceOrAdd(name: location, value: $0) }
default:
headers.replaceOrAdd(name: location, value: "\(value)")
}
case .headerPrefix(let prefix):
if let dictionary = value as? AWSRequestEncodableDictionary {
dictionary.encoded.forEach { headers.replaceOrAdd(name: "\(prefix)\($0.key)", value: $0.value) }
}
case .querystring(let location):
switch value {
case let string as AWSRequestEncodableString:
string.encoded.map { queryParams.append((key: location, value: $0)) }
case let array as AWSRequestEncodableArray:
array.encoded.forEach { queryParams.append((key: location, value: $0)) }
case let dictionary as AWSRequestEncodableDictionary:
dictionary.encoded.forEach { queryParams.append($0) }
default:
queryParams.append((key: location, value: "\(value)"))
}
case .uri(let location):
path = path
.replacingOccurrences(of: "{\(location)}", with: Self.urlEncodePathComponent(String(describing: value)))
.replacingOccurrences(of: "{\(location)+}", with: Self.urlEncodePath(String(describing: value)))
case .hostname(let location):
hostPrefix = hostPrefix?
.replacingOccurrences(of: "{\(location)}", with: Self.urlEncodePathComponent(String(describing: value)))
default:
memberVariablesCount += 1
}
}
}
switch configuration.serviceProtocol {
case .json, .restjson:
if let shapeWithPayload = Input.self as? AWSShapeWithPayload.Type {
let payload = shapeWithPayload._payloadPath
if let payloadBody = mirror.getAttribute(forKey: payload) {
switch payloadBody {
case let awsPayload as AWSPayload:
Self.verifyStream(operation: operationName, payload: awsPayload, input: shapeWithPayload)
body = .raw(awsPayload)
case let shape as AWSEncodableShape:
body = .json(try shape.encodeAsJSON(byteBufferAllocator: configuration.byteBufferAllocator))
default:
preconditionFailure("Cannot add this as a payload")
}
} else {
body = .empty
}
} else {
// only include the body if there are members that are output in the body.
if memberVariablesCount > 0 {
body = .json(try input.encodeAsJSON(byteBufferAllocator: configuration.byteBufferAllocator))
} else if httpMethod == .PUT || httpMethod == .POST {
// PUT and POST requests require a body even if it is empty. This is not the case with XML
body = .json(configuration.byteBufferAllocator.buffer(string: "{}"))
}
}
case .restxml:
if let shapeWithPayload = Input.self as? AWSShapeWithPayload.Type {
let payload = shapeWithPayload._payloadPath
if let payloadBody = mirror.getAttribute(forKey: payload) {
switch payloadBody {
case let awsPayload as AWSPayload:
Self.verifyStream(operation: operationName, payload: awsPayload, input: shapeWithPayload)
body = .raw(awsPayload)
case let shape as AWSEncodableShape:
var rootName: String?
// extract custom payload name
if let encoding = Input.getEncoding(for: payload), case .body(let locationName) = encoding.location {
rootName = locationName
}
body = .xml(try shape.encodeAsXML(rootName: rootName, namespace: configuration.xmlNamespace))
default:
preconditionFailure("Cannot add this as a payload")
}
} else {
body = .empty
}
} else {
// only include the body if there are members that are output in the body.
if memberVariablesCount > 0 {
body = .xml(try input.encodeAsXML(namespace: configuration.xmlNamespace))
}
}
case .query:
if let query = try input.encodeAsQuery(with: ["Action": operationName, "Version": configuration.apiVersion]) {
body = .text(query)
}
case .ec2:
if let query = try input.encodeAsQueryForEC2(with: ["Action": operationName, "Version": configuration.apiVersion]) {
body = .text(query)
}
}
guard var urlComponents = URLComponents(string: "\(configuration.endpoint)\(path)") else {
throw AWSClient.ClientError.invalidURL
}
if let hostPrefix = hostPrefix, let host = urlComponents.host {
urlComponents.host = hostPrefix + host
}
// add queries from the parsed path to the query params list
if let pathQueryItems = urlComponents.queryItems {
for item in pathQueryItems {
queryParams.append((key: item.name, value: item.value ?? ""))
}
}
// Set query params. Percent encode these ourselves as Foundation and AWS disagree on what should be percent encoded in the query values
// Also the signer doesn't percent encode the queries so they need to be encoded here
if queryParams.count > 0 {
let urlQueryString = queryParams
.map { (key: $0.key, value: "\($0.value)") }
.sorted {
// sort by key. if key are equal then sort by value
if $0.key < $1.key { return true }
if $0.key > $1.key { return false }
return $0.value < $1.value
}
.map { "\($0.key)=\(Self.urlEncodeQueryParam($0.value))" }
.joined(separator: "&")
urlComponents.percentEncodedQuery = urlQueryString
}
guard let url = urlComponents.url else {
throw AWSClient.ClientError.invalidURL
}
headers = Self.calculateChecksumHeader(
headers: headers,
body: body,
shapeType: Input.self,
configuration: configuration
)
self.region = configuration.region
self.url = url
self.serviceProtocol = configuration.serviceProtocol
self.operation = operationName
self.httpMethod = httpMethod
self.httpHeaders = headers
self.body = body
addStandardHeaders()
}
/// Calculate checksum header for request
/// - Parameters:
/// - headers: request headers
/// - body: request body
/// - shapeType: Request shape type
/// - configuration: Service configuration
/// - Returns: New set of headers
private static func calculateChecksumHeader<Input: AWSEncodableShape>(
headers: HTTPHeaders,
body: Body,
shapeType: Input.Type,
configuration: AWSServiceConfig
) -> HTTPHeaders {
var headers = headers
var checksumType: ChecksumType?
if shapeType._options.contains(.checksumHeader) {
checksumType = headers["x-amz-sdk-checksum-algorithm"].first.map { ChecksumType(rawValue: $0) } ?? nil
}
if checksumType == nil {
if Input._options.contains(.checksumRequired) ||
(Input._options.contains(.md5ChecksumHeader) && configuration.options.contains(.calculateMD5))
{
checksumType = .md5
}
}
guard let checksumType = checksumType,
let buffer = body.asByteBuffer(byteBufferAllocator: configuration.byteBufferAllocator),
let checksumHeader = Self.checksumHeaders[checksumType],
headers[checksumHeader].first == nil else { return headers }
var checksum: String?
switch checksumType {
case .crc32:
let bufferView = ByteBufferView(buffer)
let crc = soto_crc32(0, bytes: bufferView)
var crc32 = UInt32(crc).bigEndian
let data = withUnsafePointer(to: &crc32) { pointer in
return Data(bytes: pointer, count: 4)
}
checksum = data.base64EncodedString()
case .crc32c:
let bufferView = ByteBufferView(buffer)
let crc = soto_crc32c(0, bytes: bufferView)
var crc32 = UInt32(crc).bigEndian
let data = withUnsafePointer(to: &crc32) { pointer in
return Data(bytes: pointer, count: 4)
}
checksum = data.base64EncodedString()
case .sha1:
checksum = calculateChecksum(buffer, function: Insecure.SHA1.self)
case .sha256:
checksum = calculateChecksum(buffer, function: SHA256.self)
case .md5:
checksum = calculateChecksum(buffer, function: Insecure.MD5.self)
}
if let checksum = checksum {
headers.add(name: checksumHeader, value: checksum)
}
return headers
}
/// Add headers standard to all requests "content-type" and "user-agent"
private mutating func addStandardHeaders() {
httpHeaders.replaceOrAdd(name: "user-agent", value: "Soto/6.0")
guard httpHeaders["content-type"].first == nil else {
return
}
guard httpMethod != .GET, httpMethod != .HEAD else {
return
}
if case .restjson = serviceProtocol, case .raw = body {
httpHeaders.replaceOrAdd(name: "content-type", value: "binary/octet-stream")
} else {
httpHeaders.replaceOrAdd(name: "content-type", value: serviceProtocol.contentType)
}
}
/// this list of query allowed characters comes from https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
static let queryAllowedCharacters = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
static let pathAllowedCharacters = CharacterSet.urlPathAllowed.subtracting(.init(charactersIn: "+"))
static let pathComponentAllowedCharacters = CharacterSet.urlPathAllowed.subtracting(.init(charactersIn: "+/"))
/// percent encode query parameter value.
private static func urlEncodeQueryParam(_ value: String) -> String {
return value.addingPercentEncoding(withAllowedCharacters: AWSRequest.queryAllowedCharacters) ?? value
}
/// percent encode path value.
private static func urlEncodePath(_ value: String) -> String {
return value.addingPercentEncoding(withAllowedCharacters: AWSRequest.pathAllowedCharacters) ?? value
}
/// percent encode path component value. ie also encode "/"
private static func urlEncodePathComponent(_ value: String) -> String {
return value.addingPercentEncoding(withAllowedCharacters: AWSRequest.pathComponentAllowedCharacters) ?? value
}
/// verify streaming is allowed for this operation
internal static func verifyStream(operation: String, payload: AWSPayload, input: AWSShapeWithPayload.Type) {
guard case .stream(let reader) = payload.payload else { return }
precondition(input._options.contains(.allowStreaming), "\(operation) does not allow streaming of data")
precondition(reader.size != nil || input._options.contains(.allowChunkedStreaming), "\(operation) does not allow chunked streaming of data. Please supply a data size.")
}
private static func calculateChecksum<H: HashFunction>(_ byteBuffer: ByteBuffer, function: H.Type) -> String? {
// if request has a body, calculate the MD5 for that body
let byteBufferView = byteBuffer.readableBytesView
return byteBufferView.withContiguousStorageIfAvailable { bytes in
return Data(H.hash(data: bytes)).base64EncodedString()
}
}
private enum ChecksumType: String {
case crc32 = "CRC32"
case crc32c = "CRC32C"
case sha1 = "SHA1"
case sha256 = "SHA256"
case md5 = "MD5"
}
private static let checksumHeaders: [ChecksumType: String] = [
.crc32: "x-amz-checksum-crc32",
.crc32c: "x-amz-checksum-crc32c",
.sha1: "x-amz-checksum-sha1",
.sha256: "x-amz-checksum-sha256",
.md5: "content-md5",
]
}
private protocol AWSRequestEncodableArray {
var encoded: [String] { get }
}
extension Array: AWSRequestEncodableArray {
var encoded: [String] { return self.map { "\($0)" }}
}
private protocol AWSRequestEncodableDictionary {
var encoded: [(key: String, value: String)] { get }
}
extension Dictionary: AWSRequestEncodableDictionary {
var encoded: [(key: String, value: String)] {
return self.map { (key: "\($0.key)", value: "\($0.value)") }
}
}
private protocol AWSRequestEncodableString {
var encoded: String? { get }
}
extension CustomCoding: AWSRequestEncodableString where Coder: CustomEncoder {
var encoded: String? {
return Coder.string(from: self.wrappedValue)
}
}
extension OptionalCustomCoding: AWSRequestEncodableString where Coder: CustomEncoder {
var encoded: String? {
guard let value = self.wrappedValue else { return nil }
return Coder.string(from: value)
}
}
| 43.070686 | 176 | 0.608438 |
ac63e5645b1d10734f4bff83ad8371dc30b76046 | 604 | //
// Visibility.swift
//
//
// Created by Jonathan Downing on 12/4/20.
//
import Foundation
public struct Visibility: Hashable, CustomStringConvertible {
public enum Modifier {
case lessThan, equalTo, greaterThan
}
public var modifier: Modifier = .equalTo
public var measurement: Measurement<UnitLength>
public var description: String {
switch modifier {
case .lessThan:
return "<\(measurement)"
case .equalTo:
return "\(measurement)"
case .greaterThan:
return ">\(measurement)"
}
}
}
| 19.483871 | 61 | 0.604305 |
79404b3a1409152f35912365c614854b0b0bbf49 | 2,300 | /*
* Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar
*
* 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
struct Config {
static var observer: FileObserver = {
Log.debug("Setting up listener for \(Paths.configFile)")
return FileObserver(path: Paths.configFile, callback: {
Log.debug("Initiating config singleton reset.")
reload()
})
}()
private static var _instance: Configuration = Configuration(dictionary: [String: Any]())
static var instance: Configuration {
if (_instance.version == nil) { reload() }
return _instance
}
static var fileExists: Bool {
return FileManager.default.fileExists(atPath: Paths.configFile)
}
static func observe() {
// This is a silly no-op to initiate the `observer` variable.
if observer as FileObserver? != nil {}
reload()
}
static func reload() {
Log.debug("Reloading Configuration singleton from file")
let reader = JSONReader(filePath: Paths.configFile)
if reader.failure { return }
let dictionary = reader.dictionary
// Discard the old configuration and instantiate a new one.
_instance = Configuration(dictionary: dictionary)
NotificationCenter.default.post(name:.configChanged, object: nil, userInfo: nil)
}
}
| 39.655172 | 133 | 0.734783 |
d6346fe6c7f6e590d7d59bbacfabb1445ce164c4 | 1,447 | //
// TabbarView.swift
// ACHNBrowserUI
//
// Created by Thomas Ricouard on 08/04/2020.
// Copyright © 2020 Thomas Ricouard. All rights reserved.
//
import SwiftUI
import Backend
struct TabbarView: View {
@EnvironmentObject private var uiState: UIState
func tabbarItem(text: String, image: String) -> some View {
VStack {
Image(image)
Text(text)
}
}
var body: some View {
TabView(selection: $uiState.selectedTab) {
Group {
DashboardView().tabItem{
self.tabbarItem(text: "Dashboard", image: "icon-bells")
}.tag(UIState.Tab.dashboard)
CategoriesView(categories: Category.items()).tabItem{
self.tabbarItem(text: "Catalog", image: "icon-leaf")
}.tag(UIState.Tab.items)
TurnipsView().tabItem {
tabbarItem(text: "Turnips", image: "icon-turnip")
}.tag(UIState.Tab.turnips)
VillagersListView().environmentObject(UserCollection.shared).tabItem{
self.tabbarItem(text: "Villagers", image: "icon-villager")
}.tag(UIState.Tab.villagers)
CollectionListView().tabItem{
self.tabbarItem(text: "My Stuff", image: "icon-cardboard")
}.tag(UIState.Tab.collection)
}
}.accentColor(.white)
}
}
| 32.886364 | 85 | 0.555632 |
5014ef073f3206a4ff215a51db0dd3fdedd7fda2 | 2,071 | import Foundation
import Fluent
/// A `Pivot` holding a siblings relation between `User` and `ForumPost`.
final class PostLikes: Model {
static let schema = "post+likes"
// MARK: Properties
/// The ID of the pivot.
@ID(key: .id) var id: UUID?
/// The type of like reaction. Needs to be optional to conform to `ModifiablePivot`'s
/// required `init(_:_:)`.
@Field(key: "liketype") var likeType: LikeType?
/// TRUE if this forum post is favorited by this user.
@Field(key: "favorite") var isFavorite: Bool
// MARK: Relationships
/// The associated `User` who likes this.
@Parent(key: "user") var user: User
/// The associated `ForumPost` that was liked.
@Parent(key: "forumPost") var post: ForumPost
// MARK: Initialization
// Used by Fluent
init() { }
/// Initializes a new PostLikes pivot.
///
/// - Parameters:
/// - user: The left hand `User` model.
/// - post: The right hand `ForumPost` model.
init(_ userID: UUID, _ post: ForumPost) throws {
self.$user.id = userID
self.$post.id = try post.requireID()
self.$post.value = post
self.isFavorite = false
}
/// Convenience initializer to provide `.likeType` initializaion.
///
/// - Parameters:
/// - user: The left hand `User` model.
/// - post: The right hand `ForumPost` model.
/// - likeType: The type of like reaction for this pivot.
convenience init(_ userID: UUID, _ post: ForumPost, likeType: LikeType) throws {
try self.init(userID, post)
self.likeType = likeType
}
}
struct CreatePostLikesSchema: AsyncMigration {
func prepare(on database: Database) async throws {
try await database.schema("post+likes")
.id()
.unique(on: "user", "forumPost")
.field("liketype", .string)
.field("favorite", .bool, .required)
.field("user", .uuid, .required, .references("user", "id", onDelete: .cascade))
.field("forumPost", .int, .required, .references("forumpost", "id", onDelete: .cascade))
.create()
}
func revert(on database: Database) async throws {
try await database.schema("post+likes").delete()
}
}
| 27.613333 | 93 | 0.662965 |
3a1636ece123aa9c80b0f3586e78471c1f00af76 | 4,745 | /*
Copyright (c) 2019, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
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 OWNER 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
/// A protocol that all outcome queries are expected to conform to.
public protocol OCKAnyOutcomeQuery: OCKEntityQuery {
/// Any array of local database IDs of tass for which outcomes should be returned.
var taskIDs: [String] { get set }
/// The order in which the results will be sorted when returned from the query.
var sortDescriptors: [OCKOutcomeSortDescriptor] { get set }
}
public extension OCKAnyOutcomeQuery {
init(_ query: OCKAnyOutcomeQuery) {
if let other = query as? Self {
self = other
return
}
self = Self(query as OCKEntityQuery)
self.taskIDs = query.taskIDs
self.sortDescriptors = query.sortDescriptors
}
}
/// Describes the order in which tasks can be sorted when queried.
public enum OCKOutcomeSortDescriptor: Equatable {
case date(ascending: Bool)
fileprivate var extendedVersion: OCKOutcomeQuery.SortDescriptor {
switch self {
case .date(let ascending): return .date(ascending: ascending)
}
}
}
/// A query that limits which outcomes will be returned when fetching.
public struct OCKOutcomeQuery: OCKAnyOutcomeQuery, Equatable {
/// Specifies the order in which query results will be sorted.
enum SortDescriptor: Equatable {
case date(ascending: Bool)
case createdDate(ascending: Bool)
fileprivate var basicVersion: OCKOutcomeSortDescriptor? {
switch self {
case .date(let ascending): return .date(ascending: ascending)
case .createdDate: return nil
}
}
}
/// An array of universally unique identifiers of tasks for which outcomes should be returned.
public var taskUUIDs: [UUID] = []
/// An array of remote IDs of tasks for which outcomes should be returned.
public var taskRemoteIDs: [String] = []
/// An array of group identifiers to match against.
public var groupIdentifiers: [String?] = []
/// The order in which the results will be sorted when returned from the query.
public var sortDescriptors: [OCKOutcomeSortDescriptor] {
get { extendedSortDescriptors.compactMap { $0.basicVersion } }
set { extendedSortDescriptors = newValue.map { $0.extendedVersion } }
}
/// The order in which the results will be sorted when returned from the query. This property supports
/// additional sort descriptors unique to `OCKStore`.
internal var extendedSortDescriptors: [SortDescriptor] = []
/// An array of tags to match against. If an object's tags contains one or more of entries, it will match the query.
public var tags: [String] = []
// MARK: OCKAnyOutcomeQuery
public var ids: [String] = []
public var uuids: [UUID] = []
public var remoteIDs: [String?] = []
public var taskIDs: [String] = []
public var dateInterval: DateInterval?
public var limit: Int?
public var offset: Int = 0
public init() {
extendedSortDescriptors = [
.date(ascending: false),
.createdDate(ascending: false)
]
}
}
| 39.541667 | 120 | 0.713383 |
f753f7bb4c4f2ec1df33605f6b1672a7f1d11176 | 516 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol P {
class func ^(t: e? = D> {
func c) {
public var f = D>(c(A? {
}
}
}
func c) {
}
typealias e : Sequence, e
| 27.157895 | 79 | 0.705426 |
16a5fb6c506aa803064c4d1959b944492132cafa | 446 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Actor",
products: [
.library(name: "Actor", targets: ["Actor"]),
],
dependencies: [
],
targets: [
.target(name: "Actor", dependencies: []),
.testTarget(name: "ActorTests", dependencies: ["Actor"]),
]
)
| 22.3 | 96 | 0.605381 |
76f2bd33a297083ad0e4e2a06ef5d93498a07c1c | 8,112 | //
// RequestError.swift
// Siesta
//
// Created by Paul on 2015/6/26.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
/**
Information about a failed resource request.
Siesta can encounter errors from many possible sources, including:
- client-side encoding / request creation issues,
- network connectivity problems,
- protocol issues (e.g. certificate problems),
- server errors (404, 500, etc.), and
- client-side parsing and entity validation failures.
`RequestError` presents all these errors in a uniform structure. Several properties preserve diagnostic information,
which you can use to intercept specific known errors, but these diagnostic properties are all optional. They are not
even mutually exclusive: Siesta errors do not break cleanly into HTTP-based vs. Error / NSError-based, for example,
because network implementations may sometimes provide _both_ an underlying `Error` _and_ an HTTP diagnostic.
The one ironclad guarantee that `RequestError` makes is the presence of a `userMessage`.
*/
public struct RequestError: Error
{
/**
A description of this error suitable for showing to the user. Typically messages are brief and in plain language,
e.g. “Not found,” “Invalid username or password,” or “The internet connection is offline.”
- Note: This property is similar to Swift’s `Error.localizedDescription`, but is **not optional**. Siesta
guarantees the presence of a user-displayable message on a `RequestError`, so you never have to come up with
a default error message for your UI.
*/
public var userMessage: String
/// The HTTP status code (e.g. 404) if this error came from an HTTP response.
public var httpStatusCode: Int?
/// The response body if this error came from an HTTP response. Its meaning is API-specific.
public var entity: Entity<Any>?
/// Details about the underlying error. Errors originating from Siesta will have a cause from `RequestError.Cause`.
/// Errors originating from the `NetworkingProvider` or custom `ResponseTransformer`s have domain-specific causes.
public var cause: Error?
/// The time at which the error occurred.
public let timestamp: TimeInterval = now()
/**
Initializes the error using a network response.
If the `userMessage` parameter is nil, this initializer uses `error` or the response’s status code to generate
a user message. That failing, it gives a generic failure message.
*/
public init(
response: HTTPURLResponse?,
content: Any?,
cause: Error?,
userMessage: String? = nil)
{
self.httpStatusCode = response?.statusCode
self.cause = cause
if let content = content
{ self.entity = Entity<Any>(response: response, content: content) }
if let message = userMessage
{ self.userMessage = message }
else if let message = cause?.localizedDescription
{ self.userMessage = message }
else if let code = self.httpStatusCode
{ self.userMessage = HTTPURLResponse.localizedString(forStatusCode: code).capitalized }
else
{ self.userMessage = NSLocalizedString("Request failed", comment: "userMessage") } // Is this reachable?
}
/**
Initializes the error using an underlying error.
*/
public init(
userMessage: String,
cause: Error,
entity: Entity<Any>? = nil)
{
self.userMessage = userMessage
self.cause = cause
self.entity = entity
}
}
public extension RequestError
{
/**
Underlying causes of errors reported by Siesta. You will find these on the `RequestError.cause` property.
(Note that `cause` may also contain errors from the underlying network library that do not appear here.)
The primary purpose of these error causes is to aid debugging. Client code rarely needs to work with them,
but they can be useful if you want to add special handling for specific errors.
For example, if you’re working with an API that sometimes returns garbled text data that isn’t decodable,
and you want to show users a placeholder message instead of an error, then (1) gee, that’s weird, and
(2) you can turn that one specific error into a success by adding a transformer:
configure {
$0.pipeline[.parsing].add(GarbledResponseHandler())
}
...
struct GarbledResponseHandler: ResponseTransformer {
func process(_ response: Response) -> Response {
switch response {
case .success:
return response
case .failure(let error):
if error.cause is RequestError.Cause.InvalidTextEncoding {
return .success(Entity<Any>(
content: "Nothingness. Tumbleweeds. The Void.",
contentType: "text/string"))
} else {
return response
}
}
}
}
*/
public enum Cause
{
// MARK: Request Errors
/// Resource’s URL is nil or syntactically invalid.
public struct InvalidURL: Error
{
public let urlSource: URLConvertible?
}
/// Unable to create a text request with the requested character encoding.
public struct UnencodableText: Error
{
public let encoding: String.Encoding
public let text: String
}
/// Unable to create a JSON request using an object that is not JSON-encodable.
public struct InvalidJSONObject: Error { }
/// Unable to create a URL-encoded request, probably due to unpaired Unicode surrogate chars.
public struct NotURLEncodable: Error
{
public let offendingString: String
}
// MARK: Network Errors
/// Underlying network request was cancelled before response arrived.
public struct RequestCancelled: Error
{
public let networkError: Error?
}
// TODO: Consider explicitly detecting offline connection
// MARK: Response Errors
/// Server sent 304 (“not changed”), but we have no local data for the resource.
public struct NoLocalDataFor304: Error { }
/// The server sent a text encoding name that the OS does not recognize.
public struct InvalidTextEncoding: Error
{
public let encodingName: String
}
/// The server’s response could not be decoded using the text encoding it specified.
public struct UndecodableText: Error
{
public let encoding: String.Encoding
}
/// Siesta’s default JSON parser accepts only dictionaries and arrays, but the server
/// sent a response containing a bare JSON primitive.
public struct JSONResponseIsNotDictionaryOrArray: Error
{
public let actualType: Any.Type
}
/// The server’s response could not be parsed using any known image format.
public struct UnparsableImage: Error { }
/// A response transformer received entity content of a type it doesn’t know how to process. This error means
/// that the upstream transformations may have succeeded, but did not return a value of the type the next
/// transformer expected.
public struct WrongInputTypeInTranformerPipeline: Error
{
public let expectedType, actualType: Any.Type
public let transformer: ResponseTransformer
}
/// A `ResponseContentTransformer` or a closure passed to `Service.configureTransformer(...)` returned nil.
public struct TransformerReturnedNil: Error
{
public let transformer: ResponseTransformer
}
}
}
| 38.264151 | 119 | 0.640163 |
08a38c552ca110137f4830f932b571c5e485d7a0 | 510 | //
// NSData+Hex.swift
// iOSToolkit
//
// Created by Freddie Wang on 2015/6/12.
// Copyright (c) 2015年 freddie. All rights reserved.
//
import Foundation
extension NSData {
func toHexString() -> String {
let string = NSMutableString(capacity: length * 2)
var byte: UInt8 = 0
for i in 0 ..< length {
getBytes(&byte, range: NSMakeRange(i, 1))
string.appendFormat("%02x", byte)
}
return string as String
}
} | 21.25 | 58 | 0.556863 |
0a6735348d94d3e94e2a7e417c1536090b99e4b2 | 10,563 | // RUN: %target-typecheck-verify-swift
//===----------------------------------------------------------------------===//
// Deduction of generic arguments
//===----------------------------------------------------------------------===//
func identity<T>(_ value: T) -> T { return value }
func identity2<T>(_ value: T) -> T { return value }
func identity2<T>(_ value: T) -> Int { return 0 }
struct X { }
struct Y { }
func useIdentity(_ x: Int, y: Float, i32: Int32) {
var x2 = identity(x)
var y2 = identity(y)
// Deduction that involves the result type
x2 = identity(17)
var i32_2 : Int32 = identity(17)
// Deduction where the result type and input type can get different results
var xx : X, yy : Y
xx = identity(yy) // expected-error{{cannot convert value of type 'Y' to expected argument type 'X'}}
xx = identity2(yy) // expected-error{{cannot convert value of type 'Y' to expected argument type 'X'}}
}
// FIXME: Crummy diagnostic!
func twoIdentical<T>(_ x: T, _ y: T) -> T {}
func useTwoIdentical(_ xi: Int, yi: Float) {
var x = xi, y = yi
x = twoIdentical(x, x)
y = twoIdentical(y, y)
x = twoIdentical(x, 1)
x = twoIdentical(1, x)
y = twoIdentical(1.0, y)
y = twoIdentical(y, 1.0)
twoIdentical(x, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func mySwap<T>(_ x: inout T,
_ y: inout T) {
let tmp = x
x = y
y = tmp
}
func useSwap(_ xi: Int, yi: Float) {
var x = xi, y = yi
mySwap(&x, &x)
mySwap(&y, &y)
mySwap(x, x) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}}
// expected-error @-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{13-13=&}}
mySwap(&x, &y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func takeTuples<T, U>(_: (T, U), _: (U, T)) {
}
func useTuples(_ x: Int, y: Float, z: (Float, Int)) {
takeTuples((x, y), (y, x))
takeTuples((x, y), (x, y)) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Float'}}
// FIXME: Use 'z', which requires us to fix our tuple-conversion
// representation.
}
func acceptFunction<T, U>(_ f: (T) -> U, _ t: T, _ u: U) {}
func passFunction(_ f: (Int) -> Float, x: Int, y: Float) {
acceptFunction(f, x, y)
acceptFunction(f, y, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func returnTuple<T, U>(_: T) -> (T, U) { } // expected-note {{in call to function 'returnTuple'}}
func testReturnTuple(_ x: Int, y: Float) {
returnTuple(x) // expected-error{{generic parameter 'U' could not be inferred}}
var _ : (Int, Float) = returnTuple(x)
var _ : (Float, Float) = returnTuple(y)
// <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands
var _ : (Int, Float) = returnTuple(y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func confusingArgAndParam<T, U>(_ f: (T) -> U, _ g: (U) -> T) {
confusingArgAndParam(g, f)
confusingArgAndParam(f, g)
}
func acceptUnaryFn<T, U>(_ f: (T) -> U) { }
func acceptUnaryFnSame<T>(_ f: (T) -> T) { }
func acceptUnaryFnRef<T, U>(_ f: inout (T) -> U) { }
func acceptUnaryFnSameRef<T>(_ f: inout (T) -> T) { }
func unaryFnIntInt(_: Int) -> Int {}
func unaryFnOvl(_: Int) -> Int {} // expected-note{{found this candidate}}
func unaryFnOvl(_: Float) -> Int {} // expected-note{{found this candidate}}
// Variable forms of the above functions
var unaryFnIntIntVar : (Int) -> Int = unaryFnIntInt
func passOverloadSet() {
// Passing a non-generic function to a generic function
acceptUnaryFn(unaryFnIntInt)
acceptUnaryFnSame(unaryFnIntInt)
// Passing an overloaded function set to a generic function
// FIXME: Yet more terrible diagnostics.
acceptUnaryFn(unaryFnOvl) // expected-error{{ambiguous use of 'unaryFnOvl'}}
acceptUnaryFnSame(unaryFnOvl)
// Passing a variable of function type to a generic function
acceptUnaryFn(unaryFnIntIntVar)
acceptUnaryFnSame(unaryFnIntIntVar)
// Passing a variable of function type to a generic function to an inout parameter
acceptUnaryFnRef(&unaryFnIntIntVar)
acceptUnaryFnSameRef(&unaryFnIntIntVar)
acceptUnaryFnRef(unaryFnIntIntVar) // expected-error{{passing value of type '(Int) -> Int' to an inout parameter requires explicit '&'}} {{20-20=&}}
}
func acceptFnFloatFloat(_ f: (Float) -> Float) {}
func acceptFnDoubleDouble(_ f: (Double) -> Double) {}
func passGeneric() {
acceptFnFloatFloat(identity)
acceptFnFloatFloat(identity2)
}
//===----------------------------------------------------------------------===//
// Simple deduction for generic member functions
//===----------------------------------------------------------------------===//
struct SomeType {
func identity<T>(_ x: T) -> T { return x }
func identity2<T>(_ x: T) -> T { return x } // expected-note 2{{found this candidate}}
func identity2<T>(_ x: T) -> Float { } // expected-note 2{{found this candidate}}
func returnAs<T>() -> T {}
}
func testMemberDeduction(_ sti: SomeType, ii: Int, fi: Float) {
var st = sti, i = ii, f = fi
i = st.identity(i)
f = st.identity(f)
i = st.identity2(i)
f = st.identity2(f) // expected-error{{ambiguous use of 'identity2'}}
i = st.returnAs()
f = st.returnAs()
acceptFnFloatFloat(st.identity)
acceptFnFloatFloat(st.identity2) // expected-error{{ambiguous use of 'identity2'}}
acceptFnDoubleDouble(st.identity2)
}
struct StaticFuncs {
static func chameleon<T>() -> T {}
func chameleon2<T>() -> T {}
}
struct StaticFuncsGeneric<U> {
// FIXME: Nested generics are very broken
// static func chameleon<T>() -> T {}
}
func chameleon<T>() -> T {}
func testStatic(_ sf: StaticFuncs, sfi: StaticFuncsGeneric<Int>) {
var x: Int16
x = StaticFuncs.chameleon()
x = sf.chameleon2()
// FIXME: Nested generics are very broken
// x = sfi.chameleon()
// typealias SFI = StaticFuncsGeneric<Int>
// x = SFI.chameleon()
_ = x
}
//===----------------------------------------------------------------------===//
// Deduction checking for constraints
//===----------------------------------------------------------------------===//
protocol IsBefore {
func isBefore(_ other: Self) -> Bool
}
func min2<T : IsBefore>(_ x: T, _ y: T) -> T {
if y.isBefore(x) { return y }
return x
}
extension Int : IsBefore {
func isBefore(_ other: Int) -> Bool { return self < other }
}
func callMin(_ x: Int, y: Int, a: Float, b: Float) {
_ = min2(x, y)
min2(a, b) // expected-error{{argument type 'Float' does not conform to expected type 'IsBefore'}}
}
func rangeOfIsBefore<R : IteratorProtocol>(_ range: R) where R.Element : IsBefore {}
func callRangeOfIsBefore(_ ia: [Int], da: [Double]) {
rangeOfIsBefore(ia.makeIterator())
rangeOfIsBefore(da.makeIterator()) // expected-error{{type 'Double' does not conform to protocol 'IsBefore'}}
}
func testEqualIterElementTypes<A: IteratorProtocol, B: IteratorProtocol>(_ a: A, _ b: B) where A.Element == B.Element {}
// expected-note@-1 {{requirement specified as 'A.Element' == 'B.Element' [with A = IndexingIterator<[Int]>, B = IndexingIterator<[Double]>]}}
func compareIterators() {
var a: [Int] = []
var b: [Double] = []
testEqualIterElementTypes(a.makeIterator(), b.makeIterator()) // expected-error {{'<A, B where A : IteratorProtocol, B : IteratorProtocol, A.Element == B.Element> (A, B) -> ()' requires the types 'Int' and 'Double' be equivalent}}
}
protocol P_GI {
associatedtype Y
}
class C_GI : P_GI {
typealias Y = Double
}
class GI_Diff {}
func genericInheritsA<T>(_ x: T) where T : P_GI, T.Y : GI_Diff {}
// expected-note@-1 {{requirement specified as 'T.Y' : 'GI_Diff' [with T = C_GI]}}
genericInheritsA(C_GI()) // expected-error {{<T where T : P_GI, T.Y : GI_Diff> (T) -> ()' requires that 'C_GI.Y' (aka 'Double') inherit from 'GI_Diff'}}
//===----------------------------------------------------------------------===//
// Deduction for member operators
//===----------------------------------------------------------------------===//
protocol Addable {
static func +(x: Self, y: Self) -> Self
}
func addAddables<T : Addable, U>(_ x: T, y: T, u: U) -> T {
u + u // expected-error{{binary operator '+' cannot be applied to two 'U' operands}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }}
return x+y
}
//===----------------------------------------------------------------------===//
// Deduction for bound generic types
//===----------------------------------------------------------------------===//
struct MyVector<T> { func size() -> Int {} }
func getVectorSize<T>(_ v: MyVector<T>) -> Int {
return v.size()
}
func ovlVector<T>(_ v: MyVector<T>) -> X {}
func ovlVector<T>(_ v: MyVector<MyVector<T>>) -> Y {}
func testGetVectorSize(_ vi: MyVector<Int>, vf: MyVector<Float>) {
var i : Int
i = getVectorSize(vi)
i = getVectorSize(vf)
getVectorSize(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'MyVector<_>'}}
var x : X, y : Y
x = ovlVector(vi)
x = ovlVector(vf)
var vvi : MyVector<MyVector<Int>>
y = ovlVector(vvi)
var yy = ovlVector(vvi)
yy = y
y = yy
}
// <rdar://problem/15104554>
postfix operator <*>
protocol MetaFunction {
associatedtype Result
static postfix func <*> (_: Self) -> Result?
}
protocol Bool_ {}
struct False : Bool_ {}
struct True : Bool_ {}
postfix func <*> <B>(_: Test<B>) -> Int? { return .none }
postfix func <*> (_: Test<True>) -> String? { return .none }
class Test<C: Bool_> : MetaFunction {
typealias Result = Int
} // picks first <*>
typealias Inty = Test<True>.Result
var iy : Inty = 5 // okay, because we picked the first <*>
var iy2 : Inty = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'Inty' (aka 'Int')}}
// rdar://problem/20577950
class DeducePropertyParams {
let badSet: Set = ["Hello"]
}
// SR-69
struct A {}
func foo() {
for i in min(1,2) { // expected-error{{type 'Int' does not conform to protocol 'Sequence'}}
}
let j = min(Int(3), Float(2.5)) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
let k = min(A(), A()) // expected-error{{argument type 'A' does not conform to expected type 'Comparable'}}
let oi : Int? = 5
let l = min(3, oi) // expected-error{{value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?}}
}
| 32.906542 | 232 | 0.609391 |
d9b55bc901e8988d39e525ed6a324bc3d6728822 | 502 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "JoyStickView",
platforms: [.iOS(.v12)],
products: [
.library(
name: "JoyStickView",
targets: ["JoyStickView"]),
],
dependencies: [
],
targets: [
.target(
name: "JoyStickView",
dependencies: [],
exclude: ["Resources/Info.plist"]
),
.testTarget(
name: "JoyStickViewTests",
dependencies: ["JoyStickView"],
exclude: ["Info.plist"]
)
]
)
| 17.928571 | 39 | 0.577689 |
9c19253220ee9a02f3b9ab57a9e5a3a54a9e762d | 9,986 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import PackageModel
import PackageGraph
public func PackageGraphTester(_ graph: PackageGraph, _ result: (PackageGraphResult) -> Void) {
result(PackageGraphResult(graph))
}
public final class PackageGraphResult {
public let graph: PackageGraph
public init(_ graph: PackageGraph) {
self.graph = graph
}
// TODO: deprecate / transition to PackageIdentity
public func check(roots: String..., file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(graph.rootPackages.map{$0.manifest.displayName }.sorted(), roots.sorted(), file: file, line: line)
}
public func check(roots: PackageIdentity..., file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(graph.rootPackages.map{$0.identity }.sorted(), roots.sorted(), file: file, line: line)
}
// TODO: deprecate / transition to PackageIdentity
public func check(packages: String..., file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(graph.packages.map {$0.manifest.displayName }.sorted(), packages.sorted(), file: file, line: line)
}
public func check(packages: PackageIdentity..., file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(graph.packages.map {$0.identity }.sorted(), packages.sorted(), file: file, line: line)
}
public func check(targets: String..., file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(
graph.allTargets
.filter{ $0.type != .test }
.map{ $0.name }
.sorted(), targets.sorted(), file: file, line: line)
}
public func check(products: String..., file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(Set(graph.allProducts.map { $0.name }), Set(products), file: file, line: line)
}
public func check(reachableTargets: String..., file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(Set(graph.reachableTargets.map { $0.name }), Set(reachableTargets), file: file, line: line)
}
public func check(reachableProducts: String..., file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(Set(graph.reachableProducts.map { $0.name }), Set(reachableProducts), file: file, line: line)
}
public func check(
reachableBuildTargets: String...,
in environment: BuildEnvironment,
file: StaticString = #file,
line: UInt = #line
) throws {
let targets = Set(try self.reachableBuildTargets(in: environment).map({ $0.name }))
XCTAssertEqual(targets, Set(reachableBuildTargets), file: file, line: line)
}
public func check(
reachableBuildProducts: String...,
in environment: BuildEnvironment,
file: StaticString = #file,
line: UInt = #line
) throws {
let products = Set(try self.reachableBuildProducts(in: environment).map({ $0.name }))
XCTAssertEqual(products, Set(reachableBuildProducts), file: file, line: line)
}
public func checkTarget(
_ name: String,
file: StaticString = #file,
line: UInt = #line,
body: (ResolvedTargetResult) -> Void
) {
guard let target = find(target: name) else {
return XCTFail("Target \(name) not found", file: file, line: line)
}
body(ResolvedTargetResult(target))
}
public func checkProduct(
_ name: String,
file: StaticString = #file,
line: UInt = #line,
body: (ResolvedProductResult) -> Void
) {
guard let target = find(product: name) else {
return XCTFail("Product \(name) not found", file: file, line: line)
}
body(ResolvedProductResult(target))
}
public func check(testModules: String..., file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(
graph.allTargets
.filter{ $0.type == .test }
.map{ $0.name }
.sorted(), testModules.sorted(), file: file, line: line)
}
public func find(target: String) -> ResolvedTarget? {
return graph.allTargets.first(where: { $0.name == target })
}
public func find(product: String) -> ResolvedProduct? {
return graph.allProducts.first(where: { $0.name == product })
}
private func reachableBuildTargets(in environment: BuildEnvironment) throws -> Set<ResolvedTarget> {
let inputTargets = graph.inputPackages.lazy.flatMap { $0.targets }
let recursiveBuildTargetDependencies = try inputTargets
.flatMap { try $0.recursiveDependencies(satisfying: environment) }
.compactMap { $0.target }
return Set(inputTargets).union(recursiveBuildTargetDependencies)
}
private func reachableBuildProducts(in environment: BuildEnvironment) throws -> Set<ResolvedProduct> {
let recursiveBuildProductDependencies = try graph.inputPackages
.lazy
.flatMap { $0.targets }
.flatMap { try $0.recursiveDependencies(satisfying: environment) }
.compactMap { $0.product }
return Set(graph.inputPackages.flatMap { $0.products }).union(recursiveBuildProductDependencies)
}
}
public final class ResolvedTargetResult {
private let target: ResolvedTarget
init(_ target: ResolvedTarget) {
self.target = target
}
public func check(dependencies: String..., file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(Set(dependencies), Set(target.dependencies.map({ $0.name })), file: file, line: line)
}
public func checkDependency(
_ name: String,
file: StaticString = #file,
line: UInt = #line,
body: (ResolvedTargetDependencyResult) -> Void
) {
guard let dependency = target.dependencies.first(where: { $0.name == name }) else {
return XCTFail("Dependency \(name) not found", file: file, line: line)
}
body(ResolvedTargetDependencyResult(dependency))
}
public func check(type: Target.Kind, file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(type, target.type, file: file, line: line)
}
public func checkDeclaredPlatforms(_ platforms: [String: String], file: StaticString = #file, line: UInt = #line) {
let targetPlatforms = Dictionary(uniqueKeysWithValues: target.platforms.declared.map({ ($0.platform.name, $0.version.versionString) }))
XCTAssertEqual(platforms, targetPlatforms, file: file, line: line)
}
public func checkDerivedPlatforms(_ platforms: [String: String], file: StaticString = #file, line: UInt = #line) {
let targetPlatforms = Dictionary(uniqueKeysWithValues: target.platforms.derived.map({ ($0.platform.name, $0.version.versionString) }))
XCTAssertEqual(platforms, targetPlatforms, file: file, line: line)
}
public func checkDerivedPlatformOptions(_ platform: PackageModel.Platform, options: [String], file: StaticString = #file, line: UInt = #line) {
let platform = target.platforms.getDerived(for: platform)
XCTAssertEqual(platform?.options, options, file: file, line: line)
}
}
public final class ResolvedTargetDependencyResult {
private let dependency: ResolvedTarget.Dependency
init(_ dependency: ResolvedTarget.Dependency) {
self.dependency = dependency
}
public func checkConditions(satisfy environment: BuildEnvironment, file: StaticString = #file, line: UInt = #line) {
XCTAssert(dependency.conditions.allSatisfy({ $0.satisfies(environment) }), file: file, line: line)
}
public func checkConditions(
dontSatisfy environment: BuildEnvironment,
file: StaticString = #file,
line: UInt = #line
) {
XCTAssert(!dependency.conditions.allSatisfy({ $0.satisfies(environment) }), file: file, line: line)
}
}
public final class ResolvedProductResult {
private let product: ResolvedProduct
init(_ product: ResolvedProduct) {
self.product = product
}
public func check(targets: String..., file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(Set(targets), Set(product.targets.map({ $0.name })), file: file, line: line)
}
public func check(type: ProductType, file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(type, product.type, file: file, line: line)
}
public func checkDeclaredPlatforms(_ platforms: [String: String], file: StaticString = #file, line: UInt = #line) {
let targetPlatforms = Dictionary(uniqueKeysWithValues: product.platforms.declared.map({ ($0.platform.name, $0.version.versionString) }))
XCTAssertEqual(platforms, targetPlatforms, file: file, line: line)
}
public func checkDerivedPlatforms(_ platforms: [String: String], file: StaticString = #file, line: UInt = #line) {
let targetPlatforms = Dictionary(uniqueKeysWithValues: product.platforms.derived.map({ ($0.platform.name, $0.version.versionString) }))
XCTAssertEqual(platforms, targetPlatforms, file: file, line: line)
}
public func checkDerivedPlatformOptions(_ platform: PackageModel.Platform, options: [String], file: StaticString = #file, line: UInt = #line) {
let platform = product.platforms.getDerived(for: platform)
XCTAssertEqual(platform?.options, options, file: file, line: line)
}
}
extension ResolvedTarget.Dependency {
public var name: String {
switch self {
case .target(let target, _):
return target.name
case .product(let product, _):
return product.name
}
}
}
| 40.42915 | 147 | 0.658021 |
bfc9a0f925854f2a9c06086aef1b60330741179f | 2,061 | // Copyright © 2017 Károly Lőrentey.
// This file is part of Attabench: https://github.com/attaswift/Attabench
// For licensing information, see the file LICENSE.md in the Git repository above.
public struct Bounds<Value: Comparable>: Equatable {
public var range: ClosedRange<Value>?
var isEmpty: Bool { return range == nil }
public init(_ range: ClosedRange<Value>? = nil) {
self.range = range
}
public init(_ value: Value) {
self.range = value...value
}
public static func ==(a: Bounds, b: Bounds) -> Bool {
return a.range == b.range
}
public static func ~=(pattern: Bounds, value: Value) -> Bool {
return pattern.contains(value)
}
public func contains(_ value: Value) -> Bool {
guard let range = range else { return false }
return range.contains(value)
}
public mutating func clamp(to limits: Bounds) {
guard let range = self.range else { return }
guard let limits = limits.range else { self.range = nil; return }
self.range = range.clamped(to: limits)
}
public func clamped(to limits: Bounds) -> Bounds {
var r = self
r.clamp(to: limits)
return r
}
public mutating func formUnion(with other: Bounds) {
switch (self.range, other.range) {
case let (a?, b?):
self.range = min(a.lowerBound, b.lowerBound) ... max(a.upperBound, b.upperBound)
case let (nil, b?):
self.range = b
default:
break
}
}
public func union(with other: Bounds) -> Bounds {
var r = self
r.formUnion(with: other)
return r
}
public mutating func insert(_ value: Value) {
if let range = self.range {
self.range = min(range.lowerBound, value) ... max(range.upperBound, value)
}
else {
self.range = value ... value
}
}
public func inserted(_ value: Value) -> Bounds {
var r = self
r.insert(value)
return r
}
}
| 27.851351 | 92 | 0.57836 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.