CombinedText
stringlengths 8
3.42M
|
---|
//===--- DriverUtils.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import TestsUtils
struct BenchResults {
let sampleCount, min, max, mean, sd, median, maxRSS: UInt64
}
public var registeredBenchmarks: [BenchmarkInfo] = []
enum TestAction {
case run
case listTests
case help([String])
}
struct TestConfig {
/// The delimiter to use when printing output.
var delim: String = ","
/// The filters applied to our test names.
var filters = [String]()
/// The tags that we want to run
var tags = Set<BenchmarkCategory>()
/// Tests tagged with any of these will not be executed
var skipTags: Set<BenchmarkCategory> = [.unstable, .skip]
/// The scalar multiple of the amount of times a test should be run. This
/// enables one to cause tests to run for N iterations longer than they
/// normally would. This is useful when one wishes for a test to run for a
/// longer amount of time to perform performance analysis on the test in
/// instruments.
var iterationScale: Int = 1
/// If we are asked to have a fixed number of iterations, the number of fixed
/// iterations.
var fixedNumIters: UInt = 0
/// The number of samples we should take of each test.
var numSamples: Int = 1
/// Is verbose output enabled?
var verbose: Bool = false
/// After we run the tests, should the harness sleep to allow for utilities
/// like leaks that require a PID to run on the test harness.
var afterRunSleep: Int?
/// The list of tests to run.
var tests = [(index: String, info: BenchmarkInfo)]()
var action: TestAction = .run
mutating func processArguments() throws -> TestAction {
let validOptions = [
"--iter-scale", "--num-samples", "--num-iters",
"--verbose", "--delim", "--list", "--sleep",
"--tags", "--skip-tags", "--help"
]
guard let benchArgs = parseArgs(validOptions) else {
throw ArgumentError.general("Failed to parse arguments")
}
filters = benchArgs.positionalArgs
func optionalArg<T>(
_ name: String,
_ property: WritableKeyPath<TestConfig, T>,
defaultValue: T? = nil,
parser parse: (String) throws -> T? = { _ in nil }
) throws {
if let value = benchArgs.optionalArgsMap[name] {
guard !value.isEmpty || defaultValue != nil
else { throw ArgumentError.missingValue(name) }
guard let typedValue = (value.isEmpty) ? defaultValue
: try parse(value) else {
throw ArgumentError.invalidType(
value: value, type: String(describing: T.self), argument: name)
}
self[keyPath: property] = typedValue
}
}
try optionalArg("--iter-scale", \.iterationScale) { Int($0) }
try optionalArg("--num-iters", \.fixedNumIters) { UInt($0) }
try optionalArg("--num-samples", \.numSamples) { Int($0) }
try optionalArg("--verbose", \.verbose, defaultValue: true)
try optionalArg("--delim", \.delim) { $0 }
func parseCategory(tag: String) throws -> BenchmarkCategory {
guard let category = BenchmarkCategory(rawValue: tag) else {
throw ArgumentError.invalidType(
value: tag, type: "BenchmarkCategory", argument: nil)
}
return category
}
try optionalArg("--tags", \.tags) {
// We support specifying multiple tags by splitting on comma, i.e.:
// --tags=Array,Dictionary
Set(try $0.split(separator: ",").map(String.init).map(parseCategory))
}
try optionalArg("--skip-tags", \.skipTags, defaultValue: []) {
// We support specifying multiple tags by splitting on comma, i.e.:
// --skip-tags=Array,Set,unstable,skip
Set(try $0.split(separator: ",").map(String.init).map(parseCategory))
}
try optionalArg("--sleep", \.afterRunSleep) { Int($0) }
try optionalArg("--list", \.action, defaultValue: .listTests)
try optionalArg("--help", \.action, defaultValue: .help(validOptions))
return action
}
mutating func findTestsToRun() {
registeredBenchmarks.sort()
let indices = Dictionary(uniqueKeysWithValues:
zip(registeredBenchmarks.map{ $0.name },
(1...).lazy.map { String($0) } ))
let benchmarkNamesOrIndices = Set(filters)
// needed so we don't capture an ivar of a mutable inout self.
let (_tags, _skipTags) = (tags, skipTags)
tests = registeredBenchmarks.filter { benchmark in
if benchmarkNamesOrIndices.isEmpty {
return benchmark.tags.isSuperset(of: _tags) &&
benchmark.tags.isDisjoint(with: _skipTags)
} else {
return benchmarkNamesOrIndices.contains(benchmark.name) ||
benchmarkNamesOrIndices.contains(indices[benchmark.name]!)
}
}.map { (index: indices[$0.name]!, info: $0) }
}
}
func internalMeanSD(_ inputs: [UInt64]) -> (UInt64, UInt64) {
// If we are empty, return 0, 0.
if inputs.isEmpty {
return (0, 0)
}
// If we have one element, return elt, 0.
if inputs.count == 1 {
return (inputs[0], 0)
}
// Ok, we have 2 elements.
var sum1: UInt64 = 0
var sum2: UInt64 = 0
for i in inputs {
sum1 += i
}
let mean: UInt64 = sum1 / UInt64(inputs.count)
for i in inputs {
sum2 = sum2 &+ UInt64((Int64(i) &- Int64(mean))&*(Int64(i) &- Int64(mean)))
}
return (mean, UInt64(sqrt(Double(sum2)/(Double(inputs.count) - 1))))
}
func internalMedian(_ inputs: [UInt64]) -> UInt64 {
return inputs.sorted()[inputs.count / 2]
}
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
@_silgen_name("_swift_leaks_startTrackingObjects")
func startTrackingObjects(_: UnsafePointer<CChar>) -> ()
@_silgen_name("_swift_leaks_stopTrackingObjects")
func stopTrackingObjects(_: UnsafePointer<CChar>) -> Int
#endif
#if os(Linux)
class Timer {
typealias TimeT = timespec
func getTime() -> TimeT {
var ticks = timespec(tv_sec: 0, tv_nsec: 0)
clock_gettime(CLOCK_REALTIME, &ticks)
return ticks
}
func diffTimeInNanoSeconds(from start_ticks: TimeT, to end_ticks: TimeT) -> UInt64 {
var elapsed_ticks = timespec(tv_sec: 0, tv_nsec: 0)
if end_ticks.tv_nsec - start_ticks.tv_nsec < 0 {
elapsed_ticks.tv_sec = end_ticks.tv_sec - start_ticks.tv_sec - 1
elapsed_ticks.tv_nsec = end_ticks.tv_nsec - start_ticks.tv_nsec + 1000000000
} else {
elapsed_ticks.tv_sec = end_ticks.tv_sec - start_ticks.tv_sec
elapsed_ticks.tv_nsec = end_ticks.tv_nsec - start_ticks.tv_nsec
}
return UInt64(elapsed_ticks.tv_sec) * UInt64(1000000000) + UInt64(elapsed_ticks.tv_nsec)
}
}
#else
class Timer {
typealias TimeT = UInt64
var info = mach_timebase_info_data_t(numer: 0, denom: 0)
init() {
mach_timebase_info(&info)
}
func getTime() -> TimeT {
return mach_absolute_time()
}
func diffTimeInNanoSeconds(from start_ticks: TimeT, to end_ticks: TimeT) -> UInt64 {
let elapsed_ticks = end_ticks - start_ticks
return elapsed_ticks * UInt64(info.numer) / UInt64(info.denom)
}
}
#endif
class SampleRunner {
let timer = Timer()
let baseline = SampleRunner.usage()
let c: TestConfig
init(_ config: TestConfig) {
self.c = config
}
private static func usage() -> rusage {
var u = rusage(); getrusage(RUSAGE_SELF, &u); return u
}
/// Returns maximum resident set size (MAX_RSS) delta in bytes
func measureMemoryUsage() -> Int {
var current = SampleRunner.usage()
let maxRSS = current.ru_maxrss - baseline.ru_maxrss
if c.verbose {
let pages = maxRSS / sysconf(_SC_PAGESIZE)
func deltaEquation(_ stat: KeyPath<rusage, Int>) -> String {
let b = baseline[keyPath: stat], c = current[keyPath: stat]
return "\(c) - \(b) = \(c - b)"
}
print("""
MAX_RSS \(deltaEquation(\rusage.ru_maxrss)) (\(pages) pages)
ICS \(deltaEquation(\rusage.ru_nivcsw))
VCS \(deltaEquation(\rusage.ru_nvcsw))
""")
}
return maxRSS
}
func run(_ name: String, fn: (Int) -> Void, num_iters: UInt) -> UInt64 {
// Start the timer.
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
name.withCString { p in startTrackingObjects(p) }
#endif
let start_ticks = timer.getTime()
fn(Int(num_iters))
// Stop the timer.
let end_ticks = timer.getTime()
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
name.withCString { p in stopTrackingObjects(p) }
#endif
// Compute the spent time and the scaling factor.
return timer.diffTimeInNanoSeconds(from: start_ticks, to: end_ticks)
}
}
/// Invoke the benchmark entry point and return the run time in milliseconds.
func runBench(_ test: BenchmarkInfo, _ c: TestConfig) -> BenchResults? {
var samples = [UInt64](repeating: 0, count: c.numSamples)
// Before we do anything, check that we actually have a function to
// run. If we don't it is because the benchmark is not supported on
// the platform and we should skip it.
guard let testFn = test.runFunction else {
if c.verbose {
print("Skipping unsupported benchmark \(test.name)!")
}
return nil
}
if c.verbose {
print("Running \(test.name) for \(c.numSamples) samples.")
}
let sampler = SampleRunner(c)
for s in 0..<c.numSamples {
test.setUpFunction?()
let time_per_sample: UInt64 = 1_000_000_000 * UInt64(c.iterationScale)
var scale : UInt
var elapsed_time : UInt64 = 0
if c.fixedNumIters == 0 {
elapsed_time = sampler.run(test.name, fn: testFn, num_iters: 1)
if elapsed_time > 0 {
scale = UInt(time_per_sample / elapsed_time)
} else {
if c.verbose {
print(" Warning: elapsed time is 0. This can be safely ignored if the body is empty.")
}
scale = 1
}
} else {
// Compute the scaling factor if a fixed c.fixedNumIters is not specified.
scale = c.fixedNumIters
if scale == 1 {
elapsed_time = sampler.run(test.name, fn: testFn, num_iters: 1)
}
}
// Make integer overflow less likely on platforms where Int is 32 bits wide.
// FIXME: Switch BenchmarkInfo to use Int64 for the iteration scale, or fix
// benchmarks to not let scaling get off the charts.
scale = min(scale, UInt(Int.max) / 10_000)
// Rerun the test with the computed scale factor.
if scale > 1 {
if c.verbose {
print(" Measuring with scale \(scale).")
}
elapsed_time = sampler.run(test.name, fn: testFn, num_iters: scale)
} else {
scale = 1
}
// save result in microseconds or k-ticks
samples[s] = elapsed_time / UInt64(scale) / 1000
if c.verbose {
print(" Sample \(s),\(samples[s])")
}
test.tearDownFunction?()
}
let (mean, sd) = internalMeanSD(samples)
// Return our benchmark results.
return BenchResults(sampleCount: UInt64(samples.count),
min: samples.min()!, max: samples.max()!,
mean: mean, sd: sd, median: internalMedian(samples),
maxRSS: UInt64(sampler.measureMemoryUsage()))
}
func printRunInfo(_ c: TestConfig) {
if c.verbose {
print("--- CONFIG ---")
print("NumSamples: \(c.numSamples)")
print("Verbose: \(c.verbose)")
print("IterScale: \(c.iterationScale)")
if c.fixedNumIters != 0 {
print("FixedIters: \(c.fixedNumIters)")
}
print("Tests Filter: \(c.filters)")
print("Tests to run: ", terminator: "")
print(c.tests.map({ $0.1.name }).joined(separator: ", "))
print("")
print("--- DATA ---")
}
}
/// Execute benchmarks and continuously report the measurement results.
func runBenchmarks(_ c: TestConfig) {
let withUnit = {$0 + "(us)"}
let header = (
["#", "TEST", "SAMPLES"] +
["MIN", "MAX", "MEAN", "SD", "MEDIAN"].map(withUnit)
+ ["MAX_RSS(B)"]
).joined(separator: c.delim)
print(header)
var testCount = 0
func report(_ index: String, _ t: BenchmarkInfo, results: BenchResults?) {
func values(r: BenchResults) -> [String] {
return [r.sampleCount, r.min, r.max, r.mean, r.sd, r.median, r.maxRSS]
.map { String($0) }
}
let benchmarkStats = (
[index, t.name] + (results.map(values) ?? ["Unsupported"])
).joined(separator: c.delim)
print(benchmarkStats)
fflush(stdout)
if (results != nil) {
testCount += 1
}
}
for (index, test) in c.tests {
report(index, test, results:runBench(test, c))
}
print("")
print("Totals\(c.delim)\(testCount)")
}
public func main() {
var config = TestConfig()
do {
switch (try config.processArguments()) {
case let .help(validOptions):
print("Valid options:")
for v in validOptions {
print(" \(v)")
}
case .listTests:
config.findTestsToRun()
print("#\(config.delim)Test\(config.delim)[Tags]")
for (index, t) in config.tests {
let testDescription = [String(index), t.name, t.tags.sorted().description]
.joined(separator: config.delim)
print(testDescription)
}
case .run:
config.findTestsToRun()
printRunInfo(config)
runBenchmarks(config)
if let x = config.afterRunSleep {
sleep(UInt32(x))
}
}
} catch let error as ArgumentError {
fflush(stdout)
fputs("\(error)\n", stderr)
fflush(stderr)
exit(1)
} catch {
fatalError("\(error)")
}
}
[benchmark][Gardening] Grouped argument parsing
* Extracted tag parser
* Reordered all parsing of optional arguments to be grouped together.
//===--- DriverUtils.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import TestsUtils
struct BenchResults {
let sampleCount, min, max, mean, sd, median, maxRSS: UInt64
}
public var registeredBenchmarks: [BenchmarkInfo] = []
enum TestAction {
case run
case listTests
case help([String])
}
struct TestConfig {
/// The delimiter to use when printing output.
var delim: String = ","
/// The filters applied to our test names.
var filters = [String]()
/// The tags that we want to run
var tags = Set<BenchmarkCategory>()
/// Tests tagged with any of these will not be executed
var skipTags: Set<BenchmarkCategory> = [.unstable, .skip]
/// The scalar multiple of the amount of times a test should be run. This
/// enables one to cause tests to run for N iterations longer than they
/// normally would. This is useful when one wishes for a test to run for a
/// longer amount of time to perform performance analysis on the test in
/// instruments.
var iterationScale: Int = 1
/// If we are asked to have a fixed number of iterations, the number of fixed
/// iterations.
var fixedNumIters: UInt = 0
/// The number of samples we should take of each test.
var numSamples: Int = 1
/// Is verbose output enabled?
var verbose: Bool = false
/// After we run the tests, should the harness sleep to allow for utilities
/// like leaks that require a PID to run on the test harness.
var afterRunSleep: Int?
/// The list of tests to run.
var tests = [(index: String, info: BenchmarkInfo)]()
var action: TestAction = .run
mutating func processArguments() throws -> TestAction {
let validOptions = [
"--iter-scale", "--num-samples", "--num-iters",
"--verbose", "--delim", "--list", "--sleep",
"--tags", "--skip-tags", "--help"
]
guard let benchArgs = parseArgs(validOptions) else {
throw ArgumentError.general("Failed to parse arguments")
}
filters = benchArgs.positionalArgs
func optionalArg<T>(
_ name: String,
_ property: WritableKeyPath<TestConfig, T>,
defaultValue: T? = nil,
parser parse: (String) throws -> T? = { _ in nil }
) throws {
if let value = benchArgs.optionalArgsMap[name] {
guard !value.isEmpty || defaultValue != nil
else { throw ArgumentError.missingValue(name) }
guard let typedValue = (value.isEmpty) ? defaultValue
: try parse(value) else {
throw ArgumentError.invalidType(
value: value, type: String(describing: T.self), argument: name)
}
self[keyPath: property] = typedValue
}
}
func tag(tag: String) throws -> BenchmarkCategory {
guard let category = BenchmarkCategory(rawValue: tag) else {
throw ArgumentError.invalidType(
value: tag, type: "BenchmarkCategory", argument: nil)
}
return category
}
func tags(tags: String) throws -> Set<BenchmarkCategory> {
// We support specifying multiple tags by splitting on comma, i.e.:
// --tags=Array,Dictionary
// --skip-tags=Array,Set,unstable,skip
return Set(
try tags.split(separator: ",").map(String.init).map(tag))
}
try optionalArg("--iter-scale", \.iterationScale) { Int($0) }
try optionalArg("--num-iters", \.fixedNumIters) { UInt($0) }
try optionalArg("--num-samples", \.numSamples) { Int($0) }
try optionalArg("--verbose", \.verbose, defaultValue: true)
try optionalArg("--delim", \.delim) { $0 }
try optionalArg("--tags", \.tags, parser: tags)
try optionalArg("--skip-tags", \.skipTags, defaultValue: [], parser: tags)
try optionalArg("--sleep", \.afterRunSleep) { Int($0) }
try optionalArg("--list", \.action, defaultValue: .listTests)
try optionalArg("--help", \.action, defaultValue: .help(validOptions))
return action
}
mutating func findTestsToRun() {
registeredBenchmarks.sort()
let indices = Dictionary(uniqueKeysWithValues:
zip(registeredBenchmarks.map{ $0.name },
(1...).lazy.map { String($0) } ))
let benchmarkNamesOrIndices = Set(filters)
// needed so we don't capture an ivar of a mutable inout self.
let (_tags, _skipTags) = (tags, skipTags)
tests = registeredBenchmarks.filter { benchmark in
if benchmarkNamesOrIndices.isEmpty {
return benchmark.tags.isSuperset(of: _tags) &&
benchmark.tags.isDisjoint(with: _skipTags)
} else {
return benchmarkNamesOrIndices.contains(benchmark.name) ||
benchmarkNamesOrIndices.contains(indices[benchmark.name]!)
}
}.map { (index: indices[$0.name]!, info: $0) }
}
}
func internalMeanSD(_ inputs: [UInt64]) -> (UInt64, UInt64) {
// If we are empty, return 0, 0.
if inputs.isEmpty {
return (0, 0)
}
// If we have one element, return elt, 0.
if inputs.count == 1 {
return (inputs[0], 0)
}
// Ok, we have 2 elements.
var sum1: UInt64 = 0
var sum2: UInt64 = 0
for i in inputs {
sum1 += i
}
let mean: UInt64 = sum1 / UInt64(inputs.count)
for i in inputs {
sum2 = sum2 &+ UInt64((Int64(i) &- Int64(mean))&*(Int64(i) &- Int64(mean)))
}
return (mean, UInt64(sqrt(Double(sum2)/(Double(inputs.count) - 1))))
}
func internalMedian(_ inputs: [UInt64]) -> UInt64 {
return inputs.sorted()[inputs.count / 2]
}
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
@_silgen_name("_swift_leaks_startTrackingObjects")
func startTrackingObjects(_: UnsafePointer<CChar>) -> ()
@_silgen_name("_swift_leaks_stopTrackingObjects")
func stopTrackingObjects(_: UnsafePointer<CChar>) -> Int
#endif
#if os(Linux)
class Timer {
typealias TimeT = timespec
func getTime() -> TimeT {
var ticks = timespec(tv_sec: 0, tv_nsec: 0)
clock_gettime(CLOCK_REALTIME, &ticks)
return ticks
}
func diffTimeInNanoSeconds(from start_ticks: TimeT, to end_ticks: TimeT) -> UInt64 {
var elapsed_ticks = timespec(tv_sec: 0, tv_nsec: 0)
if end_ticks.tv_nsec - start_ticks.tv_nsec < 0 {
elapsed_ticks.tv_sec = end_ticks.tv_sec - start_ticks.tv_sec - 1
elapsed_ticks.tv_nsec = end_ticks.tv_nsec - start_ticks.tv_nsec + 1000000000
} else {
elapsed_ticks.tv_sec = end_ticks.tv_sec - start_ticks.tv_sec
elapsed_ticks.tv_nsec = end_ticks.tv_nsec - start_ticks.tv_nsec
}
return UInt64(elapsed_ticks.tv_sec) * UInt64(1000000000) + UInt64(elapsed_ticks.tv_nsec)
}
}
#else
class Timer {
typealias TimeT = UInt64
var info = mach_timebase_info_data_t(numer: 0, denom: 0)
init() {
mach_timebase_info(&info)
}
func getTime() -> TimeT {
return mach_absolute_time()
}
func diffTimeInNanoSeconds(from start_ticks: TimeT, to end_ticks: TimeT) -> UInt64 {
let elapsed_ticks = end_ticks - start_ticks
return elapsed_ticks * UInt64(info.numer) / UInt64(info.denom)
}
}
#endif
class SampleRunner {
let timer = Timer()
let baseline = SampleRunner.usage()
let c: TestConfig
init(_ config: TestConfig) {
self.c = config
}
private static func usage() -> rusage {
var u = rusage(); getrusage(RUSAGE_SELF, &u); return u
}
/// Returns maximum resident set size (MAX_RSS) delta in bytes
func measureMemoryUsage() -> Int {
var current = SampleRunner.usage()
let maxRSS = current.ru_maxrss - baseline.ru_maxrss
if c.verbose {
let pages = maxRSS / sysconf(_SC_PAGESIZE)
func deltaEquation(_ stat: KeyPath<rusage, Int>) -> String {
let b = baseline[keyPath: stat], c = current[keyPath: stat]
return "\(c) - \(b) = \(c - b)"
}
print("""
MAX_RSS \(deltaEquation(\rusage.ru_maxrss)) (\(pages) pages)
ICS \(deltaEquation(\rusage.ru_nivcsw))
VCS \(deltaEquation(\rusage.ru_nvcsw))
""")
}
return maxRSS
}
func run(_ name: String, fn: (Int) -> Void, num_iters: UInt) -> UInt64 {
// Start the timer.
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
name.withCString { p in startTrackingObjects(p) }
#endif
let start_ticks = timer.getTime()
fn(Int(num_iters))
// Stop the timer.
let end_ticks = timer.getTime()
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
name.withCString { p in stopTrackingObjects(p) }
#endif
// Compute the spent time and the scaling factor.
return timer.diffTimeInNanoSeconds(from: start_ticks, to: end_ticks)
}
}
/// Invoke the benchmark entry point and return the run time in milliseconds.
func runBench(_ test: BenchmarkInfo, _ c: TestConfig) -> BenchResults? {
var samples = [UInt64](repeating: 0, count: c.numSamples)
// Before we do anything, check that we actually have a function to
// run. If we don't it is because the benchmark is not supported on
// the platform and we should skip it.
guard let testFn = test.runFunction else {
if c.verbose {
print("Skipping unsupported benchmark \(test.name)!")
}
return nil
}
if c.verbose {
print("Running \(test.name) for \(c.numSamples) samples.")
}
let sampler = SampleRunner(c)
for s in 0..<c.numSamples {
test.setUpFunction?()
let time_per_sample: UInt64 = 1_000_000_000 * UInt64(c.iterationScale)
var scale : UInt
var elapsed_time : UInt64 = 0
if c.fixedNumIters == 0 {
elapsed_time = sampler.run(test.name, fn: testFn, num_iters: 1)
if elapsed_time > 0 {
scale = UInt(time_per_sample / elapsed_time)
} else {
if c.verbose {
print(" Warning: elapsed time is 0. This can be safely ignored if the body is empty.")
}
scale = 1
}
} else {
// Compute the scaling factor if a fixed c.fixedNumIters is not specified.
scale = c.fixedNumIters
if scale == 1 {
elapsed_time = sampler.run(test.name, fn: testFn, num_iters: 1)
}
}
// Make integer overflow less likely on platforms where Int is 32 bits wide.
// FIXME: Switch BenchmarkInfo to use Int64 for the iteration scale, or fix
// benchmarks to not let scaling get off the charts.
scale = min(scale, UInt(Int.max) / 10_000)
// Rerun the test with the computed scale factor.
if scale > 1 {
if c.verbose {
print(" Measuring with scale \(scale).")
}
elapsed_time = sampler.run(test.name, fn: testFn, num_iters: scale)
} else {
scale = 1
}
// save result in microseconds or k-ticks
samples[s] = elapsed_time / UInt64(scale) / 1000
if c.verbose {
print(" Sample \(s),\(samples[s])")
}
test.tearDownFunction?()
}
let (mean, sd) = internalMeanSD(samples)
// Return our benchmark results.
return BenchResults(sampleCount: UInt64(samples.count),
min: samples.min()!, max: samples.max()!,
mean: mean, sd: sd, median: internalMedian(samples),
maxRSS: UInt64(sampler.measureMemoryUsage()))
}
func printRunInfo(_ c: TestConfig) {
if c.verbose {
print("--- CONFIG ---")
print("NumSamples: \(c.numSamples)")
print("Verbose: \(c.verbose)")
print("IterScale: \(c.iterationScale)")
if c.fixedNumIters != 0 {
print("FixedIters: \(c.fixedNumIters)")
}
print("Tests Filter: \(c.filters)")
print("Tests to run: ", terminator: "")
print(c.tests.map({ $0.1.name }).joined(separator: ", "))
print("")
print("--- DATA ---")
}
}
/// Execute benchmarks and continuously report the measurement results.
func runBenchmarks(_ c: TestConfig) {
let withUnit = {$0 + "(us)"}
let header = (
["#", "TEST", "SAMPLES"] +
["MIN", "MAX", "MEAN", "SD", "MEDIAN"].map(withUnit)
+ ["MAX_RSS(B)"]
).joined(separator: c.delim)
print(header)
var testCount = 0
func report(_ index: String, _ t: BenchmarkInfo, results: BenchResults?) {
func values(r: BenchResults) -> [String] {
return [r.sampleCount, r.min, r.max, r.mean, r.sd, r.median, r.maxRSS]
.map { String($0) }
}
let benchmarkStats = (
[index, t.name] + (results.map(values) ?? ["Unsupported"])
).joined(separator: c.delim)
print(benchmarkStats)
fflush(stdout)
if (results != nil) {
testCount += 1
}
}
for (index, test) in c.tests {
report(index, test, results:runBench(test, c))
}
print("")
print("Totals\(c.delim)\(testCount)")
}
public func main() {
var config = TestConfig()
do {
switch (try config.processArguments()) {
case let .help(validOptions):
print("Valid options:")
for v in validOptions {
print(" \(v)")
}
case .listTests:
config.findTestsToRun()
print("#\(config.delim)Test\(config.delim)[Tags]")
for (index, t) in config.tests {
let testDescription = [String(index), t.name, t.tags.sorted().description]
.joined(separator: config.delim)
print(testDescription)
}
case .run:
config.findTestsToRun()
printRunInfo(config)
runBenchmarks(config)
if let x = config.afterRunSleep {
sleep(UInt32(x))
}
}
} catch let error as ArgumentError {
fflush(stdout)
fputs("\(error)\n", stderr)
fflush(stderr)
exit(1)
} catch {
fatalError("\(error)")
}
}
|
// TCPClientSocket.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import CLibvenice
import C7
public final class TCPConnection: C7.Connection {
public var uri: C7.URI
var socket: tcpsock?
public private(set) var closed = false
public init(to uri: C7.URI) throws {
self.uri = uri
}
public func open() throws {
guard let host = uri.host else {
throw TCPError.unknown(description: "Host was not defined in URI")
}
guard let port = uri.port else {
throw TCPError.unknown(description: "Port was not defined in URI")
}
tcpconnect(try IP(remoteAddress: host, port: port).address, never)
}
public func receive(max byteCount: Int) throws -> C7.Data {
return try receive(upTo: byteCount, timingOut: never)
}
public func send(data: C7.Data) throws {
try send(data, flush: true, deadline: never)
}
public func flush() throws {
try flush(timingOut: never)
}
public func flush(timingOut deadline: Deadline) throws {
let socket = try getSocket()
try assertNotClosed()
tcpflush(socket, deadline)
try TCPError.assertNoError()
}
public func send(data: Data, flush: Bool = true, deadline: Deadline = never) throws {
let socket = try getSocket()
try assertNotClosed()
let bytesProcessed = data.withUnsafeBufferPointer {
tcpsend(socket, $0.baseAddress, $0.count, deadline)
}
try TCPError.assertNoSendErrorWithData(data, bytesProcessed: bytesProcessed)
if flush {
try self.flush()
}
}
public func receive(upTo byteCount: Int, timingOut deadline: Deadline = never) throws -> Data {
let socket = try getSocket()
try assertNotClosed()
var data = Data.bufferWithSize(byteCount)
let bytesProcessed = data.withUnsafeMutableBufferPointer {
tcprecv(socket, $0.baseAddress, $0.count, deadline)
}
try TCPError.assertNoReceiveErrorWithData(data, bytesProcessed: bytesProcessed)
return Data(data.prefix(bytesProcessed))
}
public func receive(lowWaterMark lowWaterMark: Int, highWaterMark: Int, timingOut deadline: Deadline = never) throws -> Data {
let socket = try getSocket()
try assertNotClosed()
if lowWaterMark <= 0 || highWaterMark <= 0 {
throw TCPError.unknown(description: "Marks should be > 0")
}
if lowWaterMark > highWaterMark {
throw TCPError.unknown(description: "loweWaterMark should be less than highWaterMark")
}
var data = Data.bufferWithSize(highWaterMark)
let bytesProcessed = data.withUnsafeMutableBufferPointer {
tcprecvlh(socket, $0.baseAddress, lowWaterMark, highWaterMark, deadline)
}
try TCPError.assertNoReceiveErrorWithData(data, bytesProcessed: bytesProcessed)
return Data(data.prefix(bytesProcessed))
}
public func receive(upTo byteCount: Int, untilDelimiter delimiter: String, timingOut deadline: Deadline = never) throws -> Data {
let socket = try getSocket()
try assertNotClosed()
var data = Data.bufferWithSize(byteCount)
let bytesProcessed = data.withUnsafeMutableBufferPointer {
tcprecvuntil(socket, $0.baseAddress, $0.count, delimiter, delimiter.utf8.count, deadline)
}
try TCPError.assertNoReceiveErrorWithData(data, bytesProcessed: bytesProcessed)
return Data(data.prefix(bytesProcessed))
}
public func close() -> Bool {
guard let socket = self.socket else {
closed = true
return true
}
if closed {
return false
}
closed = true
tcpclose(socket)
return true
}
func getSocket() throws -> tcpsock {
guard let socket = self.socket else {
throw TCPError.closedSocket(description: "Socket has not been initialized. You must first connect to the socket.")
}
return socket
}
func assertNotClosed() throws {
if closed {
throw TCPError.closedSocketError
}
}
deinit {
if let socket = socket where !closed {
tcpclose(socket)
}
}
}
extension TCPConnection {
public func send(convertible: DataConvertible, timingOut deadline: Deadline = never) throws {
try send(convertible.data, deadline: deadline)
}
public func receiveString(length length: Int, timingOut deadline: Deadline = never) throws -> String {
let result = try receive(upTo: length, timingOut: deadline)
return try String(data: result)
}
public func receiveString(length length: Int, untilDelimiter delimiter: String, timingOut deadline: Deadline = never) throws -> String {
let result = try receive(upTo: length, untilDelimiter: delimiter, timingOut: deadline)
return try String(data: result)
}
}
receiveString upTo codeUnitCount
// TCPClientSocket.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import CLibvenice
import C7
public final class TCPConnection: C7.Connection {
public var uri: C7.URI
var socket: tcpsock?
public private(set) var closed = false
public init(to uri: C7.URI) throws {
self.uri = uri
}
public func open() throws {
guard let host = uri.host else {
throw TCPError.unknown(description: "Host was not defined in URI")
}
guard let port = uri.port else {
throw TCPError.unknown(description: "Port was not defined in URI")
}
tcpconnect(try IP(remoteAddress: host, port: port).address, never)
}
public func receive(max byteCount: Int) throws -> C7.Data {
return try receive(upTo: byteCount, timingOut: never)
}
public func send(data: C7.Data) throws {
try send(data, flush: true, deadline: never)
}
public func flush() throws {
try flush(timingOut: never)
}
public func flush(timingOut deadline: Deadline) throws {
let socket = try getSocket()
try assertNotClosed()
tcpflush(socket, deadline)
try TCPError.assertNoError()
}
public func send(data: Data, flush: Bool = true, deadline: Deadline = never) throws {
let socket = try getSocket()
try assertNotClosed()
let bytesProcessed = data.withUnsafeBufferPointer {
tcpsend(socket, $0.baseAddress, $0.count, deadline)
}
try TCPError.assertNoSendErrorWithData(data, bytesProcessed: bytesProcessed)
if flush {
try self.flush()
}
}
public func receive(upTo byteCount: Int, timingOut deadline: Deadline = never) throws -> Data {
let socket = try getSocket()
try assertNotClosed()
var data = Data.bufferWithSize(byteCount)
let bytesProcessed = data.withUnsafeMutableBufferPointer {
tcprecv(socket, $0.baseAddress, $0.count, deadline)
}
try TCPError.assertNoReceiveErrorWithData(data, bytesProcessed: bytesProcessed)
return Data(data.prefix(bytesProcessed))
}
public func receive(lowWaterMark lowWaterMark: Int, highWaterMark: Int, timingOut deadline: Deadline = never) throws -> Data {
let socket = try getSocket()
try assertNotClosed()
if lowWaterMark <= 0 || highWaterMark <= 0 {
throw TCPError.unknown(description: "Marks should be > 0")
}
if lowWaterMark > highWaterMark {
throw TCPError.unknown(description: "loweWaterMark should be less than highWaterMark")
}
var data = Data.bufferWithSize(highWaterMark)
let bytesProcessed = data.withUnsafeMutableBufferPointer {
tcprecvlh(socket, $0.baseAddress, lowWaterMark, highWaterMark, deadline)
}
try TCPError.assertNoReceiveErrorWithData(data, bytesProcessed: bytesProcessed)
return Data(data.prefix(bytesProcessed))
}
public func receive(upTo byteCount: Int, untilDelimiter delimiter: String, timingOut deadline: Deadline = never) throws -> Data {
let socket = try getSocket()
try assertNotClosed()
var data = Data.bufferWithSize(byteCount)
let bytesProcessed = data.withUnsafeMutableBufferPointer {
tcprecvuntil(socket, $0.baseAddress, $0.count, delimiter, delimiter.utf8.count, deadline)
}
try TCPError.assertNoReceiveErrorWithData(data, bytesProcessed: bytesProcessed)
return Data(data.prefix(bytesProcessed))
}
public func close() -> Bool {
guard let socket = self.socket else {
closed = true
return true
}
if closed {
return false
}
closed = true
tcpclose(socket)
return true
}
func getSocket() throws -> tcpsock {
guard let socket = self.socket else {
throw TCPError.closedSocket(description: "Socket has not been initialized. You must first connect to the socket.")
}
return socket
}
func assertNotClosed() throws {
if closed {
throw TCPError.closedSocketError
}
}
deinit {
if let socket = socket where !closed {
tcpclose(socket)
}
}
}
extension TCPConnection {
public func send(convertible: DataConvertible, timingOut deadline: Deadline = never) throws {
try send(convertible.data, deadline: deadline)
}
public func receiveString(upTo codeUnitCount: Int, timingOut deadline: Deadline = never) throws -> String {
let result = try receive(upTo: codeUnitCount, timingOut: deadline)
return try String(data: result)
}
public func receiveString(upTo codeUnitCount: Int, untilDelimiter delimiter: String, timingOut deadline: Deadline = never) throws -> String {
let result = try receive(upTo: codeUnitCount, untilDelimiter: delimiter, timingOut: deadline)
return try String(data: result)
}
} |
//
// MapView.swift
// BSWInterfaceKit
//
// Created by Pierluigi Cifani on 21/07/2018.
//
import UIKit
import MapKit
@objc(BSWMapView)
public class MapView: UIImageView {
public init() {
super.init(image: UIImage.interfaceKitImageNamed("grid-placeholder"))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func configureFor(lat: Double, long: Double) {
let options = MKMapSnapshotter.Options.init()
let location = CLLocationCoordinate2DMake(CLLocationDegrees(lat), CLLocationDegrees(long))
let region = MKCoordinateRegion(center: location, latitudinalMeters: 1000, longitudinalMeters: 1000)
options.region = region
options.scale = UIScreen.main.scale
options.size = self.frame.size
options.showsBuildings = true
options.showsPointsOfInterest = true
let snapshotter = MKMapSnapshotter(options: options)
let rect = self.bounds
snapshotter.start { (snapshot, error) in
guard error == nil, let snapshot = snapshot else { return }
UIGraphicsBeginImageContextWithOptions(options.size, true, 0)
snapshot.image.draw(at: .zero)
let pinView = MKPinAnnotationView(annotation: nil, reuseIdentifier: nil)
let pinImage = pinView.image
var point = snapshot.point(for: location)
if rect.contains(point) {
let pinCenterOffset = pinView.centerOffset
point.x -= pinView.bounds.size.width / 2
point.y -= pinView.bounds.size.height / 2
point.x += pinCenterOffset.x
point.y += pinCenterOffset.y
pinImage?.draw(at: point)
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.image = image
}
}
}
Render image in MapView using UIGraphicsImageRenderer
//
// MapView.swift
// BSWInterfaceKit
//
// Created by Pierluigi Cifani on 21/07/2018.
//
import UIKit
import MapKit
@objc(BSWMapView)
@available (iOS 10, *)
public class MapView: UIImageView {
public init() {
super.init(image: UIImage.interfaceKitImageNamed("grid-placeholder"))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func configureFor(lat: Double, long: Double) {
let options = MKMapSnapshotter.Options()
let location = CLLocationCoordinate2DMake(CLLocationDegrees(lat), CLLocationDegrees(long))
let region = MKCoordinateRegion(center: location, latitudinalMeters: 1000, longitudinalMeters: 1000)
options.region = region
options.scale = UIScreen.main.scale
options.size = self.frame.size
options.showsBuildings = true
options.showsPointsOfInterest = true
let snapshotter = MKMapSnapshotter(options: options)
let rect = self.bounds
snapshotter.start { (snapshot, error) in
guard error == nil, let snapshot = snapshot else { return }
let renderer = UIGraphicsImageRenderer(size: options.size)
let image = renderer.image(actions: { (context) in
snapshot.image.draw(at: .zero)
let pinView = MKPinAnnotationView(annotation: nil, reuseIdentifier: nil)
let pinImage = pinView.image
var point = snapshot.point(for: location)
if rect.contains(point) {
let pinCenterOffset = pinView.centerOffset
point.x -= pinView.bounds.size.width / 2
point.y -= pinView.bounds.size.height / 2
point.x += pinCenterOffset.x
point.y += pinCenterOffset.y
pinImage?.draw(at: point)
}
})
self.image = image
}
}
}
|
/*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import Foundation
public extension Date {
// MARK: - Formatters
static fileprivate var ISO8601MillisecondFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return formatter
}
static fileprivate var ISO8601SecondFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter
}
static fileprivate var ISO8601YearMonthDayFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}
static fileprivate var dateAndTimeFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
return formatter
}
static fileprivate var fullDateAndTimeFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .full
formatter.timeStyle = .short
return formatter
}
static fileprivate var fullDateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .full
return formatter
}
static fileprivate var timeFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.timeStyle = .short
return formatter
}
static fileprivate var dayAndMonthFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "MMM d", options: 0, locale: Locale.current)
return formatter
}
static fileprivate let parsingFormatters = [ISO8601MillisecondFormatter, ISO8601SecondFormatter, ISO8601YearMonthDayFormatter]
static public func fromISO8601String(_ dateString:String) -> Date? {
for formatter in parsingFormatters {
if let date = formatter.date(from: dateString) {
return date
}
}
return .none
}
static public func fromMillisecondsSince1970(_ milliseconds: Double) -> Date {
let dateSeconds = milliseconds / 1000.0
let dateInterval = TimeInterval(dateSeconds)
let date = Date(timeIntervalSince1970: dateInterval)
return date
}
// MARK: - Formatted computed vars
/// E.g. "3:30 PM"
public var timeString: String {
return Date.timeFormatter.string(from: self)
}
/// E.g. "Nov 23, 1937, 3:30 PM"
public var dateAndTimeString: String {
return Date.dateAndTimeFormatter.string(from: self)
}
/// E.g. "Tuesday, November 23, 1937 at 3:30 PM"
public var fullDateAndTimeString: String {
return Date.fullDateAndTimeFormatter.string(from: self)
}
/// E.g. "Tuesday, November 23, 1937"
public var fullDateString: String {
return Date.fullDateFormatter.string(from: self)
}
/// E.g. "1937-11-23T15:30:00-0700"
public var iso8601DateAndTimeString: String {
return Date.ISO8601SecondFormatter.string(from: self)
}
/// E.g. "1937-11-23T15:30:00.023-0700"
public var iso8601MillisecondString: String {
return Date.ISO8601MillisecondFormatter.string(from: self)
}
/// E.g. "1937-11-23"
public var iso8601DateString: String {
return Date.ISO8601YearMonthDayFormatter.string(from: self)
}
public var millisecondsSince1970: TimeInterval {
return round(self.timeIntervalSince1970 * 1000)
}
/// E.g. "Nov 23"
public var dayAndMonthString: String {
return Date.dayAndMonthFormatter.string(from: self)
}
/// `Today`, `Yesterday`, or month and day (e.g. Aug 15)
public var relativeDayAndMonthString: String {
let now = Date()
if isSameDay(as: now - 1.days) {
return NSLocalizedString("Yesterday", comment: "Relative date string for previous day")
}
if isSameDay(as: now) {
return NSLocalizedString("Today", comment: "Relative date string for current day")
}
if isSameDay(as: now + 1.days) {
return NSLocalizedString("Tomorrow", comment: "Relative date string for next day")
}
return dayAndMonthString
}
public var relativeDayAndTimeString: String {
return String.localizedStringWithFormat(NSLocalizedString("%@, %@", comment: "Relative date and time string. First parameter is relative date, second is time."), relativeDayAndMonthString, timeString)
}
// MARK: - Helper computed vars
public var isToday: Bool {
let now = Date()
return isSameDay(as: now)
}
public var startOfDay: Date {
let calendar = Calendar.current
let components = (calendar as NSCalendar).components([.era, .year, .month, .day], from: self)
let startOfDate = calendar.date(from: components)!
return startOfDate
}
public var endOfDay: Date {
let calendar = Calendar.current
let nextDay = (calendar as NSCalendar).date(byAdding: .day, value: 1, to: self, options: [])!
let components = (calendar as NSCalendar).components([.era, .year, .month, .day], from: nextDay)
let startOfDate = calendar.date(from: components)!
return startOfDate
}
// MARK: - Functions
public func isSameDay(as date: Date) -> Bool {
let calender = Calendar.current
let components: Set<Calendar.Component> = [.day, .month, .year]
let componentsOne = calender.dateComponents(components, from: self)
let componentsTwo = calender.dateComponents(components, from: date)
return componentsOne.day == componentsTwo.day && componentsOne.month == componentsTwo.month && componentsOne.year == componentsTwo.year
}
}
// MARK: - Time intervals on Int
public extension Int {
public var seconds: TimeInterval {
return TimeInterval(self)
}
public var minutes: TimeInterval {
return TimeInterval(self * 60)
}
public var hours: TimeInterval {
return TimeInterval(minutes * 60)
}
public var days: TimeInterval {
return TimeInterval(hours * 24)
}
public var weeks: TimeInterval {
return TimeInterval(days * 7)
}
}
Adds monthDayYearString
/*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import Foundation
public extension Date {
// MARK: - Formatters
static fileprivate var ISO8601MillisecondFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return formatter
}
static fileprivate var ISO8601SecondFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter
}
static fileprivate var ISO8601YearMonthDayFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}
static fileprivate var mediumDateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}
static fileprivate var dateAndTimeFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
return formatter
}
static fileprivate var fullDateAndTimeFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .full
formatter.timeStyle = .short
return formatter
}
static fileprivate var fullDateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .full
return formatter
}
static fileprivate var timeFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.timeStyle = .short
return formatter
}
static fileprivate var dayAndMonthFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "MMM d", options: 0, locale: Locale.current)
return formatter
}
static fileprivate let parsingFormatters = [ISO8601MillisecondFormatter, ISO8601SecondFormatter, ISO8601YearMonthDayFormatter]
static public func fromISO8601String(_ dateString:String) -> Date? {
for formatter in parsingFormatters {
if let date = formatter.date(from: dateString) {
return date
}
}
return .none
}
static public func fromMillisecondsSince1970(_ milliseconds: Double) -> Date {
let dateSeconds = milliseconds / 1000.0
let dateInterval = TimeInterval(dateSeconds)
let date = Date(timeIntervalSince1970: dateInterval)
return date
}
// MARK: - Formatted computed vars
/// E.g. "3:30 PM"
public var timeString: String {
return Date.timeFormatter.string(from: self)
}
// E.g. "Nov 23, 1937"
public var monthDayYearString: String {
return Date.mediumDateFormatter.string(from: self)
}
/// E.g. "Nov 23, 1937, 3:30 PM"
public var dateAndTimeString: String {
return Date.dateAndTimeFormatter.string(from: self)
}
/// E.g. "Tuesday, November 23, 1937 at 3:30 PM"
public var fullDateAndTimeString: String {
return Date.fullDateAndTimeFormatter.string(from: self)
}
/// E.g. "Tuesday, November 23, 1937"
public var fullDateString: String {
return Date.fullDateFormatter.string(from: self)
}
/// E.g. "1937-11-23T15:30:00-0700"
public var iso8601DateAndTimeString: String {
return Date.ISO8601SecondFormatter.string(from: self)
}
/// E.g. "1937-11-23T15:30:00.023-0700"
public var iso8601MillisecondString: String {
return Date.ISO8601MillisecondFormatter.string(from: self)
}
/// E.g. "1937-11-23"
public var iso8601DateString: String {
return Date.ISO8601YearMonthDayFormatter.string(from: self)
}
public var millisecondsSince1970: TimeInterval {
return round(self.timeIntervalSince1970 * 1000)
}
/// E.g. "Nov 23"
public var dayAndMonthString: String {
return Date.dayAndMonthFormatter.string(from: self)
}
/// `Today`, `Yesterday`, or month and day (e.g. Aug 15)
public var relativeDayAndMonthString: String {
let now = Date()
if isSameDay(as: now - 1.days) {
return NSLocalizedString("Yesterday", comment: "Relative date string for previous day")
}
if isSameDay(as: now) {
return NSLocalizedString("Today", comment: "Relative date string for current day")
}
if isSameDay(as: now + 1.days) {
return NSLocalizedString("Tomorrow", comment: "Relative date string for next day")
}
return dayAndMonthString
}
public var relativeDayAndTimeString: String {
return String.localizedStringWithFormat(NSLocalizedString("%@, %@", comment: "Relative date and time string. First parameter is relative date, second is time."), relativeDayAndMonthString, timeString)
}
// MARK: - Helper computed vars
public var isToday: Bool {
let now = Date()
return isSameDay(as: now)
}
public var startOfDay: Date {
let calendar = Calendar.current
let components = (calendar as NSCalendar).components([.era, .year, .month, .day], from: self)
let startOfDate = calendar.date(from: components)!
return startOfDate
}
public var endOfDay: Date {
let calendar = Calendar.current
let nextDay = (calendar as NSCalendar).date(byAdding: .day, value: 1, to: self, options: [])!
let components = (calendar as NSCalendar).components([.era, .year, .month, .day], from: nextDay)
let startOfDate = calendar.date(from: components)!
return startOfDate
}
// MARK: - Functions
public func isSameDay(as date: Date) -> Bool {
let calender = Calendar.current
let components: Set<Calendar.Component> = [.day, .month, .year]
let componentsOne = calender.dateComponents(components, from: self)
let componentsTwo = calender.dateComponents(components, from: date)
return componentsOne.day == componentsTwo.day && componentsOne.month == componentsTwo.month && componentsOne.year == componentsTwo.year
}
}
// MARK: - Time intervals on Int
public extension Int {
public var seconds: TimeInterval {
return TimeInterval(self)
}
public var minutes: TimeInterval {
return TimeInterval(self * 60)
}
public var hours: TimeInterval {
return TimeInterval(minutes * 60)
}
public var days: TimeInterval {
return TimeInterval(hours * 24)
}
public var weeks: TimeInterval {
return TimeInterval(days * 7)
}
}
|
// The MIT License (MIT)
//
// Copyright (c) 2017 Caleb Kleveter
//
// 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 Helpers
import Console
import Foundation
public final class Remove: Command {
public let id = "remove"
public var help: [String] = [
"Removes and uninstalls a package"
]
public var signature: [Argument] = [
Value(name: "name", help: [
"The name of the package that will be removed"
])
]
public let console: ConsoleProtocol
public init(console: ConsoleProtocol) {
self.console = console
}
public func run(arguments: [String]) throws {
let removingProgressBar = console.loadingBar(title: "Removing Dependency")
removingProgressBar.start()
let manager = FileManager.default
let name = try value("name", from: arguments)
let regex = try NSRegularExpression(pattern: "\\,?\n \\.Package\\(url:\\s?\\\"([\\d\\-\\.\\@\\w\\/\\:])+\(name)\\.git\\\"\\,\\s?([\\w\\d\\:\\(\\)\\s\\,])+\\)", options: .caseInsensitive)
let oldPins = try manager.contents(atPath: "\(manager.currentDirectoryPath)/Package.pins")?.json()?["pins"] as? [JSON]
if !manager.fileExists(atPath: "\(manager.currentDirectoryPath)/Package.swift") { throw EtherError.fail("There is no Package.swift file in the current directory") }
let packageData = manager.contents(atPath: "\(manager.currentDirectoryPath)/Package.swift")
guard let packageString = String(data: packageData!, encoding: .utf8) else { throw fail(bar: removingProgressBar, with: "Unable to read Package.swift") }
let mutableString = NSMutableString(string: packageString)
if regex.matches(in: packageString, options: [], range: NSMakeRange(0, packageString.utf8.count)).count == 0 {
throw fail(bar: removingProgressBar, with: "No packages matching the name passed in where found")
}
regex.replaceMatches(in: mutableString, options: [], range: NSMakeRange(0, mutableString.length), withTemplate: "")
do {
try String(mutableString).data(using: .utf8)?.write(to: URL(string: "file:\(manager.currentDirectoryPath)/Package.swift")!)
_ = try console.backgroundExecute(program: "swift", arguments: ["package", "--enable-prefetching", "fetch"])
_ = try console.backgroundExecute(program: "swift", arguments: ["package", "update"])
} catch let error {
removingProgressBar.fail()
throw error
}
removingProgressBar.finish()
if let pins = oldPins {
if let newPins = try manager.contents(atPath: "\(manager.currentDirectoryPath)/Package.pins")?.json()?["pins"] as? [JSON] {
let newPackages = pins.count - newPins.count
console.output("📦 \(newPackages) packages removed", style: .custom(.white), newLine: true)
}
}
}
}
Updated Remove.run script for SPM 4 API
// The MIT License (MIT)
//
// Copyright (c) 2017 Caleb Kleveter
//
// 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 Helpers
import Console
import Foundation
public final class Remove: Command {
public let id = "remove"
public var help: [String] = [
"Removes and uninstalls a package"
]
public var signature: [Argument] = [
Value(name: "name", help: [
"The name of the package that will be removed"
])
]
public let console: ConsoleProtocol
public init(console: ConsoleProtocol) {
self.console = console
}
public func run(arguments: [String]) throws {
let removingProgressBar = console.loadingBar(title: "Removing Dependency")
removingProgressBar.start()
let manager = FileManager.default
let name = try value("name", from: arguments)
let url = try Manifest.current.getPackageUrl(for: name)
let regex = try NSRegularExpression(pattern: "\\,?\\n *\\.package\\(url: *\"\(url)\", *\\.?\\w+(:|\\() *\"([\\d\\.]+)\"\\)?\\),?", options: .caseInsensitive)
let oldPins = try Manifest.current.getPins()
let packageString = try Manifest.current.get()
let mutableString = NSMutableString(string: packageString)
if regex.matches(in: packageString, options: [], range: NSMakeRange(0, packageString.utf8.count)).count == 0 {
throw fail(bar: removingProgressBar, with: "No packages matching the name passed in where found")
}
regex.replaceMatches(in: mutableString, options: [], range: NSMakeRange(0, mutableString.length), withTemplate: "")
try mutableString.removeDependency(name)
do {
try String(mutableString).data(using: .utf8)?.write(to: URL(string: "file:\(manager.currentDirectoryPath)/Package.swift")!)
_ = try console.backgroundExecute(program: "rm", arguments: ["-rf", ".build"])
_ = try console.backgroundExecute(program: "swift", arguments: ["package", "update"])
_ = try console.backgroundExecute(program: "swift", arguments: ["package", "resolve"])
_ = try console.backgroundExecute(program: "swift", arguments: ["build"])
} catch let error {
removingProgressBar.fail()
throw error
}
let pins = try Manifest.current.getPins()
let pinsCount = oldPins.count - pins.count
removingProgressBar.finish()
console.output("📦 \(pinsCount) packages removed", style: .custom(.white), newLine: true)
}
}
|
public final class Faker {
public var locale: String {
didSet {
if locale != oldValue {
parser.locale = locale
}
}
}
public let address: Address
public let app: App
public let business: Business
public let company: Company
public let commerce: Commerce
public let internet: Internet
public let lorem: Lorem
public let name: Name
public let phoneNumber: PhoneNumber
public let team: Team
public let number: Number
public let bank: Bank
public let date: Date
let parser: Parser
// MARK: - Initialization
public init(locale: String = Config.defaultLocale) {
self.locale = locale
parser = Parser(locale: self.locale)
address = Address(parser: parser)
app = App(parser: parser)
business = Business(parser: parser)
company = Company(parser: parser)
commerce = Commerce(parser: parser)
internet = Internet(parser: parser)
lorem = Lorem(parser: parser)
name = Name(parser: parser)
phoneNumber = PhoneNumber(parser: parser)
team = Team(parser: parser)
number = Number()
bank = Bank(parser: parser)
date = Date()
}
}
Adding missing variable to the Faker class to be used
public final class Faker {
public var locale: String {
didSet {
if locale != oldValue {
parser.locale = locale
}
}
}
public let address: Address
public let app: App
public let business: Business
public let company: Company
public let commerce: Commerce
public let internet: Internet
public let lorem: Lorem
public let name: Name
public let phoneNumber: PhoneNumber
public let team: Team
public let number: Number
public let bank: Bank
public let date: Date
public let car: Car
let parser: Parser
// MARK: - Initialization
public init(locale: String = Config.defaultLocale) {
self.locale = locale
parser = Parser(locale: self.locale)
address = Address(parser: parser)
app = App(parser: parser)
business = Business(parser: parser)
company = Company(parser: parser)
commerce = Commerce(parser: parser)
internet = Internet(parser: parser)
lorem = Lorem(parser: parser)
name = Name(parser: parser)
phoneNumber = PhoneNumber(parser: parser)
team = Team(parser: parser)
number = Number()
bank = Bank(parser: parser)
date = Date()
car = Car(parser: parser)
}
}
|
//
// Lexer.swift
// Kaleidoscope
//
// Created by Matthew Cheok on 15/11/15.
// Copyright © 2015 Matthew Cheok. All rights reserved.
//
import Foundation
public enum Token {
case identifier(String, CountableRange<Int>)
case number(Float, CountableRange<Int>)
case parensOpen(CountableRange<Int>)
case parensClose(CountableRange<Int>)
case comma(CountableRange<Int>)
case other(String, CountableRange<Int>)
}
typealias TokenGenerator = (String, CountableRange<Int>) -> Token?
let tokenList: [(String, TokenGenerator)] = [
("[ \t\n]", { _, _ in nil }),
("[a-zA-Z][a-zA-Z0-9]*", { .identifier($0, $1) }),
("\\-?[0-9.]+", { .number(Float($0)!, $1) }),
("\\(", { .parensOpen($1) }),
("\\)", { .parensClose($1) }),
(",", { .comma($1) })
]
public class Lexer {
let input: String
public init(input: String) {
self.input = input
}
public func tokenize() -> [Token] {
var tokens = [Token]()
var content = input
while !content.characters.isEmpty {
var matched = false
for (pattern, generator) in tokenList {
if let (m, r) = content.match(regex: pattern) {
if let t = generator(m, r) {
tokens.append(t)
}
content = content.substring(from: content.index(content.startIndex, offsetBy: m.characters.count))
matched = true
break
}
}
if !matched {
let index = content.index(content.startIndex, offsetBy: 1)
let intIndex = content.distance(from: content.startIndex, to: index)
tokens.append(.other(content.substring(to: index), intIndex..<intIndex+1))
content = content.substring(from: index)
}
}
return tokens
}
}
Remove warning on Xcode9 && Swift4. (#291)
to Swift4 syntax.
//
// Lexer.swift
// Kaleidoscope
//
// Created by Matthew Cheok on 15/11/15.
// Copyright © 2015 Matthew Cheok. All rights reserved.
//
import Foundation
public enum Token {
case identifier(String, CountableRange<Int>)
case number(Float, CountableRange<Int>)
case parensOpen(CountableRange<Int>)
case parensClose(CountableRange<Int>)
case comma(CountableRange<Int>)
case other(String, CountableRange<Int>)
}
typealias TokenGenerator = (String, CountableRange<Int>) -> Token?
let tokenList: [(String, TokenGenerator)] = [
("[ \t\n]", { _, _ in nil }),
("[a-zA-Z][a-zA-Z0-9]*", { .identifier($0, $1) }),
("\\-?[0-9.]+", { .number(Float($0)!, $1) }),
("\\(", { .parensOpen($1) }),
("\\)", { .parensClose($1) }),
(",", { .comma($1) })
]
public class Lexer {
let input: String
public init(input: String) {
self.input = input
}
public func tokenize() -> [Token] {
var tokens = [Token]()
var content = input
while !content.characters.isEmpty {
var matched = false
for (pattern, generator) in tokenList {
if let (m, r) = content.match(regex: pattern) {
if let t = generator(m, r) {
tokens.append(t)
}
content = String(content[content.index(content.startIndex, offsetBy: m.characters.count)...])
matched = true
break
}
}
if !matched {
let index = content.index(content.startIndex, offsetBy: 1)
let intIndex = content.distance(from: content.startIndex, to: index)
tokens.append(.other(String(content[..<index]), intIndex..<intIndex+1))
content = String(content[index...])
}
}
return tokens
}
}
|
//
// String.swift
// Mechanica
//
// Copyright © 2016-2017 Tinrobots.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
extension String {
// MARK: - Helper Methods
/// **Mechanica**
///
/// Returns the length of the `String`.
public var length: Int {
return self.characters.count
}
/// **Mechanica**
///
/// Reverse `self`.
public mutating func reverse() {
self = String(self.characters.reversed())
}
/// **Mechanica**
///
/// Returns a `new` reversed `String`.
/// Shorthand for *self.characters.reverse()*.
public func reversed() -> String {
return String(self.characters.reversed())
}
/// **Mechanica**
///
/// Returns true if `self` starts with a given prefix.
public func starts(with prefix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasPrefix(prefix.lowercased())
}
return hasPrefix(prefix)
}
/// **Mechanica**
///
/// Returns true if `self` ends with a given suffix.
public func ends(with suffix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasSuffix(suffix.lowercased())
}
return hasSuffix(suffix)
}
/// **Mechanica**
///
/// Checks if a `String` contains a given pattern.
///
/// - Parameters:
/// - pattern: Pattern to match.
/// - caseSensitive: Search option: *true* for case-sensitive, *false* for case-insensitive. (if true this function is equivalent to `self.contains(...)`)
///
/// - Returns: true if contains match, otherwise false.
public func contains(_ pattern: String, caseSensitive: Bool) -> Bool {
if (caseSensitive) {
return self.contains(pattern) //(self.range(of: pattern) != nil)
} else {
return (self.range(of: pattern, options: .caseInsensitive) != nil)
}
}
/// **Mechanica**
///
/// Checks if if all the characters in the string belong to a specific `CharacterSet`.
///
/// - Parameter characterSet: The `CharacterSet` used to test the string.
/// - Returns: true if all the characters in the string belong to the `CharacterSet`, otherwise, false.
public func containsCharacters(in characterSet: CharacterSet) -> Bool {
guard !isEmpty else { return false }
for scalar in unicodeScalars {
guard characterSet.contains(scalar) else { return false }
}
return true
}
/// **Mechanica**
///
/// Returns a `new` string in which all occurrences of a target are replaced by another given string.
///
/// - Parameters:
/// - target: target string
/// - replacement: replacement string
/// - caseSensitive: `true` (default) for a case-sensitive replacemente
public func replace(_ target: String, with replacement: String, caseSensitive: Bool = true) -> String {
let compareOptions: String.CompareOptions = (caseSensitive == true) ? [.literal] : [.literal, .caseInsensitive]
return self.replacingOccurrences(of: target, with: replacement, options: compareOptions, range: nil)
}
/// **Mechanica**
///
/// Generates a `new` random alphanumeric string of a given length (default 8).
public static func random(length: Int = 8) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: String = ""
for _ in 0..<length {
let randomValue = arc4random_uniform(UInt32(base.characters.count))
randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
}
return randomString
}
// MARK: - Trimming Methods
/// **Mechanica**
///
/// Removes spaces and new lines from both ends of `self.
public mutating func trim() {
self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
/// **Mechanica**
///
/// Returns a `new` String made by removing spaces and new lines from both ends.
public func trimmed() -> String {
//return trimmedLeft().trimmedRight()
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// **Mechanica**
///
/// Strips the specified characters from the beginning of `self`.
///
/// - parameter set: characters to strip
///
/// - Returns: stripped string
public func trimmedLeft(characterSet set: CharacterSet = .whitespacesAndNewlines) -> String {
if let range = rangeOfCharacter(from: set.inverted) {
return self[range.lowerBound..<endIndex]
}
return ""
}
/// **Mechanica**
///
/// Strips the specified characters from the end of `self`.
///
/// - parameter set: characters to strip
///
/// - Returns: stripped string
public func trimmedRight(characterSet set: CharacterSet = .whitespacesAndNewlines) -> String {
if let range = rangeOfCharacter(from: set.inverted, options: .backwards) {
return self[startIndex..<range.upperBound]
}
return ""
}
/// **Mechanica**
///
/// Produces a `new` string with the first character of the first word changed to the corresponding uppercase value.
public func capitalizedFirstCharacter() -> String {
guard (!self.isEmpty) else { return self }
let capitalizedFirstCharacher = String(self[startIndex]).uppercased() //capitalized
let result = capitalizedFirstCharacher + String(self.characters.dropFirst())
return result
}
/// **Mechanica**
///
/// Produces a `new` string with the first character of the first word changed to the corresponding uppercase value.
public func decapitalizedFirstCharacter() -> String {
guard (!self.isEmpty) else { return self }
let capitalizedFirstCharacher = String(self[startIndex]).lowercased()
let result = capitalizedFirstCharacher + String(self.characters.dropFirst())
return result
}
/// **Mechanica**
///
/// Returns a `new` string containing the first character of the `String`.
public var first: String {
let last = self.substring(to: self.index(after: self.startIndex))
return last
}
/// **Mechanica**
///
/// Returns a `new` string containing the last character of the `String`.
public var last: String {
let last = self.substring(from: self.index(before: self.endIndex))
return last
}
/// **Mechanica**
///
/// Returns a substring, up to maxLength in length, containing the initial elements of the `String`.
///
/// - Warning: If maxLength exceeds self.count, the result contains all the elements of self.
/// - parameter maxLength: substring max lenght
///
public func prefix(maxLength: Int) -> String {
guard maxLength > 0 else {
return ""
}
return String(self.characters.prefix(maxLength))
}
/// **Mechanica**
///
/// Returns a slice, up to maxLength in length, containing the final elements of `String`.
///
/// - Warning: If maxLength exceeds `String` character count, the result contains all the elements of `String`.
/// - parameter maxLength: substring max lenght
public func suffix(maxLength: Int) -> String {
guard maxLength > 0 else {
return ""
}
return String(self.characters.suffix(maxLength))
}
// MARK: - Remove Methods
/// **Mechanica**
///
/// Returns a new `String` containing the characters of the String from the one at a given position to the end.
///
/// - parameter upToPosition: position (included) up to which remove the prefix.
public func removingPrefix(upToPosition: Int = 1) -> String {
guard (upToPosition >= 0 && upToPosition <= self.length) else {
return ""
}
let startIndex = self.index(self.startIndex, offsetBy: upToPosition)
return self.substring(from: startIndex)
}
/// **Mechanica**
///
/// Returns a new `String` containing the characters of the String up to, but not including, the one at a given position.
///
/// - parameter fromPosition: position (included) from which remove the suffix
public func removingSuffix(fromPosition: Int = 1) -> String {
guard (fromPosition >= 0 && fromPosition <= self.length) else {
return ""
}
let startIndex = self.index(self.endIndex, offsetBy: -fromPosition)
return self.substring(to: startIndex)
}
/// **Mechanica**
///
/// Returns a new `String` removing the characters in the given set.
public func removingCharacters(in set: CharacterSet) -> String {
var chars = characters
for idx in chars.indices.reversed() {
if set.contains(String(chars[idx]).unicodeScalars.first!) {
chars.remove(at: idx)
}
}
return String(chars)
}
/// **Mechanica**
///
/// Truncates the `String` to the given length (number of characters) and appends optional trailing string if longer.
/// The default trailing is the ellipsis (…).
/// - parameter length: number of characters after which the `String` is truncated
/// - parameter trailing: optional trailing string
///
public func truncate(at length: Int, withTrailing trailing: String? = "…") -> String {
switch length {
case 0..<self.length:
//return self.substringToIndex(self.startIndex.advancedBy(length)) + (trailing ?? "")
return self.prefix(maxLength: length) + (trailing ?? "")
case _ where length >= self.length:
return self // no truncation needed
default:
return ""
}
}
// MARK: - Cleaning Methods
/// **Mechanica**
///
/// Condenses all white spaces repetitions in a single white space.
/// White space at the beginning or ending of the `String` are trimmed out.
///
/// ```
/// let aString = "test too many spaces"
/// aString.removeExcessiveSpaces //test too many spaces
/// ```
///
/// - Returns: A `new` string where all white spaces repetitions are replaced with a single white space.
public func condensingExcessiveSpaces() -> String {
let components = self.components(separatedBy: .whitespaces)
let filtered = components.filter({!$0.isEmpty})
return filtered.joined(separator: " ")
}
/// **Mechanica**
///
/// Condenses all white spaces and new lines repetitions in a single white space.
/// White space and new lines at the beginning or ending of the `String` are trimmed out.
///
/// - Returns: A `new` string where all white spaces and new lines repetitions are replaced with a single white space.
public func condensingExcessiveSpacesAndNewlines() -> String {
let components = self.components(separatedBy: .whitespacesAndNewlines)
let filtered = components.filter({!$0.isBlank})
return filtered.joined(separator: " ")
}
// MARK: Subscript Methods
/// **Mechanica**
///
/// Gets the character at the specified index as String.
///
/// - parameter index: index Position of the character to get
///
/// - Returns: Character as String or nil if the index is out of bounds
public subscript (index: Int) -> String? {
guard (0..<self.characters.count ~= index) else {
return nil
}
return String(Array(self.characters)[index])
}
/// **Mechanica**
///
/// Returns a `new` string in which the characters in a specified `CountableClosedRange` range of the String are replaced by a given string.
public func replacingCharacters(in range: CountableClosedRange<Int>, with replacement: String) -> String {
let start = characters.index(characters.startIndex, offsetBy: range.lowerBound)
let end = characters.index(start, offsetBy: range.count)
return self.replacingCharacters(in: start ..< end, with: replacement)
}
/// **Mechanica**
///
/// Returns a `new` string in which the characters in a specified `CountableRange` range of the String are replaced by a given string.
public func replacingCharacters(in range: CountableRange<Int>, with replacement: String) -> String {
let start = characters.index(characters.startIndex, offsetBy: range.lowerBound)
let end = characters.index(start, offsetBy: range.count)
return self.replacingCharacters(in: start ..< end, with: replacement)
}
/// **Mechanica**
///
/// Returns the substring in the given range.
///
/// - parameter range: range
///
/// - Returns: Substring in range or nil.
public subscript (range: Range<Int>) -> String? {
guard (0...self.self.length ~= range.lowerBound) else {
return nil
}
guard (0...self.self.length ~= range.upperBound) else {
return nil
}
let start = self.index(self.startIndex, offsetBy: range.lowerBound)
let end = self.index(self.startIndex, offsetBy: range.upperBound)
return substring(with: Range(uncheckedBounds: (lower: start, upper: end)))
}
/// **Mechanica**
///
/// Returns the substring in the given `NSRange`
///
/// - parameter range: NSRange
///
/// - Returns: Substring in range or nil.
public subscript (range: NSRange) -> String? {
let end = range.location + range.length
return self[Range(uncheckedBounds: (lower: range.location, upper: end))]
}
/// **Mechanica**
///
/// Returns the range of the first occurrence of a given string in the `String`.
///
/// - parameter substring: substring
///
/// - Returns: range of the first occurrence or nil.
public subscript (substring: String) -> Range<String.Index>? {
let range = Range(uncheckedBounds: (lower: startIndex, upper: endIndex))
return self.range(of: substring, options: .literal, range: range, locale: .current)
}
// MARK: Case Operators
/// **Mechanica**
///
/// Produces a camel cased version of the `String`.
///
/// Example:
///
/// let string = "HelloWorld"
/// print(string.decapitalized()) // "helloWorld"
///
/// - Returns: A camel cased copy of the `String`.
public func camelCased() -> String {
return pascalCased().decapitalizedFirstCharacter()
}
/// **Mechanica**
///
/// Produces the kebab cased version of the `String`.
///
/// Example:
///
/// let string = "Hello World"
/// print(string.kebabCased()) // "-Hello-World-"
///
/// - Returns: The kebab cased copy of the `String`.
public func kebabCased() -> String {
return "-" + slugCased() + "-"
}
/// **Mechanica**
///
/// Produces a pascal cased version of the `String`.
///
/// Example:
///
/// let string = "HELLO WORLD"
/// print(string.pascalCased()) // "HelloWorld"
///
/// - Returns: A pascal cased copy of the `String`.
public func pascalCased() -> String {
return self.replacingOccurrences(of: "_", with: " ").replacingOccurrences(of: "-", with: " ").components(separatedBy: .whitespaces).joined()
}
/// **Mechanica**
///
/// Produces the slug version of the `String`.
///
/// Example:
///
/// let string = "Hello World"
/// print(string.slugCased()) // "Hello-World"
///
/// - Returns: The slug copy of the `String`.
public func slugCased() -> String {
return self.replacingOccurrences(of: "_", with: " ").replacingOccurrences(of: "-", with: " ").condensingExcessiveSpaces().replacingOccurrences(of: " ", with: "-").lowercased()
}
/// **Mechanica**
///
/// Produces the snake cased version of the `String`.
///
/// Example:
///
/// let string = "hello world"
/// print(string.snakeCased())
/// // Prints "hello_world"
///
/// - Returns: The slug copy of the `String`.
public func snakeCased() -> String {
return self.replacingOccurrences(of: "_", with: " ").replacingOccurrences(of: "-", with: " ").condensingExcessiveSpaces().replacingOccurrences(of: " ", with: "_")
}
/// **Mechanica**
///
/// Produces the swap cased version of the `String`.
///
/// Example:
///
/// let string = "Hello World"
/// print(string.swapCased()) // "hELLO wORLD"
///
/// - Returns: The swap cased copy of the `String`.
public func swapCased() -> String {
return characters.map({
String($0).isLowercased ? String($0).uppercased() : String($0).lowercased()
}).joined()
}
}
comments
//
// String.swift
// Mechanica
//
// Copyright © 2016-2017 Tinrobots.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
extension String {
// MARK: - Helper Methods
/// **Mechanica**
///
/// Returns the length of the `String`.
public var length: Int {
return self.characters.count
}
/// **Mechanica**
///
/// Reverse `self`.
public mutating func reverse() {
self = String(self.characters.reversed())
}
/// **Mechanica**
///
/// Returns a `new` reversed `String`.
/// Shorthand for *self.characters.reverse()*.
public func reversed() -> String {
return String(self.characters.reversed())
}
/// **Mechanica**
///
/// Returns *true* if `self` starts with a given prefix.
public func starts(with prefix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasPrefix(prefix.lowercased())
}
return hasPrefix(prefix)
}
/// **Mechanica**
///
/// Returns *true* if `self` ends with a given suffix.
public func ends(with suffix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasSuffix(suffix.lowercased())
}
return hasSuffix(suffix)
}
/// **Mechanica**
///
/// Checks if a `String` contains a given pattern.
///
/// - Parameters:
/// - pattern: Pattern to match.
/// - caseSensitive: Search option: *true* for case-sensitive, false for case-insensitive. (if *true* this function is equivalent to `self.contains(...)`)
///
/// - Returns: *true* if contains match, otherwise false.
public func contains(_ pattern: String, caseSensitive: Bool) -> Bool {
if (caseSensitive) {
return self.contains(pattern) //(self.range(of: pattern) != nil)
} else {
return (self.range(of: pattern, options: .caseInsensitive) != nil)
}
}
/// **Mechanica**
///
/// Checks if if all the characters in the string belong to a specific `CharacterSet`.
///
/// - Parameter characterSet: The `CharacterSet` used to test the string.
/// - Returns: *true* if all the characters in the string belong to the `CharacterSet`, otherwise false.
public func containsCharacters(in characterSet: CharacterSet) -> Bool {
guard !isEmpty else { return false }
for scalar in unicodeScalars {
guard characterSet.contains(scalar) else { return false }
}
return true
}
/// **Mechanica**
///
/// Returns a `new` string in which all occurrences of a target are replaced by another given string.
///
/// - Parameters:
/// - target: target string
/// - replacement: replacement string
/// - caseSensitive: `*true*` (default) for a case-sensitive replacemente
public func replace(_ target: String, with replacement: String, caseSensitive: Bool = true) -> String {
let compareOptions: String.CompareOptions = (caseSensitive == true) ? [.literal] : [.literal, .caseInsensitive]
return self.replacingOccurrences(of: target, with: replacement, options: compareOptions, range: nil)
}
/// **Mechanica**
///
/// Generates a `new` random alphanumeric string of a given length (default 8).
public static func random(length: Int = 8) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: String = ""
for _ in 0..<length {
let randomValue = arc4random_uniform(UInt32(base.characters.count))
randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
}
return randomString
}
// MARK: - Trimming Methods
/// **Mechanica**
///
/// Removes spaces and new lines from both ends of `self.
public mutating func trim() {
self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
/// **Mechanica**
///
/// Returns a `new` String made by removing spaces and new lines from both ends.
public func trimmed() -> String {
//return trimmedLeft().trimmedRight()
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// **Mechanica**
///
/// Strips the specified characters from the beginning of `self`.
///
/// - parameter set: characters to strip
///
/// - Returns: stripped string
public func trimmedLeft(characterSet set: CharacterSet = .whitespacesAndNewlines) -> String {
if let range = rangeOfCharacter(from: set.inverted) {
return self[range.lowerBound..<endIndex]
}
return ""
}
/// **Mechanica**
///
/// Strips the specified characters from the end of `self`.
///
/// - parameter set: characters to strip
///
/// - Returns: stripped string
public func trimmedRight(characterSet set: CharacterSet = .whitespacesAndNewlines) -> String {
if let range = rangeOfCharacter(from: set.inverted, options: .backwards) {
return self[startIndex..<range.upperBound]
}
return ""
}
/// **Mechanica**
///
/// Produces a `new` string with the first character of the first word changed to the corresponding uppercase value.
public func capitalizedFirstCharacter() -> String {
guard (!self.isEmpty) else { return self }
let capitalizedFirstCharacher = String(self[startIndex]).uppercased() //capitalized
let result = capitalizedFirstCharacher + String(self.characters.dropFirst())
return result
}
/// **Mechanica**
///
/// Produces a `new` string with the first character of the first word changed to the corresponding uppercase value.
public func decapitalizedFirstCharacter() -> String {
guard (!self.isEmpty) else { return self }
let capitalizedFirstCharacher = String(self[startIndex]).lowercased()
let result = capitalizedFirstCharacher + String(self.characters.dropFirst())
return result
}
/// **Mechanica**
///
/// Returns a `new` string containing the first character of the `String`.
public var first: String {
let last = self.substring(to: self.index(after: self.startIndex))
return last
}
/// **Mechanica**
///
/// Returns a `new` string containing the last character of the `String`.
public var last: String {
let last = self.substring(from: self.index(before: self.endIndex))
return last
}
/// **Mechanica**
///
/// Returns a substring, up to maxLength in length, containing the initial elements of the `String`.
///
/// - Warning: If maxLength exceeds self.count, the result contains all the elements of self.
/// - parameter maxLength: substring max lenght
///
public func prefix(maxLength: Int) -> String {
guard maxLength > 0 else {
return ""
}
return String(self.characters.prefix(maxLength))
}
/// **Mechanica**
///
/// Returns a slice, up to maxLength in length, containing the final elements of `String`.
///
/// - Warning: If maxLength exceeds `String` character count, the result contains all the elements of `String`.
/// - parameter maxLength: substring max lenght
public func suffix(maxLength: Int) -> String {
guard maxLength > 0 else {
return ""
}
return String(self.characters.suffix(maxLength))
}
// MARK: - Remove Methods
/// **Mechanica**
///
/// Returns a new `String` containing the characters of the String from the one at a given position to the end.
///
/// - parameter upToPosition: position (included) up to which remove the prefix.
public func removingPrefix(upToPosition: Int = 1) -> String {
guard (upToPosition >= 0 && upToPosition <= self.length) else {
return ""
}
let startIndex = self.index(self.startIndex, offsetBy: upToPosition)
return self.substring(from: startIndex)
}
/// **Mechanica**
///
/// Returns a new `String` containing the characters of the String up to, but not including, the one at a given position.
///
/// - parameter fromPosition: position (included) from which remove the suffix
public func removingSuffix(fromPosition: Int = 1) -> String {
guard (fromPosition >= 0 && fromPosition <= self.length) else {
return ""
}
let startIndex = self.index(self.endIndex, offsetBy: -fromPosition)
return self.substring(to: startIndex)
}
/// **Mechanica**
///
/// Returns a new `String` removing the characters in the given set.
public func removingCharacters(in set: CharacterSet) -> String {
var chars = characters
for idx in chars.indices.reversed() {
if set.contains(String(chars[idx]).unicodeScalars.first!) {
chars.remove(at: idx)
}
}
return String(chars)
}
/// **Mechanica**
///
/// Truncates the `String` to the given length (number of characters) and appends optional trailing string if longer.
/// The default trailing is the ellipsis (…).
/// - parameter length: number of characters after which the `String` is truncated
/// - parameter trailing: optional trailing string
///
public func truncate(at length: Int, withTrailing trailing: String? = "…") -> String {
switch length {
case 0..<self.length:
//return self.substringToIndex(self.startIndex.advancedBy(length)) + (trailing ?? "")
return self.prefix(maxLength: length) + (trailing ?? "")
case _ where length >= self.length:
return self // no truncation needed
default:
return ""
}
}
// MARK: - Cleaning Methods
/// **Mechanica**
///
/// Condenses all white spaces repetitions in a single white space.
/// White space at the beginning or ending of the `String` are trimmed out.
///
/// ```
/// let aString = "test too many spaces"
/// aString.removeExcessiveSpaces //test too many spaces
/// ```
///
/// - Returns: A `new` string where all white spaces repetitions are replaced with a single white space.
public func condensingExcessiveSpaces() -> String {
let components = self.components(separatedBy: .whitespaces)
let filtered = components.filter({!$0.isEmpty})
return filtered.joined(separator: " ")
}
/// **Mechanica**
///
/// Condenses all white spaces and new lines repetitions in a single white space.
/// White space and new lines at the beginning or ending of the `String` are trimmed out.
///
/// - Returns: A `new` string where all white spaces and new lines repetitions are replaced with a single white space.
public func condensingExcessiveSpacesAndNewlines() -> String {
let components = self.components(separatedBy: .whitespacesAndNewlines)
let filtered = components.filter({!$0.isBlank})
return filtered.joined(separator: " ")
}
// MARK: Subscript Methods
/// **Mechanica**
///
/// Gets the character at the specified index as String.
///
/// - parameter index: index Position of the character to get
///
/// - Returns: Character as String or nil if the index is out of bounds
public subscript (index: Int) -> String? {
guard (0..<self.characters.count ~= index) else {
return nil
}
return String(Array(self.characters)[index])
}
/// **Mechanica**
///
/// Returns a `new` string in which the characters in a specified `CountableClosedRange` range of the String are replaced by a given string.
public func replacingCharacters(in range: CountableClosedRange<Int>, with replacement: String) -> String {
let start = characters.index(characters.startIndex, offsetBy: range.lowerBound)
let end = characters.index(start, offsetBy: range.count)
return self.replacingCharacters(in: start ..< end, with: replacement)
}
/// **Mechanica**
///
/// Returns a `new` string in which the characters in a specified `CountableRange` range of the String are replaced by a given string.
public func replacingCharacters(in range: CountableRange<Int>, with replacement: String) -> String {
let start = characters.index(characters.startIndex, offsetBy: range.lowerBound)
let end = characters.index(start, offsetBy: range.count)
return self.replacingCharacters(in: start ..< end, with: replacement)
}
/// **Mechanica**
///
/// Returns the substring in the given range.
///
/// - parameter range: range
///
/// - Returns: Substring in range or nil.
public subscript (range: Range<Int>) -> String? {
guard (0...self.self.length ~= range.lowerBound) else {
return nil
}
guard (0...self.self.length ~= range.upperBound) else {
return nil
}
let start = self.index(self.startIndex, offsetBy: range.lowerBound)
let end = self.index(self.startIndex, offsetBy: range.upperBound)
return substring(with: Range(uncheckedBounds: (lower: start, upper: end)))
}
/// **Mechanica**
///
/// Returns the substring in the given `NSRange`
///
/// - parameter range: NSRange
///
/// - Returns: Substring in range or nil.
public subscript (range: NSRange) -> String? {
let end = range.location + range.length
return self[Range(uncheckedBounds: (lower: range.location, upper: end))]
}
/// **Mechanica**
///
/// Returns the range of the first occurrence of a given string in the `String`.
///
/// - parameter substring: substring
///
/// - Returns: range of the first occurrence or nil.
public subscript (substring: String) -> Range<String.Index>? {
let range = Range(uncheckedBounds: (lower: startIndex, upper: endIndex))
return self.range(of: substring, options: .literal, range: range, locale: .current)
}
// MARK: Case Operators
/// **Mechanica**
///
/// Produces a camel cased version of the `String`.
///
/// Example:
///
/// let string = "HelloWorld"
/// print(string.decapitalized()) // "helloWorld"
///
/// - Returns: A camel cased copy of the `String`.
public func camelCased() -> String {
return pascalCased().decapitalizedFirstCharacter()
}
/// **Mechanica**
///
/// Produces the kebab cased version of the `String`.
///
/// Example:
///
/// let string = "Hello World"
/// print(string.kebabCased()) // "-Hello-World-"
///
/// - Returns: The kebab cased copy of the `String`.
public func kebabCased() -> String {
return "-" + slugCased() + "-"
}
/// **Mechanica**
///
/// Produces a pascal cased version of the `String`.
///
/// Example:
///
/// let string = "HELLO WORLD"
/// print(string.pascalCased()) // "HelloWorld"
///
/// - Returns: A pascal cased copy of the `String`.
public func pascalCased() -> String {
return self.replacingOccurrences(of: "_", with: " ").replacingOccurrences(of: "-", with: " ").components(separatedBy: .whitespaces).joined()
}
/// **Mechanica**
///
/// Produces the slug version of the `String`.
///
/// Example:
///
/// let string = "Hello World"
/// print(string.slugCased()) // "Hello-World"
///
/// - Returns: The slug copy of the `String`.
public func slugCased() -> String {
return self.replacingOccurrences(of: "_", with: " ").replacingOccurrences(of: "-", with: " ").condensingExcessiveSpaces().replacingOccurrences(of: " ", with: "-").lowercased()
}
/// **Mechanica**
///
/// Produces the snake cased version of the `String`.
///
/// Example:
///
/// let string = "hello world"
/// print(string.snakeCased())
/// // Prints "hello_world"
///
/// - Returns: The slug copy of the `String`.
public func snakeCased() -> String {
return self.replacingOccurrences(of: "_", with: " ").replacingOccurrences(of: "-", with: " ").condensingExcessiveSpaces().replacingOccurrences(of: " ", with: "_")
}
/// **Mechanica**
///
/// Produces the swap cased version of the `String`.
///
/// Example:
///
/// let string = "Hello World"
/// print(string.swapCased()) // "hELLO wORLD"
///
/// - Returns: The swap cased copy of the `String`.
public func swapCased() -> String {
return characters.map({
String($0).isLowercased ? String($0).uppercased() : String($0).lowercased()
}).joined()
}
}
|
//
// Files.swift
//
//
// Created by Tjeerd in ‘t Veen on 15/09/2021.
//
import Foundation
#if os(iOS)
import MobileCoreServices
#endif
enum FilesError: Error {
case relatedFileNotFound
case dataIsEmpty
}
/// This type handles the storage for `TUSClient`
/// It makes sure that files (that are to be uploaded) are properly stored, together with their metaData.
/// Underwater it uses `FileManager.default`.
final class Files {
let storageDirectory: URL
/// Pass a directory to store the local cache in.
/// - Parameter storageDirectory: Leave nil for the documents dir. Pass a relative path for a dir inside the documents dir. Pass an absolute path for storing files there.
init(storageDirectory: URL?) {
func removeLeadingSlash(url: URL) -> String {
if url.absoluteString.first == "/" {
return String(url.absoluteString.dropFirst())
} else {
return url.absoluteString
}
}
func removeTrailingSlash(url: URL) -> String {
if url.absoluteString.last == "/" {
return String(url.absoluteString.dropLast())
} else {
return url.absoluteString
}
}
guard let storageDirectory = storageDirectory else {
self.storageDirectory = type(of: self).documentsDirectory.appendingPathComponent("TUS")
return
}
// If a path is relative, e.g. blabla/mypath or /blabla/mypath. Then it's a folder for the documentsdir
let isRelativePath = removeTrailingSlash(url: storageDirectory) == storageDirectory.relativePath || storageDirectory.absoluteString.first == "/"
let dir = removeLeadingSlash(url: storageDirectory)
if isRelativePath {
self.storageDirectory = type(of: self).documentsDirectory.appendingPathComponent(dir)
} else {
if let url = URL(string: dir) {
self.storageDirectory = url
} else {
assertionFailure("Can't recreate URL")
self.storageDirectory = type(of: self).documentsDirectory.appendingPathComponent("TUS")
}
}
do {
try makeDirectoryIfNeeded()
} catch {
assertionFailure("Couldn't create dir \(storageDirectory). In other methods this class will try as well.")
}
}
static private var documentsDirectory: URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
}
/// Loads all metadata (decoded plist files) from the target directory.
/// - Important:Metadata assumes to be in the same directory as the file it references.
/// This means that once retrieved, this method updates the metadata's filePath to the directory that the metadata is in.
/// This happens, because theoretically the documents directory can change. Meaning that metadata's filepaths are invalid.
/// By updating the filePaths back to the metadata's filepath, we keep the metadata and its related file in sync.
/// It's a little magic, but it helps prevent strange issues.
/// - Throws: File related errors
/// - Returns: An array of UploadMetadata types
func loadAllMetadata() throws -> [UploadMetadata] {
let directoryContents = try FileManager.default.contentsOfDirectory(at: storageDirectory, includingPropertiesForKeys: nil)
// if you want to filter the directory contents you can do like this:
let files = directoryContents.filter{ $0.pathExtension == "plist" }
let decoder = PropertyListDecoder()
return files.compactMap { url in
if let data = try? Data(contentsOf: url) {
let metaData = try? decoder.decode(UploadMetadata.self, from: data)
// The documentsDirectory can change between restarts (at least during testing). So we update the filePath to match the existing plist again. To avoid getting an out of sync situation where the filePath still points to a dir in a different directory than the plist.
// (The plist and file to upload should always be in the same dir together).
metaData?.filePath = url.deletingPathExtension()
return metaData
}
// Improvement: Handle error when it can't be decoded?
return nil
}
}
/// Copy a file from location to a TUS directory, get the URL from the new location
/// - Parameter location: The location where to copy a file from
/// - Parameter id: The unique identifier for the data. Will be used as a filename.
/// - Throws: Any error related to file handling.
/// - Returns:The URL of the new location.
@discardableResult
func copy(from location: URL, id: UUID) throws -> URL {
try makeDirectoryIfNeeded()
// We don't use lastPathComponent (filename) because then you can't add the same file file.
// With a unique name, you can upload the same file twice if you want.
let fileName = id.uuidString + location.lastPathComponent
let targetLocation = storageDirectory.appendingPathComponent(fileName)
try FileManager.default.copyItem(atPath: location.path, toPath: targetLocation.path)
return targetLocation
}
/// Store data in the TUS directory, get a URL of the location
/// - Parameter data: The data to store
/// - Parameter id: The unique identifier for the data. Will be used as a filename.
/// - Throws: Any file related error (e.g. can't save)
/// - Returns: The URL of the stored file
@discardableResult
func store(data: Data, id: UUID) throws -> URL {
guard !data.isEmpty else { throw FilesError.dataIsEmpty }
try makeDirectoryIfNeeded()
let fileName = id.uuidString
let targetLocation = storageDirectory.appendingPathComponent(fileName)
try data.write(to: targetLocation)
return targetLocation
}
/// Removes metadata and its related file from disk
/// - Parameter metaData: The metadata description
/// - Throws: Any error from FileManager when removing a file.
func removeFileAndMetadata(_ metaData: UploadMetadata) throws {
let filePath = metaData.filePath
let metaDataPath = metaData.filePath.appendingPathExtension("plist")
try FileManager.default.removeItem(at: filePath)
try FileManager.default.removeItem(at: metaDataPath)
}
/// Store the metadata of a file. Will follow a convention, based on a file's url, to determine where to store it.
/// Hence no need to give it a location to store the metadata.
/// The reason to use this method is persistence between runs. E.g. Between app launches or background threads.
/// - Parameter metaData: The metadata of a file to store.
/// - Throws: Any error related to file handling
/// - Returns: The URL of the location where the metadata is stored.
@discardableResult
func encodeAndStore(metaData: UploadMetadata) throws -> URL {
guard FileManager.default.fileExists(atPath: metaData.filePath.path) else {
// Could not find the file that's related to this metadata.
throw FilesError.relatedFileNotFound
}
let targetLocation = metaData.filePath.appendingPathExtension("plist")
try makeDirectoryIfNeeded()
let encoder = PropertyListEncoder()
let encodedData = try encoder.encode(metaData)
try encodedData.write(to: targetLocation)
return targetLocation
}
/// Load metadata from store and find matching one by id
/// - Parameter id: Id to find metadata
/// - Returns: optional `UploadMetadata` type
func findMetadata(id: UUID) throws -> UploadMetadata? {
return try loadAllMetadata().first(where: { metaData in
metaData.id == id
})
}
func makeDirectoryIfNeeded() throws {
let doesExist = FileManager.default.fileExists(atPath: storageDirectory.path, isDirectory: nil)
if !doesExist {
try FileManager.default.createDirectory(at: storageDirectory, withIntermediateDirectories: true)
}
}
func clearCacheInStorageDirectory() throws {
guard FileManager.default.fileExists(atPath: storageDirectory.path, isDirectory: nil) else {
return
}
// We collect errors since we don't want to stop iterating at any error
// We try to delete whatever we can.
let metaDataFiles = try loadAllMetadata()
let errors = metaDataFiles.collectErrors { metaData in
try removeFileAndMetadata(metaData)
}
if let error = errors.first {
throw error
}
}
}
extension URL {
var mimeType: String {
let pathExtension = self.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream"
}
}
private extension Array {
/// Iterate through the array. If any error occurs, keep going. Then at the end, return an array of errors received
/// Useful if you don't want to stop iteration when an error occurs
/// - Parameter action: Anything you want to perform.
/// - Returns: An array of possible errors
func collectErrors(action: (Element) throws -> Void) -> [Error] {
var errors = [Error]()
for element in self {
do {
try action(element)
} catch {
errors.append(error)
}
}
return errors
}
}
Making Files threadsafe(r)
//
// Files.swift
//
//
// Created by Tjeerd in ‘t Veen on 15/09/2021.
//
import Foundation
#if os(iOS)
import MobileCoreServices
#endif
enum FilesError: Error {
case relatedFileNotFound
case dataIsEmpty
case unknownError
}
/// This type handles the storage for `TUSClient`
/// It makes sure that files (that are to be uploaded) are properly stored, together with their metaData.
/// Underwater it uses `FileManager.default`.
final class Files {
let storageDirectory: URL
private let queue = DispatchQueue(label: "com.tuskit.files")
/// Pass a directory to store the local cache in.
/// - Parameter storageDirectory: Leave nil for the documents dir. Pass a relative path for a dir inside the documents dir. Pass an absolute path for storing files there.
init(storageDirectory: URL?) {
func removeLeadingSlash(url: URL) -> String {
if url.absoluteString.first == "/" {
return String(url.absoluteString.dropFirst())
} else {
return url.absoluteString
}
}
func removeTrailingSlash(url: URL) -> String {
if url.absoluteString.last == "/" {
return String(url.absoluteString.dropLast())
} else {
return url.absoluteString
}
}
guard let storageDirectory = storageDirectory else {
self.storageDirectory = type(of: self).documentsDirectory.appendingPathComponent("TUS")
return
}
// If a path is relative, e.g. blabla/mypath or /blabla/mypath. Then it's a folder for the documentsdir
let isRelativePath = removeTrailingSlash(url: storageDirectory) == storageDirectory.relativePath || storageDirectory.absoluteString.first == "/"
let dir = removeLeadingSlash(url: storageDirectory)
if isRelativePath {
self.storageDirectory = type(of: self).documentsDirectory.appendingPathComponent(dir)
} else {
if let url = URL(string: dir) {
self.storageDirectory = url
} else {
assertionFailure("Can't recreate URL")
self.storageDirectory = type(of: self).documentsDirectory.appendingPathComponent("TUS")
}
}
do {
try makeDirectoryIfNeeded()
} catch {
assertionFailure("Couldn't create dir \(storageDirectory). In other methods this class will try as well.")
}
}
static private var documentsDirectory: URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
}
/// Loads all metadata (decoded plist files) from the target directory.
/// - Important:Metadata assumes to be in the same directory as the file it references.
/// This means that once retrieved, this method updates the metadata's filePath to the directory that the metadata is in.
/// This happens, because theoretically the documents directory can change. Meaning that metadata's filepaths are invalid.
/// By updating the filePaths back to the metadata's filepath, we keep the metadata and its related file in sync.
/// It's a little magic, but it helps prevent strange issues.
/// - Throws: File related errors
/// - Returns: An array of UploadMetadata types
func loadAllMetadata() throws -> [UploadMetadata] {
try queue.sync {
let directoryContents = try FileManager.default.contentsOfDirectory(at: storageDirectory, includingPropertiesForKeys: nil)
// if you want to filter the directory contents you can do like this:
let files = directoryContents.filter{ $0.pathExtension == "plist" }
let decoder = PropertyListDecoder()
let metaData: [UploadMetadata] = files.compactMap { url in
if let data = try? Data(contentsOf: url) {
let metaData = try? decoder.decode(UploadMetadata.self, from: data)
// The documentsDirectory can change between restarts (at least during testing). So we update the filePath to match the existing plist again. To avoid getting an out of sync situation where the filePath still points to a dir in a different directory than the plist.
// (The plist and file to upload should always be in the same dir together).
metaData?.filePath = url.deletingPathExtension()
return metaData
}
// Improvement: Handle error when it can't be decoded?
return nil
}
return metaData
}
}
/// Copy a file from location to a TUS directory, get the URL from the new location
/// - Parameter location: The location where to copy a file from
/// - Parameter id: The unique identifier for the data. Will be used as a filename.
/// - Throws: Any error related to file handling.
/// - Returns:The URL of the new location.
@discardableResult
func copy(from location: URL, id: UUID) throws -> URL {
try makeDirectoryIfNeeded()
// We don't use lastPathComponent (filename) because then you can't add the same file file.
// With a unique name, you can upload the same file twice if you want.
let fileName = id.uuidString + location.lastPathComponent
let targetLocation = storageDirectory.appendingPathComponent(fileName)
try FileManager.default.copyItem(atPath: location.path, toPath: targetLocation.path)
return targetLocation
}
/// Store data in the TUS directory, get a URL of the location
/// - Parameter data: The data to store
/// - Parameter id: The unique identifier for the data. Will be used as a filename.
/// - Throws: Any file related error (e.g. can't save)
/// - Returns: The URL of the stored file
@discardableResult
func store(data: Data, id: UUID) throws -> URL {
try queue.sync {
guard !data.isEmpty else { throw FilesError.dataIsEmpty }
try makeDirectoryIfNeeded()
let fileName = id.uuidString
let targetLocation = storageDirectory.appendingPathComponent(fileName)
try data.write(to: targetLocation, options: .atomic)
return targetLocation
}
}
/// Removes metadata and its related file from disk
/// - Parameter metaData: The metadata description
/// - Throws: Any error from FileManager when removing a file.
func removeFileAndMetadata(_ metaData: UploadMetadata) throws {
let filePath = metaData.filePath
let metaDataPath = metaData.filePath.appendingPathExtension("plist")
try FileManager.default.removeItem(at: filePath)
try FileManager.default.removeItem(at: metaDataPath)
}
/// Store the metadata of a file. Will follow a convention, based on a file's url, to determine where to store it.
/// Hence no need to give it a location to store the metadata.
/// The reason to use this method is persistence between runs. E.g. Between app launches or background threads.
/// - Parameter metaData: The metadata of a file to store.
/// - Throws: Any error related to file handling
/// - Returns: The URL of the location where the metadata is stored.
@discardableResult
func encodeAndStore(metaData: UploadMetadata) throws -> URL {
try queue.sync {
guard FileManager.default.fileExists(atPath: metaData.filePath.path) else {
// Could not find the file that's related to this metadata.
throw FilesError.relatedFileNotFound
}
let targetLocation = metaData.filePath.appendingPathExtension("plist")
try self.makeDirectoryIfNeeded()
let encoder = PropertyListEncoder()
let encodedData = try encoder.encode(metaData)
try encodedData.write(to: targetLocation, options: .atomic)
return targetLocation
}
}
/// Load metadata from store and find matching one by id
/// - Parameter id: Id to find metadata
/// - Returns: optional `UploadMetadata` type
func findMetadata(id: UUID) throws -> UploadMetadata? {
return try loadAllMetadata().first(where: { metaData in
metaData.id == id
})
}
func makeDirectoryIfNeeded() throws {
let doesExist = FileManager.default.fileExists(atPath: storageDirectory.path, isDirectory: nil)
if !doesExist {
try FileManager.default.createDirectory(at: storageDirectory, withIntermediateDirectories: true)
}
}
func clearCacheInStorageDirectory() throws {
guard FileManager.default.fileExists(atPath: storageDirectory.path, isDirectory: nil) else {
return
}
// We collect errors since we don't want to stop iterating at any error
// We try to delete whatever we can.
let metaDataFiles = try loadAllMetadata()
let errors = metaDataFiles.collectErrors { metaData in
try removeFileAndMetadata(metaData)
}
if let error = errors.first {
throw error
}
}
}
extension URL {
var mimeType: String {
let pathExtension = self.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream"
}
}
private extension Array {
/// Iterate through the array. If any error occurs, keep going. Then at the end, return an array of errors received
/// Useful if you don't want to stop iteration when an error occurs
/// - Parameter action: Anything you want to perform.
/// - Returns: An array of possible errors
func collectErrors(action: (Element) throws -> Void) -> [Error] {
var errors = [Error]()
for element in self {
do {
try action(element)
} catch {
errors.append(error)
}
}
return errors
}
}
|
import UIKit
@objc(JetPack_ImageView)
public /* non-final */ class ImageView: View {
public typealias Session = _ImageViewSession
public typealias SessionListener = _ImageViewSessionListener
public typealias Source = _ImageViewSource
private var activityIndicatorIsVisible = false
private var imageLayer = ImageLayer()
private var isLayouting = false
private var isSettingImage = false
private var isSettingImageFromSource = false
private var isSettingSource = false
private var isSettingSourceFromImage = false
private var lastAppliedTintColor: UIColor?
private var lastLayoutedSize = CGSize()
private var sourceImageRetrievalCompleted = false
private var sourceSession: Session?
private var sourceSessionConfigurationIsValid = true
private var tintedImage: UIImage?
public var imageChanged: Closure?
public override init() {
super.init()
userInteractionEnabled = false
layer.addSublayer(imageLayer)
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
}
deinit {
sourceSession?.stopRetrievingImage()
}
private var _activityIndicator: UIActivityIndicatorView?
public final var activityIndicator: UIActivityIndicatorView {
return _activityIndicator ?? {
let child = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
child.hidesWhenStopped = false
child.alpha = 0
child.startAnimating()
_activityIndicator = child
return child
}()
}
private var activityIndicatorShouldBeVisible: Bool {
guard showsActivityIndicatorWhileLoading else {
return false
}
guard source != nil && !sourceImageRetrievalCompleted else {
return false
}
return true
}
private func computeImageLayerFrame() -> CGRect {
guard let image = image else {
return .zero
}
let imageSize = image.size
let maximumImageLayerFrame = CGRect(size: bounds.size).insetBy(padding)
guard imageSize.isPositive && maximumImageLayerFrame.size.isPositive else {
return .zero
}
let gravity = self.gravity
let scaling = self.scaling
var imageLayerFrame = CGRect()
switch scaling {
case .FitIgnoringAspectRatio:
imageLayerFrame.size = maximumImageLayerFrame.size
case .FitInside, .FitOutside:
let horizontalScale = maximumImageLayerFrame.width / imageSize.width
let verticalScale = maximumImageLayerFrame.height / imageSize.height
let scale = (scaling == .FitInside ? min : max)(horizontalScale, verticalScale)
imageLayerFrame.size = imageSize.scaleBy(scale)
case .FitHorizontally:
imageLayerFrame.width = maximumImageLayerFrame.width
imageLayerFrame.height = imageSize.height * (imageLayerFrame.width / imageSize.width)
case .FitHorizontallyIgnoringAspectRatio:
imageLayerFrame.width = maximumImageLayerFrame.width
imageLayerFrame.height = imageSize.height
case .FitVertically:
imageLayerFrame.height = maximumImageLayerFrame.height
imageLayerFrame.width = imageSize.width * (imageLayerFrame.height / imageSize.height)
case .FitVerticallyIgnoringAspectRatio:
imageLayerFrame.height = maximumImageLayerFrame.height
imageLayerFrame.width = imageSize.width
case .None:
imageLayerFrame.size = imageSize
}
switch gravity.horizontal {
case .Left:
imageLayerFrame.left = maximumImageLayerFrame.left
case .Center:
imageLayerFrame.horizontalCenter = maximumImageLayerFrame.horizontalCenter
case .Right:
imageLayerFrame.right = maximumImageLayerFrame.right
}
switch gravity.vertical {
case .Top:
imageLayerFrame.top = maximumImageLayerFrame.top
case .Center:
imageLayerFrame.verticalCenter = maximumImageLayerFrame.verticalCenter
case .Bottom:
imageLayerFrame.bottom = maximumImageLayerFrame.bottom
}
switch image.imageOrientation {
case .Left, .LeftMirrored, .Right, .RightMirrored:
let center = imageLayerFrame.center
swap(&imageLayerFrame.width, &imageLayerFrame.height)
imageLayerFrame.center = center
case .Down, .DownMirrored, .Up, .UpMirrored:
break
}
imageLayerFrame = alignToGrid(imageLayerFrame)
return imageLayerFrame
}
private func computeImageLayerTransform() -> CGAffineTransform {
guard let image = image else {
return CGAffineTransformIdentity
}
// TODO support mirrored variants
let transform: CGAffineTransform
switch image.imageOrientation {
case .Down: transform = CGAffineTransformMakeRotation(.Pi)
case .DownMirrored: transform = CGAffineTransformMakeRotation(.Pi)
case .Left: transform = CGAffineTransformMakeRotation(-.Pi / 2)
case .LeftMirrored: transform = CGAffineTransformMakeRotation(-.Pi / 2)
case .Right: transform = CGAffineTransformMakeRotation(.Pi / 2)
case .RightMirrored: transform = CGAffineTransformMakeRotation(.Pi / 2)
case .Up: transform = CGAffineTransformIdentity
case .UpMirrored: transform = CGAffineTransformIdentity
}
return transform
}
@available(*, unavailable, message="Use .gravity and .scaling instead.")
public final override var contentMode: UIViewContentMode {
get { return super.contentMode }
set { super.contentMode = newValue }
}
public override func didMoveToWindow() {
super.didMoveToWindow()
if window != nil {
setNeedsLayout()
}
}
public var gravity = Gravity.Center {
didSet {
guard gravity != oldValue else {
return
}
setNeedsLayout()
invalidateConfiguration()
}
}
public var image: UIImage? {
didSet {
precondition(!isSettingImage, "Cannot recursively set ImageView's 'image'.")
precondition(!isSettingSource || isSettingImageFromSource, "Cannot recursively set ImageView's 'image' and 'source'.")
isSettingImage = true
defer { isSettingImage = false }
if image == oldValue {
return
}
if !isSettingImageFromSource {
isSettingSourceFromImage = true
source = nil
isSettingSourceFromImage = false
}
lastAppliedTintColor = nil
setNeedsLayout()
if (image?.size ?? .zero) != (oldValue?.size ?? .zero) {
invalidateIntrinsicContentSize()
}
updateActivityIndicatorAnimated(true)
}
}
public override func intrinsicContentSize() -> CGSize {
return sizeThatFits()
}
private func invalidateConfiguration() {
guard sourceSessionConfigurationIsValid else {
return
}
sourceSessionConfigurationIsValid = false
setNeedsLayout()
}
public override func layoutSubviews() {
isLayouting = true
defer { isLayouting = false }
super.layoutSubviews()
let bounds = self.bounds
if bounds.size != lastLayoutedSize {
lastLayoutedSize = bounds.size
sourceSessionConfigurationIsValid = false
}
if let activityIndicator = _activityIndicator {
activityIndicator.center = bounds.insetBy(padding).center
}
let imageLayerFrame = computeImageLayerFrame()
imageLayer.bounds = CGRect(size: imageLayerFrame.size)
imageLayer.position = imageLayerFrame.center
if let image = image where image.renderingMode == .AlwaysTemplate {
if tintColor != lastAppliedTintColor {
lastAppliedTintColor = tintColor
tintedImage = image.imageWithColor(tintColor)
}
}
else {
tintedImage = nil
}
if let contentImage = tintedImage ?? image {
imageLayer.contents = contentImage.CGImage
imageLayer.transform = CATransform3DMakeAffineTransform(computeImageLayerTransform())
}
else {
imageLayer.contents = nil
imageLayer.transform = CATransform3DIdentity
}
startOrUpdateSourceSession()
}
public var optimalImageSize: CGSize {
let size = bounds.size.insetBy(padding).scaleBy(gridScaleFactor)
guard size.width > 0 && size.height > 0 else {
return .zero
}
return size
}
public var padding = UIEdgeInsets() {
didSet {
if padding == oldValue {
return
}
setNeedsLayout()
invalidateConfiguration()
invalidateIntrinsicContentSize()
}
}
public var preferredSize: CGSize? {
didSet {
guard preferredSize != oldValue else {
return
}
invalidateConfiguration()
invalidateIntrinsicContentSize()
}
}
public var scaling = Scaling.FitInside {
didSet {
guard scaling != oldValue else {
return
}
setNeedsLayout()
invalidateConfiguration()
}
}
public var showsActivityIndicatorWhileLoading = true {
didSet {
guard showsActivityIndicatorWhileLoading != oldValue else {
return
}
updateActivityIndicatorAnimated(true)
}
}
public override func sizeThatFitsSize(maximumSize: CGSize) -> CGSize {
if let preferredSize = preferredSize {
return alignToGrid(preferredSize)
}
let imageSizeThatFits: CGSize
let availableSize = maximumSize.insetBy(padding)
if availableSize.isPositive, let imageSize = image?.size where imageSize.isPositive {
let imageRatio = imageSize.width / imageSize.height
switch scaling {
case .FitHorizontally,
.FitHorizontallyIgnoringAspectRatio:
imageSizeThatFits = CGSize(
width: availableSize.width,
height: availableSize.width / imageRatio
)
case .FitVertically,
.FitVerticallyIgnoringAspectRatio:
imageSizeThatFits = CGSize(
width: availableSize.height * imageRatio,
height: availableSize.height
)
case .FitIgnoringAspectRatio,
.FitInside,
.FitOutside,
.None:
imageSizeThatFits = imageSize
}
}
else {
imageSizeThatFits = .zero
}
return alignToGrid(CGSize(
width: imageSizeThatFits.width + padding.left + padding.right,
height: imageSizeThatFits.height + padding.top + padding.bottom
))
}
public var source: Source? {
didSet {
precondition(!isSettingSource, "Cannot recursively set ImageView's 'source'.")
precondition(!isSettingSource || isSettingSourceFromImage, "Cannot recursively set ImageView's 'source' and 'image'.")
if let source = source, oldSource = oldValue where source.equals(oldSource) {
if sourceImageRetrievalCompleted && image == nil {
stopSourceSession()
startOrUpdateSourceSession()
updateActivityIndicatorAnimated(true)
}
return
}
if source == nil && oldValue == nil {
return
}
isSettingSource = true
defer {
isSettingSource = false
}
stopSourceSession()
if !isSettingSourceFromImage {
isSettingImageFromSource = true
image = nil
isSettingImageFromSource = false
}
if source != nil {
sourceSessionConfigurationIsValid = false
startOrUpdateSourceSession()
}
updateActivityIndicatorAnimated(true)
}
}
private func startOrUpdateSourceSession() {
guard !sourceSessionConfigurationIsValid && window != nil && (isLayouting || !needsLayout), let source = source else {
return
}
let optimalImageSize = self.optimalImageSize
guard !optimalImageSize.isEmpty else {
return
}
sourceSessionConfigurationIsValid = true
if let sourceSession = sourceSession {
sourceSession.imageViewDidChangeConfiguration(self)
}
else {
if let sourceSession = source.createSession() {
let listener = ClosureSessionListener { [weak self] image in
precondition(NSThread.isMainThread(), "ImageView.SessionListener.sessionDidRetrieveImage(_:) must be called on the main thread.")
guard let imageView = self else {
return
}
if sourceSession !== imageView.sourceSession {
log("ImageView.SessionListener.sessionDidRetrieveImage(_:) was called after session was stopped. The call will be ignored.")
return
}
if imageView.isSettingImageFromSource {
log("ImageView.SessionListener.sessionDidRetrieveImage(_:) was called from within an 'image' property observer. The call will be ignored.")
return
}
imageView.sourceImageRetrievalCompleted = true
imageView.isSettingImageFromSource = true
imageView.image = image
imageView.isSettingImageFromSource = false
imageView.updateActivityIndicatorAnimated(true)
imageView.imageChanged?()
}
self.sourceSession = sourceSession
sourceSession.startRetrievingImageForImageView(self, listener: listener)
}
else if let image = source.staticImage {
sourceImageRetrievalCompleted = true
isSettingImageFromSource = true
self.image = image
isSettingImageFromSource = false
updateActivityIndicatorAnimated(true)
}
}
}
private func stopSourceSession() {
guard let sourceSession = sourceSession else {
return
}
sourceImageRetrievalCompleted = false
self.sourceSession = nil
sourceSession.stopRetrievingImage()
}
public override func tintColorDidChange() {
super.tintColorDidChange()
setNeedsLayout()
}
private func updateActivityIndicatorAnimated(animated: Bool) {
if activityIndicatorShouldBeVisible {
guard !activityIndicatorIsVisible else {
return
}
let activityIndicator = self.activityIndicator
activityIndicatorIsVisible = true
addSubview(activityIndicator)
Animation.run(animated ? Animation() : nil) {
activityIndicator.alpha = 1
}
}
else {
guard activityIndicatorIsVisible, let activityIndicator = _activityIndicator else {
return
}
activityIndicatorIsVisible = false
Animation.runWithCompletion(animated ? Animation() : nil) { complete in
activityIndicator.alpha = 0
complete { _ in
if !self.activityIndicatorIsVisible {
activityIndicator.removeFromSuperview()
}
}
}
}
}
public enum Gravity {
case BottomCenter
case BottomLeft
case BottomRight
case Center
case CenterLeft
case CenterRight
case TopCenter
case TopLeft
case TopRight
public init(horizontal: Horizontal, vertical: Vertical) {
switch vertical {
case .Bottom:
switch horizontal {
case .Left: self = .BottomLeft
case .Center: self = .BottomCenter
case .Right: self = .BottomRight
}
case .Center:
switch horizontal {
case .Left: self = .CenterLeft
case .Center: self = .Center
case .Right: self = .CenterRight
}
case .Top:
switch horizontal {
case .Left: self = .TopLeft
case .Center: self = .TopCenter
case .Right: self = .TopRight
}
}
}
public var horizontal: Horizontal {
switch self {
case .BottomLeft, .CenterLeft, .TopLeft:
return .Left
case .BottomCenter, .Center, .TopCenter:
return .Center
case .BottomRight, .CenterRight, .TopRight:
return .Right
}
}
public var vertical: Vertical {
switch self {
case .BottomCenter, .BottomLeft, .BottomRight:
return .Bottom
case .Center, .CenterLeft, .CenterRight:
return .Center
case .TopCenter, .TopLeft, .TopRight:
return .Top
}
}
public enum Horizontal {
case Center
case Left
case Right
}
public enum Vertical {
case Bottom
case Center
case Top
}
}
public enum Scaling {
case FitHorizontally
case FitHorizontallyIgnoringAspectRatio
case FitIgnoringAspectRatio
case FitInside
case FitOutside
case FitVertically
case FitVerticallyIgnoringAspectRatio
case None
}
}
public protocol _ImageViewSession: class {
func imageViewDidChangeConfiguration (imageView: ImageView)
func startRetrievingImageForImageView (imageView: ImageView, listener: ImageView.SessionListener)
func stopRetrievingImage ()
}
public protocol _ImageViewSessionListener {
func sessionDidFailToRetrieveImageWithFailure (failure: Failure)
func sessionDidRetrieveImage (image: UIImage)
}
public protocol _ImageViewSource {
var staticImage: UIImage? { get }
func createSession () -> ImageView.Session?
func equals (source: ImageView.Source) -> Bool
}
extension _ImageViewSource where Self: Equatable {
public func equals(source: ImageView.Source) -> Bool {
guard let source = source as? Self else {
return false
}
return self == source
}
}
private struct ClosureSessionListener: ImageView.SessionListener {
private let didRetrieveImage: UIImage -> Void
private init(didRetrieveImage: UIImage -> Void) {
self.didRetrieveImage = didRetrieveImage
}
private func sessionDidFailToRetrieveImageWithFailure(failure: Failure) {
// TODO support this case
}
private func sessionDidRetrieveImage(image: UIImage) {
didRetrieveImage(image)
}
}
private final class ImageLayer: Layer {
private override func actionForKey(event: String) -> CAAction? {
return nil
}
}
Fixed that setting imageView.image to nil sometimes didn't unset the source
import UIKit
@objc(JetPack_ImageView)
public /* non-final */ class ImageView: View {
public typealias Session = _ImageViewSession
public typealias SessionListener = _ImageViewSessionListener
public typealias Source = _ImageViewSource
private var activityIndicatorIsVisible = false
private var imageLayer = ImageLayer()
private var isLayouting = false
private var isSettingImage = false
private var isSettingImageFromSource = false
private var isSettingSource = false
private var isSettingSourceFromImage = false
private var lastAppliedTintColor: UIColor?
private var lastLayoutedSize = CGSize()
private var sourceImageRetrievalCompleted = false
private var sourceSession: Session?
private var sourceSessionConfigurationIsValid = true
private var tintedImage: UIImage?
public var imageChanged: Closure?
public override init() {
super.init()
userInteractionEnabled = false
layer.addSublayer(imageLayer)
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
}
deinit {
sourceSession?.stopRetrievingImage()
}
private var _activityIndicator: UIActivityIndicatorView?
public final var activityIndicator: UIActivityIndicatorView {
return _activityIndicator ?? {
let child = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
child.hidesWhenStopped = false
child.alpha = 0
child.startAnimating()
_activityIndicator = child
return child
}()
}
private var activityIndicatorShouldBeVisible: Bool {
guard showsActivityIndicatorWhileLoading else {
return false
}
guard source != nil && !sourceImageRetrievalCompleted else {
return false
}
return true
}
private func computeImageLayerFrame() -> CGRect {
guard let image = image else {
return .zero
}
let imageSize = image.size
let maximumImageLayerFrame = CGRect(size: bounds.size).insetBy(padding)
guard imageSize.isPositive && maximumImageLayerFrame.size.isPositive else {
return .zero
}
let gravity = self.gravity
let scaling = self.scaling
var imageLayerFrame = CGRect()
switch scaling {
case .FitIgnoringAspectRatio:
imageLayerFrame.size = maximumImageLayerFrame.size
case .FitInside, .FitOutside:
let horizontalScale = maximumImageLayerFrame.width / imageSize.width
let verticalScale = maximumImageLayerFrame.height / imageSize.height
let scale = (scaling == .FitInside ? min : max)(horizontalScale, verticalScale)
imageLayerFrame.size = imageSize.scaleBy(scale)
case .FitHorizontally:
imageLayerFrame.width = maximumImageLayerFrame.width
imageLayerFrame.height = imageSize.height * (imageLayerFrame.width / imageSize.width)
case .FitHorizontallyIgnoringAspectRatio:
imageLayerFrame.width = maximumImageLayerFrame.width
imageLayerFrame.height = imageSize.height
case .FitVertically:
imageLayerFrame.height = maximumImageLayerFrame.height
imageLayerFrame.width = imageSize.width * (imageLayerFrame.height / imageSize.height)
case .FitVerticallyIgnoringAspectRatio:
imageLayerFrame.height = maximumImageLayerFrame.height
imageLayerFrame.width = imageSize.width
case .None:
imageLayerFrame.size = imageSize
}
switch gravity.horizontal {
case .Left:
imageLayerFrame.left = maximumImageLayerFrame.left
case .Center:
imageLayerFrame.horizontalCenter = maximumImageLayerFrame.horizontalCenter
case .Right:
imageLayerFrame.right = maximumImageLayerFrame.right
}
switch gravity.vertical {
case .Top:
imageLayerFrame.top = maximumImageLayerFrame.top
case .Center:
imageLayerFrame.verticalCenter = maximumImageLayerFrame.verticalCenter
case .Bottom:
imageLayerFrame.bottom = maximumImageLayerFrame.bottom
}
switch image.imageOrientation {
case .Left, .LeftMirrored, .Right, .RightMirrored:
let center = imageLayerFrame.center
swap(&imageLayerFrame.width, &imageLayerFrame.height)
imageLayerFrame.center = center
case .Down, .DownMirrored, .Up, .UpMirrored:
break
}
imageLayerFrame = alignToGrid(imageLayerFrame)
return imageLayerFrame
}
private func computeImageLayerTransform() -> CGAffineTransform {
guard let image = image else {
return CGAffineTransformIdentity
}
// TODO support mirrored variants
let transform: CGAffineTransform
switch image.imageOrientation {
case .Down: transform = CGAffineTransformMakeRotation(.Pi)
case .DownMirrored: transform = CGAffineTransformMakeRotation(.Pi)
case .Left: transform = CGAffineTransformMakeRotation(-.Pi / 2)
case .LeftMirrored: transform = CGAffineTransformMakeRotation(-.Pi / 2)
case .Right: transform = CGAffineTransformMakeRotation(.Pi / 2)
case .RightMirrored: transform = CGAffineTransformMakeRotation(.Pi / 2)
case .Up: transform = CGAffineTransformIdentity
case .UpMirrored: transform = CGAffineTransformIdentity
}
return transform
}
@available(*, unavailable, message="Use .gravity and .scaling instead.")
public final override var contentMode: UIViewContentMode {
get { return super.contentMode }
set { super.contentMode = newValue }
}
public override func didMoveToWindow() {
super.didMoveToWindow()
if window != nil {
setNeedsLayout()
}
}
public var gravity = Gravity.Center {
didSet {
guard gravity != oldValue else {
return
}
setNeedsLayout()
invalidateConfiguration()
}
}
public var image: UIImage? {
didSet {
precondition(!isSettingImage, "Cannot recursively set ImageView's 'image'.")
precondition(!isSettingSource || isSettingImageFromSource, "Cannot recursively set ImageView's 'image' and 'source'.")
isSettingImage = true
defer { isSettingImage = false }
guard image != oldValue || (oldValue == nil && source != nil) else { // TODO what if the current image is set again manually? source should be unset?
return
}
if !isSettingImageFromSource {
isSettingSourceFromImage = true
source = nil
isSettingSourceFromImage = false
}
lastAppliedTintColor = nil
setNeedsLayout()
if (image?.size ?? .zero) != (oldValue?.size ?? .zero) {
invalidateIntrinsicContentSize()
}
updateActivityIndicatorAnimated(true)
}
}
public override func intrinsicContentSize() -> CGSize {
return sizeThatFits()
}
private func invalidateConfiguration() {
guard sourceSessionConfigurationIsValid else {
return
}
sourceSessionConfigurationIsValid = false
setNeedsLayout()
}
public override func layoutSubviews() {
isLayouting = true
defer { isLayouting = false }
super.layoutSubviews()
let bounds = self.bounds
if bounds.size != lastLayoutedSize {
lastLayoutedSize = bounds.size
sourceSessionConfigurationIsValid = false
}
if let activityIndicator = _activityIndicator {
activityIndicator.center = bounds.insetBy(padding).center
}
let imageLayerFrame = computeImageLayerFrame()
imageLayer.bounds = CGRect(size: imageLayerFrame.size)
imageLayer.position = imageLayerFrame.center
if let image = image where image.renderingMode == .AlwaysTemplate {
if tintColor != lastAppliedTintColor {
lastAppliedTintColor = tintColor
tintedImage = image.imageWithColor(tintColor)
}
}
else {
tintedImage = nil
}
if let contentImage = tintedImage ?? image {
imageLayer.contents = contentImage.CGImage
imageLayer.transform = CATransform3DMakeAffineTransform(computeImageLayerTransform())
}
else {
imageLayer.contents = nil
imageLayer.transform = CATransform3DIdentity
}
startOrUpdateSourceSession()
}
public var optimalImageSize: CGSize {
let size = bounds.size.insetBy(padding).scaleBy(gridScaleFactor)
guard size.width > 0 && size.height > 0 else {
return .zero
}
return size
}
public var padding = UIEdgeInsets() {
didSet {
if padding == oldValue {
return
}
setNeedsLayout()
invalidateConfiguration()
invalidateIntrinsicContentSize()
}
}
public var preferredSize: CGSize? {
didSet {
guard preferredSize != oldValue else {
return
}
invalidateConfiguration()
invalidateIntrinsicContentSize()
}
}
public var scaling = Scaling.FitInside {
didSet {
guard scaling != oldValue else {
return
}
setNeedsLayout()
invalidateConfiguration()
}
}
public var showsActivityIndicatorWhileLoading = true {
didSet {
guard showsActivityIndicatorWhileLoading != oldValue else {
return
}
updateActivityIndicatorAnimated(true)
}
}
public override func sizeThatFitsSize(maximumSize: CGSize) -> CGSize {
if let preferredSize = preferredSize {
return alignToGrid(preferredSize)
}
let imageSizeThatFits: CGSize
let availableSize = maximumSize.insetBy(padding)
if availableSize.isPositive, let imageSize = image?.size where imageSize.isPositive {
let imageRatio = imageSize.width / imageSize.height
switch scaling {
case .FitHorizontally,
.FitHorizontallyIgnoringAspectRatio:
imageSizeThatFits = CGSize(
width: availableSize.width,
height: availableSize.width / imageRatio
)
case .FitVertically,
.FitVerticallyIgnoringAspectRatio:
imageSizeThatFits = CGSize(
width: availableSize.height * imageRatio,
height: availableSize.height
)
case .FitIgnoringAspectRatio,
.FitInside,
.FitOutside,
.None:
imageSizeThatFits = imageSize
}
}
else {
imageSizeThatFits = .zero
}
return alignToGrid(CGSize(
width: imageSizeThatFits.width + padding.left + padding.right,
height: imageSizeThatFits.height + padding.top + padding.bottom
))
}
public var source: Source? {
didSet {
precondition(!isSettingSource, "Cannot recursively set ImageView's 'source'.")
precondition(!isSettingSource || isSettingSourceFromImage, "Cannot recursively set ImageView's 'source' and 'image'.")
if let source = source, oldSource = oldValue where source.equals(oldSource) {
if sourceImageRetrievalCompleted && image == nil {
stopSourceSession()
startOrUpdateSourceSession()
updateActivityIndicatorAnimated(true)
}
return
}
if source == nil && oldValue == nil {
return
}
isSettingSource = true
defer {
isSettingSource = false
}
stopSourceSession()
if !isSettingSourceFromImage {
isSettingImageFromSource = true
image = nil
isSettingImageFromSource = false
}
if source != nil {
sourceSessionConfigurationIsValid = false
startOrUpdateSourceSession()
}
updateActivityIndicatorAnimated(true)
}
}
private func startOrUpdateSourceSession() {
guard !sourceSessionConfigurationIsValid && window != nil && (isLayouting || !needsLayout), let source = source else {
return
}
let optimalImageSize = self.optimalImageSize
guard !optimalImageSize.isEmpty else {
return
}
sourceSessionConfigurationIsValid = true
if let sourceSession = sourceSession {
sourceSession.imageViewDidChangeConfiguration(self)
}
else {
if let sourceSession = source.createSession() {
let listener = ClosureSessionListener { [weak self] image in
precondition(NSThread.isMainThread(), "ImageView.SessionListener.sessionDidRetrieveImage(_:) must be called on the main thread.")
guard let imageView = self else {
return
}
if sourceSession !== imageView.sourceSession {
log("ImageView.SessionListener.sessionDidRetrieveImage(_:) was called after session was stopped. The call will be ignored.")
return
}
if imageView.isSettingImageFromSource {
log("ImageView.SessionListener.sessionDidRetrieveImage(_:) was called from within an 'image' property observer. The call will be ignored.")
return
}
imageView.sourceImageRetrievalCompleted = true
imageView.isSettingImageFromSource = true
imageView.image = image
imageView.isSettingImageFromSource = false
imageView.updateActivityIndicatorAnimated(true)
imageView.imageChanged?()
}
self.sourceSession = sourceSession
sourceSession.startRetrievingImageForImageView(self, listener: listener)
}
else if let image = source.staticImage {
sourceImageRetrievalCompleted = true
isSettingImageFromSource = true
self.image = image
isSettingImageFromSource = false
updateActivityIndicatorAnimated(true)
}
}
}
private func stopSourceSession() {
guard let sourceSession = sourceSession else {
return
}
sourceImageRetrievalCompleted = false
self.sourceSession = nil
sourceSession.stopRetrievingImage()
}
public override func tintColorDidChange() {
super.tintColorDidChange()
setNeedsLayout()
}
private func updateActivityIndicatorAnimated(animated: Bool) {
if activityIndicatorShouldBeVisible {
guard !activityIndicatorIsVisible else {
return
}
let activityIndicator = self.activityIndicator
activityIndicatorIsVisible = true
addSubview(activityIndicator)
Animation.run(animated ? Animation() : nil) {
activityIndicator.alpha = 1
}
}
else {
guard activityIndicatorIsVisible, let activityIndicator = _activityIndicator else {
return
}
activityIndicatorIsVisible = false
Animation.runWithCompletion(animated ? Animation() : nil) { complete in
activityIndicator.alpha = 0
complete { _ in
if !self.activityIndicatorIsVisible {
activityIndicator.removeFromSuperview()
}
}
}
}
}
public enum Gravity {
case BottomCenter
case BottomLeft
case BottomRight
case Center
case CenterLeft
case CenterRight
case TopCenter
case TopLeft
case TopRight
public init(horizontal: Horizontal, vertical: Vertical) {
switch vertical {
case .Bottom:
switch horizontal {
case .Left: self = .BottomLeft
case .Center: self = .BottomCenter
case .Right: self = .BottomRight
}
case .Center:
switch horizontal {
case .Left: self = .CenterLeft
case .Center: self = .Center
case .Right: self = .CenterRight
}
case .Top:
switch horizontal {
case .Left: self = .TopLeft
case .Center: self = .TopCenter
case .Right: self = .TopRight
}
}
}
public var horizontal: Horizontal {
switch self {
case .BottomLeft, .CenterLeft, .TopLeft:
return .Left
case .BottomCenter, .Center, .TopCenter:
return .Center
case .BottomRight, .CenterRight, .TopRight:
return .Right
}
}
public var vertical: Vertical {
switch self {
case .BottomCenter, .BottomLeft, .BottomRight:
return .Bottom
case .Center, .CenterLeft, .CenterRight:
return .Center
case .TopCenter, .TopLeft, .TopRight:
return .Top
}
}
public enum Horizontal {
case Center
case Left
case Right
}
public enum Vertical {
case Bottom
case Center
case Top
}
}
public enum Scaling {
case FitHorizontally
case FitHorizontallyIgnoringAspectRatio
case FitIgnoringAspectRatio
case FitInside
case FitOutside
case FitVertically
case FitVerticallyIgnoringAspectRatio
case None
}
}
public protocol _ImageViewSession: class {
func imageViewDidChangeConfiguration (imageView: ImageView)
func startRetrievingImageForImageView (imageView: ImageView, listener: ImageView.SessionListener)
func stopRetrievingImage ()
}
public protocol _ImageViewSessionListener {
func sessionDidFailToRetrieveImageWithFailure (failure: Failure)
func sessionDidRetrieveImage (image: UIImage)
}
public protocol _ImageViewSource {
var staticImage: UIImage? { get }
func createSession () -> ImageView.Session?
func equals (source: ImageView.Source) -> Bool
}
extension _ImageViewSource where Self: Equatable {
public func equals(source: ImageView.Source) -> Bool {
guard let source = source as? Self else {
return false
}
return self == source
}
}
private struct ClosureSessionListener: ImageView.SessionListener {
private let didRetrieveImage: UIImage -> Void
private init(didRetrieveImage: UIImage -> Void) {
self.didRetrieveImage = didRetrieveImage
}
private func sessionDidFailToRetrieveImageWithFailure(failure: Failure) {
// TODO support this case
}
private func sessionDidRetrieveImage(image: UIImage) {
didRetrieveImage(image)
}
}
private final class ImageLayer: Layer {
private override func actionForKey(event: String) -> CAAction? {
return nil
}
}
|
//
// Emitter.swift
// Yams
//
// Created by Norio Nomura on 12/28/16.
// Copyright (c) 2016 Yams. All rights reserved.
//
#if SWIFT_PACKAGE
import CYaml
#endif
import Foundation
public func dump<S>(
objects: S,
canonical: Bool = false,
indent: Int = 0,
width: Int = 0,
allowUnicode: Bool = false,
lineBreak: Emitter.LineBreak = .ln,
explicitStart: Bool = false,
explicitEnd: Bool = false,
version: (major: Int, minor: Int)? = nil) throws -> String
where S: Sequence, S.Iterator.Element: NodeRepresentable {
return try serialize(
nodes: objects.map { try $0.represented() },
canonical: canonical,
indent: indent,
width: width,
allowUnicode: allowUnicode,
lineBreak: lineBreak,
explicitStart: explicitStart,
explicitEnd: explicitEnd,
version: version)
}
public func dump<Object>(
object: Object,
canonical: Bool = false,
indent: Int = 0,
width: Int = 0,
allowUnicode: Bool = false,
lineBreak: Emitter.LineBreak = .ln,
explicitStart: Bool = false,
explicitEnd: Bool = false,
version: (major: Int, minor: Int)? = nil) throws -> String
where Object: NodeRepresentable {
return try dump(
objects: [object],
canonical: canonical,
indent: indent,
width: width,
allowUnicode: allowUnicode,
lineBreak: lineBreak,
explicitStart: explicitStart,
explicitEnd: explicitEnd,
version: version)
}
public func serialize<S>(
nodes: S,
canonical: Bool = false,
indent: Int = 0,
width: Int = 0,
allowUnicode: Bool = false,
lineBreak: Emitter.LineBreak = .ln,
explicitStart: Bool = false,
explicitEnd: Bool = false,
version: (major: Int, minor: Int)? = nil) throws -> String
where S: Sequence, S.Iterator.Element == Node {
let emitter = Emitter(
canonical: canonical,
indent: indent,
width: width,
allowUnicode: allowUnicode,
lineBreak: lineBreak,
explicitStart: explicitStart,
explicitEnd: explicitEnd,
version: version)
try emitter.open()
try nodes.forEach(emitter.serialize)
try emitter.close()
#if USE_UTF16
return String(data: emitter.data, encoding: .utf16)!
#else
return String(data: emitter.data, encoding: .utf8)!
#endif
}
public func serialize(
node: Node,
canonical: Bool = false,
indent: Int = 0,
width: Int = 0,
allowUnicode: Bool = false,
lineBreak: Emitter.LineBreak = .ln,
explicitStart: Bool = false,
explicitEnd: Bool = false,
version: (major: Int, minor: Int)? = nil) throws -> String {
return try serialize(
nodes: [node],
canonical: canonical,
indent: indent,
width: width,
allowUnicode: allowUnicode,
lineBreak: lineBreak,
explicitStart: explicitStart,
explicitEnd: explicitEnd,
version: version)
}
public enum EmitterError: Swift.Error {
case invalidState(String)
}
public final class Emitter {
public enum LineBreak {
/// Use CR for line breaks (Mac style).
case cr
/// Use LN for line breaks (Unix style).
case ln
/// Use CR LN for line breaks (DOS style).
case crln
}
public var data = Data()
let documentStartImplicit: Int32
let documentEndImplicit: Int32
let version: (major: Int, minor: Int)?
public init(canonical: Bool = false,
indent: Int = 0,
width: Int = 0,
allowUnicode: Bool = false,
lineBreak: LineBreak = .ln,
explicitStart: Bool = false,
explicitEnd: Bool = false,
version: (major: Int, minor: Int)? = nil) {
documentStartImplicit = explicitStart ? 0 : 1
documentEndImplicit = explicitStart ? 0 : 1
self.version = version
// configure emitter
yaml_emitter_initialize(&emitter)
yaml_emitter_set_output(&self.emitter, { pointer, buffer, size in
guard let buffer = buffer else { return 0 }
let emitter = unsafeBitCast(pointer, to: Emitter.self)
emitter.data.append(buffer, count: size)
return 1
}, unsafeBitCast(self, to: UnsafeMutableRawPointer.self))
yaml_emitter_set_canonical(&emitter, canonical ? 1 : 0)
yaml_emitter_set_indent(&emitter, Int32(indent))
yaml_emitter_set_width(&emitter, Int32(width))
yaml_emitter_set_unicode(&emitter, allowUnicode ? 1 : 0)
switch lineBreak {
case .cr: yaml_emitter_set_break(&emitter, YAML_CR_BREAK)
case .ln: yaml_emitter_set_break(&emitter, YAML_LN_BREAK)
case .crln: yaml_emitter_set_break(&emitter, YAML_CRLN_BREAK)
}
#if USE_UTF16
yaml_emitter_set_encoding(&emitter, YAML_UTF16BE_ENCODING)
#else
yaml_emitter_set_encoding(&emitter, YAML_UTF8_ENCODING)
#endif
}
deinit {
yaml_emitter_delete(&emitter)
}
public func open() throws {
switch state {
case .initialized:
var event = yaml_event_t()
#if USE_UTF16
yaml_stream_start_event_initialize(&event, YAML_UTF16BE_ENCODING)
#else
yaml_stream_start_event_initialize(&event, YAML_UTF8_ENCODING)
#endif
try emit(&event)
state = .opened
case .opened:
throw EmitterError.invalidState("serializer is already opened")
case .closed:
throw EmitterError.invalidState("serializer is closed")
}
}
public func close() throws {
switch state {
case .initialized:
throw EmitterError.invalidState("serializer is not opened")
case .opened:
var event = yaml_event_t()
yaml_stream_end_event_initialize(&event)
try emit(&event)
state = .closed
case .closed:
break // do nothing
}
}
public func serialize(node: Node) throws {
switch state {
case .initialized:
throw EmitterError.invalidState("serializer is not opened")
case .opened:
break
case .closed:
throw EmitterError.invalidState("serializer is closed")
}
var event = yaml_event_t()
var versionDirective: UnsafeMutablePointer<yaml_version_directive_t>?
var versionDirectiveValue = yaml_version_directive_t()
if let (major, minor) = version {
versionDirectiveValue.major = Int32(major)
versionDirectiveValue.minor = Int32(minor)
versionDirective = UnsafeMutablePointer(&versionDirectiveValue)
}
// TODO: Support tags
yaml_document_start_event_initialize(&event, versionDirective, nil, nil, documentStartImplicit)
try emit(&event)
try serializeNode(node)
yaml_document_end_event_initialize(&event, documentEndImplicit)
try emit(&event)
}
// private
fileprivate var emitter = yaml_emitter_t()
fileprivate enum State { case initialized, opened, closed }
fileprivate var state: State = .initialized
}
// MARK: implementation details
extension Emitter {
fileprivate func emit(_ event: UnsafeMutablePointer<yaml_event_t>) throws {
guard yaml_emitter_emit(&emitter, event) == 1 else {
throw YamlError(from: emitter)
}
}
fileprivate func serializeNode(_ node: Node) throws {
switch node {
case .scalar: try serializeScalarNode(node)
case .sequence: try serializeSequenceNode(node)
case .mapping: try serializeMappingNode(node)
}
}
private func serializeScalarNode(_ node: Node) throws {
assert(node.isScalar) // swiftlint:disable:next force_unwrapping
let scalar = node.scalar!
var value = scalar.string.utf8CString, tag = node.tag.name.rawValue.utf8CString
let implicit: Int32 = node.tag.name == .str ? 1 : 0
let scalar_style = yaml_scalar_style_t(rawValue: scalar.style.rawValue)
var event = yaml_event_t()
_ = value.withUnsafeMutableBytes { value in
tag.withUnsafeMutableBytes { tag in
yaml_scalar_event_initialize(
&event,
nil,
tag.baseAddress?.assumingMemoryBound(to: UInt8.self),
value.baseAddress?.assumingMemoryBound(to: UInt8.self),
Int32(value.count - 1),
0,
implicit,
scalar_style)
}
}
try emit(&event)
}
private func serializeSequenceNode(_ node: Node) throws {
assert(node.isSequence) // swiftlint:disable:next force_unwrapping
var sequence = node.sequence!, tag = node.tag.name.rawValue.utf8CString
let implicit: Int32 = node.tag.name == .seq ? 1 : 0
let sequence_style = yaml_sequence_style_t(rawValue: sequence.style.rawValue)
var event = yaml_event_t()
_ = tag.withUnsafeMutableBytes { tag in
yaml_sequence_start_event_initialize(
&event,
nil,
tag.baseAddress?.assumingMemoryBound(to: UInt8.self),
implicit,
sequence_style)
}
try emit(&event)
try sequence.nodes.forEach(self.serializeNode)
yaml_sequence_end_event_initialize(&event)
try emit(&event)
}
private func serializeMappingNode(_ node: Node) throws {
assert(node.isMapping) // swiftlint:disable:next force_unwrapping
let mapping = node.mapping!
var pairs = mapping.pairs, tag = node.tag.name.rawValue.utf8CString
let implicit: Int32 = node.tag.name == Tag.Name.map ? 1 : 0
let mapping_style = yaml_mapping_style_t(rawValue: mapping.style.rawValue)
var event = yaml_event_t()
_ = tag.withUnsafeMutableBytes { tag in
yaml_mapping_start_event_initialize(
&event,
nil,
tag.baseAddress?.assumingMemoryBound(to: UInt8.self),
implicit,
mapping_style)
}
try emit(&event)
try pairs.forEach { pair in
try self.serializeNode(pair.key)
try self.serializeNode(pair.value)
}
yaml_mapping_end_event_initialize(&event)
try emit(&event)
}
}
Rename names of generic parameters
//
// Emitter.swift
// Yams
//
// Created by Norio Nomura on 12/28/16.
// Copyright (c) 2016 Yams. All rights reserved.
//
#if SWIFT_PACKAGE
import CYaml
#endif
import Foundation
public func dump<Objects>(
objects: Objects,
canonical: Bool = false,
indent: Int = 0,
width: Int = 0,
allowUnicode: Bool = false,
lineBreak: Emitter.LineBreak = .ln,
explicitStart: Bool = false,
explicitEnd: Bool = false,
version: (major: Int, minor: Int)? = nil) throws -> String
where Objects: Sequence, Objects.Iterator.Element: NodeRepresentable {
return try serialize(
nodes: objects.map { try $0.represented() },
canonical: canonical,
indent: indent,
width: width,
allowUnicode: allowUnicode,
lineBreak: lineBreak,
explicitStart: explicitStart,
explicitEnd: explicitEnd,
version: version)
}
public func dump<Object>(
object: Object,
canonical: Bool = false,
indent: Int = 0,
width: Int = 0,
allowUnicode: Bool = false,
lineBreak: Emitter.LineBreak = .ln,
explicitStart: Bool = false,
explicitEnd: Bool = false,
version: (major: Int, minor: Int)? = nil) throws -> String
where Object: NodeRepresentable {
return try dump(
objects: [object],
canonical: canonical,
indent: indent,
width: width,
allowUnicode: allowUnicode,
lineBreak: lineBreak,
explicitStart: explicitStart,
explicitEnd: explicitEnd,
version: version)
}
public func serialize<Nodes>(
nodes: Nodes,
canonical: Bool = false,
indent: Int = 0,
width: Int = 0,
allowUnicode: Bool = false,
lineBreak: Emitter.LineBreak = .ln,
explicitStart: Bool = false,
explicitEnd: Bool = false,
version: (major: Int, minor: Int)? = nil) throws -> String
where Nodes: Sequence, Nodes.Iterator.Element == Node {
let emitter = Emitter(
canonical: canonical,
indent: indent,
width: width,
allowUnicode: allowUnicode,
lineBreak: lineBreak,
explicitStart: explicitStart,
explicitEnd: explicitEnd,
version: version)
try emitter.open()
try nodes.forEach(emitter.serialize)
try emitter.close()
#if USE_UTF16
return String(data: emitter.data, encoding: .utf16)!
#else
return String(data: emitter.data, encoding: .utf8)!
#endif
}
public func serialize(
node: Node,
canonical: Bool = false,
indent: Int = 0,
width: Int = 0,
allowUnicode: Bool = false,
lineBreak: Emitter.LineBreak = .ln,
explicitStart: Bool = false,
explicitEnd: Bool = false,
version: (major: Int, minor: Int)? = nil) throws -> String {
return try serialize(
nodes: [node],
canonical: canonical,
indent: indent,
width: width,
allowUnicode: allowUnicode,
lineBreak: lineBreak,
explicitStart: explicitStart,
explicitEnd: explicitEnd,
version: version)
}
public enum EmitterError: Swift.Error {
case invalidState(String)
}
public final class Emitter {
public enum LineBreak {
/// Use CR for line breaks (Mac style).
case cr
/// Use LN for line breaks (Unix style).
case ln
/// Use CR LN for line breaks (DOS style).
case crln
}
public var data = Data()
let documentStartImplicit: Int32
let documentEndImplicit: Int32
let version: (major: Int, minor: Int)?
public init(canonical: Bool = false,
indent: Int = 0,
width: Int = 0,
allowUnicode: Bool = false,
lineBreak: LineBreak = .ln,
explicitStart: Bool = false,
explicitEnd: Bool = false,
version: (major: Int, minor: Int)? = nil) {
documentStartImplicit = explicitStart ? 0 : 1
documentEndImplicit = explicitStart ? 0 : 1
self.version = version
// configure emitter
yaml_emitter_initialize(&emitter)
yaml_emitter_set_output(&self.emitter, { pointer, buffer, size in
guard let buffer = buffer else { return 0 }
let emitter = unsafeBitCast(pointer, to: Emitter.self)
emitter.data.append(buffer, count: size)
return 1
}, unsafeBitCast(self, to: UnsafeMutableRawPointer.self))
yaml_emitter_set_canonical(&emitter, canonical ? 1 : 0)
yaml_emitter_set_indent(&emitter, Int32(indent))
yaml_emitter_set_width(&emitter, Int32(width))
yaml_emitter_set_unicode(&emitter, allowUnicode ? 1 : 0)
switch lineBreak {
case .cr: yaml_emitter_set_break(&emitter, YAML_CR_BREAK)
case .ln: yaml_emitter_set_break(&emitter, YAML_LN_BREAK)
case .crln: yaml_emitter_set_break(&emitter, YAML_CRLN_BREAK)
}
#if USE_UTF16
yaml_emitter_set_encoding(&emitter, YAML_UTF16BE_ENCODING)
#else
yaml_emitter_set_encoding(&emitter, YAML_UTF8_ENCODING)
#endif
}
deinit {
yaml_emitter_delete(&emitter)
}
public func open() throws {
switch state {
case .initialized:
var event = yaml_event_t()
#if USE_UTF16
yaml_stream_start_event_initialize(&event, YAML_UTF16BE_ENCODING)
#else
yaml_stream_start_event_initialize(&event, YAML_UTF8_ENCODING)
#endif
try emit(&event)
state = .opened
case .opened:
throw EmitterError.invalidState("serializer is already opened")
case .closed:
throw EmitterError.invalidState("serializer is closed")
}
}
public func close() throws {
switch state {
case .initialized:
throw EmitterError.invalidState("serializer is not opened")
case .opened:
var event = yaml_event_t()
yaml_stream_end_event_initialize(&event)
try emit(&event)
state = .closed
case .closed:
break // do nothing
}
}
public func serialize(node: Node) throws {
switch state {
case .initialized:
throw EmitterError.invalidState("serializer is not opened")
case .opened:
break
case .closed:
throw EmitterError.invalidState("serializer is closed")
}
var event = yaml_event_t()
var versionDirective: UnsafeMutablePointer<yaml_version_directive_t>?
var versionDirectiveValue = yaml_version_directive_t()
if let (major, minor) = version {
versionDirectiveValue.major = Int32(major)
versionDirectiveValue.minor = Int32(minor)
versionDirective = UnsafeMutablePointer(&versionDirectiveValue)
}
// TODO: Support tags
yaml_document_start_event_initialize(&event, versionDirective, nil, nil, documentStartImplicit)
try emit(&event)
try serializeNode(node)
yaml_document_end_event_initialize(&event, documentEndImplicit)
try emit(&event)
}
// private
fileprivate var emitter = yaml_emitter_t()
fileprivate enum State { case initialized, opened, closed }
fileprivate var state: State = .initialized
}
// MARK: implementation details
extension Emitter {
fileprivate func emit(_ event: UnsafeMutablePointer<yaml_event_t>) throws {
guard yaml_emitter_emit(&emitter, event) == 1 else {
throw YamlError(from: emitter)
}
}
fileprivate func serializeNode(_ node: Node) throws {
switch node {
case .scalar: try serializeScalarNode(node)
case .sequence: try serializeSequenceNode(node)
case .mapping: try serializeMappingNode(node)
}
}
private func serializeScalarNode(_ node: Node) throws {
assert(node.isScalar) // swiftlint:disable:next force_unwrapping
let scalar = node.scalar!
var value = scalar.string.utf8CString, tag = node.tag.name.rawValue.utf8CString
let implicit: Int32 = node.tag.name == .str ? 1 : 0
let scalar_style = yaml_scalar_style_t(rawValue: scalar.style.rawValue)
var event = yaml_event_t()
_ = value.withUnsafeMutableBytes { value in
tag.withUnsafeMutableBytes { tag in
yaml_scalar_event_initialize(
&event,
nil,
tag.baseAddress?.assumingMemoryBound(to: UInt8.self),
value.baseAddress?.assumingMemoryBound(to: UInt8.self),
Int32(value.count - 1),
0,
implicit,
scalar_style)
}
}
try emit(&event)
}
private func serializeSequenceNode(_ node: Node) throws {
assert(node.isSequence) // swiftlint:disable:next force_unwrapping
var sequence = node.sequence!, tag = node.tag.name.rawValue.utf8CString
let implicit: Int32 = node.tag.name == .seq ? 1 : 0
let sequence_style = yaml_sequence_style_t(rawValue: sequence.style.rawValue)
var event = yaml_event_t()
_ = tag.withUnsafeMutableBytes { tag in
yaml_sequence_start_event_initialize(
&event,
nil,
tag.baseAddress?.assumingMemoryBound(to: UInt8.self),
implicit,
sequence_style)
}
try emit(&event)
try sequence.nodes.forEach(self.serializeNode)
yaml_sequence_end_event_initialize(&event)
try emit(&event)
}
private func serializeMappingNode(_ node: Node) throws {
assert(node.isMapping) // swiftlint:disable:next force_unwrapping
let mapping = node.mapping!
var pairs = mapping.pairs, tag = node.tag.name.rawValue.utf8CString
let implicit: Int32 = node.tag.name == Tag.Name.map ? 1 : 0
let mapping_style = yaml_mapping_style_t(rawValue: mapping.style.rawValue)
var event = yaml_event_t()
_ = tag.withUnsafeMutableBytes { tag in
yaml_mapping_start_event_initialize(
&event,
nil,
tag.baseAddress?.assumingMemoryBound(to: UInt8.self),
implicit,
mapping_style)
}
try emit(&event)
try pairs.forEach { pair in
try self.serializeNode(pair.key)
try self.serializeNode(pair.value)
}
yaml_mapping_end_event_initialize(&event)
try emit(&event)
}
}
|
//
// TextFieldTableViewCell.swift
// Pippin
//
// Created by Andrew McKnight on 12/9/16.
// Copyright © 2016 Two Ring Software. All rights reserved.
//
import UIKit
public let textFieldTableViewCellReuseIdentifier = "TextFieldTableViewCell"
/**
A `UITableViewCell` subclass providing a label on the left and a text field on the right. By default the label's `numberOfLines` is not set to 0, but it is layed out such that the label may extend to multiple lines and leave the text field at the top.
*/
public class TextFieldTableViewCell: UITableViewCell {
public let textField = UITextField(frame: .zero)
public let titleLabel = UILabel(frame: .zero)
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .clear
contentView.backgroundColor = .clear
selectionStyle = .none
if #available(iOS 13.0, *) {
textField.backgroundColor = .systemFill
}
[textField, titleLabel].forEach {
contentView.addSubview($0)
$0.translatesAutoresizingMaskIntoConstraints = false
}
[
titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: CGFloat.horizontalMargin),
titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: CGFloat.verticalMargin),
titleLabel.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -CGFloat.verticalMargin),
textField.leadingAnchor.constraint(equalTo: titleLabel.trailingAnchor, constant: CGFloat.horizontalSpacing),
textField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -CGFloat.horizontalMargin),
textField.firstBaselineAnchor.constraint(equalTo: titleLabel.firstBaselineAnchor),
textField.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -CGFloat.verticalMargin),
].forEach { $0.isActive = true }
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
ensure equal vertical spacing around text field
//
// TextFieldTableViewCell.swift
// Pippin
//
// Created by Andrew McKnight on 12/9/16.
// Copyright © 2016 Two Ring Software. All rights reserved.
//
import UIKit
public let textFieldTableViewCellReuseIdentifier = "TextFieldTableViewCell"
/**
A `UITableViewCell` subclass providing a label on the left and a text field on the right. By default the label's `numberOfLines` is not set to 0, but it is layed out such that the label may extend to multiple lines and leave the text field at the top.
*/
public class TextFieldTableViewCell: UITableViewCell {
public let textField = UITextField(frame: .zero)
public let titleLabel = UILabel(frame: .zero)
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .clear
contentView.backgroundColor = .clear
selectionStyle = .none
if #available(iOS 13.0, *) {
textField.backgroundColor = .systemFill
}
[textField, titleLabel].forEach {
contentView.addSubview($0)
$0.translatesAutoresizingMaskIntoConstraints = false
}
[
titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: CGFloat.horizontalMargin),
titleLabel.topAnchor.constraint(greaterThanOrEqualTo: contentView.topAnchor, constant: CGFloat.verticalMargin),
titleLabel.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -CGFloat.verticalMargin),
textField.topAnchor.constraint(greaterThanOrEqualTo: contentView.topAnchor, constant: CGFloat.verticalMargin),
textField.leadingAnchor.constraint(equalTo: titleLabel.trailingAnchor, constant: CGFloat.horizontalSpacing),
textField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -CGFloat.horizontalMargin),
textField.firstBaselineAnchor.constraint(equalTo: titleLabel.firstBaselineAnchor),
textField.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -CGFloat.verticalMargin),
].forEach { $0.isActive = true }
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// EpisodeTableViewController.swift
// Podverse
//
// Created by Mitchell Downey on 10/1/17.
// Copyright © 2017 Podverse LLC. All rights reserved.
//
import UIKit
class EpisodeTableViewController: PVViewController {
var feedUrl: String?
var mediaRefs = [MediaRef]()
var mediaUrl: String?
let moc = CoreDataHelper.createMOCForThread(threadType: .privateThread)
let reachability = PVReachability.shared
@IBOutlet weak var webView: UIWebView!
var filterTypeSelected: EpisodeFilterType = .showNotes {
didSet {
self.filterType.setTitle(filterTypeSelected.text + "\u{2304}", for: .normal)
if filterTypeSelected == .showNotes {
self.webView.isHidden = false
} else {
self.webView.isHidden = true
}
}
}
@IBOutlet weak var episodeTitle: UILabel!
@IBOutlet weak var headerImageView: UIImageView!
@IBOutlet weak var localMultiButton: UIButton!
@IBOutlet weak var streamButton: UIButton!
@IBOutlet weak var filterType: UIButton!
@IBOutlet weak var sorting: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.filterTypeSelected = .showNotes
setupNotificationListeners()
loadHeaderButtons()
setupWebView()
loadData()
}
deinit {
removeObservers()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.webView.scrollView.contentInset = UIEdgeInsets.zero;
}
fileprivate func setupNotificationListeners() {
NotificationCenter.default.addObserver(self, selector: #selector(self.downloadStarted(_:)), name: .downloadStarted, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.downloadResumed(_:)), name: .downloadResumed, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.downloadPaused(_:)), name: .downloadPaused, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.downloadFinished(_:)), name: .downloadFinished, object: nil)
}
fileprivate func removeObservers() {
NotificationCenter.default.removeObserver(self, name: .downloadStarted, object: nil)
NotificationCenter.default.removeObserver(self, name: .downloadResumed, object: nil)
NotificationCenter.default.removeObserver(self, name: .downloadPaused, object: nil)
NotificationCenter.default.removeObserver(self, name: .downloadFinished, object: nil)
}
func setupWebView() {
if let mediaUrl = self.mediaUrl, let episode = Episode.episodeForMediaUrl(mediaUrlString: mediaUrl, managedObjectContext: self.moc) {
if let summary = episode.summary {
self.webView.loadHTMLString(summary.formatHtmlString(isWhiteBg: true), baseURL: nil)
}
self.webView.delegate = self
}
}
@IBAction func downloadPlay(_ sender: Any) {
if let mediaUrl = self.mediaUrl, let episode = Episode.episodeForMediaUrl(mediaUrlString: mediaUrl, managedObjectContext: self.moc) {
if episode.fileName != nil {
let playerHistoryItem: PlayerHistoryItem?
if let mediaUrl = episode.mediaUrl, let item = playerHistoryManager.retrieveExistingPlayerHistoryItem(mediaUrl: mediaUrl) {
playerHistoryItem = item
} else {
playerHistoryItem = playerHistoryManager.convertEpisodeToPlayerHistoryItem(episode: episode)
}
goToNowPlaying()
if let item = playerHistoryItem {
self.pvMediaPlayer.loadPlayerHistoryItem(item: item)
}
} else {
if reachability.hasWiFiConnection() == false {
showInternetNeededAlertWithDesciription(message: "Connect to WiFi to download an episode.")
return
}
PVDownloader.shared.startDownloadingEpisode(episode: episode)
}
}
}
@IBAction func stream(_ sender: Any) {
if let mediaUrl = self.mediaUrl, let episode = Episode.episodeForMediaUrl(mediaUrlString: mediaUrl, managedObjectContext: self.moc) {
let item = playerHistoryManager.convertEpisodeToPlayerHistoryItem(episode: episode)
goToNowPlaying()
self.pvMediaPlayer.loadPlayerHistoryItem(item: item)
}
}
@IBAction func updateFilter(_ sender: Any) {
let alert = UIAlertController(title: "From this Episode", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Show Notes", style: .default, handler: { action in
self.filterTypeSelected = .showNotes
self.loadData()
}))
alert.addAction(UIAlertAction(title: "Clips", style: .default, handler: { action in
self.filterTypeSelected = .clips
self.loadData()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
@IBAction func updateSorting(_ sender: Any) {
}
func loadData() {
if let feedUrl = feedUrl, let podcast = Podcast.podcastForFeedUrl(feedUrlString: feedUrl, managedObjectContext: moc), let mediaUrl = mediaUrl, let episode = Episode.episodeForMediaUrl(mediaUrlString: mediaUrl, managedObjectContext: moc) {
episodeTitle.text = episode.title
self.headerImageView.image = Podcast.retrievePodcastImage(podcastImageURLString: podcast.imageUrl, feedURLString: podcast.feedUrl, managedObjectID: podcast.objectID, completion: { _ in
self.headerImageView.sd_setImage(with: URL(string: podcast.imageUrl ?? ""), placeholderImage: #imageLiteral(resourceName: "PodverseIcon"))
})
if self.filterTypeSelected == .showNotes {
print("show notes filter selected")
} else if self.filterTypeSelected == .clips {
print("clips filter selected")
}
}
}
func loadHeaderButtons() {
if let feedUrl = feedUrl, let podcast = Podcast.podcastForFeedUrl(feedUrlString: feedUrl, managedObjectContext: moc), let mediaUrl = mediaUrl, let episode = Episode.episodeForMediaUrl(mediaUrlString: mediaUrl, managedObjectContext: moc) {
if (DownloadingEpisodeList.shared.downloadingEpisodes.contains(where: {$0.mediaUrl == mediaUrl})) {
self.streamButton.isHidden = false
self.streamButton.setTitle("Stream", for: .normal)
self.localMultiButton.setTitle("Downloading", for: .normal)
} else if episode.fileName == nil {
self.streamButton.isHidden = false
self.streamButton.setTitle("Stream", for: .normal)
self.localMultiButton.setTitle("Download", for: .normal)
} else {
self.streamButton.isHidden = true
self.localMultiButton.setTitle("Play", for: .normal)
}
}
}
override func goToNowPlaying () {
if let mediaPlayerVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MediaPlayerVC") as? MediaPlayerViewController {
pvMediaPlayer.shouldAutoplayOnce = true
self.navigationController?.pushViewController(mediaPlayerVC, animated: true)
}
}
}
extension EpisodeTableViewController:UIWebViewDelegate {
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.linkClicked {
if let url = request.url {
UIApplication.shared.openURL(url)
}
return false
}
return true
}
}
extension EpisodeTableViewController {
func updateButtonsByNotification(_ notification:Notification) {
if let downloadingEpisode = notification.userInfo?[Episode.episodeKey] as? DownloadingEpisode, let dlMediaUrl = downloadingEpisode.mediaUrl, let mediaUrl = self.mediaUrl, dlMediaUrl == mediaUrl {
loadHeaderButtons()
}
}
func downloadFinished(_ notification:Notification) {
updateButtonsByNotification(notification)
}
func downloadPaused(_ notification:Notification) {
updateButtonsByNotification(notification)
}
func downloadResumed(_ notification:Notification) {
updateButtonsByNotification(notification)
}
func downloadStarted(_ notification:Notification) {
updateButtonsByNotification(notification)
}
}
Add line breaks to account for NowPlayingBar
//
// EpisodeTableViewController.swift
// Podverse
//
// Created by Mitchell Downey on 10/1/17.
// Copyright © 2017 Podverse LLC. All rights reserved.
//
import UIKit
class EpisodeTableViewController: PVViewController {
var feedUrl: String?
var mediaRefs = [MediaRef]()
var mediaUrl: String?
let moc = CoreDataHelper.createMOCForThread(threadType: .privateThread)
let reachability = PVReachability.shared
@IBOutlet weak var webView: UIWebView!
var filterTypeSelected: EpisodeFilterType = .showNotes {
didSet {
self.filterType.setTitle(filterTypeSelected.text + "\u{2304}", for: .normal)
if filterTypeSelected == .showNotes {
self.webView.isHidden = false
} else {
self.webView.isHidden = true
}
}
}
@IBOutlet weak var episodeTitle: UILabel!
@IBOutlet weak var headerImageView: UIImageView!
@IBOutlet weak var localMultiButton: UIButton!
@IBOutlet weak var streamButton: UIButton!
@IBOutlet weak var filterType: UIButton!
@IBOutlet weak var sorting: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.filterTypeSelected = .showNotes
setupNotificationListeners()
loadHeaderButtons()
setupWebView()
loadData()
}
deinit {
removeObservers()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.webView.scrollView.contentInset = UIEdgeInsets.zero;
}
fileprivate func setupNotificationListeners() {
NotificationCenter.default.addObserver(self, selector: #selector(self.downloadStarted(_:)), name: .downloadStarted, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.downloadResumed(_:)), name: .downloadResumed, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.downloadPaused(_:)), name: .downloadPaused, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.downloadFinished(_:)), name: .downloadFinished, object: nil)
}
fileprivate func removeObservers() {
NotificationCenter.default.removeObserver(self, name: .downloadStarted, object: nil)
NotificationCenter.default.removeObserver(self, name: .downloadResumed, object: nil)
NotificationCenter.default.removeObserver(self, name: .downloadPaused, object: nil)
NotificationCenter.default.removeObserver(self, name: .downloadFinished, object: nil)
}
func setupWebView() {
if let mediaUrl = self.mediaUrl, let episode = Episode.episodeForMediaUrl(mediaUrlString: mediaUrl, managedObjectContext: self.moc) {
if var summary = episode.summary {
// add linebreaks to account for the NowPlayingBar on the bottom of the screen
summary += "<br><br>"
self.webView.loadHTMLString(summary.formatHtmlString(isWhiteBg: true), baseURL: nil)
}
self.webView.delegate = self
}
}
@IBAction func downloadPlay(_ sender: Any) {
if let mediaUrl = self.mediaUrl, let episode = Episode.episodeForMediaUrl(mediaUrlString: mediaUrl, managedObjectContext: self.moc) {
if episode.fileName != nil {
let playerHistoryItem: PlayerHistoryItem?
if let mediaUrl = episode.mediaUrl, let item = playerHistoryManager.retrieveExistingPlayerHistoryItem(mediaUrl: mediaUrl) {
playerHistoryItem = item
} else {
playerHistoryItem = playerHistoryManager.convertEpisodeToPlayerHistoryItem(episode: episode)
}
goToNowPlaying()
if let item = playerHistoryItem {
self.pvMediaPlayer.loadPlayerHistoryItem(item: item)
}
} else {
if reachability.hasWiFiConnection() == false {
showInternetNeededAlertWithDesciription(message: "Connect to WiFi to download an episode.")
return
}
PVDownloader.shared.startDownloadingEpisode(episode: episode)
}
}
}
@IBAction func stream(_ sender: Any) {
if let mediaUrl = self.mediaUrl, let episode = Episode.episodeForMediaUrl(mediaUrlString: mediaUrl, managedObjectContext: self.moc) {
let item = playerHistoryManager.convertEpisodeToPlayerHistoryItem(episode: episode)
goToNowPlaying()
self.pvMediaPlayer.loadPlayerHistoryItem(item: item)
}
}
@IBAction func updateFilter(_ sender: Any) {
let alert = UIAlertController(title: "From this Episode", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Show Notes", style: .default, handler: { action in
self.filterTypeSelected = .showNotes
self.loadData()
}))
alert.addAction(UIAlertAction(title: "Clips", style: .default, handler: { action in
self.filterTypeSelected = .clips
self.loadData()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
@IBAction func updateSorting(_ sender: Any) {
}
func loadData() {
if let feedUrl = feedUrl, let podcast = Podcast.podcastForFeedUrl(feedUrlString: feedUrl, managedObjectContext: moc), let mediaUrl = mediaUrl, let episode = Episode.episodeForMediaUrl(mediaUrlString: mediaUrl, managedObjectContext: moc) {
episodeTitle.text = episode.title
self.headerImageView.image = Podcast.retrievePodcastImage(podcastImageURLString: podcast.imageUrl, feedURLString: podcast.feedUrl, managedObjectID: podcast.objectID, completion: { _ in
self.headerImageView.sd_setImage(with: URL(string: podcast.imageUrl ?? ""), placeholderImage: #imageLiteral(resourceName: "PodverseIcon"))
})
if self.filterTypeSelected == .showNotes {
print("show notes filter selected")
} else if self.filterTypeSelected == .clips {
print("clips filter selected")
}
}
}
func loadHeaderButtons() {
if let feedUrl = feedUrl, let podcast = Podcast.podcastForFeedUrl(feedUrlString: feedUrl, managedObjectContext: moc), let mediaUrl = mediaUrl, let episode = Episode.episodeForMediaUrl(mediaUrlString: mediaUrl, managedObjectContext: moc) {
if (DownloadingEpisodeList.shared.downloadingEpisodes.contains(where: {$0.mediaUrl == mediaUrl})) {
self.streamButton.isHidden = false
self.streamButton.setTitle("Stream", for: .normal)
self.localMultiButton.setTitle("Downloading", for: .normal)
} else if episode.fileName == nil {
self.streamButton.isHidden = false
self.streamButton.setTitle("Stream", for: .normal)
self.localMultiButton.setTitle("Download", for: .normal)
} else {
self.streamButton.isHidden = true
self.localMultiButton.setTitle("Play", for: .normal)
}
}
}
override func goToNowPlaying () {
if let mediaPlayerVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MediaPlayerVC") as? MediaPlayerViewController {
pvMediaPlayer.shouldAutoplayOnce = true
self.navigationController?.pushViewController(mediaPlayerVC, animated: true)
}
}
}
extension EpisodeTableViewController:UIWebViewDelegate {
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.linkClicked {
if let url = request.url {
UIApplication.shared.openURL(url)
}
return false
}
return true
}
}
extension EpisodeTableViewController {
func updateButtonsByNotification(_ notification:Notification) {
if let downloadingEpisode = notification.userInfo?[Episode.episodeKey] as? DownloadingEpisode, let dlMediaUrl = downloadingEpisode.mediaUrl, let mediaUrl = self.mediaUrl, dlMediaUrl == mediaUrl {
loadHeaderButtons()
}
}
func downloadFinished(_ notification:Notification) {
updateButtonsByNotification(notification)
}
func downloadPaused(_ notification:Notification) {
updateButtonsByNotification(notification)
}
func downloadResumed(_ notification:Notification) {
updateButtonsByNotification(notification)
}
func downloadStarted(_ notification:Notification) {
updateButtonsByNotification(notification)
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
protocol LocationProvider: class {
func getCurrentLocation() -> CLLocation?
}
protocol LocationMonitorDelegate: class {
func locationMonitor(_ locationMonitor: LocationMonitor, didUpdateLocation location: CLLocation)
func locationMonitor(_ locationMonitor: LocationMonitor, userDidExitCurrentLocation location: CLLocation)
func locationMonitorNeedsUserPermissionsPrompt(_ locationMonitor: LocationMonitor)
func locationMonitor(_ locationMonitor: LocationMonitor, userDidVisitLocation location: CLLocation)
func locationMonitor(_ locationMonitor: LocationMonitor, didFailInitialUpdateWithError error: Error)
}
// an extension on the delegate allows us to give default implementations to some of the functions, making them optional
extension LocationMonitorDelegate {
func locationMonitor(_ locationMonitor: LocationMonitor, userDidVisitLocation location: CLLocation) {}
func locationMonitor(_ locationMonitor: LocationMonitor, userDidExitCurrentLocation location: CLLocation) {}
}
class LocationMonitor: NSObject {
weak var delegate: LocationMonitorDelegate?
fileprivate(set) var currentLocation: CLLocation?
fileprivate let currentLocationIdentifier = "CURRENT_LOCATION"
fileprivate let MIN_SECS_BETWEEN_LOCATION_UPDATES: TimeInterval = 1
fileprivate(set) var timeOfLastLocationUpdate: Date? {
get {
return UserDefaults.standard.value(forKey: AppConstants.timeOfLastLocationUpdateKey) as? Date
}
set {
UserDefaults.standard.set(newValue, forKey: AppConstants.timeOfLastLocationUpdateKey)
}
}
lazy var locationManager: CLLocationManager = {
let manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
// TODO: update to a more sane distance value when testing is over.
// This is probably going to be around 100m
manager.distanceFilter = RemoteConfigKeys.significantLocationChangeDistanceMeters.value
manager.pausesLocationUpdatesAutomatically = true
return manager
}()
// fake the location to Hilton Waikaloa Village, Kona, Hawaii
var fakeLocation: CLLocation = CLLocation(latitude: 19.924043, longitude: -155.887652)
fileprivate var monitoredRegions: [String: GeofenceRegion] = [String: GeofenceRegion]()
fileprivate var timeAtLocationTimer: Timer?
fileprivate var isAuthorized = false
func refreshLocation() {
if (CLLocationManager.hasLocationPermissionAndEnabled()) {
isAuthorized = true
locationManager.startUpdatingLocation()
} else {
isAuthorized = false
// requestLocation expected to be called on authorization status change.
maybeRequestLocationPermission()
}
}
func cancelTimeAtLocationTimer() {
timeAtLocationTimer?.invalidate()
timeAtLocationTimer = nil
}
func startTimeAtLocationTimer() {
if timeAtLocationTimer == nil {
timeAtLocationTimer = Timer.scheduledTimer(timeInterval: AppConstants.minimumIntervalAtLocationBeforeFetchingEvents, target: self, selector: #selector(timerFired(timer:)), userInfo: nil, repeats: true)
}
}
@objc fileprivate func timerFired(timer: Timer) {
guard let currentLocation = getCurrentLocation() else { return }
delegate?.locationMonitor(self, userDidVisitLocation: currentLocation)
}
func startMonitoringForVisitAtCurrentLocation() {
guard let currentLocation = getCurrentLocation(),
!monitoredRegions.keys.contains(currentLocationIdentifier) else { return }
startTimeAtLocationTimer()
startMonitoring(location: currentLocation, withIdentifier: currentLocationIdentifier, withRadius: RemoteConfigKeys.radiusForCurrentLocationMonitoringMeters.value, forEntry: nil, forExit: { region in
self.cancelTimeAtLocationTimer()
self.stopMonitoringRegion(withIdentifier: self.currentLocationIdentifier)
self.delegate?.locationMonitor(self, userDidExitCurrentLocation: currentLocation)
})
}
func startMonitoring(location: CLLocation, withIdentifier identifier: String, withRadius radius: CLLocationDistance, forEntry: ((GeofenceRegion)->())?, forExit: ((GeofenceRegion)->())?) {
let region = GeofenceRegion(location: location.coordinate, identifier: identifier, radius: radius, onEntry: forEntry, onExit: forExit)
monitoredRegions[identifier] = region
self.locationManager.startMonitoring(for: region.region)
}
func stopMonitoringRegion(withIdentifier identifier: String) {
guard let monitoredRegion = monitoredRegions[identifier]?.region else {
return
}
self.locationManager.stopMonitoring(for: monitoredRegion)
monitoredRegions.removeValue(forKey: identifier)
}
/*
* Requests permission to use device location services.
*
* May use the passed UIViewController to display a dialog:
* be sure to call this method at the appropriate time.
*/
func maybeRequestLocationPermission() {
guard CLLocationManager.locationServicesEnabled() else {
// This dialog, nor the app settings page it opens, are not a good descriptor that location
// services are disabled but I don't think putting in the work right now is worth it.
delegate?.locationMonitorNeedsUserPermissionsPrompt(self)
return
}
switch (CLLocationManager.authorizationStatus()) {
case .notDetermined:
locationManager.requestAlwaysAuthorization()
case .restricted, .denied:
delegate?.locationMonitorNeedsUserPermissionsPrompt(self)
case .authorizedAlways:
break
case .authorizedWhenInUse:
assertionFailure("Location permission, authorized when in use, not expected.")
}
}
}
extension LocationMonitor: LocationProvider {
func getCurrentLocation() -> CLLocation? {
if currentLocation == nil {
if AppConstants.MOZ_LOCATION_FAKING {
// fake the location to Hilton Waikaloa Village, Kona, Hawaii
currentLocation = fakeLocation
}else {
currentLocation = self.locationManager.location
}
}
return currentLocation
}
}
extension LocationMonitor: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if !isAuthorized || !CLLocationManager.hasLocationPermissionAndEnabled(){
refreshLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Use last coord: we want to display where the user is now.
if var location = locations.last {
// In iOS9, didUpdateLocations can be unexpectedly called multiple
// times for a single `requestLocation`: we guard against that here.
if AppConstants.MOZ_LOCATION_FAKING {
// fake the location to Hilton Waikaloa Village, Kona, Hawaii
location = fakeLocation
}
self.currentLocation = location
self.delegate?.locationMonitor(self, didUpdateLocation: location)
timeOfLastLocationUpdate = location.timestamp
locationManager.stopUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
guard currentLocation == nil else {
// If we have a cached location, we can use that - no need to display another error.
return
}
log.error("location \(error.localizedDescription)")
self.delegate?.locationMonitor(self, didFailInitialUpdateWithError: error)
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
guard let region = monitoredRegions[region.identifier] else { return }
region.onEntry?(region)
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
guard let region = monitoredRegions[region.identifier] else { return }
region.onExit?(region)
}
func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
log.error("location region monitoring failed \(error.localizedDescription)")
}
}
No issue: Don't display missing location dialog when location faking.
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
protocol LocationProvider: class {
func getCurrentLocation() -> CLLocation?
}
protocol LocationMonitorDelegate: class {
func locationMonitor(_ locationMonitor: LocationMonitor, didUpdateLocation location: CLLocation)
func locationMonitor(_ locationMonitor: LocationMonitor, userDidExitCurrentLocation location: CLLocation)
func locationMonitorNeedsUserPermissionsPrompt(_ locationMonitor: LocationMonitor)
func locationMonitor(_ locationMonitor: LocationMonitor, userDidVisitLocation location: CLLocation)
func locationMonitor(_ locationMonitor: LocationMonitor, didFailInitialUpdateWithError error: Error)
}
// an extension on the delegate allows us to give default implementations to some of the functions, making them optional
extension LocationMonitorDelegate {
func locationMonitor(_ locationMonitor: LocationMonitor, userDidVisitLocation location: CLLocation) {}
func locationMonitor(_ locationMonitor: LocationMonitor, userDidExitCurrentLocation location: CLLocation) {}
}
class LocationMonitor: NSObject {
weak var delegate: LocationMonitorDelegate?
fileprivate(set) var currentLocation: CLLocation?
fileprivate let currentLocationIdentifier = "CURRENT_LOCATION"
fileprivate let MIN_SECS_BETWEEN_LOCATION_UPDATES: TimeInterval = 1
fileprivate(set) var timeOfLastLocationUpdate: Date? {
get {
return UserDefaults.standard.value(forKey: AppConstants.timeOfLastLocationUpdateKey) as? Date
}
set {
UserDefaults.standard.set(newValue, forKey: AppConstants.timeOfLastLocationUpdateKey)
}
}
lazy var locationManager: CLLocationManager = {
let manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
// TODO: update to a more sane distance value when testing is over.
// This is probably going to be around 100m
manager.distanceFilter = RemoteConfigKeys.significantLocationChangeDistanceMeters.value
manager.pausesLocationUpdatesAutomatically = true
return manager
}()
// fake the location to Hilton Waikaloa Village, Kona, Hawaii
var fakeLocation: CLLocation = CLLocation(latitude: 19.924043, longitude: -155.887652)
fileprivate var monitoredRegions: [String: GeofenceRegion] = [String: GeofenceRegion]()
fileprivate var timeAtLocationTimer: Timer?
fileprivate var isAuthorized = false
func refreshLocation() {
if (CLLocationManager.hasLocationPermissionAndEnabled()) {
isAuthorized = true
locationManager.startUpdatingLocation()
} else {
isAuthorized = false
// requestLocation expected to be called on authorization status change.
maybeRequestLocationPermission()
}
}
func cancelTimeAtLocationTimer() {
timeAtLocationTimer?.invalidate()
timeAtLocationTimer = nil
}
func startTimeAtLocationTimer() {
if timeAtLocationTimer == nil {
timeAtLocationTimer = Timer.scheduledTimer(timeInterval: AppConstants.minimumIntervalAtLocationBeforeFetchingEvents, target: self, selector: #selector(timerFired(timer:)), userInfo: nil, repeats: true)
}
}
@objc fileprivate func timerFired(timer: Timer) {
guard let currentLocation = getCurrentLocation() else { return }
delegate?.locationMonitor(self, userDidVisitLocation: currentLocation)
}
func startMonitoringForVisitAtCurrentLocation() {
guard let currentLocation = getCurrentLocation(),
!monitoredRegions.keys.contains(currentLocationIdentifier) else { return }
startTimeAtLocationTimer()
startMonitoring(location: currentLocation, withIdentifier: currentLocationIdentifier, withRadius: RemoteConfigKeys.radiusForCurrentLocationMonitoringMeters.value, forEntry: nil, forExit: { region in
self.cancelTimeAtLocationTimer()
self.stopMonitoringRegion(withIdentifier: self.currentLocationIdentifier)
self.delegate?.locationMonitor(self, userDidExitCurrentLocation: currentLocation)
})
}
func startMonitoring(location: CLLocation, withIdentifier identifier: String, withRadius radius: CLLocationDistance, forEntry: ((GeofenceRegion)->())?, forExit: ((GeofenceRegion)->())?) {
let region = GeofenceRegion(location: location.coordinate, identifier: identifier, radius: radius, onEntry: forEntry, onExit: forExit)
monitoredRegions[identifier] = region
self.locationManager.startMonitoring(for: region.region)
}
func stopMonitoringRegion(withIdentifier identifier: String) {
guard let monitoredRegion = monitoredRegions[identifier]?.region else {
return
}
self.locationManager.stopMonitoring(for: monitoredRegion)
monitoredRegions.removeValue(forKey: identifier)
}
/*
* Requests permission to use device location services.
*
* May use the passed UIViewController to display a dialog:
* be sure to call this method at the appropriate time.
*/
func maybeRequestLocationPermission() {
guard CLLocationManager.locationServicesEnabled() else {
// This dialog, nor the app settings page it opens, are not a good descriptor that location
// services are disabled but I don't think putting in the work right now is worth it.
delegate?.locationMonitorNeedsUserPermissionsPrompt(self)
return
}
switch (CLLocationManager.authorizationStatus()) {
case .notDetermined:
locationManager.requestAlwaysAuthorization()
case .restricted, .denied:
delegate?.locationMonitorNeedsUserPermissionsPrompt(self)
case .authorizedAlways:
break
case .authorizedWhenInUse:
assertionFailure("Location permission, authorized when in use, not expected.")
}
}
}
extension LocationMonitor: LocationProvider {
func getCurrentLocation() -> CLLocation? {
if currentLocation == nil {
if AppConstants.MOZ_LOCATION_FAKING {
// fake the location to Hilton Waikaloa Village, Kona, Hawaii
currentLocation = fakeLocation
}else {
currentLocation = self.locationManager.location
}
}
return currentLocation
}
}
extension LocationMonitor: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if !isAuthorized || !CLLocationManager.hasLocationPermissionAndEnabled(){
refreshLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Use last coord: we want to display where the user is now.
if var location = locations.last {
// In iOS9, didUpdateLocations can be unexpectedly called multiple
// times for a single `requestLocation`: we guard against that here.
if AppConstants.MOZ_LOCATION_FAKING {
// fake the location to Hilton Waikaloa Village, Kona, Hawaii
location = fakeLocation
}
self.currentLocation = location
self.delegate?.locationMonitor(self, didUpdateLocation: location)
timeOfLastLocationUpdate = location.timestamp
locationManager.stopUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
if AppConstants.MOZ_LOCATION_FAKING,
let location = getCurrentLocation() { // should never be nil.
self.delegate?.locationMonitor(self, didUpdateLocation: location)
return
}
guard currentLocation == nil else {
// If we have a cached location, we can use that - no need to display another error.
return
}
log.error("location \(error.localizedDescription)")
self.delegate?.locationMonitor(self, didFailInitialUpdateWithError: error)
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
guard let region = monitoredRegions[region.identifier] else { return }
region.onEntry?(region)
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
guard let region = monitoredRegions[region.identifier] else { return }
region.onExit?(region)
}
func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
log.error("location region monitoring failed \(error.localizedDescription)")
}
}
|
//
// CollapseCollectionViewLayout.swift
// PageTabBarControllerExample
//
// Created by Keith Chan on 22/9/2017.
// Copyright © 2017 com.mingloan. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
public struct CollapseCollectionViewLayoutSettings {
var isHeaderStretchy = true
var headerSize = CGSize.zero
var headerStretchHeight: CGFloat = 64
var headerMinimumHeight: CGFloat = 0
public static func defaultSettings() -> CollapseCollectionViewLayoutSettings {
return CollapseCollectionViewLayoutSettings(headerSize: CGSize.zero, isHeaderStretchy: true, headerStretchHeight: 64, headerMinimumHeight: 0)
}
public init(headerSize: CGSize, isHeaderStretchy: Bool, headerStretchHeight: CGFloat, headerMinimumHeight: CGFloat) {
self.isHeaderStretchy = isHeaderStretchy
self.headerSize = headerSize
self.headerStretchHeight = headerStretchHeight
self.headerMinimumHeight = headerMinimumHeight
}
}
@objc
protocol CollapseCollectionViewLayoutDelegate: class {
@objc optional func collapseCollectionView(_ collapseCollectionView: CollapseCollectionView, layout: CollapseCollectionViewLayout, sizeForStaticHeaderAt indexPath: IndexPath) -> CGSize
}
final class CollapseCollectionViewLayout: UICollectionViewLayout {
weak var delegate: CollapseCollectionViewLayoutDelegate?
enum Element: String {
case staticHeader
case header
case cell
var id: String {
return self.rawValue
}
var kind: String {
return "Kind\(self.rawValue.capitalized)"
}
}
var settings = CollapseCollectionViewLayoutSettings.defaultSettings()
fileprivate var contentSize = CGSize.zero
fileprivate var oldBounds = CGRect.zero
fileprivate var cache = [Element: [IndexPath: UICollectionViewLayoutAttributes]]()
fileprivate var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()
convenience init(settings: CollapseCollectionViewLayoutSettings = CollapseCollectionViewLayoutSettings.defaultSettings()) {
self.init()
self.settings = settings
}
override public class var layoutAttributesClass: AnyClass {
return UICollectionViewLayoutAttributes.self
}
override public var collectionViewContentSize: CGSize {
return contentSize
}
override public func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
switch elementKind {
case Element.staticHeader.kind:
return cache[.staticHeader]?[indexPath]
case Element.header.kind:
return cache[.header]?[indexPath]
default:
return nil
}
}
override public func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache[.cell]?[indexPath]
}
override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let collectionView = collectionView else {
return nil
}
visibleLayoutAttributes.removeAll(keepingCapacity: true)
for (type, elementInfos) in cache {
for (indexPath, attributes) in elementInfos {
updateViews(type,
attributes: attributes,
collectionView: collectionView,
indexPath: indexPath)
visibleLayoutAttributes.append(attributes)
}
}
return visibleLayoutAttributes
}
//MARK: - Preparation
private func prepareCache() {
cache.removeAll(keepingCapacity: true)
cache[.header] = [IndexPath: UICollectionViewLayoutAttributes]()
cache[.staticHeader] = [IndexPath: UICollectionViewLayoutAttributes]()
cache[.cell] = [IndexPath: UICollectionViewLayoutAttributes]()
}
private func prepareElement(size: CGSize, type: Element, attributes: UICollectionViewLayoutAttributes) {
guard size != .zero else {
return
}
switch type {
case .staticHeader:
attributes.zIndex = 10
attributes.frame = CGRect(origin: CGPoint(x: 0, y: settings.headerSize.height - size.height), size: size)
break
case .header:
attributes.zIndex = 1
attributes.frame = CGRect(origin: CGPoint.zero, size: size)
break
case .cell:
attributes.zIndex = 10
attributes.frame = CGRect(origin: CGPoint(x: 0, y: settings.headerSize.height), size: size)
break
}
cache[type]?[attributes.indexPath] = attributes
}
private func updateViews(_ type: Element, attributes: UICollectionViewLayoutAttributes, collectionView: UICollectionView, indexPath: IndexPath) {
let headerHeight = settings.headerSize.height
let strechyHeight = settings.isHeaderStretchy ? settings.headerStretchHeight : 0
if collectionView.contentOffset.y < 0 {
switch type {
case .staticHeader:
let y = min(headerHeight + collectionView.contentOffset.y + strechyHeight, headerHeight) - attributes.size.height
attributes.frame = CGRect(origin: CGPoint(x: 0, y: y),
size: attributes.size)
break
case .header:
let updatedHeight = min(headerHeight + strechyHeight,
max(headerHeight, headerHeight - collectionView.contentOffset.y))
let scaleFactor = updatedHeight / headerHeight
let delta = (updatedHeight - headerHeight) / 2
let scale = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)
let translation = CGAffineTransform(translationX: 0,
y: min(collectionView.contentOffset.y, headerHeight) + delta)
attributes.transform = scale.concatenating(translation)
break
case .cell:
let y = min(headerHeight + collectionView.contentOffset.y + strechyHeight, headerHeight)
let maxHeight = collectionView.frame.height - headerHeight - strechyHeight
let height = collectionView.frame.height - headerHeight + collectionView.contentOffset.y
attributes.frame = CGRect(origin: CGPoint(x: 0, y: y),
size: CGSize(width: attributes.frame.width,
height: max(maxHeight, height)))
break
}
} else {
switch type {
case .staticHeader:
let originY = headerHeight - attributes.frame.height + max(0, collectionView.contentOffset.y - headerHeight + settings.headerMinimumHeight)
attributes.frame = CGRect(origin: CGPoint(x: 0, y: originY),
size: attributes.size)
break
case .header:
attributes.transform = .identity
let originY = max(0, collectionView.contentOffset.y - headerHeight + settings.headerMinimumHeight)
attributes.frame = CGRect(origin: CGPoint(x: 0, y: originY),
size: attributes.frame.size)
break
case .cell:
let originY = max(headerHeight, collectionView.contentOffset.y + settings.headerMinimumHeight)
attributes.frame = CGRect(origin: CGPoint(x: 0, y: originY),
size: CGSize(width: attributes.frame.width,
height: collectionView.frame.height - originY + collectionView.contentOffset.y))
break
}
}
}
// MARK: - Layout Details
override public func prepare() {
guard let collectionView = collectionView as? CollapseCollectionView, cache.isEmpty else {
return
}
prepareCache()
let maxHeight = ceil(collectionView.frame.height + settings.headerSize.height - settings.headerMinimumHeight)
contentSize = CGSize(width: collectionView.frame.width, height: maxHeight)
oldBounds = collectionView.bounds
let staticHeaderAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: Element.staticHeader.kind,
with: IndexPath(item: 0, section: 0))
if let staticHeaderSize = delegate?.collapseCollectionView?(collectionView, layout: self, sizeForStaticHeaderAt: IndexPath(item: 0, section: 0)) {
prepareElement(size: staticHeaderSize, type: .staticHeader, attributes: staticHeaderAttributes)
} else {
prepareElement(size: CGSize(width: collectionView.bounds.width, height: 0), type: .staticHeader, attributes: staticHeaderAttributes)
}
let headerAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: Element.header.kind,
with: IndexPath(item: 0, section: 0))
prepareElement(size: settings.headerSize, type: .header, attributes: headerAttributes)
for item in 0 ..< collectionView.numberOfItems(inSection: 0) {
let cellIndexPath = IndexPath(item: item, section: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWith: cellIndexPath)
let size = CGSize(width: collectionView.bounds.width,
height: collectionView.bounds.height - settings.headerMinimumHeight)
prepareElement(size: size, type: .cell, attributes: attributes)
}
}
// MARK: - Invalidation
override func shouldInvalidateLayout (forBoundsChange newBounds : CGRect) -> Bool {
return true
}
// MARK: - ContentOffset
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
return CGPoint.zero
}
}
no message
//
// CollapseCollectionViewLayout.swift
// PageTabBarControllerExample
//
// Created by Keith Chan on 22/9/2017.
// Copyright © 2017 com.mingloan. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
public struct CollapseCollectionViewLayoutSettings {
var isHeaderStretchy = true
var headerSize = CGSize.zero
var headerStretchHeight: CGFloat = 64
var headerMinimumHeight: CGFloat = 0
public static func defaultSettings() -> CollapseCollectionViewLayoutSettings {
return CollapseCollectionViewLayoutSettings(headerSize: CGSize.zero, isHeaderStretchy: true, headerStretchHeight: 64, headerMinimumHeight: 0)
}
public init(headerSize: CGSize, isHeaderStretchy: Bool, headerStretchHeight: CGFloat, headerMinimumHeight: CGFloat) {
self.isHeaderStretchy = isHeaderStretchy
self.headerSize = headerSize
self.headerStretchHeight = headerStretchHeight
self.headerMinimumHeight = headerMinimumHeight
}
}
@objc
protocol CollapseCollectionViewLayoutDelegate: class {
@objc optional func collapseCollectionView(_ collapseCollectionView: CollapseCollectionView, layout: CollapseCollectionViewLayout, sizeForStaticHeaderAt indexPath: IndexPath) -> CGSize
}
final class CollapseCollectionViewLayout: UICollectionViewLayout {
weak var delegate: CollapseCollectionViewLayoutDelegate?
enum Element: String {
case staticHeader
case header
case cell
var id: String {
return self.rawValue
}
var kind: String {
return "Kind\(self.rawValue.capitalized)"
}
}
var settings = CollapseCollectionViewLayoutSettings.defaultSettings()
fileprivate var contentSize = CGSize.zero
fileprivate var oldBounds = CGRect.zero
fileprivate var cache = [Element: [IndexPath: UICollectionViewLayoutAttributes]]()
fileprivate var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()
convenience init(settings: CollapseCollectionViewLayoutSettings = CollapseCollectionViewLayoutSettings.defaultSettings()) {
self.init()
self.settings = settings
}
override public class var layoutAttributesClass: AnyClass {
return UICollectionViewLayoutAttributes.self
}
override public var collectionViewContentSize: CGSize {
return contentSize
}
override public func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
switch elementKind {
case Element.staticHeader.kind:
return cache[.staticHeader]?[indexPath]
case Element.header.kind:
return cache[.header]?[indexPath]
default:
return nil
}
}
override public func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache[.cell]?[indexPath]
}
override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let collectionView = collectionView else {
return nil
}
visibleLayoutAttributes.removeAll(keepingCapacity: true)
for (type, elementInfos) in cache {
for (indexPath, attributes) in elementInfos {
updateViews(type,
attributes: attributes,
collectionView: collectionView,
indexPath: indexPath)
visibleLayoutAttributes.append(attributes)
}
}
return visibleLayoutAttributes
}
//MARK: - Preparation
private func prepareCache() {
cache.removeAll(keepingCapacity: true)
cache[.header] = [IndexPath: UICollectionViewLayoutAttributes]()
cache[.staticHeader] = [IndexPath: UICollectionViewLayoutAttributes]()
cache[.cell] = [IndexPath: UICollectionViewLayoutAttributes]()
}
private func prepareElement(size: CGSize, type: Element, attributes: UICollectionViewLayoutAttributes) {
guard size != .zero else {
return
}
switch type {
case .staticHeader:
attributes.zIndex = 10
attributes.frame = CGRect(origin: CGPoint(x: 0, y: settings.headerSize.height - size.height), size: size)
break
case .header:
attributes.zIndex = 1
attributes.frame = CGRect(origin: CGPoint.zero, size: size)
break
case .cell:
attributes.zIndex = 10
attributes.frame = CGRect(origin: CGPoint(x: 0, y: settings.headerSize.height), size: size)
break
}
cache[type]?[attributes.indexPath] = attributes
}
private func updateViews(_ type: Element, attributes: UICollectionViewLayoutAttributes, collectionView: UICollectionView, indexPath: IndexPath) {
let headerHeight = settings.headerSize.height
let strechyHeight = settings.isHeaderStretchy ? settings.headerStretchHeight : 0
if collectionView.contentOffset.y < 0 {
switch type {
case .staticHeader:
let y = min(headerHeight + collectionView.contentOffset.y + strechyHeight, headerHeight) - attributes.size.height
attributes.frame = CGRect(origin: CGPoint(x: 0, y: y),
size: attributes.size)
break
case .header:
let updatedHeight = min(headerHeight + strechyHeight,
max(headerHeight, headerHeight - collectionView.contentOffset.y))
let scaleFactor = updatedHeight / headerHeight
let delta = (updatedHeight - headerHeight) / 2
let scale = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)
let translation = CGAffineTransform(translationX: 0,
y: min(collectionView.contentOffset.y, headerHeight) + delta)
attributes.transform = scale.concatenating(translation)
break
case .cell:
let y = min(headerHeight + collectionView.contentOffset.y + strechyHeight, headerHeight)
let maxHeight = collectionView.frame.height - headerHeight - strechyHeight
let height = collectionView.frame.height - headerHeight + collectionView.contentOffset.y
attributes.frame = CGRect(origin: CGPoint(x: 0, y: y),
size: CGSize(width: attributes.frame.width,
height: max(maxHeight, height)))
break
}
} else {
switch type {
case .staticHeader:
let originY = headerHeight - attributes.frame.height + max(0, collectionView.contentOffset.y - headerHeight + settings.headerMinimumHeight)
attributes.frame = CGRect(origin: CGPoint(x: 0, y: originY),
size: attributes.size)
break
case .header:
attributes.transform = .identity
let originY = max(0, collectionView.contentOffset.y - headerHeight + settings.headerMinimumHeight)
attributes.frame = CGRect(origin: CGPoint(x: 0, y: originY),
size: attributes.frame.size)
break
case .cell:
let originY = max(headerHeight, collectionView.contentOffset.y + settings.headerMinimumHeight)
attributes.frame = CGRect(origin: CGPoint(x: 0, y: originY),
size: CGSize(width: attributes.frame.width,
height: collectionView.frame.height - originY + collectionView.contentOffset.y))
break
}
}
}
// MARK: - Layout Details
override public func prepare() {
guard let collectionView = collectionView as? CollapseCollectionView, cache.isEmpty else {
return
}
prepareCache()
let maxHeight = ceil(collectionView.frame.height + settings.headerSize.height - settings.headerMinimumHeight)
contentSize = CGSize(width: collectionView.frame.width, height: maxHeight)
oldBounds = collectionView.bounds
let staticHeaderAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: Element.staticHeader.kind,
with: IndexPath(item: 0, section: 0))
if let staticHeaderSize = delegate?.collapseCollectionView?(collectionView, layout: self, sizeForStaticHeaderAt: IndexPath(item: 0, section: 0)) {
prepareElement(size: staticHeaderSize, type: .staticHeader, attributes: staticHeaderAttributes)
} else {
prepareElement(size: CGSize(width: collectionView.bounds.width, height: 0), type: .staticHeader, attributes: staticHeaderAttributes)
}
let headerAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: Element.header.kind,
with: IndexPath(item: 0, section: 0))
prepareElement(size: settings.headerSize, type: .header, attributes: headerAttributes)
for item in 0 ..< collectionView.numberOfItems(inSection: 0) {
let cellIndexPath = IndexPath(item: item, section: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWith: cellIndexPath)
let size = CGSize(width: collectionView.bounds.width,
height: collectionView.bounds.height - settings.headerMinimumHeight)
prepareElement(size: size, type: .cell, attributes: attributes)
}
}
// MARK: - Invalidation
override func shouldInvalidateLayout (forBoundsChange newBounds : CGRect) -> Bool {
return true
}
// MARK: - ContentOffset
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
return CGPoint.zero
}
}
|
//
// PXInitSearchBody.swift
// MercadoPagoSDK
//
// Created by Esteban Adrian Boffa on 11/08/2019.
//
import Foundation
import UIKit
struct PXInitBody: Codable {
let preference: PXCheckoutPreference?
let publicKey: String
let flow: String?
let cardsWithESC: [String]
let charges: [PXPaymentTypeChargeRule]
let discountConfiguration: PXDiscountParamsConfiguration?
let features: PXInitFeatures
init(preference: PXCheckoutPreference?, publicKey: String, flow: String?, cardsWithESC: [String], charges: [PXPaymentTypeChargeRule], discountConfiguration: PXDiscountParamsConfiguration?, features: PXInitFeatures) {
self.preference = preference
self.publicKey = publicKey
self.flow = flow
self.cardsWithESC = cardsWithESC
self.charges = charges
self.discountConfiguration = discountConfiguration
self.features = features
}
enum CodingKeys: String, CodingKey {
case preference
case publicKey = "public_key"
case flow = "flow"
case cardsWithESC = "cards_with_esc"
case charges
case discountConfiguration = "discount_configuration"
case features
}
public func toJSON() throws -> Data {
let encoder = JSONEncoder()
return try encoder.encode(self)
}
}
struct PXInitFeatures: Codable {
let oneTap: Bool
let split: Bool
let odr: Bool
let comboCard: Bool
let hybridCard: Bool
let validationPrograms: [String]
init(oneTap: Bool = true, split: Bool, odr: Bool = true, comboCard: Bool = false, hybridCard: Bool = false, validationPrograms: [String] = []) {
self.oneTap = oneTap
self.split = split
self.odr = odr
self.comboCard = comboCard
self.hybridCard = hybridCard
self.validationPrograms = validationPrograms
}
enum CodingKeys: String, CodingKey {
case oneTap = "one_tap"
case split = "split"
case odr
case comboCard = "combo_card"
case hybridCard = "hybrid_card"
case validationPrograms = "validations_programs"
}
}
Update PXInitSearchBody.swift
//
// PXInitSearchBody.swift
// MercadoPagoSDK
//
// Created by Esteban Adrian Boffa on 11/08/2019.
//
import Foundation
import UIKit
struct PXInitBody: Codable {
let preference: PXCheckoutPreference?
let publicKey: String
let flow: String?
let cardsWithESC: [String]
let charges: [PXPaymentTypeChargeRule]
let discountConfiguration: PXDiscountParamsConfiguration?
let features: PXInitFeatures
init(preference: PXCheckoutPreference?, publicKey: String, flow: String?, cardsWithESC: [String], charges: [PXPaymentTypeChargeRule], discountConfiguration: PXDiscountParamsConfiguration?, features: PXInitFeatures) {
self.preference = preference
self.publicKey = publicKey
self.flow = flow
self.cardsWithESC = cardsWithESC
self.charges = charges
self.discountConfiguration = discountConfiguration
self.features = features
}
enum CodingKeys: String, CodingKey {
case preference
case publicKey = "public_key"
case flow = "flow"
case cardsWithESC = "cards_with_esc"
case charges
case discountConfiguration = "discount_configuration"
case features
}
public func toJSON() throws -> Data {
let encoder = JSONEncoder()
return try encoder.encode(self)
}
}
struct PXInitFeatures: Codable {
let oneTap: Bool
let split: Bool
let odr: Bool
let comboCard: Bool
let hybridCard: Bool
let validationPrograms: [String]
let pix: Bool
init(oneTap: Bool = true, split: Bool, odr: Bool = true, comboCard: Bool = false, hybridCard: Bool = false, validationPrograms: [String] = []) {
self.oneTap = oneTap
self.split = split
self.odr = odr
self.comboCard = comboCard
self.hybridCard = hybridCard
self.validationPrograms = validationPrograms
self.pix = pix
}
enum CodingKeys: String, CodingKey {
case oneTap = "one_tap"
case split = "split"
case odr
case comboCard = "combo_card"
case hybridCard = "hybrid_card"
case validationPrograms = "validations_programs"
}
}
|
import Darwin
extension Tensor {
public var softmax: Tensor {
let exps = exp
let sum = exps.elements.reduce(0.0, combine: +)
return exps / sum
}
public var relu: Tensor {
return Tensor(shape: shape, elements: elements.map { fmax($0, 0.0) })
}
}
extension Tensor {
public func maxPool(ksize ksize: [Int], strides: [Int]) -> Tensor { // padding = Same
assert(shape.dimensions.count == 4, "`shape.dimensions.count` must be 4: \(shape.dimensions.count)")
assert(ksize.count >= 4, "`ksize.count` must be greater than or equal to 4: \(ksize.count)")
assert(strides.count >= 4, "`strides.count` must be greater than or equal to 4: \(strides.count)")
assert(strides[0] == 1 ,"`strides[0]` must be 1")
assert(strides[3] == 1 ,"`strides[3]` must be 1")
assert(ksize[0] == 1 ,"`ksize[0]` must be 1")
assert(ksize[3] == 1 ,"`ksize[3]` must be 1")
let numBatches = Int(ceil(Float(shape.dimensions[0].value) / Float(strides[0])))
let numCols = Int(ceil(Float(shape.dimensions[1].value) / Float(strides[1])))
let numRows = Int(ceil(Float(shape.dimensions[2].value) / Float(strides[2])))
let numChannels = Int(ceil(Float(shape.dimensions[3].value) / Float(strides[3])))
let padAlongHeight = (numCols - 1) * strides[1] + ksize[1] - shape.dimensions[1].value
let padAlongWidth = (numRows - 1) * strides[2] + ksize[2] - shape.dimensions[2].value
let padTop = padAlongHeight / 2
let padBottom = padAlongHeight - padTop
let padLeft = padAlongWidth / 2
let padRight = padAlongWidth - padLeft
var elements: [Element] = []
elements.reserveCapacity(numBatches * numCols * numRows * numChannels)
for batch in 0.stride(to: shape.dimensions[0].value, by: strides[0]) {
var es: [Element] = Array.init(count: shape.dimensions[3].value, repeatedValue: 0)
for y in (0-padTop).stride(to: shape.dimensions[1].value+padBottom-ksize[1]+1, by: strides[1]) {
for x in (0-padLeft).stride(to: shape.dimensions[2].value+padRight-ksize[2]+1, by: strides[2]) {
for j in 0..<ksize[1] {
if y+j < 0 || y+j >= shape.dimensions[1].value {
continue
}
for i in 0..<ksize[2] {
if x+i < 0 || x+i >= shape.dimensions[2].value {
continue
}
es = es.enumerate().map { $0.element < self[batch, y+j, x+i, $0.index] ? self[batch, y+j, x+i, $0.index] : $0.element }
}
}
for e in es {
elements.append(e)
}
}
}
}
return Tensor(shape: [Dimension(numBatches) ,Dimension(numCols), Dimension(numRows), Dimension(numChannels)], elements: elements)
}
public func conv2d(filter filter: Tensor, strides: [Int]) -> Tensor { // padding = Same
assert(shape.dimensions.count == 4, "`shape.dimensions.count` must be 4: \(shape.dimensions.count)")
assert(filter.shape.dimensions.count == 4, "`filter.shape.dimensions.count` must be 4: \(filter.shape.dimensions.count)")
assert(strides.count >= 4, "`strides.count` must be greater than or equal to 4: \(strides.count)")
assert(strides[0] == 1 ,"`strides[0]` must be 1")
assert(strides[3] == 1 ,"`strides[3]` must be 1")
let numBatches = Int(ceil(Float(shape.dimensions[0].value) / Float(strides[0])))
let numRows = Int(ceil(Float(shape.dimensions[1].value) / Float(strides[1])))
let numCols = Int(ceil(Float(shape.dimensions[2].value) / Float(strides[2])))
let numOutChannels = filter.shape.dimensions[3].value
let padAlongHeight = (numRows - 1) * strides[1] + filter.shape.dimensions[0].value - shape.dimensions[1].value
let padAlongWidth = (numCols - 1) * strides[2] + filter.shape.dimensions[1].value - shape.dimensions[2].value
let padTop = padAlongHeight / 2
let padLeft = padAlongWidth / 2
let elements = [Element](count: numBatches * numCols * numRows * numOutChannels, repeatedValue: 0)
// https://www.tensorflow.org/versions/r0.7/api_docs/python/nn.html#conv2d
// output[b, i, j, k] =
// sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] *
// filter[di, dj, q, k]
for b in 0..<numBatches {
// インデックス計算を途中までaccumulate
let selfIndexB = b * shape.dimensions[1].value
var pointerIndexI = b * numRows
for i in 0..<numRows {
for di in 0..<filter.shape.dimensions[0].value { // filter height
let y = strides[1]*i+di - padTop
if(y<0){
continue
}
if(y>=self.shape.dimensions[1].value){
// Yが大きい場合それ以降も常に大きいのでbreak
break
}
// インデックス計算を途中までaccumulate
let selfIndexY = (selfIndexB + y) * shape.dimensions[2].value
let filterIndexDI = di * filter.shape.dimensions[1].value
var pointerIndexJ = pointerIndexI * numCols
for j in 0..<numCols {
// xが確定する前にポインタを作れる(=xもシーケンシャルアクセス)
let selfIndex = (selfIndexY + max(0, strides[2]*j - padLeft)) * shape.dimensions[3].value
var selfPointer = UnsafeMutablePointer<Element>(self.elements) + selfIndex
for dj in 0..<filter.shape.dimensions[1].value { // filter width
let x = strides[2]*j+dj - padLeft
if(x < 0 || x>=self.shape.dimensions[2].value){
continue
}
// filterのポインタ
let filterIndex = (filterIndexDI + dj) * filter.shape.dimensions[2].value * filter.shape.dimensions[3].value
var filterPointer = UnsafeMutablePointer<Element>(filter.elements) + filterIndex
for _ in 0..<filter.shape.dimensions[2].value { // in channelss (loop of q)
// elementsのポインタ
var pointer = UnsafeMutablePointer<Element>(elements) + pointerIndexJ * numOutChannels
for _ in 0..<numOutChannels { // loop of k
pointer.memory += selfPointer.memory * filterPointer.memory
// kの増加でインクリメント
pointer += 1
filterPointer += 1
}
// qの増加でインクリメント
selfPointer += 1
}
}
pointerIndexJ += 1
}
}
pointerIndexI += 1
}
}
return Tensor(shape: [Dimension(numBatches) ,Dimension(numRows), Dimension(numCols), Dimension(numOutChannels)], elements: elements)
}
}
Rewrite comments in English.
import Darwin
extension Tensor {
public var softmax: Tensor {
let exps = exp
let sum = exps.elements.reduce(0.0, combine: +)
return exps / sum
}
public var relu: Tensor {
return Tensor(shape: shape, elements: elements.map { fmax($0, 0.0) })
}
}
extension Tensor {
public func maxPool(ksize ksize: [Int], strides: [Int]) -> Tensor { // padding = Same
assert(shape.dimensions.count == 4, "`shape.dimensions.count` must be 4: \(shape.dimensions.count)")
assert(ksize.count >= 4, "`ksize.count` must be greater than or equal to 4: \(ksize.count)")
assert(strides.count >= 4, "`strides.count` must be greater than or equal to 4: \(strides.count)")
assert(strides[0] == 1 ,"`strides[0]` must be 1")
assert(strides[3] == 1 ,"`strides[3]` must be 1")
assert(ksize[0] == 1 ,"`ksize[0]` must be 1")
assert(ksize[3] == 1 ,"`ksize[3]` must be 1")
let numBatches = Int(ceil(Float(shape.dimensions[0].value) / Float(strides[0])))
let numCols = Int(ceil(Float(shape.dimensions[1].value) / Float(strides[1])))
let numRows = Int(ceil(Float(shape.dimensions[2].value) / Float(strides[2])))
let numChannels = Int(ceil(Float(shape.dimensions[3].value) / Float(strides[3])))
let padAlongHeight = (numCols - 1) * strides[1] + ksize[1] - shape.dimensions[1].value
let padAlongWidth = (numRows - 1) * strides[2] + ksize[2] - shape.dimensions[2].value
let padTop = padAlongHeight / 2
let padBottom = padAlongHeight - padTop
let padLeft = padAlongWidth / 2
let padRight = padAlongWidth - padLeft
var elements: [Element] = []
elements.reserveCapacity(numBatches * numCols * numRows * numChannels)
for batch in 0.stride(to: shape.dimensions[0].value, by: strides[0]) {
var es: [Element] = Array.init(count: shape.dimensions[3].value, repeatedValue: 0)
for y in (0-padTop).stride(to: shape.dimensions[1].value+padBottom-ksize[1]+1, by: strides[1]) {
for x in (0-padLeft).stride(to: shape.dimensions[2].value+padRight-ksize[2]+1, by: strides[2]) {
for j in 0..<ksize[1] {
if y+j < 0 || y+j >= shape.dimensions[1].value {
continue
}
for i in 0..<ksize[2] {
if x+i < 0 || x+i >= shape.dimensions[2].value {
continue
}
es = es.enumerate().map { $0.element < self[batch, y+j, x+i, $0.index] ? self[batch, y+j, x+i, $0.index] : $0.element }
}
}
for e in es {
elements.append(e)
}
}
}
}
return Tensor(shape: [Dimension(numBatches) ,Dimension(numCols), Dimension(numRows), Dimension(numChannels)], elements: elements)
}
public func conv2d(filter filter: Tensor, strides: [Int]) -> Tensor { // padding = Same
assert(shape.dimensions.count == 4, "`shape.dimensions.count` must be 4: \(shape.dimensions.count)")
assert(filter.shape.dimensions.count == 4, "`filter.shape.dimensions.count` must be 4: \(filter.shape.dimensions.count)")
assert(strides.count >= 4, "`strides.count` must be greater than or equal to 4: \(strides.count)")
assert(strides[0] == 1 ,"`strides[0]` must be 1")
assert(strides[3] == 1 ,"`strides[3]` must be 1")
let numBatches = Int(ceil(Float(shape.dimensions[0].value) / Float(strides[0])))
let numRows = Int(ceil(Float(shape.dimensions[1].value) / Float(strides[1])))
let numCols = Int(ceil(Float(shape.dimensions[2].value) / Float(strides[2])))
let numOutChannels = filter.shape.dimensions[3].value
let padAlongHeight = (numRows - 1) * strides[1] + filter.shape.dimensions[0].value - shape.dimensions[1].value
let padAlongWidth = (numCols - 1) * strides[2] + filter.shape.dimensions[1].value - shape.dimensions[2].value
let padTop = padAlongHeight / 2
let padLeft = padAlongWidth / 2
let imageWidth = shape.dimensions[2].value
let imageHeight = shape.dimensions[1].value
let numInChannels = shape.dimensions[3].value
let filterWidth = filter.shape.dimensions[1].value
let filterHeight = filter.shape.dimensions[0].value
let z = Tensor(shape: [Dimension(numBatches), Dimension(numRows), Dimension(numCols), Dimension(numOutChannels)])
// https://www.tensorflow.org/versions/r0.7/api_docs/python/nn.html#conv2d
// output[b, i, j, k] =
// sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] *
// filter[di, dj, q, k]
for b in 0..<numBatches {
// Accumulate index calculation
let selfIndexB = b * imageHeight
var pointerIndexI = b * numRows
for i in 0..<numRows {
for di in 0..<filterHeight {
let y = strides[1]*i+di - padTop
if(y<0){
continue
}
if(y>=imageHeight){
// If y is larger, it will never be smaller in this di loop.
break
}
// Accumulate index calculation
let selfIndexY = (selfIndexB + y) * imageWidth
let filterIndexDI = di * filterWidth
var pointerIndexJ = pointerIndexI * numCols
for j in 0..<numCols {
// Can get pointer before calculate x.
let selfIndex = (selfIndexY + max(0, strides[2]*j - padLeft)) * numInChannels
var selfPointer = UnsafeMutablePointer<Element>(self.elements) + selfIndex
for dj in 0..<filterWidth {
let x = strides[2]*j+dj - padLeft
if(x < 0 || x>=imageWidth){
continue
}
// Pointer of filter
let filterIndex = (filterIndexDI + dj) * numInChannels * numOutChannels
var filterPointer = UnsafeMutablePointer<Element>(filter.elements) + filterIndex
for _ in 0..<numInChannels { // Loop of q
// Pointer of elements
var pointer = UnsafeMutablePointer<Element>(z.elements) + pointerIndexJ * numOutChannels
for _ in 0..<numOutChannels { // Loop of k
pointer.memory += selfPointer.memory * filterPointer.memory
// Increment by k's grow
pointer += 1
filterPointer += 1
}
// Increment by q's grow
selfPointer += 1
}
}
pointerIndexJ += 1
}
}
pointerIndexI += 1
}
}
return z
}
} |
// Copyright (c) 2015 Rob Rix. All rights reserved.
public typealias Error = (Identifier, String)
private func error(reason: String, from: Identifier) -> Either<Error, Value> {
return .left((from, reason))
}
public func evaluate(graph: Graph<Node>, from: Identifier, environment: Environment = Prelude) -> Either<Error, Value> {
return evaluate(graph, from, environment, [:])
}
private func evaluate(graph: Graph<Node>, from: Identifier, environment: Environment, visited: [Identifier: Value]) -> Either<Error, Value> {
return
visited[from].map(Either.right)
?? graph.nodes[from].map { evaluate(graph, from, environment, visited, $0) }
?? error("could not find identifier in graph", from)
}
private func evaluate(graph: Graph<Node>, from: Identifier, environment: Environment, visited: [Identifier: Value], node: Node) -> Either<Error, Value> {
let inputs = lazy(graph.edges)
.filter { $0.destination.identifier == from }
.map { ($0.destination, graph.nodes[$0.source.identifier]!) }
|> (flip(sorted) <| { $0.0 < $1.0 })
switch node {
case let .Symbolic(symbol):
return environment[symbol].map(Either.right) ?? error("\(symbol) not found in environment", from)
case .Parameter:
break
case .Return where inputs.count != 1:
return error("expected one return edge, but \(inputs.count) were found", from)
case .Return:
return evaluate(graph, inputs[0].0.identifier, environment, visited)
}
return error("don’t know how to evaluate \(node)", from)
}
// MARK: - Imports
import Either
import Prelude
Apply all symbolic values.
// Copyright (c) 2015 Rob Rix. All rights reserved.
public typealias Error = (Identifier, String)
private func error(reason: String, from: Identifier) -> Either<Error, Value> {
return .left((from, reason))
}
public func evaluate(graph: Graph<Node>, from: Identifier, environment: Environment = Prelude) -> Either<Error, Value> {
return evaluate(graph, from, environment, [:])
}
private func evaluate(graph: Graph<Node>, from: Identifier, environment: Environment, visited: [Identifier: Value]) -> Either<Error, Value> {
return
visited[from].map(Either.right)
?? graph.nodes[from].map { evaluate(graph, from, environment, visited, $0) }
?? error("could not find identifier in graph", from)
}
private func evaluate(graph: Graph<Node>, from: Identifier, environment: Environment, visited: [Identifier: Value], node: Node) -> Either<Error, Value> {
let inputs = lazy(graph.edges)
.filter { $0.destination.identifier == from }
.map { ($0.destination, graph.nodes[$0.source.identifier]!) }
|> (flip(sorted) <| { $0.0 < $1.0 })
switch node {
case let .Symbolic(symbol):
return environment[symbol].map((flip(apply) <| inputs) >>> Either.right) ?? error("\(symbol) not found in environment", from)
case .Parameter:
break
case .Return where inputs.count != 1:
return error("expected one return edge, but \(inputs.count) were found", from)
case .Return:
return evaluate(graph, inputs[0].0.identifier, environment, visited)
}
return error("don’t know how to evaluate \(node)", from)
}
// MARK: - Imports
import Either
import Prelude
|
//
// BarcodeDisplayViewController.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 15/1/17.
//
// Updated by Jarvie8176 on 01/21/2016
//
// Copyright (c) 2015年 P.D.Q. All rights reserved.
//
import UIKit
import AVFoundation
import RSBarcodes
class BarcodeDisplayViewController: UIViewController {
@IBOutlet weak var imageDisplayed: UIImageView!
var contents: String = "https://github.com/VMwareFusion/nautilus"
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = contents
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: false)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let gen = RSUnifiedCodeGenerator.shared
gen.fillColor = UIColor.white
gen.strokeColor = UIColor.black
print ("generating image with barcode: " + contents)
if let image = gen.generateCode("Text Example", machineReadableCodeObjectType: AVMetadataObject.ObjectType.qr.rawValue, targetSize: CGSize(width: 1000, height: 1000)) {
debugPrint(image.size)
self.imageDisplayed.layer.borderWidth = 1
self.imageDisplayed.image = RSAbstractCodeGenerator.resizeImage(image, targetSize: self.imageDisplayed.bounds.size, contentMode: UIView.ContentMode.bottomRight)
}
}
}
Update sample qr string value
//
// BarcodeDisplayViewController.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 15/1/17.
//
// Updated by Jarvie8176 on 01/21/2016
//
// Copyright (c) 2015年 P.D.Q. All rights reserved.
//
import UIKit
import AVFoundation
import RSBarcodes
class BarcodeDisplayViewController: UIViewController {
@IBOutlet weak var imageDisplayed: UIImageView!
var contents: String = "https://github.com/yeahdongcn/"
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = contents
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: false)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let gen = RSUnifiedCodeGenerator.shared
gen.fillColor = UIColor.white
gen.strokeColor = UIColor.black
print ("generating image with barcode: " + contents)
if let image = gen.generateCode("Text Example", machineReadableCodeObjectType: AVMetadataObject.ObjectType.qr.rawValue, targetSize: CGSize(width: 1000, height: 1000)) {
debugPrint(image.size)
self.imageDisplayed.layer.borderWidth = 1
self.imageDisplayed.image = RSAbstractCodeGenerator.resizeImage(image, targetSize: self.imageDisplayed.bounds.size, contentMode: UIView.ContentMode.bottomRight)
}
}
}
|
import UIKit
public class SnapImagePickerViewController: UIViewController {
@IBOutlet weak var mainScrollView: UIScrollView? {
didSet {
mainScrollView?.bounces = false
mainScrollView?.delegate = self
}
}
@IBOutlet weak var selectedImageScrollView: UIScrollView? {
didSet {
selectedImageScrollView?.delegate = self
selectedImageScrollView?.minimumZoomScale = 1.0
selectedImageScrollView?.maximumZoomScale = currentDisplay.MaxZoomScale
}
}
@IBOutlet weak var selectedImageScrollViewHeightToFrameWidthAspectRatioConstraint: NSLayoutConstraint?
@IBOutlet weak var selectedImageView: UIImageView?
private var selectedImage: SnapImagePickerImage? {
didSet {
if let selectedImage = selectedImage {
selectedImageView?.image = selectedImage.image
}
}
}
@IBOutlet weak var albumCollectionView: UICollectionView? {
didSet {
albumCollectionView?.delegate = self
albumCollectionView?.dataSource = self
}
}
@IBOutlet weak var albumCollectionViewHeightConstraint: NSLayoutConstraint?
@IBOutlet weak var albumCollectionWidthConstraint: NSLayoutConstraint?
@IBOutlet weak var imageGridView: ImageGridView? {
didSet {
imageGridView?.userInteractionEnabled = false
}
}
@IBOutlet weak var imageGridViewWidthConstraint: NSLayoutConstraint?
@IBOutlet weak var blackOverlayView: UIView? {
didSet {
blackOverlayView?.userInteractionEnabled = false
blackOverlayView?.alpha = 0.0
}
}
@IBOutlet weak var mainImageLoadIndicator: UIActivityIndicatorView?
@IBOutlet weak var rotateButton: UIButton?
@IBOutlet weak var rotateButtonLeadingConstraint: NSLayoutConstraint?
@IBAction func rotateButtonPressed(sender: UIButton) {
UIView.animateWithDuration(0.3, animations: {
self.selectedImageRotation = self.selectedImageRotation.next()
sender.enabled = false
}, completion: {
_ in sender.enabled = true
})
}
private var _delegate: SnapImagePickerDelegate?
var eventHandler: SnapImagePickerEventHandlerProtocol?
var albumTitle = L10n.AllPhotosAlbumName.string {
didSet {
visibleCells = nil
setupTitleButton()
}
}
private var currentlySelectedIndex = 0 {
didSet {
scrollToIndex(currentlySelectedIndex)
}
}
private var selectedImageRotation = UIImageOrientation.Up {
didSet {
self.selectedImageScrollView?.transform = CGAffineTransformMakeRotation(CGFloat(self.selectedImageRotation.toCGAffineTransformRadians()))
}
}
private var state: DisplayState = .Image {
didSet {
let imageInteractionEnabled = (state == .Image)
rotateButton?.enabled = imageInteractionEnabled
selectedImageScrollView?.userInteractionEnabled = imageInteractionEnabled
setVisibleCellsInAlbumCollectionView()
setMainOffsetForState(state)
}
}
private var currentDisplay = Display.Portrait {
didSet {
albumCollectionWidthConstraint =
albumCollectionWidthConstraint?.changeMultiplier(currentDisplay.AlbumCollectionWidthMultiplier)
albumCollectionView?.reloadData()
selectedImageScrollViewHeightToFrameWidthAspectRatioConstraint =
selectedImageScrollViewHeightToFrameWidthAspectRatioConstraint?.changeMultiplier(currentDisplay.SelectedImageWidthMultiplier)
imageGridViewWidthConstraint =
imageGridViewWidthConstraint?.changeMultiplier(currentDisplay.SelectedImageWidthMultiplier)
setRotateButtonConstraint()
}
}
private func setRotateButtonConstraint() {
let ratioNotCoveredByImage = (1 - currentDisplay.SelectedImageWidthMultiplier)
let widthNotCoveredByImage = ratioNotCoveredByImage * view.frame.width
let selectedImageStart = widthNotCoveredByImage / 2
rotateButtonLeadingConstraint?.constant = selectedImageStart + 20
}
private var visibleCells: Range<Int>? {
didSet {
if let visibleCells = visibleCells where oldValue != visibleCells {
let increasing = oldValue?.startIndex < visibleCells.startIndex
eventHandler?.scrolledToCells(visibleCells, increasing: increasing)
}
}
}
private var userIsScrolling = false
private var enqueuedBounce: (() -> Void)?
override public func viewDidLoad() {
super.viewDidLoad()
calculateViewSizes()
setupGestureRecognizers()
setupTitleButton()
automaticallyAdjustsScrollViewInsets = false
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
currentDisplay = view.frame.size.displayType()
let width = currentDisplay.CellWidthInViewWithWidth(view.bounds.width)
eventHandler?.viewWillAppearWithCellSize(CGSize(width: width, height: width))
selectedImageScrollView?.userInteractionEnabled = true
}
override public func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
setVisibleCellsInAlbumCollectionView()
if let selectedImage = selectedImage {
self.selectedImage = nil
displayMainImage(selectedImage)
}
}
override public func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
let newDisplay = size.displayType()
if newDisplay != currentDisplay {
let ratio = newDisplay.SelectedImageWidthMultiplier / currentDisplay.SelectedImageWidthMultiplier
let offsetRatio = ratio * ((newDisplay == .Landscape) ? 1 * 1.33 : 1 / 1.33)
let newOffset = selectedImageScrollView!.contentOffset * offsetRatio
coordinator.animateAlongsideTransition({
[weak self] _ in
if let strongSelf = self,
let selectedImageScrollView = strongSelf.selectedImageScrollView {
let height = selectedImageScrollView.frame.height
let newHeight = height * ratio
strongSelf.setMainOffsetForState(strongSelf.state, withHeight: newHeight, animated: false)
}
self?.selectedImageScrollView?.setContentOffset(newOffset, animated: true)
self?.currentDisplay = newDisplay
self?.setVisibleCellsInAlbumCollectionView()
self?.calculateViewSizes()
}, completion: {
[weak self] _ in
if let size = self?.selectedImage?.image.size {
let zoomScale = self?.selectedImageScrollView?.zoomScale ?? 1.0
let insets = self?.getInsetsForSize(size, withZoomScale: zoomScale) ?? UIEdgeInsetsZero
self?.selectedImageScrollView?.contentInset = insets
}
})
}
}
}
extension SnapImagePickerViewController: SnapImagePickerProtocol {
public var delegate: SnapImagePickerDelegate? {
get {
return _delegate
}
set {
_delegate = newValue
}
}
public static func initializeWithCameraRollAccess(cameraRollAccess: Bool) -> SnapImagePickerViewController? {
let bundle = NSBundle(forClass: SnapImagePickerViewController.self)
let storyboard = UIStoryboard(name: SnapImagePickerConnector.Names.SnapImagePickerStoryboard.rawValue, bundle: bundle)
if let snapImagePickerViewController = storyboard.instantiateInitialViewController() as? SnapImagePickerViewController {
let presenter = SnapImagePickerPresenter(view: snapImagePickerViewController, cameraRollAccess: cameraRollAccess)
snapImagePickerViewController.eventHandler = presenter
snapImagePickerViewController.cameraRollAccess = cameraRollAccess
return snapImagePickerViewController
}
return nil
}
public var cameraRollAccess: Bool {
get {
return eventHandler?.cameraRollAccess ?? false
}
set {
eventHandler?.cameraRollAccess = newValue
if !newValue {
selectedImageView?.image = nil
selectedImage = nil
albumCollectionView?.reloadData()
}
}
}
public func reload() {
let width = self.currentDisplay.CellWidthInViewWithWidth(view.bounds.width)
eventHandler?.viewWillAppearWithCellSize(CGSize(width: width, height: width))
if let visibleCells = visibleCells {
eventHandler?.scrolledToCells(visibleCells, increasing: true)
} else {
setVisibleCellsInAlbumCollectionView()
}
}
public func getCurrentImage() -> (image: UIImage, options: ImageOptions)? {
if let scrollView = selectedImageScrollView,
let image = selectedImage?.image {
if image.size.height > image.size.width {
let viewRatio = image.size.width / scrollView.contentSize.width
let diff = (image.size.height - image.size.width) / 2
let cropRect = CGRect(x: scrollView.contentOffset.x * viewRatio,
y: (scrollView.contentOffset.y * viewRatio) + diff,
width: scrollView.bounds.width * viewRatio,
height: scrollView.bounds.height * viewRatio)
let options = ImageOptions(cropRect: cropRect, rotation: selectedImageRotation)
return (image: image, options: options)
} else {
let viewRatio = image.size.height / scrollView.contentSize.height
let diff = (image.size.width - image.size.height) / 2
let cropRect = CGRect(x: (scrollView.contentOffset.x * viewRatio) + diff,
y: (scrollView.contentOffset.y * viewRatio),
width: scrollView.bounds.width * viewRatio,
height: scrollView.bounds.height * viewRatio)
let options = ImageOptions(cropRect: cropRect, rotation: selectedImageRotation)
return (image: image, options: options)
}
}
return nil
}
}
extension SnapImagePickerViewController {
func albumTitlePressed() {
eventHandler?.albumTitlePressed(self.navigationController)
}
private func setupTitleButton() {
var title = albumTitle
if albumTitle == AlbumType.AllPhotos.getAlbumName() {
title = L10n.AllPhotosAlbumName.string
} else if albumTitle == AlbumType.Favorites.getAlbumName() {
title = L10n.FavoritesAlbumName.string
}
let button = UIButton()
setupTitleButtonTitle(button, withTitle: title)
setupTitleButtonImage(button)
button.addTarget(self, action: #selector(albumTitlePressed), forControlEvents: .TouchUpInside)
navigationItem.titleView = button
delegate?.setTitleView(button)
}
private func setupTitleButtonTitle(button: UIButton, withTitle title: String) {
button.titleLabel?.font = SnapImagePickerTheme.font
button.setTitle(title, forState: .Normal)
button.setTitleColor(UIColor.blackColor(), forState: .Normal)
button.setTitleColor(UIColor.init(red: 0xB8/0xFF, green: 0xB8/0xFF, blue: 0xB8/0xFF, alpha: 1), forState: .Highlighted)
}
private func setupTitleButtonImage(button: UIButton) {
if let mainImage = UIImage(named: "icon_s_arrow_down_gray", inBundle: NSBundle(forClass: SnapImagePickerViewController.self), compatibleWithTraitCollection: nil),
let mainCgImage = mainImage.CGImage,
let navBarHeight = navigationController?.navigationBar.frame.height {
let scale = mainImage.findRoundedScale(mainImage.size.height / (navBarHeight / 6))
let scaledMainImage = UIImage(CGImage: mainCgImage, scale: scale, orientation: .Up)
let scaledHighlightedImage = scaledMainImage.setAlpha(0.3)
button.setImage(scaledMainImage, forState: .Normal)
button.setImage(scaledHighlightedImage, forState: .Highlighted)
button.frame = CGRect(x: 0, y: 0, width: scaledHighlightedImage.size.width, height: scaledHighlightedImage.size.height)
button.rightAlignImage(scaledHighlightedImage)
}
}
private func calculateViewSizes() {
if let mainScrollView = mainScrollView {
let mainFrame = mainScrollView.frame
let imageSizeWhenDisplayed = view.frame.width * CGFloat(currentDisplay.SelectedImageWidthMultiplier) * CGFloat(DisplayState.Album.offset)
let imageSizeWhenHidden = view.frame.width * CGFloat(currentDisplay.SelectedImageWidthMultiplier) * (1 - CGFloat(DisplayState.Album.offset))
mainScrollView.contentSize = CGSize(width: mainFrame.width, height: mainFrame.height + imageSizeWhenDisplayed)
albumCollectionViewHeightConstraint?.constant = view.frame.height - imageSizeWhenHidden - currentDisplay.NavBarHeight
}
}
}
extension SnapImagePickerViewController: SnapImagePickerViewControllerProtocol {
func displayMainImage(mainImage: SnapImagePickerImage) {
let size = mainImage.image.size
if selectedImage == nil
|| mainImage.localIdentifier != selectedImage!.localIdentifier
|| size.height > selectedImage!.image.size.height {
setMainImage(mainImage)
selectedImageScrollView?.contentInset = getInsetsForSize(size)
selectedImageScrollView?.minimumZoomScale = min(size.width, size.height) / max(size.width, size.height)
selectedImageScrollView?.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
selectedImageScrollView?.setZoomScale(1, animated: false)
}
if state != .Image {
state = .Image
}
mainImageLoadIndicator?.stopAnimating()
}
private func setMainImage(mainImage: SnapImagePickerImage) {
selectedImageView?.contentMode = .ScaleAspectFill
selectedImage = mainImage
selectedImageRotation = .Up
}
private func getInsetsForSize(size: CGSize, withZoomScale zoomScale: CGFloat = 1) -> UIEdgeInsets{
if (size.height > size.width) {
return getInsetsForTallRectangle(size, withZoomScale: zoomScale)
} else {
return getInsetsForWideRectangle(size, withZoomScale: zoomScale)
}
}
private func getInsetsForTallRectangle(size: CGSize, withZoomScale zoomScale: CGFloat = 1) -> UIEdgeInsets {
if let scrollView = selectedImageScrollView {
let ratio = scrollView.frame.width / size.width
let imageHeight = size.height * ratio
let diff = imageHeight - scrollView.frame.width
let inset = diff / 2
var insets = UIEdgeInsets(top: inset * zoomScale, left: 0, bottom: inset * zoomScale, right: 0)
let contentWidth = scrollView.contentSize.width
if contentWidth > 0 && contentWidth < scrollView.frame.width {
let padding = CGFloat(scrollView.frame.width - contentWidth) / 2
insets = insets.addHorizontalInset(padding)
}
return insets
}
return UIEdgeInsetsZero
}
private func getInsetsForWideRectangle(size: CGSize, withZoomScale zoomScale: CGFloat = 1) -> UIEdgeInsets {
if let scrollView = selectedImageScrollView {
let ratio = scrollView.frame.width / size.height
let imageWidth = size.width * ratio
let diff = imageWidth - scrollView.frame.width
let inset = diff / 2
var insets = UIEdgeInsets(top: 0, left: inset * zoomScale, bottom: 0, right: inset * zoomScale)
let contentHeight = scrollView.contentSize.height
if contentHeight > 0 && contentHeight < scrollView.frame.width {
let padding = CGFloat(scrollView.frame.width - contentHeight) / 2
insets = insets.addVerticalInset(padding)
}
return insets
}
return UIEdgeInsetsZero
}
func reloadAlbum() {
albumCollectionView?.reloadData()
}
func reloadCellAtIndexes(indexes: [Int]) {
var indexPaths = [NSIndexPath]()
for index in indexes {
indexPaths.append(arrayIndexToIndexPath(index))
}
if indexes.count > 0 {
UIView.performWithoutAnimation() {
self.albumCollectionView?.reloadItemsAtIndexPaths(indexPaths)
}
}
}
}
extension SnapImagePickerViewController: UICollectionViewDataSource {
public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return eventHandler?.numberOfItemsInSection(section) ?? 0
}
public func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let index = indexPathToArrayIndex(indexPath)
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Image Cell", forIndexPath: indexPath)
if let imageCell = cell as? ImageCell {
eventHandler?.presentCell(imageCell, atIndex: index)
}
return cell
}
private func indexPathToArrayIndex(indexPath: NSIndexPath) -> Int {
return indexPath.item
}
private func arrayIndexToIndexPath(index: Int) -> NSIndexPath {
return NSIndexPath(forItem: index, inSection: 0)
}
private func scrollToIndex(index: Int) {
if let albumCollectionView = albumCollectionView {
let row = index / currentDisplay.NumberOfColumns
let offset = CGFloat(row) * (currentDisplay.CellWidthInView(albumCollectionView) + currentDisplay.Spacing)
// Does not scroll to index if there is not enough content to fill the screen
if offset + albumCollectionView.frame.height > albumCollectionView.contentSize.height {
return
}
if offset > 0 {
albumCollectionView.setContentOffset(CGPoint(x: 0, y: offset), animated: true)
}
}
}
}
extension SnapImagePickerViewController: UICollectionViewDelegateFlowLayout {
public func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let size = currentDisplay.CellWidthInView(collectionView)
return CGSizeMake(size, size)
}
}
extension SnapImagePickerViewController: UICollectionViewDelegate {
public func collectionView(collectionView: UICollectionView,
willDisplayCell cell: UICollectionViewCell,
forItemAtIndexPath indexPath: NSIndexPath) {
if visibleCells == nil
|| indexPath.item % currentDisplay.NumberOfColumns == (currentDisplay.NumberOfColumns - 1)
&& !(visibleCells! ~= indexPath.item) {
self.setVisibleCellsInAlbumCollectionView()
}
}
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let index = indexPathToArrayIndex(indexPath)
print("Contentoffset: \(selectedImageScrollView?.contentOffset)")
if eventHandler?.albumImageClicked(index) == true {
scrollToIndex(index)
mainImageLoadIndicator?.startAnimating()
}
}
}
extension SnapImagePickerViewController: UIScrollViewDelegate {
public func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView == mainScrollView {
mainScrollViewDidScroll(scrollView)
} else if scrollView == albumCollectionView {
albumCollectionViewDidScroll(scrollView)
}
}
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return selectedImageView
}
public func scrollViewWillEndDragging(scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
userIsScrolling = false
if scrollView == albumCollectionView && velocity.y != 0.0 && targetContentOffset.memory.y == 0 {
enqueuedBounce = {
self.mainScrollView?.manuallyBounceBasedOnVelocity(velocity)
}
}
}
public func scrollViewWillBeginDragging(scrollView: UIScrollView) {
userIsScrolling = true
if scrollView == selectedImageScrollView {
setImageGridViewAlpha(0.2)
}
}
public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if scrollView == selectedImageScrollView {
setImageGridViewAlpha(0.0)
} else if scrollView == albumCollectionView && !decelerate {
scrolledToOffsetRatio(calculateOffsetToImageHeightRatio())
}
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if scrollView == albumCollectionView && state == .Album {
state = .Album
} else if scrollView == selectedImageScrollView {
setImageGridViewAlpha(0.0)
}
}
public func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView?) {
if scrollView == selectedImageScrollView {
setImageGridViewAlpha(0.2)
}
}
public func scrollViewDidZoom(scrollView: UIScrollView) {
if let size = selectedImage?.image.size {
let zoomScale = selectedImageScrollView?.zoomScale ?? 1.0
selectedImageScrollView?.contentInset = getInsetsForSize(size, withZoomScale: zoomScale)
}
}
public func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
if scrollView == selectedImageScrollView {
setImageGridViewAlpha(0.0)
}
}
}
extension SnapImagePickerViewController {
private func mainScrollViewDidScroll(scrollView: UIScrollView) {
if let albumCollectionView = albumCollectionView {
let remainingAlbumCollectionHeight = albumCollectionView.contentSize.height - albumCollectionView.contentOffset.y
let albumStart = albumCollectionView.frame.minY - scrollView.contentOffset.y
let offset = scrollView.frame.height - (albumStart + remainingAlbumCollectionHeight)
if offset > 0 && albumCollectionView.contentOffset.y - offset > 0 {
albumCollectionView.contentOffset = CGPoint(x: 0, y: albumCollectionView.contentOffset.y - offset)
}
}
}
private func albumCollectionViewDidScroll(scrollView: UIScrollView) {
if let mainScrollView = mainScrollView
where scrollView.contentOffset.y < 0 {
if userIsScrolling {
let y = mainScrollView.contentOffset.y + scrollView.contentOffset.y
mainScrollView.contentOffset = CGPoint(x: mainScrollView.contentOffset.x, y: y)
if let height = selectedImageView?.frame.height {
blackOverlayView?.alpha = (mainScrollView.contentOffset.y / height) * currentDisplay.MaxImageFadeRatio
}
} else if let enqueuedBounce = enqueuedBounce {
enqueuedBounce()
self.enqueuedBounce = nil
}
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: 0)
}
}
private func scrolledToOffsetRatio(ratio: Double) {
if state == .Album && ratio < currentDisplay.OffsetThreshold.end {
state = .Image
} else if state == .Image && ratio > currentDisplay.OffsetThreshold.start {
state = .Album
} else {
setMainOffsetForState(state)
}
}
}
extension SnapImagePickerViewController {
private func setVisibleCellsInAlbumCollectionView() {
if let albumCollectionView = albumCollectionView {
let rowHeight = currentDisplay.CellWidthInView(albumCollectionView) + currentDisplay.Spacing
let topVisibleRow = Int(albumCollectionView.contentOffset.y / rowHeight)
let firstVisibleCell = topVisibleRow * currentDisplay.NumberOfColumns
let imageViewHeight = selectedImageScrollView!.frame.height * CGFloat(1 - state.offset)
let visibleAreaOfAlbumCollectionView = mainScrollView!.frame.height - imageViewHeight
let numberOfVisibleRows = Int(ceil(visibleAreaOfAlbumCollectionView / rowHeight)) + 1
let numberOfVisibleCells = numberOfVisibleRows * currentDisplay.NumberOfColumns
let lastVisibleCell = firstVisibleCell + numberOfVisibleCells
if (lastVisibleCell > firstVisibleCell) {
visibleCells = firstVisibleCell..<lastVisibleCell
}
}
}
private func calculateOffsetToImageHeightRatio() -> Double {
if let offset = mainScrollView?.contentOffset.y,
let height = selectedImageScrollView?.frame.height {
return Double((offset + currentDisplay.NavBarHeight) / height)
}
return 0.0
}
private func setImageGridViewAlpha(alpha: CGFloat) {
UIView.animateWithDuration(0.3) {
[weak self] in self?.imageGridView?.alpha = alpha
}
}
}
extension SnapImagePickerViewController {
private func setupGestureRecognizers() {
removeMainScrollViewPanRecognizers()
setupPanGestureRecognizerForScrollView(mainScrollView)
setupPanGestureRecognizerForScrollView(albumCollectionView)
}
private func removeMainScrollViewPanRecognizers() {
if let recognizers = mainScrollView?.gestureRecognizers {
for recognizer in recognizers {
if recognizer is UIPanGestureRecognizer {
mainScrollView?.removeGestureRecognizer(recognizer)
}
}
}
}
private func setupPanGestureRecognizerForScrollView(scrollView: UIScrollView?) {
let recognizer = UIPanGestureRecognizer(target: self, action: #selector(pan(_:)))
recognizer.delegate = self
scrollView?.addGestureRecognizer(recognizer)
}
func pan(recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .Changed:
panMainScrollViewWithRecognizer(recognizer)
case .Ended, .Cancelled, .Failed:
panEnded()
default: break
}
}
private func panMainScrollViewWithRecognizer(recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translationInView(mainScrollView)
if let mainScrollView = mainScrollView {
let old = mainScrollView.contentOffset.y
let offset = old - translation.y
mainScrollView.setContentOffset(CGPoint(x: 0, y: offset), animated: false)
recognizer.setTranslation(CGPointZero, inView: mainScrollView)
if let height = selectedImageView?.frame.height {
let alpha = (offset / height) * currentDisplay.MaxImageFadeRatio
blackOverlayView?.alpha = alpha
rotateButton?.alpha = 1 - alpha
}
}
}
private func panEnded() {
scrolledToOffsetRatio(calculateOffsetToImageHeightRatio())
}
private func setMainOffsetForState(state: DisplayState, animated: Bool = true) {
if let height = selectedImageScrollView?.bounds.height {
setMainOffsetForState(state, withHeight: height, animated: animated)
}
}
private func setMainOffsetForState(state: DisplayState, withHeight height: CGFloat, animated: Bool = true) {
let offset = (height * CGFloat(state.offset))
if animated {
UIView.animateWithDuration(0.3) {
[weak self] in self?.displayViewStateForOffset(offset, withHeight: height)
}
} else {
displayViewStateForOffset(offset, withHeight: height)
}
}
private func displayViewStateForOffset(offset: CGFloat, withHeight height: CGFloat) {
mainScrollView?.contentOffset = CGPoint(x: 0, y: offset)
blackOverlayView?.alpha = (offset / height) * self.currentDisplay.MaxImageFadeRatio
rotateButton?.alpha = state.rotateButtonAlpha
}
}
extension SnapImagePickerViewController: UIGestureRecognizerDelegate {
public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.view == albumCollectionView {
return state == .Image
} else if gestureRecognizer.view == mainScrollView {
let isInImageView =
gestureRecognizer.locationInView(selectedImageScrollView).y < selectedImageScrollView?.frame.height
if state == .Image && isInImageView {
return false
}
return true
}
return false
}
}
Removed some dead code
import UIKit
public class SnapImagePickerViewController: UIViewController {
@IBOutlet weak var mainScrollView: UIScrollView? {
didSet {
mainScrollView?.bounces = false
mainScrollView?.delegate = self
}
}
@IBOutlet weak var selectedImageScrollView: UIScrollView? {
didSet {
selectedImageScrollView?.delegate = self
selectedImageScrollView?.minimumZoomScale = 1.0
selectedImageScrollView?.maximumZoomScale = currentDisplay.MaxZoomScale
}
}
@IBOutlet weak var selectedImageScrollViewHeightToFrameWidthAspectRatioConstraint: NSLayoutConstraint?
@IBOutlet weak var selectedImageView: UIImageView?
private var selectedImage: SnapImagePickerImage? {
didSet {
if let selectedImage = selectedImage {
selectedImageView?.image = selectedImage.image
}
}
}
@IBOutlet weak var albumCollectionView: UICollectionView? {
didSet {
albumCollectionView?.delegate = self
albumCollectionView?.dataSource = self
}
}
@IBOutlet weak var albumCollectionViewHeightConstraint: NSLayoutConstraint?
@IBOutlet weak var albumCollectionWidthConstraint: NSLayoutConstraint?
@IBOutlet weak var imageGridView: ImageGridView? {
didSet {
imageGridView?.userInteractionEnabled = false
}
}
@IBOutlet weak var imageGridViewWidthConstraint: NSLayoutConstraint?
@IBOutlet weak var blackOverlayView: UIView? {
didSet {
blackOverlayView?.userInteractionEnabled = false
blackOverlayView?.alpha = 0.0
}
}
@IBOutlet weak var mainImageLoadIndicator: UIActivityIndicatorView?
@IBOutlet weak var rotateButton: UIButton?
@IBOutlet weak var rotateButtonLeadingConstraint: NSLayoutConstraint?
@IBAction func rotateButtonPressed(sender: UIButton) {
UIView.animateWithDuration(0.3, animations: {
self.selectedImageRotation = self.selectedImageRotation.next()
sender.enabled = false
}, completion: {
_ in sender.enabled = true
})
}
private var _delegate: SnapImagePickerDelegate?
var eventHandler: SnapImagePickerEventHandlerProtocol?
var albumTitle = L10n.AllPhotosAlbumName.string {
didSet {
visibleCells = nil
setupTitleButton()
}
}
private var currentlySelectedIndex = 0 {
didSet {
scrollToIndex(currentlySelectedIndex)
}
}
private var selectedImageRotation = UIImageOrientation.Up {
didSet {
self.selectedImageScrollView?.transform = CGAffineTransformMakeRotation(CGFloat(self.selectedImageRotation.toCGAffineTransformRadians()))
}
}
private var state: DisplayState = .Image {
didSet {
let imageInteractionEnabled = (state == .Image)
rotateButton?.enabled = imageInteractionEnabled
selectedImageScrollView?.userInteractionEnabled = imageInteractionEnabled
setVisibleCellsInAlbumCollectionView()
setMainOffsetForState(state)
}
}
private var currentDisplay = Display.Portrait {
didSet {
albumCollectionWidthConstraint =
albumCollectionWidthConstraint?.changeMultiplier(currentDisplay.AlbumCollectionWidthMultiplier)
albumCollectionView?.reloadData()
selectedImageScrollViewHeightToFrameWidthAspectRatioConstraint =
selectedImageScrollViewHeightToFrameWidthAspectRatioConstraint?.changeMultiplier(currentDisplay.SelectedImageWidthMultiplier)
imageGridViewWidthConstraint =
imageGridViewWidthConstraint?.changeMultiplier(currentDisplay.SelectedImageWidthMultiplier)
setRotateButtonConstraint()
}
}
private func setRotateButtonConstraint() {
let ratioNotCoveredByImage = (1 - currentDisplay.SelectedImageWidthMultiplier)
let widthNotCoveredByImage = ratioNotCoveredByImage * view.frame.width
let selectedImageStart = widthNotCoveredByImage / 2
rotateButtonLeadingConstraint?.constant = selectedImageStart + 20
}
private var visibleCells: Range<Int>? {
didSet {
if let visibleCells = visibleCells where oldValue != visibleCells {
let increasing = oldValue?.startIndex < visibleCells.startIndex
eventHandler?.scrolledToCells(visibleCells, increasing: increasing)
}
}
}
private var userIsScrolling = false
private var enqueuedBounce: (() -> Void)?
override public func viewDidLoad() {
super.viewDidLoad()
calculateViewSizes()
setupGestureRecognizers()
setupTitleButton()
automaticallyAdjustsScrollViewInsets = false
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
currentDisplay = view.frame.size.displayType()
let width = currentDisplay.CellWidthInViewWithWidth(view.bounds.width)
eventHandler?.viewWillAppearWithCellSize(CGSize(width: width, height: width))
selectedImageScrollView?.userInteractionEnabled = true
}
override public func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
setVisibleCellsInAlbumCollectionView()
}
override public func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
let newDisplay = size.displayType()
if newDisplay != currentDisplay {
let ratio = newDisplay.SelectedImageWidthMultiplier / currentDisplay.SelectedImageWidthMultiplier
let offsetRatio = ratio * ((newDisplay == .Landscape) ? 1 * 1.33 : 1 / 1.33)
let newOffset = selectedImageScrollView!.contentOffset * offsetRatio
coordinator.animateAlongsideTransition({
[weak self] _ in
if let strongSelf = self,
let selectedImageScrollView = strongSelf.selectedImageScrollView {
let height = selectedImageScrollView.frame.height
let newHeight = height * ratio
strongSelf.setMainOffsetForState(strongSelf.state, withHeight: newHeight, animated: false)
}
self?.selectedImageScrollView?.setContentOffset(newOffset, animated: true)
self?.currentDisplay = newDisplay
self?.setVisibleCellsInAlbumCollectionView()
self?.calculateViewSizes()
}, completion: {
[weak self] _ in
if let size = self?.selectedImage?.image.size {
let zoomScale = self?.selectedImageScrollView?.zoomScale ?? 1.0
let insets = self?.getInsetsForSize(size, withZoomScale: zoomScale) ?? UIEdgeInsetsZero
self?.selectedImageScrollView?.contentInset = insets
}
})
}
}
}
extension SnapImagePickerViewController: SnapImagePickerProtocol {
public var delegate: SnapImagePickerDelegate? {
get {
return _delegate
}
set {
_delegate = newValue
}
}
public static func initializeWithCameraRollAccess(cameraRollAccess: Bool) -> SnapImagePickerViewController? {
let bundle = NSBundle(forClass: SnapImagePickerViewController.self)
let storyboard = UIStoryboard(name: SnapImagePickerConnector.Names.SnapImagePickerStoryboard.rawValue, bundle: bundle)
if let snapImagePickerViewController = storyboard.instantiateInitialViewController() as? SnapImagePickerViewController {
let presenter = SnapImagePickerPresenter(view: snapImagePickerViewController, cameraRollAccess: cameraRollAccess)
snapImagePickerViewController.eventHandler = presenter
snapImagePickerViewController.cameraRollAccess = cameraRollAccess
return snapImagePickerViewController
}
return nil
}
public var cameraRollAccess: Bool {
get {
return eventHandler?.cameraRollAccess ?? false
}
set {
eventHandler?.cameraRollAccess = newValue
if !newValue {
selectedImageView?.image = nil
selectedImage = nil
albumCollectionView?.reloadData()
}
}
}
public func reload() {
let width = self.currentDisplay.CellWidthInViewWithWidth(view.bounds.width)
eventHandler?.viewWillAppearWithCellSize(CGSize(width: width, height: width))
if let visibleCells = visibleCells {
eventHandler?.scrolledToCells(visibleCells, increasing: true)
} else {
setVisibleCellsInAlbumCollectionView()
}
}
public func getCurrentImage() -> (image: UIImage, options: ImageOptions)? {
if let scrollView = selectedImageScrollView,
let image = selectedImage?.image {
if image.size.height > image.size.width {
let viewRatio = image.size.width / scrollView.contentSize.width
let diff = (image.size.height - image.size.width) / 2
let cropRect = CGRect(x: scrollView.contentOffset.x * viewRatio,
y: (scrollView.contentOffset.y * viewRatio) + diff,
width: scrollView.bounds.width * viewRatio,
height: scrollView.bounds.height * viewRatio)
let options = ImageOptions(cropRect: cropRect, rotation: selectedImageRotation)
return (image: image, options: options)
} else {
let viewRatio = image.size.height / scrollView.contentSize.height
let diff = (image.size.width - image.size.height) / 2
let cropRect = CGRect(x: (scrollView.contentOffset.x * viewRatio) + diff,
y: (scrollView.contentOffset.y * viewRatio),
width: scrollView.bounds.width * viewRatio,
height: scrollView.bounds.height * viewRatio)
let options = ImageOptions(cropRect: cropRect, rotation: selectedImageRotation)
return (image: image, options: options)
}
}
return nil
}
}
extension SnapImagePickerViewController {
func albumTitlePressed() {
eventHandler?.albumTitlePressed(self.navigationController)
}
private func setupTitleButton() {
var title = albumTitle
if albumTitle == AlbumType.AllPhotos.getAlbumName() {
title = L10n.AllPhotosAlbumName.string
} else if albumTitle == AlbumType.Favorites.getAlbumName() {
title = L10n.FavoritesAlbumName.string
}
let button = UIButton()
setupTitleButtonTitle(button, withTitle: title)
setupTitleButtonImage(button)
button.addTarget(self, action: #selector(albumTitlePressed), forControlEvents: .TouchUpInside)
navigationItem.titleView = button
delegate?.setTitleView(button)
}
private func setupTitleButtonTitle(button: UIButton, withTitle title: String) {
button.titleLabel?.font = SnapImagePickerTheme.font
button.setTitle(title, forState: .Normal)
button.setTitleColor(UIColor.blackColor(), forState: .Normal)
button.setTitleColor(UIColor.init(red: 0xB8/0xFF, green: 0xB8/0xFF, blue: 0xB8/0xFF, alpha: 1), forState: .Highlighted)
}
private func setupTitleButtonImage(button: UIButton) {
if let mainImage = UIImage(named: "icon_s_arrow_down_gray", inBundle: NSBundle(forClass: SnapImagePickerViewController.self), compatibleWithTraitCollection: nil),
let mainCgImage = mainImage.CGImage,
let navBarHeight = navigationController?.navigationBar.frame.height {
let scale = mainImage.findRoundedScale(mainImage.size.height / (navBarHeight / 6))
let scaledMainImage = UIImage(CGImage: mainCgImage, scale: scale, orientation: .Up)
let scaledHighlightedImage = scaledMainImage.setAlpha(0.3)
button.setImage(scaledMainImage, forState: .Normal)
button.setImage(scaledHighlightedImage, forState: .Highlighted)
button.frame = CGRect(x: 0, y: 0, width: scaledHighlightedImage.size.width, height: scaledHighlightedImage.size.height)
button.rightAlignImage(scaledHighlightedImage)
}
}
private func calculateViewSizes() {
if let mainScrollView = mainScrollView {
let mainFrame = mainScrollView.frame
let imageSizeWhenDisplayed = view.frame.width * CGFloat(currentDisplay.SelectedImageWidthMultiplier) * CGFloat(DisplayState.Album.offset)
let imageSizeWhenHidden = view.frame.width * CGFloat(currentDisplay.SelectedImageWidthMultiplier) * (1 - CGFloat(DisplayState.Album.offset))
mainScrollView.contentSize = CGSize(width: mainFrame.width, height: mainFrame.height + imageSizeWhenDisplayed)
albumCollectionViewHeightConstraint?.constant = view.frame.height - imageSizeWhenHidden - currentDisplay.NavBarHeight
}
}
}
extension SnapImagePickerViewController: SnapImagePickerViewControllerProtocol {
func displayMainImage(mainImage: SnapImagePickerImage) {
let size = mainImage.image.size
if selectedImage == nil
|| mainImage.localIdentifier != selectedImage!.localIdentifier
|| size.height > selectedImage!.image.size.height {
setMainImage(mainImage)
selectedImageScrollView?.contentInset = getInsetsForSize(size)
selectedImageScrollView?.minimumZoomScale = min(size.width, size.height) / max(size.width, size.height)
selectedImageScrollView?.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
selectedImageScrollView?.setZoomScale(1, animated: false)
}
if state != .Image {
state = .Image
}
mainImageLoadIndicator?.stopAnimating()
}
private func setMainImage(mainImage: SnapImagePickerImage) {
selectedImageView?.contentMode = .ScaleAspectFill
selectedImage = mainImage
selectedImageRotation = .Up
}
private func getInsetsForSize(size: CGSize, withZoomScale zoomScale: CGFloat = 1) -> UIEdgeInsets{
if (size.height > size.width) {
return getInsetsForTallRectangle(size, withZoomScale: zoomScale)
} else {
return getInsetsForWideRectangle(size, withZoomScale: zoomScale)
}
}
private func getInsetsForTallRectangle(size: CGSize, withZoomScale zoomScale: CGFloat = 1) -> UIEdgeInsets {
if let scrollView = selectedImageScrollView {
let ratio = scrollView.frame.width / size.width
let imageHeight = size.height * ratio
let diff = imageHeight - scrollView.frame.width
let inset = diff / 2
var insets = UIEdgeInsets(top: inset * zoomScale, left: 0, bottom: inset * zoomScale, right: 0)
let contentWidth = scrollView.contentSize.width
if contentWidth > 0 && contentWidth < scrollView.frame.width {
let padding = CGFloat(scrollView.frame.width - contentWidth) / 2
insets = insets.addHorizontalInset(padding)
}
return insets
}
return UIEdgeInsetsZero
}
private func getInsetsForWideRectangle(size: CGSize, withZoomScale zoomScale: CGFloat = 1) -> UIEdgeInsets {
if let scrollView = selectedImageScrollView {
let ratio = scrollView.frame.width / size.height
let imageWidth = size.width * ratio
let diff = imageWidth - scrollView.frame.width
let inset = diff / 2
var insets = UIEdgeInsets(top: 0, left: inset * zoomScale, bottom: 0, right: inset * zoomScale)
let contentHeight = scrollView.contentSize.height
if contentHeight > 0 && contentHeight < scrollView.frame.width {
let padding = CGFloat(scrollView.frame.width - contentHeight) / 2
insets = insets.addVerticalInset(padding)
}
return insets
}
return UIEdgeInsetsZero
}
func reloadAlbum() {
albumCollectionView?.reloadData()
}
func reloadCellAtIndexes(indexes: [Int]) {
var indexPaths = [NSIndexPath]()
for index in indexes {
indexPaths.append(arrayIndexToIndexPath(index))
}
if indexes.count > 0 {
UIView.performWithoutAnimation() {
self.albumCollectionView?.reloadItemsAtIndexPaths(indexPaths)
}
}
}
}
extension SnapImagePickerViewController: UICollectionViewDataSource {
public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return eventHandler?.numberOfItemsInSection(section) ?? 0
}
public func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let index = indexPathToArrayIndex(indexPath)
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Image Cell", forIndexPath: indexPath)
if let imageCell = cell as? ImageCell {
eventHandler?.presentCell(imageCell, atIndex: index)
}
return cell
}
private func indexPathToArrayIndex(indexPath: NSIndexPath) -> Int {
return indexPath.item
}
private func arrayIndexToIndexPath(index: Int) -> NSIndexPath {
return NSIndexPath(forItem: index, inSection: 0)
}
private func scrollToIndex(index: Int) {
if let albumCollectionView = albumCollectionView {
let row = index / currentDisplay.NumberOfColumns
let offset = CGFloat(row) * (currentDisplay.CellWidthInView(albumCollectionView) + currentDisplay.Spacing)
// Does not scroll to index if there is not enough content to fill the screen
if offset + albumCollectionView.frame.height > albumCollectionView.contentSize.height {
return
}
if offset > 0 {
albumCollectionView.setContentOffset(CGPoint(x: 0, y: offset), animated: true)
}
}
}
}
extension SnapImagePickerViewController: UICollectionViewDelegateFlowLayout {
public func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let size = currentDisplay.CellWidthInView(collectionView)
return CGSizeMake(size, size)
}
}
extension SnapImagePickerViewController: UICollectionViewDelegate {
public func collectionView(collectionView: UICollectionView,
willDisplayCell cell: UICollectionViewCell,
forItemAtIndexPath indexPath: NSIndexPath) {
if visibleCells == nil
|| indexPath.item % currentDisplay.NumberOfColumns == (currentDisplay.NumberOfColumns - 1)
&& !(visibleCells! ~= indexPath.item) {
self.setVisibleCellsInAlbumCollectionView()
}
}
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let index = indexPathToArrayIndex(indexPath)
print("Contentoffset: \(selectedImageScrollView?.contentOffset)")
if eventHandler?.albumImageClicked(index) == true {
scrollToIndex(index)
mainImageLoadIndicator?.startAnimating()
}
}
}
extension SnapImagePickerViewController: UIScrollViewDelegate {
public func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView == mainScrollView {
mainScrollViewDidScroll(scrollView)
} else if scrollView == albumCollectionView {
albumCollectionViewDidScroll(scrollView)
}
}
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return selectedImageView
}
public func scrollViewWillEndDragging(scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
userIsScrolling = false
if scrollView == albumCollectionView && velocity.y != 0.0 && targetContentOffset.memory.y == 0 {
enqueuedBounce = {
self.mainScrollView?.manuallyBounceBasedOnVelocity(velocity)
}
}
}
public func scrollViewWillBeginDragging(scrollView: UIScrollView) {
userIsScrolling = true
if scrollView == selectedImageScrollView {
setImageGridViewAlpha(0.2)
}
}
public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if scrollView == selectedImageScrollView {
setImageGridViewAlpha(0.0)
} else if scrollView == albumCollectionView && !decelerate {
scrolledToOffsetRatio(calculateOffsetToImageHeightRatio())
}
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if scrollView == albumCollectionView && state == .Album {
state = .Album
} else if scrollView == selectedImageScrollView {
setImageGridViewAlpha(0.0)
}
}
public func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView?) {
if scrollView == selectedImageScrollView {
setImageGridViewAlpha(0.2)
}
}
public func scrollViewDidZoom(scrollView: UIScrollView) {
if let size = selectedImage?.image.size {
let zoomScale = selectedImageScrollView?.zoomScale ?? 1.0
selectedImageScrollView?.contentInset = getInsetsForSize(size, withZoomScale: zoomScale)
}
}
public func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
if scrollView == selectedImageScrollView {
setImageGridViewAlpha(0.0)
}
}
}
extension SnapImagePickerViewController {
private func mainScrollViewDidScroll(scrollView: UIScrollView) {
if let albumCollectionView = albumCollectionView {
let remainingAlbumCollectionHeight = albumCollectionView.contentSize.height - albumCollectionView.contentOffset.y
let albumStart = albumCollectionView.frame.minY - scrollView.contentOffset.y
let offset = scrollView.frame.height - (albumStart + remainingAlbumCollectionHeight)
if offset > 0 && albumCollectionView.contentOffset.y - offset > 0 {
albumCollectionView.contentOffset = CGPoint(x: 0, y: albumCollectionView.contentOffset.y - offset)
}
}
}
private func albumCollectionViewDidScroll(scrollView: UIScrollView) {
if let mainScrollView = mainScrollView
where scrollView.contentOffset.y < 0 {
if userIsScrolling {
let y = mainScrollView.contentOffset.y + scrollView.contentOffset.y
mainScrollView.contentOffset = CGPoint(x: mainScrollView.contentOffset.x, y: y)
if let height = selectedImageView?.frame.height {
blackOverlayView?.alpha = (mainScrollView.contentOffset.y / height) * currentDisplay.MaxImageFadeRatio
}
} else if let enqueuedBounce = enqueuedBounce {
enqueuedBounce()
self.enqueuedBounce = nil
}
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: 0)
}
}
private func scrolledToOffsetRatio(ratio: Double) {
if state == .Album && ratio < currentDisplay.OffsetThreshold.end {
state = .Image
} else if state == .Image && ratio > currentDisplay.OffsetThreshold.start {
state = .Album
} else {
setMainOffsetForState(state)
}
}
}
extension SnapImagePickerViewController {
private func setVisibleCellsInAlbumCollectionView() {
if let albumCollectionView = albumCollectionView {
let rowHeight = currentDisplay.CellWidthInView(albumCollectionView) + currentDisplay.Spacing
let topVisibleRow = Int(albumCollectionView.contentOffset.y / rowHeight)
let firstVisibleCell = topVisibleRow * currentDisplay.NumberOfColumns
let imageViewHeight = selectedImageScrollView!.frame.height * CGFloat(1 - state.offset)
let visibleAreaOfAlbumCollectionView = mainScrollView!.frame.height - imageViewHeight
let numberOfVisibleRows = Int(ceil(visibleAreaOfAlbumCollectionView / rowHeight)) + 1
let numberOfVisibleCells = numberOfVisibleRows * currentDisplay.NumberOfColumns
let lastVisibleCell = firstVisibleCell + numberOfVisibleCells
if (lastVisibleCell > firstVisibleCell) {
visibleCells = firstVisibleCell..<lastVisibleCell
}
}
}
private func calculateOffsetToImageHeightRatio() -> Double {
if let offset = mainScrollView?.contentOffset.y,
let height = selectedImageScrollView?.frame.height {
return Double((offset + currentDisplay.NavBarHeight) / height)
}
return 0.0
}
private func setImageGridViewAlpha(alpha: CGFloat) {
UIView.animateWithDuration(0.3) {
[weak self] in self?.imageGridView?.alpha = alpha
}
}
}
extension SnapImagePickerViewController {
private func setupGestureRecognizers() {
removeMainScrollViewPanRecognizers()
setupPanGestureRecognizerForScrollView(mainScrollView)
setupPanGestureRecognizerForScrollView(albumCollectionView)
}
private func removeMainScrollViewPanRecognizers() {
if let recognizers = mainScrollView?.gestureRecognizers {
for recognizer in recognizers {
if recognizer is UIPanGestureRecognizer {
mainScrollView?.removeGestureRecognizer(recognizer)
}
}
}
}
private func setupPanGestureRecognizerForScrollView(scrollView: UIScrollView?) {
let recognizer = UIPanGestureRecognizer(target: self, action: #selector(pan(_:)))
recognizer.delegate = self
scrollView?.addGestureRecognizer(recognizer)
}
func pan(recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .Changed:
panMainScrollViewWithRecognizer(recognizer)
case .Ended, .Cancelled, .Failed:
panEnded()
default: break
}
}
private func panMainScrollViewWithRecognizer(recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translationInView(mainScrollView)
if let mainScrollView = mainScrollView {
let old = mainScrollView.contentOffset.y
let offset = old - translation.y
mainScrollView.setContentOffset(CGPoint(x: 0, y: offset), animated: false)
recognizer.setTranslation(CGPointZero, inView: mainScrollView)
if let height = selectedImageView?.frame.height {
let alpha = (offset / height) * currentDisplay.MaxImageFadeRatio
blackOverlayView?.alpha = alpha
rotateButton?.alpha = 1 - alpha
}
}
}
private func panEnded() {
scrolledToOffsetRatio(calculateOffsetToImageHeightRatio())
}
private func setMainOffsetForState(state: DisplayState, animated: Bool = true) {
if let height = selectedImageScrollView?.bounds.height {
setMainOffsetForState(state, withHeight: height, animated: animated)
}
}
private func setMainOffsetForState(state: DisplayState, withHeight height: CGFloat, animated: Bool = true) {
let offset = (height * CGFloat(state.offset))
if animated {
UIView.animateWithDuration(0.3) {
[weak self] in self?.displayViewStateForOffset(offset, withHeight: height)
}
} else {
displayViewStateForOffset(offset, withHeight: height)
}
}
private func displayViewStateForOffset(offset: CGFloat, withHeight height: CGFloat) {
mainScrollView?.contentOffset = CGPoint(x: 0, y: offset)
blackOverlayView?.alpha = (offset / height) * self.currentDisplay.MaxImageFadeRatio
rotateButton?.alpha = state.rotateButtonAlpha
}
}
extension SnapImagePickerViewController: UIGestureRecognizerDelegate {
public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.view == albumCollectionView {
return state == .Image
} else if gestureRecognizer.view == mainScrollView {
let isInImageView =
gestureRecognizer.locationInView(selectedImageScrollView).y < selectedImageScrollView?.frame.height
if state == .Image && isInImageView {
return false
}
return true
}
return false
}
} |
open class PlayButton: MediaControl.Element {
open class override var name: String { "PlayButton" }
override open var panel: MediaControlPanel { .center}
override open var position: MediaControlPosition { .center }
public var playIcon = UIImage.fromName("play", for: PlayButton.self)!
public var pauseIcon = UIImage.fromName("pause", for: PlayButton.self)!
public var replayIcon = UIImage.fromName("replay", for: PlayButton.self)!
public var button: UIButton? {
didSet {
guard let button = button else { return }
view.addSubview(button)
button.setImage(playIcon, for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.addTarget(self, action: #selector(togglePlayPause), for: .touchUpInside)
button.bindFrameToSuperviewBounds()
}
}
private var canShowPlayIcon: Bool {
activePlayback?.state == .paused || activePlayback?.state == .idle
}
private var canShowPauseIcon: Bool {
activePlayback?.state == .playing
}
private var shouldReplay: Bool {
guard let playback = activePlayback else { return false }
return playback.position == playback.duration
}
override open func bindEvents() {
bindPlaybackEvents()
}
func bindPlaybackEvents() {
guard let playback = activePlayback else { return }
listenTo(playback, event: .didPause) { [weak self] _ in self?.onPause() }
listenTo(playback, event: .playing) { [weak self] _ in self?.onPlay() }
listenTo(playback, event: .stalling) { [weak self] _ in self?.hide() }
listenTo(playback, event: .didStop) { [weak self] _ in self?.onStop() }
listenTo(playback, event: .didComplete) { [weak self] _ in self?.onComplete() }
listenTo(playback, event: .willSeek) { [weak self] info in
guard let position = info?["position"] as? Double else { return }
self?.onWillSeek(0)
}
}
override open func render() {
setupView()
setupButton()
}
private func setupView() {
guard let superview = view.superview else { return }
view.widthAnchor.constraint(equalTo: superview.widthAnchor, multiplier: 0.6).isActive = true
view.heightAnchor.constraint(equalTo: superview.heightAnchor, multiplier: 0.6).isActive = true
}
private func setupButton() {
button = UIButton(type: .custom)
button?.accessibilityIdentifier = "PlayPauseButton"
}
open func onPlay() {
show()
changeToPauseIcon()
}
private func onPause() {
show()
changeToPlayIcon()
}
private func onStop() {
show()
changeToPlayIcon()
}
private func onComplete() {
show()
changeToReplayIcon()
}
private func onWillSeek(_ position: Double) {
guard let playback = activePlayback, position != playback.duration else { return }
show()
canShowPlayIcon ? changeToPlayIcon() : changeToPauseIcon()
}
public func hide() {
view.isHidden = true
}
public func show() {
view.isHidden = false
}
@objc func togglePlayPause() {
guard let playback = activePlayback else { return }
if shouldReplay { playback.seek(0) }
switch playback.state {
case .playing:
pause()
case .paused, .idle:
play()
default:
break
}
}
private func pause() {
activePlayback?.pause()
}
private func play() {
activePlayback?.play()
}
private func changeToPlayIcon() {
guard canShowPlayIcon else { return }
button?.setImage(playIcon, for: .normal)
}
public func changeToPauseIcon() {
guard canShowPauseIcon else { return }
button?.setImage(pauseIcon, for: .normal)
}
private func changeToReplayIcon() {
button?.setImage(replayIcon, for: .normal)
}
}
refactor: adjust parameter of onWillSeek
open class PlayButton: MediaControl.Element {
open class override var name: String { "PlayButton" }
override open var panel: MediaControlPanel { .center}
override open var position: MediaControlPosition { .center }
public var playIcon = UIImage.fromName("play", for: PlayButton.self)!
public var pauseIcon = UIImage.fromName("pause", for: PlayButton.self)!
public var replayIcon = UIImage.fromName("replay", for: PlayButton.self)!
public var button: UIButton? {
didSet {
guard let button = button else { return }
view.addSubview(button)
button.setImage(playIcon, for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.addTarget(self, action: #selector(togglePlayPause), for: .touchUpInside)
button.bindFrameToSuperviewBounds()
}
}
private var canShowPlayIcon: Bool {
activePlayback?.state == .paused || activePlayback?.state == .idle
}
private var canShowPauseIcon: Bool {
activePlayback?.state == .playing
}
private var shouldReplay: Bool {
guard let playback = activePlayback else { return false }
return playback.position == playback.duration
}
override open func bindEvents() {
bindPlaybackEvents()
}
func bindPlaybackEvents() {
guard let playback = activePlayback else { return }
listenTo(playback, event: .didPause) { [weak self] _ in self?.onPause() }
listenTo(playback, event: .playing) { [weak self] _ in self?.onPlay() }
listenTo(playback, event: .stalling) { [weak self] _ in self?.hide() }
listenTo(playback, event: .didStop) { [weak self] _ in self?.onStop() }
listenTo(playback, event: .didComplete) { [weak self] _ in self?.onComplete() }
listenTo(playback, event: .willSeek) { [weak self] info in
guard let position = info?["position"] as? Double else { return }
self?.onWillSeek(position)
}
}
override open func render() {
setupView()
setupButton()
}
private func setupView() {
guard let superview = view.superview else { return }
view.widthAnchor.constraint(equalTo: superview.widthAnchor, multiplier: 0.6).isActive = true
view.heightAnchor.constraint(equalTo: superview.heightAnchor, multiplier: 0.6).isActive = true
}
private func setupButton() {
button = UIButton(type: .custom)
button?.accessibilityIdentifier = "PlayPauseButton"
}
open func onPlay() {
show()
changeToPauseIcon()
}
private func onPause() {
show()
changeToPlayIcon()
}
private func onStop() {
show()
changeToPlayIcon()
}
private func onComplete() {
show()
changeToReplayIcon()
}
private func onWillSeek(_ position: Double) {
guard let playback = activePlayback, position != playback.duration else { return }
show()
canShowPlayIcon ? changeToPlayIcon() : changeToPauseIcon()
}
public func hide() {
view.isHidden = true
}
public func show() {
view.isHidden = false
}
@objc func togglePlayPause() {
guard let playback = activePlayback else { return }
if shouldReplay { playback.seek(0) }
switch playback.state {
case .playing:
pause()
case .paused, .idle:
play()
default:
break
}
}
private func pause() {
activePlayback?.pause()
}
private func play() {
activePlayback?.play()
}
private func changeToPlayIcon() {
guard canShowPlayIcon else { return }
button?.setImage(playIcon, for: .normal)
}
public func changeToPauseIcon() {
guard canShowPauseIcon else { return }
button?.setImage(pauseIcon, for: .normal)
}
private func changeToReplayIcon() {
button?.setImage(replayIcon, for: .normal)
}
}
|
//
// Debug.swift
// ViewQuery
//
// Created by David James on 1/20/17.
// Copyright © 2017 David B James. All rights reserved.
//
import UIKit
/// Is the current build using DEBUG configuration.
public func isDebugBuild() -> Bool {
#if DEBUG
return true
#else
return false
#endif
}
// "ApiDebug" is a development-only debug tool that provides
// user-friendly console output intended to "reveal" the operations of
// any API/library that uses it. (RxSwift.debug does something similar.)
// Libraries that use it would add pertinent debug output at critical points
// in the code and then users of the library would toggle debug output
// via a "debug" operator or similar mechanism (optionally passing DebugConfig
// and DebugOptions).
// NOTE: "ApiDebug" is not a general purpose logging/reporting system, which
// could exist alongside. As such, "ApiDebug" has no reporting levels, etc.
public struct ApiDebugOptions : OptionSet {
public let rawValue:Int
public init(rawValue:Int) {
self.rawValue = rawValue
}
/// Abbreviated output.
public static let compact = ApiDebugOptions(rawValue: 1 << 0)
/// Extended output. Pretty print plus add'l vertical space for readability.
public static let expanded = ApiDebugOptions(rawValue: 1 << 1)
public static let tips = ApiDebugOptions(rawValue: 1 << 2)
fileprivate var isDefaultVerbosity:Bool {
return !contains(.expanded) && !contains(.compact)
}
}
/// Whether debugging is off, on or is on with options.
public enum ApiDebugConfig {
case off
case on
case onWithOptions(ApiDebugOptions)
public var isDebug:Bool {
switch self {
case .off :
return false
case .on, .onWithOptions :
#if DEBUG
return true
#else
return false
#endif
}
}
/// Factory to get a debug instance
public var debug:ApiDebug? {
switch self {
case .on :
return ApiDebug()
case .onWithOptions(let options) :
return ApiDebug(options)
case .off :
return nil
}
}
}
public protocol ApiDebugPrintable : CustomStringConvertible {
var options:ApiDebugOptions { get }
var shortOutput:String { get }
func pretty(indent:Int?) -> String
}
extension ApiDebugPrintable {
public func output(indent:Int? = nil) {
// This should be the ONLY print statement related to debugging.
print(options.contains(.compact) ? shortOutput : pretty(indent:indent))
}
}
/// Wrapper for outputting structured API debug information to the console.
/// NOT a general logging system.
public struct ApiDebug {
public let options:ApiDebugOptions
public init?(_ options:ApiDebugOptions? = nil) {
#if DEBUG
self.options = options ?? []
#else
return nil
#endif
}
// "hasTip" is a flag to say that a particular notice/warning/error
// has a helpful tip available indicating the user can add .tips
// to debug options to view it. Assumes tip() is called directly
// after the notice/warning/error.
public func notice(_ message:String, hasTip:Bool = false) -> ApiDebug.Log {
let _message = message + (hasTip && !options.contains(.tips) ? " TIP AVAILABLE." : "")
return Log(options:self.options, message: _message, type:.notice)
}
public func warning(_ message:String, hasTip:Bool = false) -> ApiDebug.Log {
let _message = message + (hasTip && !options.contains(.tips) ? " TIP AVAILABLE." : "")
return Log(options:self.options, message: _message, type:.warning)
}
public func error(_ message:String, hasTip:Bool = false) -> ApiDebug.Log {
let _message = message + (hasTip && !options.contains(.tips) ? " TIP AVAILABLE." : "")
return Log(options:self.options, message: _message, type:.error)
}
public func message(_ message:String, icon:String? = nil) -> ApiDebug.Basic {
return Basic(options:self.options, message: message, icon:icon)
}
public func tip(_ tip:String) -> ApiDebug.Log? {
guard options.contains(.tips) else { return nil }
return Log(options:self.options, message:tip, type:.tip)
}
/// Output a result. This is the same as message() but adds a bit of
/// decoration to the message to indicate it's a final result. Use at
/// the end of a series of operations when a final value has been computed.
public func result(_ message:String) -> ApiDebug.Result {
return Result(options: self.options, message: message)
}
/// Output a method signature with runtime values.
public func method(_ wrapper:Any, _ method:String, _ params:[String]? = nil, _ vals:[Any?]? = nil, delegates:Bool = false) -> ApiDebug.Method {
return Method(options:self.options, wrapper:wrapper, method:method, params:params, vals:vals, delegates:delegates)
}
public func constructor(_ wrapper:Any, _ params:[String]? = nil, _ vals:[Any?]? = nil) -> ApiDebug.Method {
return Method(options:self.options, wrapper:wrapper, method:"init", params:params, vals:vals, delegates: false)
}
// Printable debug wrappers
public struct Log : ApiDebugPrintable {
public let options:ApiDebugOptions
var message:String
let type:LogType
enum LogType : CustomStringConvertible {
case notice, warning, error, tip
var description: String {
switch self {
case .notice :
return "NOTICE"
case .warning :
return "WARNING"
case .error :
return "ERROR"
case .tip :
return "TIP"
}
}
var icon:String {
switch self {
case .notice :
return "💬"
case .warning :
return "⚠️"
case .error :
return "🛑"
case .tip :
return "💡"
}
}
}
public var description: String {
return "\(type): \(message)"
}
public var shortOutput: String {
return "ViewQuery Log: \(description)"
}
public func pretty(indent:Int?) -> String {
var output = repeatElement(" " , count: (indent ?? 0) * 4).joined()
output += type.icon // 💬 ⚠️ 🔥
output += " "
output += description
if options.contains(.expanded) {
output += "\n"
}
return output
}
}
public struct Basic : ApiDebugPrintable {
public let options:ApiDebugOptions
private var message:String
private let icon:String
private var prefix:String?
private var suffix:String?
init(options:ApiDebugOptions, message:String, icon:String? = nil) {
self.options = options
self.message = message
self.icon = icon ?? "⚙️"
}
public var description: String {
var before = ""
var after = ""
if let prefix = prefix {
before = "\(prefix) "
}
if let suffix = suffix {
after = " \(suffix)"
}
return before + message + after
}
public var shortOutput: String {
return "ViewQuery Debug: \(description)"
}
public func pretty(indent:Int?) -> String {
var output = repeatElement(" " , count: (indent ?? 0) * 4).joined()
if let prefix = prefix {
output += "\(prefix) "
}
output += "\(icon) "
output += message
if let suffix = suffix {
output += " \(suffix)"
}
if options.contains(.expanded) {
output += "\n"
}
return output
}
public mutating func prepend(_ string:String) {
if let prefix = prefix {
self.prefix = "\(string) " + prefix
} else {
self.prefix = string
}
}
public mutating func append(_ string:String) {
if let suffix = suffix {
self.suffix = suffix + " \(string)"
} else {
self.suffix = string
}
}
}
public struct Result : ApiDebugPrintable {
public var options:ApiDebugOptions
fileprivate var message:String
public var description: String {
return message
}
public var shortOutput: String {
return "ViewQuery Result: \(description)"
}
public func pretty(indent:Int?) -> String {
var output = repeatElement(" " , count: (indent ?? 4) * 4).joined()
output += "🎁 "
output += description
if options.contains(.expanded) {
output += "\n"
}
return output
}
}
// TODO: ✅ Consider mapping argument calls to colons in the standard #function macro.
// This would obviate some brittle debug code (the parameter names) but beware the result
// would not be exactly the same as it is now. #function uses *external* argument names
// (which when no external would be _), instead of the current *internal* argument names
// which frequently are more helpful.
public struct Method : ApiDebugPrintable {
public let options:ApiDebugOptions
fileprivate let wrapper:Any
fileprivate let method:String
fileprivate var params:[String]?
fileprivate var vals:[Any?]?
fileprivate let delegates:Bool
public var description:String {
let isInit = method == "init"
var output = options.contains(.compact) ? "" : (isInit ? "🚛 " : "🚜 ")
output += String(describing:type(of:wrapper))
if isInit {
// Don't add the method name because inits don't count.
// Example: ViewMutator(..)
} else {
// remove from first open parens onward
// this allows passing #function to this.
output += "." + method.trim(from: "(")
// Example: ViewMutator.center(..)
}
output += "("
if let params = self.params, let values = self.vals {
for i in 0..<(params.count) {
guard i >= values.startIndex && i < values.endIndex else {
continue
}
output += params[i] + ":"
let _val = values[i] // this returns an optional
if let value = _val {
if let displayStyle = Mirror(reflecting: value).displayStyle {
switch displayStyle {
case .class :
output += String(describing: type(of:value))
if value is NSObject {
// For NSObjects/UIView include the memory address
output += " (" + (value as! NSObject).memoryAddress(shortened: true) + ")"
}
default : // .enum, .collection, .struct, .tuple, .dictionary, .set
output += String(describing:value)
}
} else {
// All other primitive values, output as is.
output += String(describing: value)
}
} else {
output += "nil"
}
if i < params.count - 1 {
output += ", "
}
}
}
output += ")"
if delegates && !options.contains(.compact) {
// The method called for this debug delegates to another method with debug information.
output += " ..."
}
return output
}
public var shortOutput: String {
return "ViewQuery Method: \(description)"
}
public func pretty(indent:Int?) -> String {
var output = ""
if indent == nil {
// extra line for first indent
output += "\n"
}
let indentString = repeatElement(" ", count: (indent ?? 0) * 4).joined()
output += indentString
output += repeatElement("▪️", count: 30).joined()
output += "\n"
output += indentString
output += description
if options.contains(.expanded) {
output += "\n"
}
return output
}
}
}
ApiDebug options accessor.
//
// Debug.swift
// ViewQuery
//
// Created by David James on 1/20/17.
// Copyright © 2017 David B James. All rights reserved.
//
import UIKit
/// Is the current build using DEBUG configuration.
public func isDebugBuild() -> Bool {
#if DEBUG
return true
#else
return false
#endif
}
// "ApiDebug" is a development-only debug tool that provides
// user-friendly console output intended to "reveal" the operations of
// any API/library that uses it. (RxSwift.debug does something similar.)
// Libraries that use it would add pertinent debug output at critical points
// in the code and then users of the library would toggle debug output
// via a "debug" operator or similar mechanism (optionally passing DebugConfig
// and DebugOptions).
// NOTE: "ApiDebug" is not a general purpose logging/reporting system, which
// could exist alongside. As such, "ApiDebug" has no reporting levels, etc.
public struct ApiDebugOptions : OptionSet {
public let rawValue:Int
public init(rawValue:Int) {
self.rawValue = rawValue
}
/// Abbreviated output.
public static let compact = ApiDebugOptions(rawValue: 1 << 0)
/// Extended output. Pretty print plus add'l vertical space for readability.
public static let expanded = ApiDebugOptions(rawValue: 1 << 1)
public static let tips = ApiDebugOptions(rawValue: 1 << 2)
fileprivate var isDefaultVerbosity:Bool {
return !contains(.expanded) && !contains(.compact)
}
}
/// Whether debugging is off, on or is on with options.
public enum ApiDebugConfig {
case off
case on
case onWithOptions(ApiDebugOptions)
public var isDebug:Bool {
switch self {
case .off :
return false
case .on, .onWithOptions :
#if DEBUG
return true
#else
return false
#endif
}
}
/// Factory to get a debug instance
public var debug:ApiDebug? {
switch self {
case .on :
return ApiDebug()
case .onWithOptions(let options) :
return ApiDebug(options)
case .off :
return nil
}
}
public var options:ApiDebugOptions? {
if case let .onWithOptions(opts) = self {
return opts
}
return nil
}
}
public protocol ApiDebugPrintable : CustomStringConvertible {
var options:ApiDebugOptions { get }
var shortOutput:String { get }
func pretty(indent:Int?) -> String
}
extension ApiDebugPrintable {
public func output(indent:Int? = nil) {
// This should be the ONLY print statement related to debugging.
print(options.contains(.compact) ? shortOutput : pretty(indent:indent))
}
}
/// Wrapper for outputting structured API debug information to the console.
/// NOT a general logging system.
public struct ApiDebug {
public let options:ApiDebugOptions
public init?(_ options:ApiDebugOptions? = nil) {
#if DEBUG
self.options = options ?? []
#else
return nil
#endif
}
// "hasTip" is a flag to say that a particular notice/warning/error
// has a helpful tip available indicating the user can add .tips
// to debug options to view it. Assumes tip() is called directly
// after the notice/warning/error.
public func notice(_ message:String, hasTip:Bool = false) -> ApiDebug.Log {
let _message = message + (hasTip && !options.contains(.tips) ? " TIP AVAILABLE." : "")
return Log(options:self.options, message: _message, type:.notice)
}
public func warning(_ message:String, hasTip:Bool = false) -> ApiDebug.Log {
let _message = message + (hasTip && !options.contains(.tips) ? " TIP AVAILABLE." : "")
return Log(options:self.options, message: _message, type:.warning)
}
public func error(_ message:String, hasTip:Bool = false) -> ApiDebug.Log {
let _message = message + (hasTip && !options.contains(.tips) ? " TIP AVAILABLE." : "")
return Log(options:self.options, message: _message, type:.error)
}
public func message(_ message:String, icon:String? = nil) -> ApiDebug.Basic {
return Basic(options:self.options, message: message, icon:icon)
}
public func tip(_ tip:String) -> ApiDebug.Log? {
guard options.contains(.tips) else { return nil }
return Log(options:self.options, message:tip, type:.tip)
}
/// Output a result. This is the same as message() but adds a bit of
/// decoration to the message to indicate it's a final result. Use at
/// the end of a series of operations when a final value has been computed.
public func result(_ message:String) -> ApiDebug.Result {
return Result(options: self.options, message: message)
}
/// Output a method signature with runtime values.
public func method(_ wrapper:Any, _ method:String, _ params:[String]? = nil, _ vals:[Any?]? = nil, delegates:Bool = false) -> ApiDebug.Method {
return Method(options:self.options, wrapper:wrapper, method:method, params:params, vals:vals, delegates:delegates)
}
public func constructor(_ wrapper:Any, _ params:[String]? = nil, _ vals:[Any?]? = nil) -> ApiDebug.Method {
return Method(options:self.options, wrapper:wrapper, method:"init", params:params, vals:vals, delegates: false)
}
// Printable debug wrappers
public struct Log : ApiDebugPrintable {
public let options:ApiDebugOptions
var message:String
let type:LogType
enum LogType : CustomStringConvertible {
case notice, warning, error, tip
var description: String {
switch self {
case .notice :
return "NOTICE"
case .warning :
return "WARNING"
case .error :
return "ERROR"
case .tip :
return "TIP"
}
}
var icon:String {
switch self {
case .notice :
return "💬"
case .warning :
return "⚠️"
case .error :
return "🛑"
case .tip :
return "💡"
}
}
}
public var description: String {
return "\(type): \(message)"
}
public var shortOutput: String {
return "ViewQuery Log: \(description)"
}
public func pretty(indent:Int?) -> String {
var output = repeatElement(" " , count: (indent ?? 0) * 4).joined()
output += type.icon // 💬 ⚠️ 🔥
output += " "
output += description
if options.contains(.expanded) {
output += "\n"
}
return output
}
}
public struct Basic : ApiDebugPrintable {
public let options:ApiDebugOptions
private var message:String
private let icon:String
private var prefix:String?
private var suffix:String?
init(options:ApiDebugOptions, message:String, icon:String? = nil) {
self.options = options
self.message = message
self.icon = icon ?? "⚙️"
}
public var description: String {
var before = ""
var after = ""
if let prefix = prefix {
before = "\(prefix) "
}
if let suffix = suffix {
after = " \(suffix)"
}
return before + message + after
}
public var shortOutput: String {
return "ViewQuery Debug: \(description)"
}
public func pretty(indent:Int?) -> String {
var output = repeatElement(" " , count: (indent ?? 0) * 4).joined()
if let prefix = prefix {
output += "\(prefix) "
}
output += "\(icon) "
output += message
if let suffix = suffix {
output += " \(suffix)"
}
if options.contains(.expanded) {
output += "\n"
}
return output
}
public mutating func prepend(_ string:String) {
if let prefix = prefix {
self.prefix = "\(string) " + prefix
} else {
self.prefix = string
}
}
public mutating func append(_ string:String) {
if let suffix = suffix {
self.suffix = suffix + " \(string)"
} else {
self.suffix = string
}
}
}
public struct Result : ApiDebugPrintable {
public var options:ApiDebugOptions
fileprivate var message:String
public var description: String {
return message
}
public var shortOutput: String {
return "ViewQuery Result: \(description)"
}
public func pretty(indent:Int?) -> String {
var output = repeatElement(" " , count: (indent ?? 4) * 4).joined()
output += "🎁 "
output += description
if options.contains(.expanded) {
output += "\n"
}
return output
}
}
// TODO: ✅ Consider mapping argument calls to colons in the standard #function macro.
// This would obviate some brittle debug code (the parameter names) but beware the result
// would not be exactly the same as it is now. #function uses *external* argument names
// (which when no external would be _), instead of the current *internal* argument names
// which frequently are more helpful.
public struct Method : ApiDebugPrintable {
public let options:ApiDebugOptions
fileprivate let wrapper:Any
fileprivate let method:String
fileprivate var params:[String]?
fileprivate var vals:[Any?]?
fileprivate let delegates:Bool
public var description:String {
let isInit = method == "init"
var output = options.contains(.compact) ? "" : (isInit ? "🚛 " : "🚜 ")
output += String(describing:type(of:wrapper))
if isInit {
// Don't add the method name because inits don't count.
// Example: ViewMutator(..)
} else {
// remove from first open parens onward
// this allows passing #function to this.
output += "." + method.trim(from: "(")
// Example: ViewMutator.center(..)
}
output += "("
if let params = self.params, let values = self.vals {
for i in 0..<(params.count) {
guard i >= values.startIndex && i < values.endIndex else {
continue
}
output += params[i] + ":"
let _val = values[i] // this returns an optional
if let value = _val {
if let displayStyle = Mirror(reflecting: value).displayStyle {
switch displayStyle {
case .class :
output += String(describing: type(of:value))
if value is NSObject {
// For NSObjects/UIView include the memory address
output += " (" + (value as! NSObject).memoryAddress(shortened: true) + ")"
}
default : // .enum, .collection, .struct, .tuple, .dictionary, .set
output += String(describing:value)
}
} else {
// All other primitive values, output as is.
output += String(describing: value)
}
} else {
output += "nil"
}
if i < params.count - 1 {
output += ", "
}
}
}
output += ")"
if delegates && !options.contains(.compact) {
// The method called for this debug delegates to another method with debug information.
output += " ..."
}
return output
}
public var shortOutput: String {
return "ViewQuery Method: \(description)"
}
public func pretty(indent:Int?) -> String {
var output = ""
if indent == nil {
// extra line for first indent
output += "\n"
}
let indentString = repeatElement(" ", count: (indent ?? 0) * 4).joined()
output += indentString
output += repeatElement("▪️", count: 30).joined()
output += "\n"
output += indentString
output += description
if options.contains(.expanded) {
output += "\n"
}
return output
}
}
}
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
internal func _abstract(
methodName: StaticString = #function,
file: StaticString = #file, line: UInt = #line
) -> Never {
#if INTERNAL_CHECKS_ENABLED
_fatalErrorMessage("abstract method", methodName, file: file, line: line,
flags: _fatalErrorFlags())
#else
_conditionallyUnreachable()
#endif
}
// MARK: Type-erased abstract base classes
// NOTE: older runtimes had Swift.AnyKeyPath as the ObjC name.
// The two must coexist, so it was renamed. The old name must not be
// used in the new runtime. _TtCs11_AnyKeyPath is the mangled name for
// Swift._AnyKeyPath.
@_objcRuntimeName(_TtCs11_AnyKeyPath)
/// A type-erased key path, from any root type to any resulting value
/// type.
public class AnyKeyPath: Hashable, _AppendKeyPath {
/// The root type for this key path.
@inlinable
public static var rootType: Any.Type {
return _rootAndValueType.root
}
/// The value type for this key path.
@inlinable
public static var valueType: Any.Type {
return _rootAndValueType.value
}
internal final var _kvcKeyPathStringPtr: UnsafePointer<CChar>?
/// The hash value.
final public var hashValue: Int {
return _hashValue(for: self)
}
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@_effects(releasenone)
final public func hash(into hasher: inout Hasher) {
ObjectIdentifier(type(of: self)).hash(into: &hasher)
return withBuffer {
var buffer = $0
if buffer.data.isEmpty { return }
while true {
let (component, type) = buffer.next()
hasher.combine(component.value)
if let type = type {
hasher.combine(unsafeBitCast(type, to: Int.self))
} else {
break
}
}
}
}
public static func ==(a: AnyKeyPath, b: AnyKeyPath) -> Bool {
// Fast-path identical objects
if a === b {
return true
}
// Short-circuit differently-typed key paths
if type(of: a) != type(of: b) {
return false
}
return a.withBuffer {
var aBuffer = $0
return b.withBuffer {
var bBuffer = $0
// Two equivalent key paths should have the same reference prefix
if aBuffer.hasReferencePrefix != bBuffer.hasReferencePrefix {
return false
}
// Identity is equal to identity
if aBuffer.data.isEmpty {
return bBuffer.data.isEmpty
}
while true {
let (aComponent, aType) = aBuffer.next()
let (bComponent, bType) = bBuffer.next()
if aComponent.header.endOfReferencePrefix
!= bComponent.header.endOfReferencePrefix
|| aComponent.value != bComponent.value
|| aType != bType {
return false
}
if aType == nil {
return true
}
}
}
}
}
// SPI for the Foundation overlay to allow interop with KVC keypath-based
// APIs.
public var _kvcKeyPathString: String? {
@_semantics("keypath.kvcKeyPathString")
get {
guard let ptr = _kvcKeyPathStringPtr else { return nil }
return String(validatingUTF8: ptr)
}
}
// MARK: Implementation details
// Prevent normal initialization. We use tail allocation via
// allocWithTailElems().
@available(*, unavailable)
internal init() {
_internalInvariantFailure("use _create(...)")
}
@usableFromInline
internal class var _rootAndValueType: (root: Any.Type, value: Any.Type) {
_abstract()
}
internal static func _create(
capacityInBytes bytes: Int,
initializedBy body: (UnsafeMutableRawBufferPointer) -> Void
) -> Self {
_internalInvariant(bytes > 0 && bytes % 4 == 0,
"capacity must be multiple of 4 bytes")
let result = Builtin.allocWithTailElems_1(self, (bytes/4)._builtinWordValue,
Int32.self)
result._kvcKeyPathStringPtr = nil
let base = UnsafeMutableRawPointer(Builtin.projectTailElems(result,
Int32.self))
body(UnsafeMutableRawBufferPointer(start: base, count: bytes))
return result
}
final internal func withBuffer<T>(_ f: (KeyPathBuffer) throws -> T) rethrows -> T {
defer { _fixLifetime(self) }
let base = UnsafeRawPointer(Builtin.projectTailElems(self, Int32.self))
return try f(KeyPathBuffer(base: base))
}
@usableFromInline // Exposed as public API by MemoryLayout<Root>.offset(of:)
internal var _storedInlineOffset: Int? {
return withBuffer {
var buffer = $0
// The identity key path is effectively a stored keypath of type Self
// at offset zero
if buffer.data.isEmpty { return 0 }
var offset = 0
while true {
let (rawComponent, optNextType) = buffer.next()
switch rawComponent.header.kind {
case .struct:
offset += rawComponent._structOrClassOffset
case .class, .computed, .optionalChain, .optionalForce, .optionalWrap, .external:
return .none
}
if optNextType == nil { return .some(offset) }
}
}
}
}
/// A partially type-erased key path, from a concrete root type to any
/// resulting value type.
public class PartialKeyPath<Root>: AnyKeyPath { }
// MARK: Concrete implementations
internal enum KeyPathKind { case readOnly, value, reference }
/// A key path from a specific root type to a specific resulting value type.
public class KeyPath<Root, Value>: PartialKeyPath<Root> {
@usableFromInline
internal final override class var _rootAndValueType: (
root: Any.Type,
value: Any.Type
) {
return (Root.self, Value.self)
}
// MARK: Implementation
internal typealias Kind = KeyPathKind
internal class var kind: Kind { return .readOnly }
internal static func appendedType<AppendedValue>(
with t: KeyPath<Value, AppendedValue>.Type
) -> KeyPath<Root, AppendedValue>.Type {
let resultKind: Kind
switch (self.kind, t.kind) {
case (_, .reference):
resultKind = .reference
case (let x, .value):
resultKind = x
default:
resultKind = .readOnly
}
switch resultKind {
case .readOnly:
return KeyPath<Root, AppendedValue>.self
case .value:
return WritableKeyPath.self
case .reference:
return ReferenceWritableKeyPath.self
}
}
@usableFromInline
internal final func _projectReadOnly(from root: Root) -> Value {
// TODO: For perf, we could use a local growable buffer instead of Any
var curBase: Any = root
return withBuffer {
var buffer = $0
if buffer.data.isEmpty {
return unsafeBitCast(root, to: Value.self)
}
while true {
let (rawComponent, optNextType) = buffer.next()
let valueType = optNextType ?? Value.self
let isLast = optNextType == nil
func project<CurValue>(_ base: CurValue) -> Value? {
func project2<NewValue>(_: NewValue.Type) -> Value? {
switch rawComponent._projectReadOnly(base,
to: NewValue.self, endingWith: Value.self) {
case .continue(let newBase):
if isLast {
_internalInvariant(NewValue.self == Value.self,
"key path does not terminate in correct type")
return unsafeBitCast(newBase, to: Value.self)
} else {
curBase = newBase
return nil
}
case .break(let result):
return result
}
}
return _openExistential(valueType, do: project2)
}
if let result = _openExistential(curBase, do: project) {
return result
}
}
}
}
deinit {
withBuffer { $0.destroy() }
}
}
/// A key path that supports reading from and writing to the resulting value.
public class WritableKeyPath<Root, Value>: KeyPath<Root, Value> {
// MARK: Implementation detail
internal override class var kind: Kind { return .value }
// `base` is assumed to be undergoing a formal access for the duration of the
// call, so must not be mutated by an alias
@usableFromInline
internal func _projectMutableAddress(from base: UnsafePointer<Root>)
-> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
var p = UnsafeRawPointer(base)
var type: Any.Type = Root.self
var keepAlive: AnyObject?
return withBuffer {
var buffer = $0
_internalInvariant(!buffer.hasReferencePrefix,
"WritableKeyPath should not have a reference prefix")
if buffer.data.isEmpty {
return (
UnsafeMutablePointer<Value>(
mutating: p.assumingMemoryBound(to: Value.self)),
nil)
}
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent._projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == UnsafeRawPointer(base),
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(type, do: project)
if optNextType == nil { break }
type = nextType
}
// TODO: With coroutines, it would be better to yield here, so that
// we don't need the hack of the keepAlive reference to manage closing
// accesses.
let typedPointer = p.assumingMemoryBound(to: Value.self)
return (pointer: UnsafeMutablePointer(mutating: typedPointer),
owner: keepAlive)
}
}
}
/// A key path that supports reading from and writing to the resulting value
/// with reference semantics.
public class ReferenceWritableKeyPath<
Root, Value
>: WritableKeyPath<Root, Value> {
// MARK: Implementation detail
internal final override class var kind: Kind { return .reference }
@usableFromInline
internal final func _projectMutableAddress(from origBase: Root)
-> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
var keepAlive: AnyObject?
let address: UnsafeMutablePointer<Value> = withBuffer {
var buffer = $0
// Project out the reference prefix.
var base: Any = origBase
while buffer.hasReferencePrefix {
let (rawComponent, optNextType) = buffer.next()
_internalInvariant(optNextType != nil,
"reference prefix should not go to end of buffer")
let nextType = optNextType.unsafelyUnwrapped
func project<NewValue>(_: NewValue.Type) -> Any {
func project2<CurValue>(_ base: CurValue) -> Any {
return rawComponent._projectReadOnly(
base, to: NewValue.self, endingWith: Value.self)
.assumingContinue
}
return _openExistential(base, do: project2)
}
base = _openExistential(nextType, do: project)
}
// Start formal access to the mutable value, based on the final base
// value.
func formalMutation<MutationRoot>(_ base: MutationRoot)
-> UnsafeMutablePointer<Value> {
var base2 = base
return withUnsafeBytes(of: &base2) { baseBytes in
var p = baseBytes.baseAddress.unsafelyUnwrapped
var curType: Any.Type = MutationRoot.self
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent._projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == baseBytes.baseAddress,
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(curType, do: project)
if optNextType == nil { break }
curType = nextType
}
let typedPointer = p.assumingMemoryBound(to: Value.self)
return UnsafeMutablePointer(mutating: typedPointer)
}
}
return _openExistential(base, do: formalMutation)
}
return (address, keepAlive)
}
}
// MARK: Implementation details
internal enum KeyPathComponentKind {
/// The keypath references an externally-defined property or subscript whose
/// component describes how to interact with the key path.
case external
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`
/// The keypath projects using a getter/setter pair.
case computed
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
}
internal struct ComputedPropertyID: Hashable {
internal var value: Int
internal var kind: KeyPathComputedIDKind
internal static func ==(
x: ComputedPropertyID, y: ComputedPropertyID
) -> Bool {
return x.value == y.value
&& x.kind == y.kind
}
internal func hash(into hasher: inout Hasher) {
hasher.combine(value)
hasher.combine(kind)
}
}
internal struct ComputedAccessorsPtr {
#if INTERNAL_CHECKS_ENABLED
internal let header: RawKeyPathComponent.Header
#endif
internal let _value: UnsafeRawPointer
init(header: RawKeyPathComponent.Header, value: UnsafeRawPointer) {
#if INTERNAL_CHECKS_ENABLED
self.header = header
#endif
self._value = value
}
@_transparent
static var getterPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_Getter)
}
@_transparent
static var nonmutatingSetterPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_NonmutatingSetter)
}
@_transparent
static var mutatingSetterPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_MutatingSetter)
}
internal typealias Getter<CurValue, NewValue> = @convention(thin)
(CurValue, UnsafeRawPointer, Int) -> NewValue
internal typealias NonmutatingSetter<CurValue, NewValue> = @convention(thin)
(NewValue, CurValue, UnsafeRawPointer, Int) -> ()
internal typealias MutatingSetter<CurValue, NewValue> = @convention(thin)
(NewValue, inout CurValue, UnsafeRawPointer, Int) -> ()
internal var getterPtr: UnsafeRawPointer {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(header.kind == .computed,
"not a computed property")
#endif
return _value
}
internal var setterPtr: UnsafeRawPointer {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(header.isComputedSettable,
"not a settable property")
#endif
return _value + MemoryLayout<Int>.size
}
internal func getter<CurValue, NewValue>()
-> Getter<CurValue, NewValue> {
return getterPtr._loadAddressDiscriminatedFunctionPointer(
as: Getter.self,
discriminator: ComputedAccessorsPtr.getterPtrAuthKey)
}
internal func nonmutatingSetter<CurValue, NewValue>()
-> NonmutatingSetter<CurValue, NewValue> {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(header.isComputedSettable && !header.isComputedMutating,
"not a nonmutating settable property")
#endif
return setterPtr._loadAddressDiscriminatedFunctionPointer(
as: NonmutatingSetter.self,
discriminator: ComputedAccessorsPtr.nonmutatingSetterPtrAuthKey)
}
internal func mutatingSetter<CurValue, NewValue>()
-> MutatingSetter<CurValue, NewValue> {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(header.isComputedSettable && header.isComputedMutating,
"not a mutating settable property")
#endif
return setterPtr._loadAddressDiscriminatedFunctionPointer(
as: MutatingSetter.self,
discriminator: ComputedAccessorsPtr.mutatingSetterPtrAuthKey)
}
}
internal struct ComputedArgumentWitnessesPtr {
internal let _value: UnsafeRawPointer
init(_ value: UnsafeRawPointer) {
self._value = value
}
@_transparent
static var destroyPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentDestroy)
}
@_transparent
static var copyPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentCopy)
}
@_transparent
static var equalsPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentEquals)
}
@_transparent
static var hashPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentHash)
}
@_transparent
static var layoutPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentLayout)
}
@_transparent
static var initPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentInit)
}
internal typealias Destroy = @convention(thin)
(_ instanceArguments: UnsafeMutableRawPointer, _ size: Int) -> ()
internal typealias Copy = @convention(thin)
(_ srcInstanceArguments: UnsafeRawPointer,
_ destInstanceArguments: UnsafeMutableRawPointer,
_ size: Int) -> ()
internal typealias Equals = @convention(thin)
(_ xInstanceArguments: UnsafeRawPointer,
_ yInstanceArguments: UnsafeRawPointer,
_ size: Int) -> Bool
// FIXME(hasher) Combine to an inout Hasher instead
internal typealias Hash = @convention(thin)
(_ instanceArguments: UnsafeRawPointer,
_ size: Int) -> Int
// The witnesses are stored as address-discriminated authenticated
// pointers.
internal var destroy: Destroy? {
return _value._loadAddressDiscriminatedFunctionPointer(
as: Optional<Destroy>.self,
discriminator: ComputedArgumentWitnessesPtr.destroyPtrAuthKey)
}
internal var copy: Copy {
return _value._loadAddressDiscriminatedFunctionPointer(
fromByteOffset: MemoryLayout<UnsafeRawPointer>.size,
as: Copy.self,
discriminator: ComputedArgumentWitnessesPtr.copyPtrAuthKey)
}
internal var equals: Equals {
return _value._loadAddressDiscriminatedFunctionPointer(
fromByteOffset: 2*MemoryLayout<UnsafeRawPointer>.size,
as: Equals.self,
discriminator: ComputedArgumentWitnessesPtr.equalsPtrAuthKey)
}
internal var hash: Hash {
return _value._loadAddressDiscriminatedFunctionPointer(
fromByteOffset: 3*MemoryLayout<UnsafeRawPointer>.size,
as: Hash.self,
discriminator: ComputedArgumentWitnessesPtr.hashPtrAuthKey)
}
}
internal enum KeyPathComponent: Hashable {
internal struct ArgumentRef {
internal init(
data: UnsafeRawBufferPointer,
witnesses: ComputedArgumentWitnessesPtr,
witnessSizeAdjustment: Int
) {
self.data = data
self.witnesses = witnesses
self.witnessSizeAdjustment = witnessSizeAdjustment
}
internal var data: UnsafeRawBufferPointer
internal var witnesses: ComputedArgumentWitnessesPtr
internal var witnessSizeAdjustment: Int
}
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`(offset: Int)
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`(offset: Int)
/// The keypath projects using a getter.
case get(id: ComputedPropertyID,
accessors: ComputedAccessorsPtr,
argument: ArgumentRef?)
/// The keypath projects using a getter/setter pair. The setter can mutate
/// the base value in-place.
case mutatingGetSet(id: ComputedPropertyID,
accessors: ComputedAccessorsPtr,
argument: ArgumentRef?)
/// The keypath projects using a getter/setter pair that does not mutate its
/// base.
case nonmutatingGetSet(id: ComputedPropertyID,
accessors: ComputedAccessorsPtr,
argument: ArgumentRef?)
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
internal static func ==(a: KeyPathComponent, b: KeyPathComponent) -> Bool {
switch (a, b) {
case (.struct(offset: let a), .struct(offset: let b)),
(.class (offset: let a), .class (offset: let b)):
return a == b
case (.optionalChain, .optionalChain),
(.optionalForce, .optionalForce),
(.optionalWrap, .optionalWrap):
return true
case (.get(id: let id1, accessors: _, argument: let argument1),
.get(id: let id2, accessors: _, argument: let argument2)),
(.mutatingGetSet(id: let id1, accessors: _, argument: let argument1),
.mutatingGetSet(id: let id2, accessors: _, argument: let argument2)),
(.nonmutatingGetSet(id: let id1, accessors: _, argument: let argument1),
.nonmutatingGetSet(id: let id2, accessors: _, argument: let argument2)):
if id1 != id2 {
return false
}
if let arg1 = argument1, let arg2 = argument2 {
return arg1.witnesses.equals(
arg1.data.baseAddress.unsafelyUnwrapped,
arg2.data.baseAddress.unsafelyUnwrapped,
arg1.data.count - arg1.witnessSizeAdjustment)
}
// If only one component has arguments, that should indicate that the
// only arguments in that component were generic captures and therefore
// not affecting equality.
return true
case (.struct, _),
(.class, _),
(.optionalChain, _),
(.optionalForce, _),
(.optionalWrap, _),
(.get, _),
(.mutatingGetSet, _),
(.nonmutatingGetSet, _):
return false
}
}
@_effects(releasenone)
internal func hash(into hasher: inout Hasher) {
func appendHashFromArgument(
_ argument: KeyPathComponent.ArgumentRef?
) {
if let argument = argument {
let hash = argument.witnesses.hash(
argument.data.baseAddress.unsafelyUnwrapped,
argument.data.count - argument.witnessSizeAdjustment)
// Returning 0 indicates that the arguments should not impact the
// hash value of the overall key path.
// FIXME(hasher): hash witness should just mutate hasher directly
if hash != 0 {
hasher.combine(hash)
}
}
}
switch self {
case .struct(offset: let a):
hasher.combine(0)
hasher.combine(a)
case .class(offset: let b):
hasher.combine(1)
hasher.combine(b)
case .optionalChain:
hasher.combine(2)
case .optionalForce:
hasher.combine(3)
case .optionalWrap:
hasher.combine(4)
case .get(id: let id, accessors: _, argument: let argument):
hasher.combine(5)
hasher.combine(id)
appendHashFromArgument(argument)
case .mutatingGetSet(id: let id, accessors: _, argument: let argument):
hasher.combine(6)
hasher.combine(id)
appendHashFromArgument(argument)
case .nonmutatingGetSet(id: let id, accessors: _, argument: let argument):
hasher.combine(7)
hasher.combine(id)
appendHashFromArgument(argument)
}
}
}
// A class that maintains ownership of another object while a mutable projection
// into it is underway. The lifetime of the instance of this class is also used
// to begin and end exclusive 'modify' access to the projected address.
internal final class ClassHolder<ProjectionType> {
/// The type of the scratch record passed to the runtime to record
/// accesses to guarantee exclusive access.
internal typealias AccessRecord = Builtin.UnsafeValueBuffer
internal var previous: AnyObject?
internal var instance: AnyObject
internal init(previous: AnyObject?, instance: AnyObject) {
self.previous = previous
self.instance = instance
}
internal final class func _create(
previous: AnyObject?,
instance: AnyObject,
accessingAddress address: UnsafeRawPointer,
type: ProjectionType.Type
) -> ClassHolder {
// Tail allocate the UnsafeValueBuffer used as the AccessRecord.
// This avoids a second heap allocation since there is no source-level way to
// initialize a Builtin.UnsafeValueBuffer type and thus we cannot have a
// stored property of that type.
let holder: ClassHolder = Builtin.allocWithTailElems_1(self,
1._builtinWordValue,
AccessRecord.self)
// Initialize the ClassHolder's instance variables. This is done via
// withUnsafeMutablePointer(to:) because the instance was just allocated with
// allocWithTailElems_1 and so we need to make sure to use an initialization
// rather than an assignment.
withUnsafeMutablePointer(to: &holder.previous) {
$0.initialize(to: previous)
}
withUnsafeMutablePointer(to: &holder.instance) {
$0.initialize(to: instance)
}
let accessRecordPtr = Builtin.projectTailElems(holder, AccessRecord.self)
// Begin a 'modify' access to the address. This access is ended in
// ClassHolder's deinitializer.
Builtin.beginUnpairedModifyAccess(address._rawValue, accessRecordPtr, type)
return holder
}
deinit {
let accessRecordPtr = Builtin.projectTailElems(self, AccessRecord.self)
// Ends the access begun in _create().
Builtin.endUnpairedAccess(accessRecordPtr)
}
}
// A class that triggers writeback to a pointer when destroyed.
internal final class MutatingWritebackBuffer<CurValue, NewValue> {
internal let previous: AnyObject?
internal let base: UnsafeMutablePointer<CurValue>
internal let set: ComputedAccessorsPtr.MutatingSetter<CurValue, NewValue>
internal let argument: UnsafeRawPointer
internal let argumentSize: Int
internal var value: NewValue
deinit {
set(value, &base.pointee, argument, argumentSize)
}
internal init(previous: AnyObject?,
base: UnsafeMutablePointer<CurValue>,
set: @escaping ComputedAccessorsPtr.MutatingSetter<CurValue, NewValue>,
argument: UnsafeRawPointer,
argumentSize: Int,
value: NewValue) {
self.previous = previous
self.base = base
self.set = set
self.argument = argument
self.argumentSize = argumentSize
self.value = value
}
}
// A class that triggers writeback to a non-mutated value when destroyed.
internal final class NonmutatingWritebackBuffer<CurValue, NewValue> {
internal let previous: AnyObject?
internal let base: CurValue
internal let set: ComputedAccessorsPtr.NonmutatingSetter<CurValue, NewValue>
internal let argument: UnsafeRawPointer
internal let argumentSize: Int
internal var value: NewValue
deinit {
set(value, base, argument, argumentSize)
}
internal
init(previous: AnyObject?,
base: CurValue,
set: @escaping ComputedAccessorsPtr.NonmutatingSetter<CurValue, NewValue>,
argument: UnsafeRawPointer,
argumentSize: Int,
value: NewValue) {
self.previous = previous
self.base = base
self.set = set
self.argument = argument
self.argumentSize = argumentSize
self.value = value
}
}
internal typealias KeyPathComputedArgumentLayoutFn = @convention(thin)
(_ patternArguments: UnsafeRawPointer?) -> (size: Int, alignmentMask: Int)
internal typealias KeyPathComputedArgumentInitializerFn = @convention(thin)
(_ patternArguments: UnsafeRawPointer?,
_ instanceArguments: UnsafeMutableRawPointer) -> ()
internal enum KeyPathComputedIDKind {
case pointer
case storedPropertyIndex
case vtableOffset
}
internal enum KeyPathComputedIDResolution {
case resolved
case indirectPointer
case functionCall
}
internal struct RawKeyPathComponent {
internal init(header: Header, body: UnsafeRawBufferPointer) {
self.header = header
self.body = body
}
internal var header: Header
internal var body: UnsafeRawBufferPointer
@_transparent
static var metadataAccessorPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_MetadataAccessor)
}
internal struct Header {
internal static var payloadMask: UInt32 {
return _SwiftKeyPathComponentHeader_PayloadMask
}
internal static var discriminatorMask: UInt32 {
return _SwiftKeyPathComponentHeader_DiscriminatorMask
}
internal static var discriminatorShift: UInt32 {
return _SwiftKeyPathComponentHeader_DiscriminatorShift
}
internal static var externalTag: UInt32 {
return _SwiftKeyPathComponentHeader_ExternalTag
}
internal static var structTag: UInt32 {
return _SwiftKeyPathComponentHeader_StructTag
}
internal static var computedTag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedTag
}
internal static var classTag: UInt32 {
return _SwiftKeyPathComponentHeader_ClassTag
}
internal static var optionalTag: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalTag
}
internal static var optionalChainPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalChainPayload
}
internal static var optionalWrapPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalWrapPayload
}
internal static var optionalForcePayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalForcePayload
}
internal static var endOfReferencePrefixFlag: UInt32 {
return _SwiftKeyPathComponentHeader_EndOfReferencePrefixFlag
}
internal static var storedMutableFlag: UInt32 {
return _SwiftKeyPathComponentHeader_StoredMutableFlag
}
internal static var storedOffsetPayloadMask: UInt32 {
return _SwiftKeyPathComponentHeader_StoredOffsetPayloadMask
}
internal static var outOfLineOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OutOfLineOffsetPayload
}
internal static var unresolvedFieldOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_UnresolvedFieldOffsetPayload
}
internal static var unresolvedIndirectOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_UnresolvedIndirectOffsetPayload
}
internal static var maximumOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_MaximumOffsetPayload
}
internal var isStoredMutable: Bool {
_internalInvariant(kind == .struct || kind == .class)
return _value & Header.storedMutableFlag != 0
}
internal static var computedMutatingFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedMutatingFlag
}
internal var isComputedMutating: Bool {
_internalInvariant(kind == .computed)
return _value & Header.computedMutatingFlag != 0
}
internal static var computedSettableFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedSettableFlag
}
internal var isComputedSettable: Bool {
_internalInvariant(kind == .computed)
return _value & Header.computedSettableFlag != 0
}
internal static var computedIDByStoredPropertyFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDByStoredPropertyFlag
}
internal static var computedIDByVTableOffsetFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDByVTableOffsetFlag
}
internal var computedIDKind: KeyPathComputedIDKind {
let storedProperty = _value & Header.computedIDByStoredPropertyFlag != 0
let vtableOffset = _value & Header.computedIDByVTableOffsetFlag != 0
switch (storedProperty, vtableOffset) {
case (true, true):
_internalInvariantFailure("not allowed")
case (true, false):
return .storedPropertyIndex
case (false, true):
return .vtableOffset
case (false, false):
return .pointer
}
}
internal static var computedHasArgumentsFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedHasArgumentsFlag
}
internal var hasComputedArguments: Bool {
_internalInvariant(kind == .computed)
return _value & Header.computedHasArgumentsFlag != 0
}
// If a computed component is instantiated from an external property
// descriptor, and both components carry arguments, we need to carry some
// extra matter to be able to map between the client and external generic
// contexts.
internal static var computedInstantiatedFromExternalWithArgumentsFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedInstantiatedFromExternalWithArgumentsFlag
}
internal var isComputedInstantiatedFromExternalWithArguments: Bool {
get {
_internalInvariant(kind == .computed)
return
_value & Header.computedInstantiatedFromExternalWithArgumentsFlag != 0
}
set {
_internalInvariant(kind == .computed)
_value =
_value & ~Header.computedInstantiatedFromExternalWithArgumentsFlag
| (newValue ? Header.computedInstantiatedFromExternalWithArgumentsFlag
: 0)
}
}
internal static var externalWithArgumentsExtraSize: Int {
return MemoryLayout<Int>.size
}
internal static var computedIDResolutionMask: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDResolutionMask
}
internal static var computedIDResolved: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDResolved
}
internal static var computedIDUnresolvedIndirectPointer: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedIndirectPointer
}
internal static var computedIDUnresolvedFunctionCall: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedFunctionCall
}
internal var computedIDResolution: KeyPathComputedIDResolution {
switch payload & Header.computedIDResolutionMask {
case Header.computedIDResolved:
return .resolved
case Header.computedIDUnresolvedIndirectPointer:
return .indirectPointer
case Header.computedIDUnresolvedFunctionCall:
return .functionCall
default:
_internalInvariantFailure("invalid key path resolution")
}
}
internal var _value: UInt32
internal var discriminator: UInt32 {
get {
return (_value & Header.discriminatorMask) >> Header.discriminatorShift
}
set {
let shifted = newValue << Header.discriminatorShift
_internalInvariant(shifted & Header.discriminatorMask == shifted,
"discriminator doesn't fit")
_value = _value & ~Header.discriminatorMask | shifted
}
}
internal var payload: UInt32 {
get {
return _value & Header.payloadMask
}
set {
_internalInvariant(newValue & Header.payloadMask == newValue,
"payload too big")
_value = _value & ~Header.payloadMask | newValue
}
}
internal var storedOffsetPayload: UInt32 {
get {
_internalInvariant(kind == .struct || kind == .class,
"not a stored component")
return _value & Header.storedOffsetPayloadMask
}
set {
_internalInvariant(kind == .struct || kind == .class,
"not a stored component")
_internalInvariant(newValue & Header.storedOffsetPayloadMask == newValue,
"payload too big")
_value = _value & ~Header.storedOffsetPayloadMask | newValue
}
}
internal var endOfReferencePrefix: Bool {
get {
return _value & Header.endOfReferencePrefixFlag != 0
}
set {
if newValue {
_value |= Header.endOfReferencePrefixFlag
} else {
_value &= ~Header.endOfReferencePrefixFlag
}
}
}
internal var kind: KeyPathComponentKind {
switch (discriminator, payload) {
case (Header.externalTag, _):
return .external
case (Header.structTag, _):
return .struct
case (Header.classTag, _):
return .class
case (Header.computedTag, _):
return .computed
case (Header.optionalTag, Header.optionalChainPayload):
return .optionalChain
case (Header.optionalTag, Header.optionalWrapPayload):
return .optionalWrap
case (Header.optionalTag, Header.optionalForcePayload):
return .optionalForce
default:
_internalInvariantFailure("invalid header")
}
}
// The component header is 4 bytes, but may be followed by an aligned
// pointer field for some kinds of component, forcing padding.
internal static var pointerAlignmentSkew: Int {
return MemoryLayout<Int>.size - MemoryLayout<Int32>.size
}
internal var isTrivialPropertyDescriptor: Bool {
return _value ==
_SwiftKeyPathComponentHeader_TrivialPropertyDescriptorMarker
}
/// If this is the header for a component in a key path pattern, return
/// the size of the body of the component.
internal var patternComponentBodySize: Int {
return _componentBodySize(forPropertyDescriptor: false)
}
/// If this is the header for a property descriptor, return
/// the size of the body of the component.
internal var propertyDescriptorBodySize: Int {
if isTrivialPropertyDescriptor { return 0 }
return _componentBodySize(forPropertyDescriptor: true)
}
internal func _componentBodySize(forPropertyDescriptor: Bool) -> Int {
switch kind {
case .struct, .class:
if storedOffsetPayload == Header.unresolvedFieldOffsetPayload
|| storedOffsetPayload == Header.outOfLineOffsetPayload
|| storedOffsetPayload == Header.unresolvedIndirectOffsetPayload {
// A 32-bit offset is stored in the body.
return MemoryLayout<UInt32>.size
}
// Otherwise, there's no body.
return 0
case .external:
// The body holds a pointer to the external property descriptor,
// and some number of substitution arguments, the count of which is
// in the payload.
return 4 * (1 + Int(payload))
case .computed:
// The body holds at minimum the id and getter.
var size = 8
// If settable, it also holds the setter.
if isComputedSettable {
size += 4
}
// If there are arguments, there's also a layout function,
// witness table, and initializer function.
// Property descriptors never carry argument information, though.
if !forPropertyDescriptor && hasComputedArguments {
size += 12
}
return size
case .optionalForce, .optionalChain, .optionalWrap:
// Otherwise, there's no body.
return 0
}
}
init(discriminator: UInt32, payload: UInt32) {
_value = 0
self.discriminator = discriminator
self.payload = payload
}
init(optionalForce: ()) {
self.init(discriminator: Header.optionalTag,
payload: Header.optionalForcePayload)
}
init(optionalWrap: ()) {
self.init(discriminator: Header.optionalTag,
payload: Header.optionalWrapPayload)
}
init(optionalChain: ()) {
self.init(discriminator: Header.optionalTag,
payload: Header.optionalChainPayload)
}
init(stored kind: KeyPathStructOrClass,
mutable: Bool,
inlineOffset: UInt32) {
let discriminator: UInt32
switch kind {
case .struct: discriminator = Header.structTag
case .class: discriminator = Header.classTag
}
_internalInvariant(inlineOffset <= Header.maximumOffsetPayload)
let payload = inlineOffset
| (mutable ? Header.storedMutableFlag : 0)
self.init(discriminator: discriminator,
payload: payload)
}
init(storedWithOutOfLineOffset kind: KeyPathStructOrClass,
mutable: Bool) {
let discriminator: UInt32
switch kind {
case .struct: discriminator = Header.structTag
case .class: discriminator = Header.classTag
}
let payload = Header.outOfLineOffsetPayload
| (mutable ? Header.storedMutableFlag : 0)
self.init(discriminator: discriminator,
payload: payload)
}
init(computedWithIDKind kind: KeyPathComputedIDKind,
mutating: Bool,
settable: Bool,
hasArguments: Bool,
instantiatedFromExternalWithArguments: Bool) {
let discriminator = Header.computedTag
var payload =
(mutating ? Header.computedMutatingFlag : 0)
| (settable ? Header.computedSettableFlag : 0)
| (hasArguments ? Header.computedHasArgumentsFlag : 0)
| (instantiatedFromExternalWithArguments
? Header.computedInstantiatedFromExternalWithArgumentsFlag : 0)
switch kind {
case .pointer:
break
case .storedPropertyIndex:
payload |= Header.computedIDByStoredPropertyFlag
case .vtableOffset:
payload |= Header.computedIDByVTableOffsetFlag
}
self.init(discriminator: discriminator,
payload: payload)
}
}
internal var bodySize: Int {
let ptrSize = MemoryLayout<Int>.size
switch header.kind {
case .struct, .class:
if header.storedOffsetPayload == Header.outOfLineOffsetPayload {
return 4 // overflowed
}
return 0
case .external:
_internalInvariantFailure("should be instantiated away")
case .optionalChain, .optionalForce, .optionalWrap:
return 0
case .computed:
// align to pointer, minimum two pointers for id and get
var total = Header.pointerAlignmentSkew + ptrSize * 2
// additional word for a setter
if header.isComputedSettable {
total += ptrSize
}
// include the argument size
if header.hasComputedArguments {
// two words for argument header: size, witnesses
total += ptrSize * 2
// size of argument area
total += _computedArgumentSize
if header.isComputedInstantiatedFromExternalWithArguments {
total += Header.externalWithArgumentsExtraSize
}
}
return total
}
}
internal var _structOrClassOffset: Int {
_internalInvariant(header.kind == .struct || header.kind == .class,
"no offset for this kind")
// An offset too large to fit inline is represented by a signal and stored
// in the body.
if header.storedOffsetPayload == Header.outOfLineOffsetPayload {
// Offset overflowed into body
_internalInvariant(body.count >= MemoryLayout<UInt32>.size,
"component not big enough")
return Int(body.load(as: UInt32.self))
}
return Int(header.storedOffsetPayload)
}
internal var _computedIDValue: Int {
_internalInvariant(header.kind == .computed,
"not a computed property")
return body.load(fromByteOffset: Header.pointerAlignmentSkew,
as: Int.self)
}
internal var _computedID: ComputedPropertyID {
_internalInvariant(header.kind == .computed,
"not a computed property")
return ComputedPropertyID(
value: _computedIDValue,
kind: header.computedIDKind)
}
internal var _computedAccessors: ComputedAccessorsPtr {
_internalInvariant(header.kind == .computed,
"not a computed property")
return ComputedAccessorsPtr(
header: header,
value: body.baseAddress.unsafelyUnwrapped +
Header.pointerAlignmentSkew + MemoryLayout<Int>.size)
}
internal var _computedArgumentHeaderPointer: UnsafeRawPointer {
_internalInvariant(header.hasComputedArguments, "no arguments")
return body.baseAddress.unsafelyUnwrapped
+ Header.pointerAlignmentSkew
+ MemoryLayout<Int>.size *
(header.isComputedSettable ? 3 : 2)
}
internal var _computedArgumentSize: Int {
return _computedArgumentHeaderPointer.load(as: Int.self)
}
internal
var _computedArgumentWitnesses: ComputedArgumentWitnessesPtr {
return _computedArgumentHeaderPointer.load(
fromByteOffset: MemoryLayout<Int>.size,
as: ComputedArgumentWitnessesPtr.self)
}
internal var _computedArguments: UnsafeRawPointer {
var base = _computedArgumentHeaderPointer + MemoryLayout<Int>.size * 2
// If the component was instantiated from an external property descriptor
// with its own arguments, we include some additional capture info to
// be able to map to the original argument context by adjusting the size
// passed to the witness operations.
if header.isComputedInstantiatedFromExternalWithArguments {
base += Header.externalWithArgumentsExtraSize
}
return base
}
internal var _computedMutableArguments: UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(mutating: _computedArguments)
}
internal var _computedArgumentWitnessSizeAdjustment: Int {
if header.isComputedInstantiatedFromExternalWithArguments {
return _computedArguments.load(
fromByteOffset: -Header.externalWithArgumentsExtraSize,
as: Int.self)
}
return 0
}
internal var value: KeyPathComponent {
switch header.kind {
case .struct:
return .struct(offset: _structOrClassOffset)
case .class:
return .class(offset: _structOrClassOffset)
case .optionalChain:
return .optionalChain
case .optionalForce:
return .optionalForce
case .optionalWrap:
return .optionalWrap
case .computed:
let isSettable = header.isComputedSettable
let isMutating = header.isComputedMutating
let id = _computedID
let accessors = _computedAccessors
// Argument value is unused if there are no arguments.
let argument: KeyPathComponent.ArgumentRef?
if header.hasComputedArguments {
argument = KeyPathComponent.ArgumentRef(
data: UnsafeRawBufferPointer(start: _computedArguments,
count: _computedArgumentSize),
witnesses: _computedArgumentWitnesses,
witnessSizeAdjustment: _computedArgumentWitnessSizeAdjustment)
} else {
argument = nil
}
switch (isSettable, isMutating) {
case (false, false):
return .get(id: id, accessors: accessors, argument: argument)
case (true, false):
return .nonmutatingGetSet(id: id,
accessors: accessors,
argument: argument)
case (true, true):
return .mutatingGetSet(id: id,
accessors: accessors,
argument: argument)
case (false, true):
_internalInvariantFailure("impossible")
}
case .external:
_internalInvariantFailure("should have been instantiated away")
}
}
internal func destroy() {
switch header.kind {
case .struct,
.class,
.optionalChain,
.optionalForce,
.optionalWrap:
// trivial
break
case .computed:
// Run destructor, if any
if header.hasComputedArguments,
let destructor = _computedArgumentWitnesses.destroy {
destructor(_computedMutableArguments,
_computedArgumentSize - _computedArgumentWitnessSizeAdjustment)
}
case .external:
_internalInvariantFailure("should have been instantiated away")
}
}
internal func clone(into buffer: inout UnsafeMutableRawBufferPointer,
endOfReferencePrefix: Bool) {
var newHeader = header
newHeader.endOfReferencePrefix = endOfReferencePrefix
var componentSize = MemoryLayout<Header>.size
buffer.storeBytes(of: newHeader, as: Header.self)
switch header.kind {
case .struct,
.class:
if header.storedOffsetPayload == Header.outOfLineOffsetPayload {
let overflowOffset = body.load(as: UInt32.self)
buffer.storeBytes(of: overflowOffset, toByteOffset: 4,
as: UInt32.self)
componentSize += 4
}
case .optionalChain,
.optionalForce,
.optionalWrap:
break
case .computed:
// Fields are pointer-aligned after the header
componentSize += Header.pointerAlignmentSkew
buffer.storeBytes(of: _computedIDValue,
toByteOffset: componentSize,
as: Int.self)
componentSize += MemoryLayout<Int>.size
let accessors = _computedAccessors
(buffer.baseAddress.unsafelyUnwrapped + MemoryLayout<Int>.size * 2)
._copyAddressDiscriminatedFunctionPointer(
from: accessors.getterPtr,
discriminator: ComputedAccessorsPtr.getterPtrAuthKey)
componentSize += MemoryLayout<Int>.size
if header.isComputedSettable {
(buffer.baseAddress.unsafelyUnwrapped + MemoryLayout<Int>.size * 3)
._copyAddressDiscriminatedFunctionPointer(
from: accessors.setterPtr,
discriminator: header.isComputedMutating
? ComputedAccessorsPtr.mutatingSetterPtrAuthKey
: ComputedAccessorsPtr.nonmutatingSetterPtrAuthKey)
componentSize += MemoryLayout<Int>.size
}
if header.hasComputedArguments {
let arguments = _computedArguments
let argumentSize = _computedArgumentSize
buffer.storeBytes(of: argumentSize,
toByteOffset: componentSize,
as: Int.self)
componentSize += MemoryLayout<Int>.size
buffer.storeBytes(of: _computedArgumentWitnesses,
toByteOffset: componentSize,
as: ComputedArgumentWitnessesPtr.self)
componentSize += MemoryLayout<Int>.size
if header.isComputedInstantiatedFromExternalWithArguments {
// Include the extra matter for components instantiated from
// external property descriptors with arguments.
buffer.storeBytes(of: _computedArgumentWitnessSizeAdjustment,
toByteOffset: componentSize,
as: Int.self)
componentSize += MemoryLayout<Int>.size
}
let adjustedSize = argumentSize - _computedArgumentWitnessSizeAdjustment
let argumentDest =
buffer.baseAddress.unsafelyUnwrapped + componentSize
_computedArgumentWitnesses.copy(
arguments,
argumentDest,
adjustedSize)
if header.isComputedInstantiatedFromExternalWithArguments {
// The extra information for external property descriptor arguments
// can always be memcpy'd.
_memcpy(dest: argumentDest + adjustedSize,
src: arguments + adjustedSize,
size: UInt(_computedArgumentWitnessSizeAdjustment))
}
componentSize += argumentSize
}
case .external:
_internalInvariantFailure("should have been instantiated away")
}
buffer = UnsafeMutableRawBufferPointer(
start: buffer.baseAddress.unsafelyUnwrapped + componentSize,
count: buffer.count - componentSize)
}
internal enum ProjectionResult<NewValue, LeafValue> {
/// Continue projecting the key path with the given new value.
case `continue`(NewValue)
/// Stop projecting the key path and use the given value as the final
/// result of the projection.
case `break`(LeafValue)
internal var assumingContinue: NewValue {
switch self {
case .continue(let x):
return x
case .break:
_internalInvariantFailure("should not have stopped key path projection")
}
}
}
internal func _projectReadOnly<CurValue, NewValue, LeafValue>(
_ base: CurValue,
to: NewValue.Type,
endingWith: LeafValue.Type
) -> ProjectionResult<NewValue, LeafValue> {
switch value {
case .struct(let offset):
var base2 = base
return .continue(withUnsafeBytes(of: &base2) {
let p = $0.baseAddress.unsafelyUnwrapped.advanced(by: offset)
// The contents of the struct should be well-typed, so we can assume
// typed memory here.
return p.assumingMemoryBound(to: NewValue.self).pointee
})
case .class(let offset):
_internalInvariant(CurValue.self is AnyObject.Type,
"base is not a class")
let baseObj = unsafeBitCast(base, to: AnyObject.self)
let basePtr = UnsafeRawPointer(Builtin.bridgeToRawPointer(baseObj))
defer { _fixLifetime(baseObj) }
let offsetAddress = basePtr.advanced(by: offset)
// Perform an instantaneous record access on the address in order to
// ensure that the read will not conflict with an already in-progress
// 'modify' access.
Builtin.performInstantaneousReadAccess(offsetAddress._rawValue,
NewValue.self)
return .continue(offsetAddress
.assumingMemoryBound(to: NewValue.self)
.pointee)
case .get(id: _, accessors: let accessors, argument: let argument),
.mutatingGetSet(id: _, accessors: let accessors, argument: let argument),
.nonmutatingGetSet(id: _, accessors: let accessors, argument: let argument):
return .continue(accessors.getter()(base,
argument?.data.baseAddress ?? accessors._value,
argument?.data.count ?? 0))
case .optionalChain:
_internalInvariant(CurValue.self == Optional<NewValue>.self,
"should be unwrapping optional value")
_internalInvariant(_isOptional(LeafValue.self),
"leaf result should be optional")
if let baseValue = unsafeBitCast(base, to: Optional<NewValue>.self) {
return .continue(baseValue)
} else {
// TODO: A more efficient way of getting the `none` representation
// of a dynamically-optional type...
return .break((Optional<()>.none as Any) as! LeafValue)
}
case .optionalForce:
_internalInvariant(CurValue.self == Optional<NewValue>.self,
"should be unwrapping optional value")
return .continue(unsafeBitCast(base, to: Optional<NewValue>.self)!)
case .optionalWrap:
_internalInvariant(NewValue.self == Optional<CurValue>.self,
"should be wrapping optional value")
return .continue(
unsafeBitCast(base as Optional<CurValue>, to: NewValue.self))
}
}
internal func _projectMutableAddress<CurValue, NewValue>(
_ base: UnsafeRawPointer,
from _: CurValue.Type,
to _: NewValue.Type,
isRoot: Bool,
keepAlive: inout AnyObject?
) -> UnsafeRawPointer {
switch value {
case .struct(let offset):
return base.advanced(by: offset)
case .class(let offset):
// A class dereference should only occur at the root of a mutation,
// since otherwise it would be part of the reference prefix.
_internalInvariant(isRoot,
"class component should not appear in the middle of mutation")
// AnyObject memory can alias any class reference memory, so we can
// assume type here
let object = base.assumingMemoryBound(to: AnyObject.self).pointee
let offsetAddress = UnsafeRawPointer(Builtin.bridgeToRawPointer(object))
.advanced(by: offset)
// Keep the base alive for the duration of the derived access and also
// enforce exclusive access to the address.
keepAlive = ClassHolder._create(previous: keepAlive, instance: object,
accessingAddress: offsetAddress,
type: NewValue.self)
return offsetAddress
case .mutatingGetSet(id: _, accessors: let accessors,
argument: let argument):
let baseTyped = UnsafeMutablePointer(
mutating: base.assumingMemoryBound(to: CurValue.self))
let argValue = argument?.data.baseAddress ?? accessors._value
let argSize = argument?.data.count ?? 0
let writeback = MutatingWritebackBuffer<CurValue, NewValue>(
previous: keepAlive,
base: baseTyped,
set: accessors.mutatingSetter(),
argument: argValue,
argumentSize: argSize,
value: accessors.getter()(baseTyped.pointee, argValue, argSize))
keepAlive = writeback
// A maximally-abstracted, final, stored class property should have
// a stable address.
return UnsafeRawPointer(Builtin.addressof(&writeback.value))
case .nonmutatingGetSet(id: _, accessors: let accessors,
argument: let argument):
// A nonmutating property should only occur at the root of a mutation,
// since otherwise it would be part of the reference prefix.
_internalInvariant(isRoot,
"nonmutating component should not appear in the middle of mutation")
let baseValue = base.assumingMemoryBound(to: CurValue.self).pointee
let argValue = argument?.data.baseAddress ?? accessors._value
let argSize = argument?.data.count ?? 0
let writeback = NonmutatingWritebackBuffer<CurValue, NewValue>(
previous: keepAlive,
base: baseValue,
set: accessors.nonmutatingSetter(),
argument: argValue,
argumentSize: argSize,
value: accessors.getter()(baseValue, argValue, argSize))
keepAlive = writeback
// A maximally-abstracted, final, stored class property should have
// a stable address.
return UnsafeRawPointer(Builtin.addressof(&writeback.value))
case .optionalForce:
_internalInvariant(CurValue.self == Optional<NewValue>.self,
"should be unwrapping an optional value")
// Optional's layout happens to always put the payload at the start
// address of the Optional value itself, if a value is present at all.
let baseOptionalPointer
= base.assumingMemoryBound(to: Optional<NewValue>.self)
// Assert that a value exists
_ = baseOptionalPointer.pointee!
return base
case .optionalChain, .optionalWrap, .get:
_internalInvariantFailure("not a mutable key path component")
}
}
}
internal func _pop<T>(from: inout UnsafeRawBufferPointer,
as type: T.Type) -> T {
let buffer = _pop(from: &from, as: type, count: 1)
return buffer.baseAddress.unsafelyUnwrapped.pointee
}
internal func _pop<T>(from: inout UnsafeRawBufferPointer,
as: T.Type,
count: Int) -> UnsafeBufferPointer<T> {
_internalInvariant(_isPOD(T.self), "should be POD")
from = MemoryLayout<T>._roundingUpBaseToAlignment(from)
let byteCount = MemoryLayout<T>.stride * count
let result = UnsafeBufferPointer(
start: from.baseAddress.unsafelyUnwrapped.assumingMemoryBound(to: T.self),
count: count)
from = UnsafeRawBufferPointer(
start: from.baseAddress.unsafelyUnwrapped + byteCount,
count: from.count - byteCount)
return result
}
internal struct KeyPathBuffer {
internal var data: UnsafeRawBufferPointer
internal var trivial: Bool
internal var hasReferencePrefix: Bool
internal var mutableData: UnsafeMutableRawBufferPointer {
return UnsafeMutableRawBufferPointer(mutating: data)
}
internal struct Builder {
internal var buffer: UnsafeMutableRawBufferPointer
internal init(_ buffer: UnsafeMutableRawBufferPointer) {
self.buffer = buffer
}
internal mutating func pushRaw(size: Int, alignment: Int)
-> UnsafeMutableRawBufferPointer {
var baseAddress = buffer.baseAddress.unsafelyUnwrapped
var misalign = Int(bitPattern: baseAddress) % alignment
if misalign != 0 {
misalign = alignment - misalign
baseAddress = baseAddress.advanced(by: misalign)
}
let result = UnsafeMutableRawBufferPointer(
start: baseAddress,
count: size)
buffer = UnsafeMutableRawBufferPointer(
start: baseAddress + size,
count: buffer.count - size - misalign)
return result
}
internal mutating func push<T>(_ value: T) {
let buf = pushRaw(size: MemoryLayout<T>.size,
alignment: MemoryLayout<T>.alignment)
buf.storeBytes(of: value, as: T.self)
}
internal mutating func pushHeader(_ header: Header) {
push(header)
// Start the components at pointer alignment
_ = pushRaw(size: RawKeyPathComponent.Header.pointerAlignmentSkew,
alignment: 4)
}
}
internal struct Header {
internal var _value: UInt32
internal static var sizeMask: UInt32 {
return _SwiftKeyPathBufferHeader_SizeMask
}
internal static var reservedMask: UInt32 {
return _SwiftKeyPathBufferHeader_ReservedMask
}
internal static var trivialFlag: UInt32 {
return _SwiftKeyPathBufferHeader_TrivialFlag
}
internal static var hasReferencePrefixFlag: UInt32 {
return _SwiftKeyPathBufferHeader_HasReferencePrefixFlag
}
internal init(size: Int, trivial: Bool, hasReferencePrefix: Bool) {
_internalInvariant(size <= Int(Header.sizeMask), "key path too big")
_value = UInt32(size)
| (trivial ? Header.trivialFlag : 0)
| (hasReferencePrefix ? Header.hasReferencePrefixFlag : 0)
}
internal var size: Int { return Int(_value & Header.sizeMask) }
internal var trivial: Bool { return _value & Header.trivialFlag != 0 }
internal var hasReferencePrefix: Bool {
get {
return _value & Header.hasReferencePrefixFlag != 0
}
set {
if newValue {
_value |= Header.hasReferencePrefixFlag
} else {
_value &= ~Header.hasReferencePrefixFlag
}
}
}
// In a key path pattern, the "trivial" flag is used to indicate
// "instantiable in-line"
internal var instantiableInLine: Bool {
return trivial
}
internal func validateReservedBits() {
_precondition(_value & Header.reservedMask == 0,
"Reserved bits set to an unexpected bit pattern")
}
}
internal init(base: UnsafeRawPointer) {
let header = base.load(as: Header.self)
data = UnsafeRawBufferPointer(
start: base + MemoryLayout<Int>.size,
count: header.size)
trivial = header.trivial
hasReferencePrefix = header.hasReferencePrefix
}
internal init(partialData: UnsafeRawBufferPointer,
trivial: Bool = false,
hasReferencePrefix: Bool = false) {
self.data = partialData
self.trivial = trivial
self.hasReferencePrefix = hasReferencePrefix
}
internal func destroy() {
// Short-circuit if nothing in the object requires destruction.
if trivial { return }
var bufferToDestroy = self
while true {
let (component, type) = bufferToDestroy.next()
component.destroy()
guard let _ = type else { break }
}
}
internal mutating func next() -> (RawKeyPathComponent, Any.Type?) {
let header = _pop(from: &data, as: RawKeyPathComponent.Header.self)
// Track if this is the last component of the reference prefix.
if header.endOfReferencePrefix {
_internalInvariant(self.hasReferencePrefix,
"beginMutation marker in non-reference-writable key path?")
self.hasReferencePrefix = false
}
var component = RawKeyPathComponent(header: header, body: data)
// Shrinkwrap the component buffer size.
let size = component.bodySize
component.body = UnsafeRawBufferPointer(start: component.body.baseAddress,
count: size)
_ = _pop(from: &data, as: Int8.self, count: size)
// fetch type, which is in the buffer unless it's the final component
let nextType: Any.Type?
if data.isEmpty {
nextType = nil
} else {
nextType = _pop(from: &data, as: Any.Type.self)
}
return (component, nextType)
}
}
// MARK: Library intrinsics for projecting key paths.
@_silgen_name("swift_getAtPartialKeyPath")
public // COMPILER_INTRINSIC
func _getAtPartialKeyPath<Root>(
root: Root,
keyPath: PartialKeyPath<Root>
) -> Any {
func open<Value>(_: Value.Type) -> Any {
return _getAtKeyPath(root: root,
keyPath: unsafeDowncast(keyPath, to: KeyPath<Root, Value>.self))
}
return _openExistential(type(of: keyPath).valueType, do: open)
}
@_silgen_name("swift_getAtAnyKeyPath")
public // COMPILER_INTRINSIC
func _getAtAnyKeyPath<RootValue>(
root: RootValue,
keyPath: AnyKeyPath
) -> Any? {
let (keyPathRoot, keyPathValue) = type(of: keyPath)._rootAndValueType
func openRoot<KeyPathRoot>(_: KeyPathRoot.Type) -> Any? {
guard let rootForKeyPath = root as? KeyPathRoot else {
return nil
}
func openValue<Value>(_: Value.Type) -> Any {
return _getAtKeyPath(root: rootForKeyPath,
keyPath: unsafeDowncast(keyPath, to: KeyPath<KeyPathRoot, Value>.self))
}
return _openExistential(keyPathValue, do: openValue)
}
return _openExistential(keyPathRoot, do: openRoot)
}
@_silgen_name("swift_getAtKeyPath")
public // COMPILER_INTRINSIC
func _getAtKeyPath<Root, Value>(
root: Root,
keyPath: KeyPath<Root, Value>
) -> Value {
return keyPath._projectReadOnly(from: root)
}
// The release that ends the access scope is guaranteed to happen
// immediately at the end_apply call because the continuation is a
// runtime call with a manual release (access scopes cannot be extended).
@_silgen_name("_swift_modifyAtWritableKeyPath_impl")
public // runtime entrypoint
func _modifyAtWritableKeyPath_impl<Root, Value>(
root: inout Root,
keyPath: WritableKeyPath<Root, Value>
) -> (UnsafeMutablePointer<Value>, AnyObject?) {
if type(of: keyPath).kind == .reference {
return _modifyAtReferenceWritableKeyPath_impl(root: root,
keyPath: _unsafeUncheckedDowncast(keyPath,
to: ReferenceWritableKeyPath<Root, Value>.self))
}
return keyPath._projectMutableAddress(from: &root)
}
// The release that ends the access scope is guaranteed to happen
// immediately at the end_apply call because the continuation is a
// runtime call with a manual release (access scopes cannot be extended).
@_silgen_name("_swift_modifyAtReferenceWritableKeyPath_impl")
public // runtime entrypoint
func _modifyAtReferenceWritableKeyPath_impl<Root, Value>(
root: Root,
keyPath: ReferenceWritableKeyPath<Root, Value>
) -> (UnsafeMutablePointer<Value>, AnyObject?) {
return keyPath._projectMutableAddress(from: root)
}
@_silgen_name("swift_setAtWritableKeyPath")
public // COMPILER_INTRINSIC
func _setAtWritableKeyPath<Root, Value>(
root: inout Root,
keyPath: WritableKeyPath<Root, Value>,
value: __owned Value
) {
if type(of: keyPath).kind == .reference {
return _setAtReferenceWritableKeyPath(root: root,
keyPath: _unsafeUncheckedDowncast(keyPath,
to: ReferenceWritableKeyPath<Root, Value>.self),
value: value)
}
// TODO: we should be able to do this more efficiently than projecting.
let (addr, owner) = keyPath._projectMutableAddress(from: &root)
addr.pointee = value
_fixLifetime(owner)
// FIXME: this needs a deallocation barrier to ensure that the
// release isn't extended, along with the access scope.
}
@_silgen_name("swift_setAtReferenceWritableKeyPath")
public // COMPILER_INTRINSIC
func _setAtReferenceWritableKeyPath<Root, Value>(
root: Root,
keyPath: ReferenceWritableKeyPath<Root, Value>,
value: __owned Value
) {
// TODO: we should be able to do this more efficiently than projecting.
let (addr, owner) = keyPath._projectMutableAddress(from: root)
addr.pointee = value
_fixLifetime(owner)
// FIXME: this needs a deallocation barrier to ensure that the
// release isn't extended, along with the access scope.
}
// MARK: Appending type system
// FIXME(ABI): The type relationships between KeyPath append operands are tricky
// and don't interact well with our overriding rules. Hack things by injecting
// a bunch of `appending` overloads as protocol extensions so they aren't
// constrained by being overrides, and so that we can use exact-type constraints
// on `Self` to prevent dynamically-typed methods from being inherited by
// statically-typed key paths.
/// An implementation detail of key path expressions; do not use this protocol
/// directly.
@_show_in_interface
public protocol _AppendKeyPath {}
extension _AppendKeyPath where Self == AnyKeyPath {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type. This example
/// creates key paths from `Array<Int>` to `String` and from `String` to
/// `Int`, and then tries appending each to the other:
///
/// let arrayDescription: AnyKeyPath = \Array<Int>.description
/// let stringLength: AnyKeyPath = \String.count
///
/// // Creates a key path from `Array<Int>` to `Int`
/// let arrayDescriptionLength = arrayDescription.appending(path: stringLength)
///
/// let invalidKeyPath = stringLength.appending(path: arrayDescription)
/// // invalidKeyPath == nil
///
/// The second call to `appending(path:)` returns `nil`
/// because the root type of `arrayDescription`, `Array<Int>`, does not
/// match the value type of `stringLength`, `Int`.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path and the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
@inlinable
public func appending(path: AnyKeyPath) -> AnyKeyPath? {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == PartialKeyPath<T> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type. This example
/// creates key paths from `Array<Int>` to `String` and from `String` to
/// `Int`, and then tries appending each to the other:
///
/// let arrayDescription: PartialKeyPath<Array<Int>> = \.description
/// let stringLength: PartialKeyPath<String> = \.count
///
/// // Creates a key path from `Array<Int>` to `Int`
/// let arrayDescriptionLength = arrayDescription.appending(path: stringLength)
///
/// let invalidKeyPath = stringLength.appending(path: arrayDescription)
/// // invalidKeyPath == nil
///
/// The second call to `appending(path:)` returns `nil`
/// because the root type of `arrayDescription`, `Array<Int>`, does not
/// match the value type of `stringLength`, `Int`.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path and the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
@inlinable
public func appending<Root>(path: AnyKeyPath) -> PartialKeyPath<Root>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type. This example
/// creates a key path from `Array<Int>` to `String`, and then tries
/// appending compatible and incompatible key paths:
///
/// let arrayDescription: PartialKeyPath<Array<Int>> = \.description
///
/// // Creates a key path from `Array<Int>` to `Int`
/// let arrayDescriptionLength = arrayDescription.appending(path: \String.count)
///
/// let invalidKeyPath = arrayDescription.appending(path: \Double.isZero)
/// // invalidKeyPath == nil
///
/// The second call to `appending(path:)` returns `nil` because the root type
/// of the `path` parameter, `Double`, does not match the value type of
/// `arrayDescription`, `String`.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
@inlinable
public func appending<Root, AppendedRoot, AppendedValue>(
path: KeyPath<AppendedRoot, AppendedValue>
) -> KeyPath<Root, AppendedValue>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type.
///
/// - Parameter path: The reference writeable key path to append.
/// - Returns: A key path from the root of this key path to the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
@inlinable
public func appending<Root, AppendedRoot, AppendedValue>(
path: ReferenceWritableKeyPath<AppendedRoot, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == KeyPath<T,U> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation. In the following
/// example, `keyPath1` and `keyPath2` are equivalent:
///
/// let arrayDescription = \Array<Int>.description
/// let keyPath1 = arrayDescription.appending(path: \String.count)
///
/// let keyPath2 = \Array<Int>.description.count
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: KeyPath<Value, AppendedValue>
) -> KeyPath<Root, AppendedValue>
where Self: KeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
/* TODO
public func appending<Root, Value, Leaf>(
path: Leaf,
// FIXME: Satisfy "Value generic param not used in signature" constraint
_: Value.Type = Value.self
) -> PartialKeyPath<Root>?
where Self: KeyPath<Root, Value>, Leaf == AnyKeyPath {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
*/
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: ReferenceWritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == KeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == WritableKeyPath<T,U> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: WritableKeyPath<Value, AppendedValue>
) -> WritableKeyPath<Root, AppendedValue>
where Self == WritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: ReferenceWritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == WritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == ReferenceWritableKeyPath<T,U> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: WritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == ReferenceWritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
@usableFromInline
internal func _tryToAppendKeyPaths<Result: AnyKeyPath>(
root: AnyKeyPath,
leaf: AnyKeyPath
) -> Result? {
let (rootRoot, rootValue) = type(of: root)._rootAndValueType
let (leafRoot, leafValue) = type(of: leaf)._rootAndValueType
if rootValue != leafRoot {
return nil
}
func open<Root>(_: Root.Type) -> Result {
func open2<Value>(_: Value.Type) -> Result {
func open3<AppendedValue>(_: AppendedValue.Type) -> Result {
let typedRoot = unsafeDowncast(root, to: KeyPath<Root, Value>.self)
let typedLeaf = unsafeDowncast(leaf,
to: KeyPath<Value, AppendedValue>.self)
let result = _appendingKeyPaths(root: typedRoot, leaf: typedLeaf)
return unsafeDowncast(result, to: Result.self)
}
return _openExistential(leafValue, do: open3)
}
return _openExistential(rootValue, do: open2)
}
return _openExistential(rootRoot, do: open)
}
@usableFromInline
internal func _appendingKeyPaths<
Root, Value, AppendedValue,
Result: KeyPath<Root, AppendedValue>
>(
root: KeyPath<Root, Value>,
leaf: KeyPath<Value, AppendedValue>
) -> Result {
let resultTy = type(of: root).appendedType(with: type(of: leaf))
return root.withBuffer {
var rootBuffer = $0
return leaf.withBuffer {
var leafBuffer = $0
// If either operand is the identity key path, then we should return
// the other operand back untouched.
if leafBuffer.data.isEmpty {
return unsafeDowncast(root, to: Result.self)
}
if rootBuffer.data.isEmpty {
return unsafeDowncast(leaf, to: Result.self)
}
// Reserve room for the appended KVC string, if both key paths are
// KVC-compatible.
let appendedKVCLength: Int, rootKVCLength: Int, leafKVCLength: Int
if let rootPtr = root._kvcKeyPathStringPtr,
let leafPtr = leaf._kvcKeyPathStringPtr {
rootKVCLength = Int(_swift_stdlib_strlen(rootPtr))
leafKVCLength = Int(_swift_stdlib_strlen(leafPtr))
// root + "." + leaf
appendedKVCLength = rootKVCLength + 1 + leafKVCLength + 1
} else {
rootKVCLength = 0
leafKVCLength = 0
appendedKVCLength = 0
}
// Result buffer has room for both key paths' components, plus the
// header, plus space for the middle type.
// Align up the root so that we can put the component type after it.
let rootSize = MemoryLayout<Int>._roundingUpToAlignment(rootBuffer.data.count)
let resultSize = rootSize + leafBuffer.data.count
+ 2 * MemoryLayout<Int>.size
// Tail-allocate space for the KVC string.
let totalResultSize = MemoryLayout<Int32>
._roundingUpToAlignment(resultSize + appendedKVCLength)
var kvcStringBuffer: UnsafeMutableRawPointer? = nil
let result = resultTy._create(capacityInBytes: totalResultSize) {
var destBuffer = $0
// Remember where the tail-allocated KVC string buffer begins.
if appendedKVCLength > 0 {
kvcStringBuffer = destBuffer.baseAddress.unsafelyUnwrapped
.advanced(by: resultSize)
destBuffer = .init(start: destBuffer.baseAddress,
count: resultSize)
}
var destBuilder = KeyPathBuffer.Builder(destBuffer)
// Save space for the header.
let leafIsReferenceWritable = type(of: leaf).kind == .reference
destBuilder.pushHeader(KeyPathBuffer.Header(
size: resultSize - MemoryLayout<Int>.size,
trivial: rootBuffer.trivial && leafBuffer.trivial,
hasReferencePrefix: rootBuffer.hasReferencePrefix
|| leafIsReferenceWritable
))
let leafHasReferencePrefix = leafBuffer.hasReferencePrefix
// Clone the root components into the buffer.
while true {
let (component, type) = rootBuffer.next()
let isLast = type == nil
// If the leaf appended path has a reference prefix, then the
// entire root is part of the reference prefix.
let endOfReferencePrefix: Bool
if leafHasReferencePrefix {
endOfReferencePrefix = false
} else if isLast && leafIsReferenceWritable {
endOfReferencePrefix = true
} else {
endOfReferencePrefix = component.header.endOfReferencePrefix
}
component.clone(
into: &destBuilder.buffer,
endOfReferencePrefix: endOfReferencePrefix)
// Insert our endpoint type between the root and leaf components.
if let type = type {
destBuilder.push(type)
} else {
destBuilder.push(Value.self as Any.Type)
break
}
}
// Clone the leaf components into the buffer.
while true {
let (component, type) = leafBuffer.next()
component.clone(
into: &destBuilder.buffer,
endOfReferencePrefix: component.header.endOfReferencePrefix)
if let type = type {
destBuilder.push(type)
} else {
break
}
}
_internalInvariant(destBuilder.buffer.isEmpty,
"did not fill entire result buffer")
}
// Build the KVC string if there is one.
if let kvcStringBuffer = kvcStringBuffer {
let rootPtr = root._kvcKeyPathStringPtr.unsafelyUnwrapped
let leafPtr = leaf._kvcKeyPathStringPtr.unsafelyUnwrapped
_memcpy(dest: kvcStringBuffer,
src: rootPtr,
size: UInt(rootKVCLength))
kvcStringBuffer.advanced(by: rootKVCLength)
.storeBytes(of: 0x2E /* '.' */, as: CChar.self)
_memcpy(dest: kvcStringBuffer.advanced(by: rootKVCLength + 1),
src: leafPtr,
size: UInt(leafKVCLength))
result._kvcKeyPathStringPtr =
UnsafePointer(kvcStringBuffer.assumingMemoryBound(to: CChar.self))
kvcStringBuffer.advanced(by: rootKVCLength + leafKVCLength + 1)
.storeBytes(of: 0 /* '\0' */, as: CChar.self)
}
return unsafeDowncast(result, to: Result.self)
}
}
}
// The distance in bytes from the address point of a KeyPath object to its
// buffer header. Includes the size of the Swift heap object header and the
// pointer to the KVC string.
internal var keyPathObjectHeaderSize: Int {
return MemoryLayout<HeapObject>.size + MemoryLayout<Int>.size
}
internal var keyPathPatternHeaderSize: Int {
return 16
}
// Runtime entry point to instantiate a key path object.
// Note that this has a compatibility override shim in the runtime so that
// future compilers can backward-deploy support for instantiating new key path
// pattern features.
@_cdecl("swift_getKeyPathImpl")
public func _swift_getKeyPath(pattern: UnsafeMutableRawPointer,
arguments: UnsafeRawPointer)
-> UnsafeRawPointer {
// The key path pattern is laid out like a key path object, with a few
// modifications:
// - Pointers in the instantiated object are compressed into 32-bit
// relative offsets in the pattern.
// - The pattern begins with a field that's either zero, for a pattern that
// depends on instantiation arguments, or that's a relative reference to
// a global mutable pointer variable, which can be initialized to a single
// shared instantiation of this pattern.
// - Instead of the two-word object header with isa and refcount, two
// pointers to metadata accessors are provided for the root and leaf
// value types of the key path.
// - Components may have unresolved forms that require instantiation.
// - Type metadata and protocol conformance pointers are replaced with
// relative-referenced accessor functions that instantiate the
// needed generic argument when called.
//
// The pattern never precomputes the capabilities of the key path (readonly/
// writable/reference-writable), nor does it encode the reference prefix.
// These are resolved dynamically, so that they always reflect the dynamic
// capability of the properties involved.
let oncePtrPtr = pattern
let patternPtr = pattern.advanced(by: 4)
let bufferHeader = patternPtr.load(fromByteOffset: keyPathPatternHeaderSize,
as: KeyPathBuffer.Header.self)
bufferHeader.validateReservedBits()
// If the first word is nonzero, it relative-references a cache variable
// we can use to reference a single shared instantiation of this key path.
let oncePtrOffset = oncePtrPtr.load(as: Int32.self)
let oncePtr: UnsafeRawPointer?
if oncePtrOffset != 0 {
let theOncePtr = _resolveRelativeAddress(oncePtrPtr, oncePtrOffset)
oncePtr = theOncePtr
// See whether we already instantiated this key path.
// This is a non-atomic load because the instantiated pointer will be
// written with a release barrier, and loads of the instantiated key path
// ought to carry a dependency through this loaded pointer.
let existingInstance = theOncePtr.load(as: UnsafeRawPointer?.self)
if let existingInstance = existingInstance {
// Return the instantiated object at +1.
let object = Unmanaged<AnyKeyPath>.fromOpaque(existingInstance)
// TODO: This retain will be unnecessary once we support global objects
// with inert refcounting.
_ = object.retain()
return existingInstance
}
} else {
oncePtr = nil
}
// Instantiate a new key path object modeled on the pattern.
// Do a pass to determine the class of the key path we'll be instantiating
// and how much space we'll need for it.
let (keyPathClass, rootType, size, _)
= _getKeyPathClassAndInstanceSizeFromPattern(patternPtr, arguments)
// Allocate the instance.
let instance = keyPathClass._create(capacityInBytes: size) { instanceData in
// Instantiate the pattern into the instance.
_instantiateKeyPathBuffer(patternPtr, instanceData, rootType, arguments)
}
// Adopt the KVC string from the pattern.
let kvcStringBase = patternPtr.advanced(by: 12)
let kvcStringOffset = kvcStringBase.load(as: Int32.self)
if kvcStringOffset == 0 {
// Null pointer.
instance._kvcKeyPathStringPtr = nil
} else {
let kvcStringPtr = _resolveRelativeAddress(kvcStringBase, kvcStringOffset)
instance._kvcKeyPathStringPtr =
kvcStringPtr.assumingMemoryBound(to: CChar.self)
}
// If we can cache this instance as a shared instance, do so.
if let oncePtr = oncePtr {
// Try to replace a null pointer in the cache variable with the instance
// pointer.
let instancePtr = Unmanaged.passRetained(instance)
while true {
let (oldValue, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
oncePtr._rawValue,
0._builtinWordValue,
UInt(bitPattern: instancePtr.toOpaque())._builtinWordValue)
// If the exchange succeeds, then the instance we formed is the canonical
// one.
if Bool(won) {
break
}
// Otherwise, someone raced with us to instantiate the key path pattern
// and won. Their instance should be just as good as ours, so we can take
// that one and let ours get deallocated.
if let existingInstance = UnsafeRawPointer(bitPattern: Int(oldValue)) {
// Return the instantiated object at +1.
let object = Unmanaged<AnyKeyPath>.fromOpaque(existingInstance)
// TODO: This retain will be unnecessary once we support global objects
// with inert refcounting.
_ = object.retain()
// Release the instance we created.
instancePtr.release()
return existingInstance
} else {
// Try the cmpxchg again if it spuriously failed.
continue
}
}
}
return UnsafeRawPointer(Unmanaged.passRetained(instance).toOpaque())
}
// A reference to metadata, which is a pointer to a mangled name.
internal typealias MetadataReference = UnsafeRawPointer
// Determine the length of the given mangled name.
internal func _getSymbolicMangledNameLength(_ base: UnsafeRawPointer) -> Int {
var end = base
while let current = Optional(end.load(as: UInt8.self)), current != 0 {
// Skip the current character
end = end + 1
// Skip over a symbolic reference
if current >= 0x1 && current <= 0x17 {
end += 4
} else if current >= 0x18 && current <= 0x1F {
end += MemoryLayout<Int>.size
}
}
return end - base
}
// Resolve a mangled name in a generic environment, described by either a
// flat GenericEnvironment * (if the bottom tag bit is 0) or possibly-nested
// ContextDescriptor * (if the bottom tag bit is 1)
internal func _getTypeByMangledNameInEnvironmentOrContext(
_ name: UnsafePointer<UInt8>,
_ nameLength: UInt,
genericEnvironmentOrContext: UnsafeRawPointer?,
genericArguments: UnsafeRawPointer?)
-> Any.Type? {
let taggedPointer = UInt(bitPattern: genericEnvironmentOrContext)
if taggedPointer & 1 == 0 {
return _getTypeByMangledNameInEnvironment(name, nameLength,
genericEnvironment: genericEnvironmentOrContext,
genericArguments: genericArguments)
} else {
let context = UnsafeRawPointer(bitPattern: taggedPointer & ~1)
return _getTypeByMangledNameInContext(name, nameLength,
genericContext: context,
genericArguments: genericArguments)
}
}
// Resolve the given generic argument reference to a generic argument.
internal func _resolveKeyPathGenericArgReference(
_ reference: UnsafeRawPointer,
genericEnvironment: UnsafeRawPointer?,
arguments: UnsafeRawPointer?)
-> UnsafeRawPointer {
// If the low bit is clear, it's a direct reference to the argument.
if (UInt(bitPattern: reference) & 0x01 == 0) {
return reference
}
// Adjust the reference.
let referenceStart = reference - 1
// If we have a symbolic reference to an accessor, call it.
let first = referenceStart.load(as: UInt8.self)
if first == 255 && reference.load(as: UInt8.self) == 9 {
typealias MetadataAccessor =
@convention(c) (UnsafeRawPointer?) -> UnsafeRawPointer
// Unaligned load of the offset.
let pointerReference = reference + 1
var offset: Int32 = 0
_memcpy(dest: &offset, src: pointerReference, size: 4)
let accessorPtrRaw = _resolveRelativeAddress(pointerReference, offset)
let accessorPtrSigned =
_PtrAuth.sign(pointer: accessorPtrRaw,
key: .processIndependentCode,
discriminator: _PtrAuth.discriminator(for: MetadataAccessor.self))
let accessor = unsafeBitCast(accessorPtrSigned, to: MetadataAccessor.self)
return accessor(arguments)
}
let nameLength = _getSymbolicMangledNameLength(referenceStart)
let namePtr = referenceStart.bindMemory(to: UInt8.self,
capacity: nameLength + 1)
// FIXME: Could extract this information from the mangled name.
guard let result =
_getTypeByMangledNameInEnvironmentOrContext(namePtr, UInt(nameLength),
genericEnvironmentOrContext: genericEnvironment,
genericArguments: arguments)
else {
let nameStr = String._fromUTF8Repairing(
UnsafeBufferPointer(start: namePtr, count: nameLength)
).0
fatalError("could not demangle keypath type from '\(nameStr)'")
}
return unsafeBitCast(result, to: UnsafeRawPointer.self)
}
// Resolve the given metadata reference to (type) metadata.
internal func _resolveKeyPathMetadataReference(
_ reference: UnsafeRawPointer,
genericEnvironment: UnsafeRawPointer?,
arguments: UnsafeRawPointer?)
-> Any.Type {
return unsafeBitCast(
_resolveKeyPathGenericArgReference(
reference,
genericEnvironment: genericEnvironment,
arguments: arguments),
to: Any.Type.self)
}
internal enum KeyPathStructOrClass {
case `struct`, `class`
}
internal enum KeyPathPatternStoredOffset {
case inline(UInt32)
case outOfLine(UInt32)
case unresolvedFieldOffset(UInt32)
case unresolvedIndirectOffset(UnsafePointer<UInt>)
}
internal struct KeyPathPatternComputedArguments {
var getLayout: KeyPathComputedArgumentLayoutFn
var witnesses: ComputedArgumentWitnessesPtr
var initializer: KeyPathComputedArgumentInitializerFn
}
internal protocol KeyPathPatternVisitor {
mutating func visitHeader(genericEnvironment: UnsafeRawPointer?,
rootMetadataRef: MetadataReference,
leafMetadataRef: MetadataReference,
kvcCompatibilityString: UnsafeRawPointer?)
mutating func visitStoredComponent(kind: KeyPathStructOrClass,
mutable: Bool,
offset: KeyPathPatternStoredOffset)
mutating func visitComputedComponent(mutating: Bool,
idKind: KeyPathComputedIDKind,
idResolution: KeyPathComputedIDResolution,
idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?,
arguments: KeyPathPatternComputedArguments?,
externalArgs: UnsafeBufferPointer<Int32>?)
mutating func visitOptionalChainComponent()
mutating func visitOptionalForceComponent()
mutating func visitOptionalWrapComponent()
mutating func visitIntermediateComponentType(metadataRef: MetadataReference)
mutating func finish()
}
internal func _resolveRelativeAddress(_ base: UnsafeRawPointer,
_ offset: Int32) -> UnsafeRawPointer {
// Sign-extend the offset to pointer width and add with wrap on overflow.
return UnsafeRawPointer(bitPattern: Int(bitPattern: base) &+ Int(offset))
.unsafelyUnwrapped
}
internal func _resolveRelativeIndirectableAddress(_ base: UnsafeRawPointer,
_ offset: Int32)
-> UnsafeRawPointer {
// Low bit indicates whether the reference is indirected or not.
if offset & 1 != 0 {
let ptrToPtr = _resolveRelativeAddress(base, offset - 1)
return ptrToPtr.load(as: UnsafeRawPointer.self)
}
return _resolveRelativeAddress(base, offset)
}
internal func _loadRelativeAddress<T>(at: UnsafeRawPointer,
fromByteOffset: Int = 0,
as: T.Type) -> T {
let offset = at.load(fromByteOffset: fromByteOffset, as: Int32.self)
return unsafeBitCast(_resolveRelativeAddress(at + fromByteOffset, offset),
to: T.self)
}
internal func _walkKeyPathPattern<W: KeyPathPatternVisitor>(
_ pattern: UnsafeRawPointer,
walker: inout W) {
// Visit the header.
let genericEnvironment = _loadRelativeAddress(at: pattern,
as: UnsafeRawPointer.self)
let rootMetadataRef = _loadRelativeAddress(at: pattern, fromByteOffset: 4,
as: MetadataReference.self)
let leafMetadataRef = _loadRelativeAddress(at: pattern, fromByteOffset: 8,
as: MetadataReference.self)
let kvcString = _loadRelativeAddress(at: pattern, fromByteOffset: 12,
as: UnsafeRawPointer.self)
walker.visitHeader(genericEnvironment: genericEnvironment,
rootMetadataRef: rootMetadataRef,
leafMetadataRef: leafMetadataRef,
kvcCompatibilityString: kvcString)
func visitStored(header: RawKeyPathComponent.Header,
componentBuffer: inout UnsafeRawBufferPointer) {
// Decode a stored property. A small offset may be stored inline in the
// header word, or else be stored out-of-line, or need instantiation of some
// kind.
let offset: KeyPathPatternStoredOffset
switch header.storedOffsetPayload {
case RawKeyPathComponent.Header.outOfLineOffsetPayload:
offset = .outOfLine(_pop(from: &componentBuffer,
as: UInt32.self))
case RawKeyPathComponent.Header.unresolvedFieldOffsetPayload:
offset = .unresolvedFieldOffset(_pop(from: &componentBuffer,
as: UInt32.self))
case RawKeyPathComponent.Header.unresolvedIndirectOffsetPayload:
let base = componentBuffer.baseAddress.unsafelyUnwrapped
let relativeOffset = _pop(from: &componentBuffer,
as: Int32.self)
let ptr = _resolveRelativeIndirectableAddress(base, relativeOffset)
offset = .unresolvedIndirectOffset(
ptr.assumingMemoryBound(to: UInt.self))
default:
offset = .inline(header.storedOffsetPayload)
}
let kind: KeyPathStructOrClass = header.kind == .struct
? .struct : .class
walker.visitStoredComponent(kind: kind,
mutable: header.isStoredMutable,
offset: offset)
}
func popComputedAccessors(header: RawKeyPathComponent.Header,
componentBuffer: inout UnsafeRawBufferPointer)
-> (idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?) {
let idValueBase = componentBuffer.baseAddress.unsafelyUnwrapped
let idValue = _pop(from: &componentBuffer, as: Int32.self)
let getterBase = componentBuffer.baseAddress.unsafelyUnwrapped
let getterRef = _pop(from: &componentBuffer, as: Int32.self)
let getter = _resolveRelativeAddress(getterBase, getterRef)
let setter: UnsafeRawPointer?
if header.isComputedSettable {
let setterBase = componentBuffer.baseAddress.unsafelyUnwrapped
let setterRef = _pop(from: &componentBuffer, as: Int32.self)
setter = _resolveRelativeAddress(setterBase, setterRef)
} else {
setter = nil
}
return (idValueBase: idValueBase, idValue: idValue,
getter: getter, setter: setter)
}
func popComputedArguments(header: RawKeyPathComponent.Header,
componentBuffer: inout UnsafeRawBufferPointer)
-> KeyPathPatternComputedArguments? {
if header.hasComputedArguments {
let getLayoutBase = componentBuffer.baseAddress.unsafelyUnwrapped
let getLayoutRef = _pop(from: &componentBuffer, as: Int32.self)
let getLayoutRaw = _resolveRelativeAddress(getLayoutBase, getLayoutRef)
let getLayoutSigned = _PtrAuth.sign(pointer: getLayoutRaw,
key: .processIndependentCode,
discriminator: _PtrAuth.discriminator(for: KeyPathComputedArgumentLayoutFn.self))
let getLayout = unsafeBitCast(getLayoutSigned,
to: KeyPathComputedArgumentLayoutFn.self)
let witnessesBase = componentBuffer.baseAddress.unsafelyUnwrapped
let witnessesRef = _pop(from: &componentBuffer, as: Int32.self)
let witnesses: UnsafeRawPointer
if witnessesRef == 0 {
witnesses = __swift_keyPathGenericWitnessTable_addr()
} else {
witnesses = _resolveRelativeAddress(witnessesBase, witnessesRef)
}
let initializerBase = componentBuffer.baseAddress.unsafelyUnwrapped
let initializerRef = _pop(from: &componentBuffer, as: Int32.self)
let initializerRaw = _resolveRelativeAddress(initializerBase,
initializerRef)
let initializerSigned = _PtrAuth.sign(pointer: initializerRaw,
key: .processIndependentCode,
discriminator: _PtrAuth.discriminator(for: KeyPathComputedArgumentInitializerFn.self))
let initializer = unsafeBitCast(initializerSigned,
to: KeyPathComputedArgumentInitializerFn.self)
return KeyPathPatternComputedArguments(getLayout: getLayout,
witnesses: ComputedArgumentWitnessesPtr(witnesses),
initializer: initializer)
} else {
return nil
}
}
// We declare this down here to avoid the temptation to use it within
// the functions above.
let bufferPtr = pattern.advanced(by: keyPathPatternHeaderSize)
let bufferHeader = bufferPtr.load(as: KeyPathBuffer.Header.self)
var buffer = UnsafeRawBufferPointer(start: bufferPtr + 4,
count: bufferHeader.size)
while !buffer.isEmpty {
let header = _pop(from: &buffer,
as: RawKeyPathComponent.Header.self)
// Ensure that we pop an amount of data consistent with what
// RawKeyPathComponent.Header.patternComponentBodySize computes.
var bufferSizeBefore = 0
var expectedPop = 0
_internalInvariant({
bufferSizeBefore = buffer.count
expectedPop = header.patternComponentBodySize
return true
}())
switch header.kind {
case .class, .struct:
visitStored(header: header, componentBuffer: &buffer)
case .computed:
let (idValueBase, idValue, getter, setter)
= popComputedAccessors(header: header,
componentBuffer: &buffer)
// If there are arguments, gather those too.
let arguments = popComputedArguments(header: header,
componentBuffer: &buffer)
walker.visitComputedComponent(mutating: header.isComputedMutating,
idKind: header.computedIDKind,
idResolution: header.computedIDResolution,
idValueBase: idValueBase,
idValue: idValue,
getter: getter,
setter: setter,
arguments: arguments,
externalArgs: nil)
case .optionalChain:
walker.visitOptionalChainComponent()
case .optionalWrap:
walker.visitOptionalWrapComponent()
case .optionalForce:
walker.visitOptionalForceComponent()
case .external:
// Look at the external property descriptor to see if we should take it
// over the component given in the pattern.
let genericParamCount = Int(header.payload)
let descriptorBase = buffer.baseAddress.unsafelyUnwrapped
let descriptorOffset = _pop(from: &buffer,
as: Int32.self)
let descriptor =
_resolveRelativeIndirectableAddress(descriptorBase, descriptorOffset)
let descriptorHeader =
descriptor.load(as: RawKeyPathComponent.Header.self)
if descriptorHeader.isTrivialPropertyDescriptor {
// If the descriptor is trivial, then use the local candidate.
// Skip the external generic parameter accessors to get to it.
_ = _pop(from: &buffer, as: Int32.self, count: genericParamCount)
continue
}
// Grab the generic parameter accessors to pass to the external component.
let externalArgs = _pop(from: &buffer, as: Int32.self,
count: genericParamCount)
// Grab the header for the local candidate in case we need it for
// a computed property.
let localCandidateHeader = _pop(from: &buffer,
as: RawKeyPathComponent.Header.self)
let localCandidateSize = localCandidateHeader.patternComponentBodySize
_internalInvariant({
expectedPop += localCandidateSize + 4
return true
}())
let descriptorSize = descriptorHeader.propertyDescriptorBodySize
var descriptorBuffer = UnsafeRawBufferPointer(start: descriptor + 4,
count: descriptorSize)
// Look at what kind of component the external property has.
switch descriptorHeader.kind {
case .struct, .class:
// A stored component. We can instantiate it
// without help from the local candidate.
_ = _pop(from: &buffer, as: UInt8.self, count: localCandidateSize)
visitStored(header: descriptorHeader,
componentBuffer: &descriptorBuffer)
case .computed:
// A computed component. The accessors come from the descriptor.
let (idValueBase, idValue, getter, setter)
= popComputedAccessors(header: descriptorHeader,
componentBuffer: &descriptorBuffer)
// Get the arguments from the external descriptor and/or local candidate
// component.
let arguments: KeyPathPatternComputedArguments?
if localCandidateHeader.kind == .computed
&& localCandidateHeader.hasComputedArguments {
// If both have arguments, then we have to build a bit of a chimera.
// The canonical identity and accessors come from the descriptor,
// but the argument equality/hash handling is still as described
// in the local candidate.
// We don't need the local candidate's accessors.
_ = popComputedAccessors(header: localCandidateHeader,
componentBuffer: &buffer)
// We do need the local arguments.
arguments = popComputedArguments(header: localCandidateHeader,
componentBuffer: &buffer)
} else {
// If the local candidate doesn't have arguments, we don't need
// anything from it at all.
_ = _pop(from: &buffer, as: UInt8.self, count: localCandidateSize)
arguments = nil
}
walker.visitComputedComponent(
mutating: descriptorHeader.isComputedMutating,
idKind: descriptorHeader.computedIDKind,
idResolution: descriptorHeader.computedIDResolution,
idValueBase: idValueBase,
idValue: idValue,
getter: getter,
setter: setter,
arguments: arguments,
externalArgs: genericParamCount > 0 ? externalArgs : nil)
case .optionalChain, .optionalWrap, .optionalForce, .external:
_internalInvariantFailure("not possible for property descriptor")
}
}
// Check that we consumed the expected amount of data from the pattern.
_internalInvariant(
{
// Round the amount of data we read up to alignment.
let popped = MemoryLayout<Int32>._roundingUpToAlignment(
bufferSizeBefore - buffer.count)
return expectedPop == popped
}(),
"""
component size consumed during pattern walk does not match \
component size returned by patternComponentBodySize
""")
// Break if this is the last component.
if buffer.isEmpty { break }
// Otherwise, pop the intermediate component type accessor and
// go around again.
let componentTypeBase = buffer.baseAddress.unsafelyUnwrapped
let componentTypeOffset = _pop(from: &buffer, as: Int32.self)
let componentTypeRef = _resolveRelativeAddress(componentTypeBase,
componentTypeOffset)
walker.visitIntermediateComponentType(metadataRef: componentTypeRef)
_internalInvariant(!buffer.isEmpty)
}
// We should have walked the entire pattern.
_internalInvariant(buffer.isEmpty, "did not walk entire pattern buffer")
walker.finish()
}
internal struct GetKeyPathClassAndInstanceSizeFromPattern
: KeyPathPatternVisitor {
var size: Int = MemoryLayout<Int>.size // start with one word for the header
var capability: KeyPathKind = .value
var didChain: Bool = false
var root: Any.Type!
var leaf: Any.Type!
var genericEnvironment: UnsafeRawPointer?
let patternArgs: UnsafeRawPointer?
init(patternArgs: UnsafeRawPointer?) {
self.patternArgs = patternArgs
}
mutating func roundUpToPointerAlignment() {
size = MemoryLayout<Int>._roundingUpToAlignment(size)
}
mutating func visitHeader(genericEnvironment: UnsafeRawPointer?,
rootMetadataRef: MetadataReference,
leafMetadataRef: MetadataReference,
kvcCompatibilityString: UnsafeRawPointer?) {
self.genericEnvironment = genericEnvironment
// Get the root and leaf type metadata so we can form the class type
// for the entire key path.
root = _resolveKeyPathMetadataReference(
rootMetadataRef,
genericEnvironment: genericEnvironment,
arguments: patternArgs)
leaf = _resolveKeyPathMetadataReference(
leafMetadataRef,
genericEnvironment: genericEnvironment,
arguments: patternArgs)
}
mutating func visitStoredComponent(kind: KeyPathStructOrClass,
mutable: Bool,
offset: KeyPathPatternStoredOffset) {
// Mutable class properties can be the root of a reference mutation.
// Mutable struct properties pass through the existing capability.
if mutable {
switch kind {
case .class:
capability = .reference
case .struct:
break
}
} else {
// Immutable properties can only be read.
capability = .readOnly
}
// The size of the instantiated component depends on whether we can fit
// the offset inline.
switch offset {
case .inline:
size += 4
case .outOfLine, .unresolvedFieldOffset, .unresolvedIndirectOffset:
size += 8
}
}
mutating func visitComputedComponent(mutating: Bool,
idKind: KeyPathComputedIDKind,
idResolution: KeyPathComputedIDResolution,
idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?,
arguments: KeyPathPatternComputedArguments?,
externalArgs: UnsafeBufferPointer<Int32>?) {
let settable = setter != nil
switch (settable, mutating) {
case (false, false):
// If the property is get-only, the capability becomes read-only, unless
// we get another reference-writable component.
capability = .readOnly
case (true, false):
capability = .reference
case (true, true):
// Writable if the base is. No effect.
break
case (false, true):
_internalInvariantFailure("unpossible")
}
// Save space for the header...
size += 4
roundUpToPointerAlignment()
// ...id, getter, and maybe setter...
size += MemoryLayout<Int>.size * 2
if settable {
size += MemoryLayout<Int>.size
}
// ...and the arguments, if any.
let argumentHeaderSize = MemoryLayout<Int>.size * 2
switch (arguments, externalArgs) {
case (nil, nil):
break
case (let arguments?, nil):
size += argumentHeaderSize
// If we have arguments, calculate how much space they need by invoking
// the layout function.
let (addedSize, addedAlignmentMask) = arguments.getLayout(patternArgs)
// TODO: Handle over-aligned values
_internalInvariant(addedAlignmentMask < MemoryLayout<Int>.alignment,
"overaligned computed property element not supported")
size += addedSize
case (let arguments?, let externalArgs?):
// If we're referencing an external declaration, and it takes captured
// arguments, then we have to build a bit of a chimera. The canonical
// identity and accessors come from the descriptor, but the argument
// handling is still as described in the local candidate.
size += argumentHeaderSize
let (addedSize, addedAlignmentMask) = arguments.getLayout(patternArgs)
// TODO: Handle over-aligned values
_internalInvariant(addedAlignmentMask < MemoryLayout<Int>.alignment,
"overaligned computed property element not supported")
size += addedSize
// We also need to store the size of the local arguments so we can
// find the external component arguments.
roundUpToPointerAlignment()
size += RawKeyPathComponent.Header.externalWithArgumentsExtraSize
size += MemoryLayout<Int>.size * externalArgs.count
case (nil, let externalArgs?):
// If we're instantiating an external property with a local
// candidate that has no arguments, then things are a little
// easier. We only need to instantiate the generic
// arguments for the external component's accessors.
size += argumentHeaderSize
size += MemoryLayout<Int>.size * externalArgs.count
}
}
mutating func visitOptionalChainComponent() {
// Optional chaining forces the entire keypath to be read-only, even if
// there are further reference-writable components.
didChain = true
capability = .readOnly
size += 4
}
mutating func visitOptionalWrapComponent() {
// Optional chaining forces the entire keypath to be read-only, even if
// there are further reference-writable components.
didChain = true
capability = .readOnly
size += 4
}
mutating func visitOptionalForceComponent() {
// Force-unwrapping passes through the mutability of the preceding keypath.
size += 4
}
mutating
func visitIntermediateComponentType(metadataRef _: MetadataReference) {
// The instantiated component type will be stored in the instantiated
// object.
roundUpToPointerAlignment()
size += MemoryLayout<Int>.size
}
mutating func finish() {
}
}
internal func _getKeyPathClassAndInstanceSizeFromPattern(
_ pattern: UnsafeRawPointer,
_ arguments: UnsafeRawPointer
) -> (
keyPathClass: AnyKeyPath.Type,
rootType: Any.Type,
size: Int,
alignmentMask: Int
) {
var walker = GetKeyPathClassAndInstanceSizeFromPattern(patternArgs: arguments)
_walkKeyPathPattern(pattern, walker: &walker)
// Chaining always renders the whole key path read-only.
if walker.didChain {
walker.capability = .readOnly
}
// Grab the class object for the key path type we'll end up with.
func openRoot<Root>(_: Root.Type) -> AnyKeyPath.Type {
func openLeaf<Leaf>(_: Leaf.Type) -> AnyKeyPath.Type {
switch walker.capability {
case .readOnly:
return KeyPath<Root, Leaf>.self
case .value:
return WritableKeyPath<Root, Leaf>.self
case .reference:
return ReferenceWritableKeyPath<Root, Leaf>.self
}
}
return _openExistential(walker.leaf!, do: openLeaf)
}
let classTy = _openExistential(walker.root!, do: openRoot)
return (keyPathClass: classTy,
rootType: walker.root!,
size: walker.size,
// FIXME: Handle overalignment
alignmentMask: MemoryLayout<Int>._alignmentMask)
}
internal struct InstantiateKeyPathBuffer: KeyPathPatternVisitor {
var destData: UnsafeMutableRawBufferPointer
var genericEnvironment: UnsafeRawPointer?
let patternArgs: UnsafeRawPointer?
var base: Any.Type
init(destData: UnsafeMutableRawBufferPointer,
patternArgs: UnsafeRawPointer?,
root: Any.Type) {
self.destData = destData
self.patternArgs = patternArgs
self.base = root
}
// Track the triviality of the resulting object data.
var isTrivial: Bool = true
// Track where the reference prefix begins.
var endOfReferencePrefixComponent: UnsafeMutableRawPointer? = nil
var previousComponentAddr: UnsafeMutableRawPointer? = nil
mutating func adjustDestForAlignment<T>(of: T.Type) -> (
baseAddress: UnsafeMutableRawPointer,
misalign: Int
) {
let alignment = MemoryLayout<T>.alignment
var baseAddress = destData.baseAddress.unsafelyUnwrapped
var misalign = Int(bitPattern: baseAddress) % alignment
if misalign != 0 {
misalign = alignment - misalign
baseAddress = baseAddress.advanced(by: misalign)
}
return (baseAddress, misalign)
}
mutating func pushDest<T>(_ value: T) {
_internalInvariant(_isPOD(T.self))
let size = MemoryLayout<T>.size
let (baseAddress, misalign) = adjustDestForAlignment(of: T.self)
withUnsafeBytes(of: value) {
_memcpy(dest: baseAddress, src: $0.baseAddress.unsafelyUnwrapped,
size: UInt(size))
}
destData = UnsafeMutableRawBufferPointer(
start: baseAddress + size,
count: destData.count - size - misalign)
}
mutating func pushAddressDiscriminatedFunctionPointer(
_ unsignedPointer: UnsafeRawPointer,
discriminator: UInt64
) {
let size = MemoryLayout<UnsafeRawPointer>.size
let (baseAddress, misalign) =
adjustDestForAlignment(of: UnsafeRawPointer.self)
baseAddress._storeFunctionPointerWithAddressDiscrimination(
unsignedPointer, discriminator: discriminator)
destData = UnsafeMutableRawBufferPointer(
start: baseAddress + size,
count: destData.count - size - misalign)
}
mutating func updatePreviousComponentAddr() -> UnsafeMutableRawPointer? {
let oldValue = previousComponentAddr
previousComponentAddr = destData.baseAddress.unsafelyUnwrapped
return oldValue
}
mutating func visitHeader(genericEnvironment: UnsafeRawPointer?,
rootMetadataRef: MetadataReference,
leafMetadataRef: MetadataReference,
kvcCompatibilityString: UnsafeRawPointer?) {
self.genericEnvironment = genericEnvironment
}
mutating func visitStoredComponent(kind: KeyPathStructOrClass,
mutable: Bool,
offset: KeyPathPatternStoredOffset) {
let previous = updatePreviousComponentAddr()
switch kind {
case .class:
// A mutable class property can end the reference prefix.
if mutable {
endOfReferencePrefixComponent = previous
}
fallthrough
case .struct:
// Resolve the offset.
switch offset {
case .inline(let value):
let header = RawKeyPathComponent.Header(stored: kind,
mutable: mutable,
inlineOffset: value)
pushDest(header)
case .outOfLine(let offset):
let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind,
mutable: mutable)
pushDest(header)
pushDest(offset)
case .unresolvedFieldOffset(let offsetOfOffset):
// Look up offset in the type metadata. The value in the pattern is
// the offset within the metadata object.
let metadataPtr = unsafeBitCast(base, to: UnsafeRawPointer.self)
let offset: UInt32
switch kind {
case .class:
offset = UInt32(metadataPtr.load(fromByteOffset: Int(offsetOfOffset),
as: UInt.self))
case .struct:
offset = UInt32(metadataPtr.load(fromByteOffset: Int(offsetOfOffset),
as: UInt32.self))
}
let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind,
mutable: mutable)
pushDest(header)
pushDest(offset)
case .unresolvedIndirectOffset(let pointerToOffset):
// Look up offset in the indirectly-referenced variable we have a
// pointer.
_internalInvariant(pointerToOffset.pointee <= UInt32.max)
let offset = UInt32(truncatingIfNeeded: pointerToOffset.pointee)
let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind,
mutable: mutable)
pushDest(header)
pushDest(offset)
}
}
}
mutating func visitComputedComponent(mutating: Bool,
idKind: KeyPathComputedIDKind,
idResolution: KeyPathComputedIDResolution,
idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?,
arguments: KeyPathPatternComputedArguments?,
externalArgs: UnsafeBufferPointer<Int32>?) {
let previous = updatePreviousComponentAddr()
let settable = setter != nil
// A nonmutating settable property can end the reference prefix.
if settable && !mutating {
endOfReferencePrefixComponent = previous
}
// Resolve the ID.
let resolvedID: UnsafeRawPointer?
switch idKind {
case .storedPropertyIndex, .vtableOffset:
_internalInvariant(idResolution == .resolved)
// Zero-extend the integer value to get the instantiated id.
let value = UInt(UInt32(bitPattern: idValue))
resolvedID = UnsafeRawPointer(bitPattern: value)
case .pointer:
// Resolve the sign-extended relative reference.
var absoluteID: UnsafeRawPointer? = _resolveRelativeAddress(idValueBase, idValue)
// If the pointer ID is unresolved, then it needs work to get to
// the final value.
switch idResolution {
case .resolved:
break
case .indirectPointer:
// The pointer in the pattern is an indirect pointer to the real
// identifier pointer.
absoluteID = absoluteID.unsafelyUnwrapped
.load(as: UnsafeRawPointer?.self)
case .functionCall:
// The pointer in the pattern is to a function that generates the
// identifier pointer.
typealias Resolver = @convention(c) (UnsafeRawPointer?) -> UnsafeRawPointer?
let resolverSigned = _PtrAuth.sign(
pointer: absoluteID.unsafelyUnwrapped,
key: .processIndependentCode,
discriminator: _PtrAuth.discriminator(for: Resolver.self))
let resolverFn = unsafeBitCast(resolverSigned,
to: Resolver.self)
absoluteID = resolverFn(patternArgs)
}
resolvedID = absoluteID
}
// Bring over the header, getter, and setter.
let header = RawKeyPathComponent.Header(computedWithIDKind: idKind,
mutating: mutating,
settable: settable,
hasArguments: arguments != nil || externalArgs != nil,
instantiatedFromExternalWithArguments:
arguments != nil && externalArgs != nil)
pushDest(header)
pushDest(resolvedID)
pushAddressDiscriminatedFunctionPointer(getter,
discriminator: ComputedAccessorsPtr.getterPtrAuthKey)
if let setter = setter {
pushAddressDiscriminatedFunctionPointer(setter,
discriminator: mutating ? ComputedAccessorsPtr.mutatingSetterPtrAuthKey
: ComputedAccessorsPtr.nonmutatingSetterPtrAuthKey)
}
if let arguments = arguments {
// Instantiate the arguments.
let (baseSize, alignmentMask) = arguments.getLayout(patternArgs)
_internalInvariant(alignmentMask < MemoryLayout<Int>.alignment,
"overaligned computed arguments not implemented yet")
// The real buffer stride will be rounded up to alignment.
var totalSize = (baseSize + alignmentMask) & ~alignmentMask
// If an external property descriptor also has arguments, they'll be
// added to the end with pointer alignment.
if let externalArgs = externalArgs {
totalSize = MemoryLayout<Int>._roundingUpToAlignment(totalSize)
totalSize += MemoryLayout<Int>.size * externalArgs.count
}
pushDest(totalSize)
pushDest(arguments.witnesses)
// A nonnull destructor in the witnesses file indicates the instantiated
// payload is nontrivial.
if let _ = arguments.witnesses.destroy {
isTrivial = false
}
// If the descriptor has arguments, store the size of its specific
// arguments here, so we can drop them when trying to invoke
// the component's witnesses.
if let externalArgs = externalArgs {
pushDest(externalArgs.count * MemoryLayout<Int>.size)
}
// Initialize the local candidate arguments here.
_internalInvariant(Int(bitPattern: destData.baseAddress) & alignmentMask == 0,
"argument destination not aligned")
arguments.initializer(patternArgs,
destData.baseAddress.unsafelyUnwrapped)
destData = UnsafeMutableRawBufferPointer(
start: destData.baseAddress.unsafelyUnwrapped + baseSize,
count: destData.count - baseSize)
}
if let externalArgs = externalArgs {
if arguments == nil {
// If we're instantiating an external property without any local
// arguments, then we only need to instantiate the arguments to the
// property descriptor.
let stride = MemoryLayout<Int>.size * externalArgs.count
pushDest(stride)
pushDest(__swift_keyPathGenericWitnessTable_addr())
}
// Write the descriptor's generic arguments, which should all be relative
// references to metadata accessor functions.
for i in externalArgs.indices {
let base = externalArgs.baseAddress.unsafelyUnwrapped + i
let offset = base.pointee
let metadataRef = _resolveRelativeAddress(UnsafeRawPointer(base), offset)
let result = _resolveKeyPathGenericArgReference(
metadataRef,
genericEnvironment: genericEnvironment,
arguments: patternArgs)
pushDest(result)
}
}
}
mutating func visitOptionalChainComponent() {
let _ = updatePreviousComponentAddr()
let header = RawKeyPathComponent.Header(optionalChain: ())
pushDest(header)
}
mutating func visitOptionalWrapComponent() {
let _ = updatePreviousComponentAddr()
let header = RawKeyPathComponent.Header(optionalWrap: ())
pushDest(header)
}
mutating func visitOptionalForceComponent() {
let _ = updatePreviousComponentAddr()
let header = RawKeyPathComponent.Header(optionalForce: ())
pushDest(header)
}
mutating func visitIntermediateComponentType(metadataRef: MetadataReference) {
// Get the metadata for the intermediate type.
let metadata = _resolveKeyPathMetadataReference(
metadataRef,
genericEnvironment: genericEnvironment,
arguments: patternArgs)
pushDest(metadata)
base = metadata
}
mutating func finish() {
// Should have filled the entire buffer by the time we reach the end of the
// pattern.
_internalInvariant(destData.isEmpty,
"should have filled entire destination buffer")
}
}
#if INTERNAL_CHECKS_ENABLED
// In debug builds of the standard library, check that instantiation produces
// components whose sizes are consistent with the sizing visitor pass.
internal struct ValidatingInstantiateKeyPathBuffer: KeyPathPatternVisitor {
var sizeVisitor: GetKeyPathClassAndInstanceSizeFromPattern
var instantiateVisitor: InstantiateKeyPathBuffer
let origDest: UnsafeMutableRawPointer
init(sizeVisitor: GetKeyPathClassAndInstanceSizeFromPattern,
instantiateVisitor: InstantiateKeyPathBuffer) {
self.sizeVisitor = sizeVisitor
self.instantiateVisitor = instantiateVisitor
origDest = self.instantiateVisitor.destData.baseAddress.unsafelyUnwrapped
}
mutating func visitHeader(genericEnvironment: UnsafeRawPointer?,
rootMetadataRef: MetadataReference,
leafMetadataRef: MetadataReference,
kvcCompatibilityString: UnsafeRawPointer?) {
sizeVisitor.visitHeader(genericEnvironment: genericEnvironment,
rootMetadataRef: rootMetadataRef,
leafMetadataRef: leafMetadataRef,
kvcCompatibilityString: kvcCompatibilityString)
instantiateVisitor.visitHeader(genericEnvironment: genericEnvironment,
rootMetadataRef: rootMetadataRef,
leafMetadataRef: leafMetadataRef,
kvcCompatibilityString: kvcCompatibilityString)
}
mutating func visitStoredComponent(kind: KeyPathStructOrClass,
mutable: Bool,
offset: KeyPathPatternStoredOffset) {
sizeVisitor.visitStoredComponent(kind: kind, mutable: mutable,
offset: offset)
instantiateVisitor.visitStoredComponent(kind: kind, mutable: mutable,
offset: offset)
checkSizeConsistency()
}
mutating func visitComputedComponent(mutating: Bool,
idKind: KeyPathComputedIDKind,
idResolution: KeyPathComputedIDResolution,
idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?,
arguments: KeyPathPatternComputedArguments?,
externalArgs: UnsafeBufferPointer<Int32>?) {
sizeVisitor.visitComputedComponent(mutating: mutating,
idKind: idKind,
idResolution: idResolution,
idValueBase: idValueBase,
idValue: idValue,
getter: getter,
setter: setter,
arguments: arguments,
externalArgs: externalArgs)
instantiateVisitor.visitComputedComponent(mutating: mutating,
idKind: idKind,
idResolution: idResolution,
idValueBase: idValueBase,
idValue: idValue,
getter: getter,
setter: setter,
arguments: arguments,
externalArgs: externalArgs)
checkSizeConsistency()
}
mutating func visitOptionalChainComponent() {
sizeVisitor.visitOptionalChainComponent()
instantiateVisitor.visitOptionalChainComponent()
checkSizeConsistency()
}
mutating func visitOptionalWrapComponent() {
sizeVisitor.visitOptionalWrapComponent()
instantiateVisitor.visitOptionalWrapComponent()
checkSizeConsistency()
}
mutating func visitOptionalForceComponent() {
sizeVisitor.visitOptionalForceComponent()
instantiateVisitor.visitOptionalForceComponent()
checkSizeConsistency()
}
mutating func visitIntermediateComponentType(metadataRef: MetadataReference) {
sizeVisitor.visitIntermediateComponentType(metadataRef: metadataRef)
instantiateVisitor.visitIntermediateComponentType(metadataRef: metadataRef)
checkSizeConsistency()
}
mutating func finish() {
sizeVisitor.finish()
instantiateVisitor.finish()
checkSizeConsistency()
}
func checkSizeConsistency() {
let nextDest = instantiateVisitor.destData.baseAddress.unsafelyUnwrapped
let curSize = nextDest - origDest + MemoryLayout<Int>.size
_internalInvariant(curSize == sizeVisitor.size,
"size and instantiation visitors out of sync")
}
}
#endif // INTERNAL_CHECKS_ENABLED
internal func _instantiateKeyPathBuffer(
_ pattern: UnsafeRawPointer,
_ origDestData: UnsafeMutableRawBufferPointer,
_ rootType: Any.Type,
_ arguments: UnsafeRawPointer
) {
let destHeaderPtr = origDestData.baseAddress.unsafelyUnwrapped
var destData = UnsafeMutableRawBufferPointer(
start: destHeaderPtr.advanced(by: MemoryLayout<Int>.size),
count: origDestData.count - MemoryLayout<Int>.size)
#if INTERNAL_CHECKS_ENABLED
// If checks are enabled, use a validating walker that ensures that the
// size pre-walk and instantiation walk are in sync.
let sizeWalker = GetKeyPathClassAndInstanceSizeFromPattern(
patternArgs: arguments)
let instantiateWalker = InstantiateKeyPathBuffer(
destData: destData,
patternArgs: arguments,
root: rootType)
var walker = ValidatingInstantiateKeyPathBuffer(sizeVisitor: sizeWalker,
instantiateVisitor: instantiateWalker)
#else
var walker = InstantiateKeyPathBuffer(
destData: destData,
patternArgs: arguments,
root: rootType)
#endif
_walkKeyPathPattern(pattern, walker: &walker)
#if INTERNAL_CHECKS_ENABLED
let isTrivial = walker.instantiateVisitor.isTrivial
let endOfReferencePrefixComponent =
walker.instantiateVisitor.endOfReferencePrefixComponent
#else
let isTrivial = walker.isTrivial
let endOfReferencePrefixComponent = walker.endOfReferencePrefixComponent
#endif
// Write out the header.
let destHeader = KeyPathBuffer.Header(
size: origDestData.count - MemoryLayout<Int>.size,
trivial: isTrivial,
hasReferencePrefix: endOfReferencePrefixComponent != nil)
destHeaderPtr.storeBytes(of: destHeader, as: KeyPathBuffer.Header.self)
// Mark the reference prefix if there is one.
if let endOfReferencePrefixComponent = endOfReferencePrefixComponent {
var componentHeader = endOfReferencePrefixComponent
.load(as: RawKeyPathComponent.Header.self)
componentHeader.endOfReferencePrefix = true
endOfReferencePrefixComponent.storeBytes(of: componentHeader,
as: RawKeyPathComponent.Header.self)
}
}
Keep doc comment before declaration.
Because the attribute is part of the declaration, putting a doc comment
between the attribute and "public" ends up with the comment in the
middle of the declaration. This results in SourceKit skipping over the
comment, and the docs not being shown.
Fixes <rdar://problem/58716408>.
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
internal func _abstract(
methodName: StaticString = #function,
file: StaticString = #file, line: UInt = #line
) -> Never {
#if INTERNAL_CHECKS_ENABLED
_fatalErrorMessage("abstract method", methodName, file: file, line: line,
flags: _fatalErrorFlags())
#else
_conditionallyUnreachable()
#endif
}
// MARK: Type-erased abstract base classes
// NOTE: older runtimes had Swift.AnyKeyPath as the ObjC name.
// The two must coexist, so it was renamed. The old name must not be
// used in the new runtime. _TtCs11_AnyKeyPath is the mangled name for
// Swift._AnyKeyPath.
/// A type-erased key path, from any root type to any resulting value
/// type.
@_objcRuntimeName(_TtCs11_AnyKeyPath)
public class AnyKeyPath: Hashable, _AppendKeyPath {
/// The root type for this key path.
@inlinable
public static var rootType: Any.Type {
return _rootAndValueType.root
}
/// The value type for this key path.
@inlinable
public static var valueType: Any.Type {
return _rootAndValueType.value
}
internal final var _kvcKeyPathStringPtr: UnsafePointer<CChar>?
/// The hash value.
final public var hashValue: Int {
return _hashValue(for: self)
}
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@_effects(releasenone)
final public func hash(into hasher: inout Hasher) {
ObjectIdentifier(type(of: self)).hash(into: &hasher)
return withBuffer {
var buffer = $0
if buffer.data.isEmpty { return }
while true {
let (component, type) = buffer.next()
hasher.combine(component.value)
if let type = type {
hasher.combine(unsafeBitCast(type, to: Int.self))
} else {
break
}
}
}
}
public static func ==(a: AnyKeyPath, b: AnyKeyPath) -> Bool {
// Fast-path identical objects
if a === b {
return true
}
// Short-circuit differently-typed key paths
if type(of: a) != type(of: b) {
return false
}
return a.withBuffer {
var aBuffer = $0
return b.withBuffer {
var bBuffer = $0
// Two equivalent key paths should have the same reference prefix
if aBuffer.hasReferencePrefix != bBuffer.hasReferencePrefix {
return false
}
// Identity is equal to identity
if aBuffer.data.isEmpty {
return bBuffer.data.isEmpty
}
while true {
let (aComponent, aType) = aBuffer.next()
let (bComponent, bType) = bBuffer.next()
if aComponent.header.endOfReferencePrefix
!= bComponent.header.endOfReferencePrefix
|| aComponent.value != bComponent.value
|| aType != bType {
return false
}
if aType == nil {
return true
}
}
}
}
}
// SPI for the Foundation overlay to allow interop with KVC keypath-based
// APIs.
public var _kvcKeyPathString: String? {
@_semantics("keypath.kvcKeyPathString")
get {
guard let ptr = _kvcKeyPathStringPtr else { return nil }
return String(validatingUTF8: ptr)
}
}
// MARK: Implementation details
// Prevent normal initialization. We use tail allocation via
// allocWithTailElems().
@available(*, unavailable)
internal init() {
_internalInvariantFailure("use _create(...)")
}
@usableFromInline
internal class var _rootAndValueType: (root: Any.Type, value: Any.Type) {
_abstract()
}
internal static func _create(
capacityInBytes bytes: Int,
initializedBy body: (UnsafeMutableRawBufferPointer) -> Void
) -> Self {
_internalInvariant(bytes > 0 && bytes % 4 == 0,
"capacity must be multiple of 4 bytes")
let result = Builtin.allocWithTailElems_1(self, (bytes/4)._builtinWordValue,
Int32.self)
result._kvcKeyPathStringPtr = nil
let base = UnsafeMutableRawPointer(Builtin.projectTailElems(result,
Int32.self))
body(UnsafeMutableRawBufferPointer(start: base, count: bytes))
return result
}
final internal func withBuffer<T>(_ f: (KeyPathBuffer) throws -> T) rethrows -> T {
defer { _fixLifetime(self) }
let base = UnsafeRawPointer(Builtin.projectTailElems(self, Int32.self))
return try f(KeyPathBuffer(base: base))
}
@usableFromInline // Exposed as public API by MemoryLayout<Root>.offset(of:)
internal var _storedInlineOffset: Int? {
return withBuffer {
var buffer = $0
// The identity key path is effectively a stored keypath of type Self
// at offset zero
if buffer.data.isEmpty { return 0 }
var offset = 0
while true {
let (rawComponent, optNextType) = buffer.next()
switch rawComponent.header.kind {
case .struct:
offset += rawComponent._structOrClassOffset
case .class, .computed, .optionalChain, .optionalForce, .optionalWrap, .external:
return .none
}
if optNextType == nil { return .some(offset) }
}
}
}
}
/// A partially type-erased key path, from a concrete root type to any
/// resulting value type.
public class PartialKeyPath<Root>: AnyKeyPath { }
// MARK: Concrete implementations
internal enum KeyPathKind { case readOnly, value, reference }
/// A key path from a specific root type to a specific resulting value type.
public class KeyPath<Root, Value>: PartialKeyPath<Root> {
@usableFromInline
internal final override class var _rootAndValueType: (
root: Any.Type,
value: Any.Type
) {
return (Root.self, Value.self)
}
// MARK: Implementation
internal typealias Kind = KeyPathKind
internal class var kind: Kind { return .readOnly }
internal static func appendedType<AppendedValue>(
with t: KeyPath<Value, AppendedValue>.Type
) -> KeyPath<Root, AppendedValue>.Type {
let resultKind: Kind
switch (self.kind, t.kind) {
case (_, .reference):
resultKind = .reference
case (let x, .value):
resultKind = x
default:
resultKind = .readOnly
}
switch resultKind {
case .readOnly:
return KeyPath<Root, AppendedValue>.self
case .value:
return WritableKeyPath.self
case .reference:
return ReferenceWritableKeyPath.self
}
}
@usableFromInline
internal final func _projectReadOnly(from root: Root) -> Value {
// TODO: For perf, we could use a local growable buffer instead of Any
var curBase: Any = root
return withBuffer {
var buffer = $0
if buffer.data.isEmpty {
return unsafeBitCast(root, to: Value.self)
}
while true {
let (rawComponent, optNextType) = buffer.next()
let valueType = optNextType ?? Value.self
let isLast = optNextType == nil
func project<CurValue>(_ base: CurValue) -> Value? {
func project2<NewValue>(_: NewValue.Type) -> Value? {
switch rawComponent._projectReadOnly(base,
to: NewValue.self, endingWith: Value.self) {
case .continue(let newBase):
if isLast {
_internalInvariant(NewValue.self == Value.self,
"key path does not terminate in correct type")
return unsafeBitCast(newBase, to: Value.self)
} else {
curBase = newBase
return nil
}
case .break(let result):
return result
}
}
return _openExistential(valueType, do: project2)
}
if let result = _openExistential(curBase, do: project) {
return result
}
}
}
}
deinit {
withBuffer { $0.destroy() }
}
}
/// A key path that supports reading from and writing to the resulting value.
public class WritableKeyPath<Root, Value>: KeyPath<Root, Value> {
// MARK: Implementation detail
internal override class var kind: Kind { return .value }
// `base` is assumed to be undergoing a formal access for the duration of the
// call, so must not be mutated by an alias
@usableFromInline
internal func _projectMutableAddress(from base: UnsafePointer<Root>)
-> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
var p = UnsafeRawPointer(base)
var type: Any.Type = Root.self
var keepAlive: AnyObject?
return withBuffer {
var buffer = $0
_internalInvariant(!buffer.hasReferencePrefix,
"WritableKeyPath should not have a reference prefix")
if buffer.data.isEmpty {
return (
UnsafeMutablePointer<Value>(
mutating: p.assumingMemoryBound(to: Value.self)),
nil)
}
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent._projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == UnsafeRawPointer(base),
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(type, do: project)
if optNextType == nil { break }
type = nextType
}
// TODO: With coroutines, it would be better to yield here, so that
// we don't need the hack of the keepAlive reference to manage closing
// accesses.
let typedPointer = p.assumingMemoryBound(to: Value.self)
return (pointer: UnsafeMutablePointer(mutating: typedPointer),
owner: keepAlive)
}
}
}
/// A key path that supports reading from and writing to the resulting value
/// with reference semantics.
public class ReferenceWritableKeyPath<
Root, Value
>: WritableKeyPath<Root, Value> {
// MARK: Implementation detail
internal final override class var kind: Kind { return .reference }
@usableFromInline
internal final func _projectMutableAddress(from origBase: Root)
-> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
var keepAlive: AnyObject?
let address: UnsafeMutablePointer<Value> = withBuffer {
var buffer = $0
// Project out the reference prefix.
var base: Any = origBase
while buffer.hasReferencePrefix {
let (rawComponent, optNextType) = buffer.next()
_internalInvariant(optNextType != nil,
"reference prefix should not go to end of buffer")
let nextType = optNextType.unsafelyUnwrapped
func project<NewValue>(_: NewValue.Type) -> Any {
func project2<CurValue>(_ base: CurValue) -> Any {
return rawComponent._projectReadOnly(
base, to: NewValue.self, endingWith: Value.self)
.assumingContinue
}
return _openExistential(base, do: project2)
}
base = _openExistential(nextType, do: project)
}
// Start formal access to the mutable value, based on the final base
// value.
func formalMutation<MutationRoot>(_ base: MutationRoot)
-> UnsafeMutablePointer<Value> {
var base2 = base
return withUnsafeBytes(of: &base2) { baseBytes in
var p = baseBytes.baseAddress.unsafelyUnwrapped
var curType: Any.Type = MutationRoot.self
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent._projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == baseBytes.baseAddress,
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(curType, do: project)
if optNextType == nil { break }
curType = nextType
}
let typedPointer = p.assumingMemoryBound(to: Value.self)
return UnsafeMutablePointer(mutating: typedPointer)
}
}
return _openExistential(base, do: formalMutation)
}
return (address, keepAlive)
}
}
// MARK: Implementation details
internal enum KeyPathComponentKind {
/// The keypath references an externally-defined property or subscript whose
/// component describes how to interact with the key path.
case external
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`
/// The keypath projects using a getter/setter pair.
case computed
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
}
internal struct ComputedPropertyID: Hashable {
internal var value: Int
internal var kind: KeyPathComputedIDKind
internal static func ==(
x: ComputedPropertyID, y: ComputedPropertyID
) -> Bool {
return x.value == y.value
&& x.kind == y.kind
}
internal func hash(into hasher: inout Hasher) {
hasher.combine(value)
hasher.combine(kind)
}
}
internal struct ComputedAccessorsPtr {
#if INTERNAL_CHECKS_ENABLED
internal let header: RawKeyPathComponent.Header
#endif
internal let _value: UnsafeRawPointer
init(header: RawKeyPathComponent.Header, value: UnsafeRawPointer) {
#if INTERNAL_CHECKS_ENABLED
self.header = header
#endif
self._value = value
}
@_transparent
static var getterPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_Getter)
}
@_transparent
static var nonmutatingSetterPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_NonmutatingSetter)
}
@_transparent
static var mutatingSetterPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_MutatingSetter)
}
internal typealias Getter<CurValue, NewValue> = @convention(thin)
(CurValue, UnsafeRawPointer, Int) -> NewValue
internal typealias NonmutatingSetter<CurValue, NewValue> = @convention(thin)
(NewValue, CurValue, UnsafeRawPointer, Int) -> ()
internal typealias MutatingSetter<CurValue, NewValue> = @convention(thin)
(NewValue, inout CurValue, UnsafeRawPointer, Int) -> ()
internal var getterPtr: UnsafeRawPointer {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(header.kind == .computed,
"not a computed property")
#endif
return _value
}
internal var setterPtr: UnsafeRawPointer {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(header.isComputedSettable,
"not a settable property")
#endif
return _value + MemoryLayout<Int>.size
}
internal func getter<CurValue, NewValue>()
-> Getter<CurValue, NewValue> {
return getterPtr._loadAddressDiscriminatedFunctionPointer(
as: Getter.self,
discriminator: ComputedAccessorsPtr.getterPtrAuthKey)
}
internal func nonmutatingSetter<CurValue, NewValue>()
-> NonmutatingSetter<CurValue, NewValue> {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(header.isComputedSettable && !header.isComputedMutating,
"not a nonmutating settable property")
#endif
return setterPtr._loadAddressDiscriminatedFunctionPointer(
as: NonmutatingSetter.self,
discriminator: ComputedAccessorsPtr.nonmutatingSetterPtrAuthKey)
}
internal func mutatingSetter<CurValue, NewValue>()
-> MutatingSetter<CurValue, NewValue> {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(header.isComputedSettable && header.isComputedMutating,
"not a mutating settable property")
#endif
return setterPtr._loadAddressDiscriminatedFunctionPointer(
as: MutatingSetter.self,
discriminator: ComputedAccessorsPtr.mutatingSetterPtrAuthKey)
}
}
internal struct ComputedArgumentWitnessesPtr {
internal let _value: UnsafeRawPointer
init(_ value: UnsafeRawPointer) {
self._value = value
}
@_transparent
static var destroyPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentDestroy)
}
@_transparent
static var copyPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentCopy)
}
@_transparent
static var equalsPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentEquals)
}
@_transparent
static var hashPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentHash)
}
@_transparent
static var layoutPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentLayout)
}
@_transparent
static var initPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentInit)
}
internal typealias Destroy = @convention(thin)
(_ instanceArguments: UnsafeMutableRawPointer, _ size: Int) -> ()
internal typealias Copy = @convention(thin)
(_ srcInstanceArguments: UnsafeRawPointer,
_ destInstanceArguments: UnsafeMutableRawPointer,
_ size: Int) -> ()
internal typealias Equals = @convention(thin)
(_ xInstanceArguments: UnsafeRawPointer,
_ yInstanceArguments: UnsafeRawPointer,
_ size: Int) -> Bool
// FIXME(hasher) Combine to an inout Hasher instead
internal typealias Hash = @convention(thin)
(_ instanceArguments: UnsafeRawPointer,
_ size: Int) -> Int
// The witnesses are stored as address-discriminated authenticated
// pointers.
internal var destroy: Destroy? {
return _value._loadAddressDiscriminatedFunctionPointer(
as: Optional<Destroy>.self,
discriminator: ComputedArgumentWitnessesPtr.destroyPtrAuthKey)
}
internal var copy: Copy {
return _value._loadAddressDiscriminatedFunctionPointer(
fromByteOffset: MemoryLayout<UnsafeRawPointer>.size,
as: Copy.self,
discriminator: ComputedArgumentWitnessesPtr.copyPtrAuthKey)
}
internal var equals: Equals {
return _value._loadAddressDiscriminatedFunctionPointer(
fromByteOffset: 2*MemoryLayout<UnsafeRawPointer>.size,
as: Equals.self,
discriminator: ComputedArgumentWitnessesPtr.equalsPtrAuthKey)
}
internal var hash: Hash {
return _value._loadAddressDiscriminatedFunctionPointer(
fromByteOffset: 3*MemoryLayout<UnsafeRawPointer>.size,
as: Hash.self,
discriminator: ComputedArgumentWitnessesPtr.hashPtrAuthKey)
}
}
internal enum KeyPathComponent: Hashable {
internal struct ArgumentRef {
internal init(
data: UnsafeRawBufferPointer,
witnesses: ComputedArgumentWitnessesPtr,
witnessSizeAdjustment: Int
) {
self.data = data
self.witnesses = witnesses
self.witnessSizeAdjustment = witnessSizeAdjustment
}
internal var data: UnsafeRawBufferPointer
internal var witnesses: ComputedArgumentWitnessesPtr
internal var witnessSizeAdjustment: Int
}
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`(offset: Int)
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`(offset: Int)
/// The keypath projects using a getter.
case get(id: ComputedPropertyID,
accessors: ComputedAccessorsPtr,
argument: ArgumentRef?)
/// The keypath projects using a getter/setter pair. The setter can mutate
/// the base value in-place.
case mutatingGetSet(id: ComputedPropertyID,
accessors: ComputedAccessorsPtr,
argument: ArgumentRef?)
/// The keypath projects using a getter/setter pair that does not mutate its
/// base.
case nonmutatingGetSet(id: ComputedPropertyID,
accessors: ComputedAccessorsPtr,
argument: ArgumentRef?)
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
internal static func ==(a: KeyPathComponent, b: KeyPathComponent) -> Bool {
switch (a, b) {
case (.struct(offset: let a), .struct(offset: let b)),
(.class (offset: let a), .class (offset: let b)):
return a == b
case (.optionalChain, .optionalChain),
(.optionalForce, .optionalForce),
(.optionalWrap, .optionalWrap):
return true
case (.get(id: let id1, accessors: _, argument: let argument1),
.get(id: let id2, accessors: _, argument: let argument2)),
(.mutatingGetSet(id: let id1, accessors: _, argument: let argument1),
.mutatingGetSet(id: let id2, accessors: _, argument: let argument2)),
(.nonmutatingGetSet(id: let id1, accessors: _, argument: let argument1),
.nonmutatingGetSet(id: let id2, accessors: _, argument: let argument2)):
if id1 != id2 {
return false
}
if let arg1 = argument1, let arg2 = argument2 {
return arg1.witnesses.equals(
arg1.data.baseAddress.unsafelyUnwrapped,
arg2.data.baseAddress.unsafelyUnwrapped,
arg1.data.count - arg1.witnessSizeAdjustment)
}
// If only one component has arguments, that should indicate that the
// only arguments in that component were generic captures and therefore
// not affecting equality.
return true
case (.struct, _),
(.class, _),
(.optionalChain, _),
(.optionalForce, _),
(.optionalWrap, _),
(.get, _),
(.mutatingGetSet, _),
(.nonmutatingGetSet, _):
return false
}
}
@_effects(releasenone)
internal func hash(into hasher: inout Hasher) {
func appendHashFromArgument(
_ argument: KeyPathComponent.ArgumentRef?
) {
if let argument = argument {
let hash = argument.witnesses.hash(
argument.data.baseAddress.unsafelyUnwrapped,
argument.data.count - argument.witnessSizeAdjustment)
// Returning 0 indicates that the arguments should not impact the
// hash value of the overall key path.
// FIXME(hasher): hash witness should just mutate hasher directly
if hash != 0 {
hasher.combine(hash)
}
}
}
switch self {
case .struct(offset: let a):
hasher.combine(0)
hasher.combine(a)
case .class(offset: let b):
hasher.combine(1)
hasher.combine(b)
case .optionalChain:
hasher.combine(2)
case .optionalForce:
hasher.combine(3)
case .optionalWrap:
hasher.combine(4)
case .get(id: let id, accessors: _, argument: let argument):
hasher.combine(5)
hasher.combine(id)
appendHashFromArgument(argument)
case .mutatingGetSet(id: let id, accessors: _, argument: let argument):
hasher.combine(6)
hasher.combine(id)
appendHashFromArgument(argument)
case .nonmutatingGetSet(id: let id, accessors: _, argument: let argument):
hasher.combine(7)
hasher.combine(id)
appendHashFromArgument(argument)
}
}
}
// A class that maintains ownership of another object while a mutable projection
// into it is underway. The lifetime of the instance of this class is also used
// to begin and end exclusive 'modify' access to the projected address.
internal final class ClassHolder<ProjectionType> {
/// The type of the scratch record passed to the runtime to record
/// accesses to guarantee exclusive access.
internal typealias AccessRecord = Builtin.UnsafeValueBuffer
internal var previous: AnyObject?
internal var instance: AnyObject
internal init(previous: AnyObject?, instance: AnyObject) {
self.previous = previous
self.instance = instance
}
internal final class func _create(
previous: AnyObject?,
instance: AnyObject,
accessingAddress address: UnsafeRawPointer,
type: ProjectionType.Type
) -> ClassHolder {
// Tail allocate the UnsafeValueBuffer used as the AccessRecord.
// This avoids a second heap allocation since there is no source-level way to
// initialize a Builtin.UnsafeValueBuffer type and thus we cannot have a
// stored property of that type.
let holder: ClassHolder = Builtin.allocWithTailElems_1(self,
1._builtinWordValue,
AccessRecord.self)
// Initialize the ClassHolder's instance variables. This is done via
// withUnsafeMutablePointer(to:) because the instance was just allocated with
// allocWithTailElems_1 and so we need to make sure to use an initialization
// rather than an assignment.
withUnsafeMutablePointer(to: &holder.previous) {
$0.initialize(to: previous)
}
withUnsafeMutablePointer(to: &holder.instance) {
$0.initialize(to: instance)
}
let accessRecordPtr = Builtin.projectTailElems(holder, AccessRecord.self)
// Begin a 'modify' access to the address. This access is ended in
// ClassHolder's deinitializer.
Builtin.beginUnpairedModifyAccess(address._rawValue, accessRecordPtr, type)
return holder
}
deinit {
let accessRecordPtr = Builtin.projectTailElems(self, AccessRecord.self)
// Ends the access begun in _create().
Builtin.endUnpairedAccess(accessRecordPtr)
}
}
// A class that triggers writeback to a pointer when destroyed.
internal final class MutatingWritebackBuffer<CurValue, NewValue> {
internal let previous: AnyObject?
internal let base: UnsafeMutablePointer<CurValue>
internal let set: ComputedAccessorsPtr.MutatingSetter<CurValue, NewValue>
internal let argument: UnsafeRawPointer
internal let argumentSize: Int
internal var value: NewValue
deinit {
set(value, &base.pointee, argument, argumentSize)
}
internal init(previous: AnyObject?,
base: UnsafeMutablePointer<CurValue>,
set: @escaping ComputedAccessorsPtr.MutatingSetter<CurValue, NewValue>,
argument: UnsafeRawPointer,
argumentSize: Int,
value: NewValue) {
self.previous = previous
self.base = base
self.set = set
self.argument = argument
self.argumentSize = argumentSize
self.value = value
}
}
// A class that triggers writeback to a non-mutated value when destroyed.
internal final class NonmutatingWritebackBuffer<CurValue, NewValue> {
internal let previous: AnyObject?
internal let base: CurValue
internal let set: ComputedAccessorsPtr.NonmutatingSetter<CurValue, NewValue>
internal let argument: UnsafeRawPointer
internal let argumentSize: Int
internal var value: NewValue
deinit {
set(value, base, argument, argumentSize)
}
internal
init(previous: AnyObject?,
base: CurValue,
set: @escaping ComputedAccessorsPtr.NonmutatingSetter<CurValue, NewValue>,
argument: UnsafeRawPointer,
argumentSize: Int,
value: NewValue) {
self.previous = previous
self.base = base
self.set = set
self.argument = argument
self.argumentSize = argumentSize
self.value = value
}
}
internal typealias KeyPathComputedArgumentLayoutFn = @convention(thin)
(_ patternArguments: UnsafeRawPointer?) -> (size: Int, alignmentMask: Int)
internal typealias KeyPathComputedArgumentInitializerFn = @convention(thin)
(_ patternArguments: UnsafeRawPointer?,
_ instanceArguments: UnsafeMutableRawPointer) -> ()
internal enum KeyPathComputedIDKind {
case pointer
case storedPropertyIndex
case vtableOffset
}
internal enum KeyPathComputedIDResolution {
case resolved
case indirectPointer
case functionCall
}
internal struct RawKeyPathComponent {
internal init(header: Header, body: UnsafeRawBufferPointer) {
self.header = header
self.body = body
}
internal var header: Header
internal var body: UnsafeRawBufferPointer
@_transparent
static var metadataAccessorPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_MetadataAccessor)
}
internal struct Header {
internal static var payloadMask: UInt32 {
return _SwiftKeyPathComponentHeader_PayloadMask
}
internal static var discriminatorMask: UInt32 {
return _SwiftKeyPathComponentHeader_DiscriminatorMask
}
internal static var discriminatorShift: UInt32 {
return _SwiftKeyPathComponentHeader_DiscriminatorShift
}
internal static var externalTag: UInt32 {
return _SwiftKeyPathComponentHeader_ExternalTag
}
internal static var structTag: UInt32 {
return _SwiftKeyPathComponentHeader_StructTag
}
internal static var computedTag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedTag
}
internal static var classTag: UInt32 {
return _SwiftKeyPathComponentHeader_ClassTag
}
internal static var optionalTag: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalTag
}
internal static var optionalChainPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalChainPayload
}
internal static var optionalWrapPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalWrapPayload
}
internal static var optionalForcePayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalForcePayload
}
internal static var endOfReferencePrefixFlag: UInt32 {
return _SwiftKeyPathComponentHeader_EndOfReferencePrefixFlag
}
internal static var storedMutableFlag: UInt32 {
return _SwiftKeyPathComponentHeader_StoredMutableFlag
}
internal static var storedOffsetPayloadMask: UInt32 {
return _SwiftKeyPathComponentHeader_StoredOffsetPayloadMask
}
internal static var outOfLineOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OutOfLineOffsetPayload
}
internal static var unresolvedFieldOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_UnresolvedFieldOffsetPayload
}
internal static var unresolvedIndirectOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_UnresolvedIndirectOffsetPayload
}
internal static var maximumOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_MaximumOffsetPayload
}
internal var isStoredMutable: Bool {
_internalInvariant(kind == .struct || kind == .class)
return _value & Header.storedMutableFlag != 0
}
internal static var computedMutatingFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedMutatingFlag
}
internal var isComputedMutating: Bool {
_internalInvariant(kind == .computed)
return _value & Header.computedMutatingFlag != 0
}
internal static var computedSettableFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedSettableFlag
}
internal var isComputedSettable: Bool {
_internalInvariant(kind == .computed)
return _value & Header.computedSettableFlag != 0
}
internal static var computedIDByStoredPropertyFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDByStoredPropertyFlag
}
internal static var computedIDByVTableOffsetFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDByVTableOffsetFlag
}
internal var computedIDKind: KeyPathComputedIDKind {
let storedProperty = _value & Header.computedIDByStoredPropertyFlag != 0
let vtableOffset = _value & Header.computedIDByVTableOffsetFlag != 0
switch (storedProperty, vtableOffset) {
case (true, true):
_internalInvariantFailure("not allowed")
case (true, false):
return .storedPropertyIndex
case (false, true):
return .vtableOffset
case (false, false):
return .pointer
}
}
internal static var computedHasArgumentsFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedHasArgumentsFlag
}
internal var hasComputedArguments: Bool {
_internalInvariant(kind == .computed)
return _value & Header.computedHasArgumentsFlag != 0
}
// If a computed component is instantiated from an external property
// descriptor, and both components carry arguments, we need to carry some
// extra matter to be able to map between the client and external generic
// contexts.
internal static var computedInstantiatedFromExternalWithArgumentsFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedInstantiatedFromExternalWithArgumentsFlag
}
internal var isComputedInstantiatedFromExternalWithArguments: Bool {
get {
_internalInvariant(kind == .computed)
return
_value & Header.computedInstantiatedFromExternalWithArgumentsFlag != 0
}
set {
_internalInvariant(kind == .computed)
_value =
_value & ~Header.computedInstantiatedFromExternalWithArgumentsFlag
| (newValue ? Header.computedInstantiatedFromExternalWithArgumentsFlag
: 0)
}
}
internal static var externalWithArgumentsExtraSize: Int {
return MemoryLayout<Int>.size
}
internal static var computedIDResolutionMask: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDResolutionMask
}
internal static var computedIDResolved: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDResolved
}
internal static var computedIDUnresolvedIndirectPointer: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedIndirectPointer
}
internal static var computedIDUnresolvedFunctionCall: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedFunctionCall
}
internal var computedIDResolution: KeyPathComputedIDResolution {
switch payload & Header.computedIDResolutionMask {
case Header.computedIDResolved:
return .resolved
case Header.computedIDUnresolvedIndirectPointer:
return .indirectPointer
case Header.computedIDUnresolvedFunctionCall:
return .functionCall
default:
_internalInvariantFailure("invalid key path resolution")
}
}
internal var _value: UInt32
internal var discriminator: UInt32 {
get {
return (_value & Header.discriminatorMask) >> Header.discriminatorShift
}
set {
let shifted = newValue << Header.discriminatorShift
_internalInvariant(shifted & Header.discriminatorMask == shifted,
"discriminator doesn't fit")
_value = _value & ~Header.discriminatorMask | shifted
}
}
internal var payload: UInt32 {
get {
return _value & Header.payloadMask
}
set {
_internalInvariant(newValue & Header.payloadMask == newValue,
"payload too big")
_value = _value & ~Header.payloadMask | newValue
}
}
internal var storedOffsetPayload: UInt32 {
get {
_internalInvariant(kind == .struct || kind == .class,
"not a stored component")
return _value & Header.storedOffsetPayloadMask
}
set {
_internalInvariant(kind == .struct || kind == .class,
"not a stored component")
_internalInvariant(newValue & Header.storedOffsetPayloadMask == newValue,
"payload too big")
_value = _value & ~Header.storedOffsetPayloadMask | newValue
}
}
internal var endOfReferencePrefix: Bool {
get {
return _value & Header.endOfReferencePrefixFlag != 0
}
set {
if newValue {
_value |= Header.endOfReferencePrefixFlag
} else {
_value &= ~Header.endOfReferencePrefixFlag
}
}
}
internal var kind: KeyPathComponentKind {
switch (discriminator, payload) {
case (Header.externalTag, _):
return .external
case (Header.structTag, _):
return .struct
case (Header.classTag, _):
return .class
case (Header.computedTag, _):
return .computed
case (Header.optionalTag, Header.optionalChainPayload):
return .optionalChain
case (Header.optionalTag, Header.optionalWrapPayload):
return .optionalWrap
case (Header.optionalTag, Header.optionalForcePayload):
return .optionalForce
default:
_internalInvariantFailure("invalid header")
}
}
// The component header is 4 bytes, but may be followed by an aligned
// pointer field for some kinds of component, forcing padding.
internal static var pointerAlignmentSkew: Int {
return MemoryLayout<Int>.size - MemoryLayout<Int32>.size
}
internal var isTrivialPropertyDescriptor: Bool {
return _value ==
_SwiftKeyPathComponentHeader_TrivialPropertyDescriptorMarker
}
/// If this is the header for a component in a key path pattern, return
/// the size of the body of the component.
internal var patternComponentBodySize: Int {
return _componentBodySize(forPropertyDescriptor: false)
}
/// If this is the header for a property descriptor, return
/// the size of the body of the component.
internal var propertyDescriptorBodySize: Int {
if isTrivialPropertyDescriptor { return 0 }
return _componentBodySize(forPropertyDescriptor: true)
}
internal func _componentBodySize(forPropertyDescriptor: Bool) -> Int {
switch kind {
case .struct, .class:
if storedOffsetPayload == Header.unresolvedFieldOffsetPayload
|| storedOffsetPayload == Header.outOfLineOffsetPayload
|| storedOffsetPayload == Header.unresolvedIndirectOffsetPayload {
// A 32-bit offset is stored in the body.
return MemoryLayout<UInt32>.size
}
// Otherwise, there's no body.
return 0
case .external:
// The body holds a pointer to the external property descriptor,
// and some number of substitution arguments, the count of which is
// in the payload.
return 4 * (1 + Int(payload))
case .computed:
// The body holds at minimum the id and getter.
var size = 8
// If settable, it also holds the setter.
if isComputedSettable {
size += 4
}
// If there are arguments, there's also a layout function,
// witness table, and initializer function.
// Property descriptors never carry argument information, though.
if !forPropertyDescriptor && hasComputedArguments {
size += 12
}
return size
case .optionalForce, .optionalChain, .optionalWrap:
// Otherwise, there's no body.
return 0
}
}
init(discriminator: UInt32, payload: UInt32) {
_value = 0
self.discriminator = discriminator
self.payload = payload
}
init(optionalForce: ()) {
self.init(discriminator: Header.optionalTag,
payload: Header.optionalForcePayload)
}
init(optionalWrap: ()) {
self.init(discriminator: Header.optionalTag,
payload: Header.optionalWrapPayload)
}
init(optionalChain: ()) {
self.init(discriminator: Header.optionalTag,
payload: Header.optionalChainPayload)
}
init(stored kind: KeyPathStructOrClass,
mutable: Bool,
inlineOffset: UInt32) {
let discriminator: UInt32
switch kind {
case .struct: discriminator = Header.structTag
case .class: discriminator = Header.classTag
}
_internalInvariant(inlineOffset <= Header.maximumOffsetPayload)
let payload = inlineOffset
| (mutable ? Header.storedMutableFlag : 0)
self.init(discriminator: discriminator,
payload: payload)
}
init(storedWithOutOfLineOffset kind: KeyPathStructOrClass,
mutable: Bool) {
let discriminator: UInt32
switch kind {
case .struct: discriminator = Header.structTag
case .class: discriminator = Header.classTag
}
let payload = Header.outOfLineOffsetPayload
| (mutable ? Header.storedMutableFlag : 0)
self.init(discriminator: discriminator,
payload: payload)
}
init(computedWithIDKind kind: KeyPathComputedIDKind,
mutating: Bool,
settable: Bool,
hasArguments: Bool,
instantiatedFromExternalWithArguments: Bool) {
let discriminator = Header.computedTag
var payload =
(mutating ? Header.computedMutatingFlag : 0)
| (settable ? Header.computedSettableFlag : 0)
| (hasArguments ? Header.computedHasArgumentsFlag : 0)
| (instantiatedFromExternalWithArguments
? Header.computedInstantiatedFromExternalWithArgumentsFlag : 0)
switch kind {
case .pointer:
break
case .storedPropertyIndex:
payload |= Header.computedIDByStoredPropertyFlag
case .vtableOffset:
payload |= Header.computedIDByVTableOffsetFlag
}
self.init(discriminator: discriminator,
payload: payload)
}
}
internal var bodySize: Int {
let ptrSize = MemoryLayout<Int>.size
switch header.kind {
case .struct, .class:
if header.storedOffsetPayload == Header.outOfLineOffsetPayload {
return 4 // overflowed
}
return 0
case .external:
_internalInvariantFailure("should be instantiated away")
case .optionalChain, .optionalForce, .optionalWrap:
return 0
case .computed:
// align to pointer, minimum two pointers for id and get
var total = Header.pointerAlignmentSkew + ptrSize * 2
// additional word for a setter
if header.isComputedSettable {
total += ptrSize
}
// include the argument size
if header.hasComputedArguments {
// two words for argument header: size, witnesses
total += ptrSize * 2
// size of argument area
total += _computedArgumentSize
if header.isComputedInstantiatedFromExternalWithArguments {
total += Header.externalWithArgumentsExtraSize
}
}
return total
}
}
internal var _structOrClassOffset: Int {
_internalInvariant(header.kind == .struct || header.kind == .class,
"no offset for this kind")
// An offset too large to fit inline is represented by a signal and stored
// in the body.
if header.storedOffsetPayload == Header.outOfLineOffsetPayload {
// Offset overflowed into body
_internalInvariant(body.count >= MemoryLayout<UInt32>.size,
"component not big enough")
return Int(body.load(as: UInt32.self))
}
return Int(header.storedOffsetPayload)
}
internal var _computedIDValue: Int {
_internalInvariant(header.kind == .computed,
"not a computed property")
return body.load(fromByteOffset: Header.pointerAlignmentSkew,
as: Int.self)
}
internal var _computedID: ComputedPropertyID {
_internalInvariant(header.kind == .computed,
"not a computed property")
return ComputedPropertyID(
value: _computedIDValue,
kind: header.computedIDKind)
}
internal var _computedAccessors: ComputedAccessorsPtr {
_internalInvariant(header.kind == .computed,
"not a computed property")
return ComputedAccessorsPtr(
header: header,
value: body.baseAddress.unsafelyUnwrapped +
Header.pointerAlignmentSkew + MemoryLayout<Int>.size)
}
internal var _computedArgumentHeaderPointer: UnsafeRawPointer {
_internalInvariant(header.hasComputedArguments, "no arguments")
return body.baseAddress.unsafelyUnwrapped
+ Header.pointerAlignmentSkew
+ MemoryLayout<Int>.size *
(header.isComputedSettable ? 3 : 2)
}
internal var _computedArgumentSize: Int {
return _computedArgumentHeaderPointer.load(as: Int.self)
}
internal
var _computedArgumentWitnesses: ComputedArgumentWitnessesPtr {
return _computedArgumentHeaderPointer.load(
fromByteOffset: MemoryLayout<Int>.size,
as: ComputedArgumentWitnessesPtr.self)
}
internal var _computedArguments: UnsafeRawPointer {
var base = _computedArgumentHeaderPointer + MemoryLayout<Int>.size * 2
// If the component was instantiated from an external property descriptor
// with its own arguments, we include some additional capture info to
// be able to map to the original argument context by adjusting the size
// passed to the witness operations.
if header.isComputedInstantiatedFromExternalWithArguments {
base += Header.externalWithArgumentsExtraSize
}
return base
}
internal var _computedMutableArguments: UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(mutating: _computedArguments)
}
internal var _computedArgumentWitnessSizeAdjustment: Int {
if header.isComputedInstantiatedFromExternalWithArguments {
return _computedArguments.load(
fromByteOffset: -Header.externalWithArgumentsExtraSize,
as: Int.self)
}
return 0
}
internal var value: KeyPathComponent {
switch header.kind {
case .struct:
return .struct(offset: _structOrClassOffset)
case .class:
return .class(offset: _structOrClassOffset)
case .optionalChain:
return .optionalChain
case .optionalForce:
return .optionalForce
case .optionalWrap:
return .optionalWrap
case .computed:
let isSettable = header.isComputedSettable
let isMutating = header.isComputedMutating
let id = _computedID
let accessors = _computedAccessors
// Argument value is unused if there are no arguments.
let argument: KeyPathComponent.ArgumentRef?
if header.hasComputedArguments {
argument = KeyPathComponent.ArgumentRef(
data: UnsafeRawBufferPointer(start: _computedArguments,
count: _computedArgumentSize),
witnesses: _computedArgumentWitnesses,
witnessSizeAdjustment: _computedArgumentWitnessSizeAdjustment)
} else {
argument = nil
}
switch (isSettable, isMutating) {
case (false, false):
return .get(id: id, accessors: accessors, argument: argument)
case (true, false):
return .nonmutatingGetSet(id: id,
accessors: accessors,
argument: argument)
case (true, true):
return .mutatingGetSet(id: id,
accessors: accessors,
argument: argument)
case (false, true):
_internalInvariantFailure("impossible")
}
case .external:
_internalInvariantFailure("should have been instantiated away")
}
}
internal func destroy() {
switch header.kind {
case .struct,
.class,
.optionalChain,
.optionalForce,
.optionalWrap:
// trivial
break
case .computed:
// Run destructor, if any
if header.hasComputedArguments,
let destructor = _computedArgumentWitnesses.destroy {
destructor(_computedMutableArguments,
_computedArgumentSize - _computedArgumentWitnessSizeAdjustment)
}
case .external:
_internalInvariantFailure("should have been instantiated away")
}
}
internal func clone(into buffer: inout UnsafeMutableRawBufferPointer,
endOfReferencePrefix: Bool) {
var newHeader = header
newHeader.endOfReferencePrefix = endOfReferencePrefix
var componentSize = MemoryLayout<Header>.size
buffer.storeBytes(of: newHeader, as: Header.self)
switch header.kind {
case .struct,
.class:
if header.storedOffsetPayload == Header.outOfLineOffsetPayload {
let overflowOffset = body.load(as: UInt32.self)
buffer.storeBytes(of: overflowOffset, toByteOffset: 4,
as: UInt32.self)
componentSize += 4
}
case .optionalChain,
.optionalForce,
.optionalWrap:
break
case .computed:
// Fields are pointer-aligned after the header
componentSize += Header.pointerAlignmentSkew
buffer.storeBytes(of: _computedIDValue,
toByteOffset: componentSize,
as: Int.self)
componentSize += MemoryLayout<Int>.size
let accessors = _computedAccessors
(buffer.baseAddress.unsafelyUnwrapped + MemoryLayout<Int>.size * 2)
._copyAddressDiscriminatedFunctionPointer(
from: accessors.getterPtr,
discriminator: ComputedAccessorsPtr.getterPtrAuthKey)
componentSize += MemoryLayout<Int>.size
if header.isComputedSettable {
(buffer.baseAddress.unsafelyUnwrapped + MemoryLayout<Int>.size * 3)
._copyAddressDiscriminatedFunctionPointer(
from: accessors.setterPtr,
discriminator: header.isComputedMutating
? ComputedAccessorsPtr.mutatingSetterPtrAuthKey
: ComputedAccessorsPtr.nonmutatingSetterPtrAuthKey)
componentSize += MemoryLayout<Int>.size
}
if header.hasComputedArguments {
let arguments = _computedArguments
let argumentSize = _computedArgumentSize
buffer.storeBytes(of: argumentSize,
toByteOffset: componentSize,
as: Int.self)
componentSize += MemoryLayout<Int>.size
buffer.storeBytes(of: _computedArgumentWitnesses,
toByteOffset: componentSize,
as: ComputedArgumentWitnessesPtr.self)
componentSize += MemoryLayout<Int>.size
if header.isComputedInstantiatedFromExternalWithArguments {
// Include the extra matter for components instantiated from
// external property descriptors with arguments.
buffer.storeBytes(of: _computedArgumentWitnessSizeAdjustment,
toByteOffset: componentSize,
as: Int.self)
componentSize += MemoryLayout<Int>.size
}
let adjustedSize = argumentSize - _computedArgumentWitnessSizeAdjustment
let argumentDest =
buffer.baseAddress.unsafelyUnwrapped + componentSize
_computedArgumentWitnesses.copy(
arguments,
argumentDest,
adjustedSize)
if header.isComputedInstantiatedFromExternalWithArguments {
// The extra information for external property descriptor arguments
// can always be memcpy'd.
_memcpy(dest: argumentDest + adjustedSize,
src: arguments + adjustedSize,
size: UInt(_computedArgumentWitnessSizeAdjustment))
}
componentSize += argumentSize
}
case .external:
_internalInvariantFailure("should have been instantiated away")
}
buffer = UnsafeMutableRawBufferPointer(
start: buffer.baseAddress.unsafelyUnwrapped + componentSize,
count: buffer.count - componentSize)
}
internal enum ProjectionResult<NewValue, LeafValue> {
/// Continue projecting the key path with the given new value.
case `continue`(NewValue)
/// Stop projecting the key path and use the given value as the final
/// result of the projection.
case `break`(LeafValue)
internal var assumingContinue: NewValue {
switch self {
case .continue(let x):
return x
case .break:
_internalInvariantFailure("should not have stopped key path projection")
}
}
}
internal func _projectReadOnly<CurValue, NewValue, LeafValue>(
_ base: CurValue,
to: NewValue.Type,
endingWith: LeafValue.Type
) -> ProjectionResult<NewValue, LeafValue> {
switch value {
case .struct(let offset):
var base2 = base
return .continue(withUnsafeBytes(of: &base2) {
let p = $0.baseAddress.unsafelyUnwrapped.advanced(by: offset)
// The contents of the struct should be well-typed, so we can assume
// typed memory here.
return p.assumingMemoryBound(to: NewValue.self).pointee
})
case .class(let offset):
_internalInvariant(CurValue.self is AnyObject.Type,
"base is not a class")
let baseObj = unsafeBitCast(base, to: AnyObject.self)
let basePtr = UnsafeRawPointer(Builtin.bridgeToRawPointer(baseObj))
defer { _fixLifetime(baseObj) }
let offsetAddress = basePtr.advanced(by: offset)
// Perform an instantaneous record access on the address in order to
// ensure that the read will not conflict with an already in-progress
// 'modify' access.
Builtin.performInstantaneousReadAccess(offsetAddress._rawValue,
NewValue.self)
return .continue(offsetAddress
.assumingMemoryBound(to: NewValue.self)
.pointee)
case .get(id: _, accessors: let accessors, argument: let argument),
.mutatingGetSet(id: _, accessors: let accessors, argument: let argument),
.nonmutatingGetSet(id: _, accessors: let accessors, argument: let argument):
return .continue(accessors.getter()(base,
argument?.data.baseAddress ?? accessors._value,
argument?.data.count ?? 0))
case .optionalChain:
_internalInvariant(CurValue.self == Optional<NewValue>.self,
"should be unwrapping optional value")
_internalInvariant(_isOptional(LeafValue.self),
"leaf result should be optional")
if let baseValue = unsafeBitCast(base, to: Optional<NewValue>.self) {
return .continue(baseValue)
} else {
// TODO: A more efficient way of getting the `none` representation
// of a dynamically-optional type...
return .break((Optional<()>.none as Any) as! LeafValue)
}
case .optionalForce:
_internalInvariant(CurValue.self == Optional<NewValue>.self,
"should be unwrapping optional value")
return .continue(unsafeBitCast(base, to: Optional<NewValue>.self)!)
case .optionalWrap:
_internalInvariant(NewValue.self == Optional<CurValue>.self,
"should be wrapping optional value")
return .continue(
unsafeBitCast(base as Optional<CurValue>, to: NewValue.self))
}
}
internal func _projectMutableAddress<CurValue, NewValue>(
_ base: UnsafeRawPointer,
from _: CurValue.Type,
to _: NewValue.Type,
isRoot: Bool,
keepAlive: inout AnyObject?
) -> UnsafeRawPointer {
switch value {
case .struct(let offset):
return base.advanced(by: offset)
case .class(let offset):
// A class dereference should only occur at the root of a mutation,
// since otherwise it would be part of the reference prefix.
_internalInvariant(isRoot,
"class component should not appear in the middle of mutation")
// AnyObject memory can alias any class reference memory, so we can
// assume type here
let object = base.assumingMemoryBound(to: AnyObject.self).pointee
let offsetAddress = UnsafeRawPointer(Builtin.bridgeToRawPointer(object))
.advanced(by: offset)
// Keep the base alive for the duration of the derived access and also
// enforce exclusive access to the address.
keepAlive = ClassHolder._create(previous: keepAlive, instance: object,
accessingAddress: offsetAddress,
type: NewValue.self)
return offsetAddress
case .mutatingGetSet(id: _, accessors: let accessors,
argument: let argument):
let baseTyped = UnsafeMutablePointer(
mutating: base.assumingMemoryBound(to: CurValue.self))
let argValue = argument?.data.baseAddress ?? accessors._value
let argSize = argument?.data.count ?? 0
let writeback = MutatingWritebackBuffer<CurValue, NewValue>(
previous: keepAlive,
base: baseTyped,
set: accessors.mutatingSetter(),
argument: argValue,
argumentSize: argSize,
value: accessors.getter()(baseTyped.pointee, argValue, argSize))
keepAlive = writeback
// A maximally-abstracted, final, stored class property should have
// a stable address.
return UnsafeRawPointer(Builtin.addressof(&writeback.value))
case .nonmutatingGetSet(id: _, accessors: let accessors,
argument: let argument):
// A nonmutating property should only occur at the root of a mutation,
// since otherwise it would be part of the reference prefix.
_internalInvariant(isRoot,
"nonmutating component should not appear in the middle of mutation")
let baseValue = base.assumingMemoryBound(to: CurValue.self).pointee
let argValue = argument?.data.baseAddress ?? accessors._value
let argSize = argument?.data.count ?? 0
let writeback = NonmutatingWritebackBuffer<CurValue, NewValue>(
previous: keepAlive,
base: baseValue,
set: accessors.nonmutatingSetter(),
argument: argValue,
argumentSize: argSize,
value: accessors.getter()(baseValue, argValue, argSize))
keepAlive = writeback
// A maximally-abstracted, final, stored class property should have
// a stable address.
return UnsafeRawPointer(Builtin.addressof(&writeback.value))
case .optionalForce:
_internalInvariant(CurValue.self == Optional<NewValue>.self,
"should be unwrapping an optional value")
// Optional's layout happens to always put the payload at the start
// address of the Optional value itself, if a value is present at all.
let baseOptionalPointer
= base.assumingMemoryBound(to: Optional<NewValue>.self)
// Assert that a value exists
_ = baseOptionalPointer.pointee!
return base
case .optionalChain, .optionalWrap, .get:
_internalInvariantFailure("not a mutable key path component")
}
}
}
internal func _pop<T>(from: inout UnsafeRawBufferPointer,
as type: T.Type) -> T {
let buffer = _pop(from: &from, as: type, count: 1)
return buffer.baseAddress.unsafelyUnwrapped.pointee
}
internal func _pop<T>(from: inout UnsafeRawBufferPointer,
as: T.Type,
count: Int) -> UnsafeBufferPointer<T> {
_internalInvariant(_isPOD(T.self), "should be POD")
from = MemoryLayout<T>._roundingUpBaseToAlignment(from)
let byteCount = MemoryLayout<T>.stride * count
let result = UnsafeBufferPointer(
start: from.baseAddress.unsafelyUnwrapped.assumingMemoryBound(to: T.self),
count: count)
from = UnsafeRawBufferPointer(
start: from.baseAddress.unsafelyUnwrapped + byteCount,
count: from.count - byteCount)
return result
}
internal struct KeyPathBuffer {
internal var data: UnsafeRawBufferPointer
internal var trivial: Bool
internal var hasReferencePrefix: Bool
internal var mutableData: UnsafeMutableRawBufferPointer {
return UnsafeMutableRawBufferPointer(mutating: data)
}
internal struct Builder {
internal var buffer: UnsafeMutableRawBufferPointer
internal init(_ buffer: UnsafeMutableRawBufferPointer) {
self.buffer = buffer
}
internal mutating func pushRaw(size: Int, alignment: Int)
-> UnsafeMutableRawBufferPointer {
var baseAddress = buffer.baseAddress.unsafelyUnwrapped
var misalign = Int(bitPattern: baseAddress) % alignment
if misalign != 0 {
misalign = alignment - misalign
baseAddress = baseAddress.advanced(by: misalign)
}
let result = UnsafeMutableRawBufferPointer(
start: baseAddress,
count: size)
buffer = UnsafeMutableRawBufferPointer(
start: baseAddress + size,
count: buffer.count - size - misalign)
return result
}
internal mutating func push<T>(_ value: T) {
let buf = pushRaw(size: MemoryLayout<T>.size,
alignment: MemoryLayout<T>.alignment)
buf.storeBytes(of: value, as: T.self)
}
internal mutating func pushHeader(_ header: Header) {
push(header)
// Start the components at pointer alignment
_ = pushRaw(size: RawKeyPathComponent.Header.pointerAlignmentSkew,
alignment: 4)
}
}
internal struct Header {
internal var _value: UInt32
internal static var sizeMask: UInt32 {
return _SwiftKeyPathBufferHeader_SizeMask
}
internal static var reservedMask: UInt32 {
return _SwiftKeyPathBufferHeader_ReservedMask
}
internal static var trivialFlag: UInt32 {
return _SwiftKeyPathBufferHeader_TrivialFlag
}
internal static var hasReferencePrefixFlag: UInt32 {
return _SwiftKeyPathBufferHeader_HasReferencePrefixFlag
}
internal init(size: Int, trivial: Bool, hasReferencePrefix: Bool) {
_internalInvariant(size <= Int(Header.sizeMask), "key path too big")
_value = UInt32(size)
| (trivial ? Header.trivialFlag : 0)
| (hasReferencePrefix ? Header.hasReferencePrefixFlag : 0)
}
internal var size: Int { return Int(_value & Header.sizeMask) }
internal var trivial: Bool { return _value & Header.trivialFlag != 0 }
internal var hasReferencePrefix: Bool {
get {
return _value & Header.hasReferencePrefixFlag != 0
}
set {
if newValue {
_value |= Header.hasReferencePrefixFlag
} else {
_value &= ~Header.hasReferencePrefixFlag
}
}
}
// In a key path pattern, the "trivial" flag is used to indicate
// "instantiable in-line"
internal var instantiableInLine: Bool {
return trivial
}
internal func validateReservedBits() {
_precondition(_value & Header.reservedMask == 0,
"Reserved bits set to an unexpected bit pattern")
}
}
internal init(base: UnsafeRawPointer) {
let header = base.load(as: Header.self)
data = UnsafeRawBufferPointer(
start: base + MemoryLayout<Int>.size,
count: header.size)
trivial = header.trivial
hasReferencePrefix = header.hasReferencePrefix
}
internal init(partialData: UnsafeRawBufferPointer,
trivial: Bool = false,
hasReferencePrefix: Bool = false) {
self.data = partialData
self.trivial = trivial
self.hasReferencePrefix = hasReferencePrefix
}
internal func destroy() {
// Short-circuit if nothing in the object requires destruction.
if trivial { return }
var bufferToDestroy = self
while true {
let (component, type) = bufferToDestroy.next()
component.destroy()
guard let _ = type else { break }
}
}
internal mutating func next() -> (RawKeyPathComponent, Any.Type?) {
let header = _pop(from: &data, as: RawKeyPathComponent.Header.self)
// Track if this is the last component of the reference prefix.
if header.endOfReferencePrefix {
_internalInvariant(self.hasReferencePrefix,
"beginMutation marker in non-reference-writable key path?")
self.hasReferencePrefix = false
}
var component = RawKeyPathComponent(header: header, body: data)
// Shrinkwrap the component buffer size.
let size = component.bodySize
component.body = UnsafeRawBufferPointer(start: component.body.baseAddress,
count: size)
_ = _pop(from: &data, as: Int8.self, count: size)
// fetch type, which is in the buffer unless it's the final component
let nextType: Any.Type?
if data.isEmpty {
nextType = nil
} else {
nextType = _pop(from: &data, as: Any.Type.self)
}
return (component, nextType)
}
}
// MARK: Library intrinsics for projecting key paths.
@_silgen_name("swift_getAtPartialKeyPath")
public // COMPILER_INTRINSIC
func _getAtPartialKeyPath<Root>(
root: Root,
keyPath: PartialKeyPath<Root>
) -> Any {
func open<Value>(_: Value.Type) -> Any {
return _getAtKeyPath(root: root,
keyPath: unsafeDowncast(keyPath, to: KeyPath<Root, Value>.self))
}
return _openExistential(type(of: keyPath).valueType, do: open)
}
@_silgen_name("swift_getAtAnyKeyPath")
public // COMPILER_INTRINSIC
func _getAtAnyKeyPath<RootValue>(
root: RootValue,
keyPath: AnyKeyPath
) -> Any? {
let (keyPathRoot, keyPathValue) = type(of: keyPath)._rootAndValueType
func openRoot<KeyPathRoot>(_: KeyPathRoot.Type) -> Any? {
guard let rootForKeyPath = root as? KeyPathRoot else {
return nil
}
func openValue<Value>(_: Value.Type) -> Any {
return _getAtKeyPath(root: rootForKeyPath,
keyPath: unsafeDowncast(keyPath, to: KeyPath<KeyPathRoot, Value>.self))
}
return _openExistential(keyPathValue, do: openValue)
}
return _openExistential(keyPathRoot, do: openRoot)
}
@_silgen_name("swift_getAtKeyPath")
public // COMPILER_INTRINSIC
func _getAtKeyPath<Root, Value>(
root: Root,
keyPath: KeyPath<Root, Value>
) -> Value {
return keyPath._projectReadOnly(from: root)
}
// The release that ends the access scope is guaranteed to happen
// immediately at the end_apply call because the continuation is a
// runtime call with a manual release (access scopes cannot be extended).
@_silgen_name("_swift_modifyAtWritableKeyPath_impl")
public // runtime entrypoint
func _modifyAtWritableKeyPath_impl<Root, Value>(
root: inout Root,
keyPath: WritableKeyPath<Root, Value>
) -> (UnsafeMutablePointer<Value>, AnyObject?) {
if type(of: keyPath).kind == .reference {
return _modifyAtReferenceWritableKeyPath_impl(root: root,
keyPath: _unsafeUncheckedDowncast(keyPath,
to: ReferenceWritableKeyPath<Root, Value>.self))
}
return keyPath._projectMutableAddress(from: &root)
}
// The release that ends the access scope is guaranteed to happen
// immediately at the end_apply call because the continuation is a
// runtime call with a manual release (access scopes cannot be extended).
@_silgen_name("_swift_modifyAtReferenceWritableKeyPath_impl")
public // runtime entrypoint
func _modifyAtReferenceWritableKeyPath_impl<Root, Value>(
root: Root,
keyPath: ReferenceWritableKeyPath<Root, Value>
) -> (UnsafeMutablePointer<Value>, AnyObject?) {
return keyPath._projectMutableAddress(from: root)
}
@_silgen_name("swift_setAtWritableKeyPath")
public // COMPILER_INTRINSIC
func _setAtWritableKeyPath<Root, Value>(
root: inout Root,
keyPath: WritableKeyPath<Root, Value>,
value: __owned Value
) {
if type(of: keyPath).kind == .reference {
return _setAtReferenceWritableKeyPath(root: root,
keyPath: _unsafeUncheckedDowncast(keyPath,
to: ReferenceWritableKeyPath<Root, Value>.self),
value: value)
}
// TODO: we should be able to do this more efficiently than projecting.
let (addr, owner) = keyPath._projectMutableAddress(from: &root)
addr.pointee = value
_fixLifetime(owner)
// FIXME: this needs a deallocation barrier to ensure that the
// release isn't extended, along with the access scope.
}
@_silgen_name("swift_setAtReferenceWritableKeyPath")
public // COMPILER_INTRINSIC
func _setAtReferenceWritableKeyPath<Root, Value>(
root: Root,
keyPath: ReferenceWritableKeyPath<Root, Value>,
value: __owned Value
) {
// TODO: we should be able to do this more efficiently than projecting.
let (addr, owner) = keyPath._projectMutableAddress(from: root)
addr.pointee = value
_fixLifetime(owner)
// FIXME: this needs a deallocation barrier to ensure that the
// release isn't extended, along with the access scope.
}
// MARK: Appending type system
// FIXME(ABI): The type relationships between KeyPath append operands are tricky
// and don't interact well with our overriding rules. Hack things by injecting
// a bunch of `appending` overloads as protocol extensions so they aren't
// constrained by being overrides, and so that we can use exact-type constraints
// on `Self` to prevent dynamically-typed methods from being inherited by
// statically-typed key paths.
/// An implementation detail of key path expressions; do not use this protocol
/// directly.
@_show_in_interface
public protocol _AppendKeyPath {}
extension _AppendKeyPath where Self == AnyKeyPath {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type. This example
/// creates key paths from `Array<Int>` to `String` and from `String` to
/// `Int`, and then tries appending each to the other:
///
/// let arrayDescription: AnyKeyPath = \Array<Int>.description
/// let stringLength: AnyKeyPath = \String.count
///
/// // Creates a key path from `Array<Int>` to `Int`
/// let arrayDescriptionLength = arrayDescription.appending(path: stringLength)
///
/// let invalidKeyPath = stringLength.appending(path: arrayDescription)
/// // invalidKeyPath == nil
///
/// The second call to `appending(path:)` returns `nil`
/// because the root type of `arrayDescription`, `Array<Int>`, does not
/// match the value type of `stringLength`, `Int`.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path and the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
@inlinable
public func appending(path: AnyKeyPath) -> AnyKeyPath? {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == PartialKeyPath<T> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type. This example
/// creates key paths from `Array<Int>` to `String` and from `String` to
/// `Int`, and then tries appending each to the other:
///
/// let arrayDescription: PartialKeyPath<Array<Int>> = \.description
/// let stringLength: PartialKeyPath<String> = \.count
///
/// // Creates a key path from `Array<Int>` to `Int`
/// let arrayDescriptionLength = arrayDescription.appending(path: stringLength)
///
/// let invalidKeyPath = stringLength.appending(path: arrayDescription)
/// // invalidKeyPath == nil
///
/// The second call to `appending(path:)` returns `nil`
/// because the root type of `arrayDescription`, `Array<Int>`, does not
/// match the value type of `stringLength`, `Int`.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path and the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
@inlinable
public func appending<Root>(path: AnyKeyPath) -> PartialKeyPath<Root>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type. This example
/// creates a key path from `Array<Int>` to `String`, and then tries
/// appending compatible and incompatible key paths:
///
/// let arrayDescription: PartialKeyPath<Array<Int>> = \.description
///
/// // Creates a key path from `Array<Int>` to `Int`
/// let arrayDescriptionLength = arrayDescription.appending(path: \String.count)
///
/// let invalidKeyPath = arrayDescription.appending(path: \Double.isZero)
/// // invalidKeyPath == nil
///
/// The second call to `appending(path:)` returns `nil` because the root type
/// of the `path` parameter, `Double`, does not match the value type of
/// `arrayDescription`, `String`.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
@inlinable
public func appending<Root, AppendedRoot, AppendedValue>(
path: KeyPath<AppendedRoot, AppendedValue>
) -> KeyPath<Root, AppendedValue>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type.
///
/// - Parameter path: The reference writeable key path to append.
/// - Returns: A key path from the root of this key path to the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
@inlinable
public func appending<Root, AppendedRoot, AppendedValue>(
path: ReferenceWritableKeyPath<AppendedRoot, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == KeyPath<T,U> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation. In the following
/// example, `keyPath1` and `keyPath2` are equivalent:
///
/// let arrayDescription = \Array<Int>.description
/// let keyPath1 = arrayDescription.appending(path: \String.count)
///
/// let keyPath2 = \Array<Int>.description.count
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: KeyPath<Value, AppendedValue>
) -> KeyPath<Root, AppendedValue>
where Self: KeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
/* TODO
public func appending<Root, Value, Leaf>(
path: Leaf,
// FIXME: Satisfy "Value generic param not used in signature" constraint
_: Value.Type = Value.self
) -> PartialKeyPath<Root>?
where Self: KeyPath<Root, Value>, Leaf == AnyKeyPath {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
*/
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: ReferenceWritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == KeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == WritableKeyPath<T,U> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: WritableKeyPath<Value, AppendedValue>
) -> WritableKeyPath<Root, AppendedValue>
where Self == WritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: ReferenceWritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == WritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == ReferenceWritableKeyPath<T,U> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: WritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == ReferenceWritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
@usableFromInline
internal func _tryToAppendKeyPaths<Result: AnyKeyPath>(
root: AnyKeyPath,
leaf: AnyKeyPath
) -> Result? {
let (rootRoot, rootValue) = type(of: root)._rootAndValueType
let (leafRoot, leafValue) = type(of: leaf)._rootAndValueType
if rootValue != leafRoot {
return nil
}
func open<Root>(_: Root.Type) -> Result {
func open2<Value>(_: Value.Type) -> Result {
func open3<AppendedValue>(_: AppendedValue.Type) -> Result {
let typedRoot = unsafeDowncast(root, to: KeyPath<Root, Value>.self)
let typedLeaf = unsafeDowncast(leaf,
to: KeyPath<Value, AppendedValue>.self)
let result = _appendingKeyPaths(root: typedRoot, leaf: typedLeaf)
return unsafeDowncast(result, to: Result.self)
}
return _openExistential(leafValue, do: open3)
}
return _openExistential(rootValue, do: open2)
}
return _openExistential(rootRoot, do: open)
}
@usableFromInline
internal func _appendingKeyPaths<
Root, Value, AppendedValue,
Result: KeyPath<Root, AppendedValue>
>(
root: KeyPath<Root, Value>,
leaf: KeyPath<Value, AppendedValue>
) -> Result {
let resultTy = type(of: root).appendedType(with: type(of: leaf))
return root.withBuffer {
var rootBuffer = $0
return leaf.withBuffer {
var leafBuffer = $0
// If either operand is the identity key path, then we should return
// the other operand back untouched.
if leafBuffer.data.isEmpty {
return unsafeDowncast(root, to: Result.self)
}
if rootBuffer.data.isEmpty {
return unsafeDowncast(leaf, to: Result.self)
}
// Reserve room for the appended KVC string, if both key paths are
// KVC-compatible.
let appendedKVCLength: Int, rootKVCLength: Int, leafKVCLength: Int
if let rootPtr = root._kvcKeyPathStringPtr,
let leafPtr = leaf._kvcKeyPathStringPtr {
rootKVCLength = Int(_swift_stdlib_strlen(rootPtr))
leafKVCLength = Int(_swift_stdlib_strlen(leafPtr))
// root + "." + leaf
appendedKVCLength = rootKVCLength + 1 + leafKVCLength + 1
} else {
rootKVCLength = 0
leafKVCLength = 0
appendedKVCLength = 0
}
// Result buffer has room for both key paths' components, plus the
// header, plus space for the middle type.
// Align up the root so that we can put the component type after it.
let rootSize = MemoryLayout<Int>._roundingUpToAlignment(rootBuffer.data.count)
let resultSize = rootSize + leafBuffer.data.count
+ 2 * MemoryLayout<Int>.size
// Tail-allocate space for the KVC string.
let totalResultSize = MemoryLayout<Int32>
._roundingUpToAlignment(resultSize + appendedKVCLength)
var kvcStringBuffer: UnsafeMutableRawPointer? = nil
let result = resultTy._create(capacityInBytes: totalResultSize) {
var destBuffer = $0
// Remember where the tail-allocated KVC string buffer begins.
if appendedKVCLength > 0 {
kvcStringBuffer = destBuffer.baseAddress.unsafelyUnwrapped
.advanced(by: resultSize)
destBuffer = .init(start: destBuffer.baseAddress,
count: resultSize)
}
var destBuilder = KeyPathBuffer.Builder(destBuffer)
// Save space for the header.
let leafIsReferenceWritable = type(of: leaf).kind == .reference
destBuilder.pushHeader(KeyPathBuffer.Header(
size: resultSize - MemoryLayout<Int>.size,
trivial: rootBuffer.trivial && leafBuffer.trivial,
hasReferencePrefix: rootBuffer.hasReferencePrefix
|| leafIsReferenceWritable
))
let leafHasReferencePrefix = leafBuffer.hasReferencePrefix
// Clone the root components into the buffer.
while true {
let (component, type) = rootBuffer.next()
let isLast = type == nil
// If the leaf appended path has a reference prefix, then the
// entire root is part of the reference prefix.
let endOfReferencePrefix: Bool
if leafHasReferencePrefix {
endOfReferencePrefix = false
} else if isLast && leafIsReferenceWritable {
endOfReferencePrefix = true
} else {
endOfReferencePrefix = component.header.endOfReferencePrefix
}
component.clone(
into: &destBuilder.buffer,
endOfReferencePrefix: endOfReferencePrefix)
// Insert our endpoint type between the root and leaf components.
if let type = type {
destBuilder.push(type)
} else {
destBuilder.push(Value.self as Any.Type)
break
}
}
// Clone the leaf components into the buffer.
while true {
let (component, type) = leafBuffer.next()
component.clone(
into: &destBuilder.buffer,
endOfReferencePrefix: component.header.endOfReferencePrefix)
if let type = type {
destBuilder.push(type)
} else {
break
}
}
_internalInvariant(destBuilder.buffer.isEmpty,
"did not fill entire result buffer")
}
// Build the KVC string if there is one.
if let kvcStringBuffer = kvcStringBuffer {
let rootPtr = root._kvcKeyPathStringPtr.unsafelyUnwrapped
let leafPtr = leaf._kvcKeyPathStringPtr.unsafelyUnwrapped
_memcpy(dest: kvcStringBuffer,
src: rootPtr,
size: UInt(rootKVCLength))
kvcStringBuffer.advanced(by: rootKVCLength)
.storeBytes(of: 0x2E /* '.' */, as: CChar.self)
_memcpy(dest: kvcStringBuffer.advanced(by: rootKVCLength + 1),
src: leafPtr,
size: UInt(leafKVCLength))
result._kvcKeyPathStringPtr =
UnsafePointer(kvcStringBuffer.assumingMemoryBound(to: CChar.self))
kvcStringBuffer.advanced(by: rootKVCLength + leafKVCLength + 1)
.storeBytes(of: 0 /* '\0' */, as: CChar.self)
}
return unsafeDowncast(result, to: Result.self)
}
}
}
// The distance in bytes from the address point of a KeyPath object to its
// buffer header. Includes the size of the Swift heap object header and the
// pointer to the KVC string.
internal var keyPathObjectHeaderSize: Int {
return MemoryLayout<HeapObject>.size + MemoryLayout<Int>.size
}
internal var keyPathPatternHeaderSize: Int {
return 16
}
// Runtime entry point to instantiate a key path object.
// Note that this has a compatibility override shim in the runtime so that
// future compilers can backward-deploy support for instantiating new key path
// pattern features.
@_cdecl("swift_getKeyPathImpl")
public func _swift_getKeyPath(pattern: UnsafeMutableRawPointer,
arguments: UnsafeRawPointer)
-> UnsafeRawPointer {
// The key path pattern is laid out like a key path object, with a few
// modifications:
// - Pointers in the instantiated object are compressed into 32-bit
// relative offsets in the pattern.
// - The pattern begins with a field that's either zero, for a pattern that
// depends on instantiation arguments, or that's a relative reference to
// a global mutable pointer variable, which can be initialized to a single
// shared instantiation of this pattern.
// - Instead of the two-word object header with isa and refcount, two
// pointers to metadata accessors are provided for the root and leaf
// value types of the key path.
// - Components may have unresolved forms that require instantiation.
// - Type metadata and protocol conformance pointers are replaced with
// relative-referenced accessor functions that instantiate the
// needed generic argument when called.
//
// The pattern never precomputes the capabilities of the key path (readonly/
// writable/reference-writable), nor does it encode the reference prefix.
// These are resolved dynamically, so that they always reflect the dynamic
// capability of the properties involved.
let oncePtrPtr = pattern
let patternPtr = pattern.advanced(by: 4)
let bufferHeader = patternPtr.load(fromByteOffset: keyPathPatternHeaderSize,
as: KeyPathBuffer.Header.self)
bufferHeader.validateReservedBits()
// If the first word is nonzero, it relative-references a cache variable
// we can use to reference a single shared instantiation of this key path.
let oncePtrOffset = oncePtrPtr.load(as: Int32.self)
let oncePtr: UnsafeRawPointer?
if oncePtrOffset != 0 {
let theOncePtr = _resolveRelativeAddress(oncePtrPtr, oncePtrOffset)
oncePtr = theOncePtr
// See whether we already instantiated this key path.
// This is a non-atomic load because the instantiated pointer will be
// written with a release barrier, and loads of the instantiated key path
// ought to carry a dependency through this loaded pointer.
let existingInstance = theOncePtr.load(as: UnsafeRawPointer?.self)
if let existingInstance = existingInstance {
// Return the instantiated object at +1.
let object = Unmanaged<AnyKeyPath>.fromOpaque(existingInstance)
// TODO: This retain will be unnecessary once we support global objects
// with inert refcounting.
_ = object.retain()
return existingInstance
}
} else {
oncePtr = nil
}
// Instantiate a new key path object modeled on the pattern.
// Do a pass to determine the class of the key path we'll be instantiating
// and how much space we'll need for it.
let (keyPathClass, rootType, size, _)
= _getKeyPathClassAndInstanceSizeFromPattern(patternPtr, arguments)
// Allocate the instance.
let instance = keyPathClass._create(capacityInBytes: size) { instanceData in
// Instantiate the pattern into the instance.
_instantiateKeyPathBuffer(patternPtr, instanceData, rootType, arguments)
}
// Adopt the KVC string from the pattern.
let kvcStringBase = patternPtr.advanced(by: 12)
let kvcStringOffset = kvcStringBase.load(as: Int32.self)
if kvcStringOffset == 0 {
// Null pointer.
instance._kvcKeyPathStringPtr = nil
} else {
let kvcStringPtr = _resolveRelativeAddress(kvcStringBase, kvcStringOffset)
instance._kvcKeyPathStringPtr =
kvcStringPtr.assumingMemoryBound(to: CChar.self)
}
// If we can cache this instance as a shared instance, do so.
if let oncePtr = oncePtr {
// Try to replace a null pointer in the cache variable with the instance
// pointer.
let instancePtr = Unmanaged.passRetained(instance)
while true {
let (oldValue, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
oncePtr._rawValue,
0._builtinWordValue,
UInt(bitPattern: instancePtr.toOpaque())._builtinWordValue)
// If the exchange succeeds, then the instance we formed is the canonical
// one.
if Bool(won) {
break
}
// Otherwise, someone raced with us to instantiate the key path pattern
// and won. Their instance should be just as good as ours, so we can take
// that one and let ours get deallocated.
if let existingInstance = UnsafeRawPointer(bitPattern: Int(oldValue)) {
// Return the instantiated object at +1.
let object = Unmanaged<AnyKeyPath>.fromOpaque(existingInstance)
// TODO: This retain will be unnecessary once we support global objects
// with inert refcounting.
_ = object.retain()
// Release the instance we created.
instancePtr.release()
return existingInstance
} else {
// Try the cmpxchg again if it spuriously failed.
continue
}
}
}
return UnsafeRawPointer(Unmanaged.passRetained(instance).toOpaque())
}
// A reference to metadata, which is a pointer to a mangled name.
internal typealias MetadataReference = UnsafeRawPointer
// Determine the length of the given mangled name.
internal func _getSymbolicMangledNameLength(_ base: UnsafeRawPointer) -> Int {
var end = base
while let current = Optional(end.load(as: UInt8.self)), current != 0 {
// Skip the current character
end = end + 1
// Skip over a symbolic reference
if current >= 0x1 && current <= 0x17 {
end += 4
} else if current >= 0x18 && current <= 0x1F {
end += MemoryLayout<Int>.size
}
}
return end - base
}
// Resolve a mangled name in a generic environment, described by either a
// flat GenericEnvironment * (if the bottom tag bit is 0) or possibly-nested
// ContextDescriptor * (if the bottom tag bit is 1)
internal func _getTypeByMangledNameInEnvironmentOrContext(
_ name: UnsafePointer<UInt8>,
_ nameLength: UInt,
genericEnvironmentOrContext: UnsafeRawPointer?,
genericArguments: UnsafeRawPointer?)
-> Any.Type? {
let taggedPointer = UInt(bitPattern: genericEnvironmentOrContext)
if taggedPointer & 1 == 0 {
return _getTypeByMangledNameInEnvironment(name, nameLength,
genericEnvironment: genericEnvironmentOrContext,
genericArguments: genericArguments)
} else {
let context = UnsafeRawPointer(bitPattern: taggedPointer & ~1)
return _getTypeByMangledNameInContext(name, nameLength,
genericContext: context,
genericArguments: genericArguments)
}
}
// Resolve the given generic argument reference to a generic argument.
internal func _resolveKeyPathGenericArgReference(
_ reference: UnsafeRawPointer,
genericEnvironment: UnsafeRawPointer?,
arguments: UnsafeRawPointer?)
-> UnsafeRawPointer {
// If the low bit is clear, it's a direct reference to the argument.
if (UInt(bitPattern: reference) & 0x01 == 0) {
return reference
}
// Adjust the reference.
let referenceStart = reference - 1
// If we have a symbolic reference to an accessor, call it.
let first = referenceStart.load(as: UInt8.self)
if first == 255 && reference.load(as: UInt8.self) == 9 {
typealias MetadataAccessor =
@convention(c) (UnsafeRawPointer?) -> UnsafeRawPointer
// Unaligned load of the offset.
let pointerReference = reference + 1
var offset: Int32 = 0
_memcpy(dest: &offset, src: pointerReference, size: 4)
let accessorPtrRaw = _resolveRelativeAddress(pointerReference, offset)
let accessorPtrSigned =
_PtrAuth.sign(pointer: accessorPtrRaw,
key: .processIndependentCode,
discriminator: _PtrAuth.discriminator(for: MetadataAccessor.self))
let accessor = unsafeBitCast(accessorPtrSigned, to: MetadataAccessor.self)
return accessor(arguments)
}
let nameLength = _getSymbolicMangledNameLength(referenceStart)
let namePtr = referenceStart.bindMemory(to: UInt8.self,
capacity: nameLength + 1)
// FIXME: Could extract this information from the mangled name.
guard let result =
_getTypeByMangledNameInEnvironmentOrContext(namePtr, UInt(nameLength),
genericEnvironmentOrContext: genericEnvironment,
genericArguments: arguments)
else {
let nameStr = String._fromUTF8Repairing(
UnsafeBufferPointer(start: namePtr, count: nameLength)
).0
fatalError("could not demangle keypath type from '\(nameStr)'")
}
return unsafeBitCast(result, to: UnsafeRawPointer.self)
}
// Resolve the given metadata reference to (type) metadata.
internal func _resolveKeyPathMetadataReference(
_ reference: UnsafeRawPointer,
genericEnvironment: UnsafeRawPointer?,
arguments: UnsafeRawPointer?)
-> Any.Type {
return unsafeBitCast(
_resolveKeyPathGenericArgReference(
reference,
genericEnvironment: genericEnvironment,
arguments: arguments),
to: Any.Type.self)
}
internal enum KeyPathStructOrClass {
case `struct`, `class`
}
internal enum KeyPathPatternStoredOffset {
case inline(UInt32)
case outOfLine(UInt32)
case unresolvedFieldOffset(UInt32)
case unresolvedIndirectOffset(UnsafePointer<UInt>)
}
internal struct KeyPathPatternComputedArguments {
var getLayout: KeyPathComputedArgumentLayoutFn
var witnesses: ComputedArgumentWitnessesPtr
var initializer: KeyPathComputedArgumentInitializerFn
}
internal protocol KeyPathPatternVisitor {
mutating func visitHeader(genericEnvironment: UnsafeRawPointer?,
rootMetadataRef: MetadataReference,
leafMetadataRef: MetadataReference,
kvcCompatibilityString: UnsafeRawPointer?)
mutating func visitStoredComponent(kind: KeyPathStructOrClass,
mutable: Bool,
offset: KeyPathPatternStoredOffset)
mutating func visitComputedComponent(mutating: Bool,
idKind: KeyPathComputedIDKind,
idResolution: KeyPathComputedIDResolution,
idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?,
arguments: KeyPathPatternComputedArguments?,
externalArgs: UnsafeBufferPointer<Int32>?)
mutating func visitOptionalChainComponent()
mutating func visitOptionalForceComponent()
mutating func visitOptionalWrapComponent()
mutating func visitIntermediateComponentType(metadataRef: MetadataReference)
mutating func finish()
}
internal func _resolveRelativeAddress(_ base: UnsafeRawPointer,
_ offset: Int32) -> UnsafeRawPointer {
// Sign-extend the offset to pointer width and add with wrap on overflow.
return UnsafeRawPointer(bitPattern: Int(bitPattern: base) &+ Int(offset))
.unsafelyUnwrapped
}
internal func _resolveRelativeIndirectableAddress(_ base: UnsafeRawPointer,
_ offset: Int32)
-> UnsafeRawPointer {
// Low bit indicates whether the reference is indirected or not.
if offset & 1 != 0 {
let ptrToPtr = _resolveRelativeAddress(base, offset - 1)
return ptrToPtr.load(as: UnsafeRawPointer.self)
}
return _resolveRelativeAddress(base, offset)
}
internal func _loadRelativeAddress<T>(at: UnsafeRawPointer,
fromByteOffset: Int = 0,
as: T.Type) -> T {
let offset = at.load(fromByteOffset: fromByteOffset, as: Int32.self)
return unsafeBitCast(_resolveRelativeAddress(at + fromByteOffset, offset),
to: T.self)
}
internal func _walkKeyPathPattern<W: KeyPathPatternVisitor>(
_ pattern: UnsafeRawPointer,
walker: inout W) {
// Visit the header.
let genericEnvironment = _loadRelativeAddress(at: pattern,
as: UnsafeRawPointer.self)
let rootMetadataRef = _loadRelativeAddress(at: pattern, fromByteOffset: 4,
as: MetadataReference.self)
let leafMetadataRef = _loadRelativeAddress(at: pattern, fromByteOffset: 8,
as: MetadataReference.self)
let kvcString = _loadRelativeAddress(at: pattern, fromByteOffset: 12,
as: UnsafeRawPointer.self)
walker.visitHeader(genericEnvironment: genericEnvironment,
rootMetadataRef: rootMetadataRef,
leafMetadataRef: leafMetadataRef,
kvcCompatibilityString: kvcString)
func visitStored(header: RawKeyPathComponent.Header,
componentBuffer: inout UnsafeRawBufferPointer) {
// Decode a stored property. A small offset may be stored inline in the
// header word, or else be stored out-of-line, or need instantiation of some
// kind.
let offset: KeyPathPatternStoredOffset
switch header.storedOffsetPayload {
case RawKeyPathComponent.Header.outOfLineOffsetPayload:
offset = .outOfLine(_pop(from: &componentBuffer,
as: UInt32.self))
case RawKeyPathComponent.Header.unresolvedFieldOffsetPayload:
offset = .unresolvedFieldOffset(_pop(from: &componentBuffer,
as: UInt32.self))
case RawKeyPathComponent.Header.unresolvedIndirectOffsetPayload:
let base = componentBuffer.baseAddress.unsafelyUnwrapped
let relativeOffset = _pop(from: &componentBuffer,
as: Int32.self)
let ptr = _resolveRelativeIndirectableAddress(base, relativeOffset)
offset = .unresolvedIndirectOffset(
ptr.assumingMemoryBound(to: UInt.self))
default:
offset = .inline(header.storedOffsetPayload)
}
let kind: KeyPathStructOrClass = header.kind == .struct
? .struct : .class
walker.visitStoredComponent(kind: kind,
mutable: header.isStoredMutable,
offset: offset)
}
func popComputedAccessors(header: RawKeyPathComponent.Header,
componentBuffer: inout UnsafeRawBufferPointer)
-> (idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?) {
let idValueBase = componentBuffer.baseAddress.unsafelyUnwrapped
let idValue = _pop(from: &componentBuffer, as: Int32.self)
let getterBase = componentBuffer.baseAddress.unsafelyUnwrapped
let getterRef = _pop(from: &componentBuffer, as: Int32.self)
let getter = _resolveRelativeAddress(getterBase, getterRef)
let setter: UnsafeRawPointer?
if header.isComputedSettable {
let setterBase = componentBuffer.baseAddress.unsafelyUnwrapped
let setterRef = _pop(from: &componentBuffer, as: Int32.self)
setter = _resolveRelativeAddress(setterBase, setterRef)
} else {
setter = nil
}
return (idValueBase: idValueBase, idValue: idValue,
getter: getter, setter: setter)
}
func popComputedArguments(header: RawKeyPathComponent.Header,
componentBuffer: inout UnsafeRawBufferPointer)
-> KeyPathPatternComputedArguments? {
if header.hasComputedArguments {
let getLayoutBase = componentBuffer.baseAddress.unsafelyUnwrapped
let getLayoutRef = _pop(from: &componentBuffer, as: Int32.self)
let getLayoutRaw = _resolveRelativeAddress(getLayoutBase, getLayoutRef)
let getLayoutSigned = _PtrAuth.sign(pointer: getLayoutRaw,
key: .processIndependentCode,
discriminator: _PtrAuth.discriminator(for: KeyPathComputedArgumentLayoutFn.self))
let getLayout = unsafeBitCast(getLayoutSigned,
to: KeyPathComputedArgumentLayoutFn.self)
let witnessesBase = componentBuffer.baseAddress.unsafelyUnwrapped
let witnessesRef = _pop(from: &componentBuffer, as: Int32.self)
let witnesses: UnsafeRawPointer
if witnessesRef == 0 {
witnesses = __swift_keyPathGenericWitnessTable_addr()
} else {
witnesses = _resolveRelativeAddress(witnessesBase, witnessesRef)
}
let initializerBase = componentBuffer.baseAddress.unsafelyUnwrapped
let initializerRef = _pop(from: &componentBuffer, as: Int32.self)
let initializerRaw = _resolveRelativeAddress(initializerBase,
initializerRef)
let initializerSigned = _PtrAuth.sign(pointer: initializerRaw,
key: .processIndependentCode,
discriminator: _PtrAuth.discriminator(for: KeyPathComputedArgumentInitializerFn.self))
let initializer = unsafeBitCast(initializerSigned,
to: KeyPathComputedArgumentInitializerFn.self)
return KeyPathPatternComputedArguments(getLayout: getLayout,
witnesses: ComputedArgumentWitnessesPtr(witnesses),
initializer: initializer)
} else {
return nil
}
}
// We declare this down here to avoid the temptation to use it within
// the functions above.
let bufferPtr = pattern.advanced(by: keyPathPatternHeaderSize)
let bufferHeader = bufferPtr.load(as: KeyPathBuffer.Header.self)
var buffer = UnsafeRawBufferPointer(start: bufferPtr + 4,
count: bufferHeader.size)
while !buffer.isEmpty {
let header = _pop(from: &buffer,
as: RawKeyPathComponent.Header.self)
// Ensure that we pop an amount of data consistent with what
// RawKeyPathComponent.Header.patternComponentBodySize computes.
var bufferSizeBefore = 0
var expectedPop = 0
_internalInvariant({
bufferSizeBefore = buffer.count
expectedPop = header.patternComponentBodySize
return true
}())
switch header.kind {
case .class, .struct:
visitStored(header: header, componentBuffer: &buffer)
case .computed:
let (idValueBase, idValue, getter, setter)
= popComputedAccessors(header: header,
componentBuffer: &buffer)
// If there are arguments, gather those too.
let arguments = popComputedArguments(header: header,
componentBuffer: &buffer)
walker.visitComputedComponent(mutating: header.isComputedMutating,
idKind: header.computedIDKind,
idResolution: header.computedIDResolution,
idValueBase: idValueBase,
idValue: idValue,
getter: getter,
setter: setter,
arguments: arguments,
externalArgs: nil)
case .optionalChain:
walker.visitOptionalChainComponent()
case .optionalWrap:
walker.visitOptionalWrapComponent()
case .optionalForce:
walker.visitOptionalForceComponent()
case .external:
// Look at the external property descriptor to see if we should take it
// over the component given in the pattern.
let genericParamCount = Int(header.payload)
let descriptorBase = buffer.baseAddress.unsafelyUnwrapped
let descriptorOffset = _pop(from: &buffer,
as: Int32.self)
let descriptor =
_resolveRelativeIndirectableAddress(descriptorBase, descriptorOffset)
let descriptorHeader =
descriptor.load(as: RawKeyPathComponent.Header.self)
if descriptorHeader.isTrivialPropertyDescriptor {
// If the descriptor is trivial, then use the local candidate.
// Skip the external generic parameter accessors to get to it.
_ = _pop(from: &buffer, as: Int32.self, count: genericParamCount)
continue
}
// Grab the generic parameter accessors to pass to the external component.
let externalArgs = _pop(from: &buffer, as: Int32.self,
count: genericParamCount)
// Grab the header for the local candidate in case we need it for
// a computed property.
let localCandidateHeader = _pop(from: &buffer,
as: RawKeyPathComponent.Header.self)
let localCandidateSize = localCandidateHeader.patternComponentBodySize
_internalInvariant({
expectedPop += localCandidateSize + 4
return true
}())
let descriptorSize = descriptorHeader.propertyDescriptorBodySize
var descriptorBuffer = UnsafeRawBufferPointer(start: descriptor + 4,
count: descriptorSize)
// Look at what kind of component the external property has.
switch descriptorHeader.kind {
case .struct, .class:
// A stored component. We can instantiate it
// without help from the local candidate.
_ = _pop(from: &buffer, as: UInt8.self, count: localCandidateSize)
visitStored(header: descriptorHeader,
componentBuffer: &descriptorBuffer)
case .computed:
// A computed component. The accessors come from the descriptor.
let (idValueBase, idValue, getter, setter)
= popComputedAccessors(header: descriptorHeader,
componentBuffer: &descriptorBuffer)
// Get the arguments from the external descriptor and/or local candidate
// component.
let arguments: KeyPathPatternComputedArguments?
if localCandidateHeader.kind == .computed
&& localCandidateHeader.hasComputedArguments {
// If both have arguments, then we have to build a bit of a chimera.
// The canonical identity and accessors come from the descriptor,
// but the argument equality/hash handling is still as described
// in the local candidate.
// We don't need the local candidate's accessors.
_ = popComputedAccessors(header: localCandidateHeader,
componentBuffer: &buffer)
// We do need the local arguments.
arguments = popComputedArguments(header: localCandidateHeader,
componentBuffer: &buffer)
} else {
// If the local candidate doesn't have arguments, we don't need
// anything from it at all.
_ = _pop(from: &buffer, as: UInt8.self, count: localCandidateSize)
arguments = nil
}
walker.visitComputedComponent(
mutating: descriptorHeader.isComputedMutating,
idKind: descriptorHeader.computedIDKind,
idResolution: descriptorHeader.computedIDResolution,
idValueBase: idValueBase,
idValue: idValue,
getter: getter,
setter: setter,
arguments: arguments,
externalArgs: genericParamCount > 0 ? externalArgs : nil)
case .optionalChain, .optionalWrap, .optionalForce, .external:
_internalInvariantFailure("not possible for property descriptor")
}
}
// Check that we consumed the expected amount of data from the pattern.
_internalInvariant(
{
// Round the amount of data we read up to alignment.
let popped = MemoryLayout<Int32>._roundingUpToAlignment(
bufferSizeBefore - buffer.count)
return expectedPop == popped
}(),
"""
component size consumed during pattern walk does not match \
component size returned by patternComponentBodySize
""")
// Break if this is the last component.
if buffer.isEmpty { break }
// Otherwise, pop the intermediate component type accessor and
// go around again.
let componentTypeBase = buffer.baseAddress.unsafelyUnwrapped
let componentTypeOffset = _pop(from: &buffer, as: Int32.self)
let componentTypeRef = _resolveRelativeAddress(componentTypeBase,
componentTypeOffset)
walker.visitIntermediateComponentType(metadataRef: componentTypeRef)
_internalInvariant(!buffer.isEmpty)
}
// We should have walked the entire pattern.
_internalInvariant(buffer.isEmpty, "did not walk entire pattern buffer")
walker.finish()
}
internal struct GetKeyPathClassAndInstanceSizeFromPattern
: KeyPathPatternVisitor {
var size: Int = MemoryLayout<Int>.size // start with one word for the header
var capability: KeyPathKind = .value
var didChain: Bool = false
var root: Any.Type!
var leaf: Any.Type!
var genericEnvironment: UnsafeRawPointer?
let patternArgs: UnsafeRawPointer?
init(patternArgs: UnsafeRawPointer?) {
self.patternArgs = patternArgs
}
mutating func roundUpToPointerAlignment() {
size = MemoryLayout<Int>._roundingUpToAlignment(size)
}
mutating func visitHeader(genericEnvironment: UnsafeRawPointer?,
rootMetadataRef: MetadataReference,
leafMetadataRef: MetadataReference,
kvcCompatibilityString: UnsafeRawPointer?) {
self.genericEnvironment = genericEnvironment
// Get the root and leaf type metadata so we can form the class type
// for the entire key path.
root = _resolveKeyPathMetadataReference(
rootMetadataRef,
genericEnvironment: genericEnvironment,
arguments: patternArgs)
leaf = _resolveKeyPathMetadataReference(
leafMetadataRef,
genericEnvironment: genericEnvironment,
arguments: patternArgs)
}
mutating func visitStoredComponent(kind: KeyPathStructOrClass,
mutable: Bool,
offset: KeyPathPatternStoredOffset) {
// Mutable class properties can be the root of a reference mutation.
// Mutable struct properties pass through the existing capability.
if mutable {
switch kind {
case .class:
capability = .reference
case .struct:
break
}
} else {
// Immutable properties can only be read.
capability = .readOnly
}
// The size of the instantiated component depends on whether we can fit
// the offset inline.
switch offset {
case .inline:
size += 4
case .outOfLine, .unresolvedFieldOffset, .unresolvedIndirectOffset:
size += 8
}
}
mutating func visitComputedComponent(mutating: Bool,
idKind: KeyPathComputedIDKind,
idResolution: KeyPathComputedIDResolution,
idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?,
arguments: KeyPathPatternComputedArguments?,
externalArgs: UnsafeBufferPointer<Int32>?) {
let settable = setter != nil
switch (settable, mutating) {
case (false, false):
// If the property is get-only, the capability becomes read-only, unless
// we get another reference-writable component.
capability = .readOnly
case (true, false):
capability = .reference
case (true, true):
// Writable if the base is. No effect.
break
case (false, true):
_internalInvariantFailure("unpossible")
}
// Save space for the header...
size += 4
roundUpToPointerAlignment()
// ...id, getter, and maybe setter...
size += MemoryLayout<Int>.size * 2
if settable {
size += MemoryLayout<Int>.size
}
// ...and the arguments, if any.
let argumentHeaderSize = MemoryLayout<Int>.size * 2
switch (arguments, externalArgs) {
case (nil, nil):
break
case (let arguments?, nil):
size += argumentHeaderSize
// If we have arguments, calculate how much space they need by invoking
// the layout function.
let (addedSize, addedAlignmentMask) = arguments.getLayout(patternArgs)
// TODO: Handle over-aligned values
_internalInvariant(addedAlignmentMask < MemoryLayout<Int>.alignment,
"overaligned computed property element not supported")
size += addedSize
case (let arguments?, let externalArgs?):
// If we're referencing an external declaration, and it takes captured
// arguments, then we have to build a bit of a chimera. The canonical
// identity and accessors come from the descriptor, but the argument
// handling is still as described in the local candidate.
size += argumentHeaderSize
let (addedSize, addedAlignmentMask) = arguments.getLayout(patternArgs)
// TODO: Handle over-aligned values
_internalInvariant(addedAlignmentMask < MemoryLayout<Int>.alignment,
"overaligned computed property element not supported")
size += addedSize
// We also need to store the size of the local arguments so we can
// find the external component arguments.
roundUpToPointerAlignment()
size += RawKeyPathComponent.Header.externalWithArgumentsExtraSize
size += MemoryLayout<Int>.size * externalArgs.count
case (nil, let externalArgs?):
// If we're instantiating an external property with a local
// candidate that has no arguments, then things are a little
// easier. We only need to instantiate the generic
// arguments for the external component's accessors.
size += argumentHeaderSize
size += MemoryLayout<Int>.size * externalArgs.count
}
}
mutating func visitOptionalChainComponent() {
// Optional chaining forces the entire keypath to be read-only, even if
// there are further reference-writable components.
didChain = true
capability = .readOnly
size += 4
}
mutating func visitOptionalWrapComponent() {
// Optional chaining forces the entire keypath to be read-only, even if
// there are further reference-writable components.
didChain = true
capability = .readOnly
size += 4
}
mutating func visitOptionalForceComponent() {
// Force-unwrapping passes through the mutability of the preceding keypath.
size += 4
}
mutating
func visitIntermediateComponentType(metadataRef _: MetadataReference) {
// The instantiated component type will be stored in the instantiated
// object.
roundUpToPointerAlignment()
size += MemoryLayout<Int>.size
}
mutating func finish() {
}
}
internal func _getKeyPathClassAndInstanceSizeFromPattern(
_ pattern: UnsafeRawPointer,
_ arguments: UnsafeRawPointer
) -> (
keyPathClass: AnyKeyPath.Type,
rootType: Any.Type,
size: Int,
alignmentMask: Int
) {
var walker = GetKeyPathClassAndInstanceSizeFromPattern(patternArgs: arguments)
_walkKeyPathPattern(pattern, walker: &walker)
// Chaining always renders the whole key path read-only.
if walker.didChain {
walker.capability = .readOnly
}
// Grab the class object for the key path type we'll end up with.
func openRoot<Root>(_: Root.Type) -> AnyKeyPath.Type {
func openLeaf<Leaf>(_: Leaf.Type) -> AnyKeyPath.Type {
switch walker.capability {
case .readOnly:
return KeyPath<Root, Leaf>.self
case .value:
return WritableKeyPath<Root, Leaf>.self
case .reference:
return ReferenceWritableKeyPath<Root, Leaf>.self
}
}
return _openExistential(walker.leaf!, do: openLeaf)
}
let classTy = _openExistential(walker.root!, do: openRoot)
return (keyPathClass: classTy,
rootType: walker.root!,
size: walker.size,
// FIXME: Handle overalignment
alignmentMask: MemoryLayout<Int>._alignmentMask)
}
internal struct InstantiateKeyPathBuffer: KeyPathPatternVisitor {
var destData: UnsafeMutableRawBufferPointer
var genericEnvironment: UnsafeRawPointer?
let patternArgs: UnsafeRawPointer?
var base: Any.Type
init(destData: UnsafeMutableRawBufferPointer,
patternArgs: UnsafeRawPointer?,
root: Any.Type) {
self.destData = destData
self.patternArgs = patternArgs
self.base = root
}
// Track the triviality of the resulting object data.
var isTrivial: Bool = true
// Track where the reference prefix begins.
var endOfReferencePrefixComponent: UnsafeMutableRawPointer? = nil
var previousComponentAddr: UnsafeMutableRawPointer? = nil
mutating func adjustDestForAlignment<T>(of: T.Type) -> (
baseAddress: UnsafeMutableRawPointer,
misalign: Int
) {
let alignment = MemoryLayout<T>.alignment
var baseAddress = destData.baseAddress.unsafelyUnwrapped
var misalign = Int(bitPattern: baseAddress) % alignment
if misalign != 0 {
misalign = alignment - misalign
baseAddress = baseAddress.advanced(by: misalign)
}
return (baseAddress, misalign)
}
mutating func pushDest<T>(_ value: T) {
_internalInvariant(_isPOD(T.self))
let size = MemoryLayout<T>.size
let (baseAddress, misalign) = adjustDestForAlignment(of: T.self)
withUnsafeBytes(of: value) {
_memcpy(dest: baseAddress, src: $0.baseAddress.unsafelyUnwrapped,
size: UInt(size))
}
destData = UnsafeMutableRawBufferPointer(
start: baseAddress + size,
count: destData.count - size - misalign)
}
mutating func pushAddressDiscriminatedFunctionPointer(
_ unsignedPointer: UnsafeRawPointer,
discriminator: UInt64
) {
let size = MemoryLayout<UnsafeRawPointer>.size
let (baseAddress, misalign) =
adjustDestForAlignment(of: UnsafeRawPointer.self)
baseAddress._storeFunctionPointerWithAddressDiscrimination(
unsignedPointer, discriminator: discriminator)
destData = UnsafeMutableRawBufferPointer(
start: baseAddress + size,
count: destData.count - size - misalign)
}
mutating func updatePreviousComponentAddr() -> UnsafeMutableRawPointer? {
let oldValue = previousComponentAddr
previousComponentAddr = destData.baseAddress.unsafelyUnwrapped
return oldValue
}
mutating func visitHeader(genericEnvironment: UnsafeRawPointer?,
rootMetadataRef: MetadataReference,
leafMetadataRef: MetadataReference,
kvcCompatibilityString: UnsafeRawPointer?) {
self.genericEnvironment = genericEnvironment
}
mutating func visitStoredComponent(kind: KeyPathStructOrClass,
mutable: Bool,
offset: KeyPathPatternStoredOffset) {
let previous = updatePreviousComponentAddr()
switch kind {
case .class:
// A mutable class property can end the reference prefix.
if mutable {
endOfReferencePrefixComponent = previous
}
fallthrough
case .struct:
// Resolve the offset.
switch offset {
case .inline(let value):
let header = RawKeyPathComponent.Header(stored: kind,
mutable: mutable,
inlineOffset: value)
pushDest(header)
case .outOfLine(let offset):
let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind,
mutable: mutable)
pushDest(header)
pushDest(offset)
case .unresolvedFieldOffset(let offsetOfOffset):
// Look up offset in the type metadata. The value in the pattern is
// the offset within the metadata object.
let metadataPtr = unsafeBitCast(base, to: UnsafeRawPointer.self)
let offset: UInt32
switch kind {
case .class:
offset = UInt32(metadataPtr.load(fromByteOffset: Int(offsetOfOffset),
as: UInt.self))
case .struct:
offset = UInt32(metadataPtr.load(fromByteOffset: Int(offsetOfOffset),
as: UInt32.self))
}
let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind,
mutable: mutable)
pushDest(header)
pushDest(offset)
case .unresolvedIndirectOffset(let pointerToOffset):
// Look up offset in the indirectly-referenced variable we have a
// pointer.
_internalInvariant(pointerToOffset.pointee <= UInt32.max)
let offset = UInt32(truncatingIfNeeded: pointerToOffset.pointee)
let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind,
mutable: mutable)
pushDest(header)
pushDest(offset)
}
}
}
mutating func visitComputedComponent(mutating: Bool,
idKind: KeyPathComputedIDKind,
idResolution: KeyPathComputedIDResolution,
idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?,
arguments: KeyPathPatternComputedArguments?,
externalArgs: UnsafeBufferPointer<Int32>?) {
let previous = updatePreviousComponentAddr()
let settable = setter != nil
// A nonmutating settable property can end the reference prefix.
if settable && !mutating {
endOfReferencePrefixComponent = previous
}
// Resolve the ID.
let resolvedID: UnsafeRawPointer?
switch idKind {
case .storedPropertyIndex, .vtableOffset:
_internalInvariant(idResolution == .resolved)
// Zero-extend the integer value to get the instantiated id.
let value = UInt(UInt32(bitPattern: idValue))
resolvedID = UnsafeRawPointer(bitPattern: value)
case .pointer:
// Resolve the sign-extended relative reference.
var absoluteID: UnsafeRawPointer? = _resolveRelativeAddress(idValueBase, idValue)
// If the pointer ID is unresolved, then it needs work to get to
// the final value.
switch idResolution {
case .resolved:
break
case .indirectPointer:
// The pointer in the pattern is an indirect pointer to the real
// identifier pointer.
absoluteID = absoluteID.unsafelyUnwrapped
.load(as: UnsafeRawPointer?.self)
case .functionCall:
// The pointer in the pattern is to a function that generates the
// identifier pointer.
typealias Resolver = @convention(c) (UnsafeRawPointer?) -> UnsafeRawPointer?
let resolverSigned = _PtrAuth.sign(
pointer: absoluteID.unsafelyUnwrapped,
key: .processIndependentCode,
discriminator: _PtrAuth.discriminator(for: Resolver.self))
let resolverFn = unsafeBitCast(resolverSigned,
to: Resolver.self)
absoluteID = resolverFn(patternArgs)
}
resolvedID = absoluteID
}
// Bring over the header, getter, and setter.
let header = RawKeyPathComponent.Header(computedWithIDKind: idKind,
mutating: mutating,
settable: settable,
hasArguments: arguments != nil || externalArgs != nil,
instantiatedFromExternalWithArguments:
arguments != nil && externalArgs != nil)
pushDest(header)
pushDest(resolvedID)
pushAddressDiscriminatedFunctionPointer(getter,
discriminator: ComputedAccessorsPtr.getterPtrAuthKey)
if let setter = setter {
pushAddressDiscriminatedFunctionPointer(setter,
discriminator: mutating ? ComputedAccessorsPtr.mutatingSetterPtrAuthKey
: ComputedAccessorsPtr.nonmutatingSetterPtrAuthKey)
}
if let arguments = arguments {
// Instantiate the arguments.
let (baseSize, alignmentMask) = arguments.getLayout(patternArgs)
_internalInvariant(alignmentMask < MemoryLayout<Int>.alignment,
"overaligned computed arguments not implemented yet")
// The real buffer stride will be rounded up to alignment.
var totalSize = (baseSize + alignmentMask) & ~alignmentMask
// If an external property descriptor also has arguments, they'll be
// added to the end with pointer alignment.
if let externalArgs = externalArgs {
totalSize = MemoryLayout<Int>._roundingUpToAlignment(totalSize)
totalSize += MemoryLayout<Int>.size * externalArgs.count
}
pushDest(totalSize)
pushDest(arguments.witnesses)
// A nonnull destructor in the witnesses file indicates the instantiated
// payload is nontrivial.
if let _ = arguments.witnesses.destroy {
isTrivial = false
}
// If the descriptor has arguments, store the size of its specific
// arguments here, so we can drop them when trying to invoke
// the component's witnesses.
if let externalArgs = externalArgs {
pushDest(externalArgs.count * MemoryLayout<Int>.size)
}
// Initialize the local candidate arguments here.
_internalInvariant(Int(bitPattern: destData.baseAddress) & alignmentMask == 0,
"argument destination not aligned")
arguments.initializer(patternArgs,
destData.baseAddress.unsafelyUnwrapped)
destData = UnsafeMutableRawBufferPointer(
start: destData.baseAddress.unsafelyUnwrapped + baseSize,
count: destData.count - baseSize)
}
if let externalArgs = externalArgs {
if arguments == nil {
// If we're instantiating an external property without any local
// arguments, then we only need to instantiate the arguments to the
// property descriptor.
let stride = MemoryLayout<Int>.size * externalArgs.count
pushDest(stride)
pushDest(__swift_keyPathGenericWitnessTable_addr())
}
// Write the descriptor's generic arguments, which should all be relative
// references to metadata accessor functions.
for i in externalArgs.indices {
let base = externalArgs.baseAddress.unsafelyUnwrapped + i
let offset = base.pointee
let metadataRef = _resolveRelativeAddress(UnsafeRawPointer(base), offset)
let result = _resolveKeyPathGenericArgReference(
metadataRef,
genericEnvironment: genericEnvironment,
arguments: patternArgs)
pushDest(result)
}
}
}
mutating func visitOptionalChainComponent() {
let _ = updatePreviousComponentAddr()
let header = RawKeyPathComponent.Header(optionalChain: ())
pushDest(header)
}
mutating func visitOptionalWrapComponent() {
let _ = updatePreviousComponentAddr()
let header = RawKeyPathComponent.Header(optionalWrap: ())
pushDest(header)
}
mutating func visitOptionalForceComponent() {
let _ = updatePreviousComponentAddr()
let header = RawKeyPathComponent.Header(optionalForce: ())
pushDest(header)
}
mutating func visitIntermediateComponentType(metadataRef: MetadataReference) {
// Get the metadata for the intermediate type.
let metadata = _resolveKeyPathMetadataReference(
metadataRef,
genericEnvironment: genericEnvironment,
arguments: patternArgs)
pushDest(metadata)
base = metadata
}
mutating func finish() {
// Should have filled the entire buffer by the time we reach the end of the
// pattern.
_internalInvariant(destData.isEmpty,
"should have filled entire destination buffer")
}
}
#if INTERNAL_CHECKS_ENABLED
// In debug builds of the standard library, check that instantiation produces
// components whose sizes are consistent with the sizing visitor pass.
internal struct ValidatingInstantiateKeyPathBuffer: KeyPathPatternVisitor {
var sizeVisitor: GetKeyPathClassAndInstanceSizeFromPattern
var instantiateVisitor: InstantiateKeyPathBuffer
let origDest: UnsafeMutableRawPointer
init(sizeVisitor: GetKeyPathClassAndInstanceSizeFromPattern,
instantiateVisitor: InstantiateKeyPathBuffer) {
self.sizeVisitor = sizeVisitor
self.instantiateVisitor = instantiateVisitor
origDest = self.instantiateVisitor.destData.baseAddress.unsafelyUnwrapped
}
mutating func visitHeader(genericEnvironment: UnsafeRawPointer?,
rootMetadataRef: MetadataReference,
leafMetadataRef: MetadataReference,
kvcCompatibilityString: UnsafeRawPointer?) {
sizeVisitor.visitHeader(genericEnvironment: genericEnvironment,
rootMetadataRef: rootMetadataRef,
leafMetadataRef: leafMetadataRef,
kvcCompatibilityString: kvcCompatibilityString)
instantiateVisitor.visitHeader(genericEnvironment: genericEnvironment,
rootMetadataRef: rootMetadataRef,
leafMetadataRef: leafMetadataRef,
kvcCompatibilityString: kvcCompatibilityString)
}
mutating func visitStoredComponent(kind: KeyPathStructOrClass,
mutable: Bool,
offset: KeyPathPatternStoredOffset) {
sizeVisitor.visitStoredComponent(kind: kind, mutable: mutable,
offset: offset)
instantiateVisitor.visitStoredComponent(kind: kind, mutable: mutable,
offset: offset)
checkSizeConsistency()
}
mutating func visitComputedComponent(mutating: Bool,
idKind: KeyPathComputedIDKind,
idResolution: KeyPathComputedIDResolution,
idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?,
arguments: KeyPathPatternComputedArguments?,
externalArgs: UnsafeBufferPointer<Int32>?) {
sizeVisitor.visitComputedComponent(mutating: mutating,
idKind: idKind,
idResolution: idResolution,
idValueBase: idValueBase,
idValue: idValue,
getter: getter,
setter: setter,
arguments: arguments,
externalArgs: externalArgs)
instantiateVisitor.visitComputedComponent(mutating: mutating,
idKind: idKind,
idResolution: idResolution,
idValueBase: idValueBase,
idValue: idValue,
getter: getter,
setter: setter,
arguments: arguments,
externalArgs: externalArgs)
checkSizeConsistency()
}
mutating func visitOptionalChainComponent() {
sizeVisitor.visitOptionalChainComponent()
instantiateVisitor.visitOptionalChainComponent()
checkSizeConsistency()
}
mutating func visitOptionalWrapComponent() {
sizeVisitor.visitOptionalWrapComponent()
instantiateVisitor.visitOptionalWrapComponent()
checkSizeConsistency()
}
mutating func visitOptionalForceComponent() {
sizeVisitor.visitOptionalForceComponent()
instantiateVisitor.visitOptionalForceComponent()
checkSizeConsistency()
}
mutating func visitIntermediateComponentType(metadataRef: MetadataReference) {
sizeVisitor.visitIntermediateComponentType(metadataRef: metadataRef)
instantiateVisitor.visitIntermediateComponentType(metadataRef: metadataRef)
checkSizeConsistency()
}
mutating func finish() {
sizeVisitor.finish()
instantiateVisitor.finish()
checkSizeConsistency()
}
func checkSizeConsistency() {
let nextDest = instantiateVisitor.destData.baseAddress.unsafelyUnwrapped
let curSize = nextDest - origDest + MemoryLayout<Int>.size
_internalInvariant(curSize == sizeVisitor.size,
"size and instantiation visitors out of sync")
}
}
#endif // INTERNAL_CHECKS_ENABLED
internal func _instantiateKeyPathBuffer(
_ pattern: UnsafeRawPointer,
_ origDestData: UnsafeMutableRawBufferPointer,
_ rootType: Any.Type,
_ arguments: UnsafeRawPointer
) {
let destHeaderPtr = origDestData.baseAddress.unsafelyUnwrapped
var destData = UnsafeMutableRawBufferPointer(
start: destHeaderPtr.advanced(by: MemoryLayout<Int>.size),
count: origDestData.count - MemoryLayout<Int>.size)
#if INTERNAL_CHECKS_ENABLED
// If checks are enabled, use a validating walker that ensures that the
// size pre-walk and instantiation walk are in sync.
let sizeWalker = GetKeyPathClassAndInstanceSizeFromPattern(
patternArgs: arguments)
let instantiateWalker = InstantiateKeyPathBuffer(
destData: destData,
patternArgs: arguments,
root: rootType)
var walker = ValidatingInstantiateKeyPathBuffer(sizeVisitor: sizeWalker,
instantiateVisitor: instantiateWalker)
#else
var walker = InstantiateKeyPathBuffer(
destData: destData,
patternArgs: arguments,
root: rootType)
#endif
_walkKeyPathPattern(pattern, walker: &walker)
#if INTERNAL_CHECKS_ENABLED
let isTrivial = walker.instantiateVisitor.isTrivial
let endOfReferencePrefixComponent =
walker.instantiateVisitor.endOfReferencePrefixComponent
#else
let isTrivial = walker.isTrivial
let endOfReferencePrefixComponent = walker.endOfReferencePrefixComponent
#endif
// Write out the header.
let destHeader = KeyPathBuffer.Header(
size: origDestData.count - MemoryLayout<Int>.size,
trivial: isTrivial,
hasReferencePrefix: endOfReferencePrefixComponent != nil)
destHeaderPtr.storeBytes(of: destHeader, as: KeyPathBuffer.Header.self)
// Mark the reference prefix if there is one.
if let endOfReferencePrefixComponent = endOfReferencePrefixComponent {
var componentHeader = endOfReferencePrefixComponent
.load(as: RawKeyPathComponent.Header.self)
componentHeader.endOfReferencePrefix = true
endOfReferencePrefixComponent.storeBytes(of: componentHeader,
as: RawKeyPathComponent.Header.self)
}
}
|
//
// RPSLSUITests.swift
// RPSLSUITests
//
// Created by Daniel Gulko on 10/5/15.
// Copyright © 2015 Magnet Systems, Inc. All rights reserved.
//
import XCTest
class RPSLSSignInTests: XCTestCase {
let app = XCUIApplication()
override func setUp() {
super.setUp()
// 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.
app.launch()
// added condition to look for notification alert and confirm
if XCUIApplication().alerts.collectionViews.buttons["OK"].exists {
app.alerts.collectionViews.buttons["OK"].tap()
}
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// sign in
private func signIn(user:String, password:String) {
let usernameTextField = app.textFields["Username"]
usernameTextField.tap()
usernameTextField.typeText(user)
let passwordSecureTextField = app.secureTextFields["Password"]
passwordSecureTextField.tap()
passwordSecureTextField.typeText(password)
}
// wait for element
private func evaluateElementExist(element:AnyObject) {
let exists = NSPredicate(format: "exists == 1")
expectationForPredicate(exists, evaluatedWithObject: element, handler: nil)
waitForExpectationsWithTimeout(30, handler: nil)
}
// confirm alert
private func confirmAlert(title: String, message: String) {
if app.alerts.collectionViews.buttons["OK"].exists {
let title = app.staticTexts[title]
let message = app.staticTexts[message]
evaluateElementExist(title)
evaluateElementExist(message)
app.buttons["OK"].tap()
}
}
// sign in and registration tests
func test1signInNonExistingUser() {
let signinButton = app.buttons["Sign In"]
evaluateElementExist(signinButton)
app.textFields["Username"].tap() // get app focus by tapping username if notification was confirmed
signIn("nonexistinguser", password: "password")
app.buttons["Sign In"].tap()
confirmAlert("Error", message: "Not Authorized. Please check your credentials and try again.")
}
func test2registerExistingUser() {
signIn("serveruser", password: "password")
app.buttons["Register"].tap()
confirmAlert("Error Registering User", message: "You have tried to create a duplicate entry.")
}
func test3registerEmptyUserName() {
signIn("", password: "password")
app.buttons["Register"].tap()
confirmAlert("Error", message: "Username must be at least 5 characters in length.")
}
func test4registerEmptyPassword() {
signIn("newuser", password: "")
app.buttons["Register"].tap()
confirmAlert("Error", message: "You must provide a password")
}
func test5signInEmptyUsername() {
signIn("", password: "password")
app.buttons["Sign In"].tap()
confirmAlert("Error", message: "Username must be at least 5 characters in length.")
}
func test6signInEmptyPassword() {
signIn("newuser", password: "")
app.buttons["Sign In"].tap()
confirmAlert("Error", message: "You must provide a password")
}
func test7registerUser() {
let findOpponentButton = app.buttons["Find Opponent"]
signIn("rpslsuser", password: "password")
app.buttons["Register"].tap()
evaluateElementExist(findOpponentButton)
XCTAssertEqual(app.staticTexts["Connected as rpslsuser"].exists, true)
}
func test8signInUser() {
let findOpponentButton = app.buttons["Find Opponent"]
signIn("rpslsuser", password: "password")
app.buttons["Sign In"].tap()
evaluateElementExist(findOpponentButton)
XCTAssertEqual(app.staticTexts["Connected as rpslsuser"].exists, true)
}
}
modified sign in test 1 and 6 to purposely fail to verify jenkins picks up failure
//
// RPSLSUITests.swift
// RPSLSUITests
//
// Created by Daniel Gulko on 10/5/15.
// Copyright © 2015 Magnet Systems, Inc. All rights reserved.
//
import XCTest
class RPSLSSignInTests: XCTestCase {
let app = XCUIApplication()
override func setUp() {
super.setUp()
// 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.
app.launch()
// added condition to look for notification alert and confirm
if XCUIApplication().alerts.collectionViews.buttons["OK"].exists {
app.alerts.collectionViews.buttons["OK"].tap()
}
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// sign in
private func signIn(user:String, password:String) {
let usernameTextField = app.textFields["Username"]
usernameTextField.tap()
usernameTextField.typeText(user)
let passwordSecureTextField = app.secureTextFields["Password"]
passwordSecureTextField.tap()
passwordSecureTextField.typeText(password)
}
// wait for element
private func evaluateElementExist(element:AnyObject) {
let exists = NSPredicate(format: "exists == 1")
expectationForPredicate(exists, evaluatedWithObject: element, handler: nil)
waitForExpectationsWithTimeout(30, handler: nil)
}
// confirm alert
private func confirmAlert(title: String, message: String) {
if app.alerts.collectionViews.buttons["OK"].exists {
let title = app.staticTexts[title]
let message = app.staticTexts[message]
evaluateElementExist(title)
evaluateElementExist(message)
app.buttons["OK"].tap()
}
}
// sign in and registration tests
func test1signInNonExistingUser() {
let signinButton = app.buttons["Sign In"]
evaluateElementExist(signinButton)
app.textFields["Username"].tap() // get app focus by tapping username if notification was confirmed
signIn("nonexistinguser", password: "password")
app.buttons["Sign In"].tap()
confirmAlert("Error!", message: "Not Authorized. Please check your credentials and try again.")
}
func test2registerExistingUser() {
signIn("serveruser", password: "password")
app.buttons["Register"].tap()
confirmAlert("Error Registering User", message: "You have tried to create a duplicate entry.")
}
func test3registerEmptyUserName() {
signIn("", password: "password")
app.buttons["Register"].tap()
confirmAlert("Error", message: "Username must be at least 5 characters in length.")
}
func test4registerEmptyPassword() {
signIn("newuser", password: "")
app.buttons["Register"].tap()
confirmAlert("Error", message: "You must provide a password")
}
func test5signInEmptyUsername() {
signIn("", password: "password")
app.buttons["Sign In"].tap()
confirmAlert("Error", message: "Username must be at least 5 characters in length.")
}
func test6signInEmptyPassword() {
signIn("newuser", password: "")
app.buttons["Sign In"].tap()
confirmAlert("Error!", message: "You must provide a password")
}
func test7registerUser() {
let findOpponentButton = app.buttons["Find Opponent"]
signIn("rpslsuser", password: "password")
app.buttons["Register"].tap()
evaluateElementExist(findOpponentButton)
XCTAssertEqual(app.staticTexts["Connected as rpslsuser"].exists, true)
}
func test8signInUser() {
let findOpponentButton = app.buttons["Find Opponent"]
signIn("rpslsuser", password: "password")
app.buttons["Sign In"].tap()
evaluateElementExist(findOpponentButton)
XCTAssertEqual(app.staticTexts["Connected as rpslsuser"].exists, true)
}
} |
//
// SignalSpec.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2015-01-23.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import LlamaKit
import Nimble
import Quick
import ReactiveCocoa
class SignalSpec: QuickSpec {
override func spec() {
describe("init") {
var testScheduler: TestScheduler!
beforeEach {
testScheduler = TestScheduler()
}
it("should run the generator immediately") {
var didRunGenerator = false
Signal<AnyObject, NoError> { observer in
didRunGenerator = true
return nil
}
expect(didRunGenerator).to(beTruthy())
}
it("should keep signal alive if not terminated") {
weak var signal: Signal<AnyObject, NoError>? = Signal.never
expect(signal).toNot(beNil())
}
it("should deallocate after erroring") {
weak var signal: Signal<AnyObject, TestError>? = Signal { observer in
testScheduler.schedule {
sendError(observer, TestError.Default)
}
return nil
}
var errored = false
signal?.observe(error: { _ in errored = true })
expect(errored).to(beFalsy())
expect(signal).toNot(beNil())
testScheduler.run()
expect(errored).to(beTruthy())
expect(signal).to(beNil())
}
it("should deallocate after completing") {
weak var signal: Signal<AnyObject, NoError>? = Signal { observer in
testScheduler.schedule {
sendCompleted(observer)
}
return nil
}
var completed = false
signal?.observe(completed: { completed = true })
expect(completed).to(beFalsy())
expect(signal).toNot(beNil())
testScheduler.run()
expect(completed).to(beTruthy())
expect(signal).to(beNil())
}
it("should forward events to observers") {
let numbers = [ 1, 2, 5 ]
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
for number in numbers {
sendNext(observer, number)
}
sendCompleted(observer)
}
return nil
}
var fromSignal: [Int] = []
var completed = false
signal.observe(next: { number in
fromSignal.append(number)
}, completed: {
completed = true
})
expect(completed).to(beFalsy())
expect(fromSignal).to(beEmpty())
testScheduler.run()
expect(completed).to(beTruthy())
expect(fromSignal).to(equal(numbers))
}
it("should dispose of returned disposable upon error") {
let disposable = SimpleDisposable()
let signal: Signal<AnyObject, TestError> = Signal { observer in
testScheduler.schedule {
sendError(observer, TestError.Default)
}
return disposable
}
var errored = false
signal.observe(error: { _ in errored = true })
expect(errored).to(beFalsy())
expect(disposable.disposed).to(beFalsy())
testScheduler.run()
expect(errored).to(beTruthy())
expect(disposable.disposed).to(beTruthy())
}
it("should dispose of returned disposable upon completion") {
let disposable = SimpleDisposable()
let signal: Signal<AnyObject, NoError> = Signal { observer in
testScheduler.schedule {
sendCompleted(observer)
}
return disposable
}
var completed = false
signal.observe(completed: { completed = true })
expect(completed).to(beFalsy())
expect(disposable.disposed).to(beFalsy())
testScheduler.run()
expect(completed).to(beTruthy())
expect(disposable.disposed).to(beTruthy())
}
}
describe("Signal.pipe") {
it("should keep signal alive if not terminated") {
weak var signal = Signal<(), NoError>.pipe().0
expect(signal).toNot(beNil())
}
pending("should deallocate after erroring") {
}
pending("should deallocate after completing") {
}
it("should forward events to observers") {
let (signal, observer) = Signal<Int, NoError>.pipe()
var fromSignal: [Int] = []
var completed = false
signal.observe(next: { number in
fromSignal.append(number)
}, completed: {
completed = true
})
expect(fromSignal).to(beEmpty())
expect(completed).to(beFalsy())
sendNext(observer, 1)
expect(fromSignal).to(equal([1]))
sendNext(observer, 2)
expect(fromSignal).to(equal([1, 2]))
expect(completed).to(beFalsy())
sendCompleted(observer)
expect(completed).to(beTruthy())
}
}
describe("observe") {
var testScheduler: TestScheduler!
beforeEach {
testScheduler = TestScheduler()
}
it("should stop forwarding events when disposed") {
let disposable = SimpleDisposable()
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
for number in [1, 2] {
sendNext(observer, number)
}
sendCompleted(observer)
sendNext(observer, 4)
}
return disposable
}
var fromSignal: [Int] = []
signal.observe(next: { number in
fromSignal.append(number)
})
expect(disposable.disposed).to(beFalsy())
expect(fromSignal).to(beEmpty())
testScheduler.run()
expect(disposable.disposed).to(beTruthy())
expect(fromSignal).to(equal([1, 2]))
}
it("should not trigger side effects") {
var runCount = 0
let signal: Signal<(), NoError> = Signal { observer in
runCount += 1
return nil
}
expect(runCount).to(equal(1))
signal.observe()
expect(runCount).to(equal(1))
}
pending("should release observer after termination") {
}
pending("should release observer after disposal") {
}
}
describe("map") {
it("should transform the values of the signal") {
let numbers = [ 1, 2, 5 ]
var testScheduler = TestScheduler()
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
for number in numbers {
sendNext(observer, number)
}
}
return nil
}
var afterMap: [Int] = []
signal
|> map { $0 * 2 }
|> observe(next: { afterMap.append($0) })
testScheduler.run()
expect(afterMap).to(equal([2, 4, 10]))
}
}
describe("filter") {
it("should omit values from the signal") {
let numbers = [ 1, 2, 4, 5 ]
var testScheduler = TestScheduler()
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
for number in numbers {
sendNext(observer, number)
}
}
return nil
}
var afterFilter: [Int] = []
signal
|> filter { $0 % 2 == 0 }
|> observe(next: { afterFilter.append($0) })
testScheduler.run()
expect(afterFilter).to(equal([2, 4]))
}
}
describe("scan") {
it("should incrementally accumulate a value") {
let numbers = [ 1, 2, 4, 5 ]
var testScheduler = TestScheduler()
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
for number in numbers {
sendNext(observer, number)
}
}
return nil
}
var scanned: [Int] = []
signal
|> scan(0) { $0 + $1 }
|> observe(next: { scanned.append($0) })
testScheduler.run()
expect(scanned).to(equal([1, 3, 7, 12]))
}
}
describe("reduce") {
it("should accumulate one value") {
let numbers = [ 1, 2, 4, 5 ]
var testScheduler = TestScheduler()
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
for number in numbers {
sendNext(observer, number)
}
sendCompleted(observer)
}
return nil
}
var result: [Int] = []
signal
|> reduce(0) { $0 + $1 }
|> observe(next: { result.append($0) })
testScheduler.run()
// using array to make sure only one value sent
expect(result).to(equal([12]))
}
it("should send the initial value if none are received") {
var testScheduler = TestScheduler()
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
sendCompleted(observer)
}
return nil
}
var result: [Int] = []
signal
|> reduce(99) { $0 + $1 }
|> observe(next: { result.append($0) })
testScheduler.run()
expect(result).to(equal([99]))
}
}
describe("skip") {
pending("should skip initial values") {
}
pending("should not skip any values when 0") {
}
}
describe("skipRepeats") {
pending("should skip duplicate Equatable values") {
}
pending("should skip values according to a predicate") {
}
}
describe("skipWhile") {
pending("should skip while the predicate is true") {
}
pending("should not skip any values when the predicate starts false") {
}
}
describe("take") {
pending("should take initial values") {
}
pending("should complete when 0") {
}
}
describe("takeUntil") {
pending("should take values until the trigger fires") {
}
pending("should complete if the trigger fires immediately") {
}
}
describe("takeUntilReplacement") {
pending("should take values from the original then the replacement") {
}
}
describe("takeWhile") {
pending("should take while the predicate is true") {
}
pending("should complete if the predicate starts false") {
}
}
describe("observeOn") {
pending("should send events on the given scheduler") {
}
}
describe("delay") {
pending("should send events on the given scheduler after the interval") {
}
pending("should schedule errors immediately") {
}
}
describe("throttle") {
pending("should send values on the given scheduler at no less than the interval") {
}
pending("should schedule errors immediately") {
}
}
describe("sampleOn") {
pending("should forward the latest value when the sampler fires") {
}
pending("should complete when both inputs have completed") {
}
}
describe("combineLatestWith") {
pending("should forward the latest values from both inputs") {
}
pending("should complete when both inputs have completed") {
}
}
describe("zipWith") {
pending("should combine pairs") {
}
pending("should complete when the shorter signal has completed") {
}
}
describe("materialize") {
pending("should reify events from the signal") {
}
}
describe("dematerialize") {
pending("should send values for Next events") {
}
pending("should error out for Error events") {
}
pending("should complete early for Completed events") {
}
}
describe("takeLast") {
pending("should send the last N values upon completion") {
}
pending("should send less than N values if not enough were received") {
}
}
describe("timeoutWithError") {
pending("should complete if within the interval") {
}
pending("should error if not completed before the interval has elapsed") {
}
}
describe("try") {
pending("should forward original values upon success") {
}
pending("should error if an attempt fails") {
}
}
describe("tryMap") {
pending("should forward mapped values upon success") {
}
pending("should error if a mapping fails") {
}
}
}
}
finished Signal.pipe tests
//
// SignalSpec.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2015-01-23.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import LlamaKit
import Nimble
import Quick
import ReactiveCocoa
class SignalSpec: QuickSpec {
override func spec() {
describe("init") {
var testScheduler: TestScheduler!
beforeEach {
testScheduler = TestScheduler()
}
it("should run the generator immediately") {
var didRunGenerator = false
Signal<AnyObject, NoError> { observer in
didRunGenerator = true
return nil
}
expect(didRunGenerator).to(beTruthy())
}
it("should keep signal alive if not terminated") {
weak var signal: Signal<AnyObject, NoError>? = Signal.never
expect(signal).toNot(beNil())
}
it("should deallocate after erroring") {
weak var signal: Signal<AnyObject, TestError>? = Signal { observer in
testScheduler.schedule {
sendError(observer, TestError.Default)
}
return nil
}
var errored = false
signal?.observe(error: { _ in errored = true })
expect(errored).to(beFalsy())
expect(signal).toNot(beNil())
testScheduler.run()
expect(errored).to(beTruthy())
expect(signal).to(beNil())
}
it("should deallocate after completing") {
weak var signal: Signal<AnyObject, NoError>? = Signal { observer in
testScheduler.schedule {
sendCompleted(observer)
}
return nil
}
var completed = false
signal?.observe(completed: { completed = true })
expect(completed).to(beFalsy())
expect(signal).toNot(beNil())
testScheduler.run()
expect(completed).to(beTruthy())
expect(signal).to(beNil())
}
it("should forward events to observers") {
let numbers = [ 1, 2, 5 ]
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
for number in numbers {
sendNext(observer, number)
}
sendCompleted(observer)
}
return nil
}
var fromSignal: [Int] = []
var completed = false
signal.observe(next: { number in
fromSignal.append(number)
}, completed: {
completed = true
})
expect(completed).to(beFalsy())
expect(fromSignal).to(beEmpty())
testScheduler.run()
expect(completed).to(beTruthy())
expect(fromSignal).to(equal(numbers))
}
it("should dispose of returned disposable upon error") {
let disposable = SimpleDisposable()
let signal: Signal<AnyObject, TestError> = Signal { observer in
testScheduler.schedule {
sendError(observer, TestError.Default)
}
return disposable
}
var errored = false
signal.observe(error: { _ in errored = true })
expect(errored).to(beFalsy())
expect(disposable.disposed).to(beFalsy())
testScheduler.run()
expect(errored).to(beTruthy())
expect(disposable.disposed).to(beTruthy())
}
it("should dispose of returned disposable upon completion") {
let disposable = SimpleDisposable()
let signal: Signal<AnyObject, NoError> = Signal { observer in
testScheduler.schedule {
sendCompleted(observer)
}
return disposable
}
var completed = false
signal.observe(completed: { completed = true })
expect(completed).to(beFalsy())
expect(disposable.disposed).to(beFalsy())
testScheduler.run()
expect(completed).to(beTruthy())
expect(disposable.disposed).to(beTruthy())
}
}
describe("Signal.pipe") {
it("should keep signal alive if not terminated") {
weak var signal = Signal<(), NoError>.pipe().0
expect(signal).toNot(beNil())
}
it("should deallocate after erroring") {
let testScheduler = TestScheduler()
weak var weakSignal: Signal<(), TestError>?
// Use an inner closure to help ARC deallocate things as we
// expect.
let test: () -> () = {
let (signal, observer) = Signal<(), TestError>.pipe()
weakSignal = signal
testScheduler.schedule {
sendError(observer, TestError.Default)
}
}
test()
expect(weakSignal).toNot(beNil())
testScheduler.run()
expect(weakSignal).to(beNil())
}
it("should deallocate after completing") {
let testScheduler = TestScheduler()
weak var weakSignal: Signal<(), TestError>?
// Use an inner closure to help ARC deallocate things as we
// expect.
let test: () -> () = {
let (signal, observer) = Signal<(), TestError>.pipe()
weakSignal = signal
testScheduler.schedule {
sendCompleted(observer)
}
}
test()
expect(weakSignal).toNot(beNil())
testScheduler.run()
expect(weakSignal).to(beNil())
}
it("should forward events to observers") {
let (signal, observer) = Signal<Int, NoError>.pipe()
var fromSignal: [Int] = []
var completed = false
signal.observe(next: { number in
fromSignal.append(number)
}, completed: {
completed = true
})
expect(fromSignal).to(beEmpty())
expect(completed).to(beFalsy())
sendNext(observer, 1)
expect(fromSignal).to(equal([1]))
sendNext(observer, 2)
expect(fromSignal).to(equal([1, 2]))
expect(completed).to(beFalsy())
sendCompleted(observer)
expect(completed).to(beTruthy())
}
}
describe("observe") {
var testScheduler: TestScheduler!
beforeEach {
testScheduler = TestScheduler()
}
it("should stop forwarding events when disposed") {
let disposable = SimpleDisposable()
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
for number in [1, 2] {
sendNext(observer, number)
}
sendCompleted(observer)
sendNext(observer, 4)
}
return disposable
}
var fromSignal: [Int] = []
signal.observe(next: { number in
fromSignal.append(number)
})
expect(disposable.disposed).to(beFalsy())
expect(fromSignal).to(beEmpty())
testScheduler.run()
expect(disposable.disposed).to(beTruthy())
expect(fromSignal).to(equal([1, 2]))
}
it("should not trigger side effects") {
var runCount = 0
let signal: Signal<(), NoError> = Signal { observer in
runCount += 1
return nil
}
expect(runCount).to(equal(1))
signal.observe()
expect(runCount).to(equal(1))
}
pending("should release observer after termination") {
}
pending("should release observer after disposal") {
}
}
describe("map") {
it("should transform the values of the signal") {
let numbers = [ 1, 2, 5 ]
var testScheduler = TestScheduler()
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
for number in numbers {
sendNext(observer, number)
}
}
return nil
}
var afterMap: [Int] = []
signal
|> map { $0 * 2 }
|> observe(next: { afterMap.append($0) })
testScheduler.run()
expect(afterMap).to(equal([2, 4, 10]))
}
}
describe("filter") {
it("should omit values from the signal") {
let numbers = [ 1, 2, 4, 5 ]
var testScheduler = TestScheduler()
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
for number in numbers {
sendNext(observer, number)
}
}
return nil
}
var afterFilter: [Int] = []
signal
|> filter { $0 % 2 == 0 }
|> observe(next: { afterFilter.append($0) })
testScheduler.run()
expect(afterFilter).to(equal([2, 4]))
}
}
describe("scan") {
it("should incrementally accumulate a value") {
let numbers = [ 1, 2, 4, 5 ]
var testScheduler = TestScheduler()
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
for number in numbers {
sendNext(observer, number)
}
}
return nil
}
var scanned: [Int] = []
signal
|> scan(0) { $0 + $1 }
|> observe(next: { scanned.append($0) })
testScheduler.run()
expect(scanned).to(equal([1, 3, 7, 12]))
}
}
describe("reduce") {
it("should accumulate one value") {
let numbers = [ 1, 2, 4, 5 ]
var testScheduler = TestScheduler()
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
for number in numbers {
sendNext(observer, number)
}
sendCompleted(observer)
}
return nil
}
var result: [Int] = []
signal
|> reduce(0) { $0 + $1 }
|> observe(next: { result.append($0) })
testScheduler.run()
// using array to make sure only one value sent
expect(result).to(equal([12]))
}
it("should send the initial value if none are received") {
var testScheduler = TestScheduler()
let signal: Signal<Int, NoError> = Signal { observer in
testScheduler.schedule {
sendCompleted(observer)
}
return nil
}
var result: [Int] = []
signal
|> reduce(99) { $0 + $1 }
|> observe(next: { result.append($0) })
testScheduler.run()
expect(result).to(equal([99]))
}
}
describe("skip") {
pending("should skip initial values") {
}
pending("should not skip any values when 0") {
}
}
describe("skipRepeats") {
pending("should skip duplicate Equatable values") {
}
pending("should skip values according to a predicate") {
}
}
describe("skipWhile") {
pending("should skip while the predicate is true") {
}
pending("should not skip any values when the predicate starts false") {
}
}
describe("take") {
pending("should take initial values") {
}
pending("should complete when 0") {
}
}
describe("takeUntil") {
pending("should take values until the trigger fires") {
}
pending("should complete if the trigger fires immediately") {
}
}
describe("takeUntilReplacement") {
pending("should take values from the original then the replacement") {
}
}
describe("takeWhile") {
pending("should take while the predicate is true") {
}
pending("should complete if the predicate starts false") {
}
}
describe("observeOn") {
pending("should send events on the given scheduler") {
}
}
describe("delay") {
pending("should send events on the given scheduler after the interval") {
}
pending("should schedule errors immediately") {
}
}
describe("throttle") {
pending("should send values on the given scheduler at no less than the interval") {
}
pending("should schedule errors immediately") {
}
}
describe("sampleOn") {
pending("should forward the latest value when the sampler fires") {
}
pending("should complete when both inputs have completed") {
}
}
describe("combineLatestWith") {
pending("should forward the latest values from both inputs") {
}
pending("should complete when both inputs have completed") {
}
}
describe("zipWith") {
pending("should combine pairs") {
}
pending("should complete when the shorter signal has completed") {
}
}
describe("materialize") {
pending("should reify events from the signal") {
}
}
describe("dematerialize") {
pending("should send values for Next events") {
}
pending("should error out for Error events") {
}
pending("should complete early for Completed events") {
}
}
describe("takeLast") {
pending("should send the last N values upon completion") {
}
pending("should send less than N values if not enough were received") {
}
}
describe("timeoutWithError") {
pending("should complete if within the interval") {
}
pending("should error if not completed before the interval has elapsed") {
}
}
describe("try") {
pending("should forward original values upon success") {
}
pending("should error if an attempt fails") {
}
}
describe("tryMap") {
pending("should forward mapped values upon success") {
}
pending("should error if a mapping fails") {
}
}
}
}
|
import UIKit
class VSpinner:UIImageView
{
private let kAnimationDuration:TimeInterval = 1
init()
{
super.init(frame:CGRect.zero)
let images:[UIImage] = [
#imageLiteral(resourceName: "assetSpinner0")]
isUserInteractionEnabled = false
translatesAutoresizingMaskIntoConstraints = false
clipsToBounds = true
animationDuration = kAnimationDuration
animationImages = images
contentMode = UIViewContentMode.center
startAnimating()
}
required init?(coder:NSCoder)
{
return nil
}
}
Update spinner view
import UIKit
class VSpinner:UIImageView
{
private let kAnimationDuration:TimeInterval = 1
init()
{
super.init(frame:CGRect.zero)
let images:[UIImage] = [
#imageLiteral(resourceName: "assetSpinner0"),
#imageLiteral(resourceName: "assetSpinner1"),
#imageLiteral(resourceName: "assetSpinner2"),
#imageLiteral(resourceName: "assetSpinner3"),
#imageLiteral(resourceName: "assetSpinner4"),
#imageLiteral(resourceName: "assetSpinner5"),
#imageLiteral(resourceName: "assetSpinner6"),
#imageLiteral(resourceName: "assetSpinner7"),
#imageLiteral(resourceName: "assetSpinner8")]
isUserInteractionEnabled = false
translatesAutoresizingMaskIntoConstraints = false
clipsToBounds = true
animationDuration = kAnimationDuration
animationImages = images
contentMode = UIViewContentMode.center
startAnimating()
}
required init?(coder:NSCoder)
{
return nil
}
}
|
import Foundation
final class MVitaPtpMessageIn
{
}
Remove final modifier
import Foundation
class MVitaPtpMessageIn
{
}
|
import Foundation
import XmlHero
final class MVitaXmlThumbnail
{
//MARK: private
private init() { }
private class func findThumbnail(
item:DVitaItemDirectory) -> Data?
{
guard
let elements:[DVitaItemElement] = item.elements?.array as? [
DVitaItemElement],
let thumbnail:DVitaItemElement = findSmallerImage(
elements:elements),
let data:Data = MVitaLink.elementData(
element:thumbnail)
else
{
return nil
}
return data
}
private class func findSmallerImage(
elements:[DVitaItemElement]) -> DVitaItemElement?
{
var smaller:DVitaItemElement?
for element:DVitaItemElement in elements
{
guard
element.fileExtension == MVitaItemInExtension.png
else
{
continue
}
guard
let currentSmaller:DVitaItemElement = smaller,
element.size > currentSmaller.size
else
{
smaller = element
continue
}
}
return smaller
}
//MARK: internal
class func factoryMetadata(
item:DVitaItemDirectory,
completion:@escaping((Data?) -> ()))
{
}
}
Look for pngs on directory
import Foundation
import XmlHero
final class MVitaXmlThumbnail
{
//MARK: private
private init() { }
private class func findThumbnail(
item:DVitaItemDirectory) -> Data?
{
guard
let pngs:[DVitaItemElementPng] = item.png?.array as? [
DVitaItemElementPng],
let thumbnail:DVitaItemElement = findSmallerImage(
pngs:pngs),
let data:Data = MVitaLink.elementData(
element:thumbnail)
else
{
return nil
}
return data
}
private class func findSmallerImage(
pngs:[DVitaItemElementPng]) -> DVitaItemElement?
{
var smaller:DVitaItemElement?
for png:DVitaItemElement in pngs
{
guard
let currentSmaller:DVitaItemElement = smaller,
png.size > currentSmaller.size
else
{
smaller = png
continue
}
}
return smaller
}
//MARK: internal
class func factoryMetadata(
item:DVitaItemDirectory,
completion:@escaping((Data?) -> ()))
{
}
}
|
/*
NanoSocket.swift
Copyright (c) 2016 Stephen Whittle All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
import Foundation
import CNanoMessage
import ISFLibrary
/// A NanoMessage base socket.
public class NanoSocket {
/// The raw nanomsg socket file descriptor.
public private(set) var socketFd: CInt = -1
/// A set of `EndPoint` structures that the socket is attached to either locally or remotly.
public fileprivate(set) var endPoints = Set<EndPoint>()
private var _closureAttempts: Int = 100
/// The number of attempts to close down a socket or endpoint, this is clamped to between 1 and 1000.
///
/// - Note: The `getLinger()` function is called to determine the number of milliseconds to
/// wait for a socket/endpoint to clear and close, this is divided by `closureAttempts`
/// to determine the minimum pause between each attempt.
public var closureAttempts: Int {
get {
return self._closureAttempts
}
set (attempts) {
self._closureAttempts = clamp(value: attempts, lower: 1, upper: 1000)
}
}
/// Determine if when de-referencing the socket we are going to keep attempting to close the socket until successful.
///
/// - Warning: Please not that if true this will block until the class has been de-referenced.
public var blockTillCloseSuccess = false
/// Creates a nanomsg socket with the specified socketDomain and socketProtocol.
///
/// - Parameters:
/// - socketDomain: The sockets Domain.
/// - socketProtocol: The sockets Protocol.
///
/// - Throws: `NanoMessageError.NanoSocket` if the nanomsg socket has failed to be created
public init(socketDomain: SocketDomain, socketProtocol: SocketProtocol) throws {
self.socketFd = nn_socket(socketDomain.rawValue, socketProtocol.rawValue)
guard (self.socketFd >= 0) else {
throw NanoMessageError.NanoSocket(code: nn_errno())
}
}
deinit {
func closeSocket() throws {
if (self.socketFd >= 0) { // if we have a valid nanomsg socket file descriptor then...
var loopCount = 0
while (true) {
let returnCode = nn_close(self.socketFd) // try and close the nanomsg socket
if (returnCode < 0) { // if `nn_close()` failed then...
let errno = nn_errno()
if (errno == EINTR) { // if we were interrupted by a signal, reattempt is allowed by the native library
if (loopCount >= self.closureAttempts) { // we've reached our limit so say we were interrupted
throw NanoMessageError.Interrupted
}
} else {
throw NanoMessageError.Close(code: errno)
}
usleep(self._closureDelay) // zzzz...
loopCount += 1
} else {
break // we've closed the socket succesfully
}
}
}
}
// are we going to terminate the `repeat` loop below.
var terminateLoop = true
repeat {
do {
try closeSocket()
} catch NanoMessageError.Interrupted {
print("NanoSocket.deinit(): \(NanoMessageError.Interrupted))")
if (self.blockTillCloseSuccess) {
terminateLoop = false
}
} catch let error as NanoMessageError {
print(error)
terminateLoop = true
} catch {
print("an unexpected error '\(error)' has occured in the library libNanoMessage.")
terminateLoop = true
}
} while (!terminateLoop)
}
/// Get the time in milliseconds to allow to attempt to close a socket or endpoint.
///
/// - Returns: The closure time in microseconds.
fileprivate var _closureDelay: UInt32 {
var milliseconds = 1000
if let linger = try? self.getLinger() {
if (linger > 0) { // account for infinate linger timeout.
milliseconds = linger
}
}
return UInt32((milliseconds * 1000) / self.closureAttempts)
}
}
extension NanoSocket {
/// Get socket priorites (receive/send)
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: Tuple of receive and send send priorities, if either is nil then
/// socket is either not a receiver or sender.
private func _socketPriorities() throws -> (receivePriority: Int?, sendPriority: Int?) {
var receivePriority: Int?
var sendPriority: Int?
if let _: Int = try? getSocketOption(socketFd, .ReceiveFd) { // if this is a receiver socket then...
receivePriority = try getSocketOption(self.socketFd, .ReceivePriority) // obtain the receive priority for the end-point.
}
if let _: Int = try? getSocketOption(socketFd, .SendFd) { // if this is a sender socket then...
sendPriority = try getSocketOption(self.socketFd, .SendPriority) // obtain the send priority for the end-point.
}
return (receivePriority, sendPriority)
}
/// Adds a local endpoint to the socket. The endpoint can be then used by other applications to connect to.
///
/// - Parameters:
/// - endPointAddress: Consists of two parts as follows: transport://address. The transport specifies the
/// underlying transport protocol to use. The meaning of the address part is specific
/// to the underlying transport protocol.
/// - endPointName: An optional endpoint name.
///
/// - Throws: `NanoMessageError.BindToAddress` if there was a problem binding the socket to the address.
/// `NanoMessageError.GetSocketOption`
///
/// - Returns: An endpoint that has just been binded too. The endpoint can be later used to remove the
/// endpoint from the socket via `removeEndPoint()` function.
///
/// - Note: Note that `bindToAddress()` may be called multiple times on the same socket thus allowing the
/// socket to communicate with multiple heterogeneous endpoints.
public func bindToAddress(_ endPointAddress: String, endPointName: String = "") throws -> EndPoint {
var endPointId: CInt = -1
let socket: (receivePriority: Int?, sendPriority: Int?) = try _socketPriorities()
endPointAddress.withCString {
endPointId = nn_bind(self.socketFd, $0)
}
guard (endPointId >= 0) else {
throw NanoMessageError.BindToAddress(code: nn_errno(), address: endPointAddress)
}
let endPoint = EndPoint(endPointId: Int(endPointId),
endPointAddress: endPointAddress,
connectionType: .BindToAddress,
receivePriority: socket.receivePriority,
sendPriority: socket.sendPriority,
endPointName: endPointName)
self.endPoints.insert(endPoint)
return endPoint
}
/// Adds a local endpoint to the socket. The endpoint can be then used by other applications to connect to.
///
/// - Parameters:
/// - endPointAddress: Consists of two parts as follows: transport://address. The transport specifies the
/// underlying transport protocol to use. The meaning of the address part is specific
/// to the underlying transport protocol.
/// - endPointName: An optional endpoint name.
///
/// - Throws: `NanoMessageError.BindToAddress` if there was a problem binding the socket to the address.
/// `NanoMessageError.GetSocketOption`
///
/// - Returns: An endpoint ID is returned. The endpoint ID can be later used to remove the endpoint from
/// the socket via `removeEndPoint()` function.
///
/// - Note: Note that `bindToAddress()` may be called multiple times on the same socket thus allowing the
/// socket to communicate with multiple heterogeneous endpoints.
public func bindToAddress(_ endPointAddress: String, endPointName: String = "") throws -> Int {
let endPoint: EndPoint = try self.bindToAddress(endPointAddress, endPointName: endPointName)
return endPoint.id
}
/// Adds a remote endpoint to the socket. The library would then try to connect to the specified remote endpoint.
///
/// - Parameters:
/// - endPointAddress: Consists of two parts as follows: transport://address. The transport specifies the
/// underlying transport protocol to use. The meaning of the address part is specific
/// to the underlying transport protocol.
/// - endPointName: An optional endpoint name.
///
/// - Throws: `NanoMessageError.ConnectToAddress` if there was a problem binding the socket to the address.
/// `NanoMessageError.GetSocketOption`
///
/// - Returns: The endpoint that has just been connected too. The endpoint can be later used to remove the
/// endpoint from the socket via `removeEndPoint()` function.
///
/// - Note: Note that `connectToAddress()` may be called multiple times on the same socket thus allowing the
/// socket to communicate with multiple heterogeneous endpoints.
public func connectToAddress(_ endPointAddress: String, endPointName: String = "") throws -> EndPoint {
var endPointId: CInt = -1
let socket: (receivePriority: Int?, sendPriority: Int?) = try _socketPriorities()
endPointAddress.withCString {
endPointId = nn_connect(self.socketFd, $0)
}
guard (endPointId >= 0) else {
throw NanoMessageError.ConnectToAddress(code: nn_errno(), address: endPointAddress)
}
let endPoint = EndPoint(endPointId: Int(endPointId),
endPointAddress: endPointAddress,
connectionType: .ConnectToAddress,
receivePriority: socket.receivePriority,
sendPriority: socket.sendPriority,
endPointName: endPointName)
self.endPoints.insert(endPoint)
return endPoint
}
/// Adds a remote endpoint to the socket. The library would then try to connect to the specified remote endpoint.
///
/// - Parameters:
/// - endPointAddress: Consists of two parts as follows: transport://address. The transport specifies the
/// underlying transport protocol to use. The meaning of the address part is specific
/// to the underlying transport protocol.
/// - endPointName: An optional endpoint name.
///
/// - Throws: `NanoMessageError.ConnectToAddress` if there was a problem binding the socket to the address.
/// `NanoMessageError.GetSocketOption`
///
/// - Returns: An endpoint ID is returned. The endpoint ID can be later used to remove the endpoint from the
/// socket via the `removeEndPoint()` function.
///
/// - Note: Note that `connectToAddress()` may be called multiple times on the same socket thus allowing the
/// socket to communicate with multiple heterogeneous endpoints.
public func connectToAddress(_ endPointAddress: String, endPointName: String = "") throws -> Int {
let endPoint: EndPoint = try self.connectToAddress(endPointAddress, endPointName: endPointName)
return endPoint.id
}
/// Remove an endpoint from the socket.
///
/// - Parameters:
/// - endPoint: An endpoint.
///
/// - Throws: `NanoMessageError.RemoveEndPoint` if the endpoint failed to be removed,
/// `NanoMessageError.Interrupted` if the endpoint removal was interrupted.
///
/// - Returns: If the endpoint was removed, false indicates that the endpoint was not attached to the socket.
@discardableResult
public func removeEndPoint(_ endPoint: EndPoint) throws -> Bool {
if (self.endPoints.contains(endPoint)) {
var loopCount = 0
while (true) {
let returnCode = nn_shutdown(self.socketFd, CInt(endPoint.id)) // attempt to close down the endpoint
if (returnCode < 0) { // if `nn_shutdown()` failed then...
let errno = nn_errno()
if (errno == EINTR) { // if we were interrupted by a signal, reattempt is allowed by the native library
if (loopCount >= self.closureAttempts) {
throw NanoMessageError.Interrupted
}
usleep(self._closureDelay) // zzzz...
loopCount += 1
} else {
throw NanoMessageError.RemoveEndPoint(code: errno, address: endPoint.address, endPointId: endPoint.id)
}
} else {
break // we've closed the endpoint succesfully
}
}
self.endPoints.remove(endPoint)
return true
}
return false
}
/// Remove an endpoint from the socket.
///
/// - Parameters:
/// - endPoint: An endpoint.
///
/// - Throws: `NanoMessageError.RemoveEndPoint` if the endpoint failed to be removed,
/// `NanoMessageError.Interrupted` if the endpoint removal was interrupted.
///
/// - Returns: If the endpoint was removed, false indicates that the endpoint was not attached to the socket.
@discardableResult
public func removeEndPoint(_ endPointId: Int) throws -> Bool {
for endPoint in self.endPoints {
if (endPointId == endPoint.id) {
return try self.removeEndPoint(endPoint)
}
}
return false
}
/// Check a socket and reports whether it’s possible to send a message to the socket and/or receive a message from the socket.
///
/// - Parameters:
/// - timeout milliseconds: The maximum number of milliseconds to poll the socket for an event to occur,
/// default is 1000 milliseconds (1 second).
///
/// - Throws: `NanoMessageError.PollSocket` if polling the socket fails.
///
/// - Returns: Message waiting and send queue blocked as a tuple of bools.
public func pollSocket(timeout milliseconds: Int = 1000) throws -> (messageIsWaiting: Bool, sendIsBlocked: Bool) {
let pollinMask = CShort(NN_POLLIN) // define nn_poll event masks as short's so we only
let polloutMask = CShort(NN_POLLOUT) // cast once in the function
var eventMask = CShort.allZeros //
if let _: Int = try? getSocketOption(self.socketFd, .ReceiveFd) { // rely on the fact that getting the for example receive
eventMask = pollinMask // file descriptor for a socket type that does not support
} // receiving will throw a nil return value to determine
if let _: Int = try? getSocketOption(self.socketFd, .SendFd) { // what our polling event mask will be.
eventMask = eventMask | polloutMask //
} //
var pfd = nn_pollfd(fd: self.socketFd, events: eventMask, revents: 0) // define the pollfd struct for this socket
let returnCode = nn_poll(&pfd, 1, CInt(milliseconds)) // poll the nano socket
guard (returnCode >= 0) else {
throw NanoMessageError.PollSocket(code: nn_errno())
}
let messageIsWaiting = ((pfd.revents & pollinMask) != 0) ? true : false // using the event masks determine our return values
let sendIsBlocked = ((pfd.revents & polloutMask) != 0) ? true : false //
return (messageIsWaiting, sendIsBlocked)
}
/// Starts a device to bind the socket to another and forward messages between two sockets
///
/// - Parameters:
/// - nanoSocket: The socket to bind too.
///
/// - Throws: `NanoMessageError.BindToSocket` if a problem has been encountered.
public func bindToSocket(_ nanoSocket: NanoSocket) throws {
let returnCode = nn_device(self.socketFd, nanoSocket.socketFd)
guard (returnCode >= 0) else {
throw NanoMessageError.BindToSocket(code: nn_errno())
}
}
/// Starts a 'loopback' on the socket, it loops and sends any messages received from the socket back to itself.
///
/// - Throws: `NanoMessageError.BindToSocket` if a problem has been encountered.
public func loopBack() throws {
let returnCode = nn_device(self.socketFd, -1)
guard (returnCode >= 0) else {
throw NanoMessageError.LoopBack(code: nn_errno())
}
}
}
extension NanoSocket {
/// Get the domain of the socket as it was created with.
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The sockets domain.
public func getSocketDomain() throws -> SocketDomain {
return SocketDomain(rawValue: try getSocketOption(self.socketFd, .Domain))!
}
/// Get the protocol of the socket as it was created with.
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The sockets protocol.
public func getSocketProtocol() throws -> SocketProtocol {
return SocketProtocol(rawValue: try getSocketOption(self.socketFd, .Protocol))!
}
/// Get the protocol family of the socket as it was created with.
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The sockets protocol family.
public func getSocketProtocolFamily() throws -> ProtocolFamily {
return ProtocolFamily(rawValue: try self.getSocketProtocol())
}
/// Specifies how long the socket should try to send pending outbound messages after the socket
/// has been de-referenced, in milliseconds. A Negative value means infinite linger.
///
/// Default value is 1000 milliseconds (1 second).
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The linger time on the socket.
///
/// - Note: The nanomsg library no longer supports setting the linger option, linger time will
/// therefore always it's default value.
public func getLinger() throws -> Int {
return try getSocketOption(self.socketFd, .Linger)
}
/// Specifies how long the socket should try to send pending outbound messages after the socket
/// has been de-referenced, in milliseconds. A Negative value means infinite linger.
///
/// - Parameters:
/// - milliseconds: The linger time in milliseconds.
///
/// - Throws: `NanoMessageError.SetSocketOption`
///
/// - Note: The nanomsg library no longer supports this feature, linger time is always it's default value.
@available(*, unavailable, message: "nanomsg library no longer supports this feature")
public func setLinger(milliseconds: Int) throws {
try setSocketOption(self.socketFd, .Linger, milliseconds)
}
/// For connection-based transports such as TCP, this specifies how long to wait, in milliseconds,
/// when connection is broken before trying to re-establish it. Note that actual reconnect interval
/// may be randomised to some extent to prevent severe reconnection storms.
///
/// Default value is 100 milliseconds (0.1 second).
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The sockets reconnect interval.
public func getReconnectInterval() throws -> UInt {
return try getSocketOption(self.socketFd, .ReconnectInterval)
}
/// For connection-based transports such as TCP, this specifies how long to wait, in milliseconds,
/// when connection is broken before trying to re-establish it. Note that actual reconnect interval
/// may be randomised to some extent to prevent severe reconnection storms.
///
/// - Parameters:
/// - milliseconds: The reconnection interval in milliseconds.
///
/// - Throws: `NanoMessageError.SetSocketOption`
public func setReconnectInterval(milliseconds: UInt) throws {
try setSocketOption(self.socketFd, .ReconnectInterval, milliseconds)
}
/// This is to be used only in addition to `set/getReconnectInterval()`. It specifies maximum reconnection
/// interval. On each reconnect attempt, the previous interval is doubled until `getReconnectIntervalMax()`
/// is reached. Value of zero means that no exponential backoff is performed and reconnect interval is based
/// only on `getReconnectInterval()`.
/// If `getReconnectIntervalMax()` is less than `getReconnectInterval()`, it is ignored.
///
/// Default value is 0 milliseconds (0 seconds).
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The sockets reconnect maximum interval.
public func getReconnectIntervalMaximum() throws -> UInt {
return try getSocketOption(self.socketFd, .ReconnectIntervalMaximum)
}
/// This is to be used only in addition to `set/getReconnectInterval()`. It specifies maximum reconnection
/// interval. On each reconnect attempt, the previous interval is doubled until `getReconnectIntervalMax()`
/// is reached. Value of zero means that no exponential backoff is performed and reconnect interval is based
/// only on `getReconnectInterval()`.
/// If `getReconnectIntervalMax()` is less than `getReconnectInterval()`, it is ignored.
///
/// - Parameters:
/// - milliseconds: The reconnection maximum interval in milliseconds.
///
/// - Throws: `NanoMessageError.SetSocketOption`
public func setReconnectIntervalMaximum(milliseconds: UInt) throws {
try setSocketOption(self.socketFd, .ReconnectIntervalMaximum, milliseconds)
}
/// Socket name for error reporting and statistics.
///
/// Default value is "N" where N is socket file descriptor.
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The sockets name.
///
/// - Note: This feature is deamed as experimental by the nanomsg library.
public func getSocketName() throws -> String {
return try getSocketOption(self.socketFd, .SocketName)
}
/// Socket name for error reporting and statistics.
///
/// - Parameters:
/// - socketName: Name of the socket.
///
/// - Throws: `NanoMessageError.SetSocketOption`
///
/// - Note: This feature is deamed as experimental by the nanomsg library.
public func setSocketName(_ socketName: String) throws {
try setSocketOption(self.socketFd, .SocketName, socketName)
}
/// If true, only IPv4 addresses are used. If false, both IPv4 and IPv6 addresses are used.
///
/// Default value is true.
///
/// - Returns: The IP4v4/Ipv6 type.
///
/// - Throws: `NanoMessageError.GetSocketOption`
public func getIPv4Only() throws -> Bool {
return try getSocketOption(self.socketFd, .IPv4Only)
}
/// If true, only IPv4 addresses are used. If false, both IPv4 and IPv6 addresses are used.
///
/// - Parameters:
/// - ip4Only: Use IPv4 or IPv4 and IPv6.
///
/// - Throws: `NanoMessageError.SetSocketOption`
public func setIPv4Only(_ ip4Only: Bool) throws {
try setSocketOption(self.socketFd, .IPv4Only, ip4Only)
}
/// The maximum number of "hops" a message can go through before it is dropped. Each time the
/// message is received (for example via the `bindToSocket()` function) counts as a single hop.
/// This provides a form of protection against inadvertent loops.
///
/// - Returns: The number of hops before a message is dropped.
///
/// - Throws: `NanoMessageError.GetSocketOption`
public func getMaxTTL() throws -> Int {
return try getSocketOption(self.socketFd, .MaxTTL)
}
/// The maximum number of "hops" a message can go through before it is dropped. Each time the
/// message is received (for example via the `bindToSocket()` function) counts as a single hop.
/// This provides a form of protection against inadvertent loops.
///
/// - Parameters:
/// - hops: The number of hops before a message is dropped.
///
/// - Throws: `NanoMessageError.SetSocketOption`
public func setMaxTTL(hops: Int) throws {
try setSocketOption(self.socketFd, .MaxTTL, hops)
}
/// When true, disables Nagle’s algorithm. It also disables delaying of TCP acknowledgments.
/// Using this option improves latency at the expense of throughput.
///
/// Default value is false.
///
/// - Returns: Is Nagele's algorithm enabled.
///
/// - Throws: `NanoMessageError.GetSocketOption`
public func getTCPNoDelay(transportMechanism: TransportMechanism = .TCP) throws -> Bool {
let valueReturned: CInt = try getSocketOption(self.socketFd, .TCPNoDelay, transportMechanism)
return (valueReturned == NN_TCP_NODELAY) ? true : false
}
/// When true, disables Nagle’s algorithm. It also disables delaying of TCP acknowledgments.
/// Using this option improves latency at the expense of throughput.
///
/// - Parameters:
/// - disableNagles: Disable or enable Nagle's algorithm.
///
/// - Throws: `NanoMessageError.SetSocketOption`
public func setTCPNoDelay(disableNagles: Bool, transportMechanism: TransportMechanism = .TCP) throws {
let valueToSet: CInt = (disableNagles) ? NN_TCP_NODELAY : 0
try setSocketOption(self.socketFd, .TCPNoDelay, valueToSet, transportMechanism)
}
/// This value determines whether data messages are sent as WebSocket text frames, or binary frames,
/// per RFC 6455. Text frames should contain only valid UTF-8 text in their payload, or they will be
/// rejected. Binary frames may contain any data. Not all WebSocket implementations support binary frames.
///
/// The default is to send binary frames.
///
/// - Returns: The web sockets message type.
///
/// - Throws: `NanoMessageError.GetSocketOption`
public func getWebSocketMessageType() throws -> WebSocketMessageType {
return WebSocketMessageType(rawValue: try getSocketOption(self.socketFd, .WebSocketMessageType, .WebSocket))
}
/// This value determines whether data messages are sent as WebSocket text frames, or binary frames,
/// per RFC 6455. Text frames should contain only valid UTF-8 text in their payload, or they will be
/// rejected. Binary frames may contain any data. Not all WebSocket implementations support binary frames.
///
/// - Parameters:
/// - type: Define the web socket message type.
///
/// - Throws: `NanoMessageError.SetSocketOption`
public func setWebSocketMessageType(_ type: WebSocketMessageType) throws {
try setSocketOption(self.socketFd, .WebSocketMessageType, type, .WebSocket)
}
}
extension NanoSocket {
/// The number of connections successfully established that were initiated from this socket.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getEstablishedConnections() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .EstablishedConnections)
}
/// The number of connections successfully established that were accepted by this socket.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getAcceptedConnections() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .AcceptedConnections)
}
/// The number of established connections that were dropped by this socket.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getDroppedConnections() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .DroppedConnections)
}
/// The number of established connections that were closed by this socket, typically due to protocol errors.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getBrokenConnections() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .BrokenConnections)
}
/// The number of errors encountered by this socket trying to connect to a remote peer.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getConnectErrors() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .ConnectErrors)
}
/// The number of errors encountered by this socket trying to bind to a local address.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getBindErrors() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .BindErrors)
}
/// The number of errors encountered by this socket trying to accept a a connection from a remote peer.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getAcceptErrors() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .AcceptErrors)
}
/// The number of connections currently estabalished to this socket.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getCurrentConnections() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .CurrentConnections)
}
}
improved socket/end-point closures (comments corrected)
/*
NanoSocket.swift
Copyright (c) 2016 Stephen Whittle All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
import Foundation
import CNanoMessage
import ISFLibrary
/// A NanoMessage base socket.
public class NanoSocket {
/// The raw nanomsg socket file descriptor.
public private(set) var socketFd: CInt = -1
/// A set of `EndPoint` structures that the socket is attached to either locally or remotly.
public fileprivate(set) var endPoints = Set<EndPoint>()
private var _closureAttempts: Int = 100
/// The number of attempts to close down a socket or endpoint, this is clamped to between 1 and 1000.
///
/// - Note: The `getLinger()` function is called to determine the number of milliseconds to
/// wait for a socket/endpoint to clear and close, this is divided by `closureAttempts`
/// to determine the minimum pause between each attempt.
public var closureAttempts: Int {
get {
return self._closureAttempts
}
set (attempts) {
self._closureAttempts = clamp(value: attempts, lower: 1, upper: 1000)
}
}
/// The socket/end-point closure time in microseconds.
fileprivate var _closureDelay: UInt32 {
var milliseconds = 1000
if let linger = try? self.getLinger() {
if (linger > 0) { // account for infinate linger timeout.
milliseconds = linger
}
}
return UInt32((milliseconds * 1000) / self.closureAttempts)
}
/// Determine if when de-referencing the socket we are going to keep attempting to close the socket until successful.
///
/// - Warning: Please not that if true this will block until the class has been de-referenced.
public var blockTillCloseSuccess = false
/// Creates a nanomsg socket with the specified socketDomain and socketProtocol.
///
/// - Parameters:
/// - socketDomain: The sockets Domain.
/// - socketProtocol: The sockets Protocol.
///
/// - Throws: `NanoMessageError.NanoSocket` if the nanomsg socket has failed to be created
public init(socketDomain: SocketDomain, socketProtocol: SocketProtocol) throws {
self.socketFd = nn_socket(socketDomain.rawValue, socketProtocol.rawValue)
guard (self.socketFd >= 0) else {
throw NanoMessageError.NanoSocket(code: nn_errno())
}
}
deinit {
func closeSocket() throws {
if (self.socketFd >= 0) { // if we have a valid nanomsg socket file descriptor then...
var loopCount = 0
while (true) {
let returnCode = nn_close(self.socketFd) // try and close the nanomsg socket
if (returnCode < 0) { // if `nn_close()` failed then...
let errno = nn_errno()
if (errno == EINTR) { // if we were interrupted by a signal, reattempt is allowed by the native library
if (loopCount >= self.closureAttempts) { // we've reached our limit so say we were interrupted
throw NanoMessageError.Interrupted
}
} else {
throw NanoMessageError.Close(code: errno)
}
usleep(self._closureDelay) // zzzz...
loopCount += 1
} else {
break // we've closed the socket succesfully
}
}
}
}
// are we going to terminate the `repeat` loop below.
var terminateLoop = true
repeat {
do {
try closeSocket()
} catch NanoMessageError.Interrupted {
print("NanoSocket.deinit(): \(NanoMessageError.Interrupted))")
if (self.blockTillCloseSuccess) {
terminateLoop = false
}
} catch let error as NanoMessageError {
print(error)
terminateLoop = true
} catch {
print("an unexpected error '\(error)' has occured in the library libNanoMessage.")
terminateLoop = true
}
} while (!terminateLoop)
}
}
extension NanoSocket {
/// Get socket priorites (receive/send)
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: Tuple of receive and send send priorities, if either is nil then
/// socket is either not a receiver or sender.
private func _socketPriorities() throws -> (receivePriority: Int?, sendPriority: Int?) {
var receivePriority: Int?
var sendPriority: Int?
if let _: Int = try? getSocketOption(socketFd, .ReceiveFd) { // if this is a receiver socket then...
receivePriority = try getSocketOption(self.socketFd, .ReceivePriority) // obtain the receive priority for the end-point.
}
if let _: Int = try? getSocketOption(socketFd, .SendFd) { // if this is a sender socket then...
sendPriority = try getSocketOption(self.socketFd, .SendPriority) // obtain the send priority for the end-point.
}
return (receivePriority, sendPriority)
}
/// Adds a local endpoint to the socket. The endpoint can be then used by other applications to connect to.
///
/// - Parameters:
/// - endPointAddress: Consists of two parts as follows: transport://address. The transport specifies the
/// underlying transport protocol to use. The meaning of the address part is specific
/// to the underlying transport protocol.
/// - endPointName: An optional endpoint name.
///
/// - Throws: `NanoMessageError.BindToAddress` if there was a problem binding the socket to the address.
/// `NanoMessageError.GetSocketOption`
///
/// - Returns: An endpoint that has just been binded too. The endpoint can be later used to remove the
/// endpoint from the socket via `removeEndPoint()` function.
///
/// - Note: Note that `bindToAddress()` may be called multiple times on the same socket thus allowing the
/// socket to communicate with multiple heterogeneous endpoints.
public func bindToAddress(_ endPointAddress: String, endPointName: String = "") throws -> EndPoint {
var endPointId: CInt = -1
let socket: (receivePriority: Int?, sendPriority: Int?) = try _socketPriorities()
endPointAddress.withCString {
endPointId = nn_bind(self.socketFd, $0)
}
guard (endPointId >= 0) else {
throw NanoMessageError.BindToAddress(code: nn_errno(), address: endPointAddress)
}
let endPoint = EndPoint(endPointId: Int(endPointId),
endPointAddress: endPointAddress,
connectionType: .BindToAddress,
receivePriority: socket.receivePriority,
sendPriority: socket.sendPriority,
endPointName: endPointName)
self.endPoints.insert(endPoint)
return endPoint
}
/// Adds a local endpoint to the socket. The endpoint can be then used by other applications to connect to.
///
/// - Parameters:
/// - endPointAddress: Consists of two parts as follows: transport://address. The transport specifies the
/// underlying transport protocol to use. The meaning of the address part is specific
/// to the underlying transport protocol.
/// - endPointName: An optional endpoint name.
///
/// - Throws: `NanoMessageError.BindToAddress` if there was a problem binding the socket to the address.
/// `NanoMessageError.GetSocketOption`
///
/// - Returns: An endpoint ID is returned. The endpoint ID can be later used to remove the endpoint from
/// the socket via `removeEndPoint()` function.
///
/// - Note: Note that `bindToAddress()` may be called multiple times on the same socket thus allowing the
/// socket to communicate with multiple heterogeneous endpoints.
public func bindToAddress(_ endPointAddress: String, endPointName: String = "") throws -> Int {
let endPoint: EndPoint = try self.bindToAddress(endPointAddress, endPointName: endPointName)
return endPoint.id
}
/// Adds a remote endpoint to the socket. The library would then try to connect to the specified remote endpoint.
///
/// - Parameters:
/// - endPointAddress: Consists of two parts as follows: transport://address. The transport specifies the
/// underlying transport protocol to use. The meaning of the address part is specific
/// to the underlying transport protocol.
/// - endPointName: An optional endpoint name.
///
/// - Throws: `NanoMessageError.ConnectToAddress` if there was a problem binding the socket to the address.
/// `NanoMessageError.GetSocketOption`
///
/// - Returns: The endpoint that has just been connected too. The endpoint can be later used to remove the
/// endpoint from the socket via `removeEndPoint()` function.
///
/// - Note: Note that `connectToAddress()` may be called multiple times on the same socket thus allowing the
/// socket to communicate with multiple heterogeneous endpoints.
public func connectToAddress(_ endPointAddress: String, endPointName: String = "") throws -> EndPoint {
var endPointId: CInt = -1
let socket: (receivePriority: Int?, sendPriority: Int?) = try _socketPriorities()
endPointAddress.withCString {
endPointId = nn_connect(self.socketFd, $0)
}
guard (endPointId >= 0) else {
throw NanoMessageError.ConnectToAddress(code: nn_errno(), address: endPointAddress)
}
let endPoint = EndPoint(endPointId: Int(endPointId),
endPointAddress: endPointAddress,
connectionType: .ConnectToAddress,
receivePriority: socket.receivePriority,
sendPriority: socket.sendPriority,
endPointName: endPointName)
self.endPoints.insert(endPoint)
return endPoint
}
/// Adds a remote endpoint to the socket. The library would then try to connect to the specified remote endpoint.
///
/// - Parameters:
/// - endPointAddress: Consists of two parts as follows: transport://address. The transport specifies the
/// underlying transport protocol to use. The meaning of the address part is specific
/// to the underlying transport protocol.
/// - endPointName: An optional endpoint name.
///
/// - Throws: `NanoMessageError.ConnectToAddress` if there was a problem binding the socket to the address.
/// `NanoMessageError.GetSocketOption`
///
/// - Returns: An endpoint ID is returned. The endpoint ID can be later used to remove the endpoint from the
/// socket via the `removeEndPoint()` function.
///
/// - Note: Note that `connectToAddress()` may be called multiple times on the same socket thus allowing the
/// socket to communicate with multiple heterogeneous endpoints.
public func connectToAddress(_ endPointAddress: String, endPointName: String = "") throws -> Int {
let endPoint: EndPoint = try self.connectToAddress(endPointAddress, endPointName: endPointName)
return endPoint.id
}
/// Remove an endpoint from the socket.
///
/// - Parameters:
/// - endPoint: An endpoint.
///
/// - Throws: `NanoMessageError.RemoveEndPoint` if the endpoint failed to be removed,
/// `NanoMessageError.Interrupted` if the endpoint removal was interrupted.
///
/// - Returns: If the endpoint was removed, false indicates that the endpoint was not attached to the socket.
@discardableResult
public func removeEndPoint(_ endPoint: EndPoint) throws -> Bool {
if (self.endPoints.contains(endPoint)) {
var loopCount = 0
while (true) {
let returnCode = nn_shutdown(self.socketFd, CInt(endPoint.id)) // attempt to close down the endpoint
if (returnCode < 0) { // if `nn_shutdown()` failed then...
let errno = nn_errno()
if (errno == EINTR) { // if we were interrupted by a signal, reattempt is allowed by the native library
if (loopCount >= self.closureAttempts) {
throw NanoMessageError.Interrupted
}
usleep(self._closureDelay) // zzzz...
loopCount += 1
} else {
throw NanoMessageError.RemoveEndPoint(code: errno, address: endPoint.address, endPointId: endPoint.id)
}
} else {
break // we've closed the endpoint succesfully
}
}
self.endPoints.remove(endPoint)
return true
}
return false
}
/// Remove an endpoint from the socket.
///
/// - Parameters:
/// - endPoint: An endpoint.
///
/// - Throws: `NanoMessageError.RemoveEndPoint` if the endpoint failed to be removed,
/// `NanoMessageError.Interrupted` if the endpoint removal was interrupted.
///
/// - Returns: If the endpoint was removed, false indicates that the endpoint was not attached to the socket.
@discardableResult
public func removeEndPoint(_ endPointId: Int) throws -> Bool {
for endPoint in self.endPoints {
if (endPointId == endPoint.id) {
return try self.removeEndPoint(endPoint)
}
}
return false
}
/// Check a socket and reports whether it’s possible to send a message to the socket and/or receive a message from the socket.
///
/// - Parameters:
/// - timeout milliseconds: The maximum number of milliseconds to poll the socket for an event to occur,
/// default is 1000 milliseconds (1 second).
///
/// - Throws: `NanoMessageError.PollSocket` if polling the socket fails.
///
/// - Returns: Message waiting and send queue blocked as a tuple of bools.
public func pollSocket(timeout milliseconds: Int = 1000) throws -> (messageIsWaiting: Bool, sendIsBlocked: Bool) {
let pollinMask = CShort(NN_POLLIN) // define nn_poll event masks as short's so we only
let polloutMask = CShort(NN_POLLOUT) // cast once in the function
var eventMask = CShort.allZeros //
if let _: Int = try? getSocketOption(self.socketFd, .ReceiveFd) { // rely on the fact that getting the for example receive
eventMask = pollinMask // file descriptor for a socket type that does not support
} // receiving will throw a nil return value to determine
if let _: Int = try? getSocketOption(self.socketFd, .SendFd) { // what our polling event mask will be.
eventMask = eventMask | polloutMask //
} //
var pfd = nn_pollfd(fd: self.socketFd, events: eventMask, revents: 0) // define the pollfd struct for this socket
let returnCode = nn_poll(&pfd, 1, CInt(milliseconds)) // poll the nano socket
guard (returnCode >= 0) else {
throw NanoMessageError.PollSocket(code: nn_errno())
}
let messageIsWaiting = ((pfd.revents & pollinMask) != 0) ? true : false // using the event masks determine our return values
let sendIsBlocked = ((pfd.revents & polloutMask) != 0) ? true : false //
return (messageIsWaiting, sendIsBlocked)
}
/// Starts a device to bind the socket to another and forward messages between two sockets
///
/// - Parameters:
/// - nanoSocket: The socket to bind too.
///
/// - Throws: `NanoMessageError.BindToSocket` if a problem has been encountered.
public func bindToSocket(_ nanoSocket: NanoSocket) throws {
let returnCode = nn_device(self.socketFd, nanoSocket.socketFd)
guard (returnCode >= 0) else {
throw NanoMessageError.BindToSocket(code: nn_errno())
}
}
/// Starts a 'loopback' on the socket, it loops and sends any messages received from the socket back to itself.
///
/// - Throws: `NanoMessageError.BindToSocket` if a problem has been encountered.
public func loopBack() throws {
let returnCode = nn_device(self.socketFd, -1)
guard (returnCode >= 0) else {
throw NanoMessageError.LoopBack(code: nn_errno())
}
}
}
extension NanoSocket {
/// Get the domain of the socket as it was created with.
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The sockets domain.
public func getSocketDomain() throws -> SocketDomain {
return SocketDomain(rawValue: try getSocketOption(self.socketFd, .Domain))!
}
/// Get the protocol of the socket as it was created with.
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The sockets protocol.
public func getSocketProtocol() throws -> SocketProtocol {
return SocketProtocol(rawValue: try getSocketOption(self.socketFd, .Protocol))!
}
/// Get the protocol family of the socket as it was created with.
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The sockets protocol family.
public func getSocketProtocolFamily() throws -> ProtocolFamily {
return ProtocolFamily(rawValue: try self.getSocketProtocol())
}
/// Specifies how long the socket should try to send pending outbound messages after the socket
/// has been de-referenced, in milliseconds. A Negative value means infinite linger.
///
/// Default value is 1000 milliseconds (1 second).
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The linger time on the socket.
///
/// - Note: The nanomsg library no longer supports setting the linger option, linger time will
/// therefore always it's default value.
public func getLinger() throws -> Int {
return try getSocketOption(self.socketFd, .Linger)
}
/// Specifies how long the socket should try to send pending outbound messages after the socket
/// has been de-referenced, in milliseconds. A Negative value means infinite linger.
///
/// - Parameters:
/// - milliseconds: The linger time in milliseconds.
///
/// - Throws: `NanoMessageError.SetSocketOption`
///
/// - Note: The nanomsg library no longer supports this feature, linger time is always it's default value.
@available(*, unavailable, message: "nanomsg library no longer supports this feature")
public func setLinger(milliseconds: Int) throws {
try setSocketOption(self.socketFd, .Linger, milliseconds)
}
/// For connection-based transports such as TCP, this specifies how long to wait, in milliseconds,
/// when connection is broken before trying to re-establish it. Note that actual reconnect interval
/// may be randomised to some extent to prevent severe reconnection storms.
///
/// Default value is 100 milliseconds (0.1 second).
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The sockets reconnect interval.
public func getReconnectInterval() throws -> UInt {
return try getSocketOption(self.socketFd, .ReconnectInterval)
}
/// For connection-based transports such as TCP, this specifies how long to wait, in milliseconds,
/// when connection is broken before trying to re-establish it. Note that actual reconnect interval
/// may be randomised to some extent to prevent severe reconnection storms.
///
/// - Parameters:
/// - milliseconds: The reconnection interval in milliseconds.
///
/// - Throws: `NanoMessageError.SetSocketOption`
public func setReconnectInterval(milliseconds: UInt) throws {
try setSocketOption(self.socketFd, .ReconnectInterval, milliseconds)
}
/// This is to be used only in addition to `set/getReconnectInterval()`. It specifies maximum reconnection
/// interval. On each reconnect attempt, the previous interval is doubled until `getReconnectIntervalMax()`
/// is reached. Value of zero means that no exponential backoff is performed and reconnect interval is based
/// only on `getReconnectInterval()`.
/// If `getReconnectIntervalMax()` is less than `getReconnectInterval()`, it is ignored.
///
/// Default value is 0 milliseconds (0 seconds).
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The sockets reconnect maximum interval.
public func getReconnectIntervalMaximum() throws -> UInt {
return try getSocketOption(self.socketFd, .ReconnectIntervalMaximum)
}
/// This is to be used only in addition to `set/getReconnectInterval()`. It specifies maximum reconnection
/// interval. On each reconnect attempt, the previous interval is doubled until `getReconnectIntervalMax()`
/// is reached. Value of zero means that no exponential backoff is performed and reconnect interval is based
/// only on `getReconnectInterval()`.
/// If `getReconnectIntervalMax()` is less than `getReconnectInterval()`, it is ignored.
///
/// - Parameters:
/// - milliseconds: The reconnection maximum interval in milliseconds.
///
/// - Throws: `NanoMessageError.SetSocketOption`
public func setReconnectIntervalMaximum(milliseconds: UInt) throws {
try setSocketOption(self.socketFd, .ReconnectIntervalMaximum, milliseconds)
}
/// Socket name for error reporting and statistics.
///
/// Default value is "N" where N is socket file descriptor.
///
/// - Throws: `NanoMessageError.GetSocketOption`
///
/// - Returns: The sockets name.
///
/// - Note: This feature is deamed as experimental by the nanomsg library.
public func getSocketName() throws -> String {
return try getSocketOption(self.socketFd, .SocketName)
}
/// Socket name for error reporting and statistics.
///
/// - Parameters:
/// - socketName: Name of the socket.
///
/// - Throws: `NanoMessageError.SetSocketOption`
///
/// - Note: This feature is deamed as experimental by the nanomsg library.
public func setSocketName(_ socketName: String) throws {
try setSocketOption(self.socketFd, .SocketName, socketName)
}
/// If true, only IPv4 addresses are used. If false, both IPv4 and IPv6 addresses are used.
///
/// Default value is true.
///
/// - Returns: The IP4v4/Ipv6 type.
///
/// - Throws: `NanoMessageError.GetSocketOption`
public func getIPv4Only() throws -> Bool {
return try getSocketOption(self.socketFd, .IPv4Only)
}
/// If true, only IPv4 addresses are used. If false, both IPv4 and IPv6 addresses are used.
///
/// - Parameters:
/// - ip4Only: Use IPv4 or IPv4 and IPv6.
///
/// - Throws: `NanoMessageError.SetSocketOption`
public func setIPv4Only(_ ip4Only: Bool) throws {
try setSocketOption(self.socketFd, .IPv4Only, ip4Only)
}
/// The maximum number of "hops" a message can go through before it is dropped. Each time the
/// message is received (for example via the `bindToSocket()` function) counts as a single hop.
/// This provides a form of protection against inadvertent loops.
///
/// - Returns: The number of hops before a message is dropped.
///
/// - Throws: `NanoMessageError.GetSocketOption`
public func getMaxTTL() throws -> Int {
return try getSocketOption(self.socketFd, .MaxTTL)
}
/// The maximum number of "hops" a message can go through before it is dropped. Each time the
/// message is received (for example via the `bindToSocket()` function) counts as a single hop.
/// This provides a form of protection against inadvertent loops.
///
/// - Parameters:
/// - hops: The number of hops before a message is dropped.
///
/// - Throws: `NanoMessageError.SetSocketOption`
public func setMaxTTL(hops: Int) throws {
try setSocketOption(self.socketFd, .MaxTTL, hops)
}
/// When true, disables Nagle’s algorithm. It also disables delaying of TCP acknowledgments.
/// Using this option improves latency at the expense of throughput.
///
/// Default value is false.
///
/// - Returns: Is Nagele's algorithm enabled.
///
/// - Throws: `NanoMessageError.GetSocketOption`
public func getTCPNoDelay(transportMechanism: TransportMechanism = .TCP) throws -> Bool {
let valueReturned: CInt = try getSocketOption(self.socketFd, .TCPNoDelay, transportMechanism)
return (valueReturned == NN_TCP_NODELAY) ? true : false
}
/// When true, disables Nagle’s algorithm. It also disables delaying of TCP acknowledgments.
/// Using this option improves latency at the expense of throughput.
///
/// - Parameters:
/// - disableNagles: Disable or enable Nagle's algorithm.
///
/// - Throws: `NanoMessageError.SetSocketOption`
public func setTCPNoDelay(disableNagles: Bool, transportMechanism: TransportMechanism = .TCP) throws {
let valueToSet: CInt = (disableNagles) ? NN_TCP_NODELAY : 0
try setSocketOption(self.socketFd, .TCPNoDelay, valueToSet, transportMechanism)
}
/// This value determines whether data messages are sent as WebSocket text frames, or binary frames,
/// per RFC 6455. Text frames should contain only valid UTF-8 text in their payload, or they will be
/// rejected. Binary frames may contain any data. Not all WebSocket implementations support binary frames.
///
/// The default is to send binary frames.
///
/// - Returns: The web sockets message type.
///
/// - Throws: `NanoMessageError.GetSocketOption`
public func getWebSocketMessageType() throws -> WebSocketMessageType {
return WebSocketMessageType(rawValue: try getSocketOption(self.socketFd, .WebSocketMessageType, .WebSocket))
}
/// This value determines whether data messages are sent as WebSocket text frames, or binary frames,
/// per RFC 6455. Text frames should contain only valid UTF-8 text in their payload, or they will be
/// rejected. Binary frames may contain any data. Not all WebSocket implementations support binary frames.
///
/// - Parameters:
/// - type: Define the web socket message type.
///
/// - Throws: `NanoMessageError.SetSocketOption`
public func setWebSocketMessageType(_ type: WebSocketMessageType) throws {
try setSocketOption(self.socketFd, .WebSocketMessageType, type, .WebSocket)
}
}
extension NanoSocket {
/// The number of connections successfully established that were initiated from this socket.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getEstablishedConnections() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .EstablishedConnections)
}
/// The number of connections successfully established that were accepted by this socket.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getAcceptedConnections() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .AcceptedConnections)
}
/// The number of established connections that were dropped by this socket.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getDroppedConnections() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .DroppedConnections)
}
/// The number of established connections that were closed by this socket, typically due to protocol errors.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getBrokenConnections() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .BrokenConnections)
}
/// The number of errors encountered by this socket trying to connect to a remote peer.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getConnectErrors() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .ConnectErrors)
}
/// The number of errors encountered by this socket trying to bind to a local address.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getBindErrors() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .BindErrors)
}
/// The number of errors encountered by this socket trying to accept a a connection from a remote peer.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getAcceptErrors() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .AcceptErrors)
}
/// The number of connections currently estabalished to this socket.
///
/// - Returns: As per description.
///
/// - Throws: `NanoMessageError.GetSocketStatistic`
public func getCurrentConnections() throws -> UInt64 {
return try getSocketStatistic(self.socketFd, .CurrentConnections)
}
}
|
import Async
/// An async `UnsafeBufferPointer<UInt8>` stream wrapper for `TCPSocket`.
public final class TCPSocketStream: Stream {
/// See `InputStream.Input`
public typealias Input = UnsafeBufferPointer<UInt8>
/// See `OutputStream.Output`
public typealias Output = UnsafeBufferPointer<UInt8>
/// Internal socket source stream.
internal let source: TCPSocketSource
/// Internal socket sink stream.
internal let sink: TCPSocketSink
/// Internal stream init. Use socket convenience method.
internal init(socket: TCPSocket, bufferSize: Int, on worker: Worker) {
self.source = socket.source(on: worker, bufferSize: bufferSize)
self.sink = socket.sink(on: worker)
}
/// See `InputStream.input(_:)`
public func input(_ event: InputEvent<UnsafeBufferPointer<UInt8>>) {
sink.input(event)
}
/// See `OutputStream.input(_:)`
public func output<S>(to inputStream: S) where S : InputStream, TCPSocketStream.Output == S.Input {
source.output(to: inputStream)
}
}
extension TCPSocket {
/// Create a `TCPSocketStream` for this socket.
public func stream(bufferSize: Int = 4096, on worker: Worker) {
self.stream(bufferSize: bufferSize, on: worker)
}
}
fix recursive call
import Async
/// An async `UnsafeBufferPointer<UInt8>` stream wrapper for `TCPSocket`.
public final class TCPSocketStream: Stream {
/// See `InputStream.Input`
public typealias Input = UnsafeBufferPointer<UInt8>
/// See `OutputStream.Output`
public typealias Output = UnsafeBufferPointer<UInt8>
/// Internal socket source stream.
internal let source: TCPSocketSource
/// Internal socket sink stream.
internal let sink: TCPSocketSink
/// Internal stream init. Use socket convenience method.
internal init(socket: TCPSocket, bufferSize: Int, on worker: Worker) {
self.source = socket.source(on: worker, bufferSize: bufferSize)
self.sink = socket.sink(on: worker)
}
/// See `InputStream.input(_:)`
public func input(_ event: InputEvent<UnsafeBufferPointer<UInt8>>) {
sink.input(event)
}
/// See `OutputStream.input(_:)`
public func output<S>(to inputStream: S) where S : InputStream, TCPSocketStream.Output == S.Input {
source.output(to: inputStream)
}
}
extension TCPSocket {
/// Create a `TCPSocketStream` for this socket.
public func stream(bufferSize: Int = 4096, on worker: Worker) -> TCPSocketStream {
return TCPSocketStream(socket: self, bufferSize: bufferSize, on: worker)
}
}
|
//
// WKInterfaceImage+Kingfisher.swift
// Kingfisher
//
// Created by Rodrigo Borges Soares on 04/05/18.
//
// Copyright (c) 2018 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import WatchKit
// MARK: - Extension methods.
/**
* Set image to use from web.
*/
extension Kingfisher where Base: WKInterfaceImage {
/**
Set an image with a resource.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
*/
public func setImage(_ resource: Resource?) {
guard let resource = resource else {
return
}
KingfisherManager.shared.retrieveImage(with: resource, options: nil, progressBlock: nil, completionHandler: { [weak base] image, error, cacheType, imageURL in
DispatchQueue.main.safeAsync {
base?.setImage(image)
}
})
}
}
Add callbacks and image task to WKInterfaceImage extension
//
// WKInterfaceImage+Kingfisher.swift
// Kingfisher
//
// Created by Rodrigo Borges Soares on 04/05/18.
//
// Copyright (c) 2018 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import WatchKit
// MARK: - Extension methods.
/**
* Set image to use from web.
*/
extension Kingfisher where Base: WKInterfaceImage {
/**
Set an image with a resource.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
@discardableResult
public func setImage(_ resource: Resource?,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask {
guard let resource = resource else {
setWebURL(nil)
completionHandler?(nil, nil, .none, nil)
return .empty
}
setWebURL(resource.downloadURL)
let task = KingfisherManager.shared.retrieveImage(
with: resource,
options: KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo),
progressBlock: { receivedSize, totalSize in
guard resource.downloadURL == self.webURL else {
return
}
progressBlock?(receivedSize, totalSize)
},
completionHandler: { [weak base] image, error, cacheType, imageURL in
DispatchQueue.main.safeAsync {
guard let strongBase = base, imageURL == self.webURL else {
completionHandler?(image, error, cacheType, imageURL)
return
}
self.setImageTask(nil)
guard let image = image else {
completionHandler?(nil, error, cacheType, imageURL)
return
}
strongBase.setImage(image)
completionHandler?(image, error, cacheType, imageURL)
}
})
setImageTask(task)
return task
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func cancelDownloadTask() {
imageTask?.cancel()
}
}
// MARK: - Associated Object
private var lastURLKey: Void?
private var imageTaskKey: Void?
extension Kingfisher where Base: WKInterfaceImage {
/// Get the image URL binded to this image view.
public var webURL: URL? {
return objc_getAssociatedObject(base, &lastURLKey) as? URL
}
fileprivate func setWebURL(_ url: URL?) {
objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
fileprivate var imageTask: RetrieveImageTask? {
return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask
}
fileprivate func setImageTask(_ task: RetrieveImageTask?) {
objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
|
//
// SettingsBuilder.swift
// XcodeGen
//
// Created by Yonas Kolb on 26/7/17.
//
//
import Foundation
import xcproj
import PathKit
import ProjectSpec
import Yams
import JSONUtilities
extension ProjectSpec {
public func getProjectBuildSettings(config: Config) -> BuildSettings {
var buildSettings: BuildSettings = [:]
if let type = config.type, options.settingPresets.applyProject {
buildSettings += SettingsPresetFile.base.getBuildSettings()
buildSettings += SettingsPresetFile.config(type).getBuildSettings()
}
if let configPath = configFiles[config.name] {
// Do not overwrite project xcconfig's value.
if let configFile = try? XCConfig(path: basePath + configPath) {
removeValues(for: configFile.flattenedBuildSettings().keys, buildSettings: &buildSettings)
}
}
buildSettings += getBuildSettings(settings: settings, config: config)
return buildSettings
}
public func getTargetBuildSettings(target: Target, config: Config) -> BuildSettings {
var buildSettings = BuildSettings()
if options.settingPresets.applyTarget {
buildSettings += SettingsPresetFile.platform(target.platform).getBuildSettings()
buildSettings += SettingsPresetFile.product(target.type).getBuildSettings()
buildSettings += SettingsPresetFile.productPlatform(target.type, target.platform).getBuildSettings()
}
// Do not overwrite target xcconfig's values.
if let configPath = target.configFiles[config.name] {
if let configFile = try? XCConfig(path: basePath + configPath) {
removeValues(for: configFile.flattenedBuildSettings().keys, buildSettings: &buildSettings)
}
}
// Avoid overwriting target xcconfig's values by base presets' values.
if let configPath = configFiles[config.name] {
if let configFile = try? XCConfig(path: basePath + configPath) {
removeValues(for: configFile.flattenedBuildSettings().keys, buildSettings: &buildSettings)
}
}
buildSettings += getBuildSettings(settings: target.settings, config: config)
return buildSettings
}
public func getBuildSettings(settings: Settings, config: Config) -> BuildSettings {
var buildSettings: BuildSettings = [:]
for group in settings.groups {
if let settings = settingGroups[group] {
buildSettings += getBuildSettings(settings: settings, config: config)
}
}
buildSettings += settings.buildSettings
for (configVariant, settings) in settings.configSettings {
if config.name.lowercased().contains(configVariant.lowercased()) {
buildSettings += getBuildSettings(settings: settings, config: config)
}
}
return buildSettings
}
// combines all levels of a target's settings: target, target config, project, project config
public func getCombinedBuildSettings(basePath: Path, target: Target, config: Config, includeProject: Bool = true) -> BuildSettings {
var buildSettings: BuildSettings = [:]
if includeProject {
if let configFilePath = configFiles[config.name] {
if let configFile = try? XCConfig(path: basePath + configFilePath) {
buildSettings += configFile.flattenedBuildSettings()
}
}
buildSettings += getProjectBuildSettings(config: config)
}
if let configFilePath = target.configFiles[config.name] {
if let configFile = try? XCConfig(path: basePath + configFilePath) {
buildSettings += configFile.flattenedBuildSettings()
}
}
buildSettings += getTargetBuildSettings(target: target, config: config)
return buildSettings
}
public func targetHasBuildSetting(_ setting: String, basePath: Path, target: Target, config: Config, includeProject: Bool = true) -> Bool {
let buildSettings = getCombinedBuildSettings(basePath: basePath, target: target, config: config, includeProject: includeProject)
return buildSettings[setting] != nil
}
// MARK: private
/// Removes values for specified keys in buildSettings
/// - parameter keys: Keys for values to remove
/// - paramerter buildSettings: inout dictionary
private func removeValues(for keys: BuildSettings.Keys, buildSettings: inout BuildSettings) {
for k in keys {
// FIXME: Catch platform specifier. e.g. LD_RUNPATH_SEARCH_PATHS[sdk=iphone*]
buildSettings.removeValue(forKey: k)
buildSettings.removeValue(forKey: "\"\(k)\"")
}
}
}
private var buildSettingFiles: [String: BuildSettings] = [:]
extension SettingsPresetFile {
public func getBuildSettings() -> BuildSettings? {
if let group = buildSettingFiles[path] {
return group
}
let relativePath = "SettingPresets/\(path).yml"
let possibleSettingsPaths: [Path] = [
Path(relativePath),
Path(Bundle.main.bundlePath) + relativePath,
Path(Bundle.main.bundlePath) + "../share/xcodegen/\(relativePath)",
Path(#file).parent().parent().parent() + relativePath,
]
guard let settingsPath = possibleSettingsPaths.first(where: { $0.exists }) else {
switch self {
case .base, .config, .platform:
print("No \"\(name)\" settings found")
case .product, .productPlatform:
break
}
return nil
}
guard let buildSettings = try? loadYamlDictionary(path: settingsPath) else {
print("Error parsing \"\(name)\" settings")
return nil
}
buildSettingFiles[path] = buildSettings
return buildSettings
}
}
refactor config file setting removing
//
// SettingsBuilder.swift
// XcodeGen
//
// Created by Yonas Kolb on 26/7/17.
//
//
import Foundation
import xcproj
import PathKit
import ProjectSpec
import Yams
import JSONUtilities
extension ProjectSpec {
public func getProjectBuildSettings(config: Config) -> BuildSettings {
var buildSettings: BuildSettings = [:]
if let type = config.type, options.settingPresets.applyProject {
buildSettings += SettingsPresetFile.base.getBuildSettings()
buildSettings += SettingsPresetFile.config(type).getBuildSettings()
}
// Prevent setting presets from overrwriting settings in project xcconfig files
if let configPath = configFiles[config.name] {
buildSettings = removeConfigFileSettings(from: buildSettings, configPath: configPath)
}
buildSettings += getBuildSettings(settings: settings, config: config)
return buildSettings
}
public func getTargetBuildSettings(target: Target, config: Config) -> BuildSettings {
var buildSettings = BuildSettings()
if options.settingPresets.applyTarget {
buildSettings += SettingsPresetFile.platform(target.platform).getBuildSettings()
buildSettings += SettingsPresetFile.product(target.type).getBuildSettings()
buildSettings += SettingsPresetFile.productPlatform(target.type, target.platform).getBuildSettings()
}
// Prevent setting presets from overrwriting settings in target xcconfig files
if let configPath = target.configFiles[config.name] {
buildSettings = removeConfigFileSettings(from: buildSettings, configPath: configPath)
}
// Prevent setting presets from overrwriting settings in project xcconfig files
if let configPath = configFiles[config.name] {
buildSettings = removeConfigFileSettings(from: buildSettings, configPath: configPath)
}
buildSettings += getBuildSettings(settings: target.settings, config: config)
return buildSettings
}
public func getBuildSettings(settings: Settings, config: Config) -> BuildSettings {
var buildSettings: BuildSettings = [:]
for group in settings.groups {
if let settings = settingGroups[group] {
buildSettings += getBuildSettings(settings: settings, config: config)
}
}
buildSettings += settings.buildSettings
for (configVariant, settings) in settings.configSettings {
if config.name.lowercased().contains(configVariant.lowercased()) {
buildSettings += getBuildSettings(settings: settings, config: config)
}
}
return buildSettings
}
// combines all levels of a target's settings: target, target config, project, project config
public func getCombinedBuildSettings(basePath: Path, target: Target, config: Config, includeProject: Bool = true) -> BuildSettings {
var buildSettings: BuildSettings = [:]
if includeProject {
if let configFilePath = configFiles[config.name] {
if let configFile = try? XCConfig(path: basePath + configFilePath) {
buildSettings += configFile.flattenedBuildSettings()
}
}
buildSettings += getProjectBuildSettings(config: config)
}
if let configFilePath = target.configFiles[config.name] {
if let configFile = try? XCConfig(path: basePath + configFilePath) {
buildSettings += configFile.flattenedBuildSettings()
}
}
buildSettings += getTargetBuildSettings(target: target, config: config)
return buildSettings
}
public func targetHasBuildSetting(_ setting: String, basePath: Path, target: Target, config: Config, includeProject: Bool = true) -> Bool {
let buildSettings = getCombinedBuildSettings(basePath: basePath, target: target, config: config, includeProject: includeProject)
return buildSettings[setting] != nil
}
/// Removes values from build settings if they are defined in an xcconfig file
private func removeConfigFileSettings(from buildSettings: BuildSettings, configPath: String) -> BuildSettings {
var buildSettings = buildSettings
if let configFile = try? XCConfig(path: basePath + configPath) {
let configSettings = configFile.flattenedBuildSettings()
for key in configSettings.keys {
// FIXME: Catch platform specifier. e.g. LD_RUNPATH_SEARCH_PATHS[sdk=iphone*]
buildSettings.removeValue(forKey: key)
buildSettings.removeValue(forKey: key.quoted)
}
}
return buildSettings
}
}
private var buildSettingFiles: [String: BuildSettings] = [:]
extension SettingsPresetFile {
public func getBuildSettings() -> BuildSettings? {
if let group = buildSettingFiles[path] {
return group
}
let relativePath = "SettingPresets/\(path).yml"
let possibleSettingsPaths: [Path] = [
Path(relativePath),
Path(Bundle.main.bundlePath) + relativePath,
Path(Bundle.main.bundlePath) + "../share/xcodegen/\(relativePath)",
Path(#file).parent().parent().parent() + relativePath,
]
guard let settingsPath = possibleSettingsPaths.first(where: { $0.exists }) else {
switch self {
case .base, .config, .platform:
print("No \"\(name)\" settings found")
case .product, .productPlatform:
break
}
return nil
}
guard let buildSettings = try? loadYamlDictionary(path: settingsPath) else {
print("Error parsing \"\(name)\" settings")
return nil
}
buildSettingFiles[path] = buildSettings
return buildSettings
}
}
|
//
// NSCoder.swift
// StackedDrafts
//
// Created by Brian Nickel on 4/27/16.
// Copyright © 2016 Stack Exchange. All rights reserved.
//
import Foundation
private class SafeWrapper : NSObject, NSCoding {
var value:Any?
init(value:Any?) {
self.value = value
}
@objc required convenience init?(coder aDecoder: NSCoder) {
self.init(value: aDecoder.decodeObject(forKey: "value"))
}
@objc func encode(with aCoder: NSCoder) {
aCoder.encode(value, forKey: "value")
}
static func wrapArray(_ array:[Any]) -> Any {
return array.map(SafeWrapper.init(value:)) as NSArray
}
static func unwrapArray<T : AnyObject>(_ array:Any?) -> [T] {
return (array as? [SafeWrapper])?.flatMap({ $0.value as? T }) ?? []
}
}
extension NSCoder {
func encodeSafeArray(_ array:[AnyObject], forKey key:String) {
encode(SafeWrapper.wrapArray(array), forKey: key)
}
func decodeSafeArrayForKey<T: AnyObject>(_ key:String) -> [T] {
return SafeWrapper.unwrapArray(decodeObject(forKey: key))
}
}
Statically dispatch encodeSafeArray(_:forKey:) because it isn't prefixed and will never be called externally.
//
// NSCoder.swift
// StackedDrafts
//
// Created by Brian Nickel on 4/27/16.
// Copyright © 2016 Stack Exchange. All rights reserved.
//
import Foundation
private class SafeWrapper : NSObject, NSCoding {
var value:Any?
init(value:Any?) {
self.value = value
}
@objc required convenience init?(coder aDecoder: NSCoder) {
self.init(value: aDecoder.decodeObject(forKey: "value"))
}
@objc func encode(with aCoder: NSCoder) {
aCoder.encode(value, forKey: "value")
}
static func wrapArray(_ array:[Any]) -> Any {
return array.map(SafeWrapper.init(value:)) as NSArray
}
static func unwrapArray<T : AnyObject>(_ array:Any?) -> [T] {
return (array as? [SafeWrapper])?.flatMap({ $0.value as? T }) ?? []
}
}
extension NSCoder {
// Marked @nonobjc to avoid dynamic dispatch on unprefixed method.
@nonobjc func encodeSafeArray(_ array:[AnyObject], forKey key:String) {
encode(SafeWrapper.wrapArray(array), forKey: key)
}
@nonobjc func decodeSafeArrayForKey<T: AnyObject>(_ key:String) -> [T] {
return SafeWrapper.unwrapArray(decodeObject(forKey: key))
}
}
|
import Foundation
import CoreWLAN
class SenecaLoginController {
let BASE_URL = "https://wlan.uniandes.edu.co/login.html"
let WIFI_NETWORK_NAME = "SENECA"
func doConnectionPOST() {}
func isSenecaCurrentSSID() -> Bool {
if let wifiInterface = CWWiFiClient.shared().interface(), let ssid = wifiInterface.ssid() {
return ssid == WIFI_NETWORK_NAME
}
return false;
}
func connectedToSeneca() {}
func connectedToInternet() {}
}
Adding old code for debugging and reference purposes
import Foundation
import CoreWLAN
class SenecaLoginController {
let BASE_URL = "https://wlan.uniandes.edu.co/login.html"
let WIFI_NETWORK_NAME = "SENECA"
func doConnectionPOST() {}
func discoverReacheableNetworks() -> Set<CWNetwork>? {
var currentInterface: CWInterface
var interfacesNames: [String] = []
var networks: Set<CWNetwork> = []
// Failable init using default interface. Fails if no connection detected
if let defaultInterface = CWWiFiClient.shared().interface(),
let name = defaultInterface.interfaceName {
currentInterface = defaultInterface
interfacesNames.append(name)
// Fetch reacheable WiFi networks
do {
networks = try currentInterface.scanForNetworks(withSSID: nil)
return networks
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
return nil;
}
}
return nil;
}
func isSenecaReacheable() -> Bool {
if let networks = discoverReacheableNetworks() {
let SSIDs = networks.map {network in network.ssid!}
return SSIDs.contains(WIFI_NETWORK_NAME)
}
return false
}
func isSenecaCurrentSSID() -> Bool {
if let wifiInterface = CWWiFiClient.shared().interface(), let ssid = wifiInterface.ssid() {
return ssid == WIFI_NETWORK_NAME
}
return false;
}
func connectedToSeneca() {}
func connectedToInternet() {}
}
|
//
// Transformable.swift
// EZMobile
//
// Created by Virpik on 23/05/2018.
// Copyright © 2018 Sybis. All rights reserved.
//
import Foundation
/// Протокол, позволяющий "Трансформировать" Создать новый объект произвольного типа,
/// на онове текущего.
public protocol Transformable {
func transform<T>(_ block: (Self) -> T) -> T
}
extension Transformable {
/// Дефолтная реализация протокола
public func transform<T>(_ block: (Self) -> T) -> T {
return block(self)
}
}
[DEV] String impl Transformable
//
// Transformable.swift
// EZMobile
//
// Created by Virpik on 23/05/2018.
// Copyright © 2018 Sybis. All rights reserved.
//
import Foundation
/// Протокол, позволяющий "Трансформировать" Создать новый объект произвольного типа,
/// на онове текущего.
public protocol Transformable {
func transform<T>(_ block: (Self) -> T) -> T
}
extension Transformable {
/// Дефолтная реализация протокола
public func transform<T>(_ block: (Self) -> T) -> T {
return block(self)
}
}
extension String: Transformable {
}
|
import XCTest
@testable import NSRegExNamedCaptureGroup
extension NSRegularExpression {
static var commonOptions: NSRegularExpression.Options {
return [
.caseInsensitive
, .allowCommentsAndWhitespace
, .anchorsMatchLines
, .useUnicodeWordBoundaries
]
}
}
class NSRegExNamedCaptureGroupTests: XCTestCase {
class TestSamples_Group1 {
static let phoneNumber = "202-555-0136"
static let areaPattern = "(?<Area>\\d\\d\\d)"
static let exchPattern = "(?:\\d\\d\\d)"
static let numPattern = "(?<Num>\\d\\d\\d\\d)"
static let USAPhoneNumberPattern = try! NSRegularExpression(
pattern: "\\b\(areaPattern)-\(exchPattern)-\(numPattern)\\b"
, options: NSRegularExpression.commonOptions
)
}
func _compareRange(
in checkingResult: NSTextCheckingResult
, byGroupName groupName: String?
, with index: Int ) -> Bool {
let rangeByGroupName = checkingResult.range( withGroupName: groupName )
let rangeByIndex = checkingResult.rangeAt( index )
return
rangeByGroupName.location == rangeByIndex.location
&& rangeByGroupName.length == rangeByIndex.length
}
func _isRangeInvalid(
in checkingResult: NSTextCheckingResult
, byGroupName groupName: String? ) -> Bool {
let rangeByGroupName = checkingResult.range( withGroupName: groupName )
return
rangeByGroupName.location == NSNotFound
&& rangeByGroupName.length == 0
}
func testArrayBasedAPI_01() {
let matches = TestSamples_Group1.USAPhoneNumberPattern.matches(
in: TestSamples_Group1.phoneNumber
, options: []
, range: NSMakeRange( 0, TestSamples_Group1.phoneNumber.utf16.count )
)
for match in matches {
XCTAssert( _compareRange( in: match, byGroupName: nil, with: 0 ) )
XCTAssert( _compareRange( in: match, byGroupName: TestSamples_Group1.areaPattern, with: 1 ) )
XCTAssert( _isRangeInvalid( in: match, byGroupName: TestSamples_Group1.exchPattern ) )
XCTAssert( _compareRange( in: match, byGroupName: TestSamples_Group1.numPattern, with: 2 ) )
}
}
func testBlockEnumerationBasedAPI_01() {
TestSamples_Group1.USAPhoneNumberPattern.enumerateMatches(
in: TestSamples_Group1.phoneNumber
, options: []
, range: NSMakeRange( 0, TestSamples_Group1.phoneNumber.utf16.count )
) { checkingResult, _, stopToken in
XCTAssertNotNil( checkingResult )
guard let checkingResult = checkingResult else {
stopToken.pointee = ObjCBool( true );
return
}
XCTAssert( _compareRange( in: checkingResult, byGroupName: nil, with: 0 ) )
XCTAssert( _compareRange( in: checkingResult, byGroupName: TestSamples_Group1.areaPattern, with: 1 ) )
XCTAssert( _isRangeInvalid( in: checkingResult, byGroupName: TestSamples_Group1.exchPattern ) )
XCTAssert( _compareRange( in: checkingResult, byGroupName: TestSamples_Group1.numPattern, with: 2 ) )
}
}
static var allTests = [
( "testArrayBasedAPI_01", testArrayBasedAPI_01 )
, ( "testBlockEnumerationBasedAPI_01", testBlockEnumerationBasedAPI_01 )
]
}
Extract NSRegEx...Tests' utility methods as an extension
import XCTest
@testable import NSRegExNamedCaptureGroup
extension NSRegularExpression {
static var commonOptions: NSRegularExpression.Options {
return [
.caseInsensitive
, .allowCommentsAndWhitespace
, .anchorsMatchLines
, .useUnicodeWordBoundaries
]
}
}
class NSRegExNamedCaptureGroupTests: XCTestCase {
class TestSamples_Group1 {
static let phoneNumber = "202-555-0136"
static let areaPattern = "(?<Area>\\d\\d\\d)"
static let exchPattern = "(?:\\d\\d\\d)"
static let numPattern = "(?<Num>\\d\\d\\d\\d)"
static let USAPhoneNumberPattern = try! NSRegularExpression(
pattern: "\\b\(areaPattern)-\(exchPattern)-\(numPattern)\\b"
, options: NSRegularExpression.commonOptions
)
}
func testArrayBasedAPI_01() {
let matches = TestSamples_Group1.USAPhoneNumberPattern.matches(
in: TestSamples_Group1.phoneNumber
, options: []
, range: NSMakeRange( 0, TestSamples_Group1.phoneNumber.utf16.count )
)
for match in matches {
XCTAssert( _compareRange( in: match, byGroupName: nil, with: 0 ) )
XCTAssert( _compareRange( in: match, byGroupName: TestSamples_Group1.areaPattern, with: 1 ) )
XCTAssert( _isRangeInvalid( in: match, byGroupName: TestSamples_Group1.exchPattern ) )
XCTAssert( _compareRange( in: match, byGroupName: TestSamples_Group1.numPattern, with: 2 ) )
}
}
func testBlockEnumerationBasedAPI_01() {
TestSamples_Group1.USAPhoneNumberPattern.enumerateMatches(
in: TestSamples_Group1.phoneNumber
, options: []
, range: NSMakeRange( 0, TestSamples_Group1.phoneNumber.utf16.count )
) { checkingResult, _, stopToken in
XCTAssertNotNil( checkingResult )
guard let checkingResult = checkingResult else {
stopToken.pointee = ObjCBool( true );
return
}
XCTAssert( _compareRange( in: checkingResult, byGroupName: nil, with: 0 ) )
XCTAssert( _compareRange( in: checkingResult, byGroupName: TestSamples_Group1.areaPattern, with: 1 ) )
XCTAssert( _isRangeInvalid( in: checkingResult, byGroupName: TestSamples_Group1.exchPattern ) )
XCTAssert( _compareRange( in: checkingResult, byGroupName: TestSamples_Group1.numPattern, with: 2 ) )
}
}
static var allTests = [
( "testArrayBasedAPI_01", testArrayBasedAPI_01 )
, ( "testBlockEnumerationBasedAPI_01", testBlockEnumerationBasedAPI_01 )
]
}
/// Utility extension for convenience
fileprivate extension NSRegExNamedCaptureGroupTests {
fileprivate func _compareRange(
in checkingResult: NSTextCheckingResult
, byGroupName groupName: String?
, with index: Int ) -> Bool {
let rangeByGroupName = checkingResult.range( withGroupName: groupName )
let rangeByIndex = checkingResult.rangeAt( index )
return
rangeByGroupName.location == rangeByIndex.location
&& rangeByGroupName.length == rangeByIndex.length
}
fileprivate func _isRangeInvalid(
in checkingResult: NSTextCheckingResult
, byGroupName groupName: String? ) -> Bool {
let rangeByGroupName = checkingResult.range( withGroupName: groupName )
return
rangeByGroupName.location == NSNotFound
&& rangeByGroupName.length == 0
}
}
|
//
// PredicateTests.swift
//
//
// Created by Alsey Coleman Miller on 4/12/20.
//
import Foundation
import XCTest
@testable import Predicate
final class PredicateTests: XCTestCase {
static let allTests = [
("testDescription", testDescription),
("testEncoder", testEncoder),
("testPredicate1", testPredicate1),
("testPredicate2", testPredicate2),
("testPredicate3", testPredicate3),
("testPredicate4", testPredicate4),
("testPredicate5", testPredicate5),
("testPredicate6", testPredicate6),
]
func testDescription() {
XCTAssertEqual(Predicate.comparison(.init(left: .keyPath("name"), right: .value(.string("Coleman")))).description, "name = \"Coleman\"")
XCTAssertEqual(((.keyPath("name") != .value(.null)) as Predicate).description, "name != NULL")
XCTAssertEqual(Predicate.compound(.not(.keyPath("name") == .value(.null))) .description, "NOT name = NULL")
}
func testEncoder() {
let event = Event(
id: 100,
name: "Event",
start: Date(timeIntervalSince1970: 60 * 60 * 2),
speakers: [
Person(
id: 1,
name: "John Apple"
)
])
let context: PredicateContext = [
"id": .uint64(100),
"name": .string("Event"),
"start": .date(Date(timeIntervalSince1970: 60 * 60 * 2)),
"speakers.@count": .uint64(1),
"speakers.0.id": .uint64(1),
"speakers.0.name": .string("John Apple"),
]
XCTAssertEqual(context, try PredicateContext(value: event))
}
func testPredicate1() {
let predicate: Predicate = "id" > Int64(0)
&& "id" != Int64(99)
&& "name".compare(.beginsWith, .value(.string("C")))
&& "name".compare(.contains, [.diacriticInsensitive, .caseInsensitive], .value(.string("COLE")))
XCTAssertEqual(predicate.description, #"((id > 0 AND id != 99) AND name BEGINSWITH "C") AND name CONTAINS[cd] "COLE""#)
XCTAssert(try Person(id: 1, name: "Coléman").evaluate(with: predicate, log: { print("Encoder: \($0)") }))
}
func testPredicate2() {
let identifiers: [Int64] = [1, 2, 3]
let predicate: Predicate = ("name").any(in: ["coleman", "miller"])
&& "id".any(in: identifiers)
|| "id".all(in: [Int16]())
XCTAssertEqual(predicate.description, #"(ANY name IN {"coleman", "miller"} AND ANY id IN {1, 2, 3}) OR ALL id IN {}"#, "Invalid description")
XCTAssert(try [Person(id: 1, name: "coleman"), Person(id: 2, name: "miller")].filter(with: predicate).count == 2)
}
func testPredicate3() {
let identifiers: [Int64] = [1, 2, 3]
let predicate: Predicate = "name".`in`(["coleman", "miller"]) && "id".`in`(identifiers)
XCTAssertEqual(predicate.description, #"name IN {"coleman", "miller"} AND id IN {1, 2, 3}"#, "Invalid description")
XCTAssert(try Person(id: 1, name: "coleman").evaluate(with: predicate, log: { print("Encoder: \($0)") }))
XCTAssert(try [Person(id: 1, name: "coleman"), Person(id: 2, name: "miller")].filter(with: predicate).count == 2)
XCTAssert(try [Person(id: 1, name: "test1"), Person(id: 2, name: "test2")].filter(with: predicate).isEmpty)
}
func testPredicate4() {
let now = Date()
let identifiers: [ID] = [100, 200, 300]
let events = [
Event(
id: identifiers[0],
name: "Awesome Event",
start: Date(timeIntervalSince1970: 0),
speakers: [
Person(
id: 1,
name: "Alsey Coleman Miller"
)
])
]
let predicate: Predicate = "name".compare(.contains, [.caseInsensitive], .value(.string("event")))
&& "name".`in`(["Awesome Event"])
&& "id".`in`(identifiers.map { $0.rawValue })
&& "start" < now
&& "speakers.name".all(in: ["Alsey Coleman Miller"])
XCTAssert(try events[0].evaluate(with: predicate, log: { print("Encoder: \($0)") }))
XCTAssertEqual(try events.filter(with: predicate), events)
}
func testPredicate5() {
let events = [
Event(
id: 100,
name: "Awesome Event",
start: Date(timeIntervalSince1970: 0),
speakers: [
Person(
id: 1,
name: "Alsey Coleman Miller"
)
]),
Event(
id: 200,
name: "Second Event",
start: Date(timeIntervalSince1970: 60 * 60 * 2),
speakers: [
Person(
id: 2,
name: "John Apple"
)
])
]
let future = Date.distantFuture
let predicate: Predicate = "name".compare(.matches, [.caseInsensitive], .value(.string(#"\w+ event"#)))
&& "start" < future
&& ("speakers.name".any(in: ["Alsey Coleman Miller"])
|| "speakers.name".compare(.contains, .value(.string("John Apple"))))
&& "speakers.name".any(in: ["Alsey Coleman Miller", "John Apple", "Test"])
&& "speakers.name".all(in: ["John Apple", "Alsey Coleman Miller"])
XCTAssertEqual(try events.filter(with: predicate), events)
XCTAssertEqual(predicate.description, #"(((name MATCHES[c] "\w+ event" AND start < 4001-01-01 00:00:00 +0000) AND (ANY speakers.name IN {"Alsey Coleman Miller"} OR speakers.name CONTAINS "John Apple")) AND ANY speakers.name IN {"Alsey Coleman Miller", "John Apple", "Test"}) AND ALL speakers.name IN {"John Apple", "Alsey Coleman Miller"}"#)
}
func testPredicate6() {
let events = [
Event(
id: 100,
name: "Awesome Event",
start: Date(timeIntervalSince1970: 0),
speakers: [
Person(
id: 1,
name: "Alsey Coleman Miller"
)
]),
Event(
id: 200,
name: "Second Event",
start: Date(timeIntervalSince1970: 60 * 60 * 2),
speakers: [
Person(
id: 2,
name: "John Apple"
)
])
]
let now = Date()
let predicate: Predicate = "name".compare(.matches, [.caseInsensitive], .value(.string(#"\w+ event"#)))
&& "start" < now
&& "speakers.@count" > 0
XCTAssertEqual(try events.filter(with: predicate), events)
}
}
// MARK: - Supporting Types
internal extension PredicateTests {
struct ID: RawRepresentable, Equatable, Hashable, Codable {
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
}
struct Person: Equatable, Hashable, Codable, PredicateEvaluatable {
var id: ID
var name: String
init(id: ID, name: String) {
self.id = id
self.name = name
}
}
struct Event: Equatable, Hashable, Codable, PredicateEvaluatable {
var id: ID
var name: String
var start: Date
var speakers: [Person]
init(id: ID, name: String, start: Date, speakers: [Person]) {
self.id = id
self.name = name
self.start = start
self.speakers = speakers
}
}
}
extension PredicateTests.ID: ExpressibleByIntegerLiteral {
public init(integerLiteral value: UInt) {
self.init(rawValue: value)
}
}
Updated unit tests
//
// PredicateTests.swift
//
//
// Created by Alsey Coleman Miller on 4/12/20.
//
import Foundation
import XCTest
@testable import Predicate
final class PredicateTests: XCTestCase {
static let allTests = [
("testDescription", testDescription),
("testEncoder", testEncoder),
("testPredicate1", testPredicate1),
("testPredicate2", testPredicate2),
("testPredicate3", testPredicate3),
("testPredicate4", testPredicate4),
("testPredicate5", testPredicate5),
("testPredicate6", testPredicate6),
]
func testDescription() {
XCTAssertEqual((.keyPath("name") == .value(.string("Coleman"))).description, "name = \"Coleman\"")
XCTAssertEqual(((.keyPath("name") != .value(.null)) as Predicate).description, "name != NULL")
XCTAssertEqual((!(.keyPath("name") == .value(.null))).description, "NOT name = NULL")
}
func testEncoder() {
let event = Event(
id: 100,
name: "Event",
start: Date(timeIntervalSince1970: 60 * 60 * 2),
speakers: [
Person(
id: 1,
name: "John Apple"
)
])
let context: PredicateContext = [
"id": .uint64(100),
"name": .string("Event"),
"start": .date(Date(timeIntervalSince1970: 60 * 60 * 2)),
"speakers.@count": .uint64(1),
"speakers.0.id": .uint64(1),
"speakers.0.name": .string("John Apple"),
]
XCTAssertEqual(context, try PredicateContext(value: event))
}
func testPredicate1() {
let predicate: Predicate = "id" > Int64(0)
&& "id" != Int64(99)
&& "name".compare(.beginsWith, .value(.string("C")))
&& "name".compare(.contains, [.diacriticInsensitive, .caseInsensitive], .value(.string("COLE")))
XCTAssertEqual(predicate.description, #"((id > 0 AND id != 99) AND name BEGINSWITH "C") AND name CONTAINS[cd] "COLE""#)
XCTAssert(try Person(id: 1, name: "Coléman").evaluate(with: predicate, log: { print("Encoder: \($0)") }))
}
func testPredicate2() {
let identifiers: [Int64] = [1, 2, 3]
let predicate: Predicate = ("name").any(in: ["coleman", "miller"])
&& "id".any(in: identifiers)
|| "id".all(in: [Int16]())
XCTAssertEqual(predicate.description, #"(ANY name IN {"coleman", "miller"} AND ANY id IN {1, 2, 3}) OR ALL id IN {}"#, "Invalid description")
XCTAssert(try [Person(id: 1, name: "coleman"), Person(id: 2, name: "miller")].filter(with: predicate).count == 2)
}
func testPredicate3() {
let identifiers: [Int64] = [1, 2, 3]
let predicate: Predicate = "name".`in`(["coleman", "miller"]) && "id".`in`(identifiers)
XCTAssertEqual(predicate.description, #"name IN {"coleman", "miller"} AND id IN {1, 2, 3}"#, "Invalid description")
XCTAssert(try Person(id: 1, name: "coleman").evaluate(with: predicate, log: { print("Encoder: \($0)") }))
XCTAssert(try [Person(id: 1, name: "coleman"), Person(id: 2, name: "miller")].filter(with: predicate).count == 2)
XCTAssert(try [Person(id: 1, name: "test1"), Person(id: 2, name: "test2")].filter(with: predicate).isEmpty)
}
func testPredicate4() {
let now = Date()
let identifiers: [ID] = [100, 200, 300]
let events = [
Event(
id: identifiers[0],
name: "Awesome Event",
start: Date(timeIntervalSince1970: 0),
speakers: [
Person(
id: 1,
name: "Alsey Coleman Miller"
)
])
]
let predicate: Predicate = "name".compare(.contains, [.caseInsensitive], .value(.string("event")))
&& "name".`in`(["Awesome Event"])
&& "id".`in`(identifiers.map { $0.rawValue })
&& "start" < now
&& "speakers.name".all(in: ["Alsey Coleman Miller"])
XCTAssert(try events[0].evaluate(with: predicate, log: { print("Encoder: \($0)") }))
XCTAssertEqual(try events.filter(with: predicate), events)
}
func testPredicate5() {
let events = [
Event(
id: 100,
name: "Awesome Event",
start: Date(timeIntervalSince1970: 0),
speakers: [
Person(
id: 1,
name: "Alsey Coleman Miller"
)
]),
Event(
id: 200,
name: "Second Event",
start: Date(timeIntervalSince1970: 60 * 60 * 2),
speakers: [
Person(
id: 2,
name: "John Apple"
)
])
]
let future = Date.distantFuture
let predicate: Predicate = "name".compare(.matches, [.caseInsensitive], .value(.string(#"\w+ event"#)))
&& "start" < future
&& ("speakers.name".any(in: ["Alsey Coleman Miller"])
|| "speakers.name".compare(.contains, .value(.string("John Apple"))))
&& "speakers.name".any(in: ["Alsey Coleman Miller", "John Apple", "Test"])
&& "speakers.name".all(in: ["John Apple", "Alsey Coleman Miller"])
XCTAssertEqual(try events.filter(with: predicate), events)
XCTAssertEqual(predicate.description, #"(((name MATCHES[c] "\w+ event" AND start < 4001-01-01 00:00:00 +0000) AND (ANY speakers.name IN {"Alsey Coleman Miller"} OR speakers.name CONTAINS "John Apple")) AND ANY speakers.name IN {"Alsey Coleman Miller", "John Apple", "Test"}) AND ALL speakers.name IN {"John Apple", "Alsey Coleman Miller"}"#)
}
func testPredicate6() {
let events = [
Event(
id: 100,
name: "Awesome Event",
start: Date(timeIntervalSince1970: 0),
speakers: [
Person(
id: 1,
name: "Alsey Coleman Miller"
)
]),
Event(
id: 200,
name: "Second Event",
start: Date(timeIntervalSince1970: 60 * 60 * 2),
speakers: [
Person(
id: 2,
name: "John Apple"
)
])
]
let now = Date()
let predicate: Predicate = "name".compare(.matches, [.caseInsensitive], .value(.string(#"\w+ event"#)))
&& "start" < now
&& "speakers.@count" > 0
XCTAssertEqual(try events.filter(with: predicate), events)
}
}
// MARK: - Supporting Types
internal extension PredicateTests {
struct ID: RawRepresentable, Equatable, Hashable, Codable {
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
}
struct Person: Equatable, Hashable, Codable, PredicateEvaluatable {
var id: ID
var name: String
init(id: ID, name: String) {
self.id = id
self.name = name
}
}
struct Event: Equatable, Hashable, Codable, PredicateEvaluatable {
var id: ID
var name: String
var start: Date
var speakers: [Person]
init(id: ID, name: String, start: Date, speakers: [Person]) {
self.id = id
self.name = name
self.start = start
self.speakers = speakers
}
}
}
extension PredicateTests.ID: ExpressibleByIntegerLiteral {
public init(integerLiteral value: UInt) {
self.init(rawValue: value)
}
}
|
//
// VaporAPNSTests.swift
// VaporAPNS
//
// Created by Matthijs Logemann on 23/09/2016.
//
//
import XCTest
@testable import VaporAPNS
import VaporJWT
import JSON
import Foundation
import CLibreSSL
import Core
class VaporAPNSTests: XCTestCase { // TODO: Set this up so others can test this 😉
let vaporAPNS: VaporAPNS! = nil
override func setUp() {
// print ("Hi")
}
func testLoadPrivateKey() throws {
if let filepath = Bundle.init(for: type(of: self)).path(forResource: "TestAPNSAuthKey", ofType: "p8") {
let (privKey, pubKey) = try filepath.tokenString()
XCTAssertEqual(privKey, "ALEILVyGWnbBaSaIFDsh0yoZaK+Ej0po/55jG2FR6u6C")
XCTAssertEqual(pubKey, "BKqKwB6hpXp9SzWGt3YxnHgCEkcbS+JSrhoqkeqru/Nf62MeE958RIiKYsLFA/czdE7ThCt46azneU0IBnMCuQU=")
} else {
XCTFail("APNS Authentication key not found!")
}
}
func testEncoding() throws {
let currentTime = Date().timeIntervalSince1970
let jsonPayload = try JSON(node: [
"iss": "D86BEC0E8B",
"iat": currentTime
])
let jwt = try! JWT(payload: jsonPayload,
header: try! JSON(node: ["alg":"ES256","kid":"E811E6AE22","typ":"JWT"]),
algorithm: .es(._256("ALEILVyGWnbBaSaIFDsh0yoZaK+Ej0po/55jG2FR6u6C")),
encoding: .base64URL)
let tokenString = try! jwt.token()
do {
let jwt2 = try JWT(token: tokenString, encoding: .base64URL)
let verified = try jwt2.verifySignature(key: "BKqKwB6hpXp9SzWGt3YxnHgCEkcbS+JSrhoqkeqru/Nf62MeE958RIiKYsLFA/czdE7ThCt46azneU0IBnMCuQU=")
XCTAssertTrue(verified)
} catch {
// fatalError("\(error)")
XCTFail ("Couldn't verify token")
}
}
}
Fixed tests, hopefully
//
// VaporAPNSTests.swift
// VaporAPNS
//
// Created by Matthijs Logemann on 23/09/2016.
//
//
import XCTest
@testable import VaporAPNS
import VaporJWT
import JSON
import Foundation
import CLibreSSL
import Core
class VaporAPNSTests: XCTestCase { // TODO: Set this up so others can test this 😉
let vaporAPNS: VaporAPNS! = nil
override func setUp() {
// print ("Hi")
}
func testLoadPrivateKey() throws {
var filepath = ""
let fileManager = FileManager.default
if let filepathe = Bundle.init(for: type(of: self)).path(forResource: "TestAPNSAuthKey", ofType: "p8") {
filepath = filepathe
}else {
filepath = fileManager.currentDirectoryPath.appending("/Tests/VaporAPNSTests/TestAPNSAuthKey.p8")
}
print (filepath)
if fileManager.fileExists(atPath: filepath) {
let (privKey, pubKey) = try filepath.tokenString()
XCTAssertEqual(privKey, "ALEILVyGWnbBaSaIFDsh0yoZaK+Ej0po/55jG2FR6u6C")
XCTAssertEqual(pubKey, "BKqKwB6hpXp9SzWGt3YxnHgCEkcbS+JSrhoqkeqru/Nf62MeE958RIiKYsLFA/czdE7ThCt46azneU0IBnMCuQU=")
} else {
XCTFail("APNS Authentication key not found!")
}
}
func testEncoding() throws {
let currentTime = Date().timeIntervalSince1970
let jsonPayload = try JSON(node: [
"iss": "D86BEC0E8B",
"iat": currentTime
])
let jwt = try! JWT(payload: jsonPayload,
header: try! JSON(node: ["alg":"ES256","kid":"E811E6AE22","typ":"JWT"]),
algorithm: .es(._256("ALEILVyGWnbBaSaIFDsh0yoZaK+Ej0po/55jG2FR6u6C")),
encoding: .base64URL)
let tokenString = try! jwt.token()
do {
let jwt2 = try JWT(token: tokenString, encoding: .base64URL)
let verified = try jwt2.verifySignature(key: "BKqKwB6hpXp9SzWGt3YxnHgCEkcbS+JSrhoqkeqru/Nf62MeE958RIiKYsLFA/czdE7ThCt46azneU0IBnMCuQU=")
XCTAssertTrue(verified)
} catch {
// fatalError("\(error)")
XCTFail ("Couldn't verify token")
}
}
}
|
//
// MIT License
//
// Copyright (c) 2017 Touchwonders Commerce B.V.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
/**
* The TransitionDriver is something the app developer will not be confronted with.
* It is owned by the TransitionController.
* It takes a Transition (specification), sets up UIViewPropertyAnimators, ties it
* all together with gesture recognizers and makes the magic happen.
*/
internal final class TransitionDriver {
let transition: Transition
let operationContext: TransitionOperationContext
let interactionController: TransitionInteractionController?
private var layerAnimators: [AnimationLayerAnimator]! /// This will be set after init
private var sharedElementAnimator: UIViewPropertyAnimator? /// This might be set after init, depending on the presence of both an interactive element and a specification
var context: UIViewControllerContextTransitioning {
return operationContext.context
}
var operation: TransitionOperation {
return operationContext.operation
}
var canBeInteractive : Bool {
return interactionController != nil
}
private let effectiveDuration: TimeInterval
private let completionCoordinator = TransitionCompletionCoordinator()
// We add an invisible view with which something is done (an empty animation block would result in the completion being called immediately).
// It is used in the progressLayerAnimator.
private let progressAnimationView = UIView(frame: .zero)
// Using this animator we have a guaranteed full-AnimationRange layer from which at any moment the overall fractionComplete can be derived.
private var progressLayerAnimator: AnimationLayerAnimator!
// Returns the current overall fractionComplete of the transition
private var totalFractionComplete: AnimationFraction {
return AnimationFraction(progressLayerAnimator.animator.fractionComplete)
}
init(transition: Transition, operationContext: TransitionOperationContext, interactionController: TransitionInteractionController?) {
self.transition = transition
self.operationContext = operationContext
self.interactionController = interactionController
// This is only computed at the very beginning, since any interaction might influence timingCurveProviders, which could change the effective duration:
self.effectiveDuration = transition.effectiveDuration
// We add an invisible view with which something is done (an empty animation block would result in the completion being called immediately).
// Using this animator we have a guaranteed full-AnimationRange layer from which at any moment the overall fractionComplete can be derived.
operationContext.context.containerView.addSubview(progressAnimationView)
let progressLayer = AnimationLayer(range: .full, timingParameters: AnimationTimingParameters(animationCurve: .linear), animation: { [weak self] in
self?.progressAnimationView.transform = CGAffineTransform(translationX: -10, y: 0)
})
self.progressLayerAnimator = AnimationLayerAnimator(layer: progressLayer, animator: propertyAnimatorFor(animationLayer: progressLayer))
completionCoordinator.add(animator: progressLayerAnimator.animator)
progressLayerAnimator.animator.addCompletion({ [weak self] completionPosition in
self?.progressLayerAnimator.completionPosition = completionPosition
})
// The animation must be set up before any interaction,
// because any added views (to the context's containerView) should logically be positioned below
// the interactive element.
transition.animation.setup(in: operationContext)
// See if there's an interactive transition element:
var sharedElement: SharedElement? = nil
if let interactionController = interactionController {
// Get informed about interaction by registering to the interactionController's GestureRecognizer:
let gestureRecognizer = interactionController.gestureRecognizer
gestureRecognizer.addTarget(self, action: #selector(updateInteraction(_:)))
if let sharedElementProvider = interactionController.sharedElementProvider {
sharedElement = sharedElementProvider.sharedElementForInteractiveTransition(with: interactionController, in: operationContext)
}
}
// The transition animation with an interactive element is optional, but if available will lead the base transtion animation, set up right after this.
if let sharedElement = sharedElement, let sharedElementTransitionSpecification = transition.sharedElement {
sharedElementTransitionSpecification.sharedElement = sharedElement
// Now the interaction can be set up, adding the interactive element to the context
transition.sharedElement?.setup(in: operationContext)
// The animator will be set up when the interactive part should animate (i.e. it's not actively interactive).
// Note that it is set up in two parts:
// one configures the property animator, allowing us to determine the exact duration (see further on in this init the effectiveDuration)
// two sets the actual animation and completion of that animator, as soon as it is required in animate()
// Add a long-press gesture recognizer to allow interruption of the animation
sharedElement.transitioningView.addGestureRecognizer(newInterruptionGestureRecognizer())
} else if interactionController != nil {
// There is no interactive element to attach the interruption gesture to, so attach it to the entire containerView of the transition:
context.containerView.addGestureRecognizer(newInterruptionGestureRecognizer())
// We do need to have an interactionController to continue after interruption
}
// Configure execution and completion of transition.animation
layerAnimators = [progressLayerAnimator]
for layer in transition.animation.layers {
let animator = propertyAnimatorFor(animationLayer: layer)
let layerAnimator = AnimationLayerAnimator(layer: layer, animator: animator)
layerAnimators.append(layerAnimator)
}
completionCoordinator.completion { [weak self] in
let completionPosition = self?.progressLayerAnimator.completionPosition ?? .end
// execute any specified completion
transition.animation.completion(position: completionPosition)
transition.sharedElement?.completion(position: completionPosition)
// delegate the completion phase
if completionPosition == .end {
self?.didTransition(with: sharedElement)
} else {
self?.cancelledTransition(with: sharedElement)
}
// cleanup
self?.removeInterruptionGestureRecognizer()
self?.progressAnimationView.removeFromSuperview()
// inform the context we are done
self?.context.completeTransition(completionPosition == .end)
}
willTransition(with: sharedElement)
if context.isInteractive {
// If the transition is initially interactive, make sure the interactive element (if present) is configured appropriately
startInteraction()
} else {
// Begin the animation phase immediately if the transition is not initially interactive
animate(.end)
}
}
// MARK: Property Animators
private func propertyAnimatorFor(animationLayer: AnimationLayer, durationFactor: TimeInterval = 1.0) -> UIViewPropertyAnimator {
let duration = animationLayer.range.length * effectiveDuration * durationFactor
let animator = UIViewPropertyAnimator(duration: duration, timingParameters: animationLayer.timingParameters.timingCurveProvider)
animator.addAnimations(animationLayer.animation)
return animator
}
private func propertyAnimatorForsharedElement() -> UIViewPropertyAnimator? {
guard let specification = transition.sharedElement else { return nil }
let remainingDuration = max(TimeInterval(1.0 - totalFractionComplete) * effectiveDuration, 0.0)
let animator = UIViewPropertyAnimator(duration: remainingDuration, timingParameters: specification.timingParameters.timingCurveProvider)
animator.addAnimations(specification.animation)
return animator
}
// MARK: Animation cycle
func animate(_ toPosition: UIViewAnimatingPosition) {
if let existingSharedElementAnimator = self.sharedElementAnimator {
// The following will ensure that the completion is called (which only contains a DispatchGroup.leave set by the completionCoordinator)
existingSharedElementAnimator.stopAnimation(false)
existingSharedElementAnimator.finishAnimation(at: .current)
}
// Create the animator for the interactive element only when it is needed, and every time we should animate.
// This effectively allows multiple animators to be stacked on the interactive element, smoothing out sharp changes in successive interaction gestures.
if let specification = transition.sharedElement,
let sharedElementAnimator = propertyAnimatorForsharedElement() {
specification.animatingPosition = toPosition
completionCoordinator.add(animator: sharedElementAnimator)
sharedElementAnimator.startAnimation()
self.sharedElementAnimator = sharedElementAnimator
}
let isReversed = toPosition == .start
// The durationFactor dictates how fast the animators should animate. If we're halfway, then they should animate twice as fast (durationFactor: 0.5).
var durationFactor = isReversed ? totalFractionComplete : 1.0 - totalFractionComplete
// If the remaining animation duration should be coupled to the sharedElementAnimator, compute it as a ratio:
if let sharedElementAnimator = sharedElementAnimator {
durationFactor = sharedElementAnimator.duration / effectiveDuration
}
for layerAnimator in layerAnimators {
let animator: UIViewPropertyAnimator = layerAnimator.animator
animator.isReversed = isReversed
let layerPosition = layerAnimator.effectiveRange.position(totalFractionComplete).reversed(isReversed)
switch layerPosition {
case .isBefore: break // We are beyond the range of this layer, so it shouldn't continue or start after a delay.
case .contains:
if animator.state == .inactive {
// this only happens when the animation is started programmatically. FractionComplete will be 0, durationFactor will be 1.
animator.addAnimations(layerAnimator.layer.animation)
animator.startAnimation()
} else {
animator.continueAnimation(withTimingParameters: nil, durationFactor: CGFloat(durationFactor))
}
case .isAfter:
let delay = layerAnimator.effectiveRange.distance(to: totalFractionComplete) * effectiveDuration
// The layer should animate after a specific delay.
if animator.state == .inactive && durationFactor == 1.0 {
// this only happens when the animation is started programmatically. FractionComplete will be 0, durationFactor will be 1.
animator.addAnimations(layerAnimator.layer.animation)
animator.startAnimation(afterDelay: delay)
} else {
// We need to adjust the duration and the delay of the animation. This can only be done by instantiating a new property animator.
let delay = delay * durationFactor
// The following ensures the completion coordinator isn't waiting on the animator that will be removed.
animator.stopAnimation(false)
animator.finishAnimation(at: .current)
// Create a new animator
let animator = propertyAnimatorFor(animationLayer: layerAnimator.layer, durationFactor: durationFactor)
completionCoordinator.add(animator: animator)
// Set it as the new animator for this layer
layerAnimator.animator = animator
animator.startAnimation(afterDelay: delay)
}
}
}
}
private func pauseAnimation() {
// Stop (without finishing) the property animator used for transition item frame changes
sharedElementAnimator?.stopAnimation(true)
// Pause the transition animator
layerAnimators.forEach { $0.animator.pauseAnimation() }
// Inform the transition context that we have paused
context.pauseInteractiveTransition()
}
// MARK: Interaction cycle
var isInteractive: Bool {
return context.isInteractive
}
private func startInteraction(with gestureRecognizer: UIGestureRecognizer? = nil) {
guard let interactionController = interactionController else { return }
if let specification = transition.sharedElement {
specification.startInteraction(in: context, gestureRecognizer: gestureRecognizer ?? interactionController.gestureRecognizer)
}
interactionController.interactionStarted(in: operationContext, gestureRecognizer: gestureRecognizer ?? interactionController.gestureRecognizer, fractionComplete: totalFractionComplete)
}
@objc func updateInteraction(_ gestureRecognizer: UIGestureRecognizer) {
guard let interactionController = interactionController else { return }
switch gestureRecognizer.state {
case .began, .changed:
let progress = interactionController.progress(in: operationContext)
// Calculate the new fractionComplete
let currentFractionComplete = progress.isStep ? (totalFractionComplete + progress.value) : progress.value
for layerAnimator in layerAnimators {
let relativeFractionComplete = layerAnimator.effectiveRange.relativeFractionComplete(to: currentFractionComplete)
// Update the transition animator's fractionCompete to scrub it's animations
layerAnimator.animator.fractionComplete = CGFloat(relativeFractionComplete)
}
// Inform the transition context of the updated percent complete
context.updateInteractiveTransition(CGFloat(currentFractionComplete))
// Update the interactive element, if available
if let specification = transition.sharedElement {
specification.updateInteraction(in: context, interactionController: interactionController, progress: progress)
}
// Reset the gesture recognizer's progress so that we get a step-by-step value each time updateInteraction() is called
interactionController.resetProgressIfNeeded(in: operationContext)
case .ended, .cancelled:
// End the interactive phase of the transition
endInteraction()
default: break
}
}
func endInteraction() {
// Ensure the context is currently interactive
guard context.isInteractive, let interactionController = interactionController else { return }
// Inform the transition context of whether we are finishing or cancelling the transition
let completionPosition = interactionController.completionPosition(in: operationContext, fractionComplete: totalFractionComplete)
if completionPosition == .end {
context.finishInteractiveTransition()
} else {
context.cancelInteractiveTransition()
}
interactionController.interactionEnded(in: operationContext, fractionComplete: totalFractionComplete)
// Begin the animation phase of the transition to either the start or finsh position
animate(completionPosition)
}
// MARK: Transition Interruption
var interruptibleAnimators: [UIViewImplicitlyAnimating] {
return layerAnimators.map { $0.animator }
}
private func newInterruptionGestureRecognizer() -> UIGestureRecognizer {
let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(interruptionGestureStateChanged(_ :)))
longPressGestureRecognizer.minimumPressDuration = 0.0
installedInterruptionGestureRecognizer = longPressGestureRecognizer
return longPressGestureRecognizer
}
// Keep a reference to the interruption GestureRecognizer such that we can properly clean up afterwards.
private weak var installedInterruptionGestureRecognizer: UIGestureRecognizer?
@objc func interruptionGestureStateChanged(_ gestureRecognizer: UILongPressGestureRecognizer) {
switch gestureRecognizer.state {
case .began:
pauseAnimation()
startInteraction(with: gestureRecognizer)
case .ended, .cancelled:
endInteraction()
default: break
}
}
private func removeInterruptionGestureRecognizer() {
if let installedInterruptionGestureRecognizer = installedInterruptionGestureRecognizer {
installedInterruptionGestureRecognizer.view?.removeGestureRecognizer(installedInterruptionGestureRecognizer)
}
}
}
// MARK: Transition phase delegation methods
fileprivate extension TransitionDriver {
private var uniqueTransitionPhaseDelegates: [TransitionPhaseDelegate] {
let uniqueParticipatingViewControllers = Array(Set([context.fromViewController, context.toViewController, operationContext.sourceViewController].flatMap { $0 }))
return uniqueParticipatingViewControllers.flatMap { $0 as? TransitionPhaseDelegate }
}
fileprivate func willTransition(with sharedElement: SharedElement?) {
guard let fromViewController = context.fromViewController, let toViewController = context.toViewController else { return }
uniqueTransitionPhaseDelegates.forEach { $0.willTransition(from: fromViewController, to: toViewController, with: sharedElement) }
}
fileprivate func didTransition(with sharedElement: SharedElement?) {
guard let fromViewController = context.fromViewController, let toViewController = context.toViewController else { return }
uniqueTransitionPhaseDelegates.forEach { $0.didTransition(from: fromViewController, to: toViewController, with: sharedElement) }
}
fileprivate func cancelledTransition(with sharedElement: SharedElement?) {
guard let fromViewController = context.fromViewController, let toViewController = context.toViewController else { return }
uniqueTransitionPhaseDelegates.forEach { $0.cancelledTransition(from: fromViewController, to: toViewController, with: sharedElement) }
}
}
Avoid animation fractionComplete to exceed 0 - 1 range
//
// MIT License
//
// Copyright (c) 2017 Touchwonders Commerce B.V.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
/**
* The TransitionDriver is something the app developer will not be confronted with.
* It is owned by the TransitionController.
* It takes a Transition (specification), sets up UIViewPropertyAnimators, ties it
* all together with gesture recognizers and makes the magic happen.
*/
internal final class TransitionDriver {
let transition: Transition
let operationContext: TransitionOperationContext
let interactionController: TransitionInteractionController?
private var layerAnimators: [AnimationLayerAnimator]! /// This will be set after init
private var sharedElementAnimator: UIViewPropertyAnimator? /// This might be set after init, depending on the presence of both an interactive element and a specification
var context: UIViewControllerContextTransitioning {
return operationContext.context
}
var operation: TransitionOperation {
return operationContext.operation
}
var canBeInteractive : Bool {
return interactionController != nil
}
private let effectiveDuration: TimeInterval
private let completionCoordinator = TransitionCompletionCoordinator()
// We add an invisible view with which something is done (an empty animation block would result in the completion being called immediately).
// It is used in the progressLayerAnimator.
private let progressAnimationView = UIView(frame: .zero)
// Using this animator we have a guaranteed full-AnimationRange layer from which at any moment the overall fractionComplete can be derived.
private var progressLayerAnimator: AnimationLayerAnimator!
// Returns the current overall fractionComplete of the transition
private var totalFractionComplete: AnimationFraction {
return AnimationFraction(progressLayerAnimator.animator.fractionComplete)
}
init(transition: Transition, operationContext: TransitionOperationContext, interactionController: TransitionInteractionController?) {
self.transition = transition
self.operationContext = operationContext
self.interactionController = interactionController
// This is only computed at the very beginning, since any interaction might influence timingCurveProviders, which could change the effective duration:
self.effectiveDuration = transition.effectiveDuration
// We add an invisible view with which something is done (an empty animation block would result in the completion being called immediately).
// Using this animator we have a guaranteed full-AnimationRange layer from which at any moment the overall fractionComplete can be derived.
operationContext.context.containerView.addSubview(progressAnimationView)
let progressLayer = AnimationLayer(range: .full, timingParameters: AnimationTimingParameters(animationCurve: .linear), animation: { [weak self] in
self?.progressAnimationView.transform = CGAffineTransform(translationX: -10, y: 0)
})
self.progressLayerAnimator = AnimationLayerAnimator(layer: progressLayer, animator: propertyAnimatorFor(animationLayer: progressLayer))
completionCoordinator.add(animator: progressLayerAnimator.animator)
progressLayerAnimator.animator.addCompletion({ [weak self] completionPosition in
self?.progressLayerAnimator.completionPosition = completionPosition
})
// The animation must be set up before any interaction,
// because any added views (to the context's containerView) should logically be positioned below
// the interactive element.
transition.animation.setup(in: operationContext)
// See if there's an interactive transition element:
var sharedElement: SharedElement? = nil
if let interactionController = interactionController {
// Get informed about interaction by registering to the interactionController's GestureRecognizer:
let gestureRecognizer = interactionController.gestureRecognizer
gestureRecognizer.addTarget(self, action: #selector(updateInteraction(_:)))
if let sharedElementProvider = interactionController.sharedElementProvider {
sharedElement = sharedElementProvider.sharedElementForInteractiveTransition(with: interactionController, in: operationContext)
}
}
// The transition animation with an interactive element is optional, but if available will lead the base transtion animation, set up right after this.
if let sharedElement = sharedElement, let sharedElementTransitionSpecification = transition.sharedElement {
sharedElementTransitionSpecification.sharedElement = sharedElement
// Now the interaction can be set up, adding the interactive element to the context
transition.sharedElement?.setup(in: operationContext)
// The animator will be set up when the interactive part should animate (i.e. it's not actively interactive).
// Note that it is set up in two parts:
// one configures the property animator, allowing us to determine the exact duration (see further on in this init the effectiveDuration)
// two sets the actual animation and completion of that animator, as soon as it is required in animate()
// Add a long-press gesture recognizer to allow interruption of the animation
sharedElement.transitioningView.addGestureRecognizer(newInterruptionGestureRecognizer())
} else if interactionController != nil {
// There is no interactive element to attach the interruption gesture to, so attach it to the entire containerView of the transition:
context.containerView.addGestureRecognizer(newInterruptionGestureRecognizer())
// We do need to have an interactionController to continue after interruption
}
// Configure execution and completion of transition.animation
layerAnimators = [progressLayerAnimator]
for layer in transition.animation.layers {
let animator = propertyAnimatorFor(animationLayer: layer)
let layerAnimator = AnimationLayerAnimator(layer: layer, animator: animator)
layerAnimators.append(layerAnimator)
}
completionCoordinator.completion { [weak self] in
let completionPosition = self?.progressLayerAnimator.completionPosition ?? .end
// execute any specified completion
transition.animation.completion(position: completionPosition)
transition.sharedElement?.completion(position: completionPosition)
// delegate the completion phase
if completionPosition == .end {
self?.didTransition(with: sharedElement)
} else {
self?.cancelledTransition(with: sharedElement)
}
// cleanup
self?.removeInterruptionGestureRecognizer()
self?.progressAnimationView.removeFromSuperview()
// inform the context we are done
self?.context.completeTransition(completionPosition == .end)
}
willTransition(with: sharedElement)
if context.isInteractive {
// If the transition is initially interactive, make sure the interactive element (if present) is configured appropriately
startInteraction()
} else {
// Begin the animation phase immediately if the transition is not initially interactive
animate(.end)
}
}
// MARK: Property Animators
private func propertyAnimatorFor(animationLayer: AnimationLayer, durationFactor: TimeInterval = 1.0) -> UIViewPropertyAnimator {
let duration = animationLayer.range.length * effectiveDuration * durationFactor
let animator = UIViewPropertyAnimator(duration: duration, timingParameters: animationLayer.timingParameters.timingCurveProvider)
animator.addAnimations(animationLayer.animation)
return animator
}
private func propertyAnimatorForsharedElement() -> UIViewPropertyAnimator? {
guard let specification = transition.sharedElement else { return nil }
let remainingDuration = max(TimeInterval(1.0 - totalFractionComplete) * effectiveDuration, 0.0)
let animator = UIViewPropertyAnimator(duration: remainingDuration, timingParameters: specification.timingParameters.timingCurveProvider)
animator.addAnimations(specification.animation)
return animator
}
// MARK: Animation cycle
func animate(_ toPosition: UIViewAnimatingPosition) {
if let existingSharedElementAnimator = self.sharedElementAnimator {
// The following will ensure that the completion is called (which only contains a DispatchGroup.leave set by the completionCoordinator)
existingSharedElementAnimator.stopAnimation(false)
existingSharedElementAnimator.finishAnimation(at: .current)
}
// Create the animator for the interactive element only when it is needed, and every time we should animate.
// This effectively allows multiple animators to be stacked on the interactive element, smoothing out sharp changes in successive interaction gestures.
if let specification = transition.sharedElement,
let sharedElementAnimator = propertyAnimatorForsharedElement() {
specification.animatingPosition = toPosition
completionCoordinator.add(animator: sharedElementAnimator)
sharedElementAnimator.startAnimation()
self.sharedElementAnimator = sharedElementAnimator
}
let isReversed = toPosition == .start
// The durationFactor dictates how fast the animators should animate. If we're halfway, then they should animate twice as fast (durationFactor: 0.5).
var durationFactor = isReversed ? totalFractionComplete : 1.0 - totalFractionComplete
// If the remaining animation duration should be coupled to the sharedElementAnimator, compute it as a ratio:
if let sharedElementAnimator = sharedElementAnimator {
durationFactor = sharedElementAnimator.duration / effectiveDuration
}
for layerAnimator in layerAnimators {
let animator: UIViewPropertyAnimator = layerAnimator.animator
animator.isReversed = isReversed
let layerPosition = layerAnimator.effectiveRange.position(totalFractionComplete).reversed(isReversed)
switch layerPosition {
case .isBefore: break // We are beyond the range of this layer, so it shouldn't continue or start after a delay.
case .contains:
if animator.state == .inactive {
// this only happens when the animation is started programmatically. FractionComplete will be 0, durationFactor will be 1.
animator.addAnimations(layerAnimator.layer.animation)
animator.startAnimation()
} else {
animator.continueAnimation(withTimingParameters: nil, durationFactor: CGFloat(durationFactor))
}
case .isAfter:
let delay = layerAnimator.effectiveRange.distance(to: totalFractionComplete) * effectiveDuration
// The layer should animate after a specific delay.
if animator.state == .inactive && durationFactor == 1.0 {
// this only happens when the animation is started programmatically. FractionComplete will be 0, durationFactor will be 1.
animator.addAnimations(layerAnimator.layer.animation)
animator.startAnimation(afterDelay: delay)
} else {
// We need to adjust the duration and the delay of the animation. This can only be done by instantiating a new property animator.
let delay = delay * durationFactor
// The following ensures the completion coordinator isn't waiting on the animator that will be removed.
animator.stopAnimation(false)
animator.finishAnimation(at: .current)
// Create a new animator
let animator = propertyAnimatorFor(animationLayer: layerAnimator.layer, durationFactor: durationFactor)
completionCoordinator.add(animator: animator)
// Set it as the new animator for this layer
layerAnimator.animator = animator
animator.startAnimation(afterDelay: delay)
}
}
}
}
private func pauseAnimation() {
// Stop (without finishing) the property animator used for transition item frame changes
sharedElementAnimator?.stopAnimation(true)
// Pause the transition animator
layerAnimators.forEach { $0.animator.pauseAnimation() }
// Inform the transition context that we have paused
context.pauseInteractiveTransition()
}
// MARK: Interaction cycle
var isInteractive: Bool {
return context.isInteractive
}
private func startInteraction(with gestureRecognizer: UIGestureRecognizer? = nil) {
guard let interactionController = interactionController else { return }
if let specification = transition.sharedElement {
specification.startInteraction(in: context, gestureRecognizer: gestureRecognizer ?? interactionController.gestureRecognizer)
}
interactionController.interactionStarted(in: operationContext, gestureRecognizer: gestureRecognizer ?? interactionController.gestureRecognizer, fractionComplete: totalFractionComplete)
}
@objc func updateInteraction(_ gestureRecognizer: UIGestureRecognizer) {
guard let interactionController = interactionController else { return }
switch gestureRecognizer.state {
case .began, .changed:
let progress = interactionController.progress(in: operationContext)
// Calculate the new fractionComplete
let currentFractionComplete = min(max(0.0, progress.isStep ? (totalFractionComplete + progress.value) : progress.value), 1.0)
for layerAnimator in layerAnimators {
let relativeFractionComplete = layerAnimator.effectiveRange.relativeFractionComplete(to: currentFractionComplete)
// Update the transition animator's fractionCompete to scrub it's animations
layerAnimator.animator.fractionComplete = CGFloat(relativeFractionComplete)
}
// Inform the transition context of the updated percent complete
context.updateInteractiveTransition(CGFloat(currentFractionComplete))
// Update the interactive element, if available
if let specification = transition.sharedElement {
specification.updateInteraction(in: context, interactionController: interactionController, progress: progress)
}
// Reset the gesture recognizer's progress so that we get a step-by-step value each time updateInteraction() is called
interactionController.resetProgressIfNeeded(in: operationContext)
case .ended, .cancelled:
// End the interactive phase of the transition
endInteraction()
default: break
}
}
func endInteraction() {
// Ensure the context is currently interactive
guard context.isInteractive, let interactionController = interactionController else { return }
// Inform the transition context of whether we are finishing or cancelling the transition
let completionPosition = interactionController.completionPosition(in: operationContext, fractionComplete: totalFractionComplete)
if completionPosition == .end {
context.finishInteractiveTransition()
} else {
context.cancelInteractiveTransition()
}
interactionController.interactionEnded(in: operationContext, fractionComplete: totalFractionComplete)
// Begin the animation phase of the transition to either the start or finsh position
animate(completionPosition)
}
// MARK: Transition Interruption
var interruptibleAnimators: [UIViewImplicitlyAnimating] {
return layerAnimators.map { $0.animator }
}
private func newInterruptionGestureRecognizer() -> UIGestureRecognizer {
let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(interruptionGestureStateChanged(_ :)))
longPressGestureRecognizer.minimumPressDuration = 0.0
installedInterruptionGestureRecognizer = longPressGestureRecognizer
return longPressGestureRecognizer
}
// Keep a reference to the interruption GestureRecognizer such that we can properly clean up afterwards.
private weak var installedInterruptionGestureRecognizer: UIGestureRecognizer?
@objc func interruptionGestureStateChanged(_ gestureRecognizer: UILongPressGestureRecognizer) {
switch gestureRecognizer.state {
case .began:
pauseAnimation()
startInteraction(with: gestureRecognizer)
case .ended, .cancelled:
endInteraction()
default: break
}
}
private func removeInterruptionGestureRecognizer() {
if let installedInterruptionGestureRecognizer = installedInterruptionGestureRecognizer {
installedInterruptionGestureRecognizer.view?.removeGestureRecognizer(installedInterruptionGestureRecognizer)
}
}
}
// MARK: Transition phase delegation methods
fileprivate extension TransitionDriver {
private var uniqueTransitionPhaseDelegates: [TransitionPhaseDelegate] {
let uniqueParticipatingViewControllers = Array(Set([context.fromViewController, context.toViewController, operationContext.sourceViewController].flatMap { $0 }))
return uniqueParticipatingViewControllers.flatMap { $0 as? TransitionPhaseDelegate }
}
fileprivate func willTransition(with sharedElement: SharedElement?) {
guard let fromViewController = context.fromViewController, let toViewController = context.toViewController else { return }
uniqueTransitionPhaseDelegates.forEach { $0.willTransition(from: fromViewController, to: toViewController, with: sharedElement) }
}
fileprivate func didTransition(with sharedElement: SharedElement?) {
guard let fromViewController = context.fromViewController, let toViewController = context.toViewController else { return }
uniqueTransitionPhaseDelegates.forEach { $0.didTransition(from: fromViewController, to: toViewController, with: sharedElement) }
}
fileprivate func cancelledTransition(with sharedElement: SharedElement?) {
guard let fromViewController = context.fromViewController, let toViewController = context.toViewController else { return }
uniqueTransitionPhaseDelegates.forEach { $0.cancelledTransition(from: fromViewController, to: toViewController, with: sharedElement) }
}
}
|
//
// TutorialBuilder.swift
// TweenController
//
// Created by Dalton Claybrook on 5/26/16.
// Copyright © 2016 Claybrook Software. All rights reserved.
//
import UIKit
import TweenController
protocol TutorialViewController: class {
var containerView: UIView! { get }
var buttonsContainerView: UIView! { get }
var pageControl: UIPageControl! { get }
}
struct TutorialBuilder {
private static let starsSize = CGSize(width: 326, height: 462)
private static let baselineScreenWidth: CGFloat = 414
private static let baselineCardViewHeight: CGFloat = 496
private static let cardYOffset: CGFloat = 186.0
private static let cardYTranslation: CGFloat = -28.0
//MARK: Public
static func buildWithContainerViewController(viewController: TutorialViewController) -> (TweenController, UIScrollView) {
let tweenController = TweenController()
let scrollView = layoutViewsWithVC(viewController)
describeBottomControlsWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
observeEndOfScrollView(viewController, tweenController: tweenController, scrollView: scrollView)
describeBackgroundWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
describeTextWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
describeCardTextWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
describeCardImageWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
describeCardFacesWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
describePinHillWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
return (tweenController, scrollView)
}
//MARK: Private
//MARK: Initial Layout
private static func layoutViewsWithVC(vc: TutorialViewController) -> UIScrollView {
let scrollView = UIScrollView(frame: vc.containerView.bounds)
guard let superview = vc.containerView.superview else { return scrollView }
layoutButtonsAndPageControlWithVC(vc, scrollView: scrollView)
superview.addSubview(scrollView)
return scrollView
}
private static func layoutButtonsAndPageControlWithVC(vc: TutorialViewController, scrollView: UIScrollView) {
let snapshot = vc.containerView.snapshotViewAfterScreenUpdates(true)
scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
let viewSize = vc.containerView.bounds.size
scrollView.contentSize = CGSizeMake(viewSize.width * 6.0, viewSize.height)
vc.pageControl.numberOfPages = 5
vc.containerView.translatesAutoresizingMaskIntoConstraints = true
scrollView.addSubview(vc.containerView)
let xOffset = scrollView.contentSize.width - viewSize.width
snapshot.frame = vc.containerView.frame.offsetBy(dx: xOffset, dy: 0.0)
scrollView.addSubview(snapshot)
let buttonsFrame = vc.buttonsContainerView.convertRect(vc.buttonsContainerView.bounds, toView: scrollView)
let pageControlFrame = vc.pageControl.convertRect(vc.pageControl.bounds, toView: scrollView)
vc.buttonsContainerView.translatesAutoresizingMaskIntoConstraints = true
vc.pageControl.translatesAutoresizingMaskIntoConstraints = true
scrollView.addSubview(vc.buttonsContainerView)
scrollView.addSubview(vc.pageControl)
vc.buttonsContainerView.frame = buttonsFrame
vc.pageControl.frame = pageControlFrame
}
//MARK: Tutorial Actions
private static func describeBottomControlsWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportSize = vc.containerView.frame.size
let startingButtonFrame = vc.buttonsContainerView.frame
let startingPageControlFrame = vc.pageControl.frame
tweenController.tweenFrom(startingButtonFrame, at: -1.0)
.to(startingButtonFrame, at: 0.0)
.thenTo(CGRect(x: startingButtonFrame.minX, y: viewportSize.height, width: startingButtonFrame.width, height: startingButtonFrame.height), at: 1.0)
.thenHoldUntil(4.0)
.thenTo(startingButtonFrame, at: 5.0)
.withAction(vc.buttonsContainerView.twc_slidingFrameActionWithScrollView(scrollView))
let nextPageControlFrame = CGRect(x: startingPageControlFrame.minX, y: startingPageControlFrame.minY + startingButtonFrame.height, width: startingPageControlFrame.width, height: startingPageControlFrame.height)
tweenController.tweenFrom(startingPageControlFrame, at: 0.0)
.to(nextPageControlFrame, at: 1.0)
.thenHoldUntil(4.0)
.thenTo(startingPageControlFrame, at: 5.0)
.withAction(vc.pageControl.twc_slidingFrameActionWithScrollView(scrollView))
}
private static func describeBackgroundWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
describeStarGradientWithVC(vc, tweenController: tweenController, scrollView: scrollView)
describeStarsWithVC(vc, tweenController: tweenController, scrollView: scrollView)
describeEiffelTowerWithVC(vc, tweenController: tweenController, scrollView: scrollView)
}
private static func describeStarGradientWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let topColor = UIColor(red: 155.0/255.0, green: 39.0/255.0, blue: 153.0/255.0, alpha: 1.0)
let bottomColor = UIColor(red: 38.0/255.0, green: 198.0/255.0, blue: 218.0/255.0, alpha: 1.0)
let gradientLayer = CAGradientLayer()
let gradientView = UIView(frame: viewportFrame.offsetBy(dx: viewportFrame.width, dy: 0.0))
gradientLayer.colors = [bottomColor.CGColor, topColor.CGColor]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
gradientLayer.frame = viewportFrame
gradientView.backgroundColor = UIColor.clearColor()
gradientView.layer.addSublayer(gradientLayer)
gradientView.alpha = 0.0
scrollView.insertSubview(gradientView, belowSubview: vc.pageControl)
tweenController.tweenFrom(viewportFrame, at: 1.0)
.thenHoldUntil(3.0)
.withAction(gradientView.twc_slidingFrameActionWithScrollView(scrollView))
tweenController.tweenFrom(gradientView.alpha, at: 1.0)
.to(1.0, at: 2.0)
.thenTo(0.0, at: 3.0)
.withAction(gradientView.twc_applyAlpha)
}
private static func describeStarsWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportSize = vc.containerView.frame.size
let xOffset = (viewportSize.width-starsSize.width)/2.0
let starsFrame = CGRect(x: xOffset, y: 0.0, width: starsSize.width, height: starsSize.height)
let starsImageView = UIImageView(image: UIImage(named: "stars"))
starsImageView.frame = starsFrame.offsetBy(dx: viewportSize.width, dy: 0.0)
starsImageView.alpha = 0.0
starsImageView.contentMode = .ScaleToFill
scrollView.insertSubview(starsImageView, belowSubview: vc.pageControl)
tweenController.tweenFrom(starsFrame, at: 1.0)
.thenHoldUntil(3.0)
.withAction(starsImageView.twc_slidingFrameActionWithScrollView(scrollView))
tweenController.tweenFrom(starsImageView.alpha, at: 1.0)
.to(1.0, at: 2.0)
.thenTo(0.0, at: 3.0)
.withAction(starsImageView.twc_applyAlpha)
}
private static func describeEiffelTowerWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let imageView = UIImageView(image: UIImage(named: "eiffel_tower"))
imageView.frame = viewportFrame.offsetBy(dx: viewportFrame.width * 2.0, dy: 0.0)
imageView.alpha = 0.0
scrollView.addSubview(imageView)
tweenController.tweenFrom(viewportFrame, at: 2.0)
.thenHoldUntil(4.0)
.withAction(imageView.twc_slidingFrameActionWithScrollView(scrollView))
tweenController.tweenFrom(imageView.alpha, at: 2.0)
.to(1.0, at: 3.0)
.thenHoldUntil(4.0)
.thenTo(0.0, at: 5.0)
.withAction(imageView.twc_applyAlpha)
}
private static func describeTextWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let multiplier = viewportFrame.width / baselineScreenWidth
let topYOffset = 50 * multiplier
let bottomYOffset = 80 * multiplier
let topView1 = UIImageView(image: UIImage(named: "top_copy_s2"))
let topView2 = UIImageView(image: UIImage(named: "top_copy_s3"))
let topView3 = UIImageView(image: UIImage(named: "top_copy_s4"))
let topView4 = UIImageView(image: UIImage(named: "top_copy_s5"))
let bottomView1 = UIImageView(image: UIImage(named: "bottom_copy_s2"))
let bottomView2 = UIImageView(image: UIImage(named: "bottom_copy_s3"))
let bottomView3 = UIImageView(image: UIImage(named: "bottom_copy_s4"))
let bottomView4 = UIImageView(image: UIImage(named: "bottom_copy_s5"))
let bottomViews = [bottomView1, bottomView2, bottomView3, bottomView4]
for i in 0..<bottomViews.count {
let view = bottomViews[i]
let size = CGSize(width: view.image!.size.width * multiplier, height: view.image!.size.height * multiplier)
let xOffset = (viewportFrame.width - size.width) / 2.0
view.frame = CGRect(x: CGFloat(i + 1) * viewportFrame.width + xOffset, y: bottomYOffset, width: size.width, height: size.height)
scrollView.addSubview(view)
}
tweenController.tweenFrom(bottomView4.alpha, at: 3.0)
.thenHoldUntil(4.0)
.thenTo(0.0, at: 5.0)
.withAction(bottomView4.twc_applyAlpha)
let topViews = [topView1, topView2, topView3, topView4]
for i in 0..<topViews.count {
let view = topViews[i]
let size = CGSize(width: view.image!.size.width * multiplier, height: view.image!.size.height * multiplier)
let xOffset = (viewportFrame.width - size.width) / 2.0 + viewportFrame.width
view.frame = CGRect(x: xOffset, y: topYOffset, width: size.width, height: size.height)
scrollView.addSubview(view)
if i != 0 {
view.alpha = 0.0
let progress = CGFloat(i) + 0.5
tweenController.tweenFrom(view.alpha, at: progress)
.to(1.0, at: progress + 0.5)
.thenTo(0.0, at: progress + 1.0)
.withAction(view.twc_applyAlpha)
} else {
tweenController.tweenFrom(view.alpha, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(0.0, at: 1.5)
.withAction(view.twc_applyAlpha)
}
tweenController.tweenFrom(view.frame, at: 0.0)
.to(view.frame.offsetBy(dx: -viewportFrame.width, dy: 0.0), at: 1.0)
.thenHoldUntil(4.0)
.withAction(view.twc_slidingFrameActionWithScrollView(scrollView))
}
}
private static func describeCardTextWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let multiplier = viewportFrame.width / baselineScreenWidth
// Text Box
let textImage = UIImage(named: "message_bubble")
let textView1 = UIImageView(image: textImage)
let textView2 = UIImageView(image: textImage)
scrollView.addSubview(textView1)
scrollView.addSubview(textView2)
let boxImageSize = CGSize(width: textImage!.size.width * multiplier, height: textImage!.size.height * multiplier)
let cardImageSize = (UIImage(named: "sunrise")?.size).flatMap() { CGSize(width: $0.width * multiplier, height: $0.height * multiplier) }!
let xOffset1 = 40.0 * multiplier + viewportFrame.width
let xOffset2 = (viewportFrame.width - boxImageSize.width) / 2.0 + viewportFrame.width * 2.0
let yOffset1 = -16.0 * multiplier + cardYOffset * multiplier + cardImageSize.height
let yOffset2 = -16.0 * multiplier + cardYOffset * multiplier + cardYTranslation * multiplier + cardImageSize.height
let frame1 = CGRect(x: xOffset1, y: yOffset1, width: boxImageSize.width, height: boxImageSize.height)
let frame2 = CGRect(x: xOffset2, y: yOffset2, width: boxImageSize.width, height: boxImageSize.height)
textView1.frame = frame1
textView2.frame = frame2.offsetBy(dx: viewportFrame.width, dy: 0.0)
tweenController.tweenFrom(frame1, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(frame2, at: 2.0)
.withAction(textView1.twc_applyFrame)
// Box Contents
let contentsView1 = UIImageView(image: UIImage(named: "card_copy_s2"))
let contentsView2 = UIImageView(image: UIImage(named: "card_copy_s3"))
let contentsView3 = UIImageView(image: UIImage(named: "card_copy_s4"))
let contents1Size = CGSize(width: contentsView1.image!.size.width * multiplier, height: contentsView1.image!.size.height * multiplier)
let contents2Size = CGSize(width: contentsView2.image!.size.width * multiplier, height: contentsView2.image!.size.height * multiplier)
let contents3Size = CGSize(width: contentsView3.image!.size.width * multiplier, height: contentsView3.image!.size.height * multiplier)
let yMod = -12.0 * multiplier
contentsView1.frame = CGRect(x: (boxImageSize.width-contents1Size.width)/2.0, y: (boxImageSize.height-contents1Size.height)/2.0 + yMod, width: contents1Size.width, height: contents1Size.height)
contentsView2.frame = CGRect(x: (boxImageSize.width-contents2Size.width)/2.0, y: (boxImageSize.height-contents2Size.height)/2.0 + yMod, width: contents2Size.width, height: contents2Size.height)
contentsView3.frame = CGRect(x: (boxImageSize.width-contents3Size.width)/2.0, y: (boxImageSize.height-contents3Size.height)/2.0 + yMod, width: contents3Size.width, height: contents3Size.height)
textView1.addSubview(contentsView1)
textView1.addSubview(contentsView2)
textView2.addSubview(contentsView3)
contentsView2.alpha = 0.0
tweenController.tweenFrom(contentsView1.alpha, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(0.0, at: 2.0)
.withAction(contentsView1.twc_applyAlpha)
tweenController.tweenFrom(contentsView2.alpha, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(1.0, at: 2.0)
.withAction(contentsView2.twc_applyAlpha)
}
private static func describeCardImageWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let sunriseView = UIImageView(image: UIImage(named: "sunrise"))
let birthdayView = UIImageView(image: UIImage(named: "birthday_cake"))
let eiffelView = UIImageView(image: UIImage(named: "eiffel"))
scrollView.addSubview(sunriseView)
scrollView.addSubview(birthdayView)
scrollView.addSubview(eiffelView)
let multiplier = viewportFrame.width / baselineScreenWidth
let imageSize = CGSize(width: sunriseView.image!.size.width * multiplier, height: sunriseView.image!.size.height * multiplier)
let imageXOffset = (viewportFrame.width - imageSize.width) / 2.0
let imageYOffset = cardYOffset * multiplier
let frame1 = CGRect(x: viewportFrame.width + imageXOffset, y: imageYOffset, width: imageSize.width, height: imageSize.height)
let frame2 = frame1.offsetBy(dx: viewportFrame.width, dy: cardYTranslation * multiplier)
sunriseView.frame = frame1
birthdayView.frame = frame1
eiffelView.frame = frame2.offsetBy(dx: viewportFrame.width, dy: 0.0)
tweenController.tweenFrom(frame1, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(frame2, at: 2.0)
.withAction(sunriseView.twc_applyFrame)
tweenController.tweenFrom(frame1, at: 1.0)
.to(frame2, at: 2.0)
.withAction(birthdayView.twc_applyFrame)
birthdayView.alpha = 0.0
tweenController.tweenFrom(sunriseView.alpha, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(0.0, at: 2.0)
.withAction(sunriseView.twc_applyAlpha)
tweenController.tweenFrom(birthdayView.alpha, at: 1.0)
.to(1.0, at: 2.0)
.withAction(birthdayView.twc_applyAlpha)
}
private static func describeCardFacesWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let multiplier = viewportFrame.width / baselineScreenWidth
let dudeImage = UIImage(named: "dude_face")
let chickImage = UIImage(named: "chick_face")
let dudeView1 = UIImageView(image: dudeImage)
let dudeView2 = UIImageView(image: dudeImage)
let chickView = UIImageView(image: chickImage)
scrollView.addSubview(dudeView1)
scrollView.addSubview(dudeView2)
scrollView.addSubview(chickView)
chickView.alpha = 0.0
let imageSize = CGSize(width: dudeImage!.size.width * multiplier, height: dudeImage!.size.height * multiplier)
let xOffset = 250.0 * multiplier
let yOffset = 380.0 * multiplier
let frame1 = CGRect(x: xOffset, y: yOffset, width: imageSize.width, height: imageSize.height)
let frame2 = frame1.offsetBy(dx: 0.0, dy: cardYTranslation * multiplier)
dudeView1.frame = frame1.offsetBy(dx: viewportFrame.width, dy: 0.0)
chickView.frame = frame1.offsetBy(dx: viewportFrame.width, dy: 0.0)
dudeView2.frame = frame2.offsetBy(dx: viewportFrame.width * 3.0, dy: 0.0)
tweenController.tweenFrom(dudeView1.frame, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(frame2.offsetBy(dx: viewportFrame.width * 2.0, dy: 0.0), at: 2.0)
.withAction(dudeView1.twc_applyFrame)
tweenController.tweenFrom(chickView.frame, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(frame2.offsetBy(dx: viewportFrame.width * 2.0, dy: 0.0), at: 2.0)
.withAction(chickView.twc_applyFrame)
tweenController.tweenFrom(dudeView1.alpha, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(0.0, at: 2.0)
.withAction(dudeView1.twc_applyAlpha)
tweenController.tweenFrom(chickView.alpha, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(1.0, at: 2.0)
.withAction(chickView.twc_applyAlpha)
}
private static func describePinHillWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let multiplier = viewportFrame.width / baselineScreenWidth
let hillView = UIImageView(image: UIImage(named: "hill"))
let pinView = UIImageView(image: UIImage(named: "hill_mark"))
scrollView.addSubview(hillView)
scrollView.addSubview(pinView)
let hillSize = CGSize(width: hillView.image!.size.width * multiplier, height: hillView.image!.size.height * multiplier)
let pinSize = CGSize(width: pinView.image!.size.width * multiplier, height: pinView.image!.size.height * multiplier)
let pinBottomOffset = 24.0 * multiplier
let pinXOffset = 28.0 * multiplier
let yTranslation = pinSize.height + pinBottomOffset
let hillTopPadding = yTranslation - hillSize.height
let hillXMod = -4.0 * multiplier
let hillYMod = 4.0 * multiplier
hillView.frame = CGRect(x: hillXMod, y: viewportFrame.maxY + hillTopPadding + hillYMod, width: hillSize.width, height: hillSize.height)
pinView.frame = CGRect(x: pinXOffset, y: viewportFrame.maxY, width: pinSize.width, height: pinSize.height)
tweenController.tweenFrom(hillView.frame, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(hillView.frame.offsetBy(dx: 0.0, dy: -yTranslation), at: 2.0)
.thenTo(hillView.frame, at: 3.0)
.withAction(hillView.twc_slidingFrameActionWithScrollView(scrollView))
tweenController.tweenFrom(pinView.frame, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(pinView.frame.offsetBy(dx: 0.0, dy: -yTranslation), at: 2.0)
.thenHoldUntil(3.0)
.thenTo(pinView.frame.offsetBy(dx: -viewportFrame.width, dy: -yTranslation), at: 4.0)
.withAction(pinView.twc_slidingFrameActionWithScrollView(scrollView))
}
//MARK: Observers
private static func observeEndOfScrollView(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
tweenController.observeForwardBoundary(5.0) { [weak scrollView, weak vc, weak tweenController] _ in
scrollView?.contentOffset = CGPointZero
scrollView?.scrollEnabled = false
scrollView?.scrollEnabled = true
tweenController?.resetProgress()
vc?.pageControl.currentPage = 0
}
}
}
Added page 5 animation
//
// TutorialBuilder.swift
// TweenController
//
// Created by Dalton Claybrook on 5/26/16.
// Copyright © 2016 Claybrook Software. All rights reserved.
//
import UIKit
import TweenController
protocol TutorialViewController: class {
var containerView: UIView! { get }
var buttonsContainerView: UIView! { get }
var pageControl: UIPageControl! { get }
}
struct TutorialBuilder {
private static let starsSize = CGSize(width: 326, height: 462)
private static let baselineScreenWidth: CGFloat = 414
private static let baselineCardViewHeight: CGFloat = 496
private static let cardYOffset: CGFloat = 186.0
private static let cardYTranslation: CGFloat = -28.0
//MARK: Public
static func buildWithContainerViewController(viewController: TutorialViewController) -> (TweenController, UIScrollView) {
let tweenController = TweenController()
let scrollView = layoutViewsWithVC(viewController)
describeBottomControlsWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
observeEndOfScrollView(viewController, tweenController: tweenController, scrollView: scrollView)
describeBackgroundWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
describeTextWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
describeCardTextWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
describeCardImageWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
describeCardFacesWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
describePinHillWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
describeAnimationWithVC(viewController, tweenController: tweenController, scrollView: scrollView)
scrollView.bringSubviewToFront(viewController.buttonsContainerView)
scrollView.bringSubviewToFront(viewController.pageControl)
return (tweenController, scrollView)
}
//MARK: Private
//MARK: Initial Layout
private static func layoutViewsWithVC(vc: TutorialViewController) -> UIScrollView {
let scrollView = UIScrollView(frame: vc.containerView.bounds)
guard let superview = vc.containerView.superview else { return scrollView }
layoutButtonsAndPageControlWithVC(vc, scrollView: scrollView)
superview.addSubview(scrollView)
return scrollView
}
private static func layoutButtonsAndPageControlWithVC(vc: TutorialViewController, scrollView: UIScrollView) {
let snapshot = vc.containerView.snapshotViewAfterScreenUpdates(true)
scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
let viewSize = vc.containerView.bounds.size
scrollView.contentSize = CGSizeMake(viewSize.width * 6.0, viewSize.height)
vc.pageControl.numberOfPages = 5
vc.containerView.translatesAutoresizingMaskIntoConstraints = true
scrollView.addSubview(vc.containerView)
let xOffset = scrollView.contentSize.width - viewSize.width
snapshot.frame = vc.containerView.frame.offsetBy(dx: xOffset, dy: 0.0)
scrollView.addSubview(snapshot)
let buttonsFrame = vc.buttonsContainerView.convertRect(vc.buttonsContainerView.bounds, toView: scrollView)
let pageControlFrame = vc.pageControl.convertRect(vc.pageControl.bounds, toView: scrollView)
vc.buttonsContainerView.translatesAutoresizingMaskIntoConstraints = true
vc.pageControl.translatesAutoresizingMaskIntoConstraints = true
scrollView.addSubview(vc.buttonsContainerView)
scrollView.addSubview(vc.pageControl)
vc.buttonsContainerView.frame = buttonsFrame
vc.pageControl.frame = pageControlFrame
}
//MARK: Tutorial Actions
private static func describeBottomControlsWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportSize = vc.containerView.frame.size
let startingButtonFrame = vc.buttonsContainerView.frame
let startingPageControlFrame = vc.pageControl.frame
tweenController.tweenFrom(startingButtonFrame, at: -1.0)
.to(startingButtonFrame, at: 0.0)
.thenTo(CGRect(x: startingButtonFrame.minX, y: viewportSize.height, width: startingButtonFrame.width, height: startingButtonFrame.height), at: 1.0)
.thenHoldUntil(4.0)
.thenTo(startingButtonFrame, at: 5.0)
.withAction(vc.buttonsContainerView.twc_slidingFrameActionWithScrollView(scrollView))
let nextPageControlFrame = CGRect(x: startingPageControlFrame.minX, y: startingPageControlFrame.minY + startingButtonFrame.height, width: startingPageControlFrame.width, height: startingPageControlFrame.height)
tweenController.tweenFrom(startingPageControlFrame, at: 0.0)
.to(nextPageControlFrame, at: 1.0)
.thenHoldUntil(4.0)
.thenTo(startingPageControlFrame, at: 5.0)
.withAction(vc.pageControl.twc_slidingFrameActionWithScrollView(scrollView))
}
private static func describeBackgroundWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
describeStarGradientWithVC(vc, tweenController: tweenController, scrollView: scrollView)
describeStarsWithVC(vc, tweenController: tweenController, scrollView: scrollView)
describeEiffelTowerWithVC(vc, tweenController: tweenController, scrollView: scrollView)
}
private static func describeStarGradientWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let topColor = UIColor(red: 155.0/255.0, green: 39.0/255.0, blue: 153.0/255.0, alpha: 1.0)
let bottomColor = UIColor(red: 38.0/255.0, green: 198.0/255.0, blue: 218.0/255.0, alpha: 1.0)
let gradientLayer = CAGradientLayer()
let gradientView = UIView(frame: viewportFrame.offsetBy(dx: viewportFrame.width, dy: 0.0))
gradientLayer.colors = [bottomColor.CGColor, topColor.CGColor]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
gradientLayer.frame = viewportFrame
gradientView.backgroundColor = UIColor.clearColor()
gradientView.layer.addSublayer(gradientLayer)
gradientView.alpha = 0.0
scrollView.insertSubview(gradientView, belowSubview: vc.pageControl)
tweenController.tweenFrom(viewportFrame, at: 1.0)
.thenHoldUntil(3.0)
.withAction(gradientView.twc_slidingFrameActionWithScrollView(scrollView))
tweenController.tweenFrom(gradientView.alpha, at: 1.0)
.to(1.0, at: 2.0)
.thenTo(0.0, at: 3.0)
.withAction(gradientView.twc_applyAlpha)
}
private static func describeStarsWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportSize = vc.containerView.frame.size
let xOffset = (viewportSize.width-starsSize.width)/2.0
let starsFrame = CGRect(x: xOffset, y: 0.0, width: starsSize.width, height: starsSize.height)
let starsImageView = UIImageView(image: UIImage(named: "stars"))
starsImageView.frame = starsFrame.offsetBy(dx: viewportSize.width, dy: 0.0)
starsImageView.alpha = 0.0
starsImageView.contentMode = .ScaleToFill
scrollView.insertSubview(starsImageView, belowSubview: vc.pageControl)
tweenController.tweenFrom(starsFrame, at: 1.0)
.thenHoldUntil(3.0)
.withAction(starsImageView.twc_slidingFrameActionWithScrollView(scrollView))
tweenController.tweenFrom(starsImageView.alpha, at: 1.0)
.to(1.0, at: 2.0)
.thenTo(0.0, at: 3.0)
.withAction(starsImageView.twc_applyAlpha)
}
private static func describeEiffelTowerWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let imageView = UIImageView(image: UIImage(named: "eiffel_tower"))
imageView.frame = viewportFrame.offsetBy(dx: viewportFrame.width * 2.0, dy: 0.0)
imageView.alpha = 0.0
scrollView.addSubview(imageView)
tweenController.tweenFrom(viewportFrame, at: 2.0)
.thenHoldUntil(4.0)
.withAction(imageView.twc_slidingFrameActionWithScrollView(scrollView))
tweenController.tweenFrom(imageView.alpha, at: 2.0)
.to(1.0, at: 3.0)
.thenHoldUntil(4.0)
.thenTo(0.0, at: 5.0)
.withAction(imageView.twc_applyAlpha)
}
private static func describeTextWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let multiplier = viewportFrame.width / baselineScreenWidth
let topYOffset = 50 * multiplier
let bottomYOffset = 80 * multiplier
let topView1 = UIImageView(image: UIImage(named: "top_copy_s2"))
let topView2 = UIImageView(image: UIImage(named: "top_copy_s3"))
let topView3 = UIImageView(image: UIImage(named: "top_copy_s4"))
let topView4 = UIImageView(image: UIImage(named: "top_copy_s5"))
let bottomView1 = UIImageView(image: UIImage(named: "bottom_copy_s2"))
let bottomView2 = UIImageView(image: UIImage(named: "bottom_copy_s3"))
let bottomView3 = UIImageView(image: UIImage(named: "bottom_copy_s4"))
let bottomView4 = UIImageView(image: UIImage(named: "bottom_copy_s5"))
let bottomViews = [bottomView1, bottomView2, bottomView3, bottomView4]
for i in 0..<bottomViews.count {
let view = bottomViews[i]
let size = CGSize(width: view.image!.size.width * multiplier, height: view.image!.size.height * multiplier)
let xOffset = (viewportFrame.width - size.width) / 2.0
view.frame = CGRect(x: CGFloat(i + 1) * viewportFrame.width + xOffset, y: bottomYOffset, width: size.width, height: size.height)
scrollView.addSubview(view)
}
tweenController.tweenFrom(bottomView4.alpha, at: 3.0)
.thenHoldUntil(4.0)
.thenTo(0.0, at: 5.0)
.withAction(bottomView4.twc_applyAlpha)
let topViews = [topView1, topView2, topView3, topView4]
for i in 0..<topViews.count {
let view = topViews[i]
let size = CGSize(width: view.image!.size.width * multiplier, height: view.image!.size.height * multiplier)
let xOffset = (viewportFrame.width - size.width) / 2.0 + viewportFrame.width
view.frame = CGRect(x: xOffset, y: topYOffset, width: size.width, height: size.height)
scrollView.addSubview(view)
if i != 0 {
view.alpha = 0.0
let progress = CGFloat(i) + 0.5
tweenController.tweenFrom(view.alpha, at: progress)
.to(1.0, at: progress + 0.5)
.thenTo(0.0, at: progress + 1.0)
.withAction(view.twc_applyAlpha)
} else {
tweenController.tweenFrom(view.alpha, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(0.0, at: 1.5)
.withAction(view.twc_applyAlpha)
}
tweenController.tweenFrom(view.frame, at: 0.0)
.to(view.frame.offsetBy(dx: -viewportFrame.width, dy: 0.0), at: 1.0)
.thenHoldUntil(4.0)
.withAction(view.twc_slidingFrameActionWithScrollView(scrollView))
}
}
private static func describeCardTextWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let multiplier = viewportFrame.width / baselineScreenWidth
// Text Box
let textImage = UIImage(named: "message_bubble")
let textView1 = UIImageView(image: textImage)
let textView2 = UIImageView(image: textImage)
scrollView.addSubview(textView1)
scrollView.addSubview(textView2)
let boxImageSize = CGSize(width: textImage!.size.width * multiplier, height: textImage!.size.height * multiplier)
let cardImageSize = (UIImage(named: "sunrise")?.size).flatMap() { CGSize(width: $0.width * multiplier, height: $0.height * multiplier) }!
let xOffset1 = 40.0 * multiplier + viewportFrame.width
let xOffset2 = (viewportFrame.width - boxImageSize.width) / 2.0 + viewportFrame.width * 2.0
let yOffset1 = -16.0 * multiplier + cardYOffset * multiplier + cardImageSize.height
let yOffset2 = -16.0 * multiplier + cardYOffset * multiplier + cardYTranslation * multiplier + cardImageSize.height
let frame1 = CGRect(x: xOffset1, y: yOffset1, width: boxImageSize.width, height: boxImageSize.height)
let frame2 = CGRect(x: xOffset2, y: yOffset2, width: boxImageSize.width, height: boxImageSize.height)
textView1.frame = frame1
textView2.frame = frame2.offsetBy(dx: viewportFrame.width, dy: 0.0)
tweenController.tweenFrom(frame1, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(frame2, at: 2.0)
.withAction(textView1.twc_applyFrame)
// Box Contents
let contentsView1 = UIImageView(image: UIImage(named: "card_copy_s2"))
let contentsView2 = UIImageView(image: UIImage(named: "card_copy_s3"))
let contentsView3 = UIImageView(image: UIImage(named: "card_copy_s4"))
let contents1Size = CGSize(width: contentsView1.image!.size.width * multiplier, height: contentsView1.image!.size.height * multiplier)
let contents2Size = CGSize(width: contentsView2.image!.size.width * multiplier, height: contentsView2.image!.size.height * multiplier)
let contents3Size = CGSize(width: contentsView3.image!.size.width * multiplier, height: contentsView3.image!.size.height * multiplier)
let yMod = -12.0 * multiplier
contentsView1.frame = CGRect(x: (boxImageSize.width-contents1Size.width)/2.0, y: (boxImageSize.height-contents1Size.height)/2.0 + yMod, width: contents1Size.width, height: contents1Size.height)
contentsView2.frame = CGRect(x: (boxImageSize.width-contents2Size.width)/2.0, y: (boxImageSize.height-contents2Size.height)/2.0 + yMod, width: contents2Size.width, height: contents2Size.height)
contentsView3.frame = CGRect(x: (boxImageSize.width-contents3Size.width)/2.0, y: (boxImageSize.height-contents3Size.height)/2.0 + yMod, width: contents3Size.width, height: contents3Size.height)
textView1.addSubview(contentsView1)
textView1.addSubview(contentsView2)
textView2.addSubview(contentsView3)
contentsView2.alpha = 0.0
tweenController.tweenFrom(contentsView1.alpha, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(0.0, at: 2.0)
.withAction(contentsView1.twc_applyAlpha)
tweenController.tweenFrom(contentsView2.alpha, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(1.0, at: 2.0)
.withAction(contentsView2.twc_applyAlpha)
}
private static func describeCardImageWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let sunriseView = UIImageView(image: UIImage(named: "sunrise"))
let birthdayView = UIImageView(image: UIImage(named: "birthday_cake"))
let eiffelView = UIImageView(image: UIImage(named: "eiffel"))
scrollView.addSubview(sunriseView)
scrollView.addSubview(birthdayView)
scrollView.addSubview(eiffelView)
let multiplier = viewportFrame.width / baselineScreenWidth
let imageSize = CGSize(width: sunriseView.image!.size.width * multiplier, height: sunriseView.image!.size.height * multiplier)
let imageXOffset = (viewportFrame.width - imageSize.width) / 2.0
let imageYOffset = cardYOffset * multiplier
let frame1 = CGRect(x: viewportFrame.width + imageXOffset, y: imageYOffset, width: imageSize.width, height: imageSize.height)
let frame2 = frame1.offsetBy(dx: viewportFrame.width, dy: cardYTranslation * multiplier)
sunriseView.frame = frame1
birthdayView.frame = frame1
eiffelView.frame = frame2.offsetBy(dx: viewportFrame.width, dy: 0.0)
tweenController.tweenFrom(frame1, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(frame2, at: 2.0)
.withAction(sunriseView.twc_applyFrame)
tweenController.tweenFrom(frame1, at: 1.0)
.to(frame2, at: 2.0)
.withAction(birthdayView.twc_applyFrame)
birthdayView.alpha = 0.0
tweenController.tweenFrom(sunriseView.alpha, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(0.0, at: 2.0)
.withAction(sunriseView.twc_applyAlpha)
tweenController.tweenFrom(birthdayView.alpha, at: 1.0)
.to(1.0, at: 2.0)
.withAction(birthdayView.twc_applyAlpha)
}
private static func describeCardFacesWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let multiplier = viewportFrame.width / baselineScreenWidth
let dudeImage = UIImage(named: "dude_face")
let chickImage = UIImage(named: "chick_face")
let dudeView1 = UIImageView(image: dudeImage)
let dudeView2 = UIImageView(image: dudeImage)
let chickView = UIImageView(image: chickImage)
scrollView.addSubview(dudeView1)
scrollView.addSubview(dudeView2)
scrollView.addSubview(chickView)
chickView.alpha = 0.0
let imageSize = CGSize(width: dudeImage!.size.width * multiplier, height: dudeImage!.size.height * multiplier)
let xOffset = 250.0 * multiplier
let yOffset = 380.0 * multiplier
let frame1 = CGRect(x: xOffset, y: yOffset, width: imageSize.width, height: imageSize.height)
let frame2 = frame1.offsetBy(dx: 0.0, dy: cardYTranslation * multiplier)
dudeView1.frame = frame1.offsetBy(dx: viewportFrame.width, dy: 0.0)
chickView.frame = frame1.offsetBy(dx: viewportFrame.width, dy: 0.0)
dudeView2.frame = frame2.offsetBy(dx: viewportFrame.width * 3.0, dy: 0.0)
tweenController.tweenFrom(dudeView1.frame, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(frame2.offsetBy(dx: viewportFrame.width * 2.0, dy: 0.0), at: 2.0)
.withAction(dudeView1.twc_applyFrame)
tweenController.tweenFrom(chickView.frame, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(frame2.offsetBy(dx: viewportFrame.width * 2.0, dy: 0.0), at: 2.0)
.withAction(chickView.twc_applyFrame)
tweenController.tweenFrom(dudeView1.alpha, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(0.0, at: 2.0)
.withAction(dudeView1.twc_applyAlpha)
tweenController.tweenFrom(chickView.alpha, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(1.0, at: 2.0)
.withAction(chickView.twc_applyAlpha)
}
private static func describePinHillWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let multiplier = viewportFrame.width / baselineScreenWidth
let hillView = UIImageView(image: UIImage(named: "hill"))
let pinView = UIImageView(image: UIImage(named: "hill_mark"))
scrollView.addSubview(hillView)
scrollView.addSubview(pinView)
let hillSize = CGSize(width: hillView.image!.size.width * multiplier, height: hillView.image!.size.height * multiplier)
let pinSize = CGSize(width: pinView.image!.size.width * multiplier, height: pinView.image!.size.height * multiplier)
let pinBottomOffset = 24.0 * multiplier
let pinXOffset = 28.0 * multiplier
let yTranslation = pinSize.height + pinBottomOffset
let hillTopPadding = yTranslation - hillSize.height
let hillXMod = -4.0 * multiplier
let hillYMod = 4.0 * multiplier
hillView.frame = CGRect(x: hillXMod, y: viewportFrame.maxY + hillTopPadding + hillYMod, width: hillSize.width, height: hillSize.height)
pinView.frame = CGRect(x: pinXOffset, y: viewportFrame.maxY, width: pinSize.width, height: pinSize.height)
tweenController.tweenFrom(hillView.frame, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(hillView.frame.offsetBy(dx: 0.0, dy: -yTranslation), at: 2.0)
.thenTo(hillView.frame, at: 3.0)
.withAction(hillView.twc_slidingFrameActionWithScrollView(scrollView))
tweenController.tweenFrom(pinView.frame, at: 0.0)
.thenHoldUntil(1.0)
.thenTo(pinView.frame.offsetBy(dx: 0.0, dy: -yTranslation), at: 2.0)
.thenHoldUntil(3.0)
.thenTo(pinView.frame.offsetBy(dx: -viewportFrame.width, dy: -yTranslation), at: 4.0)
.withAction(pinView.twc_slidingFrameActionWithScrollView(scrollView))
}
private static func describeAnimationWithVC(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
let viewportFrame = CGRect(origin: CGPointZero, size: vc.containerView.frame.size)
let multiplier = viewportFrame.width / baselineScreenWidth
let armDownImage = UIImage(named: "chick_arm_down")
let armUpImage = UIImage(named: "chick_arm_up")
let chickView = UIImageView(image: armDownImage)
let cardView = UIImageView(image: UIImage(named: "card_detail"))
scrollView.addSubview(chickView)
scrollView.addSubview(cardView)
let chickSize = CGSize(width: armDownImage!.size.width * multiplier, height: armDownImage!.size.height * multiplier)
let cardSize = CGSize(width: cardView.image!.size.width * multiplier, height: cardView.image!.size.height * multiplier)
let chickBottomOffset = 38.0 * multiplier
let chickXTranslation = -220.0 * multiplier
let cardXOffset = 82.0 * multiplier + viewportFrame.width * 4.0
let cardStartingYOffset = 174.0 * multiplier
let cardYTranslation = 14.0 * multiplier
let cardStartingFrame = CGRect(x: cardXOffset, y: cardStartingYOffset, width: cardSize.width, height: cardSize.height)
let cardEndingFrame = cardStartingFrame.offsetBy(dx: 0.0, dy: cardYTranslation)
let chickStartingFrame = CGRect(x: viewportFrame.width * 5.0, y: viewportFrame.maxY - chickBottomOffset - chickSize.height, width: chickSize.width, height: chickSize.height)
let chickEndingFrame = chickStartingFrame.offsetBy(dx: chickXTranslation, dy: 0.0)
chickView.frame = chickStartingFrame
cardView.frame = cardStartingFrame
cardView.alpha = 0.0
tweenController.observeForwardBoundary(4.0) { [weak scrollView] _ in
scrollView?.scrollEnabled = false
UIView.animateWithDuration(1.2, animations: { [weak chickView] in
chickView?.frame = chickEndingFrame
}, completion: { [weak chickView] finished in
chickView?.image = armUpImage
UIView.animateWithDuration(0.5, animations: { [weak cardView] in
cardView?.frame = cardEndingFrame
cardView?.alpha = 1.0
}, completion: { finished in
scrollView?.scrollEnabled = true
})
})
}
let resetBlock = { [weak chickView, weak cardView] (_: Double) in
chickView?.image = armDownImage
chickView?.frame = chickStartingFrame
cardView?.frame = cardStartingFrame
chickView?.alpha = 1.0
cardView?.alpha = 0.0
}
tweenController.observeBackwardBoundary(3.0, block: resetBlock)
tweenController.observeForwardBoundary(5.0, block: resetBlock)
tweenController.tweenFrom(CGFloat(1.0), at: 4.25)
.to(0.0, at: 5.0)
.withAction(cardView.twc_applyAlpha)
tweenController.tweenFrom(CGFloat(1.0), at: 3.0)
.thenHoldUntil(4.25)
.thenTo(0.0, at: 5.0)
.withAction(chickView.twc_applyAlpha)
}
//MARK: Observers
private static func observeEndOfScrollView(vc: TutorialViewController, tweenController: TweenController, scrollView: UIScrollView) {
tweenController.observeForwardBoundary(5.0) { [weak scrollView, weak vc, weak tweenController] _ in
scrollView?.contentOffset = CGPointZero
scrollView?.scrollEnabled = false
scrollView?.scrollEnabled = true
tweenController?.resetProgress()
vc?.pageControl.currentPage = 0
}
}
}
|
//
// InfoViewController.swift
// Trigonometry
//
// Created by Andrew McKnight on 1/16/17.
// Copyright © 2017 Two Ring Software. All rights reserved.
//
import Anchorage
import UIKit
class InfoViewController: UIViewController {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required init(thirdPartyKits: [String]?, acknowledgements: String?, titleFont: UIFont, textFont: UIFont) {
super.init(nibName: nil, bundle: nil)
configureUI(thirdPartyKits: thirdPartyKits, acknowledgements: acknowledgements, titleFont: titleFont, textFont: textFont)
}
}
private extension InfoViewController {
func configureUI(thirdPartyKits: [String]?, acknowledgements: String?, titleFont: UIFont, textFont: UIFont) {
view.backgroundColor = UIColor.white
let textView = UITextView(frame: CGRect.zero)
textView.isEditable = false
textView.backgroundColor = nil
textView.textAlignment = .center
textView.dataDetectorTypes = .link
textView.isScrollEnabled = false
textView.linkTextAttributes = [ NSForegroundColorAttributeName: UIColor.lightGray, NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue ]
let version = getBundleInfoWithKey("CFBundleShortVersionString")
let build = getBundleInfoWithKey("CFBundleVersion")
let appNameString = getBundleInfoWithKey("CFBundleName")
let tworingURL = "http://tworingsoft.com"
let copyrightString = "© 2016"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string:
"\(appNameString)" +
"\n\n" +
"version \(version) build \(build)" +
(acknowledgements != nil ? "\n\n\(acknowledgements!)" : "") +
(thirdPartyKits != nil ? "\n\n3rd party software used in this app:\n \(thirdPartyKits!.joined(separator: "\n"))" : "") +
"\n\n" +
" \(copyrightString) b" + // add one space before because otherwise it doesn't center properly after insert logo image
"\n\n\n\n" +
"\(tworingURL)"
)
// style the title
let titleRange = (attributedString.string as NSString).range(of: appNameString)
attributedString.addAttributes([NSFontAttributeName : titleFont], range: titleRange)
// insert two ring logo and style copyright text to match
let copyrightRange = (attributedString.string as NSString).range(of: copyrightString)
attributedString.addAttributes([NSForegroundColorAttributeName: UIColor.lightGray], range: copyrightRange)
let twoRingNameRange = NSMakeRange(copyrightRange.location + copyrightRange.length + 1, 1)
let textAttachment = NSTextAttachment()
let attachmentImage = UIImage(named: "trs-logo")!
textAttachment.image = UIImage(cgImage: attachmentImage.cgImage!, scale: attachmentImage.size.height / textFont.lineHeight * UIScreen.main.scale * 1.7, orientation: .up)
let attrStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.replaceCharacters(in: twoRingNameRange, with: attrStringWithImage)
// center everything
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
attributedString.addAttributes([NSParagraphStyleAttributeName: paragraphStyle], range: NSMakeRange(0, attributedString.string.characters.count))
// set all non-title text to text font
attributedString.addAttributes([NSFontAttributeName: textFont], range: NSMakeRange(titleRange.location + titleRange.length, attributedString.string.characters.count - titleRange.location - titleRange.length))
// set the string
textView.attributedText = attributedString
let width = view.bounds.width
view.addSubview(textView)
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let height = attributedString.boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil).height
let inset = textView.contentInset.top + textView.contentInset.bottom + textView.textContainerInset.top + textView.textContainerInset.bottom
let paddingDelta: CGFloat = 20 // for some reason the bounding size is not computed quite correctly
textView.centerYAnchor == view.centerYAnchor
textView.leadingAnchor == view.leadingAnchor
textView.trailingAnchor == view.trailingAnchor
textView.heightAnchor == height + inset + paddingDelta
}
func getBundleInfoWithKey(_ key: String) -> String {
guard let infoDict = Bundle.main.infoDictionary else {
print("[%s] could not get infoDictionary from mainBundle", type(of: self))
return "?"
}
guard let version = infoDict[key] as? String else {
print("[%s] could not get value from bundle dictionary for key %@", type(of: self), key)
return "?"
}
return version
}
}
update copyright year
//
// InfoViewController.swift
// Trigonometry
//
// Created by Andrew McKnight on 1/16/17.
// Copyright © 2017 Two Ring Software. All rights reserved.
//
import Anchorage
import UIKit
class InfoViewController: UIViewController {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required init(thirdPartyKits: [String]?, acknowledgements: String?, titleFont: UIFont, textFont: UIFont) {
super.init(nibName: nil, bundle: nil)
configureUI(thirdPartyKits: thirdPartyKits, acknowledgements: acknowledgements, titleFont: titleFont, textFont: textFont)
}
}
private extension InfoViewController {
func configureUI(thirdPartyKits: [String]?, acknowledgements: String?, titleFont: UIFont, textFont: UIFont) {
view.backgroundColor = UIColor.white
let textView = UITextView(frame: CGRect.zero)
textView.isEditable = false
textView.backgroundColor = nil
textView.textAlignment = .center
textView.dataDetectorTypes = .link
textView.isScrollEnabled = false
textView.linkTextAttributes = [ NSForegroundColorAttributeName: UIColor.lightGray, NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue ]
let version = getBundleInfoWithKey("CFBundleShortVersionString")
let build = getBundleInfoWithKey("CFBundleVersion")
let appNameString = getBundleInfoWithKey("CFBundleName")
let tworingURL = "http://tworingsoft.com"
let copyrightString = "© 2017"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string:
"\(appNameString)" +
"\n\n" +
"version \(version) build \(build)" +
(acknowledgements != nil ? "\n\n\(acknowledgements!)" : "") +
(thirdPartyKits != nil ? "\n\n3rd party software used in this app:\n \(thirdPartyKits!.joined(separator: "\n"))" : "") +
"\n\n" +
" \(copyrightString) b" + // add one space before because otherwise it doesn't center properly after insert logo image
"\n\n\n\n" +
"\(tworingURL)"
)
// style the title
let titleRange = (attributedString.string as NSString).range(of: appNameString)
attributedString.addAttributes([NSFontAttributeName : titleFont], range: titleRange)
// insert two ring logo and style copyright text to match
let copyrightRange = (attributedString.string as NSString).range(of: copyrightString)
attributedString.addAttributes([NSForegroundColorAttributeName: UIColor.lightGray], range: copyrightRange)
let twoRingNameRange = NSMakeRange(copyrightRange.location + copyrightRange.length + 1, 1)
let textAttachment = NSTextAttachment()
let attachmentImage = UIImage(named: "trs-logo")!
textAttachment.image = UIImage(cgImage: attachmentImage.cgImage!, scale: attachmentImage.size.height / textFont.lineHeight * UIScreen.main.scale * 1.7, orientation: .up)
let attrStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.replaceCharacters(in: twoRingNameRange, with: attrStringWithImage)
// center everything
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
attributedString.addAttributes([NSParagraphStyleAttributeName: paragraphStyle], range: NSMakeRange(0, attributedString.string.characters.count))
// set all non-title text to text font
attributedString.addAttributes([NSFontAttributeName: textFont], range: NSMakeRange(titleRange.location + titleRange.length, attributedString.string.characters.count - titleRange.location - titleRange.length))
// set the string
textView.attributedText = attributedString
let width = view.bounds.width
view.addSubview(textView)
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let height = attributedString.boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil).height
let inset = textView.contentInset.top + textView.contentInset.bottom + textView.textContainerInset.top + textView.textContainerInset.bottom
let paddingDelta: CGFloat = 20 // for some reason the bounding size is not computed quite correctly
textView.centerYAnchor == view.centerYAnchor
textView.leadingAnchor == view.leadingAnchor
textView.trailingAnchor == view.trailingAnchor
textView.heightAnchor == height + inset + paddingDelta
}
func getBundleInfoWithKey(_ key: String) -> String {
guard let infoDict = Bundle.main.infoDictionary else {
print("[%s] could not get infoDictionary from mainBundle", type(of: self))
return "?"
}
guard let version = infoDict[key] as? String else {
print("[%s] could not get value from bundle dictionary for key %@", type(of: self), key)
return "?"
}
return version
}
}
|
import XCTest
class GradeSchoolTest: XCTestCase
{
func testAnEmptySchool() {
let school = GradeSchool()
let expected = [:]
let result = school.db
XCTAssertEqual(result, expected)
}
func testAddStudent() {
var school = GradeSchool() // var
school.addStudent("Aimee", grade: 2)
let result = school.db
let expected: Dictionary = [2: ["Aimee"]]
XCTAssertEqual(result.keys.array, expected.keys.array)
XCTAssertEqual(result[2]!, expected[2]!)
}
func testAddMoreStudentsInSameClass() {
var school = GradeSchool()
school.addStudent("Fred", grade: 2)
school.addStudent("James", grade: 2)
school.addStudent("Paul", grade: 2)
let result = school.db
let expected = [2: ["Fred", "James", "Paul"]]
XCTAssertEqual(result.keys.array, expected.keys.array)
XCTAssertEqual(result[2]!, expected[2]!)
}
func testAddStudentsToDifferentGrades() {
var school = GradeSchool()
school.addStudent("Chelsea", grade: 3)
school.addStudent("Logan", grade: 7)
let result = school.db
let expected = [3: ["Chelsea"], 7: ["Logan"]]
XCTAssertEqual(result.keys.array.sorted(>), expected.keys.array.sorted(>))
XCTAssertEqual(result[3]!, expected[3]!)
}
func testGetStudentsInAGrade() {
var school = GradeSchool()
school.addStudent("Franklin", grade: 5)
school.addStudent("Bradley", grade: 5)
school.addStudent("Jeff", grade: 1)
let result = school.studentsInGrade(5)
let expected = [ "Franklin", "Bradley" ]
XCTAssertEqual(result, expected)
}
func testGetStudentsInANonExistantGrade() {
let school = GradeSchool()
let result = school.studentsInGrade(1)
let expected: [String] = []
XCTAssertEqual(result, expected)
}
func testSortSchool() {
var school = GradeSchool()
school.addStudent("Jennifer", grade:4)
school.addStudent("Kareem", grade:6)
school.addStudent("Christopher", grade:4)
school.addStudent("Kyle", grade: 3)
let result = school.sortedRoster()
let expected = [
3 : ["Kyle"],
4 : [ "Christopher", "Jennifer" ],
6 : [ "Kareem"]
]
XCTAssertEqual(result.keys.array.sorted(>), expected.keys.array.sorted(>))
XCTAssertEqual(result[3]!, expected[3]!)
XCTAssertEqual(result[4]!, expected[4]!)
XCTAssertEqual(result[6]!, expected[6]!)
}
}
remove extra comment
import XCTest
class GradeSchoolTest: XCTestCase
{
func testAnEmptySchool() {
let school = GradeSchool()
let expected = [:]
let result = school.db
XCTAssertEqual(result, expected)
}
func testAddStudent() {
var school = GradeSchool()
school.addStudent("Aimee", grade: 2)
let result = school.db
let expected: Dictionary = [2: ["Aimee"]]
XCTAssertEqual(result.keys.array, expected.keys.array)
XCTAssertEqual(result[2]!, expected[2]!)
}
func testAddMoreStudentsInSameClass() {
var school = GradeSchool()
school.addStudent("Fred", grade: 2)
school.addStudent("James", grade: 2)
school.addStudent("Paul", grade: 2)
let result = school.db
let expected = [2: ["Fred", "James", "Paul"]]
XCTAssertEqual(result.keys.array, expected.keys.array)
XCTAssertEqual(result[2]!, expected[2]!)
}
func testAddStudentsToDifferentGrades() {
var school = GradeSchool()
school.addStudent("Chelsea", grade: 3)
school.addStudent("Logan", grade: 7)
let result = school.db
let expected = [3: ["Chelsea"], 7: ["Logan"]]
XCTAssertEqual(result.keys.array.sorted(>), expected.keys.array.sorted(>))
XCTAssertEqual(result[3]!, expected[3]!)
}
func testGetStudentsInAGrade() {
var school = GradeSchool()
school.addStudent("Franklin", grade: 5)
school.addStudent("Bradley", grade: 5)
school.addStudent("Jeff", grade: 1)
let result = school.studentsInGrade(5)
let expected = [ "Franklin", "Bradley" ]
XCTAssertEqual(result, expected)
}
func testGetStudentsInANonExistantGrade() {
let school = GradeSchool()
let result = school.studentsInGrade(1)
let expected: [String] = []
XCTAssertEqual(result, expected)
}
func testSortSchool() {
var school = GradeSchool()
school.addStudent("Jennifer", grade:4)
school.addStudent("Kareem", grade:6)
school.addStudent("Christopher", grade:4)
school.addStudent("Kyle", grade: 3)
let result = school.sortedRoster()
let expected = [
3 : ["Kyle"],
4 : [ "Christopher", "Jennifer" ],
6 : [ "Kareem"]
]
XCTAssertEqual(result.keys.array.sorted(>), expected.keys.array.sorted(>))
XCTAssertEqual(result[3]!, expected[3]!)
XCTAssertEqual(result[4]!, expected[4]!)
XCTAssertEqual(result[6]!, expected[6]!)
}
} |
//
// This file is part of Blokada.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright © 2021 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import Foundation
import Combine
import UIKit
// Contains "main app state" mostly used in Home screen.
class AppRepo {
var appStateHot: AnyPublisher<AppState, Never> {
self.writeAppState.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
var workingHot: AnyPublisher<Bool, Never> {
self.writeWorking.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
var pausedUntilHot: AnyPublisher<Date?, Never> {
self.writePausedUntil.removeDuplicates().eraseToAnyPublisher()
}
var accountTypeHot: AnyPublisher<AccountType, Never> {
self.writeAccountType.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
private lazy var timer = Services.timer
private lazy var currentlyOngoingHot = Repos.processingRepo.currentlyOngoingHot
private lazy var accountHot = Repos.accountRepo.accountHot
private lazy var cloudRepo = Repos.cloudRepo
fileprivate let writeAppState = CurrentValueSubject<AppState?, Never>(nil)
fileprivate let writeWorking = CurrentValueSubject<Bool?, Never>(nil)
fileprivate let writePausedUntil = CurrentValueSubject<Date?, Never>(nil)
fileprivate let writeAccountType = CurrentValueSubject<AccountType?, Never>(nil)
fileprivate let pauseAppT = Tasker<Date?, Ignored>("pauseApp")
fileprivate let unpauseAppT = SimpleTasker<Ignored>("unpauseApp")
private var cancellables = Set<AnyCancellable>()
private let recentAccountType = Atomic<AccountType>(AccountType.Libre)
init() {
onPauseApp()
onUnpauseApp()
onAnythingThatAffectsAppState_UpdateIt()
onAccountChange_UpdateAccountType()
onCurrentlyOngoing_ChangeWorkingState()
onPause_WaitForExpirationToUnpause()
loadPauseTimerState()
emitWorkingStateOnStart()
}
func pauseApp(until: Date?) -> AnyPublisher<Ignored, Error> {
return pauseAppT.send(until)
}
func unpauseApp() -> AnyPublisher<Ignored, Error> {
return unpauseAppT.send()
}
// App can be paused with a timer (Date), or indefinitely (nil)
private func onPauseApp() { // TODO: also pause plus
pauseAppT.setTask { until in
return self.appStateHot.first()
.flatMap { it -> AnyPublisher<Ignored, Error> in
// App is already paused, only update timer
if it == .Paused {
guard let until = until else {
// Pause indefinitely instead
return self.timer.cancelTimer(NOTIF_PAUSE)
}
return self.timer.createTimer(NOTIF_PAUSE, when: until)
} else if it == .Activated {
guard let until = until else {
// Just pause indefinitely
return self.cloudRepo.setPaused(true)
}
return self.cloudRepo.setPaused(true)
.flatMap { _ in self.timer.createTimer(NOTIF_PAUSE, when: until) }
.eraseToAnyPublisher()
} else {
return Fail(error: "cannot pause, app in wrong state")
.eraseToAnyPublisher()
}
}
.map { _ in
self.writePausedUntil.send(until)
return true
}
.eraseToAnyPublisher()
}
}
private func onUnpauseApp() {
unpauseAppT.setTask { _ in
return self.appStateHot.first()
.flatMap { it -> AnyPublisher<Ignored, Error> in
if it == .Paused {
return self.cloudRepo.setPaused(false)
.flatMap { _ in self.timer.cancelTimer(NOTIF_PAUSE) }
.eraseToAnyPublisher()
} else {
return Fail(error: "cannot unpause, app in wrong state")
.eraseToAnyPublisher()
}
}
.map { _ in
self.writePausedUntil.send(nil)
return true
}
.eraseToAnyPublisher()
}
}
private func onAnythingThatAffectsAppState_UpdateIt() {
Publishers.CombineLatest3(
accountTypeHot,
cloudRepo.dnsProfileActivatedHot,
cloudRepo.adblockingPausedHot
)
.map { it -> AppState in
let (accountType, dnsProfileActivated, adblockingPaused) = it
if !accountType.isActive() {
return AppState.Deactivated
}
if adblockingPaused {
return AppState.Paused
}
if dnsProfileActivated {
return AppState.Activated
}
return AppState.Deactivated
}
.sink(onValue: { it in self.writeAppState.send(it) })
.store(in: &cancellables)
}
private func onAccountChange_UpdateAccountType() {
accountHot.compactMap { it in it.account.type }
.map { it in mapAccountType(it) }
.sink(onValue: { it in
self.recentAccountType.value = it
self.writeAccountType.send(it)
})
.store(in: &cancellables)
}
private func onCurrentlyOngoing_ChangeWorkingState() {
let tasksThatMarkWorkingState = Set([
"accountInit", "refreshAccount", "restoreAccount",
"pauseApp", "unpauseApp",
"newPlus", "clearPlus", "switchPlusOn", "switchPlusOff"
])
currentlyOngoingHot
.map { it in Set(it.map { $0.component }) }
.map { it in !it.intersection(tasksThatMarkWorkingState).isEmpty }
.sink(onValue: { it in self.writeWorking.send(it) })
.store(in: &cancellables)
}
private func onPause_WaitForExpirationToUnpause() {
pausedUntilHot
.compactMap { $0 }
.flatMap { _ in
// This cold producer will finish once the timer expires.
// It will error out whenever this timer is modified.
self.timer.obtainTimer(NOTIF_PAUSE)
}
.flatMap { _ in
self.unpauseApp()
}
.sink()
.store(in: &cancellables)
}
private func loadPauseTimerState() {
timer.getTimerDate(NOTIF_PAUSE)
.tryMap { it in self.writePausedUntil.send(it) }
.sink()
.store(in: &cancellables)
}
private func emitWorkingStateOnStart() {
writeAppState.send(.Paused)
writeWorking.send(true)
}
}
func getDateInTheFuture(seconds: Int) -> Date {
let date = Date()
var components = DateComponents()
components.setValue(seconds, for: .second)
let dateInTheFuture = Calendar.current.date(byAdding: components, to: date)
return dateInTheFuture!
}
class DebugAppRepo: AppRepo {
private let log = Logger("App")
private var cancellables = Set<AnyCancellable>()
override init() {
super.init()
writeAppState.sink(
onValue: { it in
self.log.v("App state: \(it)")
}
)
.store(in: &cancellables)
}
}
ios: fix initial state
//
// This file is part of Blokada.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright © 2021 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import Foundation
import Combine
import UIKit
// Contains "main app state" mostly used in Home screen.
class AppRepo {
var appStateHot: AnyPublisher<AppState, Never> {
self.writeAppState.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
var workingHot: AnyPublisher<Bool, Never> {
self.writeWorking.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
var pausedUntilHot: AnyPublisher<Date?, Never> {
self.writePausedUntil.removeDuplicates().eraseToAnyPublisher()
}
var accountTypeHot: AnyPublisher<AccountType, Never> {
self.writeAccountType.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
private lazy var timer = Services.timer
private lazy var currentlyOngoingHot = Repos.processingRepo.currentlyOngoingHot
private lazy var accountHot = Repos.accountRepo.accountHot
private lazy var cloudRepo = Repos.cloudRepo
fileprivate let writeAppState = CurrentValueSubject<AppState?, Never>(nil)
fileprivate let writeWorking = CurrentValueSubject<Bool?, Never>(nil)
fileprivate let writePausedUntil = CurrentValueSubject<Date?, Never>(nil)
fileprivate let writeAccountType = CurrentValueSubject<AccountType?, Never>(nil)
fileprivate let pauseAppT = Tasker<Date?, Ignored>("pauseApp")
fileprivate let unpauseAppT = SimpleTasker<Ignored>("unpauseApp")
private var cancellables = Set<AnyCancellable>()
private let recentAccountType = Atomic<AccountType>(AccountType.Libre)
init() {
onPauseApp()
onUnpauseApp()
onAnythingThatAffectsAppState_UpdateIt()
onAccountChange_UpdateAccountType()
onCurrentlyOngoing_ChangeWorkingState()
onPause_WaitForExpirationToUnpause()
loadPauseTimerState()
emitWorkingStateOnStart()
}
func pauseApp(until: Date?) -> AnyPublisher<Ignored, Error> {
return pauseAppT.send(until)
}
func unpauseApp() -> AnyPublisher<Ignored, Error> {
return unpauseAppT.send()
}
// App can be paused with a timer (Date), or indefinitely (nil)
private func onPauseApp() { // TODO: also pause plus
pauseAppT.setTask { until in
return self.appStateHot.first()
.flatMap { it -> AnyPublisher<Ignored, Error> in
// App is already paused, only update timer
if it == .Paused {
guard let until = until else {
// Pause indefinitely instead
return self.timer.cancelTimer(NOTIF_PAUSE)
}
return self.timer.createTimer(NOTIF_PAUSE, when: until)
} else if it == .Activated {
guard let until = until else {
// Just pause indefinitely
return self.cloudRepo.setPaused(true)
}
return self.cloudRepo.setPaused(true)
.flatMap { _ in self.timer.createTimer(NOTIF_PAUSE, when: until) }
.eraseToAnyPublisher()
} else {
return Fail(error: "cannot pause, app in wrong state")
.eraseToAnyPublisher()
}
}
.map { _ in
self.writePausedUntil.send(until)
return true
}
.eraseToAnyPublisher()
}
}
private func onUnpauseApp() {
unpauseAppT.setTask { _ in
return self.appStateHot.first()
.flatMap { it -> AnyPublisher<Ignored, Error> in
if it == .Paused {
return self.cloudRepo.setPaused(false)
.flatMap { _ in self.timer.cancelTimer(NOTIF_PAUSE) }
.eraseToAnyPublisher()
} else {
return Fail(error: "cannot unpause, app in wrong state")
.eraseToAnyPublisher()
}
}
.map { _ in
self.writePausedUntil.send(nil)
return true
}
.eraseToAnyPublisher()
}
}
private func onAnythingThatAffectsAppState_UpdateIt() {
Publishers.CombineLatest3(
accountTypeHot,
cloudRepo.dnsProfileActivatedHot,
cloudRepo.adblockingPausedHot
)
.map { it -> AppState in
let (accountType, dnsProfileActivated, adblockingPaused) = it
if !accountType.isActive() {
return AppState.Deactivated
}
if adblockingPaused {
return AppState.Paused
}
if dnsProfileActivated {
return AppState.Activated
}
return AppState.Deactivated
}
.sink(onValue: { it in self.writeAppState.send(it) })
.store(in: &cancellables)
}
private func onAccountChange_UpdateAccountType() {
accountHot.compactMap { it in it.account.type }
.map { it in mapAccountType(it) }
.sink(onValue: { it in
self.recentAccountType.value = it
self.writeAccountType.send(it)
})
.store(in: &cancellables)
}
private func onCurrentlyOngoing_ChangeWorkingState() {
let tasksThatMarkWorkingState = Set([
"accountInit", "refreshAccount", "restoreAccount",
"pauseApp", "unpauseApp",
"newPlus", "clearPlus", "switchPlusOn", "switchPlusOff"
])
currentlyOngoingHot
.map { it in Set(it.map { $0.component }) }
.map { it in !it.intersection(tasksThatMarkWorkingState).isEmpty }
.sink(onValue: { it in self.writeWorking.send(it) })
.store(in: &cancellables)
}
private func onPause_WaitForExpirationToUnpause() {
pausedUntilHot
.compactMap { $0 }
.flatMap { _ in
// This cold producer will finish once the timer expires.
// It will error out whenever this timer is modified.
self.timer.obtainTimer(NOTIF_PAUSE)
}
.flatMap { _ in
self.unpauseApp()
}
.sink()
.store(in: &cancellables)
}
private func loadPauseTimerState() {
timer.getTimerDate(NOTIF_PAUSE)
.tryMap { it in self.writePausedUntil.send(it) }
.sink()
.store(in: &cancellables)
}
private func emitWorkingStateOnStart() {
writeAppState.send(.Deactivated)
writeWorking.send(true)
}
}
func getDateInTheFuture(seconds: Int) -> Date {
let date = Date()
var components = DateComponents()
components.setValue(seconds, for: .second)
let dateInTheFuture = Calendar.current.date(byAdding: components, to: date)
return dateInTheFuture!
}
class DebugAppRepo: AppRepo {
private let log = Logger("App")
private var cancellables = Set<AnyCancellable>()
override init() {
super.init()
writeAppState.sink(
onValue: { it in
self.log.v("App state: \(it)")
}
)
.store(in: &cancellables)
}
}
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported
import ObjectiveC
//===----------------------------------------------------------------------===//
// Objective-C Primitive Types
//===----------------------------------------------------------------------===//
public typealias BooleanType = Swift.Boolean
/// The Objective-C BOOL type.
///
/// On 64-bit iOS, the Objective-C BOOL type is a typedef of C/C++
/// bool. Elsewhere, it is "signed char". The Clang importer imports it as
/// ObjCBool.
public struct ObjCBool : Boolean, BooleanLiteralConvertible {
#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
// On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char".
var _value: Int8
init(_ value: Int8) {
self._value = value
}
public init(_ value: Bool) {
self._value = value ? 1 : 0
}
#else
// Everywhere else it is C/C++'s "Bool"
var _value : Bool
public init(_ value: Bool) {
self._value = value
}
#endif
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool {
#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
return _value != 0
#else
return _value
#endif
}
/// Create an instance initialized to `value`.
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
}
extension ObjCBool : _Reflectable {
/// Returns a mirror that reflects `self`.
public func _getMirror() -> _MirrorType {
return _reflect(boolValue)
}
}
extension ObjCBool : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self.boolValue.description
}
}
// Functions used to implicitly bridge ObjCBool types to Swift's Bool type.
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertBoolToObjCBool(x: Bool) -> ObjCBool {
return ObjCBool(x)
}
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertObjCBoolToBool(x: ObjCBool) -> Bool {
return Bool(x)
}
/// The Objective-C SEL type.
///
/// The Objective-C SEL type is typically an opaque pointer. Swift
/// treats it as a distinct struct type, with operations to
/// convert between C strings and selectors.
///
/// The compiler has special knowledge of this type.
public struct Selector : StringLiteralConvertible, NilLiteralConvertible {
var ptr : OpaquePointer
/// Create a selector from a string.
public init(_ str : String) {
ptr = str.withCString { sel_registerName($0).ptr }
}
/// Create an instance initialized to `value`.
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
/// Construct a selector from `value`.
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
// FIXME: Fast-path this in the compiler, so we don't end up with
// the sel_registerName call at compile time.
/// Create an instance initialized to `value`.
public init(stringLiteral value: String) {
self = sel_registerName(value)
}
public init() {
ptr = nil
}
/// Create an instance initialized with `nil`.
@_transparent
public init(nilLiteral: ()) {
ptr = nil
}
}
@warn_unused_result
public func ==(lhs: Selector, rhs: Selector) -> Bool {
return sel_isEqual(lhs, rhs)
}
extension Selector : Equatable, Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return ptr.hashValue
}
}
extension Selector : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
if let s = String.fromCStringRepairingIllFormedUTF8(sel_getName(self)).0 {
return s
}
return "<NULL>"
}
}
extension String {
/// Construct the C string representation of an Objective-C selector.
public init(_sel: Selector) {
// FIXME: This misses the ASCII optimization.
self = String.fromCString(sel_getName(_sel))!
}
}
extension Selector : _Reflectable {
/// Returns a mirror that reflects `self`.
public func _getMirror() -> _MirrorType {
return _reflect(String(_sel: self))
}
}
//===----------------------------------------------------------------------===//
// NSZone
//===----------------------------------------------------------------------===//
public struct NSZone : NilLiteralConvertible {
var pointer : OpaquePointer
public init() { pointer = nil }
/// Create an instance initialized with `nil`.
@_transparent
public init(nilLiteral: ()) {
pointer = nil
}
}
//===----------------------------------------------------------------------===//
// FIXME: @autoreleasepool substitute
//===----------------------------------------------------------------------===//
@warn_unused_result
@_silgen_name("objc_autoreleasePoolPush")
func __pushAutoreleasePool() -> OpaquePointer
@_silgen_name("objc_autoreleasePoolPop")
func __popAutoreleasePool(pool: OpaquePointer)
public func autoreleasepool(@noescape code: () -> Void) {
let pool = __pushAutoreleasePool()
code()
__popAutoreleasePool(pool)
}
//===----------------------------------------------------------------------===//
// Mark YES and NO unavailable.
//===----------------------------------------------------------------------===//
@available(*, unavailable, message="Use 'Bool' value 'true' instead")
public var YES: ObjCBool {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, message="Use 'Bool' value 'false' instead")
public var NO: ObjCBool {
fatalError("can't retrieve unavailable property")
}
// FIXME: We can't make the fully-generic versions @_transparent due to
// rdar://problem/19418937, so here are some @_transparent overloads
// for ObjCBool
@_transparent
@warn_unused_result
public func && <T : Boolean>(
lhs: T, @autoclosure rhs: () -> ObjCBool
) -> Bool {
return lhs.boolValue ? rhs().boolValue : false
}
@_transparent
@warn_unused_result
public func || <T : Boolean>(
lhs: T, @autoclosure rhs: () -> ObjCBool
) -> Bool {
return lhs.boolValue ? true : rhs().boolValue
}
//===----------------------------------------------------------------------===//
// NSObject
//===----------------------------------------------------------------------===//
// NSObject implements Equatable's == as -[NSObject isEqual:]
// NSObject implements Hashable's hashValue() as -[NSObject hash]
// FIXME: what about NSObjectProtocol?
extension NSObject : Equatable, Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return hash
}
}
@warn_unused_result
public func == (lhs: NSObject, rhs: NSObject) -> Bool {
return lhs.isEqual(rhs)
}
extension NSObject : CVarArgType {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs
public var _cVarArgEncoding: [Int] {
_autorelease(self)
return _encodeBitsAsWords(self)
}
}
Remove the no-argument initializer, following the pattern set by unsafe pointers
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported
import ObjectiveC
//===----------------------------------------------------------------------===//
// Objective-C Primitive Types
//===----------------------------------------------------------------------===//
public typealias BooleanType = Swift.Boolean
/// The Objective-C BOOL type.
///
/// On 64-bit iOS, the Objective-C BOOL type is a typedef of C/C++
/// bool. Elsewhere, it is "signed char". The Clang importer imports it as
/// ObjCBool.
public struct ObjCBool : Boolean, BooleanLiteralConvertible {
#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
// On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char".
var _value: Int8
init(_ value: Int8) {
self._value = value
}
public init(_ value: Bool) {
self._value = value ? 1 : 0
}
#else
// Everywhere else it is C/C++'s "Bool"
var _value : Bool
public init(_ value: Bool) {
self._value = value
}
#endif
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool {
#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
return _value != 0
#else
return _value
#endif
}
/// Create an instance initialized to `value`.
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
}
extension ObjCBool : _Reflectable {
/// Returns a mirror that reflects `self`.
public func _getMirror() -> _MirrorType {
return _reflect(boolValue)
}
}
extension ObjCBool : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self.boolValue.description
}
}
// Functions used to implicitly bridge ObjCBool types to Swift's Bool type.
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertBoolToObjCBool(x: Bool) -> ObjCBool {
return ObjCBool(x)
}
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertObjCBoolToBool(x: ObjCBool) -> Bool {
return Bool(x)
}
/// The Objective-C SEL type.
///
/// The Objective-C SEL type is typically an opaque pointer. Swift
/// treats it as a distinct struct type, with operations to
/// convert between C strings and selectors.
///
/// The compiler has special knowledge of this type.
public struct Selector : StringLiteralConvertible, NilLiteralConvertible {
var ptr : OpaquePointer
/// Create a selector from a string.
public init(_ str : String) {
ptr = str.withCString { sel_registerName($0).ptr }
}
/// Create an instance initialized to `value`.
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
/// Construct a selector from `value`.
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
// FIXME: Fast-path this in the compiler, so we don't end up with
// the sel_registerName call at compile time.
/// Create an instance initialized to `value`.
public init(stringLiteral value: String) {
self = sel_registerName(value)
}
/// Create an instance initialized with `nil`.
@_transparent
public init(nilLiteral: ()) {
ptr = nil
}
}
@warn_unused_result
public func ==(lhs: Selector, rhs: Selector) -> Bool {
return sel_isEqual(lhs, rhs)
}
extension Selector : Equatable, Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return ptr.hashValue
}
}
extension Selector : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
if let s = String.fromCStringRepairingIllFormedUTF8(sel_getName(self)).0 {
return s
}
return "<NULL>"
}
}
extension String {
/// Construct the C string representation of an Objective-C selector.
public init(_sel: Selector) {
// FIXME: This misses the ASCII optimization.
self = String.fromCString(sel_getName(_sel))!
}
}
extension Selector : _Reflectable {
/// Returns a mirror that reflects `self`.
public func _getMirror() -> _MirrorType {
return _reflect(String(_sel: self))
}
}
//===----------------------------------------------------------------------===//
// NSZone
//===----------------------------------------------------------------------===//
public struct NSZone : NilLiteralConvertible {
var pointer : OpaquePointer
public init() { pointer = nil }
/// Create an instance initialized with `nil`.
@_transparent
public init(nilLiteral: ()) {
pointer = nil
}
}
//===----------------------------------------------------------------------===//
// FIXME: @autoreleasepool substitute
//===----------------------------------------------------------------------===//
@warn_unused_result
@_silgen_name("objc_autoreleasePoolPush")
func __pushAutoreleasePool() -> OpaquePointer
@_silgen_name("objc_autoreleasePoolPop")
func __popAutoreleasePool(pool: OpaquePointer)
public func autoreleasepool(@noescape code: () -> Void) {
let pool = __pushAutoreleasePool()
code()
__popAutoreleasePool(pool)
}
//===----------------------------------------------------------------------===//
// Mark YES and NO unavailable.
//===----------------------------------------------------------------------===//
@available(*, unavailable, message="Use 'Bool' value 'true' instead")
public var YES: ObjCBool {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, message="Use 'Bool' value 'false' instead")
public var NO: ObjCBool {
fatalError("can't retrieve unavailable property")
}
// FIXME: We can't make the fully-generic versions @_transparent due to
// rdar://problem/19418937, so here are some @_transparent overloads
// for ObjCBool
@_transparent
@warn_unused_result
public func && <T : Boolean>(
lhs: T, @autoclosure rhs: () -> ObjCBool
) -> Bool {
return lhs.boolValue ? rhs().boolValue : false
}
@_transparent
@warn_unused_result
public func || <T : Boolean>(
lhs: T, @autoclosure rhs: () -> ObjCBool
) -> Bool {
return lhs.boolValue ? true : rhs().boolValue
}
//===----------------------------------------------------------------------===//
// NSObject
//===----------------------------------------------------------------------===//
// NSObject implements Equatable's == as -[NSObject isEqual:]
// NSObject implements Hashable's hashValue() as -[NSObject hash]
// FIXME: what about NSObjectProtocol?
extension NSObject : Equatable, Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return hash
}
}
@warn_unused_result
public func == (lhs: NSObject, rhs: NSObject) -> Bool {
return lhs.isEqual(rhs)
}
extension NSObject : CVarArgType {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs
public var _cVarArgEncoding: [Int] {
_autorelease(self)
return _encodeBitsAsWords(self)
}
}
|
//
// WMFImageController.swift
// Wikipedia
//
// Created by Brian Gerstle on 6/22/15.
// Copyright (c) 2015 Wikimedia Foundation. All rights reserved.
//
import Foundation
import PromiseKit
///
/// @name Constants
///
public let WMFImageControllerErrorDomain = "WMFImageControllerErrorDomain"
public enum WMFImageControllerErrorCode: Int {
case DataNotFound
case FetchCancelled
case InvalidOrEmptyURL
var error: NSError {
return NSError(domain: WMFImageControllerErrorDomain, code: self.rawValue, userInfo: nil)
}
}
public func ==(err: NSError, cacheErrCode: WMFImageControllerErrorCode) -> Bool {
return err.code == cacheErrCode.rawValue
}
// need to declare the "flipped" version of NSError == WMFImageCacheErrorCode
public func ==(cacheErrorCode: WMFImageControllerErrorCode, err: NSError) -> Bool {
return err == cacheErrorCode
}
@objc
public class WMFImageController : NSObject {
public override class func initialize() {
if self === WMFImageController.self {
NSError.registerCancelledErrorDomain(WMFImageControllerErrorDomain,
code: WMFImageControllerErrorCode.FetchCancelled.rawValue)
}
}
/// MARK: - Initialization
private static let defaultNamespace = "default"
private static let _sharedInstance: WMFImageController = {
let downloader = SDWebImageDownloader.sharedDownloader()
let cache = SDImageCache.wmf_appSupportCacheWithNamespace(defaultNamespace)
return WMFImageController(manager: SDWebImageManager(downloader: downloader, cache: cache),
namespace: defaultNamespace)
}()
public class func sharedInstance() -> WMFImageController {
return _sharedInstance
}
//XC6: @testable
public let imageManager: SDWebImageManager
private let cancellingQueue: dispatch_queue_t
private lazy var cancellables: NSMapTable = {
NSMapTable.strongToWeakObjectsMapTable()
}()
public required init(manager: SDWebImageManager, namespace: String) {
self.imageManager = manager;
self.imageManager.cacheKeyFilter = { (url: NSURL?) in url?.wmf_schemelessURLString() }
self.cancellingQueue = dispatch_queue_create("org.wikimedia.wikipedia.wmfimagecontroller.\(namespace)",
DISPATCH_QUEUE_SERIAL)
super.init()
}
deinit {
cancelAllFetches()
}
/// MARK: - Complex Fetching
/**
* Perform a cascading fetch which attempts to retrieve a "main" image from memory, or fall back to a
* placeholder while fetching the image in the background.
*
* The "cascade" executes the following:
*
* - if mainURL is in cache, return immediately
* - else, fetch placeholder from cache
* - then, mainURL from network
*
* @return A promise which is resolved when the entire cascade is finished, or rejected when an error occurs.
*/
public func cascadingFetchWithMainURL(mainURL: NSURL?,
cachedPlaceholderURL: NSURL?,
mainImageBlock: (WMFImageDownload) -> Void,
cachedPlaceholderImageBlock: (WMFImageDownload) -> Void) -> Promise<Void> {
weak var wself = self
if hasImageWithURL(mainURL) {
// if mainURL is cached, return it immediately w/o fetching placeholder
return cachedImageWithURL(mainURL).then(mainImageBlock)
}
// return cached placeholder (if available)
return cachedImageWithURL(cachedPlaceholderURL)
// handle cached placeholder
.then() { cachedPlaceholderImageBlock($0) }
// ignore cache misses for placeholder
.recover() { error in
let empty: Void
return Promise(empty)
}
// when placeholder handling is finished, fetch mainURL
.then() { () -> Promise<WMFImageDownload> in
if let sself = wself {
return sself.fetchImageWithURL(mainURL)
} else {
return WMFImageController.cancelledPromise()
}
}
// handle the main image
.then() { mainImageBlock($0) }
}
/// MARK: - Simple Fetching
/**
* Retrieve the data and uncompressed image for `url`.
*
* @param url URL which corresponds to the image being retrieved. Ignores URL schemes.
*
* @return An `WMFImageDownload` with the image data and the origin it was loaded from.
*/
public func fetchImageWithURL(url: NSURL) -> Promise<WMFImageDownload> {
// HAX: make sure all image requests have a scheme (MW api sometimes omits one)
let (cancellable, promise) =
imageManager.promisedImageWithURL(url.wmf_urlByPrependingSchemeIfSchemeless(), options: .allZeros)
addCancellableForURL(cancellable, url: url)
return applyDebugTransformIfEnabled(promise)
}
public func fetchImageWithURL(url: NSURL?) -> Promise<WMFImageDownload> {
return checkForValidURL(url, then: fetchImageWithURL)
}
/// @return Whether or not a fetch is outstanding for an image with `url`.
public func isDownloadingImageWithURL(url: NSURL) -> Bool {
return imageManager.imageDownloader.isDownloadingImageAtURL(url)
}
// MARK: - Caching
// MARK: Query
/// @return Whether or not the image corresponding to `url` has been downloaded (ignores URL schemes).
public func hasImageWithURL(url: NSURL?) -> Bool {
return url == nil ? false : imageManager.cachedImageExistsForURL(url!)
}
public func cachedImageInMemoryWithURL(url: NSURL?) -> UIImage? {
return url == nil ? nil : imageManager.imageCache.imageFromMemoryCacheForKey(cacheKeyForURL(url!))
}
public func hasDataInMemoryForImageWithURL(url: NSURL?) -> Bool {
return cachedImageInMemoryWithURL(url) != nil
}
public func hasDataOnDiskForImageWithURL(url: NSURL?) -> Bool {
return url == nil ? false : imageManager.diskImageExistsForURL(url)
}
//XC6: @testable
public func diskDataForImageWithURL(url: NSURL?) -> NSData? {
if let url = url {
let path = imageManager.imageCache.defaultCachePathForKey(cacheKeyForURL(url))
return NSFileManager.defaultManager().contentsAtPath(path)
} else {
return nil
}
}
public func cachedImageWithURL(url: NSURL?) -> Promise<WMFImageDownload> {
return checkForValidURL(url, then: cachedImageWithURL)
}
public func cachedImageWithURL(url: NSURL) -> Promise<WMFImageDownload> {
let (cancellable, promise) = imageManager.imageCache.queryDiskCacheForKey(cacheKeyForURL(url))
if let cancellable = cancellable {
addCancellableForURL(cancellable, url: url)
}
return applyDebugTransformIfEnabled(promise.then() { image, origin in
return WMFImageDownload(url: url, image: image, origin: origin.rawValue)
})
}
// MARK: Deletion
public func clearMemoryCache() {
imageManager.imageCache.clearMemory()
}
public func deleteImagesWithURLs(urls: [NSURL]) {
self.imageManager.wmf_removeImageURLs(urls, fromDisk: true)
}
public func deleteImageWithURL(url: NSURL?) {
self.imageManager.wmf_removeImageForURL(url, fromDisk: true)
}
public func deleteAllImages() {
self.imageManager.imageCache.clearMemory()
self.imageManager.imageCache.clearDisk()
}
public func importImage(fromFile filepath: String, withURL url: NSURL) -> Promise<Void> {
if hasDataOnDiskForImageWithURL(url) {
//NSLog("Skipping import of image with URL \(url) since it's already in the cache, deleting it instead")
try! NSFileManager.defaultManager().removeItemAtPath(filepath)
return Promise()
} else if !NSFileManager.defaultManager().fileExistsAtPath(filepath) {
//NSLog("Source file does not exist: \(filepath)")
// Do not treat this as an error, as the image record could have been created w/o data ever being imported.
return Promise()
}
weak var wself = self
return dispatch_promise(on: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let empty: Void
if let sself = wself {
let diskCachePath = sself.imageManager.imageCache.defaultCachePathForKey(self.cacheKeyForURL(url))
var error: NSError?
NSFileManager.defaultManager().createDirectoryAtPath(diskCachePath.stringByDeletingLastPathComponent,
withIntermediateDirectories: true,
attributes: nil,
error: &error)
if error != nil && error!.code != NSFileWriteFileExistsError {
NSLog("Failed to create directory for migrated image data for url \(url) at path \(diskCachePath)"
+ "due to error \(error)")
return (empty, error)
}
NSFileManager.defaultManager().moveItemAtPath(filepath, toPath: diskCachePath, error: &error)
if error != nil && error!.code != NSFileWriteFileExistsError {
NSLog("Failed to move legacy data for url \(url) from \(filepath) to path \(diskCachePath)"
+ "due to error \(error)")
return (empty, error)
}
}
return (empty, nil)
}
}
private func cacheKeyForURL(url: NSURL) -> String {
return imageManager.cacheKeyForURL(url)
}
/**
* Utility which returns a rejected promise for `nil` URLs, or passes valid URLs to function `then`.
* @return A rejected promise with `InvalidOrEmptyURL` error if `url` is `nil`, otherwise the promise from `then`.
*/
private func checkForValidURL(url: NSURL?, then: (NSURL) -> Promise<WMFImageDownload>) -> Promise<WMFImageDownload> {
if url == nil { return Promise(WMFImageControllerErrorCode.InvalidOrEmptyURL.error) }
else { return then(url!) }
}
// MARK: - Cancellation
/// Cancel a pending fetch for an image at `url`.
public func cancelFetchForURL(url: NSURL?) {
if let url = url {
weak var wself = self;
dispatch_async(self.cancellingQueue) {
let sself = wself
if let cancellable = sself?.cancellables.objectForKey(url.absoluteString) as? Cancellable {
sself?.cancellables.removeObjectForKey(url.absoluteString)
cancellable.cancel()
}
}
}
}
public func cancelAllFetches() {
weak var wself = self;
dispatch_async(self.cancellingQueue) {
let sself = wself
let currentCancellables = sself?.cancellables.objectEnumerator()!.allObjects as! [Cancellable]
sself?.cancellables.removeAllObjects()
dispatch_async(dispatch_get_global_queue(0, 0)) {
for cancellable in currentCancellables {
cancellable.cancel()
}
}
}
}
private func addCancellableForURL(cancellable: Cancellable, url: NSURL) {
weak var wself = self;
dispatch_async(self.cancellingQueue) {
let sself = wself
sself?.cancellables.setObject(cancellable, forKey: url.absoluteString)
}
}
/// Utility for creating a `Promise` cancelled with a WMFImageController error
class func cancelledPromise<T>() -> Promise<T> {
return Promise<T>(WMFImageControllerErrorCode.FetchCancelled.error)
}
/// Utility for creating an `AnyPromise` cancelled with a WMFImageController error
class func cancelledPromise() -> AnyPromise {
return AnyPromise(bound: cancelledPromise() as Promise<Void>)
}
}
/// MARK: - Objective-C Bridge
extension WMFImageController {
/**
* Objective-C-compatible variant of fetchImageWithURL(url:) returning an `AnyPromise`.
*
* @return `AnyPromise` which resolves to `WMFImageDownload`.
*/
@objc public func fetchImageWithURL(url: NSURL?) -> AnyPromise {
return AnyPromise(bound: fetchImageWithURL(url))
}
/**
* Objective-C-compatible variant of cachedImageWithURL(url:) returning an `AnyPromise`.
*
* @return `AnyPromise` which resolves to `UIImage?`, where the image is present on a cache hit, and `nil` on a miss.
*/
@objc public func cachedImageWithURL(url: NSURL?) -> AnyPromise {
return AnyPromise(bound:
cachedImageWithURL(url)
.then() { $0.image }
.recover() { (err: NSError) -> Promise<UIImage?> in
if err.domain == WMFImageControllerErrorDomain
&& err.code == WMFImageControllerErrorCode.DataNotFound.rawValue {
return Promise<UIImage?>(nil)
} else {
return Promise(err)
}
})
}
@objc public func cascadingFetchWithMainURL(mainURL: NSURL?,
cachedPlaceholderURL: NSURL?,
mainImageBlock: (WMFImageDownload) -> Void,
cachedPlaceholderImageBlock: (WMFImageDownload) -> Void) -> AnyPromise {
let promise: Promise<Void> =
cascadingFetchWithMainURL(mainURL,
cachedPlaceholderURL: cachedPlaceholderURL,
mainImageBlock: mainImageBlock,
cachedPlaceholderImageBlock: cachedPlaceholderImageBlock)
return AnyPromise(bound: promise)
}
}
Switch over to new error handling
//
// WMFImageController.swift
// Wikipedia
//
// Created by Brian Gerstle on 6/22/15.
// Copyright (c) 2015 Wikimedia Foundation. All rights reserved.
//
import Foundation
import PromiseKit
///
/// @name Constants
///
public let WMFImageControllerErrorDomain = "WMFImageControllerErrorDomain"
public enum WMFImageControllerErrorCode: Int {
case DataNotFound
case FetchCancelled
case InvalidOrEmptyURL
var error: NSError {
return NSError(domain: WMFImageControllerErrorDomain, code: self.rawValue, userInfo: nil)
}
}
public func ==(err: NSError, cacheErrCode: WMFImageControllerErrorCode) -> Bool {
return err.code == cacheErrCode.rawValue
}
// need to declare the "flipped" version of NSError == WMFImageCacheErrorCode
public func ==(cacheErrorCode: WMFImageControllerErrorCode, err: NSError) -> Bool {
return err == cacheErrorCode
}
@objc
public class WMFImageController : NSObject {
public override class func initialize() {
if self === WMFImageController.self {
NSError.registerCancelledErrorDomain(WMFImageControllerErrorDomain,
code: WMFImageControllerErrorCode.FetchCancelled.rawValue)
}
}
/// MARK: - Initialization
private static let defaultNamespace = "default"
private static let _sharedInstance: WMFImageController = {
let downloader = SDWebImageDownloader.sharedDownloader()
let cache = SDImageCache.wmf_appSupportCacheWithNamespace(defaultNamespace)
return WMFImageController(manager: SDWebImageManager(downloader: downloader, cache: cache),
namespace: defaultNamespace)
}()
public class func sharedInstance() -> WMFImageController {
return _sharedInstance
}
//XC6: @testable
public let imageManager: SDWebImageManager
private let cancellingQueue: dispatch_queue_t
private lazy var cancellables: NSMapTable = {
NSMapTable.strongToWeakObjectsMapTable()
}()
public required init(manager: SDWebImageManager, namespace: String) {
self.imageManager = manager;
self.imageManager.cacheKeyFilter = { (url: NSURL?) in url?.wmf_schemelessURLString() }
self.cancellingQueue = dispatch_queue_create("org.wikimedia.wikipedia.wmfimagecontroller.\(namespace)",
DISPATCH_QUEUE_SERIAL)
super.init()
}
deinit {
cancelAllFetches()
}
/// MARK: - Complex Fetching
/**
* Perform a cascading fetch which attempts to retrieve a "main" image from memory, or fall back to a
* placeholder while fetching the image in the background.
*
* The "cascade" executes the following:
*
* - if mainURL is in cache, return immediately
* - else, fetch placeholder from cache
* - then, mainURL from network
*
* @return A promise which is resolved when the entire cascade is finished, or rejected when an error occurs.
*/
public func cascadingFetchWithMainURL(mainURL: NSURL?,
cachedPlaceholderURL: NSURL?,
mainImageBlock: (WMFImageDownload) -> Void,
cachedPlaceholderImageBlock: (WMFImageDownload) -> Void) -> Promise<Void> {
weak var wself = self
if hasImageWithURL(mainURL) {
// if mainURL is cached, return it immediately w/o fetching placeholder
return cachedImageWithURL(mainURL).then(mainImageBlock)
}
// return cached placeholder (if available)
return cachedImageWithURL(cachedPlaceholderURL)
// handle cached placeholder
.then() { cachedPlaceholderImageBlock($0) }
// ignore cache misses for placeholder
.recover() { error in
let empty: Void
return Promise(empty)
}
// when placeholder handling is finished, fetch mainURL
.then() { () -> Promise<WMFImageDownload> in
if let sself = wself {
return sself.fetchImageWithURL(mainURL)
} else {
return WMFImageController.cancelledPromise()
}
}
// handle the main image
.then() { mainImageBlock($0) }
}
/// MARK: - Simple Fetching
/**
* Retrieve the data and uncompressed image for `url`.
*
* @param url URL which corresponds to the image being retrieved. Ignores URL schemes.
*
* @return An `WMFImageDownload` with the image data and the origin it was loaded from.
*/
public func fetchImageWithURL(url: NSURL) -> Promise<WMFImageDownload> {
// HAX: make sure all image requests have a scheme (MW api sometimes omits one)
let (cancellable, promise) =
imageManager.promisedImageWithURL(url.wmf_urlByPrependingSchemeIfSchemeless(), options: .allZeros)
addCancellableForURL(cancellable, url: url)
return applyDebugTransformIfEnabled(promise)
}
public func fetchImageWithURL(url: NSURL?) -> Promise<WMFImageDownload> {
return checkForValidURL(url, then: fetchImageWithURL)
}
/// @return Whether or not a fetch is outstanding for an image with `url`.
public func isDownloadingImageWithURL(url: NSURL) -> Bool {
return imageManager.imageDownloader.isDownloadingImageAtURL(url)
}
// MARK: - Caching
// MARK: Query
/// @return Whether or not the image corresponding to `url` has been downloaded (ignores URL schemes).
public func hasImageWithURL(url: NSURL?) -> Bool {
return url == nil ? false : imageManager.cachedImageExistsForURL(url!)
}
public func cachedImageInMemoryWithURL(url: NSURL?) -> UIImage? {
return url == nil ? nil : imageManager.imageCache.imageFromMemoryCacheForKey(cacheKeyForURL(url!))
}
public func hasDataInMemoryForImageWithURL(url: NSURL?) -> Bool {
return cachedImageInMemoryWithURL(url) != nil
}
public func hasDataOnDiskForImageWithURL(url: NSURL?) -> Bool {
return url == nil ? false : imageManager.diskImageExistsForURL(url)
}
//XC6: @testable
public func diskDataForImageWithURL(url: NSURL?) -> NSData? {
if let url = url {
let path = imageManager.imageCache.defaultCachePathForKey(cacheKeyForURL(url))
return NSFileManager.defaultManager().contentsAtPath(path)
} else {
return nil
}
}
public func cachedImageWithURL(url: NSURL?) -> Promise<WMFImageDownload> {
return checkForValidURL(url, then: cachedImageWithURL)
}
public func cachedImageWithURL(url: NSURL) -> Promise<WMFImageDownload> {
let (cancellable, promise) = imageManager.imageCache.queryDiskCacheForKey(cacheKeyForURL(url))
if let cancellable = cancellable {
addCancellableForURL(cancellable, url: url)
}
return applyDebugTransformIfEnabled(promise.then() { image, origin in
return WMFImageDownload(url: url, image: image, origin: origin.rawValue)
})
}
// MARK: Deletion
public func clearMemoryCache() {
imageManager.imageCache.clearMemory()
}
public func deleteImagesWithURLs(urls: [NSURL]) {
self.imageManager.wmf_removeImageURLs(urls, fromDisk: true)
}
public func deleteImageWithURL(url: NSURL?) {
self.imageManager.wmf_removeImageForURL(url, fromDisk: true)
}
public func deleteAllImages() {
self.imageManager.imageCache.clearMemory()
self.imageManager.imageCache.clearDisk()
}
public func importImage(fromFile filepath: String, withURL url: NSURL) -> Promise<Void> {
if hasDataOnDiskForImageWithURL(url) {
//NSLog("Skipping import of image with URL \(url) since it's already in the cache, deleting it instead")
try! NSFileManager.defaultManager().removeItemAtPath(filepath)
return Promise()
} else if !NSFileManager.defaultManager().fileExistsAtPath(filepath) {
//NSLog("Source file does not exist: \(filepath)")
// Do not treat this as an error, as the image record could have been created w/o data ever being imported.
return Promise()
}
weak var wself = self
return dispatch_promise(on: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let empty: Void
if let sself = wself {
let diskCachePath = sself.imageManager.imageCache.defaultCachePathForKey(self.cacheKeyForURL(url))
var error: NSError?
do{
try NSFileManager.defaultManager().createDirectoryAtPath(diskCachePath.stringByDeletingLastPathComponent,
withIntermediateDirectories: true,
attributes: nil)
}catch let error as NSError{
if error.code != NSFileWriteFileExistsError {
NSLog("Failed to create directory for migrated image data for url \(url) at path \(diskCachePath)"
+ "due to error \(error)")
return (empty, error)
}
}
do{
try NSFileManager.defaultManager().moveItemAtPath(filepath, toPath: diskCachePath)
}catch let error as NSError{
if error.code != NSFileWriteFileExistsError {
NSLog("Failed to move legacy data for url \(url) from \(filepath) to path \(diskCachePath)"
+ "due to error \(error)")
return (empty, error)
}
}
}
return (empty, nil)
}
}
private func cacheKeyForURL(url: NSURL) -> String {
return imageManager.cacheKeyForURL(url)
}
/**
* Utility which returns a rejected promise for `nil` URLs, or passes valid URLs to function `then`.
* @return A rejected promise with `InvalidOrEmptyURL` error if `url` is `nil`, otherwise the promise from `then`.
*/
private func checkForValidURL(url: NSURL?, then: (NSURL) -> Promise<WMFImageDownload>) -> Promise<WMFImageDownload> {
if url == nil { return Promise(WMFImageControllerErrorCode.InvalidOrEmptyURL.error) }
else { return then(url!) }
}
// MARK: - Cancellation
/// Cancel a pending fetch for an image at `url`.
public func cancelFetchForURL(url: NSURL?) {
if let url = url {
weak var wself = self;
dispatch_async(self.cancellingQueue) {
let sself = wself
if let cancellable = sself?.cancellables.objectForKey(url.absoluteString) as? Cancellable {
sself?.cancellables.removeObjectForKey(url.absoluteString)
cancellable.cancel()
}
}
}
}
public func cancelAllFetches() {
weak var wself = self;
dispatch_async(self.cancellingQueue) {
let sself = wself
let currentCancellables = sself?.cancellables.objectEnumerator()!.allObjects as! [Cancellable]
sself?.cancellables.removeAllObjects()
dispatch_async(dispatch_get_global_queue(0, 0)) {
for cancellable in currentCancellables {
cancellable.cancel()
}
}
}
}
private func addCancellableForURL(cancellable: Cancellable, url: NSURL) {
weak var wself = self;
dispatch_async(self.cancellingQueue) {
let sself = wself
sself?.cancellables.setObject(cancellable, forKey: url.absoluteString)
}
}
/// Utility for creating a `Promise` cancelled with a WMFImageController error
class func cancelledPromise<T>() -> Promise<T> {
return Promise<T>(WMFImageControllerErrorCode.FetchCancelled.error)
}
/// Utility for creating an `AnyPromise` cancelled with a WMFImageController error
class func cancelledPromise() -> AnyPromise {
return AnyPromise(bound: cancelledPromise() as Promise<Void>)
}
}
/// MARK: - Objective-C Bridge
extension WMFImageController {
/**
* Objective-C-compatible variant of fetchImageWithURL(url:) returning an `AnyPromise`.
*
* @return `AnyPromise` which resolves to `WMFImageDownload`.
*/
@objc public func fetchImageWithURL(url: NSURL?) -> AnyPromise {
return AnyPromise(bound: fetchImageWithURL(url))
}
/**
* Objective-C-compatible variant of cachedImageWithURL(url:) returning an `AnyPromise`.
*
* @return `AnyPromise` which resolves to `UIImage?`, where the image is present on a cache hit, and `nil` on a miss.
*/
@objc public func cachedImageWithURL(url: NSURL?) -> AnyPromise {
return AnyPromise(bound:
cachedImageWithURL(url)
.then() { $0.image }
.recover() { (err: NSError) -> Promise<UIImage?> in
if err.domain == WMFImageControllerErrorDomain
&& err.code == WMFImageControllerErrorCode.DataNotFound.rawValue {
return Promise<UIImage?>(nil)
} else {
return Promise(err)
}
})
}
@objc public func cascadingFetchWithMainURL(mainURL: NSURL?,
cachedPlaceholderURL: NSURL?,
mainImageBlock: (WMFImageDownload) -> Void,
cachedPlaceholderImageBlock: (WMFImageDownload) -> Void) -> AnyPromise {
let promise: Promise<Void> =
cascadingFetchWithMainURL(mainURL,
cachedPlaceholderURL: cachedPlaceholderURL,
mainImageBlock: mainImageBlock,
cachedPlaceholderImageBlock: cachedPlaceholderImageBlock)
return AnyPromise(bound: promise)
}
}
|
//
// NSFileManager+Yep.swift
// Yep
//
// Created by NIX on 15/3/31.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
public enum FileExtension: String {
case JPEG = "jpg"
case MP4 = "mp4"
case M4A = "m4a"
public var mimeType: String {
switch self {
case .JPEG:
return "image/jpeg"
case .MP4:
return "video/mp4"
case .M4A:
return "audio/m4a"
}
}
}
public extension NSFileManager {
public class func yepCachesURL() -> NSURL {
return try! NSFileManager.defaultManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
}
// MARK: Avatar
public class func yepAvatarCachesURL() -> NSURL? {
let fileManager = NSFileManager.defaultManager()
let avatarCachesURL = yepCachesURL().URLByAppendingPathComponent("avatar_caches", isDirectory: true)
do {
try fileManager.createDirectoryAtURL(avatarCachesURL, withIntermediateDirectories: true, attributes: nil)
return avatarCachesURL
} catch _ {
}
return nil
}
public class func yepAvatarURLWithName(name: String) -> NSURL? {
if let avatarCachesURL = yepAvatarCachesURL() {
return avatarCachesURL.URLByAppendingPathComponent("\(name).\(FileExtension.JPEG.rawValue)")
}
return nil
}
public class func saveAvatarImage(avatarImage: UIImage, withName name: String) -> NSURL? {
if let avatarURL = yepAvatarURLWithName(name) {
let imageData = UIImageJPEGRepresentation(avatarImage, 0.8)
if NSFileManager.defaultManager().createFileAtPath(avatarURL.path!, contents: imageData, attributes: nil) {
return avatarURL
}
}
return nil
}
public class func deleteAvatarImageWithName(name: String) {
if let avatarURL = yepAvatarURLWithName(name) {
do {
try NSFileManager.defaultManager().removeItemAtURL(avatarURL)
} catch _ {
}
}
}
// MARK: Message
public class func yepMessageCachesURL() -> NSURL? {
let fileManager = NSFileManager.defaultManager()
let messageCachesURL = yepCachesURL().URLByAppendingPathComponent("message_caches", isDirectory: true)
do {
try fileManager.createDirectoryAtURL(messageCachesURL, withIntermediateDirectories: true, attributes: nil)
return messageCachesURL
} catch _ {
}
return nil
}
// Image
public class func yepMessageImageURLWithName(name: String) -> NSURL? {
if let messageCachesURL = yepMessageCachesURL() {
return messageCachesURL.URLByAppendingPathComponent("\(name).\(FileExtension.JPEG.rawValue)")
}
return nil
}
public class func saveMessageImageData(messageImageData: NSData, withName name: String) -> NSURL? {
if let messageImageURL = yepMessageImageURLWithName(name) {
if NSFileManager.defaultManager().createFileAtPath(messageImageURL.path!, contents: messageImageData, attributes: nil) {
return messageImageURL
}
}
return nil
}
public class func removeMessageImageFileWithName(name: String) {
if name.isEmpty {
return
}
if let messageImageURL = yepMessageImageURLWithName(name) {
do {
try NSFileManager.defaultManager().removeItemAtURL(messageImageURL)
} catch _ {
}
}
}
// Audio
public class func yepMessageAudioURLWithName(name: String) -> NSURL? {
if let messageCachesURL = yepMessageCachesURL() {
return messageCachesURL.URLByAppendingPathComponent("\(name).\(FileExtension.M4A.rawValue)")
}
return nil
}
public class func saveMessageAudioData(messageAudioData: NSData, withName name: String) -> NSURL? {
if let messageAudioURL = yepMessageAudioURLWithName(name) {
if NSFileManager.defaultManager().createFileAtPath(messageAudioURL.path!, contents: messageAudioData, attributes: nil) {
return messageAudioURL
}
}
return nil
}
public class func removeMessageAudioFileWithName(name: String) {
if name.isEmpty {
return
}
if let messageAudioURL = yepMessageAudioURLWithName(name) {
do {
try NSFileManager.defaultManager().removeItemAtURL(messageAudioURL)
} catch _ {
}
}
}
// Video
public class func yepMessageVideoURLWithName(name: String) -> NSURL? {
if let messageCachesURL = yepMessageCachesURL() {
return messageCachesURL.URLByAppendingPathComponent("\(name).\(FileExtension.MP4.rawValue)")
}
return nil
}
public class func saveMessageVideoData(messageVideoData: NSData, withName name: String) -> NSURL? {
if let messageVideoURL = yepMessageVideoURLWithName(name) {
if NSFileManager.defaultManager().createFileAtPath(messageVideoURL.path!, contents: messageVideoData, attributes: nil) {
return messageVideoURL
}
}
return nil
}
public class func removeMessageVideoFilesWithName(name: String, thumbnailName: String) {
if !name.isEmpty {
if let messageVideoURL = yepMessageVideoURLWithName(name) {
do {
try NSFileManager.defaultManager().removeItemAtURL(messageVideoURL)
} catch _ {
}
}
}
if !thumbnailName.isEmpty {
if let messageImageURL = yepMessageImageURLWithName(thumbnailName) {
do {
try NSFileManager.defaultManager().removeItemAtURL(messageImageURL)
} catch _ {
}
}
}
}
// MARK: Clean Caches
public class func cleanCachesDirectoryAtURL(cachesDirectoryURL: NSURL) {
let fileManager = NSFileManager.defaultManager()
if let fileURLs = (try? fileManager.contentsOfDirectoryAtURL(cachesDirectoryURL, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())) {
for fileURL in fileURLs {
do {
try fileManager.removeItemAtURL(fileURL)
} catch _ {
}
}
}
}
public class func cleanAvatarCaches() {
if let avatarCachesURL = yepAvatarCachesURL() {
cleanCachesDirectoryAtURL(avatarCachesURL)
}
}
public class func cleanMessageCaches() {
if let messageCachesURL = yepMessageCachesURL() {
cleanCachesDirectoryAtURL(messageCachesURL)
}
}
}
catch error
//
// NSFileManager+Yep.swift
// Yep
//
// Created by NIX on 15/3/31.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
public enum FileExtension: String {
case JPEG = "jpg"
case MP4 = "mp4"
case M4A = "m4a"
public var mimeType: String {
switch self {
case .JPEG:
return "image/jpeg"
case .MP4:
return "video/mp4"
case .M4A:
return "audio/m4a"
}
}
}
public extension NSFileManager {
public class func yepCachesURL() -> NSURL {
return try! NSFileManager.defaultManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
}
// MARK: Avatar
public class func yepAvatarCachesURL() -> NSURL? {
let fileManager = NSFileManager.defaultManager()
let avatarCachesURL = yepCachesURL().URLByAppendingPathComponent("avatar_caches", isDirectory: true)
do {
try fileManager.createDirectoryAtURL(avatarCachesURL, withIntermediateDirectories: true, attributes: nil)
return avatarCachesURL
} catch let error {
println("Directory create: \(error)")
}
return nil
}
public class func yepAvatarURLWithName(name: String) -> NSURL? {
if let avatarCachesURL = yepAvatarCachesURL() {
return avatarCachesURL.URLByAppendingPathComponent("\(name).\(FileExtension.JPEG.rawValue)")
}
return nil
}
public class func saveAvatarImage(avatarImage: UIImage, withName name: String) -> NSURL? {
if let avatarURL = yepAvatarURLWithName(name) {
let imageData = UIImageJPEGRepresentation(avatarImage, 0.8)
if NSFileManager.defaultManager().createFileAtPath(avatarURL.path!, contents: imageData, attributes: nil) {
return avatarURL
}
}
return nil
}
public class func deleteAvatarImageWithName(name: String) {
if let avatarURL = yepAvatarURLWithName(name) {
do {
try NSFileManager.defaultManager().removeItemAtURL(avatarURL)
} catch let error {
println("File delete: \(error)")
}
}
}
// MARK: Message
public class func yepMessageCachesURL() -> NSURL? {
let fileManager = NSFileManager.defaultManager()
let messageCachesURL = yepCachesURL().URLByAppendingPathComponent("message_caches", isDirectory: true)
do {
try fileManager.createDirectoryAtURL(messageCachesURL, withIntermediateDirectories: true, attributes: nil)
return messageCachesURL
} catch let error {
println("Directory create: \(error)")
}
return nil
}
// Image
public class func yepMessageImageURLWithName(name: String) -> NSURL? {
if let messageCachesURL = yepMessageCachesURL() {
return messageCachesURL.URLByAppendingPathComponent("\(name).\(FileExtension.JPEG.rawValue)")
}
return nil
}
public class func saveMessageImageData(messageImageData: NSData, withName name: String) -> NSURL? {
if let messageImageURL = yepMessageImageURLWithName(name) {
if NSFileManager.defaultManager().createFileAtPath(messageImageURL.path!, contents: messageImageData, attributes: nil) {
return messageImageURL
}
}
return nil
}
public class func removeMessageImageFileWithName(name: String) {
if name.isEmpty {
return
}
if let messageImageURL = yepMessageImageURLWithName(name) {
do {
try NSFileManager.defaultManager().removeItemAtURL(messageImageURL)
} catch let error {
println("File delete: \(error)")
}
}
}
// Audio
public class func yepMessageAudioURLWithName(name: String) -> NSURL? {
if let messageCachesURL = yepMessageCachesURL() {
return messageCachesURL.URLByAppendingPathComponent("\(name).\(FileExtension.M4A.rawValue)")
}
return nil
}
public class func saveMessageAudioData(messageAudioData: NSData, withName name: String) -> NSURL? {
if let messageAudioURL = yepMessageAudioURLWithName(name) {
if NSFileManager.defaultManager().createFileAtPath(messageAudioURL.path!, contents: messageAudioData, attributes: nil) {
return messageAudioURL
}
}
return nil
}
public class func removeMessageAudioFileWithName(name: String) {
if name.isEmpty {
return
}
if let messageAudioURL = yepMessageAudioURLWithName(name) {
do {
try NSFileManager.defaultManager().removeItemAtURL(messageAudioURL)
} catch let error {
println("File delete: \(error)")
}
}
}
// Video
public class func yepMessageVideoURLWithName(name: String) -> NSURL? {
if let messageCachesURL = yepMessageCachesURL() {
return messageCachesURL.URLByAppendingPathComponent("\(name).\(FileExtension.MP4.rawValue)")
}
return nil
}
public class func saveMessageVideoData(messageVideoData: NSData, withName name: String) -> NSURL? {
if let messageVideoURL = yepMessageVideoURLWithName(name) {
if NSFileManager.defaultManager().createFileAtPath(messageVideoURL.path!, contents: messageVideoData, attributes: nil) {
return messageVideoURL
}
}
return nil
}
public class func removeMessageVideoFilesWithName(name: String, thumbnailName: String) {
if !name.isEmpty {
if let messageVideoURL = yepMessageVideoURLWithName(name) {
do {
try NSFileManager.defaultManager().removeItemAtURL(messageVideoURL)
} catch let error {
println("File delete: \(error)")
}
}
}
if !thumbnailName.isEmpty {
if let messageImageURL = yepMessageImageURLWithName(thumbnailName) {
do {
try NSFileManager.defaultManager().removeItemAtURL(messageImageURL)
} catch let error {
println("File delete: \(error)")
}
}
}
}
// MARK: Clean Caches
public class func cleanCachesDirectoryAtURL(cachesDirectoryURL: NSURL) {
let fileManager = NSFileManager.defaultManager()
if let fileURLs = (try? fileManager.contentsOfDirectoryAtURL(cachesDirectoryURL, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())) {
for fileURL in fileURLs {
do {
try fileManager.removeItemAtURL(fileURL)
} catch let error {
println("File delete: \(error)")
}
}
}
}
public class func cleanAvatarCaches() {
if let avatarCachesURL = yepAvatarCachesURL() {
cleanCachesDirectoryAtURL(avatarCachesURL)
}
}
public class func cleanMessageCaches() {
if let messageCachesURL = yepMessageCachesURL() {
cleanCachesDirectoryAtURL(messageCachesURL)
}
}
}
|
// Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
let base = 5
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
answer
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
println("Hello, \(name)!")
}
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
println("\(animalName)s have \(legCount) legs")
}
for character in "Hello" {
print("\(character) ")
}
var index: Int
for index = 0; index < 3; ++index {
println("index is \(index)")
}
println("The loop statements were excuted \(index) times.")
control flow tuple
// Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
let base = 5
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
answer
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
println("Hello, \(name)!")
}
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
println("\(animalName)s have \(legCount) legs")
}
for character in "Hello" {
print("\(character) ")
}
var index: Int
for index = 0; index < 3; ++index {
println("index is \(index)")
}
println("The loop statements were excuted \(index) times.")
let finalSquare = 25
var board = [Int](count: finalSquare + 1, repeatedValue: 0)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
var square = 0
var diceRoll = 0
/*
while square < finalSquare {
// roll the dice
if ++diceRoll == 7 {diceRoll = 1}
// move by the rolled amount
square += diceRoll
if square < board.count {
// if we're still on the board, move up or down for a snake or a ladder
square += board[square]
}
}
println("Game over!")
*/
do {
// move up or down for a snake or ladder
square += board[square]
// roll the dice
if ++diceRoll == 7 { diceRoll = 1 }
// move by the rolled amount
square += diceRoll
} while square < finalSquare
println("Game Over!")
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
println("It's very cold. Conside wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
println("It's really warm. Don't forget to wear sunscreen.")
} else {
println("It's not that cold. Wear a T-shirt.")
}
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
println("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l",
"m","n", "p", "q", "r", "s", "t", "v", "w",
"x", "y", "z":
println("\(someCharacter) is consonant")
default:
println("\(someCharacter) is not a vowel or a consonant")
}
let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
naturalCount = "no "
case 1...3:
naturalCount = "a few "
case 4...999_999:
naturalCount = "thousands of "
default:
naturalCount = "millions and millions of "
}
println("There are \(naturalCount) \(countedThings).")
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
println("(0, 0) is at the origin")
case (_, 0):
println("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
println("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
println("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
println("on the x-axis with an x value of \(x)")
case (0, let y):
println("on the y-axis with a y value of \(y)")
case let (x, y):
println("somewhere else at (\(x), \(y))")
}
// prints "on the x-axis with an x value of 2"
|
// RUN: %empty-directory(%t)
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s -sdk %S/../Inputs/clang-importer-sdk -Xfrontend -foo -Xfrontend -bar -Xllvm -baz -Xcc -garply -F /path/to/frameworks -Fsystem /path/to/systemframeworks -F /path/to/more/frameworks -I /path/to/headers -I path/to/more/headers -module-cache-path /tmp/modules -incremental 2>&1 > %t.complex.txt
// RUN: %FileCheck %s < %t.complex.txt
// RUN: %FileCheck -check-prefix COMPLEX %s < %t.complex.txt
// RUN: %swiftc_driver -driver-print-jobs -dump-ast -target x86_64-apple-macosx10.9 %s 2>&1 > %t.ast.txt
// RUN: %FileCheck %s < %t.ast.txt
// RUN: %FileCheck -check-prefix AST-STDOUT %s < %t.ast.txt
// RUN: %swiftc_driver -driver-print-jobs -dump-ast -target x86_64-apple-macosx10.9 %s -o output.ast > %t.ast.txt
// RUN: %FileCheck %s < %t.ast.txt
// RUN: %FileCheck -check-prefix AST-O %s < %t.ast.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-silgen -target x86_64-apple-macosx10.9 %s 2>&1 > %t.silgen.txt
// RUN: %FileCheck %s < %t.silgen.txt
// RUN: %FileCheck -check-prefix SILGEN %s < %t.silgen.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-sil -target x86_64-apple-macosx10.9 %s 2>&1 > %t.sil.txt
// RUN: %FileCheck %s < %t.sil.txt
// RUN: %FileCheck -check-prefix SIL %s < %t.sil.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-ir -target x86_64-apple-macosx10.9 %s 2>&1 > %t.ir.txt
// RUN: %FileCheck %s < %t.ir.txt
// RUN: %FileCheck -check-prefix IR %s < %t.ir.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-bc -target x86_64-apple-macosx10.9 %s 2>&1 > %t.bc.txt
// RUN: %FileCheck %s < %t.bc.txt
// RUN: %FileCheck -check-prefix BC %s < %t.bc.txt
// RUN: %swiftc_driver -driver-print-jobs -S -target x86_64-apple-macosx10.9 %s 2>&1 > %t.s.txt
// RUN: %FileCheck %s < %t.s.txt
// RUN: %FileCheck -check-prefix ASM %s < %t.s.txt
// RUN: %swiftc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s 2>&1 > %t.c.txt
// RUN: %FileCheck %s < %t.c.txt
// RUN: %FileCheck -check-prefix OBJ %s < %t.c.txt
// RUN: not %swiftc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s %s 2>&1 | %FileCheck -check-prefix DUPLICATE-NAME %s
// RUN: cp %s %t
// RUN: not %swiftc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s %t/driver-compile.swift 2>&1 | %FileCheck -check-prefix DUPLICATE-NAME %s
// RUN: %swiftc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s %S/../Inputs/empty.swift -module-name main -driver-filelist-threshold=0 2>&1 | %FileCheck -check-prefix=FILELIST %s
// RUN: %empty-directory(%t)/DISTINCTIVE-PATH/usr/bin/
// RUN: %hardlink-or-copy(from: %swift_frontend_plain, to: %t/DISTINCTIVE-PATH/usr/bin/swiftc)
// RUN: ln -s "swiftc" %t/DISTINCTIVE-PATH/usr/bin/swift-update
// RUN: %t/DISTINCTIVE-PATH/usr/bin/swiftc -driver-print-jobs -c -update-code -target x86_64-apple-macosx10.9 %s 2>&1 > %t.upd.txt
// RUN: %FileCheck -check-prefix UPDATE-CODE %s < %t.upd.txt
// Clean up the test executable because hard links are expensive.
// RUN: rm -rf %t/DISTINCTIVE-PATH/usr/bin/swiftc
// RUN: %swiftc_driver -driver-print-jobs -whole-module-optimization -incremental %s 2>&1 > %t.wmo-inc.txt
// RUN: %FileCheck %s < %t.wmo-inc.txt
// RUN: %FileCheck -check-prefix NO-REFERENCE-DEPENDENCIES %s < %t.wmo-inc.txt
// RUN: %swiftc_driver -driver-print-jobs -embed-bitcode -incremental %s 2>&1 > %t.embed-inc.txt
// RUN: %FileCheck %s < %t.embed-inc.txt
// RUN: %FileCheck -check-prefix NO-REFERENCE-DEPENDENCIES %s < %t.embed-inc.txt
// REQUIRES: CODEGENERATOR=X86
// CHECK: bin{{/|\\\\}}swift
// CHECK: Driver{{/|\\\\}}driver-compile.swift
// CHECK: -o
// COMPLEX: bin{{/|\\\\}}swift
// COMPLEX: -c
// COMPLEX: Driver{{/|\\\\}}driver-compile.swift
// COMPLEX-DAG: -sdk {{.*}}/Inputs/clang-importer-sdk
// COMPLEX-DAG: -foo -bar
// COMPLEX-DAG: -Xllvm -baz
// COMPLEX-DAG: -Xcc -garply
// COMPLEX-DAG: -F /path/to/frameworks -Fsystem /path/to/systemframeworks -F /path/to/more/frameworks
// COMPLEX-DAG: -I /path/to/headers -I path/to/more/headers
// COMPLEX-DAG: -module-cache-path /tmp/modules
// COMPLEX-DAG: -emit-reference-dependencies-path {{(.*(/|\\))?driver-compile[^ /]+}}.swiftdeps
// COMPLEX: -o {{.+}}.o
// AST-STDOUT: bin{{/|\\\\}}swift
// AST-STDOUT: -dump-ast
// AST-STDOUT: -o -
// AST-O: bin{{/|\\\\}}swift
// AST-O: -dump-ast
// AST-O: -o output.ast
// SILGEN: bin{{/|\\\\}}swift
// SILGEN: -emit-silgen
// SILGEN: -o -
// SIL: bin{{/|\\\\}}swift
// SIL: -emit-sil{{ }}
// SIL: -o -
// IR: bin{{/|\\\\}}swift
// IR: -emit-ir
// IR: -o -
// BC: bin{{/|\\\\}}swift
// BC: -emit-bc
// BC: -o {{[^-]}}
// ASM: bin{{/|\\\\}}swift
// ASM: -S{{ }}
// ASM: -o -
// OBJ: bin{{/|\\\\}}swift
// OBJ: -c{{ }}
// OBJ: -o {{[^-]}}
// DUPLICATE-NAME: error: filename "driver-compile.swift" used twice: '{{.*}}test{{[/\\]}}Driver{{[/\\]}}driver-compile.swift' and '{{.*}}driver-compile.swift'
// DUPLICATE-NAME: note: filenames are used to distinguish private declarations with the same name
// FILELIST: bin{{/|\\\\}}swift
// FILELIST: -filelist [[SOURCES:(["][^"]+sources[^"]+["]|[^ ]+sources[^ ]+)]]
// FILELIST: -primary-filelist {{(["][^"]+primaryInputs[^"]+["]|[^ ]+primaryInputs[^ ]+)}}
// FILELIST: -supplementary-output-file-map {{(["][^"]+supplementaryOutputs[^"]+["]|[^ ]+supplementaryOutputs[^ ]+)}}
// FILELIST: -output-filelist {{[^-]}}
// FILELIST-NEXT: bin{{/|\\\\}}swift
// FILELIST: -filelist [[SOURCES]]
// FILELIST: -primary-filelist {{(["][^"]+primaryInputs[^"]+["]|[^ ]+primaryInputs[^ ]+)}}
// FILELIST: -supplementary-output-file-map {{(["][^"]+supplementaryOutputs[^"]+["]|[^ ]+supplementaryOutputs[^ ]+)}}
// FILELIST: -output-filelist {{[^-]}}
// UPDATE-CODE: {{DISTINCTIVE-PATH|distinctive-path}}{{/|\\\\}}usr{{/|\\\\}}bin{{/|\\\\}}swift{{c?(\.exe)?}}
// UPDATE-CODE: -frontend -c
// UPDATE-CODE: -emit-remap-file-path {{.+}}.remap
// NO-REFERENCE-DEPENDENCIES: bin{{/|\\\\}}swift
// NO-REFERENCE-DEPENDENCIES-NOT: -emit-reference-dependencies
Allow temporary file without -###### postfix
// RUN: %empty-directory(%t)
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s -sdk %S/../Inputs/clang-importer-sdk -Xfrontend -foo -Xfrontend -bar -Xllvm -baz -Xcc -garply -F /path/to/frameworks -Fsystem /path/to/systemframeworks -F /path/to/more/frameworks -I /path/to/headers -I path/to/more/headers -module-cache-path /tmp/modules -incremental 2>&1 > %t.complex.txt
// RUN: %FileCheck %s < %t.complex.txt
// RUN: %FileCheck -check-prefix COMPLEX %s < %t.complex.txt
// RUN: %swiftc_driver -driver-print-jobs -dump-ast -target x86_64-apple-macosx10.9 %s 2>&1 > %t.ast.txt
// RUN: %FileCheck %s < %t.ast.txt
// RUN: %FileCheck -check-prefix AST-STDOUT %s < %t.ast.txt
// RUN: %swiftc_driver -driver-print-jobs -dump-ast -target x86_64-apple-macosx10.9 %s -o output.ast > %t.ast.txt
// RUN: %FileCheck %s < %t.ast.txt
// RUN: %FileCheck -check-prefix AST-O %s < %t.ast.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-silgen -target x86_64-apple-macosx10.9 %s 2>&1 > %t.silgen.txt
// RUN: %FileCheck %s < %t.silgen.txt
// RUN: %FileCheck -check-prefix SILGEN %s < %t.silgen.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-sil -target x86_64-apple-macosx10.9 %s 2>&1 > %t.sil.txt
// RUN: %FileCheck %s < %t.sil.txt
// RUN: %FileCheck -check-prefix SIL %s < %t.sil.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-ir -target x86_64-apple-macosx10.9 %s 2>&1 > %t.ir.txt
// RUN: %FileCheck %s < %t.ir.txt
// RUN: %FileCheck -check-prefix IR %s < %t.ir.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-bc -target x86_64-apple-macosx10.9 %s 2>&1 > %t.bc.txt
// RUN: %FileCheck %s < %t.bc.txt
// RUN: %FileCheck -check-prefix BC %s < %t.bc.txt
// RUN: %swiftc_driver -driver-print-jobs -S -target x86_64-apple-macosx10.9 %s 2>&1 > %t.s.txt
// RUN: %FileCheck %s < %t.s.txt
// RUN: %FileCheck -check-prefix ASM %s < %t.s.txt
// RUN: %swiftc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s 2>&1 > %t.c.txt
// RUN: %FileCheck %s < %t.c.txt
// RUN: %FileCheck -check-prefix OBJ %s < %t.c.txt
// RUN: not %swiftc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s %s 2>&1 | %FileCheck -check-prefix DUPLICATE-NAME %s
// RUN: cp %s %t
// RUN: not %swiftc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s %t/driver-compile.swift 2>&1 | %FileCheck -check-prefix DUPLICATE-NAME %s
// RUN: %swiftc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s %S/../Inputs/empty.swift -module-name main -driver-filelist-threshold=0 2>&1 | %FileCheck -check-prefix=FILELIST %s
// RUN: %empty-directory(%t)/DISTINCTIVE-PATH/usr/bin/
// RUN: %hardlink-or-copy(from: %swift_frontend_plain, to: %t/DISTINCTIVE-PATH/usr/bin/swiftc)
// RUN: ln -s "swiftc" %t/DISTINCTIVE-PATH/usr/bin/swift-update
// RUN: %t/DISTINCTIVE-PATH/usr/bin/swiftc -driver-print-jobs -c -update-code -target x86_64-apple-macosx10.9 %s 2>&1 > %t.upd.txt
// RUN: %FileCheck -check-prefix UPDATE-CODE %s < %t.upd.txt
// Clean up the test executable because hard links are expensive.
// RUN: rm -rf %t/DISTINCTIVE-PATH/usr/bin/swiftc
// RUN: %swiftc_driver -driver-print-jobs -whole-module-optimization -incremental %s 2>&1 > %t.wmo-inc.txt
// RUN: %FileCheck %s < %t.wmo-inc.txt
// RUN: %FileCheck -check-prefix NO-REFERENCE-DEPENDENCIES %s < %t.wmo-inc.txt
// RUN: %swiftc_driver -driver-print-jobs -embed-bitcode -incremental %s 2>&1 > %t.embed-inc.txt
// RUN: %FileCheck %s < %t.embed-inc.txt
// RUN: %FileCheck -check-prefix NO-REFERENCE-DEPENDENCIES %s < %t.embed-inc.txt
// REQUIRES: CODEGENERATOR=X86
// CHECK: bin{{/|\\\\}}swift
// CHECK: Driver{{/|\\\\}}driver-compile.swift
// CHECK: -o
// COMPLEX: bin{{/|\\\\}}swift
// COMPLEX: -c
// COMPLEX: Driver{{/|\\\\}}driver-compile.swift
// COMPLEX-DAG: -sdk {{.*}}/Inputs/clang-importer-sdk
// COMPLEX-DAG: -foo -bar
// COMPLEX-DAG: -Xllvm -baz
// COMPLEX-DAG: -Xcc -garply
// COMPLEX-DAG: -F /path/to/frameworks -Fsystem /path/to/systemframeworks -F /path/to/more/frameworks
// COMPLEX-DAG: -I /path/to/headers -I path/to/more/headers
// COMPLEX-DAG: -module-cache-path /tmp/modules
// COMPLEX-DAG: -emit-reference-dependencies-path {{(.*(/|\\))?driver-compile[^ /]*}}.swiftdeps
// COMPLEX: -o {{.+}}.o
// AST-STDOUT: bin{{/|\\\\}}swift
// AST-STDOUT: -dump-ast
// AST-STDOUT: -o -
// AST-O: bin{{/|\\\\}}swift
// AST-O: -dump-ast
// AST-O: -o output.ast
// SILGEN: bin{{/|\\\\}}swift
// SILGEN: -emit-silgen
// SILGEN: -o -
// SIL: bin{{/|\\\\}}swift
// SIL: -emit-sil{{ }}
// SIL: -o -
// IR: bin{{/|\\\\}}swift
// IR: -emit-ir
// IR: -o -
// BC: bin{{/|\\\\}}swift
// BC: -emit-bc
// BC: -o {{[^-]}}
// ASM: bin{{/|\\\\}}swift
// ASM: -S{{ }}
// ASM: -o -
// OBJ: bin{{/|\\\\}}swift
// OBJ: -c{{ }}
// OBJ: -o {{[^-]}}
// DUPLICATE-NAME: error: filename "driver-compile.swift" used twice: '{{.*}}test{{[/\\]}}Driver{{[/\\]}}driver-compile.swift' and '{{.*}}driver-compile.swift'
// DUPLICATE-NAME: note: filenames are used to distinguish private declarations with the same name
// FILELIST: bin{{/|\\\\}}swift
// FILELIST: -filelist [[SOURCES:(["][^"]+sources[^"]+["]|[^ ]+sources[^ ]+)]]
// FILELIST: -primary-filelist {{(["][^"]+primaryInputs[^"]+["]|[^ ]+primaryInputs[^ ]+)}}
// FILELIST: -supplementary-output-file-map {{(["][^"]+supplementaryOutputs[^"]+["]|[^ ]+supplementaryOutputs[^ ]+)}}
// FILELIST: -output-filelist {{[^-]}}
// FILELIST-NEXT: bin{{/|\\\\}}swift
// FILELIST: -filelist [[SOURCES]]
// FILELIST: -primary-filelist {{(["][^"]+primaryInputs[^"]+["]|[^ ]+primaryInputs[^ ]+)}}
// FILELIST: -supplementary-output-file-map {{(["][^"]+supplementaryOutputs[^"]+["]|[^ ]+supplementaryOutputs[^ ]+)}}
// FILELIST: -output-filelist {{[^-]}}
// UPDATE-CODE: {{DISTINCTIVE-PATH|distinctive-path}}{{/|\\\\}}usr{{/|\\\\}}bin{{/|\\\\}}swift{{c?(\.exe)?}}
// UPDATE-CODE: -frontend -c
// UPDATE-CODE: -emit-remap-file-path {{.+}}.remap
// NO-REFERENCE-DEPENDENCIES: bin{{/|\\\\}}swift
// NO-REFERENCE-DEPENDENCIES-NOT: -emit-reference-dependencies
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// Command-line arguments for the current process.
@frozen // namespace
public enum CommandLine {
/// The backing static variable for argument count may come either from the
/// entry point or it may need to be computed e.g. if we're in the REPL.
@usableFromInline
internal static var _argc: Int32 = Int32()
/// The backing static variable for arguments may come either from the
/// entry point or it may need to be computed e.g. if we're in the REPL.
///
/// Care must be taken to ensure that `_swift_stdlib_getUnsafeArgvArgc` is
/// not invoked more times than is necessary (at most once).
@usableFromInline
internal static var _unsafeArgv:
UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>
= _swift_stdlib_getUnsafeArgvArgc(&_argc)
/// Access to the raw argc value from C.
public static var argc: Int32 {
_ = CommandLine.unsafeArgv // Force evaluation of argv.
return _argc
}
/// Access to the raw argv value from C. Accessing the argument vector
/// through this pointer is unsafe.
public static var unsafeArgv:
UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> {
return _unsafeArgv
}
/// Access to the swift arguments, also use lazy initialization of static
/// properties to safely initialize the swift arguments.
public static var arguments: [String]
= (0..<Int(argc)).map { String(cString: _unsafeArgv[$0]!) }
}
Update documentation for CommandLine.arguments (#25304)
Addresses SR-6776 Documentation comment for CommandLine.arguments contains implementation remarks
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// Command-line arguments for the current process.
@frozen // namespace
public enum CommandLine {
/// The backing static variable for argument count may come either from the
/// entry point or it may need to be computed e.g. if we're in the REPL.
@usableFromInline
internal static var _argc: Int32 = Int32()
/// The backing static variable for arguments may come either from the
/// entry point or it may need to be computed e.g. if we're in the REPL.
///
/// Care must be taken to ensure that `_swift_stdlib_getUnsafeArgvArgc` is
/// not invoked more times than is necessary (at most once).
@usableFromInline
internal static var _unsafeArgv:
UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>
= _swift_stdlib_getUnsafeArgvArgc(&_argc)
/// Access to the raw argc value from C.
public static var argc: Int32 {
_ = CommandLine.unsafeArgv // Force evaluation of argv.
return _argc
}
/// Access to the raw argv value from C. Accessing the argument vector
/// through this pointer is unsafe.
public static var unsafeArgv:
UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> {
return _unsafeArgv
}
/// Access to the Swift command line arguments.
// Use lazy initialization of static properties to
// safely initialize the swift arguments.
public static var arguments: [String]
= (0..<Int(argc)).map { String(cString: _unsafeArgv[$0]!) }
}
|
//
// AKDecimator.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// AudioKit version of Apple's Decimator from the Distortion Audio Unit
///
open class AKDecimator: AKNode, AKToggleable, AUComponent {
// MARK: - Properties
public static let ComponentDescription = AudioComponentDescription(appleEffect: kAudioUnitSubType_Distortion)
private var au: AUWrapper
fileprivate var lastKnownMix: Double = 1
/// Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5)
open var decimation: Double = 0.5 {
didSet {
decimation = (0...1).clamp(decimation)
au[kDistortionParam_Decimation] = decimation * 100
}
}
/// Rounding (Normalized Value) ranges from 0 to 1 (Default: 0)
open var rounding: Double = 0 {
didSet {
rounding = (0...1).clamp(rounding)
au[kDistortionParam_Rounding] = rounding * 100
}
}
/// Mix (Normalized Value) ranges from 0 to 1 (Default: 1)
open var mix: Double = 1 {
didSet {
mix = (0...1).clamp(mix)
au[kDistortionParam_FinalMix] = mix * 100
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
open var isStarted = true
// MARK: - Initialization
/// Initialize the decimator node
///
/// - Parameters:
/// - input: Input node to process
/// - decimation: Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5)
/// - rounding: Rounding (Normalized Value) ranges from 0 to 1 (Default: 0)
/// - mix: Mix (Normalized Value) ranges from 0 to 1 (Default: 1)
///
public init(
_ input: AKNode,
decimation: Double = 0.5,
rounding: Double = 0,
mix: Double = 1) {
self.decimation = decimation
self.rounding = rounding
self.mix = mix
let
internalEffect = AVAudioUnitEffect(audioComponentDescription: _Self.ComponentDescription)
au = AUWrapper(au: internalEffect.audioUnit)
super.init()
avAudioNode = internalEffect
AudioKit.engine.attach(self.avAudioNode)
input.addConnectionPoint(self)
// Since this is the Decimator, mix it to 100% and use the final mix as the mix parameter
au[kDistortionParam_Decimation] = decimation * 100
au[kDistortionParam_Rounding] = rounding * 100
au[kDistortionParam_FinalMix] = mix * 100
au[kDistortionParam_PolynomialMix] = 0
au[kDistortionParam_DelayMix] = 0
au[kDistortionParam_DelayMix] = 0
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
open func start() {
if isStopped {
mix = lastKnownMix
isStarted = true
}
}
/// Function to stop or bypass the node, both are equivalent
open func stop() {
if isPlaying {
lastKnownMix = mix
mix = 0
isStarted = false
}
}
}
* fixed ws in akdecimator
//
// AKDecimator.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// AudioKit version of Apple's Decimator from the Distortion Audio Unit
///
open class AKDecimator: AKNode, AKToggleable, AUComponent {
// MARK: - Properties
public static let ComponentDescription = AudioComponentDescription(appleEffect: kAudioUnitSubType_Distortion)
private var au: AUWrapper
fileprivate var lastKnownMix: Double = 1
/// Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5)
open var decimation: Double = 0.5 {
didSet {
decimation = (0...1).clamp(decimation)
au[kDistortionParam_Decimation] = decimation * 100
}
}
/// Rounding (Normalized Value) ranges from 0 to 1 (Default: 0)
open var rounding: Double = 0 {
didSet {
rounding = (0...1).clamp(rounding)
au[kDistortionParam_Rounding] = rounding * 100
}
}
/// Mix (Normalized Value) ranges from 0 to 1 (Default: 1)
open var mix: Double = 1 {
didSet {
mix = (0...1).clamp(mix)
au[kDistortionParam_FinalMix] = mix * 100
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
open var isStarted = true
// MARK: - Initialization
/// Initialize the decimator node
///
/// - Parameters:
/// - input: Input node to process
/// - decimation: Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5)
/// - rounding: Rounding (Normalized Value) ranges from 0 to 1 (Default: 0)
/// - mix: Mix (Normalized Value) ranges from 0 to 1 (Default: 1)
///
public init(
_ input: AKNode,
decimation: Double = 0.5,
rounding: Double = 0,
mix: Double = 1) {
self.decimation = decimation
self.rounding = rounding
self.mix = mix
let internalEffect = AVAudioUnitEffect(audioComponentDescription: _Self.ComponentDescription)
au = AUWrapper(au: internalEffect.audioUnit)
super.init()
avAudioNode = internalEffect
AudioKit.engine.attach(self.avAudioNode)
input.addConnectionPoint(self)
// Since this is the Decimator, mix it to 100% and use the final mix as the mix parameter
au[kDistortionParam_Decimation] = decimation * 100
au[kDistortionParam_Rounding] = rounding * 100
au[kDistortionParam_FinalMix] = mix * 100
au[kDistortionParam_PolynomialMix] = 0
au[kDistortionParam_DelayMix] = 0
au[kDistortionParam_DelayMix] = 0
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
open func start() {
if isStopped {
mix = lastKnownMix
isStarted = true
}
}
/// Function to stop or bypass the node, both are equivalent
open func stop() {
if isPlaying {
lastKnownMix = mix
mix = 0
isStarted = false
}
}
}
|
import Foundation
import RxSwift
import UIKit
public class ListingListViewController: UIViewController {
private let contentView: ListingListView
private let service: ListingService
private let disposeBag: DisposeBag
public init(service: ListingService,
title: String) {
self.contentView = ListingListView()
self.service = service
self.disposeBag = DisposeBag()
super.init(nibName: nil, bundle: nil)
self.title = title
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
view.backgroundColor = UIColor.white
contentView.frame = view.frame
view.addSubview(contentView)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
target: self,
action: #selector(create))
let params = ListingServiceSearchParams()
service.search(params: params) { [weak self] result in
guard let listings = result.data else { return }
self?.contentView.listings = listings
}
service.events.subscribe(onNext: { [weak self] event in
guard let `self` = self else { return }
switch event {
case let .create(listing):
self.contentView.create(listing: listing)
case let .update(listing):
self.contentView.update(listing: listing)
case let .delete(listing):
self.contentView.delete(listing: listing)
}
}, onError: { error in
print("onError: \(error)")
}, onCompleted: {
print("onCompleted")
}, onDisposed: {
print("onDisposed")
}).disposed(by: disposeBag)
contentView.selectedListing.subscribe(onNext: { [weak self] listing in
guard let `self` = self,
let listing = listing else { return }
let viewController = ListingDetailViewController(service: self.service,
listing: listing)
self.navigationController?.pushViewController(viewController, animated: true)
}, onError: { error in
print("onError: \(error)")
}, onCompleted: {
print("onCompleted")
}, onDisposed: {
print("onDisposed")
}).disposed(by: disposeBag)
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
contentView.deselectSelectedRow()
}
@objc private dynamic func create() {
let params = ListingServiceCreateParams(title: String.makeRandom(length: 10),
price: Int.makeRandom())
service.create(params: params,
completion: nil)
}
}
fix indentation in listing list vc
import Foundation
import RxSwift
import UIKit
public class ListingListViewController: UIViewController {
private let contentView: ListingListView
private let service: ListingService
private let disposeBag: DisposeBag
public init(service: ListingService,
title: String) {
self.contentView = ListingListView()
self.service = service
self.disposeBag = DisposeBag()
super.init(nibName: nil, bundle: nil)
self.title = title
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
view.backgroundColor = UIColor.white
contentView.frame = view.frame
view.addSubview(contentView)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
target: self,
action: #selector(create))
let params = ListingServiceSearchParams()
service.search(params: params) { [weak self] result in
guard let listings = result.data else { return }
self?.contentView.listings = listings
}
service.events.subscribe(onNext: { [weak self] event in
guard let `self` = self else { return }
switch event {
case let .create(listing):
self.contentView.create(listing: listing)
case let .update(listing):
self.contentView.update(listing: listing)
case let .delete(listing):
self.contentView.delete(listing: listing)
}
}, onError: { error in
print("onError: \(error)")
}, onCompleted: {
print("onCompleted")
}, onDisposed: {
print("onDisposed")
}).disposed(by: disposeBag)
contentView.selectedListing.subscribe(onNext: { [weak self] listing in
guard let `self` = self,
let listing = listing else { return }
let viewController = ListingDetailViewController(service: self.service,
listing: listing)
self.navigationController?.pushViewController(viewController, animated: true)
}, onError: { error in
print("onError: \(error)")
}, onCompleted: {
print("onCompleted")
}, onDisposed: {
print("onDisposed")
}).disposed(by: disposeBag)
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
contentView.deselectSelectedRow()
}
@objc private dynamic func create() {
let params = ListingServiceCreateParams(title: String.makeRandom(length: 10),
price: Int.makeRandom())
service.create(params: params,
completion: nil)
}
}
|
//
// ViewController.swift
// ESTabBarControllerExample
//
// Created by lihao on 2017/2/8.
// Copyright © 2017年 Vincent Li. All rights reserved.
//
import UIKit
public class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,UITabBarControllerDelegate {
@IBOutlet weak var tableView: UITableView!
public let titleArray = ["Basic", "Embed", "Animation", "Irregular", "Customize click", "Remind", "Lottie"]
public let dataArray = [
[
"UITabBarController default style",
"ESTabBarController default style",
"Mix ESTabBar and UITabBar ",
"UITabBarController style with 'More'",
"ESTabBarController style with 'More'",
"Mix ESTabBar and UITabBar with 'More'",
"UITabBarController style with non-zero default index",
"ESTabBarController style with non-zero default index"
],
[
"ESTabBarController embeds the UINavigationController style",
"UINavigationController embeds the ESTabBarController style",
],
[
"Customize the selected color style",
"Spring animation style",
"Background color change style",
"With a selected effect style",
"Suggested clicks style",
],
[
"In the middle with a larger button style",
],
[
"Hijack button click event",
"Add a special reminder box",
],
[
"System remind style",
"Imitate system remind style",
"Remind style with animation",
"Remind style with animation(2)",
"Customize remind style",
],
[
"Lottie",
],
]
public override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.init(white: 245.0 / 255.0, alpha: 1.0)
self.navigationItem.title = "Example"
if tableView != nil {
tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "UITableViewCell")
}
}
// MARK: UITableViewDataSource
public func numberOfSections(in tableView: UITableView) -> Int {
return dataArray.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray[section].count
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 52.0
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 42.0
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return titleArray[section]
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell")
cell?.textLabel?.textColor = UIColor.init(white: 0.0, alpha: 0.6)
cell?.textLabel?.font = UIFont.init(name: "ChalkboardSE-Bold", size: 14.0)
cell?.textLabel?.text = "\(indexPath.section + 1).\(indexPath.row + 1) \(dataArray[indexPath.section][indexPath.row])"
cell?.textLabel?.numberOfLines = 2
return cell!
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
self.present(ExampleProvider.systemStyle(), animated: true, completion: nil)
case 1:
self.present(ExampleProvider.customStyle(), animated: true, completion: nil)
case 2:
self.present(ExampleProvider.mixtureStyle(), animated: true, completion: nil)
case 3:
self.present(ExampleProvider.systemMoreStyle(), animated: true, completion: nil)
case 4:
self.present(ExampleProvider.customMoreStyle(), animated: true, completion: nil)
case 5:
self.present(ExampleProvider.mixtureMoreStyle(), animated: true, completion: nil)
case 6:
let tabBarController = ExampleProvider.systemStyle()
self.present(tabBarController, animated: true, completion: nil)
tabBarController.selectedIndex = 2
case 7:
let tabBarController = ExampleProvider.customStyle()
self.present(tabBarController, animated: true, completion: nil)
tabBarController.selectedIndex = 2
default:
break
}
case 1:
switch indexPath.row {
case 0:
self.present(ExampleProvider.navigationWithTabbarStyle(), animated: true, completion: nil)
case 1:
self.present(ExampleProvider.tabbarWithNavigationStyle(), animated: true, completion: nil)
default:
break
}
case 2:
switch indexPath.row {
case 0:
self.present(ExampleProvider.customColorStyle(), animated: true, completion: nil)
case 1:
self.present(ExampleProvider.customBouncesStyle(), animated: true, completion: nil)
case 2:
self.present(ExampleProvider.customBackgroundColorStyle(implies: false), animated: true, completion: nil)
case 3:
self.present(ExampleProvider.customHighlightableStyle(), animated: true, completion: nil)
case 4:
self.present(ExampleProvider.customBackgroundColorStyle(implies: true), animated: true, completion: nil)
default:
break
}
case 3:
switch indexPath.row {
case 0:
self.present(ExampleProvider.customIrregularityStyle(delegate: nil), animated: true, completion: nil)
default:
break
}
case 4:
switch indexPath.row {
case 0:
self.present(ExampleProvider.customIrregularityStyle(delegate: self), animated: true, completion: nil)
case 1:
self.present(ExampleProvider.customTipsStyle(delegate: self), animated: true, completion: nil)
default:
break
}
case 5:
switch indexPath.row {
case 0:
self.present(ExampleProvider.systemRemindStyle(), animated: true, completion: nil)
case 1:
self.present(ExampleProvider.customRemindStyle(), animated: true, completion: nil)
case 2:
self.present(ExampleProvider.customAnimateRemindStyle(implies: false), animated: true, completion: nil)
case 3:
self.present(ExampleProvider.customAnimateRemindStyle2(implies: false), animated: true, completion: nil)
case 4:
self.present(ExampleProvider.customAnimateRemindStyle3(implies: false), animated: true, completion: nil)
default:
break
}
case 6:
switch indexPath.row {
case 0:
self.present(ExampleProvider.lottieSytle(), animated: true, completion: nil)
default:
break
}
default:
break
}
}
}
Add chinese subtitles.
//
// ViewController.swift
// ESTabBarControllerExample
//
// Created by lihao on 2017/2/8.
// Copyright © 2017年 Vincent Li. All rights reserved.
//
import UIKit
public class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,UITabBarControllerDelegate {
@IBOutlet weak var tableView: UITableView!
public let sectionTitleArray = ["Basic", "Embed", "Animation", "Irregular", "Customize click", "Remind", "Lottie"]
public let sectionSubtitleArray = ["基本", "嵌套", "动画", "不规则", "自定义点击", "提醒", "Lottie"]
public let titleArray = [
[
"UITabBarController style",
"ESTabBarController like system style",
"Mix ESTabBar and UITabBar",
"UITabBarController style with 'More'",
"ESTabBarController style with 'More'",
"Mix ESTabBar and UITabBar with 'More'",
"UITabBarController style with non-zero default index",
"ESTabBarController style with non-zero default index"
],
[
"ESTabBarController embeds the UINavigationController style",
"UINavigationController embeds the ESTabBarController style",
],
[
"Customize the selected color style",
"Spring animation style",
"Background color change style",
"With a selected effect style",
"Suggested clicks style",
],
[
"In the middle with a larger button style",
],
[
"Hijack button click event",
"Add a special reminder box",
],
[
"System remind style",
"Imitate system remind style",
"Remind style with animation",
"Remind style with animation(2)",
"Customize remind style",
],
[
"Lottie",
],
]
public let subtitleArray = [
[
"UITabBarController样式",
"ESTabBarController仿系统样式",
"ESTabBar和UITabBar混合样式",
"带有'More'的UITabBarController样式",
"带有'More'的ESTabBarController样式",
"带有'More'的ESTabBar和UITabBar混合样式",
"默认index非0的UITabBarController样式",
"默认index非0的ESTabBarController样式"
],
[
"UINavigationController内嵌UITabBarController样式",
"UITabBarController内嵌UINavigationController样式",
],
[
"自定义选中颜色样式",
"弹簧动画样式",
"背景颜色变化样式",
"带有选中效果样式",
"暗示用户点击样式",
],
[
"中间带有较大按钮样式",
],
[
"劫持按钮的点击事件",
"添加一个特殊的提醒框",
],
[
"系统提醒样式",
"仿系统提醒样式",
"带动画提醒样式",
"带动画提醒样式(2)",
"自定义提醒样式",
],
[
"Lottie",
],
]
public override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.init(white: 245.0 / 255.0, alpha: 1.0)
self.navigationItem.title = "Example"
}
// MARK: UITableViewDataSource
public func numberOfSections(in tableView: UITableView) -> Int {
return sectionTitleArray.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titleArray[section].count
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 68.0
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 42.0
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitleArray[section] + " " + "(" + sectionSubtitleArray[section] + ")"
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell") ?? UITableViewCell.init(style: .subtitle, reuseIdentifier: "UITableViewCell")
cell.textLabel?.textColor = UIColor.init(white: 0.0, alpha: 0.6)
cell.textLabel?.font = UIFont.init(name: "ChalkboardSE-Bold", size: 14.0)
cell.textLabel?.lineBreakMode = .byCharWrapping
cell.textLabel?.text = "\(indexPath.section + 1).\(indexPath.row + 1) \(titleArray[indexPath.section][indexPath.row])"
cell.textLabel?.numberOfLines = 2
cell.detailTextLabel?.textColor = UIColor.init(white: 0.0, alpha: 0.5)
cell.detailTextLabel?.font = UIFont.init(name: "ChalkboardSE-Bold", size: 11.0)
cell.detailTextLabel?.text = "\(indexPath.section + 1).\(indexPath.row + 1) \(subtitleArray[indexPath.section][indexPath.row])"
cell.detailTextLabel?.numberOfLines = 2
return cell
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
self.present(ExampleProvider.systemStyle(), animated: true, completion: nil)
case 1:
self.present(ExampleProvider.customStyle(), animated: true, completion: nil)
case 2:
self.present(ExampleProvider.mixtureStyle(), animated: true, completion: nil)
case 3:
self.present(ExampleProvider.systemMoreStyle(), animated: true, completion: nil)
case 4:
self.present(ExampleProvider.customMoreStyle(), animated: true, completion: nil)
case 5:
self.present(ExampleProvider.mixtureMoreStyle(), animated: true, completion: nil)
case 6:
let tabBarController = ExampleProvider.systemStyle()
self.present(tabBarController, animated: true, completion: nil)
tabBarController.selectedIndex = 2
case 7:
let tabBarController = ExampleProvider.customStyle()
self.present(tabBarController, animated: true, completion: nil)
tabBarController.selectedIndex = 2
default:
break
}
case 1:
switch indexPath.row {
case 0:
self.present(ExampleProvider.navigationWithTabbarStyle(), animated: true, completion: nil)
case 1:
self.present(ExampleProvider.tabbarWithNavigationStyle(), animated: true, completion: nil)
default:
break
}
case 2:
switch indexPath.row {
case 0:
self.present(ExampleProvider.customColorStyle(), animated: true, completion: nil)
case 1:
self.present(ExampleProvider.customBouncesStyle(), animated: true, completion: nil)
case 2:
self.present(ExampleProvider.customBackgroundColorStyle(implies: false), animated: true, completion: nil)
case 3:
self.present(ExampleProvider.customHighlightableStyle(), animated: true, completion: nil)
case 4:
self.present(ExampleProvider.customBackgroundColorStyle(implies: true), animated: true, completion: nil)
default:
break
}
case 3:
switch indexPath.row {
case 0:
self.present(ExampleProvider.customIrregularityStyle(delegate: nil), animated: true, completion: nil)
default:
break
}
case 4:
switch indexPath.row {
case 0:
self.present(ExampleProvider.customIrregularityStyle(delegate: self), animated: true, completion: nil)
case 1:
self.present(ExampleProvider.customTipsStyle(delegate: self), animated: true, completion: nil)
default:
break
}
case 5:
switch indexPath.row {
case 0:
self.present(ExampleProvider.systemRemindStyle(), animated: true, completion: nil)
case 1:
self.present(ExampleProvider.customRemindStyle(), animated: true, completion: nil)
case 2:
self.present(ExampleProvider.customAnimateRemindStyle(implies: false), animated: true, completion: nil)
case 3:
self.present(ExampleProvider.customAnimateRemindStyle2(implies: false), animated: true, completion: nil)
case 4:
self.present(ExampleProvider.customAnimateRemindStyle3(implies: false), animated: true, completion: nil)
default:
break
}
case 6:
switch indexPath.row {
case 0:
self.present(ExampleProvider.lottieSytle(), animated: true, completion: nil)
default:
break
}
default:
break
}
}
}
|
//
// HappinessViewController.swift
// Happiness
//
// Created by Domenico on 19.03.15.
// Copyright (c) 2015 Domenico Solazzo. All rights reserved.
//
import UIKit
class HappinessViewController: UIViewController, FaceViewDataSource {
@IBOutlet weak var faceView: FaceView!{
didSet{
faceView.dataSource = self
faceView.addGestureRecognizer(UIPinchGestureRecognizer(target:faceView, action:""))
}
}
var happiness: Int = 50{ // 0 = very sad, 100 = estatic
didSet{
happiness = min(max(happiness, 0),100)
println("happiness: \(happiness)")
self.updateUI()
}
}
func updateUI(){
faceView.setNeedsDisplay()
}
func smilinessForFaceView(sender: FaceView) -> Double? {
return Double(happiness-50)/50
}
}
Adding the scale function to the UIGestureRecognizer in the FaceViewCotroller
//
// HappinessViewController.swift
// Happiness
//
// Created by Domenico on 19.03.15.
// Copyright (c) 2015 Domenico Solazzo. All rights reserved.
//
import UIKit
class HappinessViewController: UIViewController, FaceViewDataSource {
@IBOutlet weak var faceView: FaceView!{
didSet{
faceView.dataSource = self
faceView.addGestureRecognizer(UIPinchGestureRecognizer(target:faceView, action:"scale:"))
}
}
var happiness: Int = 50{ // 0 = very sad, 100 = estatic
didSet{
happiness = min(max(happiness, 0),100)
println("happiness: \(happiness)")
self.updateUI()
}
}
func updateUI(){
faceView.setNeedsDisplay()
}
func smilinessForFaceView(sender: FaceView) -> Double? {
return Double(happiness-50)/50
}
}
|
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library)
// REQUIRES: concurrency
// REQUIRES: executable_test
// REQUIRES: concurrency_runtime
// Test requires _swift_task_enterThreadLocalContext which is not available
// in the back deployment runtime.
// UNSUPPORTED: back_deployment_runtime
// UNSUPPORTED: back_deploy_concurrency
import _Concurrency
import StdlibUnittest
var tests = TestSuite("Time")
@main struct Main {
static func main() async {
tests.test("ContinuousClock sleep") {
let clock = ContinuousClock()
let elapsed = await clock.measure {
try! await clock.sleep(until: .now + .milliseconds(100))
}
// give a reasonable range of expected elapsed time
expectGT(elapsed, .milliseconds(90))
expectLT(elapsed, .milliseconds(200))
}
tests.test("ContinuousClock sleep with tolerance") {
let clock = ContinuousClock()
let elapsed = await clock.measure {
try! await clock.sleep(until: .now + .milliseconds(100), tolerance: .milliseconds(100))
}
// give a reasonable range of expected elapsed time
expectGT(elapsed, .milliseconds(90))
expectLT(elapsed, .milliseconds(300))
}
tests.test("ContinuousClock sleep longer") {
let elapsed = await ContinuousClock().measure {
try! await Task.sleep(until: .now + .seconds(1), clock: .continuous)
}
expectGT(elapsed, .seconds(1) - .milliseconds(90))
expectLT(elapsed, .seconds(1) + .milliseconds(200))
}
tests.test("SuspendingClock sleep") {
let clock = SuspendingClock()
let elapsed = await clock.measure {
try! await clock.sleep(until: .now + .milliseconds(100))
}
// give a reasonable range of expected elapsed time
expectGT(elapsed, .milliseconds(90))
expectLT(elapsed, .milliseconds(200))
}
tests.test("SuspendingClock sleep with tolerance") {
let clock = SuspendingClock()
let elapsed = await clock.measure {
try! await clock.sleep(until: .now + .milliseconds(100), tolerance: .milliseconds(100))
}
// give a reasonable range of expected elapsed time
expectGT(elapsed, .milliseconds(90))
expectLT(elapsed, .milliseconds(300))
}
tests.test("SuspendingClock sleep longer") {
let elapsed = await SuspendingClock().measure {
try! await Task.sleep(until: .now + .seconds(1), clock: .suspending)
}
expectGT(elapsed, .seconds(1) - .milliseconds(90))
expectLT(elapsed, .seconds(1) + .milliseconds(200))
}
tests.test("duration addition") {
let d1 = Duration.milliseconds(500)
let d2 = Duration.milliseconds(500)
let d3 = Duration.milliseconds(-500)
let sum = d1 + d2
expectEqual(sum, .seconds(1))
let comps = sum.components
expectEqual(comps.seconds, 1)
expectEqual(comps.attoseconds, 0)
let adjusted = sum + d3
expectEqual(adjusted, .milliseconds(500))
}
tests.test("duration subtraction") {
let d1 = Duration.nanoseconds(500)
let d2 = d1 - .nanoseconds(100)
expectEqual(d2, .nanoseconds(400))
let d3 = d1 - .nanoseconds(500)
expectEqual(d3, .nanoseconds(0))
let d4 = d1 - .nanoseconds(600)
expectEqual(d4, .nanoseconds(-100))
}
tests.test("duration division") {
let d1 = Duration.seconds(1)
let halfSecond = d1 / 2
expectEqual(halfSecond, .milliseconds(500))
}
tests.test("duration multiplication") {
let d1 = Duration.seconds(1)
let twoSeconds = d1 * 2
expectEqual(twoSeconds, .seconds(2))
}
await runAllTestsAsync()
}
}
Disabling failing test Concurrency/Runtime/clock.swift on cooperative executor
This is XFAILed on cooperative executor due to missing implementations
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library)
// REQUIRES: concurrency
// REQUIRES: executable_test
// REQUIRES: concurrency_runtime
// Test requires _swift_task_enterThreadLocalContext which is not available
// in the back deployment runtime.
// UNSUPPORTED: back_deployment_runtime
// UNSUPPORTED: back_deploy_concurrency
// This is XFAILed on cooperative executor due to missing implementations
// XFAIL: single_threaded_runtime
import _Concurrency
import StdlibUnittest
var tests = TestSuite("Time")
@main struct Main {
static func main() async {
tests.test("ContinuousClock sleep") {
let clock = ContinuousClock()
let elapsed = await clock.measure {
try! await clock.sleep(until: .now + .milliseconds(100))
}
// give a reasonable range of expected elapsed time
expectGT(elapsed, .milliseconds(90))
expectLT(elapsed, .milliseconds(200))
}
tests.test("ContinuousClock sleep with tolerance") {
let clock = ContinuousClock()
let elapsed = await clock.measure {
try! await clock.sleep(until: .now + .milliseconds(100), tolerance: .milliseconds(100))
}
// give a reasonable range of expected elapsed time
expectGT(elapsed, .milliseconds(90))
expectLT(elapsed, .milliseconds(300))
}
tests.test("ContinuousClock sleep longer") {
let elapsed = await ContinuousClock().measure {
try! await Task.sleep(until: .now + .seconds(1), clock: .continuous)
}
expectGT(elapsed, .seconds(1) - .milliseconds(90))
expectLT(elapsed, .seconds(1) + .milliseconds(200))
}
tests.test("SuspendingClock sleep") {
let clock = SuspendingClock()
let elapsed = await clock.measure {
try! await clock.sleep(until: .now + .milliseconds(100))
}
// give a reasonable range of expected elapsed time
expectGT(elapsed, .milliseconds(90))
expectLT(elapsed, .milliseconds(200))
}
tests.test("SuspendingClock sleep with tolerance") {
let clock = SuspendingClock()
let elapsed = await clock.measure {
try! await clock.sleep(until: .now + .milliseconds(100), tolerance: .milliseconds(100))
}
// give a reasonable range of expected elapsed time
expectGT(elapsed, .milliseconds(90))
expectLT(elapsed, .milliseconds(300))
}
tests.test("SuspendingClock sleep longer") {
let elapsed = await SuspendingClock().measure {
try! await Task.sleep(until: .now + .seconds(1), clock: .suspending)
}
expectGT(elapsed, .seconds(1) - .milliseconds(90))
expectLT(elapsed, .seconds(1) + .milliseconds(200))
}
tests.test("duration addition") {
let d1 = Duration.milliseconds(500)
let d2 = Duration.milliseconds(500)
let d3 = Duration.milliseconds(-500)
let sum = d1 + d2
expectEqual(sum, .seconds(1))
let comps = sum.components
expectEqual(comps.seconds, 1)
expectEqual(comps.attoseconds, 0)
let adjusted = sum + d3
expectEqual(adjusted, .milliseconds(500))
}
tests.test("duration subtraction") {
let d1 = Duration.nanoseconds(500)
let d2 = d1 - .nanoseconds(100)
expectEqual(d2, .nanoseconds(400))
let d3 = d1 - .nanoseconds(500)
expectEqual(d3, .nanoseconds(0))
let d4 = d1 - .nanoseconds(600)
expectEqual(d4, .nanoseconds(-100))
}
tests.test("duration division") {
let d1 = Duration.seconds(1)
let halfSecond = d1 / 2
expectEqual(halfSecond, .milliseconds(500))
}
tests.test("duration multiplication") {
let d1 = Duration.seconds(1)
let twoSeconds = d1 * 2
expectEqual(twoSeconds, .seconds(2))
}
await runAllTestsAsync()
}
}
|
//
// SubscriptionManager.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/9/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
struct SubscriptionManager {
static func updateUnreadApplicationBadge() {
var unread = 0
Realm.execute({ (realm) in
for obj in realm.objects(Subscription.self) {
unread += obj.unread
}
}, completion: {
UIApplication.shared.applicationIconBadgeNumber = unread
})
}
static func updateSubscriptions(_ auth: Auth, completion: (() -> Void)?) {
let client = API.current()?.client(SubscriptionsClient.self)
let lastUpdateSubscriptions = auth.lastSubscriptionFetchWithLastMessage
let lastUpdateRooms = auth.lastRoomFetchWithLastMessage
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
client?.fetchSubscriptions(updatedSince: lastUpdateSubscriptions) {
dispatchGroup.leave()
// We don't trust the updatedSince response all the time.
// Our API is having issues with caching and we can't try
// to avoid this on the request.
client?.fetchSubscriptions(updatedSince: nil) { }
}
dispatchGroup.enter()
client?.fetchRooms(updatedSince: lastUpdateRooms) {
dispatchGroup.leave()
// We don't trust the updatedSince response all the time.
// Our API is having issues with caching and we can't try
// to avoid this on the request.
client?.fetchRooms(updatedSince: nil) { }
}
dispatchGroup.notify(queue: .main) {
completion?()
}
}
static func changes(_ auth: Auth) {
guard !auth.isInvalidated else { return }
let serverURL = auth.serverURL
let eventName = "\(auth.userId ?? "")/subscriptions-changed"
let request = [
"msg": "sub",
"name": "stream-notify-user",
"params": [eventName, false]
] as [String: Any]
let currentRealm = Realm.current
SocketManager.subscribe(request, eventName: eventName) { response in
guard !response.isError() else { return Log.debug(response.result.string) }
let msg = response.result["fields"]["args"][0]
let object = response.result["fields"]["args"][1]
currentRealm?.execute({ (realm) in
guard let auth = AuthManager.isAuthenticated(realm: realm), auth.serverURL == serverURL else { return }
let subscription = Subscription.getOrCreate(realm: realm, values: object, updates: { (object) in
object?.auth = msg == "removed" ? nil : auth
})
realm.add(subscription, update: true)
})
}
}
static func subscribeRoomChanges() {
guard let user = AuthManager.currentUser() else { return }
let eventName = "\(user.identifier ?? "")/rooms-changed"
let request = [
"msg": "sub",
"name": "stream-notify-user",
"params": [eventName, false]
] as [String: Any]
let currentRealm = Realm.current
SocketManager.subscribe(request, eventName: eventName) { response in
guard !response.isError() else { return Log.debug(response.result.string) }
let object = response.result["fields"]["args"][1]
currentRealm?.execute({ (realm) in
if let rid = object["_id"].string {
if let subscription = Subscription.find(rid: rid, realm: realm) {
subscription.mapRoom(object, realm: realm)
realm.add(subscription, update: true)
}
}
})
}
}
static func subscribeInAppNotifications() {
guard let user = AuthManager.currentUser() else { return }
let eventName = "\(user.identifier ?? "")/notification"
let request = [
"msg": "sub",
"name": "stream-notify-user",
"params": [eventName, false]
] as [String: Any]
SocketManager.subscribe(request, eventName: eventName) { response in
guard !response.isError() else { return Log.debug(response.result.string) }
if let data = try? response.result["fields"]["args"][0].rawData() {
let notification = try? JSONDecoder().decode(ChatNotification.self, from: data)
notification?.post()
}
}
}
}
Refresh the current realm before instantiating the SubscriptionsClient to make sure the server version info we just persisted will be available for this call even though they might be in different threads
//
// SubscriptionManager.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/9/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
struct SubscriptionManager {
static func updateUnreadApplicationBadge() {
var unread = 0
Realm.execute({ (realm) in
for obj in realm.objects(Subscription.self) {
unread += obj.unread
}
}, completion: {
UIApplication.shared.applicationIconBadgeNumber = unread
})
}
static func updateSubscriptions(_ auth: Auth, completion: (() -> Void)?) {
Realm.current?.refresh()
let client = API.current()?.client(SubscriptionsClient.self)
let lastUpdateSubscriptions = auth.lastSubscriptionFetchWithLastMessage
let lastUpdateRooms = auth.lastRoomFetchWithLastMessage
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
client?.fetchSubscriptions(updatedSince: lastUpdateSubscriptions) {
dispatchGroup.leave()
// We don't trust the updatedSince response all the time.
// Our API is having issues with caching and we can't try
// to avoid this on the request.
client?.fetchSubscriptions(updatedSince: nil) { }
}
dispatchGroup.enter()
client?.fetchRooms(updatedSince: lastUpdateRooms) {
dispatchGroup.leave()
// We don't trust the updatedSince response all the time.
// Our API is having issues with caching and we can't try
// to avoid this on the request.
client?.fetchRooms(updatedSince: nil) { }
}
dispatchGroup.notify(queue: .main) {
completion?()
}
}
static func changes(_ auth: Auth) {
guard !auth.isInvalidated else { return }
let serverURL = auth.serverURL
let eventName = "\(auth.userId ?? "")/subscriptions-changed"
let request = [
"msg": "sub",
"name": "stream-notify-user",
"params": [eventName, false]
] as [String: Any]
let currentRealm = Realm.current
SocketManager.subscribe(request, eventName: eventName) { response in
guard !response.isError() else { return Log.debug(response.result.string) }
let msg = response.result["fields"]["args"][0]
let object = response.result["fields"]["args"][1]
currentRealm?.execute({ (realm) in
guard let auth = AuthManager.isAuthenticated(realm: realm), auth.serverURL == serverURL else { return }
let subscription = Subscription.getOrCreate(realm: realm, values: object, updates: { (object) in
object?.auth = msg == "removed" ? nil : auth
})
realm.add(subscription, update: true)
})
}
}
static func subscribeRoomChanges() {
guard let user = AuthManager.currentUser() else { return }
let eventName = "\(user.identifier ?? "")/rooms-changed"
let request = [
"msg": "sub",
"name": "stream-notify-user",
"params": [eventName, false]
] as [String: Any]
let currentRealm = Realm.current
SocketManager.subscribe(request, eventName: eventName) { response in
guard !response.isError() else { return Log.debug(response.result.string) }
let object = response.result["fields"]["args"][1]
currentRealm?.execute({ (realm) in
if let rid = object["_id"].string {
if let subscription = Subscription.find(rid: rid, realm: realm) {
subscription.mapRoom(object, realm: realm)
realm.add(subscription, update: true)
}
}
})
}
}
static func subscribeInAppNotifications() {
guard let user = AuthManager.currentUser() else { return }
let eventName = "\(user.identifier ?? "")/notification"
let request = [
"msg": "sub",
"name": "stream-notify-user",
"params": [eventName, false]
] as [String: Any]
SocketManager.subscribe(request, eventName: eventName) { response in
guard !response.isError() else { return Log.debug(response.result.string) }
if let data = try? response.result["fields"]["args"][0].rawData() {
let notification = try? JSONDecoder().decode(ChatNotification.self, from: data)
notification?.post()
}
}
}
}
|
public let DSLBitBucketServerJSON = """
{
"danger": {
"git": {
"modified_files": [".gitignore"],
"created_files": ["banana", ".babelrc"],
"deleted_files": [".babelrc.example", "jest.eslint.config.js"],
"commits": [
{
"sha": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"parents": ["c62ada76533a2de045d4c6062988ba84df140729"],
"author": {
"email": "foo@bar.com",
"name": "danger",
"date": "2018-02-24T03:19:01.000Z"
},
"committer": {
"email": "foo@bar.com",
"name": "danger",
"date": "2018-02-24T03:19:01.000Z"
},
"message": "Modify and remove files",
"tree": null,
"url": "fake://host/artsy/emission/commits/d6725486c38d46a33e76f622cf24b9a388c8d13d"
},
{
"sha": "c62ada76533a2de045d4c6062988ba84df140729",
"parents": ["8942a1f75e4c95df836f19ef681d20a87da2ee20"],
"author": {
"email": "foo@bar.com",
"name": "danger",
"date": "2018-02-17T10:38:02.000Z"
},
"committer": {
"email": "foo@bar.com",
"name": "danger",
"date": "2018-02-17T10:38:02.000Z"
},
"message": "add banana",
"tree": null,
"url": "fake://host/artsy/emission/commits/c62ada76533a2de045d4c6062988ba84df140729"
}
]
},
"bitbucket_server": {
"metadata": {
"repoSlug": "artsy/emission",
"pullRequestID": "327"
},
"pr": {
"author": {
"approved": false,
"role": "AUTHOR",
"status": "UNAPPROVED",
"user": {
"active": true,
"displayName": "test",
"emailAddress": "user@email.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
}
},
"closed": false,
"createdDate": 1518863923273,
"toRef": {
"displayId": "foo",
"id": "refs/heads/foo",
"latestCommit": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"repository": {
"forkable": true,
"id": 1,
"links": {
"clone": [
{
"href": "http://test@localhost:7990/scm/proj/repo.git",
"name": "http"
},
{
"href": "ssh://git@localhost:7999/proj/repo.git",
"name": "ssh"
}
],
"self": [
{
"href": "http://localhost:7990/projects/PROJ/repos/repo/browse"
}
]
},
"name": "Repo",
"project": {
"id": 1,
"key": "PROJ",
"links": {
"self": [
{
"href": "http://localhost:7990/projects/PROJ"
}
]
},
"name": "Project",
"public": false,
"type": "NORMAL"
},
"public": false,
"scmId": "git",
"slug": "repo",
"state": "AVAILABLE",
"statusMessage": "Available"
}
},
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/projects/PROJ/repos/repo/pull-requests/1"
}
]
},
"locked": false,
"open": true,
"participants": [
{
"approved": false,
"role": "PARTICIPANT",
"status": "UNAPPROVED",
"user": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "user@email.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
}
}
],
"reviewers": [
{
"user": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"lastReviewedCommit": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"approved": true
}
],
"state": "OPEN",
"title": "Pull request title",
"fromRef": {
"displayId": "master",
"id": "refs/heads/master",
"latestCommit": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"repository": {
"forkable": true,
"id": 1,
"links": {
"clone": [
{
"href": "http://test@localhost:7990/scm/proj/repo.git",
"name": "http"
},
{
"href": "ssh://git@localhost:7999/proj/repo.git",
"name": "ssh"
}
],
"self": [
{
"href": "http://localhost:7990/projects/PROJ/repos/repo/browse"
}
]
},
"name": "Repo",
"project": {
"id": 1,
"key": "PROJ",
"links": {
"self": [
{
"href": "http://localhost:7990/projects/PROJ"
}
]
},
"name": "Project",
"public": false,
"type": "NORMAL"
},
"public": false,
"scmId": "git",
"slug": "repo",
"state": "AVAILABLE",
"statusMessage": "Available"
}
},
"updatedDate": 1519442356495,
"version": 2
},
"commits": [
{
"author": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"authorTimestamp": 1519442341000,
"committer": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"committerTimestamp": 1519442341000,
"displayId": "d6725486c38",
"id": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"message": "Modify and remove files",
"parents": [
{
"displayId": "c62ada76533",
"id": "c62ada76533a2de045d4c6062988ba84df140729"
}
]
},
{
"author": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"authorTimestamp": 1518863882000,
"committer": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"committerTimestamp": 1518863882000,
"displayId": "c62ada76533",
"id": "c62ada76533a2de045d4c6062988ba84df140729",
"message": "add banana",
"parents": [
{
"displayId": "8942a1f75e4",
"id": "8942a1f75e4c95df836f19ef681d20a87da2ee20"
}
]
}
],
"comments": [
{
"action": "RESCOPED",
"added": {
"commits": [
{
"author": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"authorTimestamp": 1519442341000,
"committer": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"committerTimestamp": 1519442341000,
"displayId": "d6725486c38",
"id": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"message": "Modify and remove files",
"parents": [
{
"displayId": "c62ada76533",
"id": "c62ada76533a2de045d4c6062988ba84df140729"
}
]
}
],
"total": 1
},
"createdDate": 1519442356495,
"fromHash": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"id": 61,
"previousFromHash": "c62ada76533a2de045d4c6062988ba84df140729",
"previousToHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"removed": {
"commits": [],
"total": 0
},
"toHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"user": {
"active": true,
"displayName": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
}
},
{
"action": "COMMENTED",
"comment": {
"author": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"comments": [],
"createdDate": 1518939353345,
"id": 10,
"permittedOperations": {
"deletable": true,
"editable": false
},
"properties": {
"repositoryId": 1
},
"tasks": [],
"text": "Text",
"updatedDate": 1519449132488,
"version": 23
},
"commentAction": "ADDED",
"createdDate": 1518939353345,
"id": 52,
"user": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
}
},
{
"action": "UPDATED",
"addedReviewers": [],
"createdDate": 1518937747368,
"id": 43,
"removedReviewers": [
{
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
}
],
"user": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
}
},
{
"action": "UPDATED",
"addedReviewers": [
{
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
}
],
"createdDate": 1518929751675,
"id": 42,
"removedReviewers": [],
"user": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
}
},
{
"action": "COMMENTED",
"comment": {
"author": {
"active": true,
"displayName": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
},
"comments": [],
"createdDate": 1518870689956,
"id": 2,
"permittedOperations": {
"deletable": true,
"editable": true
},
"properties": {
"repositoryId": 1
},
"tasks": [],
"text": "wow",
"updatedDate": 1518870689956,
"version": 0
},
"commentAction": "ADDED",
"commentAnchor": {
"diffType": "EFFECTIVE",
"fileType": "TO",
"fromHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"line": 1,
"lineType": "ADDED",
"orphaned": false,
"path": "banana",
"toHash": "7fe85eb2a4dbaa70414155022abc7e5465f09547"
},
"createdDate": 1518870689956,
"diff": {
"destination": {
"components": ["banana"],
"name": "banana",
"parent": "",
"toString": "banana"
},
"hunks": [
{
"destinationLine": 1,
"destinationSpan": 1,
"segments": [
{
"lines": [
{
"commentIds": [2],
"destination": 1,
"line": "bar",
"source": 0,
"truncated": false
}
],
"truncated": false,
"type": "ADDED"
}
],
"sourceLine": 0,
"sourceSpan": 0,
"truncated": false
}
],
"properties": {
"current": true,
"fromHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"toHash": "7fe85eb2a4dbaa70414155022abc7e5465f09547"
},
"source": null,
"truncated": false
},
"id": 5,
"user": {
"active": true,
"displayName": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
}
},
{
"action": "COMMENTED",
"comment": {
"author": {
"active": true,
"displayName": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
},
"comments": [],
"createdDate": 1518870515570,
"id": 1,
"permittedOperations": {
"deletable": true,
"editable": true
},
"properties": {
"repositoryId": 1
},
"tasks": [],
"text": "heyo",
"updatedDate": 1518870515570,
"version": 0
},
"commentAction": "ADDED",
"createdDate": 1518870515570,
"id": 4,
"user": {
"active": true,
"displayName": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
}
},
{
"action": "OPENED",
"createdDate": 1518863923424,
"id": 3,
"user": {
"active": true,
"displayName": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
}
}
],
"activities": [
{
"id": 61,
"createdDate": 1519442356495,
"user": {
"name": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"displayName": "test",
"active": true,
"slug": "test",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
}
},
"action": "RESCOPED",
"fromHash": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"previousFromHash": "c62ada76533a2de045d4c6062988ba84df140729",
"previousToHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"toHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"added": {
"commits": [
{
"id": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"displayId": "d6725486c38",
"author": {
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
},
"authorTimestamp": 1519442341000,
"committer": {
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
},
"committerTimestamp": 1519442341000,
"message": "Modify and remove files",
"parents": [
{
"id": "c62ada76533a2de045d4c6062988ba84df140729",
"displayId": "c62ada76533"
}
]
}
],
"total": 1
},
"removed": {
"commits": [],
"total": 0
}
},
{
"id": 52,
"createdDate": 1518939353345,
"user": {
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
},
"action": "COMMENTED",
"commentAction": "ADDED",
"comment": {
"properties": {
"repositoryId": 1
},
"id": 10,
"version": 23,
"text": "Text",
"author": {
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
},
"createdDate": 1518939353345,
"updatedDate": 1519449132488,
"comments": [],
"tasks": [],
"permittedOperations": {
"editable": false,
"deletable": true
}
}
},
{
"id": 43,
"createdDate": 1518937747368,
"user": {
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
},
"action": "UPDATED",
"addedReviewers": [],
"removedReviewers": [
{
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
}
]
},
{
"id": 42,
"createdDate": 1518929751675,
"user": {
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
},
"action": "UPDATED",
"addedReviewers": [
{
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
}
],
"removedReviewers": []
},
{
"id": 5,
"createdDate": 1518870689956,
"user": {
"name": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"displayName": "test",
"active": true,
"slug": "test",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
}
},
"action": "COMMENTED",
"commentAction": "ADDED",
"comment": {
"properties": {
"repositoryId": 1
},
"id": 2,
"version": 0,
"text": "wow",
"author": {
"name": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"displayName": "test",
"active": true,
"slug": "test",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
}
},
"createdDate": 1518870689956,
"updatedDate": 1518870689956,
"comments": [],
"tasks": [],
"permittedOperations": {
"editable": true,
"deletable": true
}
},
"commentAnchor": {
"fromHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"toHash": "7fe85eb2a4dbaa70414155022abc7e5465f09547",
"line": 1,
"lineType": "ADDED",
"fileType": "TO",
"path": "banana",
"diffType": "EFFECTIVE",
"orphaned": false
},
"diff": {
"source": null,
"destination": {
"components": ["banana"],
"parent": "",
"name": "banana",
"toString": "banana"
},
"hunks": [
{
"sourceLine": 0,
"sourceSpan": 0,
"destinationLine": 1,
"destinationSpan": 1,
"segments": [
{
"type": "ADDED",
"lines": [
{
"destination": 1,
"source": 0,
"line": "bar",
"truncated": false,
"commentIds": [2]
}
],
"truncated": false
}
],
"truncated": false
}
],
"truncated": false,
"properties": {
"toHash": "7fe85eb2a4dbaa70414155022abc7e5465f09547",
"current": true,
"fromHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20"
}
}
},
{
"id": 4,
"createdDate": 1518870515570,
"user": {
"name": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"displayName": "test",
"active": true,
"slug": "test",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
}
},
"action": "COMMENTED",
"commentAction": "ADDED",
"comment": {
"properties": {
"repositoryId": 1
},
"id": 1,
"version": 0,
"text": "heyo",
"author": {
"name": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"displayName": "test",
"active": true,
"slug": "test",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
}
},
"createdDate": 1518870515570,
"updatedDate": 1518870515570,
"comments": [],
"tasks": [],
"permittedOperations": {
"editable": true,
"deletable": true
}
}
},
{
"id": 3,
"createdDate": 1518863923424,
"user": {
"name": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"displayName": "test",
"active": true,
"slug": "test",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
}
},
"action": "OPENED"
}
],
"issues": [
{
"key": "JRA-11",
"url": "https://jira.atlassian.com/browse/JRA-11"
},
{
"key": "JRA-9",
"url": "https://jira.atlassian.com/browse/JRA-9"
}
]
},
"settings": {
"github": {
"accessToken": "12345",
"additionalHeaders": {}
},
"cliArgs": {}
}
}
}
"""
Disable file_length fail
// swiftlint:disable file_length
public let DSLBitBucketServerJSON = """
{
"danger": {
"git": {
"modified_files": [".gitignore"],
"created_files": ["banana", ".babelrc"],
"deleted_files": [".babelrc.example", "jest.eslint.config.js"],
"commits": [
{
"sha": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"parents": ["c62ada76533a2de045d4c6062988ba84df140729"],
"author": {
"email": "foo@bar.com",
"name": "danger",
"date": "2018-02-24T03:19:01.000Z"
},
"committer": {
"email": "foo@bar.com",
"name": "danger",
"date": "2018-02-24T03:19:01.000Z"
},
"message": "Modify and remove files",
"tree": null,
"url": "fake://host/artsy/emission/commits/d6725486c38d46a33e76f622cf24b9a388c8d13d"
},
{
"sha": "c62ada76533a2de045d4c6062988ba84df140729",
"parents": ["8942a1f75e4c95df836f19ef681d20a87da2ee20"],
"author": {
"email": "foo@bar.com",
"name": "danger",
"date": "2018-02-17T10:38:02.000Z"
},
"committer": {
"email": "foo@bar.com",
"name": "danger",
"date": "2018-02-17T10:38:02.000Z"
},
"message": "add banana",
"tree": null,
"url": "fake://host/artsy/emission/commits/c62ada76533a2de045d4c6062988ba84df140729"
}
]
},
"bitbucket_server": {
"metadata": {
"repoSlug": "artsy/emission",
"pullRequestID": "327"
},
"pr": {
"author": {
"approved": false,
"role": "AUTHOR",
"status": "UNAPPROVED",
"user": {
"active": true,
"displayName": "test",
"emailAddress": "user@email.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
}
},
"closed": false,
"createdDate": 1518863923273,
"toRef": {
"displayId": "foo",
"id": "refs/heads/foo",
"latestCommit": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"repository": {
"forkable": true,
"id": 1,
"links": {
"clone": [
{
"href": "http://test@localhost:7990/scm/proj/repo.git",
"name": "http"
},
{
"href": "ssh://git@localhost:7999/proj/repo.git",
"name": "ssh"
}
],
"self": [
{
"href": "http://localhost:7990/projects/PROJ/repos/repo/browse"
}
]
},
"name": "Repo",
"project": {
"id": 1,
"key": "PROJ",
"links": {
"self": [
{
"href": "http://localhost:7990/projects/PROJ"
}
]
},
"name": "Project",
"public": false,
"type": "NORMAL"
},
"public": false,
"scmId": "git",
"slug": "repo",
"state": "AVAILABLE",
"statusMessage": "Available"
}
},
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/projects/PROJ/repos/repo/pull-requests/1"
}
]
},
"locked": false,
"open": true,
"participants": [
{
"approved": false,
"role": "PARTICIPANT",
"status": "UNAPPROVED",
"user": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "user@email.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
}
}
],
"reviewers": [
{
"user": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"lastReviewedCommit": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"approved": true
}
],
"state": "OPEN",
"title": "Pull request title",
"fromRef": {
"displayId": "master",
"id": "refs/heads/master",
"latestCommit": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"repository": {
"forkable": true,
"id": 1,
"links": {
"clone": [
{
"href": "http://test@localhost:7990/scm/proj/repo.git",
"name": "http"
},
{
"href": "ssh://git@localhost:7999/proj/repo.git",
"name": "ssh"
}
],
"self": [
{
"href": "http://localhost:7990/projects/PROJ/repos/repo/browse"
}
]
},
"name": "Repo",
"project": {
"id": 1,
"key": "PROJ",
"links": {
"self": [
{
"href": "http://localhost:7990/projects/PROJ"
}
]
},
"name": "Project",
"public": false,
"type": "NORMAL"
},
"public": false,
"scmId": "git",
"slug": "repo",
"state": "AVAILABLE",
"statusMessage": "Available"
}
},
"updatedDate": 1519442356495,
"version": 2
},
"commits": [
{
"author": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"authorTimestamp": 1519442341000,
"committer": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"committerTimestamp": 1519442341000,
"displayId": "d6725486c38",
"id": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"message": "Modify and remove files",
"parents": [
{
"displayId": "c62ada76533",
"id": "c62ada76533a2de045d4c6062988ba84df140729"
}
]
},
{
"author": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"authorTimestamp": 1518863882000,
"committer": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"committerTimestamp": 1518863882000,
"displayId": "c62ada76533",
"id": "c62ada76533a2de045d4c6062988ba84df140729",
"message": "add banana",
"parents": [
{
"displayId": "8942a1f75e4",
"id": "8942a1f75e4c95df836f19ef681d20a87da2ee20"
}
]
}
],
"comments": [
{
"action": "RESCOPED",
"added": {
"commits": [
{
"author": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"authorTimestamp": 1519442341000,
"committer": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"committerTimestamp": 1519442341000,
"displayId": "d6725486c38",
"id": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"message": "Modify and remove files",
"parents": [
{
"displayId": "c62ada76533",
"id": "c62ada76533a2de045d4c6062988ba84df140729"
}
]
}
],
"total": 1
},
"createdDate": 1519442356495,
"fromHash": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"id": 61,
"previousFromHash": "c62ada76533a2de045d4c6062988ba84df140729",
"previousToHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"removed": {
"commits": [],
"total": 0
},
"toHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"user": {
"active": true,
"displayName": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
}
},
{
"action": "COMMENTED",
"comment": {
"author": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
},
"comments": [],
"createdDate": 1518939353345,
"id": 10,
"permittedOperations": {
"deletable": true,
"editable": false
},
"properties": {
"repositoryId": 1
},
"tasks": [],
"text": "Text",
"updatedDate": 1519449132488,
"version": 23
},
"commentAction": "ADDED",
"createdDate": 1518939353345,
"id": 52,
"user": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
}
},
{
"action": "UPDATED",
"addedReviewers": [],
"createdDate": 1518937747368,
"id": 43,
"removedReviewers": [
{
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
}
],
"user": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
}
},
{
"action": "UPDATED",
"addedReviewers": [
{
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
}
],
"createdDate": 1518929751675,
"id": 42,
"removedReviewers": [],
"user": {
"active": true,
"displayName": "DangerCI",
"emailAddress": "foo@bar.com",
"id": 2,
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
},
"name": "danger",
"slug": "danger",
"type": "NORMAL"
}
},
{
"action": "COMMENTED",
"comment": {
"author": {
"active": true,
"displayName": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
},
"comments": [],
"createdDate": 1518870689956,
"id": 2,
"permittedOperations": {
"deletable": true,
"editable": true
},
"properties": {
"repositoryId": 1
},
"tasks": [],
"text": "wow",
"updatedDate": 1518870689956,
"version": 0
},
"commentAction": "ADDED",
"commentAnchor": {
"diffType": "EFFECTIVE",
"fileType": "TO",
"fromHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"line": 1,
"lineType": "ADDED",
"orphaned": false,
"path": "banana",
"toHash": "7fe85eb2a4dbaa70414155022abc7e5465f09547"
},
"createdDate": 1518870689956,
"diff": {
"destination": {
"components": ["banana"],
"name": "banana",
"parent": "",
"toString": "banana"
},
"hunks": [
{
"destinationLine": 1,
"destinationSpan": 1,
"segments": [
{
"lines": [
{
"commentIds": [2],
"destination": 1,
"line": "bar",
"source": 0,
"truncated": false
}
],
"truncated": false,
"type": "ADDED"
}
],
"sourceLine": 0,
"sourceSpan": 0,
"truncated": false
}
],
"properties": {
"current": true,
"fromHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"toHash": "7fe85eb2a4dbaa70414155022abc7e5465f09547"
},
"source": null,
"truncated": false
},
"id": 5,
"user": {
"active": true,
"displayName": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
}
},
{
"action": "COMMENTED",
"comment": {
"author": {
"active": true,
"displayName": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
},
"comments": [],
"createdDate": 1518870515570,
"id": 1,
"permittedOperations": {
"deletable": true,
"editable": true
},
"properties": {
"repositoryId": 1
},
"tasks": [],
"text": "heyo",
"updatedDate": 1518870515570,
"version": 0
},
"commentAction": "ADDED",
"createdDate": 1518870515570,
"id": 4,
"user": {
"active": true,
"displayName": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
}
},
{
"action": "OPENED",
"createdDate": 1518863923424,
"id": 3,
"user": {
"active": true,
"displayName": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
},
"name": "test",
"slug": "test",
"type": "NORMAL"
}
}
],
"activities": [
{
"id": 61,
"createdDate": 1519442356495,
"user": {
"name": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"displayName": "test",
"active": true,
"slug": "test",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
}
},
"action": "RESCOPED",
"fromHash": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"previousFromHash": "c62ada76533a2de045d4c6062988ba84df140729",
"previousToHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"toHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"added": {
"commits": [
{
"id": "d6725486c38d46a33e76f622cf24b9a388c8d13d",
"displayId": "d6725486c38",
"author": {
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
},
"authorTimestamp": 1519442341000,
"committer": {
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
},
"committerTimestamp": 1519442341000,
"message": "Modify and remove files",
"parents": [
{
"id": "c62ada76533a2de045d4c6062988ba84df140729",
"displayId": "c62ada76533"
}
]
}
],
"total": 1
},
"removed": {
"commits": [],
"total": 0
}
},
{
"id": 52,
"createdDate": 1518939353345,
"user": {
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
},
"action": "COMMENTED",
"commentAction": "ADDED",
"comment": {
"properties": {
"repositoryId": 1
},
"id": 10,
"version": 23,
"text": "Text",
"author": {
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
},
"createdDate": 1518939353345,
"updatedDate": 1519449132488,
"comments": [],
"tasks": [],
"permittedOperations": {
"editable": false,
"deletable": true
}
}
},
{
"id": 43,
"createdDate": 1518937747368,
"user": {
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
},
"action": "UPDATED",
"addedReviewers": [],
"removedReviewers": [
{
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
}
]
},
{
"id": 42,
"createdDate": 1518929751675,
"user": {
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
},
"action": "UPDATED",
"addedReviewers": [
{
"name": "danger",
"emailAddress": "foo@bar.com",
"id": 2,
"displayName": "DangerCI",
"active": true,
"slug": "danger",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/danger"
}
]
}
}
],
"removedReviewers": []
},
{
"id": 5,
"createdDate": 1518870689956,
"user": {
"name": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"displayName": "test",
"active": true,
"slug": "test",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
}
},
"action": "COMMENTED",
"commentAction": "ADDED",
"comment": {
"properties": {
"repositoryId": 1
},
"id": 2,
"version": 0,
"text": "wow",
"author": {
"name": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"displayName": "test",
"active": true,
"slug": "test",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
}
},
"createdDate": 1518870689956,
"updatedDate": 1518870689956,
"comments": [],
"tasks": [],
"permittedOperations": {
"editable": true,
"deletable": true
}
},
"commentAnchor": {
"fromHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20",
"toHash": "7fe85eb2a4dbaa70414155022abc7e5465f09547",
"line": 1,
"lineType": "ADDED",
"fileType": "TO",
"path": "banana",
"diffType": "EFFECTIVE",
"orphaned": false
},
"diff": {
"source": null,
"destination": {
"components": ["banana"],
"parent": "",
"name": "banana",
"toString": "banana"
},
"hunks": [
{
"sourceLine": 0,
"sourceSpan": 0,
"destinationLine": 1,
"destinationSpan": 1,
"segments": [
{
"type": "ADDED",
"lines": [
{
"destination": 1,
"source": 0,
"line": "bar",
"truncated": false,
"commentIds": [2]
}
],
"truncated": false
}
],
"truncated": false
}
],
"truncated": false,
"properties": {
"toHash": "7fe85eb2a4dbaa70414155022abc7e5465f09547",
"current": true,
"fromHash": "8942a1f75e4c95df836f19ef681d20a87da2ee20"
}
}
},
{
"id": 4,
"createdDate": 1518870515570,
"user": {
"name": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"displayName": "test",
"active": true,
"slug": "test",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
}
},
"action": "COMMENTED",
"commentAction": "ADDED",
"comment": {
"properties": {
"repositoryId": 1
},
"id": 1,
"version": 0,
"text": "heyo",
"author": {
"name": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"displayName": "test",
"active": true,
"slug": "test",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
}
},
"createdDate": 1518870515570,
"updatedDate": 1518870515570,
"comments": [],
"tasks": [],
"permittedOperations": {
"editable": true,
"deletable": true
}
}
},
{
"id": 3,
"createdDate": 1518863923424,
"user": {
"name": "test",
"emailAddress": "foo@bar.com",
"id": 1,
"displayName": "test",
"active": true,
"slug": "test",
"type": "NORMAL",
"links": {
"self": [
{
"href": "http://localhost:7990/users/test"
}
]
}
},
"action": "OPENED"
}
],
"issues": [
{
"key": "JRA-11",
"url": "https://jira.atlassian.com/browse/JRA-11"
},
{
"key": "JRA-9",
"url": "https://jira.atlassian.com/browse/JRA-9"
}
]
},
"settings": {
"github": {
"accessToken": "12345",
"additionalHeaders": {}
},
"cliArgs": {}
}
}
}
"""
|
//
// UIScrollView+RGAppTools.swift
// RGAppTools
//
// Created by RAIN on 2018/10/31.
// Copyright © 2018年 Smartech. All rights reserved.
//
import UIKit
extension RGAppTools where Base: UIScrollView {
/// 注册 Table View / Collection View 的 Cell
///
/// - Parameter cellClass: Cell 类
public func registerNibCell(with cellClass: AnyClass) {
if let nibName = anyClassToString(cellClass) {
let cellNib = UINib(nibName: nibName, bundle: nil)
if let tableView = base as? UITableView {
tableView.register(cellNib, forCellReuseIdentifier: nibName)
} else if let collectionView = base as? UICollectionView {
collectionView.register(cellNib, forCellWithReuseIdentifier: nibName)
}
}
}
public func registerNibHeaderFooter(with viewClass: AnyClass) {
if let nibName = anyClassToString(viewClass) {
let nib = UINib(nibName: nibName, bundle: nil)
if let tableView = base as? UITableView {
tableView.register(nib, forHeaderFooterViewReuseIdentifier: nibName)
}
}
}
/// 描述类名的字符串
///
/// - Parameter className: 要转换成字符串的类
/// - Returns: 转换后的字符串
private func anyClassToString(_ className: AnyClass) -> String? {
let desc = className.description()
guard desc.contains(".") else {
return desc
}
return desc.components(separatedBy: ".").last
}
}
docs (UIScrollView) : add comment
//
// UIScrollView+RGAppTools.swift
// RGAppTools
//
// Created by RAIN on 2018/10/31.
// Copyright © 2018年 Smartech. All rights reserved.
//
import UIKit
extension RGAppTools where Base: UIScrollView {
/// 注册 Table View / Collection View 的 Cell
///
/// - Parameter cellClass: Cell 类
public func registerNibCell(with cellClass: AnyClass) {
if let nibName = anyClassToString(cellClass) {
let cellNib = UINib(nibName: nibName, bundle: nil)
if let tableView = base as? UITableView {
tableView.register(cellNib, forCellReuseIdentifier: nibName)
} else if let collectionView = base as? UICollectionView {
collectionView.register(cellNib, forCellWithReuseIdentifier: nibName)
}
}
}
/// 注册 Table View 的 Header / Footer
///
/// - Parameter viewClass: Header / Footer 类
public func registerNibHeaderFooter(with viewClass: AnyClass) {
if let nibName = anyClassToString(viewClass) {
let nib = UINib(nibName: nibName, bundle: nil)
if let tableView = base as? UITableView {
tableView.register(nib, forHeaderFooterViewReuseIdentifier: nibName)
}
}
}
/// 描述类名的字符串
///
/// - Parameter className: 要转换成字符串的类
/// - Returns: 转换后的字符串
private func anyClassToString(_ className: AnyClass) -> String? {
let desc = className.description()
guard desc.contains(".") else {
return desc
}
return desc.components(separatedBy: ".").last
}
}
|
// File created from FlowTemplate
// $ createRootCoordinator.sh DeviceVerification DeviceVerification DeviceVerificationStart
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
@objcMembers
final class KeyVerificationCoordinator: KeyVerificationCoordinatorType {
// MARK: - Properties
// MARK: Private
private let navigationRouter: NavigationRouterType
private let session: MXSession
private let verificationFlow: KeyVerificationFlow
private let verificationKind: KeyVerificationKind
private weak var completeSecurityCoordinator: KeyVerificationSelfVerifyWaitCoordinatorType?
private var otherUserId: String {
let otherUserId: String
switch self.verificationFlow {
case .verifyUser(let roomMember):
otherUserId = roomMember.userId
case .verifyDevice(let userId, _):
otherUserId = userId
case .incomingRequest(let incomingKeyVerificationRequest):
otherUserId = incomingKeyVerificationRequest.otherUser
case .incomingSASTransaction(let incomingSASTransaction):
otherUserId = incomingSASTransaction.otherUserId
case .completeSecurity:
otherUserId = self.session.myUser.userId
}
return otherUserId
}
private var otherDeviceId: String? {
let otherDeviceId: String?
switch self.verificationFlow {
case .verifyUser:
otherDeviceId = nil
case .verifyDevice(_, let deviceId):
otherDeviceId = deviceId
case .incomingRequest(let incomingKeyVerificationRequest):
otherDeviceId = incomingKeyVerificationRequest.otherDevice
case .incomingSASTransaction(let incomingSASTransaction):
otherDeviceId = incomingSASTransaction.otherDeviceId
case .completeSecurity:
otherDeviceId = nil
}
return otherDeviceId
}
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
weak var delegate: KeyVerificationCoordinatorDelegate?
// MARK: - Setup
/// Creates a key verification coordinator.
///
/// - Parameters:
/// - session: The MXSession.
/// - flow: The wanted key verification flow.
/// - navigationRouter: Existing NavigationRouter from which present the flow (optional).
init(session: MXSession, flow: KeyVerificationFlow, navigationRouter: NavigationRouterType? = nil) {
self.navigationRouter = navigationRouter ?? NavigationRouter(navigationController: RiotNavigationController())
self.session = session
self.verificationFlow = flow
let verificationKind: KeyVerificationKind
switch flow {
case .incomingRequest(let request):
if request.isFromMyUser {
// TODO: Check for .newSession case
verificationKind = .otherSession
} else {
verificationKind = .user
}
case .verifyUser:
verificationKind = .user
case .completeSecurity:
verificationKind = .thisSession
case .verifyDevice:
verificationKind = .otherSession
case .incomingSASTransaction:
verificationKind = .otherSession
}
self.verificationKind = verificationKind
}
// MARK: - Public methods
func start() {
let rootCoordinator: Coordinator & Presentable
switch self.verificationFlow {
case .verifyUser(let roomMember):
rootCoordinator = self.createUserVerificationStartCoordinator(with: roomMember)
case .verifyDevice(let userId, let deviceId):
if userId == self.session.myUser.userId {
rootCoordinator = self.createSelfVerificationCoordinator(otherDeviceId: deviceId)
} else {
rootCoordinator = self.createDataLoadingScreenCoordinator(otherUserId: userId, otherDeviceId: deviceId)
}
case .incomingRequest(let incomingKeyVerificationRequest):
rootCoordinator = self.createDataLoadingScreenCoordinator(with: incomingKeyVerificationRequest)
case .incomingSASTransaction(let incomingSASTransaction):
rootCoordinator = self.createDataLoadingScreenCoordinator(otherUserId: incomingSASTransaction.otherUserId, otherDeviceId: incomingSASTransaction.otherDeviceId)
case .completeSecurity(let isNewSignIn):
let coordinator = self.createCompleteSecurityCoordinator(isNewSignIn: isNewSignIn)
self.completeSecurityCoordinator = coordinator
rootCoordinator = coordinator
}
rootCoordinator.start()
self.add(childCoordinator: rootCoordinator)
if self.navigationRouter.modules.isEmpty == false {
self.navigationRouter.push(rootCoordinator, animated: true, popCompletion: { [weak self] in
self?.remove(childCoordinator: rootCoordinator)
})
} else {
self.navigationRouter.setRootModule(rootCoordinator) { [weak self] in
self?.remove(childCoordinator: rootCoordinator)
}
}
}
func toPresentable() -> UIViewController {
return self.navigationRouter.toPresentable()
}
// MARK: - Private methods
private func didComplete() {
self.delegate?.keyVerificationCoordinatorDidComplete(self, otherUserId: self.otherUserId, otherDeviceId: self.otherDeviceId ?? "")
}
private func didCancel() {
// In the case of the complete security flow, come back to the root screen if any child flow
// like device verification has been cancelled
if self.completeSecurityCoordinator != nil && childCoordinators.count > 1 {
NSLog("[KeyVerificationCoordinator] didCancel: popToRootModule")
self.navigationRouter.popToRootModule(animated: true)
return
}
self.delegate?.keyVerificationCoordinatorDidCancel(self)
}
private func createCompleteSecurityCoordinator(isNewSignIn: Bool) -> KeyVerificationSelfVerifyWaitCoordinatorType {
let coordinator = KeyVerificationSelfVerifyWaitCoordinator(session: self.session, isNewSignIn: isNewSignIn)
coordinator.delegate = self
coordinator.start()
return coordinator
}
private func showSecretsRecovery(with recoveryMode: SecretsRecoveryMode) {
let coordinator = SecretsRecoveryCoordinator(session: self.session, recoveryMode: recoveryMode, recoveryGoal: .verifyDevice, navigationRouter: self.navigationRouter)
coordinator.delegate = self
coordinator.start()
self.add(childCoordinator: coordinator)
self.navigationRouter.setRootModule(coordinator) { [weak self] in
self?.remove(childCoordinator: coordinator)
}
}
private func createSelfVerificationCoordinator(otherDeviceId: String) -> KeyVerificationSelfVerifyStartCoordinator {
let coordinator = KeyVerificationSelfVerifyStartCoordinator(session: self.session, otherDeviceId: otherDeviceId)
coordinator.delegate = self
coordinator.start()
return coordinator
}
private func createDataLoadingScreenCoordinator(otherUserId: String, otherDeviceId: String) -> KeyVerificationDataLoadingCoordinator {
let coordinator = KeyVerificationDataLoadingCoordinator(session: self.session, verificationKind: self.verificationKind, otherUserId: otherUserId, otherDeviceId: otherDeviceId)
coordinator.delegate = self
coordinator.start()
return coordinator
}
private func createDataLoadingScreenCoordinator(with keyVerificationRequest: MXKeyVerificationRequest) -> KeyVerificationDataLoadingCoordinator {
let coordinator = KeyVerificationDataLoadingCoordinator(session: self.session, verificationKind: self.verificationKind, incomingKeyVerificationRequest: keyVerificationRequest)
coordinator.delegate = self
coordinator.start()
return coordinator
}
private func createUserVerificationStartCoordinator(with roomMember: MXRoomMember) -> UserVerificationStartCoordinator {
let coordinator = UserVerificationStartCoordinator(session: self.session, roomMember: roomMember)
coordinator.delegate = self
coordinator.start()
return coordinator
}
private func showStart(otherUser: MXUser, otherDevice: MXDeviceInfo) {
let coordinator = DeviceVerificationStartCoordinator(session: self.session, otherUser: otherUser, otherDevice: otherDevice)
coordinator.delegate = self
coordinator.start()
self.add(childCoordinator: coordinator)
self.navigationRouter.setRootModule(coordinator) { [weak self] in
self?.remove(childCoordinator: coordinator)
}
}
private func showIncoming(otherUser: MXUser, transaction: MXIncomingSASTransaction) {
let coordinator = DeviceVerificationIncomingCoordinator(session: self.session, otherUser: otherUser, transaction: transaction)
coordinator.delegate = self
coordinator.start()
self.add(childCoordinator: coordinator)
self.navigationRouter.setRootModule(coordinator) { [weak self] in
self?.remove(childCoordinator: coordinator)
}
}
private func showVerifyBySAS(transaction: MXSASTransaction, animated: Bool) {
let coordinator = KeyVerificationVerifyBySASCoordinator(session: self.session, transaction: transaction, verificationKind: self.verificationKind)
coordinator.delegate = self
coordinator.start()
self.add(childCoordinator: coordinator)
self.navigationRouter.push(coordinator, animated: animated) { [weak self] in
self?.remove(childCoordinator: coordinator)
}
}
private func showVerifyByScanning(keyVerificationRequest: MXKeyVerificationRequest, animated: Bool) {
let coordinator = KeyVerificationVerifyByScanningCoordinator(session: self.session, verificationKind: self.verificationKind, keyVerificationRequest: keyVerificationRequest)
coordinator.delegate = self
coordinator.start()
self.add(childCoordinator: coordinator)
self.navigationRouter.push(coordinator, animated: animated) { [weak self] in
self?.remove(childCoordinator: coordinator)
}
}
private func showScanConfirmation(for transaction: MXQRCodeTransaction, codeScanning: KeyVerificationScanning, animated: Bool) {
let coordinator = KeyVerificationScanConfirmationCoordinator(session: self.session, transaction: transaction, codeScanning: codeScanning, verificationKind: self.verificationKind)
coordinator.delegate = self
coordinator.start()
self.add(childCoordinator: coordinator)
self.navigationRouter.push(coordinator, animated: animated) { [weak self] in
self?.remove(childCoordinator: coordinator)
}
}
private func showVerified(animated: Bool) {
let viewController = KeyVerificationVerifiedViewController.instantiate(with: self.verificationKind)
viewController.delegate = self
self.navigationRouter.setRootModule(viewController)
}
}
// MARK: - KeyVerificationDataLoadingCoordinatorDelegate
extension KeyVerificationCoordinator: KeyVerificationDataLoadingCoordinatorDelegate {
func keyVerificationDataLoadingCoordinator(_ coordinator: KeyVerificationDataLoadingCoordinatorType, didAcceptKeyVerificationRequest keyVerificationRequest: MXKeyVerificationRequest) {
self.showVerifyByScanning(keyVerificationRequest: keyVerificationRequest, animated: true)
}
func keyVerificationDataLoadingCoordinator(_ coordinator: KeyVerificationDataLoadingCoordinatorType, didLoadUser user: MXUser, device: MXDeviceInfo) {
if case .incomingSASTransaction(let incomingTransaction) = self.verificationFlow {
self.showIncoming(otherUser: user, transaction: incomingTransaction)
} else {
self.showStart(otherUser: user, otherDevice: device)
}
}
func keyVerificationDataLoadingCoordinator(_ coordinator: KeyVerificationDataLoadingCoordinatorType, didAcceptKeyVerificationRequestWithTransaction transaction: MXKeyVerificationTransaction) {
if let sasTransaction = transaction as? MXSASTransaction {
self.showVerifyBySAS(transaction: sasTransaction, animated: true)
} else {
NSLog("[KeyVerificationCoordinator] Transaction \(transaction) is not supported")
self.didCancel()
}
}
func keyVerificationDataLoadingCoordinatorDidCancel(_ coordinator: KeyVerificationDataLoadingCoordinatorType) {
self.didCancel()
}
}
// MARK: - DeviceVerificationStartCoordinatorDelegate
extension KeyVerificationCoordinator: DeviceVerificationStartCoordinatorDelegate {
func deviceVerificationStartCoordinator(_ coordinator: DeviceVerificationStartCoordinatorType, didCompleteWithOutgoingTransaction transaction: MXSASTransaction) {
self.showVerifyBySAS(transaction: transaction, animated: true)
}
func deviceVerificationStartCoordinator(_ coordinator: DeviceVerificationStartCoordinatorType, didTransactionCancelled transaction: MXSASTransaction) {
self.didCancel()
}
func deviceVerificationStartCoordinatorDidCancel(_ coordinator: DeviceVerificationStartCoordinatorType) {
self.didCancel()
}
}
// MARK: - DeviceVerificationIncomingCoordinatorDelegate
extension KeyVerificationCoordinator: DeviceVerificationIncomingCoordinatorDelegate {
func deviceVerificationIncomingCoordinator(_ coordinator: DeviceVerificationIncomingCoordinatorType, didAcceptTransaction transaction: MXSASTransaction) {
self.showVerifyBySAS(transaction: transaction, animated: true)
}
func deviceVerificationIncomingCoordinatorDidCancel(_ coordinator: DeviceVerificationIncomingCoordinatorType) {
self.didCancel()
}
}
// MARK: - KeyVerificationVerifyBySASCoordinatorDelegate
extension KeyVerificationCoordinator: KeyVerificationVerifyBySASCoordinatorDelegate {
func keyVerificationVerifyBySASCoordinatorDidComplete(_ coordinator: KeyVerificationVerifyBySASCoordinatorType) {
self.showVerified(animated: true)
}
func keyVerificationVerifyBySASCoordinatorDidCancel(_ coordinator: KeyVerificationVerifyBySASCoordinatorType) {
self.didCancel()
}
}
// MARK: - KeyVerificationVerifiedViewControllerDelegate
extension KeyVerificationCoordinator: KeyVerificationVerifiedViewControllerDelegate {
func keyVerificationVerifiedViewControllerDidTapSetupAction(_ viewController: KeyVerificationVerifiedViewController) {
self.didComplete()
}
func keyVerificationVerifiedViewControllerDidCancel(_ viewController: KeyVerificationVerifiedViewController) {
self.didCancel()
}
}
// MARK: - UserVerificationStartCoordinatorDelegate
extension KeyVerificationCoordinator: UserVerificationStartCoordinatorDelegate {
func userVerificationStartCoordinator(_ coordinator: UserVerificationStartCoordinatorType, otherDidAcceptRequest request: MXKeyVerificationRequest) {
self.showVerifyByScanning(keyVerificationRequest: request, animated: true)
}
func userVerificationStartCoordinator(_ coordinator: UserVerificationStartCoordinatorType, didCompleteWithOutgoingTransaction transaction: MXSASTransaction) {
self.showVerifyBySAS(transaction: transaction, animated: true)
}
func userVerificationStartCoordinator(_ coordinator: UserVerificationStartCoordinatorType, didTransactionCancelled transaction: MXSASTransaction) {
self.didCancel()
}
func userVerificationStartCoordinatorDidCancel(_ coordinator: UserVerificationStartCoordinatorType) {
self.didCancel()
}
}
// MARK: - KeyVerificationVerifyByScanningCoordinatorDelegate
extension KeyVerificationCoordinator: KeyVerificationVerifyByScanningCoordinatorDelegate {
func keyVerificationVerifyByScanningCoordinatorDidCancel(_ coordinator: KeyVerificationVerifyByScanningCoordinatorType) {
self.didCancel()
}
func keyVerificationVerifyByScanningCoordinator(_ coordinator: KeyVerificationVerifyByScanningCoordinatorType, didScanOtherQRCodeData qrCodeData: MXQRCodeData, withTransaction transaction: MXQRCodeTransaction) {
self.showScanConfirmation(for: transaction, codeScanning: .scannedOtherQRCode(qrCodeData), animated: true)
}
func keyVerificationVerifyByScanningCoordinator(_ coordinator: KeyVerificationVerifyByScanningCoordinatorType, qrCodeDidScannedByOtherWithTransaction transaction: MXQRCodeTransaction) {
self.showScanConfirmation(for: transaction, codeScanning: .myQRCodeScanned, animated: true)
}
func keyVerificationVerifyByScanningCoordinator(_ coordinator: KeyVerificationVerifyByScanningCoordinatorType, didCompleteWithSASTransaction transaction: MXSASTransaction) {
self.showVerifyBySAS(transaction: transaction, animated: true)
}
}
// MARK: - KeyVerificationSelfVerifyStartCoordinatorDelegate
extension KeyVerificationCoordinator: KeyVerificationSelfVerifyStartCoordinatorDelegate {
func keyVerificationSelfVerifyStartCoordinator(_ coordinator: KeyVerificationSelfVerifyStartCoordinatorType, otherDidAcceptRequest request: MXKeyVerificationRequest) {
self.showVerifyByScanning(keyVerificationRequest: request, animated: true)
}
func keyVerificationSelfVerifyStartCoordinatorDidCancel(_ coordinator: KeyVerificationSelfVerifyStartCoordinatorType) {
self.didCancel()
}
}
// MARK: - KeyVerificationSelfVerifyWaitCoordinatorDelegate
extension KeyVerificationCoordinator: KeyVerificationSelfVerifyWaitCoordinatorDelegate {
func keyVerificationSelfVerifyWaitCoordinator(_ coordinator: KeyVerificationSelfVerifyWaitCoordinatorType, didAcceptKeyVerificationRequest keyVerificationRequest: MXKeyVerificationRequest) {
self.showVerifyByScanning(keyVerificationRequest: keyVerificationRequest, animated: true)
}
func keyVerificationSelfVerifyWaitCoordinator(_ coordinator: KeyVerificationSelfVerifyWaitCoordinatorType, didAcceptIncomingSASTransaction incomingSASTransaction: MXIncomingSASTransaction) {
self.showVerifyBySAS(transaction: incomingSASTransaction, animated: true)
}
func keyVerificationSelfVerifyWaitCoordinatorDidCancel(_ coordinator: KeyVerificationSelfVerifyWaitCoordinatorType) {
self.didCancel()
}
func keyVerificationSelfVerifyWaitCoordinator(_ coordinator: KeyVerificationSelfVerifyWaitCoordinatorType, wantsToRecoverSecretsWith secretsRecoveryMode: SecretsRecoveryMode) {
self.showSecretsRecovery(with: secretsRecoveryMode)
}
}
// MARK: - KeyVerificationScanConfirmationCoordinatorDelegate
extension KeyVerificationCoordinator: KeyVerificationScanConfirmationCoordinatorDelegate {
func keyVerificationScanConfirmationCoordinatorDidComplete(_ coordinator: KeyVerificationScanConfirmationCoordinatorType) {
self.showVerified(animated: true)
}
func keyVerificationScanConfirmationCoordinatorDidCancel(_ coordinator: KeyVerificationScanConfirmationCoordinatorType) {
self.didCancel()
}
}
// MARK: - SecretsRecoveryCoordinatorDelegate
extension KeyVerificationCoordinator: SecretsRecoveryCoordinatorDelegate {
func secretsRecoveryCoordinatorDidRecover(_ coordinator: SecretsRecoveryCoordinatorType) {
self.showVerified(animated: true)
}
func secretsRecoveryCoordinatorDidCancel(_ coordinator: SecretsRecoveryCoordinatorType) {
self.didCancel()
}
}
KeyVerificationCoordinator: Fix child coordinator removal issue.
// File created from FlowTemplate
// $ createRootCoordinator.sh DeviceVerification DeviceVerification DeviceVerificationStart
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
@objcMembers
final class KeyVerificationCoordinator: KeyVerificationCoordinatorType {
// MARK: - Properties
// MARK: Private
private let navigationRouter: NavigationRouterType
private let session: MXSession
private let verificationFlow: KeyVerificationFlow
private let verificationKind: KeyVerificationKind
private weak var completeSecurityCoordinator: KeyVerificationSelfVerifyWaitCoordinatorType?
private var otherUserId: String {
let otherUserId: String
switch self.verificationFlow {
case .verifyUser(let roomMember):
otherUserId = roomMember.userId
case .verifyDevice(let userId, _):
otherUserId = userId
case .incomingRequest(let incomingKeyVerificationRequest):
otherUserId = incomingKeyVerificationRequest.otherUser
case .incomingSASTransaction(let incomingSASTransaction):
otherUserId = incomingSASTransaction.otherUserId
case .completeSecurity:
otherUserId = self.session.myUser.userId
}
return otherUserId
}
private var otherDeviceId: String? {
let otherDeviceId: String?
switch self.verificationFlow {
case .verifyUser:
otherDeviceId = nil
case .verifyDevice(_, let deviceId):
otherDeviceId = deviceId
case .incomingRequest(let incomingKeyVerificationRequest):
otherDeviceId = incomingKeyVerificationRequest.otherDevice
case .incomingSASTransaction(let incomingSASTransaction):
otherDeviceId = incomingSASTransaction.otherDeviceId
case .completeSecurity:
otherDeviceId = nil
}
return otherDeviceId
}
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
weak var delegate: KeyVerificationCoordinatorDelegate?
// MARK: - Setup
/// Creates a key verification coordinator.
///
/// - Parameters:
/// - session: The MXSession.
/// - flow: The wanted key verification flow.
/// - navigationRouter: Existing NavigationRouter from which present the flow (optional).
init(session: MXSession, flow: KeyVerificationFlow, navigationRouter: NavigationRouterType? = nil) {
self.navigationRouter = navigationRouter ?? NavigationRouter(navigationController: RiotNavigationController())
self.session = session
self.verificationFlow = flow
let verificationKind: KeyVerificationKind
switch flow {
case .incomingRequest(let request):
if request.isFromMyUser {
// TODO: Check for .newSession case
verificationKind = .otherSession
} else {
verificationKind = .user
}
case .verifyUser:
verificationKind = .user
case .completeSecurity:
verificationKind = .thisSession
case .verifyDevice:
verificationKind = .otherSession
case .incomingSASTransaction:
verificationKind = .otherSession
}
self.verificationKind = verificationKind
}
// MARK: - Public methods
func start() {
let rootCoordinator: Coordinator & Presentable
switch self.verificationFlow {
case .verifyUser(let roomMember):
rootCoordinator = self.createUserVerificationStartCoordinator(with: roomMember)
case .verifyDevice(let userId, let deviceId):
if userId == self.session.myUser.userId {
rootCoordinator = self.createSelfVerificationCoordinator(otherDeviceId: deviceId)
} else {
rootCoordinator = self.createDataLoadingScreenCoordinator(otherUserId: userId, otherDeviceId: deviceId)
}
case .incomingRequest(let incomingKeyVerificationRequest):
rootCoordinator = self.createDataLoadingScreenCoordinator(with: incomingKeyVerificationRequest)
case .incomingSASTransaction(let incomingSASTransaction):
rootCoordinator = self.createDataLoadingScreenCoordinator(otherUserId: incomingSASTransaction.otherUserId, otherDeviceId: incomingSASTransaction.otherDeviceId)
case .completeSecurity(let isNewSignIn):
let coordinator = self.createCompleteSecurityCoordinator(isNewSignIn: isNewSignIn)
self.completeSecurityCoordinator = coordinator
rootCoordinator = coordinator
}
rootCoordinator.start()
self.add(childCoordinator: rootCoordinator)
if self.navigationRouter.modules.isEmpty == false {
self.navigationRouter.push(rootCoordinator, animated: true, popCompletion: { [weak self] in
self?.remove(childCoordinator: rootCoordinator)
})
} else {
self.navigationRouter.setRootModule(rootCoordinator) { [weak self] in
self?.remove(childCoordinator: rootCoordinator)
}
}
}
func toPresentable() -> UIViewController {
return self.navigationRouter.toPresentable()
}
// MARK: - Private methods
private func didComplete() {
self.delegate?.keyVerificationCoordinatorDidComplete(self, otherUserId: self.otherUserId, otherDeviceId: self.otherDeviceId ?? "")
}
private func didCancel() {
// In the case of the complete security flow, come back to the root screen if any child flow
// like device verification has been cancelled
if self.completeSecurityCoordinator != nil && childCoordinators.count > 1 {
NSLog("[KeyVerificationCoordinator] didCancel: popToRootModule")
self.navigationRouter.popToRootModule(animated: true)
return
}
self.delegate?.keyVerificationCoordinatorDidCancel(self)
}
private func createCompleteSecurityCoordinator(isNewSignIn: Bool) -> KeyVerificationSelfVerifyWaitCoordinatorType {
let coordinator = KeyVerificationSelfVerifyWaitCoordinator(session: self.session, isNewSignIn: isNewSignIn)
coordinator.delegate = self
coordinator.start()
return coordinator
}
private func showSecretsRecovery(with recoveryMode: SecretsRecoveryMode) {
let coordinator = SecretsRecoveryCoordinator(session: self.session, recoveryMode: recoveryMode, recoveryGoal: .verifyDevice, navigationRouter: self.navigationRouter)
coordinator.delegate = self
coordinator.start()
self.add(childCoordinator: coordinator)
}
private func createSelfVerificationCoordinator(otherDeviceId: String) -> KeyVerificationSelfVerifyStartCoordinator {
let coordinator = KeyVerificationSelfVerifyStartCoordinator(session: self.session, otherDeviceId: otherDeviceId)
coordinator.delegate = self
coordinator.start()
return coordinator
}
private func createDataLoadingScreenCoordinator(otherUserId: String, otherDeviceId: String) -> KeyVerificationDataLoadingCoordinator {
let coordinator = KeyVerificationDataLoadingCoordinator(session: self.session, verificationKind: self.verificationKind, otherUserId: otherUserId, otherDeviceId: otherDeviceId)
coordinator.delegate = self
coordinator.start()
return coordinator
}
private func createDataLoadingScreenCoordinator(with keyVerificationRequest: MXKeyVerificationRequest) -> KeyVerificationDataLoadingCoordinator {
let coordinator = KeyVerificationDataLoadingCoordinator(session: self.session, verificationKind: self.verificationKind, incomingKeyVerificationRequest: keyVerificationRequest)
coordinator.delegate = self
coordinator.start()
return coordinator
}
private func createUserVerificationStartCoordinator(with roomMember: MXRoomMember) -> UserVerificationStartCoordinator {
let coordinator = UserVerificationStartCoordinator(session: self.session, roomMember: roomMember)
coordinator.delegate = self
coordinator.start()
return coordinator
}
private func showStart(otherUser: MXUser, otherDevice: MXDeviceInfo) {
let coordinator = DeviceVerificationStartCoordinator(session: self.session, otherUser: otherUser, otherDevice: otherDevice)
coordinator.delegate = self
coordinator.start()
self.add(childCoordinator: coordinator)
self.navigationRouter.setRootModule(coordinator) { [weak self] in
self?.remove(childCoordinator: coordinator)
}
}
private func showIncoming(otherUser: MXUser, transaction: MXIncomingSASTransaction) {
let coordinator = DeviceVerificationIncomingCoordinator(session: self.session, otherUser: otherUser, transaction: transaction)
coordinator.delegate = self
coordinator.start()
self.add(childCoordinator: coordinator)
self.navigationRouter.setRootModule(coordinator) { [weak self] in
self?.remove(childCoordinator: coordinator)
}
}
private func showVerifyBySAS(transaction: MXSASTransaction, animated: Bool) {
let coordinator = KeyVerificationVerifyBySASCoordinator(session: self.session, transaction: transaction, verificationKind: self.verificationKind)
coordinator.delegate = self
coordinator.start()
self.add(childCoordinator: coordinator)
self.navigationRouter.push(coordinator, animated: animated) { [weak self] in
self?.remove(childCoordinator: coordinator)
}
}
private func showVerifyByScanning(keyVerificationRequest: MXKeyVerificationRequest, animated: Bool) {
let coordinator = KeyVerificationVerifyByScanningCoordinator(session: self.session, verificationKind: self.verificationKind, keyVerificationRequest: keyVerificationRequest)
coordinator.delegate = self
coordinator.start()
self.add(childCoordinator: coordinator)
self.navigationRouter.push(coordinator, animated: animated) { [weak self] in
self?.remove(childCoordinator: coordinator)
}
}
private func showScanConfirmation(for transaction: MXQRCodeTransaction, codeScanning: KeyVerificationScanning, animated: Bool) {
let coordinator = KeyVerificationScanConfirmationCoordinator(session: self.session, transaction: transaction, codeScanning: codeScanning, verificationKind: self.verificationKind)
coordinator.delegate = self
coordinator.start()
self.add(childCoordinator: coordinator)
self.navigationRouter.push(coordinator, animated: animated) { [weak self] in
self?.remove(childCoordinator: coordinator)
}
}
private func showVerified(animated: Bool) {
let viewController = KeyVerificationVerifiedViewController.instantiate(with: self.verificationKind)
viewController.delegate = self
self.navigationRouter.setRootModule(viewController)
}
}
// MARK: - KeyVerificationDataLoadingCoordinatorDelegate
extension KeyVerificationCoordinator: KeyVerificationDataLoadingCoordinatorDelegate {
func keyVerificationDataLoadingCoordinator(_ coordinator: KeyVerificationDataLoadingCoordinatorType, didAcceptKeyVerificationRequest keyVerificationRequest: MXKeyVerificationRequest) {
self.showVerifyByScanning(keyVerificationRequest: keyVerificationRequest, animated: true)
}
func keyVerificationDataLoadingCoordinator(_ coordinator: KeyVerificationDataLoadingCoordinatorType, didLoadUser user: MXUser, device: MXDeviceInfo) {
if case .incomingSASTransaction(let incomingTransaction) = self.verificationFlow {
self.showIncoming(otherUser: user, transaction: incomingTransaction)
} else {
self.showStart(otherUser: user, otherDevice: device)
}
}
func keyVerificationDataLoadingCoordinator(_ coordinator: KeyVerificationDataLoadingCoordinatorType, didAcceptKeyVerificationRequestWithTransaction transaction: MXKeyVerificationTransaction) {
if let sasTransaction = transaction as? MXSASTransaction {
self.showVerifyBySAS(transaction: sasTransaction, animated: true)
} else {
NSLog("[KeyVerificationCoordinator] Transaction \(transaction) is not supported")
self.didCancel()
}
}
func keyVerificationDataLoadingCoordinatorDidCancel(_ coordinator: KeyVerificationDataLoadingCoordinatorType) {
self.didCancel()
}
}
// MARK: - DeviceVerificationStartCoordinatorDelegate
extension KeyVerificationCoordinator: DeviceVerificationStartCoordinatorDelegate {
func deviceVerificationStartCoordinator(_ coordinator: DeviceVerificationStartCoordinatorType, didCompleteWithOutgoingTransaction transaction: MXSASTransaction) {
self.showVerifyBySAS(transaction: transaction, animated: true)
}
func deviceVerificationStartCoordinator(_ coordinator: DeviceVerificationStartCoordinatorType, didTransactionCancelled transaction: MXSASTransaction) {
self.didCancel()
}
func deviceVerificationStartCoordinatorDidCancel(_ coordinator: DeviceVerificationStartCoordinatorType) {
self.didCancel()
}
}
// MARK: - DeviceVerificationIncomingCoordinatorDelegate
extension KeyVerificationCoordinator: DeviceVerificationIncomingCoordinatorDelegate {
func deviceVerificationIncomingCoordinator(_ coordinator: DeviceVerificationIncomingCoordinatorType, didAcceptTransaction transaction: MXSASTransaction) {
self.showVerifyBySAS(transaction: transaction, animated: true)
}
func deviceVerificationIncomingCoordinatorDidCancel(_ coordinator: DeviceVerificationIncomingCoordinatorType) {
self.didCancel()
}
}
// MARK: - KeyVerificationVerifyBySASCoordinatorDelegate
extension KeyVerificationCoordinator: KeyVerificationVerifyBySASCoordinatorDelegate {
func keyVerificationVerifyBySASCoordinatorDidComplete(_ coordinator: KeyVerificationVerifyBySASCoordinatorType) {
self.showVerified(animated: true)
}
func keyVerificationVerifyBySASCoordinatorDidCancel(_ coordinator: KeyVerificationVerifyBySASCoordinatorType) {
self.didCancel()
}
}
// MARK: - KeyVerificationVerifiedViewControllerDelegate
extension KeyVerificationCoordinator: KeyVerificationVerifiedViewControllerDelegate {
func keyVerificationVerifiedViewControllerDidTapSetupAction(_ viewController: KeyVerificationVerifiedViewController) {
self.didComplete()
}
func keyVerificationVerifiedViewControllerDidCancel(_ viewController: KeyVerificationVerifiedViewController) {
self.didCancel()
}
}
// MARK: - UserVerificationStartCoordinatorDelegate
extension KeyVerificationCoordinator: UserVerificationStartCoordinatorDelegate {
func userVerificationStartCoordinator(_ coordinator: UserVerificationStartCoordinatorType, otherDidAcceptRequest request: MXKeyVerificationRequest) {
self.showVerifyByScanning(keyVerificationRequest: request, animated: true)
}
func userVerificationStartCoordinator(_ coordinator: UserVerificationStartCoordinatorType, didCompleteWithOutgoingTransaction transaction: MXSASTransaction) {
self.showVerifyBySAS(transaction: transaction, animated: true)
}
func userVerificationStartCoordinator(_ coordinator: UserVerificationStartCoordinatorType, didTransactionCancelled transaction: MXSASTransaction) {
self.didCancel()
}
func userVerificationStartCoordinatorDidCancel(_ coordinator: UserVerificationStartCoordinatorType) {
self.didCancel()
}
}
// MARK: - KeyVerificationVerifyByScanningCoordinatorDelegate
extension KeyVerificationCoordinator: KeyVerificationVerifyByScanningCoordinatorDelegate {
func keyVerificationVerifyByScanningCoordinatorDidCancel(_ coordinator: KeyVerificationVerifyByScanningCoordinatorType) {
self.didCancel()
}
func keyVerificationVerifyByScanningCoordinator(_ coordinator: KeyVerificationVerifyByScanningCoordinatorType, didScanOtherQRCodeData qrCodeData: MXQRCodeData, withTransaction transaction: MXQRCodeTransaction) {
self.showScanConfirmation(for: transaction, codeScanning: .scannedOtherQRCode(qrCodeData), animated: true)
}
func keyVerificationVerifyByScanningCoordinator(_ coordinator: KeyVerificationVerifyByScanningCoordinatorType, qrCodeDidScannedByOtherWithTransaction transaction: MXQRCodeTransaction) {
self.showScanConfirmation(for: transaction, codeScanning: .myQRCodeScanned, animated: true)
}
func keyVerificationVerifyByScanningCoordinator(_ coordinator: KeyVerificationVerifyByScanningCoordinatorType, didCompleteWithSASTransaction transaction: MXSASTransaction) {
self.showVerifyBySAS(transaction: transaction, animated: true)
}
}
// MARK: - KeyVerificationSelfVerifyStartCoordinatorDelegate
extension KeyVerificationCoordinator: KeyVerificationSelfVerifyStartCoordinatorDelegate {
func keyVerificationSelfVerifyStartCoordinator(_ coordinator: KeyVerificationSelfVerifyStartCoordinatorType, otherDidAcceptRequest request: MXKeyVerificationRequest) {
self.showVerifyByScanning(keyVerificationRequest: request, animated: true)
}
func keyVerificationSelfVerifyStartCoordinatorDidCancel(_ coordinator: KeyVerificationSelfVerifyStartCoordinatorType) {
self.didCancel()
}
}
// MARK: - KeyVerificationSelfVerifyWaitCoordinatorDelegate
extension KeyVerificationCoordinator: KeyVerificationSelfVerifyWaitCoordinatorDelegate {
func keyVerificationSelfVerifyWaitCoordinator(_ coordinator: KeyVerificationSelfVerifyWaitCoordinatorType, didAcceptKeyVerificationRequest keyVerificationRequest: MXKeyVerificationRequest) {
self.showVerifyByScanning(keyVerificationRequest: keyVerificationRequest, animated: true)
}
func keyVerificationSelfVerifyWaitCoordinator(_ coordinator: KeyVerificationSelfVerifyWaitCoordinatorType, didAcceptIncomingSASTransaction incomingSASTransaction: MXIncomingSASTransaction) {
self.showVerifyBySAS(transaction: incomingSASTransaction, animated: true)
}
func keyVerificationSelfVerifyWaitCoordinatorDidCancel(_ coordinator: KeyVerificationSelfVerifyWaitCoordinatorType) {
self.didCancel()
}
func keyVerificationSelfVerifyWaitCoordinator(_ coordinator: KeyVerificationSelfVerifyWaitCoordinatorType, wantsToRecoverSecretsWith secretsRecoveryMode: SecretsRecoveryMode) {
self.showSecretsRecovery(with: secretsRecoveryMode)
}
}
// MARK: - KeyVerificationScanConfirmationCoordinatorDelegate
extension KeyVerificationCoordinator: KeyVerificationScanConfirmationCoordinatorDelegate {
func keyVerificationScanConfirmationCoordinatorDidComplete(_ coordinator: KeyVerificationScanConfirmationCoordinatorType) {
self.showVerified(animated: true)
}
func keyVerificationScanConfirmationCoordinatorDidCancel(_ coordinator: KeyVerificationScanConfirmationCoordinatorType) {
self.didCancel()
}
}
// MARK: - SecretsRecoveryCoordinatorDelegate
extension KeyVerificationCoordinator: SecretsRecoveryCoordinatorDelegate {
func secretsRecoveryCoordinatorDidRecover(_ coordinator: SecretsRecoveryCoordinatorType) {
self.remove(childCoordinator: coordinator)
self.showVerified(animated: true)
}
func secretsRecoveryCoordinatorDidCancel(_ coordinator: SecretsRecoveryCoordinatorType) {
self.remove(childCoordinator: coordinator)
self.didCancel()
}
}
|
//
// CPU.swift
// C-swifty4
//
// Created by Fabio Ritrovato on 30/12/2014.
// Copyright (c) 2014 orange in a day. All rights reserved.
//
import Foundation
internal struct CPUState: ComponentState {
var pc: UInt16 = 0
var isAtFetch = false
var a: UInt8 = 0
var x: UInt8 = 0
var y: UInt8 = 0
var sp: UInt8 = 0
var c: Bool = false
var z: Bool = false
var i: Bool = false
var d: Bool = false
var b: Bool = true
var v: Bool = false
var n: Bool = false
var portDirection: UInt8 = 0x2F
var port: UInt8 = 0x37
@available(*, deprecated) var irqTriggered = false //TODO: maybe we still need to keep track if the IRQ has been triggered?
var nmiTriggered = false //TODO: see below
var nmiLine = true
var currentOpcode: UInt16 = 0
var cycle = 0
var data: UInt8 = 0
var addressLow: UInt8 = 0
var addressHigh: UInt8 = 0
var pointer: UInt8 = 0
var pageBoundaryCrossed = false
mutating func update(dictionary: [String: AnyObject]) {
pc = UInt16(dictionary["pc"] as! UInt)
isAtFetch = dictionary["isAtFetch"] as! Bool
a = UInt8(dictionary["a"] as! UInt)
x = UInt8(dictionary["x"] as! UInt)
y = UInt8(dictionary["y"] as! UInt)
sp = UInt8(dictionary["sp"] as! UInt)
c = dictionary["c"] as! Bool
z = dictionary["z"] as! Bool
i = dictionary["i"] as! Bool
d = dictionary["d"] as! Bool
b = dictionary["b"] as! Bool
v = dictionary["v"] as! Bool
n = dictionary["n"] as! Bool
portDirection = UInt8(dictionary["portDirection"] as! UInt)
port = UInt8(dictionary["port"] as! UInt)
irqTriggered = dictionary["irqTriggered"] as! Bool
nmiTriggered = dictionary["nmiTriggered"] as! Bool
currentOpcode = UInt16(dictionary["currentOpcode"] as! UInt)
cycle = dictionary["cycle"] as! Int
data = UInt8(dictionary["data"] as! UInt)
addressLow = UInt8(dictionary["addressLow"] as! UInt)
addressHigh = UInt8(dictionary["addressHigh"] as! UInt)
pointer = UInt8(dictionary["pointer"] as! UInt)
pageBoundaryCrossed = dictionary["pageBoundaryCrossed"] as! Bool
}
}
final internal class CPU: Component, IRQLineComponent {
var state = CPUState()
internal weak var irqLine: Line!
internal weak var memory: Memory!
internal var crashHandler: C64CrashHandler?
private var pcl: UInt8 {
set {
state.pc = (state.pc & 0xFF00) | UInt16(newValue)
}
get {
return UInt8(truncatingBitPattern: state.pc)
}
}
private var pch: UInt8 {
set {
state.pc = (state.pc & 0x00FF) | UInt16(newValue) << 8
}
get {
return UInt8(truncatingBitPattern: state.pc >> 8)
}
}
internal var port: UInt8 {
set {
state.port = newValue | ~state.portDirection
}
get {
return state.port
}
}
var portDirection: UInt8 {
set {
state.portDirection = newValue
}
get {
return state.portDirection
}
}
private var address: UInt16 {
get {
return UInt16(state.addressHigh) << 8 | UInt16(state.addressLow)
}
}
internal init(pc: UInt16) {
self.state.pc = pc
}
//MARK: LineComponent
func lineChanged(line: Line) {
}
//MARK: Running
internal func executeInstruction() {
if state.cycle++ == 0 {
fetch()
return
}
state.isAtFetch = false
switch state.currentOpcode {
// ADC
case 0x69:
adcImmediate()
case 0x65:
state.cycle == 2 ? zeroPage() : adcZeroPage()
case 0x75:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : adcZeroPage()
case 0x6D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : adcAbsolute()
case 0x7D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? adcPageBoundary() : adcAbsolute()
case 0x79:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? adcPageBoundary() : adcAbsolute()
case 0x61:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectX() :
state.cycle == 4 ? indirectIndex2() :
state.cycle == 5 ? indirectX2() : adcAbsolute()
case 0x71:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? adcPageBoundary() : adcAbsolute()
// ALR*
case 0x4B:
alrImmediate()
// ANC
case 0x0B, 0x2B:
ancImmediate()
// AND
case 0x29:
andImmediate()
case 0x25:
state.cycle == 2 ? zeroPage() : andZeroPage()
case 0x35:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : andZeroPage()
case 0x2D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : andAbsolute()
case 0x3D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? andPageBoundary() : andAbsolute()
case 0x39:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? andPageBoundary() : andAbsolute()
case 0x21:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectX() :
state.cycle == 4 ? indirectIndex2() :
state.cycle == 5 ? indirectX2() : andAbsolute()
case 0x31:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? andPageBoundary() : andAbsolute()
// ASL
case 0x0A:
aslAccumulator()
case 0x06:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPage2() :
state.cycle == 4 ? aslZeroPage() : zeroPageWriteUpdateNZ()
case 0x16:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() :
state.cycle == 4 ? zeroPage2() :
state.cycle == 5 ? aslZeroPage() : zeroPageWriteUpdateNZ()
case 0x0E:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? absolute3() :
state.cycle == 5 ? aslAbsolute() : absoluteWriteUpdateNZ()
case 0x1E:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? absoluteFixPage() :
state.cycle == 5 ? absolute3() :
state.cycle == 6 ? aslAbsolute() : absoluteWriteUpdateNZ()
// BCC
case 0x90:
state.cycle == 2 ? bccRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BCS
case 0xB0:
state.cycle == 2 ? bcsRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BEQ
case 0xF0:
state.cycle == 2 ? beqRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BIT
case 0x24:
state.cycle == 2 ? zeroPage() : bitZeroPage()
case 0x2C:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : bitAbsolute()
// BMI
case 0x30:
state.cycle == 2 ? bmiRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BNE
case 0xD0:
state.cycle == 2 ? bneRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BPL
case 0x10:
state.cycle == 2 ? bplRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BRK
case 0x00:
state.cycle == 2 ? immediate() :
state.cycle == 3 ? brkImplied() :
state.cycle == 4 ? brkImplied2() :
state.cycle == 5 ? brkImplied3() :
state.cycle == 6 ? brkImplied4() : brkImplied5()
// BVC
case 0x50:
state.cycle == 2 ? bvcRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BVS
case 0x70:
state.cycle == 2 ? bvsRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// CLC
case 0x18:
clcImplied()
// CLD
case 0xD8:
cldImplied()
// CLI
case 0x58:
cliImplied()
// CLV
case 0xB8:
clvImplied()
// CMP
case 0xC9:
cmpImmediate()
case 0xC5:
state.cycle == 2 ? zeroPage() : cmpZeroPage()
case 0xD5:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : cmpZeroPage()
case 0xCD:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : cmpAbsolute()
case 0xDD:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? cmpPageBoundary() : cmpAbsolute()
case 0xD9:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? cmpPageBoundary() : cmpAbsolute()
case 0xC1:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectX() :
state.cycle == 4 ? indirectIndex2() :
state.cycle == 5 ? indirectX2() : cmpAbsolute()
case 0xD1:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? cmpPageBoundary() : cmpAbsolute()
// CPX
case 0xE0:
cpxImmediate()
case 0xE4:
state.cycle == 2 ? zeroPage() : cpxZeroPage()
case 0xEC:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : cpxAbsolute()
// CPY
case 0xC0:
cpyImmediate()
case 0xC4:
state.cycle == 2 ? zeroPage() : cpyZeroPage()
case 0xCC:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : cpyAbsolute()
// DEC
case 0xC6:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPage2() :
state.cycle == 4 ? decZeroPage() : zeroPageWriteUpdateNZ()
case 0xD6:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() :
state.cycle == 4 ? zeroPage2() :
state.cycle == 5 ? decZeroPage() : zeroPageWriteUpdateNZ()
case 0xCE:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? absolute3() :
state.cycle == 5 ? decAbsolute() : absoluteWriteUpdateNZ()
case 0xDE:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? absoluteFixPage() :
state.cycle == 5 ? absolute3() :
state.cycle == 6 ? decAbsolute() : absoluteWriteUpdateNZ()
// DEX
case 0xCA:
dexImplied()
// DEY
case 0x88:
deyImplied()
// EOR
case 0x49:
eorImmediate()
case 0x45:
state.cycle == 2 ? zeroPage() : eorZeroPage()
case 0x55:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : eorZeroPage()
case 0x4D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : eorAbsolute()
case 0x5D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? eorPageBoundary() : eorAbsolute()
case 0x59:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? eorPageBoundary() : eorAbsolute()
case 0x41:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectX() :
state.cycle == 4 ? indirectIndex2() :
state.cycle == 5 ? indirectX2() : eorAbsolute()
case 0x51:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? eorPageBoundary() : eorAbsolute()
// INC
case 0xE6:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPage2() :
state.cycle == 4 ? incZeroPage() : zeroPageWriteUpdateNZ()
case 0xF6:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() :
state.cycle == 4 ? zeroPage2() :
state.cycle == 5 ? incZeroPage() : zeroPageWriteUpdateNZ()
case 0xEE:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? absolute3() :
state.cycle == 5 ? incAbsolute() : absoluteWriteUpdateNZ()
case 0xFE:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? absoluteFixPage() :
state.cycle == 5 ? absolute3() :
state.cycle == 6 ? incAbsolute() : absoluteWriteUpdateNZ()
// INX
case 0xE8:
inxImplied()
// INY
case 0xC8:
inyImplied()
// JMP
case 0x4C:
state.cycle == 2 ? absolute() : jmpAbsolute()
case 0x6C:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? indirect() : jmpIndirect()
// JSR
case 0x20:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? {}() :
state.cycle == 4 ? pushPch() :
state.cycle == 5 ? pushPcl() : jsrAbsolute()
// LAX
case 0xAF:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : laxAbsolute()
// LDA
case 0xA9:
ldaImmediate()
case 0xA5:
state.cycle == 2 ? zeroPage() : ldaZeroPage()
case 0xB5:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : ldaZeroPage()
case 0xAD:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : ldaAbsolute()
case 0xBD:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? ldaPageBoundary() : ldaAbsolute()
case 0xB9:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? ldaPageBoundary() : ldaAbsolute()
case 0xA1:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectX() :
state.cycle == 4 ? indirectIndex2() :
state.cycle == 5 ? indirectX2() : ldaAbsolute()
case 0xB1:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? ldaPageBoundary() : ldaAbsolute()
// LDX
case 0xA2:
ldxImmediate()
case 0xA6:
state.cycle == 2 ? zeroPage() : ldxZeroPage()
case 0xB6:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageY() : ldxZeroPage()
case 0xAE:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : ldxAbsolute()
case 0xBE:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? ldxPageBoundary() : ldxAbsolute()
// LDY
case 0xA0:
ldyImmediate()
case 0xA4:
state.cycle == 2 ? zeroPage() : ldyZeroPage()
case 0xB4:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : ldyZeroPage()
case 0xAC:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : ldyAbsolute()
case 0xBC:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? ldyPageBoundary() : ldyAbsolute()
// LSR
case 0x4A:
lsrAccumulator()
case 0x46:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPage2() :
state.cycle == 4 ? lsrZeroPage() : zeroPageWriteUpdateNZ()
case 0x56:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() :
state.cycle == 4 ? zeroPage2() :
state.cycle == 5 ? lsrZeroPage() : zeroPageWriteUpdateNZ()
// NOP
case 0xEA, 0x5A, 0x7A:
nop()
case 0x44:
state.cycle == 2 ? zeroPage() : nopZeroPage()
case 0x14:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : nopZeroPage()
case 0x82, 0xE2:
nopImmediate()
// ORA
case 0x09:
oraImmediate()
case 0x05:
state.cycle == 2 ? zeroPage() : oraZeroPage()
case 0x0D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : oraAbsolute()
case 0x1D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? oraPageBoundary() : oraAbsolute()
// PHA
case 0x48:
state.cycle == 2 ? implied() : phaImplied()
// PHP
case 0x08:
state.cycle == 2 ? implied() : phpImplied()
// PLA
case 0x68:
state.cycle == 2 ? implied() :
state.cycle == 3 ? implied2() : plaImplied()
// PLP
case 0x28:
state.cycle == 2 ? implied() :
state.cycle == 3 ? implied2() : plpImplied()
// ROL
case 0x2A:
rolAccumulator()
case 0x26:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPage2() :
state.cycle == 4 ? rolZeroPage() : zeroPageWriteUpdateNZ()
case 0x2E:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? absolute3() :
state.cycle == 5 ? rolAbsolute() : absoluteWriteUpdateNZ()
// ROR
case 0x6A:
rorAccumulator()
case 0x66:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPage2() :
state.cycle == 4 ? rorZeroPage() : zeroPageWriteUpdateNZ()
case 0x76:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() :
state.cycle == 4 ? zeroPage2() :
state.cycle == 5 ? rorZeroPage() : zeroPageWriteUpdateNZ()
case 0x6E:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? absolute3() :
state.cycle == 5 ? rorAbsolute() : absoluteWriteUpdateNZ()
// RTI
case 0x40:
state.cycle == 2 ? immediate() :
state.cycle == 3 ? implied2() :
state.cycle == 4 ? rtiImplied() :
state.cycle == 5 ? rtiImplied2() : rtiImplied3()
// RTS
case 0x60:
state.cycle == 2 ? immediate() :
state.cycle == 3 ? implied2() :
state.cycle == 4 ? rtsImplied() :
state.cycle == 5 ? rtsImplied2() : rtsImplied3()
// SBC
case 0xE9:
sbcImmediate()
case 0xE5:
state.cycle == 2 ? zeroPage() : sbcZeroPage()
case 0xF5:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : sbcZeroPage()
case 0xED:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? sbcAbsolute() : sbcAbsolute2()
case 0xFD:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? sbcAbsolute() : sbcAbsolute2()
case 0xF9:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? sbcAbsolute() : sbcAbsolute2()
case 0xF1:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? sbcAbsolute() : sbcAbsolute2()
// SEC
case 0x38:
secImplied()
case 0xF8:
sedImplied()
// SEI
case 0x78:
seiImplied()
// STA
case 0x85:
state.cycle == 2 ? zeroPage() : staZeroPage()
case 0x95:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : staZeroPage()
case 0x8D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : staAbsolute()
case 0x9D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? absoluteFixPage() : staAbsolute()
case 0x99:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? absoluteFixPage() : staAbsolute()
case 0x81:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectX() :
state.cycle == 4 ? indirectIndex2() :
state.cycle == 5 ? indirectX2() : staAbsolute()
case 0x91:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? absoluteFixPage() : staAbsolute()
// STX
case 0x86:
state.cycle == 2 ? zeroPage() : stxZeroPage()
case 0x96:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageY() : styZeroPage()
case 0x8E:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : stxAbsolute()
// STY
case 0x84:
state.cycle == 2 ? zeroPage() : styZeroPage()
case 0x94:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : styZeroPage()
case 0x8C:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : styAbsolute()
// TAX
case 0xAA:
taxImplied()
// TAY
case 0xA8:
tayImplied()
// TSX
case 0xBA:
tsxImplied()
// TXA
case 0x8A:
txaImplied()
// TXS
case 0x9a:
txsImplied()
// TYA
case 0x98:
tyaImplied()
// NMI
case 0xFFFE:
state.cycle == 2 ? implied() :
state.cycle == 3 ? pushPch() :
state.cycle == 4 ? pushPcl() :
state.cycle == 5 ? interrupt() :
state.cycle == 6 ? nmi() : nmi2()
// IRQ
case 0xFFFF:
state.cycle == 2 ? implied() :
state.cycle == 3 ? pushPch() :
state.cycle == 4 ? pushPcl() :
state.cycle == 5 ? interrupt() :
state.cycle == 6 ? irq() : irq2()
default:
let opcodeString = String(state.currentOpcode, radix: 16, uppercase: true)
let pcString = String((state.pc &- UInt16(1)), radix: 16, uppercase: true)
crashHandler?("Unknown opcode: " + opcodeString + " pc: " + pcString)
}
}
@available(*, deprecated) internal func setIRQLine() {
state.irqTriggered = true
}
//TODO: NMI is connected to multiple sources so it should be treated like an actual line (like IEC)
internal func setNMILine(line: Bool) {
if !line && state.nmiLine {
state.nmiTriggered = true
}
state.nmiLine = line
}
internal func setOverflow() {
state.v = true
}
internal func debugInfo() -> [String: String] {
let description: String = {
switch state.currentOpcode {
case 0x69: return String(format: "ADC #%02x", self.memory.readByte(state.pc))
case 0x65: return String(format: "ADC %02x", self.memory.readByte(state.pc))
case 0x75: return String(format: "ADC %02x,X", self.memory.readByte(state.pc))
case 0x6D: return String(format: "ADC %04x", self.memory.readWord(state.pc))
case 0x7D: return String(format: "ADC %04x,X", self.memory.readWord(state.pc))
case 0x79: return String(format: "ADC %04x,Y", self.memory.readWord(state.pc))
case 0x61: return String(format: "ADC (%02x,X)", self.memory.readByte(state.pc))
case 0x71: return String(format: "ADC (%02x),Y", self.memory.readByte(state.pc))
case 0x4B: return String(format: "ALR* #%02x", self.memory.readByte(state.pc))
case 0x0B: return String(format: "ANC* #%02x", self.memory.readByte(state.pc))
case 0x2B: return String(format: "ANC* #%02x", self.memory.readByte(state.pc))
case 0x29: return String(format: "AND #%02x", self.memory.readByte(state.pc))
case 0x25: return String(format: "AND %02x", self.memory.readByte(state.pc))
case 0x35: return String(format: "AND %02x,X", self.memory.readByte(state.pc))
case 0x2D: return String(format: "AND %04x", self.memory.readWord(state.pc))
case 0x3D: return String(format: "AND %04x,X", self.memory.readWord(state.pc))
case 0x39: return String(format: "AND %04x,Y", self.memory.readWord(state.pc))
case 0x21: return String(format: "AND (%02x,X)", self.memory.readByte(state.pc))
case 0x31: return String(format: "AND (%02x),Y", self.memory.readByte(state.pc))
case 0x0A: return "ASL"
case 0x06: return String(format: "ASL %02x", self.memory.readByte(state.pc))
case 0x16: return String(format: "ASL %02x,X", self.memory.readByte(state.pc))
case 0x0E: return String(format: "ASL %04x", self.memory.readWord(state.pc))
case 0x1E: return String(format: "ASL %04x,X", self.memory.readWord(state.pc))
case 0x90: return String(format: "BCC %02x", self.memory.readByte(state.pc))
case 0xB0: return String(format: "BCS %02x", self.memory.readByte(state.pc))
case 0xF0: return String(format: "BEQ %02x", self.memory.readByte(state.pc))
case 0x24: return String(format: "BIT %02x", self.memory.readByte(state.pc))
case 0x2C: return String(format: "BIT %04x", self.memory.readWord(state.pc))
case 0x30: return String(format: "BMI %02x", self.memory.readByte(state.pc))
case 0xD0: return String(format: "BNE %02x", self.memory.readByte(state.pc))
case 0x10: return String(format: "BPL %02x", self.memory.readByte(state.pc))
case 0x00: return "BRK"
case 0x50: return String(format: "BVC %02x", self.memory.readByte(state.pc))
case 0x70: return String(format: "BVS %02x", self.memory.readByte(state.pc))
case 0x18: return "CLC"
case 0xD8: return "CLD"
case 0x58: return "CLI"
case 0xB8: return "CLV"
case 0xC9: return String(format: "CMP #%02x", self.memory.readByte(state.pc))
case 0xC5: return String(format: "CMP %02x", self.memory.readByte(state.pc))
case 0xD5: return String(format: "CMP %02x,X", self.memory.readByte(state.pc))
case 0xCD: return String(format: "CMP %04x", self.memory.readWord(state.pc))
case 0xDD: return String(format: "CMP %04x,X", self.memory.readWord(state.pc))
case 0xD9: return String(format: "CMP %04x,Y", self.memory.readWord(state.pc))
case 0xC1: return String(format: "CMP (%02x,X)", self.memory.readByte(state.pc))
case 0xD1: return String(format: "CMP (%02x),Y", self.memory.readByte(state.pc))
case 0xE0: return String(format: "CPX #%02x", self.memory.readByte(state.pc))
case 0xE4: return String(format: "CPX %02x", self.memory.readByte(state.pc))
case 0xEC: return String(format: "CPX %04x", self.memory.readWord(state.pc))
case 0xC0: return String(format: "CPY #%02x", self.memory.readByte(state.pc))
case 0xC4: return String(format: "CPY %02x", self.memory.readByte(state.pc))
case 0xCC: return String(format: "CPY %04x", self.memory.readWord(state.pc))
case 0xC6: return String(format: "DEC %02x", self.memory.readByte(state.pc))
case 0xD6: return String(format: "DEC %02x,X", self.memory.readByte(state.pc))
case 0xCE: return String(format: "DEC %04x", self.memory.readWord(state.pc))
case 0xDE: return String(format: "DEC %04x,X", self.memory.readWord(state.pc))
case 0xCA: return "DEX"
case 0x88: return "DEY"
case 0x49: return String(format: "EOR #%02x", self.memory.readByte(state.pc))
case 0x45: return String(format: "EOR %02x", self.memory.readByte(state.pc))
case 0x55: return String(format: "EOR %02x,X", self.memory.readByte(state.pc))
case 0x4D: return String(format: "EOR %04x", self.memory.readWord(state.pc))
case 0x5D: return String(format: "EOR %04x,X", self.memory.readWord(state.pc))
case 0x59: return String(format: "EOR %04x,Y", self.memory.readWord(state.pc))
case 0x41: return String(format: "EOR (%02x,Y)", self.memory.readByte(state.pc))
case 0x51: return String(format: "EOR (%02x),Y", self.memory.readByte(state.pc))
case 0xE6: return String(format: "INC %02x", self.memory.readByte(state.pc))
case 0xF6: return String(format: "INC %02x,X", self.memory.readByte(state.pc))
case 0xEE: return String(format: "INC %04x", self.memory.readWord(state.pc))
case 0xFE: return String(format: "INC %04x,X", self.memory.readWord(state.pc))
case 0xE8: return "INX"
case 0xC8: return "INY"
case 0x4C: return String(format: "JMP %04x", self.memory.readWord(state.pc))
case 0x6C: return String(format: "JMP (%04x)", self.memory.readWord(state.pc))
case 0x20: return String(format: "JSR %04x", self.memory.readWord(state.pc))
case 0xAF: return String(format: "LAX* %04x", self.memory.readWord(state.pc))
case 0xA9: return String(format: "LDA #%02x", self.memory.readByte(state.pc))
case 0xA5: return String(format: "LDA %02x", self.memory.readByte(state.pc))
case 0xB5: return String(format: "LDA %02x,X", self.memory.readByte(state.pc))
case 0xAD: return String(format: "LDA %04x", self.memory.readWord(state.pc))
case 0xBD: return String(format: "LDA %04x,X", self.memory.readWord(state.pc))
case 0xB9: return String(format: "LDA %04x,Y", self.memory.readWord(state.pc))
case 0xA1: return String(format: "LDA (%02x,X)", self.memory.readByte(state.pc))
case 0xB1: return String(format: "LDA (%02x),Y", self.memory.readByte(state.pc))
case 0xA2: return String(format: "LDX #%02x", self.memory.readByte(state.pc))
case 0xA6: return String(format: "LDX %02x", self.memory.readByte(state.pc))
case 0xB6: return String(format: "LDX %02x,Y", self.memory.readByte(state.pc))
case 0xAE: return String(format: "LDX %04x", self.memory.readWord(state.pc))
case 0xBE: return String(format: "LDX %04x,Y", self.memory.readWord(state.pc))
case 0xA0: return String(format: "LDY #%02x", self.memory.readByte(state.pc))
case 0xA4: return String(format: "LDY %02x", self.memory.readByte(state.pc))
case 0xB4: return String(format: "LDY %02x,X", self.memory.readByte(state.pc))
case 0xAC: return String(format: "LDY %04x", self.memory.readWord(state.pc))
case 0xBC: return String(format: "LDY %04x,X", self.memory.readWord(state.pc))
case 0x4A: return "LSR"
case 0x46: return String(format: "LSR %02x", self.memory.readByte(state.pc))
case 0x56: return String(format: "LSR %02x,X", self.memory.readByte(state.pc))
case 0xEA: return "NOP"
case 0x5A: return "NOP*"
case 0x7A: return "NOP*"
case 0x44: return String(format: "NOP* %02x", self.memory.readByte(state.pc))
case 0x14: return String(format: "NOP* %02x,X", self.memory.readByte(state.pc))
case 0x82: return String(format: "NOP* #%02x", self.memory.readByte(state.pc))
case 0xE2: return String(format: "NOP* #%02x", self.memory.readByte(state.pc))
case 0x09: return String(format: "ORA #%02x", self.memory.readByte(state.pc))
case 0x05: return String(format: "ORA %02x", self.memory.readByte(state.pc))
case 0x0D: return String(format: "ORA %04x", self.memory.readWord(state.pc))
case 0x3D: return String(format: "ORA %04x,X", self.memory.readWord(state.pc))
case 0x48: return "PHA"
case 0x08: return "PHP"
case 0x68: return "PLA"
case 0x28: return "PLP"
case 0x2A: return "ROL"
case 0x26: return String(format: "ROL %02x", self.memory.readByte(state.pc))
case 0x2E: return String(format: "ROL %04x", self.memory.readWord(state.pc))
case 0x6A: return "ROR"
case 0x66: return String(format: "ROR %02x", self.memory.readByte(state.pc))
case 0x76: return String(format: "ROR %02x,X", self.memory.readByte(state.pc))
case 0x6E: return String(format: "ROR %04x", self.memory.readWord(state.pc))
case 0x40: return "RTI"
case 0x60: return "RTS"
case 0xE9: return String(format: "SBC #%02x", self.memory.readByte(state.pc))
case 0xE5: return String(format: "SBC %02x", self.memory.readByte(state.pc))
case 0xF5: return String(format: "SBC %02x,X", self.memory.readByte(state.pc))
case 0xED: return String(format: "SBC %04x", self.memory.readWord(state.pc))
case 0xFD: return String(format: "SBC %04x,X", self.memory.readWord(state.pc))
case 0xF9: return String(format: "SBC %04x,Y", self.memory.readWord(state.pc))
case 0xF1: return String(format: "SBC (%02x),Y", self.memory.readByte(state.pc))
case 0x38: return "SEC"
case 0xF8: return "SED"
case 0x78: return "SEI"
case 0x85: return String(format: "STA %02x", self.memory.readByte(state.pc))
case 0x95: return String(format: "STA %02x,X", self.memory.readByte(state.pc))
case 0x8D: return String(format: "STA %04x", self.memory.readWord(state.pc))
case 0x9D: return String(format: "STA %04x,X", self.memory.readWord(state.pc))
case 0x99: return String(format: "STA %04x,Y", self.memory.readWord(state.pc))
case 0x81: return String(format: "STA (%02x,X)", self.memory.readByte(state.pc))
case 0x91: return String(format: "STA (%02x),Y", self.memory.readByte(state.pc))
case 0x86: return String(format: "STX %02x", self.memory.readByte(state.pc))
case 0x96: return String(format: "STX %02x,Y", self.memory.readByte(state.pc))
case 0x8E: return String(format: "STX %04x", self.memory.readWord(state.pc))
case 0x84: return String(format: "STY %02x", self.memory.readByte(state.pc))
case 0x94: return String(format: "STY %02x,X", self.memory.readByte(state.pc))
case 0x8C: return String(format: "STY %04x", self.memory.readWord(state.pc))
case 0xAA: return "TAX"
case 0xA8: return "TAY"
case 0xBA: return "TSX"
case 0x8A: return "TXA"
case 0x9a: return "TXS"
case 0x98: return "TYA"
default: return String(format: "Unknown opcode: %02x", state.currentOpcode)
}
}()
return ["pc": String(format: "%04x", state.pc &- UInt16(1)),
"a": String(format: "%02x", state.a),
"x": String(format: "%02x", state.x),
"y": String(format: "%02x", state.y),
"sp": String(format: "%02x", state.sp),
"sr.n": state.n ? "✓" : " ",
"sr.v": state.v ? "✓" : " ",
"sr.b": state.b ? "✓" : " ",
"sr.d": state.d ? "✓" : " ",
"sr.i": state.i ? "✓" : " ",
"sr.z": state.z ? "✓" : " ",
"sr.c": state.c ? "✓" : " ",
"description": description
]
}
//MARK: Helpers
private func updateNFlag(value: UInt8) {
state.n = (value & 0x80 != 0)
}
private func updateZFlag(value: UInt8) {
state.z = (value == 0)
}
private func loadA(value: UInt8) {
state.a = value
state.z = (value == 0)
state.n = (value & 0x80 != 0)
}
private func loadX(value: UInt8) {
state.x = value
state.z = (value == 0)
state.n = (value & 0x80 != 0)
}
private func loadY(value: UInt8) {
state.y = value
state.z = (value == 0)
state.n = (value & 0x80 != 0)
}
private func fetch() {
if state.nmiTriggered {
state.nmiTriggered = false
state.currentOpcode = 0xFFFE
return
}
//IRQ is level sensitive, so it's always trigger as long as the line is pulled down
if !irqLine.state && !state.i {
state.currentOpcode = 0xFFFF
return
}
if state.irqTriggered && !state.i {
state.irqTriggered = false
state.currentOpcode = 0xFFFF
return
}
state.isAtFetch = true
state.currentOpcode = UInt16(memory.readByte(state.pc))
state.pc = state.pc &+ UInt16(1)
}
private func pushPch() {
memory.writeByte(0x100 &+ state.sp, byte: pch)
state.sp = state.sp &- 1
}
private func pushPcl() {
memory.writeByte(0x100 &+ state.sp, byte: pcl)
state.sp = state.sp &- 1
}
//MARK: Interrupts
private func interrupt() {
let p = UInt8((state.c ? 0x01 : 0) |
(state.z ? 0x02 : 0) |
(state.i ? 0x04 : 0) |
(state.d ? 0x08 : 0) |
// (b ? 0x10 : 0) | b is 0 on IRQ
0x20 |
(state.v ? 0x40 : 0) |
(state.n ? 0x80 : 0))
memory.writeByte(0x100 &+ state.sp, byte: p)
state.sp = state.sp &- 1
state.i = true
}
private func irq() {
state.data = memory.readByte(0xFFFE)
}
private func irq2() {
pcl = state.data
pch = memory.readByte(0xFFFF)
state.cycle = 0
}
private func nmi() {
state.data = memory.readByte(0xFFFA)
}
private func nmi2() {
pcl = state.data
pch = memory.readByte(0xFFFB)
state.cycle = 0
}
//MARK: Opcodes
//MARK: Addressing
private func zeroPage() {
state.addressLow = memory.readByte(state.pc++)
}
private func zeroPage2() {
state.data = memory.readByte(UInt16(state.addressLow))
}
private func zeroPageWriteUpdateNZ() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.z = (state.data == 0)
state.n = (state.data & 0x80 != 0)
state.cycle = 0
}
private func zeroPageX() {
state.data = memory.readByte(UInt16(state.addressLow))
state.addressLow = state.addressLow &+ state.x
}
private func zeroPageY() {
state.data = memory.readByte(UInt16(state.addressLow))
state.addressLow = state.addressLow &+ state.y
}
private func absolute() {
state.addressLow = memory.readByte(state.pc++)
}
private func absolute2() {
state.addressHigh = memory.readByte(state.pc++)
}
private func absolute3() {
state.data = memory.readByte(address)
}
private func absoluteWriteUpdateNZ() {
memory.writeByte(address, byte: state.data)
state.z = (state.data == 0)
state.n = (state.data & 0x80 != 0)
state.cycle = 0
}
private func absoluteX() {
state.addressHigh = memory.readByte(state.pc++)
state.pageBoundaryCrossed = (UInt16(state.addressLow) &+ state.x >= 0x100)
state.addressLow = state.addressLow &+ state.x
}
private func absoluteY() {
state.addressHigh = memory.readByte(state.pc++)
state.pageBoundaryCrossed = (UInt16(state.addressLow) &+ state.y >= 0x100)
state.addressLow = state.addressLow &+ state.y
}
private func absoluteFixPage() {
memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
}
}
private func indirect() {
state.data = memory.readByte(address)
}
private func indirectIndex() {
state.pointer = memory.readByte(state.pc++)
}
private func indirectIndex2() {
state.addressLow = memory.readByte(UInt16(state.pointer))
state.pointer = state.pointer &+ 1
}
private func indirectX() {
memory.readByte(UInt16(state.pointer))
state.pointer = state.pointer &+ state.x
}
private func indirectX2() {
state.addressHigh = memory.readByte(UInt16(state.pointer))
state.pointer = state.pointer &+ 1
}
private func indirectY() {
state.addressHigh = memory.readByte(UInt16(state.pointer))
state.pointer = state.pointer &+ 1
state.pageBoundaryCrossed = (UInt16(state.addressLow) &+ state.y >= 0x100)
state.addressLow = state.addressLow &+ state.y
}
private func implied() {
memory.readByte(state.pc)
}
private func implied2() {
state.sp = state.sp &+ 1
}
private func immediate() {
memory.readByte(state.pc)
state.pc = state.pc &+ UInt16(1)
}
//MARK: ADC
private func adc(value: UInt8) {
if state.d {
var lowNybble = (state.a & 0x0F) &+ (value & 0x0F) &+ (state.c ? 1 : 0)
var highNybble = (state.a >> 4) &+ (value >> 4)
if lowNybble > 9 {
lowNybble = lowNybble &+ 6
}
if lowNybble > 0x0F {
highNybble = highNybble &+ 1
}
state.z = ((state.a &+ value &+ (state.c ? 1 : 0)) & 0xFF == 0)
state.n = (highNybble & 0x08 != 0)
state.v = ((((highNybble << 4) ^ state.a) & 0x80) != 0 && ((state.a ^ value) & 0x80) == 0)
if highNybble > 9 {
highNybble = highNybble &+ 6
}
state.c = (highNybble > 0x0F)
state.a = (highNybble << 4) | (lowNybble & 0x0F)
} else {
let tempA = UInt16(state.a)
let sum = (tempA + UInt16(value) + (state.c ? 1 : 0))
state.c = (sum > 0xFF)
state.v = (((tempA ^ UInt16(value)) & 0x80) == 0 && ((tempA ^ sum) & 0x80) != 0)
loadA(UInt8(truncatingBitPattern: sum))
}
}
private func adcImmediate() {
state.data = memory.readByte(state.pc++)
adc(state.data)
state.cycle = 0
}
private func adcZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
adc(state.data)
state.cycle = 0
}
private func adcPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
adc(state.data)
state.cycle = 0
}
}
private func adcAbsolute() {
state.data = memory.readByte(address)
adc(state.data)
state.cycle = 0
}
//MARK: ALR*
private func alrImmediate() {
state.data = memory.readByte(state.pc++)
let a = state.a & state.data
state.c = ((a & 1) != 0)
loadA(a >> 1)
state.cycle = 0
}
//MARK: ANC*
private func ancImmediate() {
state.data = memory.readByte(state.pc++)
loadA(state.a & state.data)
state.c = state.n
state.cycle = 0
}
//MARK: AND
private func andImmediate() {
state.data = memory.readByte(state.pc++)
loadA(state.a & state.data)
state.cycle = 0
}
private func andZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
loadA(state.a & state.data)
state.cycle = 0
}
private func andPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadA(state.a & state.data)
state.cycle = 0
}
}
private func andAbsolute() {
state.data = memory.readByte(address)
loadA(state.a & state.data)
state.cycle = 0
}
//MARK: ASL
private func aslAccumulator() {
memory.readByte(state.pc)
state.c = ((state.a & 0x80) != 0)
loadA(state.a << 1)
state.cycle = 0
}
private func aslZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.c = ((state.data & 0x80) != 0)
state.data = state.data << 1
}
private func aslAbsolute() {
memory.writeByte(address, byte: state.data)
state.c = ((state.data & 0x80) != 0)
state.data = state.data << 1
}
//MARK: BCC
private func branch() {
memory.readByte(state.pc)
let oldPch = pch
state.pc = state.pc &+ Int8(bitPattern: state.data)
if pch == oldPch {
//TODO: delay IRQs
state.cycle = 0
}
}
private func branchOverflow() {
if state.data & 0x80 != 0 {
memory.readByte(state.pc &+ UInt16(0x100))
} else {
memory.readByte(state.pc &- UInt16(0x100))
}
state.cycle = 0
}
private func bccRelative() {
state.data = memory.readByte(state.pc++)
if state.c {
state.cycle = 0
}
}
//MARK: BCS
private func bcsRelative() {
state.data = memory.readByte(state.pc++)
if !state.c {
state.cycle = 0
}
}
//MARK: BEQ
private func beqRelative() {
state.data = memory.readByte(state.pc++)
if !state.z {
state.cycle = 0
}
}
//MARK: BIT
private func bitZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
state.n = ((state.data & 128) != 0)
state.v = ((state.data & 64) != 0)
state.z = ((state.data & state.a) == 0)
state.cycle = 0
}
private func bitAbsolute() {
state.data = memory.readByte(address)
state.n = ((state.data & 128) != 0)
state.v = ((state.data & 64) != 0)
state.z = ((state.data & state.a) == 0)
state.cycle = 0
}
//MARK: BMI
private func bmiRelative() {
state.data = memory.readByte(state.pc++)
if !state.n {
state.cycle = 0
}
}
//MARK: BNE
private func bneRelative() {
state.data = memory.readByte(state.pc++)
if state.z {
state.cycle = 0
}
}
//MARK: BPL
private func bplRelative() {
state.data = memory.readByte(state.pc++)
if state.n {
state.cycle = 0
}
}
//MARK: BRK
private func brkImplied() {
state.b = true
pushPch()
}
private func brkImplied2() {
pushPcl()
//TODO: handle NMI during BRK here
}
private func brkImplied3() {
let p = UInt8((state.c ? 0x01 : 0) |
(state.z ? 0x02 : 0) |
(state.i ? 0x04 : 0) |
(state.d ? 0x08 : 0) |
(state.b ? 0x10 : 0) |
0x20 |
(state.v ? 0x40 : 0) |
(state.n ? 0x80 : 0))
memory.writeByte(0x100 &+ state.sp, byte: p)
state.sp = state.sp &- 1
}
private func brkImplied4() {
state.data = memory.readByte(0xFFFE)
}
private func brkImplied5() {
pcl = state.data
pch = memory.readByte(0xFFFF)
state.i = true
state.cycle = 0
}
//MARK: BVC
private func bvcRelative() {
state.data = memory.readByte(state.pc++)
if state.v {
state.cycle = 0
}
}
//MARK: BVS
private func bvsRelative() {
state.data = memory.readByte(state.pc++)
if !state.v {
state.cycle = 0
}
}
//MARK: CLC
private func clcImplied() {
memory.readByte(state.pc)
state.c = false
state.cycle = 0
}
//MARK: CLD
private func cldImplied() {
memory.readByte(state.pc)
state.d = false
state.cycle = 0
}
//MARK: CLI
private func cliImplied() {
memory.readByte(state.pc)
state.i = false
state.cycle = 0
}
//MARK: CLV
private func clvImplied() {
memory.readByte(state.pc)
state.v = false
state.cycle = 0
}
//MARK: CMP
private func cmp(value1: UInt8, _ value2: UInt8) {
let diff = value1 &- value2
state.z = (diff == 0)
state.n = (diff & 0x80 != 0)
state.c = (value1 >= value2)
}
private func cmpImmediate() {
state.data = memory.readByte(state.pc++)
cmp(state.a, state.data)
state.cycle = 0
}
private func cmpZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
cmp(state.a, state.data)
state.cycle = 0
}
private func cmpAbsolute() {
state.data = memory.readByte(address)
cmp(state.a, state.data)
state.cycle = 0
}
private func cmpPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
cmp(state.a, state.data)
state.cycle = 0
}
}
//MARK: CPX
private func cpxImmediate() {
state.data = memory.readByte(state.pc++)
cmp(state.x, state.data)
state.cycle = 0
}
private func cpxZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
cmp(state.x, state.data)
state.cycle = 0
}
private func cpxAbsolute() {
state.data = memory.readByte(address)
cmp(state.x, state.data)
state.cycle = 0
}
//MARK: CPY
private func cpyImmediate() {
state.data = memory.readByte(state.pc++)
cmp(state.y, state.data)
state.cycle = 0
}
private func cpyZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
cmp(state.y, state.data)
state.cycle = 0
}
private func cpyAbsolute() {
state.data = memory.readByte(address)
cmp(state.y, state.data)
state.cycle = 0
}
//MARK: DEC
private func decZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.data = state.data &- 1
}
private func decAbsolute() {
memory.writeByte(address, byte: state.data)
state.data = state.data &- 1
}
//MARK: DEX
private func dexImplied() {
loadX(state.x &- 1)
state.cycle = 0
}
//MARK: DEY
private func deyImplied() {
loadY(state.y &- 1)
state.cycle = 0
}
//MARK: EOR
private func eorImmediate() {
state.data = memory.readByte(state.pc++)
loadA(state.a ^ state.data)
state.cycle = 0
}
private func eorZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
loadA(state.a ^ state.data)
state.cycle = 0
}
private func eorAbsolute() {
state.data = memory.readByte(address)
loadA(state.a ^ state.data)
state.cycle = 0
}
private func eorPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadA(state.a ^ state.data)
state.cycle = 0
}
}
//MARK: INC
private func incZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.data = state.data &+ 1
}
private func incAbsolute() {
memory.writeByte(address, byte: state.data)
state.data = state.data &+ 1
}
//MARK: INX
private func inxImplied() {
memory.readByte(state.pc)
loadX(state.x &+ 1)
state.cycle = 0
}
//MARK: INY
private func inyImplied() {
memory.readByte(state.pc)
loadY(state.y &+ 1)
state.cycle = 0
}
//MARK: JMP
private func jmpAbsolute() {
state.addressHigh = memory.readByte(state.pc)
state.pc = address
state.cycle = 0
}
private func jmpIndirect() {
pcl = state.data
state.addressLow = state.addressLow &+ 1
pch = memory.readByte(address)
state.cycle = 0
}
//MARK: JSR
private func jsrAbsolute() {
state.addressHigh = memory.readByte(state.pc)
state.pc = address
state.cycle = 0
}
//MARK: LAX
private func laxAbsolute() {
state.data = memory.readByte(address)
loadA(state.data)
loadX(state.data)
state.cycle = 0
}
//MARK: LDA
private func ldaImmediate() {
loadA(memory.readByte(state.pc++))
state.cycle = 0
}
private func ldaZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
loadA(state.data)
state.cycle = 0
}
private func ldaAbsolute() {
state.data = memory.readByte(address)
loadA(state.data)
state.cycle = 0
}
private func ldaPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadA(state.data)
state.cycle = 0
}
}
//MARK: LDX
private func ldxImmediate() {
loadX(memory.readByte(state.pc++))
state.cycle = 0
}
private func ldxZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
loadX(state.data)
state.cycle = 0
}
private func ldxAbsolute() {
state.data = memory.readByte(address)
loadX(state.data)
state.cycle = 0
}
private func ldxPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadX(state.data)
state.cycle = 0
}
}
//MARK: LDY
private func ldyImmediate() {
loadY(memory.readByte(state.pc++))
state.cycle = 0
}
private func ldyZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
loadY(state.data)
state.cycle = 0
}
private func ldyAbsolute() {
state.data = memory.readByte(address)
loadY(state.data)
state.cycle = 0
}
private func ldyPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadY(state.data)
state.cycle = 0
}
}
//MARK: LSR
private func lsrAccumulator() {
memory.readByte(state.pc)
state.c = ((state.a & 1) != 0)
loadA(state.a >> 1)
state.cycle = 0
}
private func lsrZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.c = ((state.data & 1) != 0)
state.data = state.data >> 1
}
//MARK: NOP
private func nop() {
memory.readByte(state.pc)
state.cycle = 0
}
private func nopZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
state.cycle = 0
}
private func nopImmediate() {
state.data = memory.readByte(state.pc++)
state.cycle = 0
}
//MARK: ORA
private func oraImmediate() {
state.data = memory.readByte(state.pc++)
loadA(state.a | state.data)
state.cycle = 0
}
private func oraZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
loadA(state.a | state.data)
state.cycle = 0
}
private func oraPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadA(state.a | state.data)
state.cycle = 0
}
}
private func oraAbsolute() {
state.data = memory.readByte(address)
loadA(state.a | state.data)
state.cycle = 0
}
//MARK: PHA
private func phaImplied() {
memory.writeByte(0x100 &+ state.sp, byte: state.a)
state.sp = state.sp &- 1
state.cycle = 0
}
//MARK: PHP
private func phpImplied() {
let p = UInt8((state.c ? 0x01 : 0) |
(state.z ? 0x02 : 0) |
(state.i ? 0x04 : 0) |
(state.d ? 0x08 : 0) |
(state.b ? 0x10 : 0) |
0x20 |
(state.v ? 0x40 : 0) |
(state.n ? 0x80 : 0))
memory.writeByte(0x100 &+ state.sp, byte: p)
state.sp = state.sp &- 1
state.cycle = 0
}
//MARK: PLA
private func plaImplied() {
loadA(memory.readByte(0x100 &+ state.sp))
state.cycle = 0
}
//MARK: PLP
private func plpImplied() {
let p = memory.readByte(0x100 &+ state.sp)
state.c = ((p & 0x01) != 0)
state.z = ((p & 0x02) != 0)
state.i = ((p & 0x04) != 0)
state.d = ((p & 0x08) != 0)
state.v = ((p & 0x40) != 0)
state.n = ((p & 0x80) != 0)
state.cycle = 0
}
//MARK: ROL
private func rolAccumulator() {
memory.readByte(state.pc)
let hasCarry = state.c
state.c = ((state.a & 0x80) != 0)
loadA((state.a << 1) + (hasCarry ? 1 : 0))
state.cycle = 0
}
private func rolZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
let hasCarry = state.c
state.c = ((state.data & 0x80) != 0)
state.data = (state.data << 1) + (hasCarry ? 1 : 0)
}
private func rolAbsolute() {
memory.writeByte(address, byte: state.data)
let hasCarry = state.c
state.c = ((state.data & 0x80) != 0)
state.data = (state.data << 1) + (hasCarry ? 1 : 0)
}
//MARK: ROR
private func rorAccumulator() {
memory.readByte(state.pc)
let hasCarry = state.c
state.c = ((state.a & 1) != 0)
loadA((state.a >> 1) + (hasCarry ? 0x80 : 0))
state.cycle = 0
}
private func rorZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
let hasCarry = state.c
state.c = ((state.data & 1) != 0)
state.data = (state.data >> 1) + (hasCarry ? 0x80 : 0)
}
private func rorAbsolute() {
memory.writeByte(address, byte: state.data)
let hasCarry = state.c
state.c = ((state.data & 1) != 0)
state.data = (state.data >> 1) + (hasCarry ? 0x80 : 0)
}
//MARK: RTI
private func rtiImplied() {
let p = memory.readByte(0x100 &+ state.sp)
state.c = (p & 0x01 != 0)
state.z = (p & 0x02 != 0)
state.i = (p & 0x04 != 0)
state.d = (p & 0x08 != 0)
state.v = (p & 0x40 != 0)
state.n = (p & 0x80 != 0)
state.sp = state.sp &+ 1
}
private func rtiImplied2() {
pcl = memory.readByte(0x100 &+ state.sp)
state.sp = state.sp &+ 1
}
private func rtiImplied3() {
pch = memory.readByte(0x100 &+ state.sp)
state.cycle = 0
}
//MARK: RTS
private func rtsImplied() {
pcl = memory.readByte(0x100 &+ state.sp)
state.sp = state.sp &+ 1
}
private func rtsImplied2() {
pch = memory.readByte(0x100 &+ state.sp)
}
private func rtsImplied3() {
++state.pc
state.cycle = 0
}
//MARK: SBC
private func sbc(value: UInt8) {
if state.d {
let tempA = UInt16(state.a)
let sum = (tempA &- UInt16(value) &- (state.c ? 0 : 1))
var lowNybble = (state.a & 0x0F) &- (value & 0x0F) &- (state.c ? 0 : 1)
var highNybble = (state.a >> 4) &- (value >> 4)
if lowNybble & 0x10 != 0 {
lowNybble = lowNybble &- 6
highNybble = highNybble &- 1
}
if highNybble & 0x10 != 0 {
highNybble = highNybble &- 6
}
state.c = (sum < 0x100)
state.v = (((tempA ^ sum) & 0x80) != 0 && ((tempA ^ UInt16(value)) & 0x80) != 0)
state.z = (UInt8(truncatingBitPattern: sum) == 0)
state.n = (sum & 0x80 != 0)
state.a = (highNybble << 4) | (lowNybble & 0x0F)
} else {
let tempA = UInt16(state.a)
let sum = (tempA &- UInt16(value) &- (state.c ? 0 : 1))
state.c = (sum <= 0xFF)
state.v = (((UInt16(state.a) ^ sum) & 0x80) != 0 && ((UInt16(state.a) ^ UInt16(value)) & 0x80) != 0)
loadA(UInt8(truncatingBitPattern: sum))
}
}
private func sbcImmediate() {
state.data = memory.readByte(state.pc++)
sbc(state.data)
state.cycle = 0
}
private func sbcZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
sbc(state.data)
state.cycle = 0
}
private func sbcAbsolute() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
sbc(state.data)
state.cycle = 0
}
}
private func sbcAbsolute2() {
state.data = memory.readByte(address)
sbc(state.data)
state.cycle = 0
}
//MARK: SEC
private func secImplied() {
memory.readByte(state.pc)
state.c = true
state.cycle = 0
}
//MARK: SED
private func sedImplied() {
memory.readByte(state.pc)
state.d = true
state.cycle = 0
}
//MARK: SEI
private func seiImplied() {
memory.readByte(state.pc)
state.i = true
state.cycle = 0
}
//MARK: STA
private func staZeroPage() {
state.data = state.a
memory.writeByte(UInt16(state.addressLow), byte: state.a)
state.cycle = 0
}
private func staAbsolute() {
state.data = state.a
memory.writeByte(address, byte: state.data)
state.cycle = 0
}
//MARK: STX
private func stxZeroPage() {
state.data = state.x
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.cycle = 0
}
private func stxAbsolute() {
state.data = state.x
memory.writeByte(address, byte: state.data)
state.cycle = 0
}
//MARK: STY
private func styZeroPage() {
state.data = state.y
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.cycle = 0
}
private func styAbsolute() {
state.data = state.y
memory.writeByte(address, byte: state.data)
state.cycle = 0
}
//MARK: TAX
private func taxImplied() {
memory.readByte(state.pc)
loadX(state.a)
state.cycle = 0
}
//MARK: TAY
private func tayImplied() {
memory.readByte(state.pc)
loadY(state.a)
state.cycle = 0
}
//MARK: TSX
private func tsxImplied() {
memory.readByte(state.pc)
loadX(state.sp)
state.cycle = 0
}
//MARK: TXA
private func txaImplied() {
memory.readByte(state.pc)
loadA(state.x)
state.cycle = 0
}
//MARK: TXS
private func txsImplied() {
memory.readByte(state.pc)
state.sp = state.x
state.cycle = 0
}
//MARK: TYA
private func tyaImplied() {
memory.readByte(state.pc)
loadA(state.y)
state.cycle = 0
}
}
Add LSR Absolute
//
// CPU.swift
// C-swifty4
//
// Created by Fabio Ritrovato on 30/12/2014.
// Copyright (c) 2014 orange in a day. All rights reserved.
//
import Foundation
internal struct CPUState: ComponentState {
var pc: UInt16 = 0
var isAtFetch = false
var a: UInt8 = 0
var x: UInt8 = 0
var y: UInt8 = 0
var sp: UInt8 = 0
var c: Bool = false
var z: Bool = false
var i: Bool = false
var d: Bool = false
var b: Bool = true
var v: Bool = false
var n: Bool = false
var portDirection: UInt8 = 0x2F
var port: UInt8 = 0x37
@available(*, deprecated) var irqTriggered = false //TODO: maybe we still need to keep track if the IRQ has been triggered?
var nmiTriggered = false //TODO: see below
var nmiLine = true
var currentOpcode: UInt16 = 0
var cycle = 0
var data: UInt8 = 0
var addressLow: UInt8 = 0
var addressHigh: UInt8 = 0
var pointer: UInt8 = 0
var pageBoundaryCrossed = false
mutating func update(dictionary: [String: AnyObject]) {
pc = UInt16(dictionary["pc"] as! UInt)
isAtFetch = dictionary["isAtFetch"] as! Bool
a = UInt8(dictionary["a"] as! UInt)
x = UInt8(dictionary["x"] as! UInt)
y = UInt8(dictionary["y"] as! UInt)
sp = UInt8(dictionary["sp"] as! UInt)
c = dictionary["c"] as! Bool
z = dictionary["z"] as! Bool
i = dictionary["i"] as! Bool
d = dictionary["d"] as! Bool
b = dictionary["b"] as! Bool
v = dictionary["v"] as! Bool
n = dictionary["n"] as! Bool
portDirection = UInt8(dictionary["portDirection"] as! UInt)
port = UInt8(dictionary["port"] as! UInt)
irqTriggered = dictionary["irqTriggered"] as! Bool
nmiTriggered = dictionary["nmiTriggered"] as! Bool
currentOpcode = UInt16(dictionary["currentOpcode"] as! UInt)
cycle = dictionary["cycle"] as! Int
data = UInt8(dictionary["data"] as! UInt)
addressLow = UInt8(dictionary["addressLow"] as! UInt)
addressHigh = UInt8(dictionary["addressHigh"] as! UInt)
pointer = UInt8(dictionary["pointer"] as! UInt)
pageBoundaryCrossed = dictionary["pageBoundaryCrossed"] as! Bool
}
}
final internal class CPU: Component, IRQLineComponent {
var state = CPUState()
internal weak var irqLine: Line!
internal weak var memory: Memory!
internal var crashHandler: C64CrashHandler?
private var pcl: UInt8 {
set {
state.pc = (state.pc & 0xFF00) | UInt16(newValue)
}
get {
return UInt8(truncatingBitPattern: state.pc)
}
}
private var pch: UInt8 {
set {
state.pc = (state.pc & 0x00FF) | UInt16(newValue) << 8
}
get {
return UInt8(truncatingBitPattern: state.pc >> 8)
}
}
internal var port: UInt8 {
set {
state.port = newValue | ~state.portDirection
}
get {
return state.port
}
}
var portDirection: UInt8 {
set {
state.portDirection = newValue
}
get {
return state.portDirection
}
}
private var address: UInt16 {
get {
return UInt16(state.addressHigh) << 8 | UInt16(state.addressLow)
}
}
internal init(pc: UInt16) {
self.state.pc = pc
}
//MARK: LineComponent
func lineChanged(line: Line) {
}
//MARK: Running
internal func executeInstruction() {
if state.cycle++ == 0 {
fetch()
return
}
state.isAtFetch = false
switch state.currentOpcode {
// ADC
case 0x69:
adcImmediate()
case 0x65:
state.cycle == 2 ? zeroPage() : adcZeroPage()
case 0x75:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : adcZeroPage()
case 0x6D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : adcAbsolute()
case 0x7D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? adcPageBoundary() : adcAbsolute()
case 0x79:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? adcPageBoundary() : adcAbsolute()
case 0x61:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectX() :
state.cycle == 4 ? indirectIndex2() :
state.cycle == 5 ? indirectX2() : adcAbsolute()
case 0x71:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? adcPageBoundary() : adcAbsolute()
// ALR*
case 0x4B:
alrImmediate()
// ANC
case 0x0B, 0x2B:
ancImmediate()
// AND
case 0x29:
andImmediate()
case 0x25:
state.cycle == 2 ? zeroPage() : andZeroPage()
case 0x35:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : andZeroPage()
case 0x2D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : andAbsolute()
case 0x3D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? andPageBoundary() : andAbsolute()
case 0x39:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? andPageBoundary() : andAbsolute()
case 0x21:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectX() :
state.cycle == 4 ? indirectIndex2() :
state.cycle == 5 ? indirectX2() : andAbsolute()
case 0x31:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? andPageBoundary() : andAbsolute()
// ASL
case 0x0A:
aslAccumulator()
case 0x06:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPage2() :
state.cycle == 4 ? aslZeroPage() : zeroPageWriteUpdateNZ()
case 0x16:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() :
state.cycle == 4 ? zeroPage2() :
state.cycle == 5 ? aslZeroPage() : zeroPageWriteUpdateNZ()
case 0x0E:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? absolute3() :
state.cycle == 5 ? aslAbsolute() : absoluteWriteUpdateNZ()
case 0x1E:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? absoluteFixPage() :
state.cycle == 5 ? absolute3() :
state.cycle == 6 ? aslAbsolute() : absoluteWriteUpdateNZ()
// BCC
case 0x90:
state.cycle == 2 ? bccRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BCS
case 0xB0:
state.cycle == 2 ? bcsRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BEQ
case 0xF0:
state.cycle == 2 ? beqRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BIT
case 0x24:
state.cycle == 2 ? zeroPage() : bitZeroPage()
case 0x2C:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : bitAbsolute()
// BMI
case 0x30:
state.cycle == 2 ? bmiRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BNE
case 0xD0:
state.cycle == 2 ? bneRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BPL
case 0x10:
state.cycle == 2 ? bplRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BRK
case 0x00:
state.cycle == 2 ? immediate() :
state.cycle == 3 ? brkImplied() :
state.cycle == 4 ? brkImplied2() :
state.cycle == 5 ? brkImplied3() :
state.cycle == 6 ? brkImplied4() : brkImplied5()
// BVC
case 0x50:
state.cycle == 2 ? bvcRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// BVS
case 0x70:
state.cycle == 2 ? bvsRelative() :
state.cycle == 3 ? branch() : branchOverflow()
// CLC
case 0x18:
clcImplied()
// CLD
case 0xD8:
cldImplied()
// CLI
case 0x58:
cliImplied()
// CLV
case 0xB8:
clvImplied()
// CMP
case 0xC9:
cmpImmediate()
case 0xC5:
state.cycle == 2 ? zeroPage() : cmpZeroPage()
case 0xD5:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : cmpZeroPage()
case 0xCD:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : cmpAbsolute()
case 0xDD:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? cmpPageBoundary() : cmpAbsolute()
case 0xD9:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? cmpPageBoundary() : cmpAbsolute()
case 0xC1:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectX() :
state.cycle == 4 ? indirectIndex2() :
state.cycle == 5 ? indirectX2() : cmpAbsolute()
case 0xD1:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? cmpPageBoundary() : cmpAbsolute()
// CPX
case 0xE0:
cpxImmediate()
case 0xE4:
state.cycle == 2 ? zeroPage() : cpxZeroPage()
case 0xEC:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : cpxAbsolute()
// CPY
case 0xC0:
cpyImmediate()
case 0xC4:
state.cycle == 2 ? zeroPage() : cpyZeroPage()
case 0xCC:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : cpyAbsolute()
// DEC
case 0xC6:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPage2() :
state.cycle == 4 ? decZeroPage() : zeroPageWriteUpdateNZ()
case 0xD6:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() :
state.cycle == 4 ? zeroPage2() :
state.cycle == 5 ? decZeroPage() : zeroPageWriteUpdateNZ()
case 0xCE:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? absolute3() :
state.cycle == 5 ? decAbsolute() : absoluteWriteUpdateNZ()
case 0xDE:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? absoluteFixPage() :
state.cycle == 5 ? absolute3() :
state.cycle == 6 ? decAbsolute() : absoluteWriteUpdateNZ()
// DEX
case 0xCA:
dexImplied()
// DEY
case 0x88:
deyImplied()
// EOR
case 0x49:
eorImmediate()
case 0x45:
state.cycle == 2 ? zeroPage() : eorZeroPage()
case 0x55:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : eorZeroPage()
case 0x4D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : eorAbsolute()
case 0x5D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? eorPageBoundary() : eorAbsolute()
case 0x59:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? eorPageBoundary() : eorAbsolute()
case 0x41:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectX() :
state.cycle == 4 ? indirectIndex2() :
state.cycle == 5 ? indirectX2() : eorAbsolute()
case 0x51:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? eorPageBoundary() : eorAbsolute()
// INC
case 0xE6:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPage2() :
state.cycle == 4 ? incZeroPage() : zeroPageWriteUpdateNZ()
case 0xF6:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() :
state.cycle == 4 ? zeroPage2() :
state.cycle == 5 ? incZeroPage() : zeroPageWriteUpdateNZ()
case 0xEE:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? absolute3() :
state.cycle == 5 ? incAbsolute() : absoluteWriteUpdateNZ()
case 0xFE:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? absoluteFixPage() :
state.cycle == 5 ? absolute3() :
state.cycle == 6 ? incAbsolute() : absoluteWriteUpdateNZ()
// INX
case 0xE8:
inxImplied()
// INY
case 0xC8:
inyImplied()
// JMP
case 0x4C:
state.cycle == 2 ? absolute() : jmpAbsolute()
case 0x6C:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? indirect() : jmpIndirect()
// JSR
case 0x20:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? {}() :
state.cycle == 4 ? pushPch() :
state.cycle == 5 ? pushPcl() : jsrAbsolute()
// LAX
case 0xAF:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : laxAbsolute()
// LDA
case 0xA9:
ldaImmediate()
case 0xA5:
state.cycle == 2 ? zeroPage() : ldaZeroPage()
case 0xB5:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : ldaZeroPage()
case 0xAD:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : ldaAbsolute()
case 0xBD:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? ldaPageBoundary() : ldaAbsolute()
case 0xB9:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? ldaPageBoundary() : ldaAbsolute()
case 0xA1:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectX() :
state.cycle == 4 ? indirectIndex2() :
state.cycle == 5 ? indirectX2() : ldaAbsolute()
case 0xB1:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? ldaPageBoundary() : ldaAbsolute()
// LDX
case 0xA2:
ldxImmediate()
case 0xA6:
state.cycle == 2 ? zeroPage() : ldxZeroPage()
case 0xB6:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageY() : ldxZeroPage()
case 0xAE:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : ldxAbsolute()
case 0xBE:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? ldxPageBoundary() : ldxAbsolute()
// LDY
case 0xA0:
ldyImmediate()
case 0xA4:
state.cycle == 2 ? zeroPage() : ldyZeroPage()
case 0xB4:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : ldyZeroPage()
case 0xAC:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : ldyAbsolute()
case 0xBC:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? ldyPageBoundary() : ldyAbsolute()
// LSR
case 0x4A:
lsrAccumulator()
case 0x46:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPage2() :
state.cycle == 4 ? lsrZeroPage() : zeroPageWriteUpdateNZ()
case 0x56:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() :
state.cycle == 4 ? zeroPage2() :
state.cycle == 5 ? lsrZeroPage() : zeroPageWriteUpdateNZ()
case 0x4E:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? absolute3() :
state.cycle == 5 ? lsrAbsolute() : absoluteWriteUpdateNZ()
// NOP
case 0xEA, 0x5A, 0x7A:
nop()
case 0x44:
state.cycle == 2 ? zeroPage() : nopZeroPage()
case 0x14:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : nopZeroPage()
case 0x82, 0xE2:
nopImmediate()
// ORA
case 0x09:
oraImmediate()
case 0x05:
state.cycle == 2 ? zeroPage() : oraZeroPage()
case 0x0D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : oraAbsolute()
case 0x1D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? oraPageBoundary() : oraAbsolute()
// PHA
case 0x48:
state.cycle == 2 ? implied() : phaImplied()
// PHP
case 0x08:
state.cycle == 2 ? implied() : phpImplied()
// PLA
case 0x68:
state.cycle == 2 ? implied() :
state.cycle == 3 ? implied2() : plaImplied()
// PLP
case 0x28:
state.cycle == 2 ? implied() :
state.cycle == 3 ? implied2() : plpImplied()
// ROL
case 0x2A:
rolAccumulator()
case 0x26:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPage2() :
state.cycle == 4 ? rolZeroPage() : zeroPageWriteUpdateNZ()
case 0x2E:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? absolute3() :
state.cycle == 5 ? rolAbsolute() : absoluteWriteUpdateNZ()
// ROR
case 0x6A:
rorAccumulator()
case 0x66:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPage2() :
state.cycle == 4 ? rorZeroPage() : zeroPageWriteUpdateNZ()
case 0x76:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() :
state.cycle == 4 ? zeroPage2() :
state.cycle == 5 ? rorZeroPage() : zeroPageWriteUpdateNZ()
case 0x6E:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? absolute3() :
state.cycle == 5 ? rorAbsolute() : absoluteWriteUpdateNZ()
// RTI
case 0x40:
state.cycle == 2 ? immediate() :
state.cycle == 3 ? implied2() :
state.cycle == 4 ? rtiImplied() :
state.cycle == 5 ? rtiImplied2() : rtiImplied3()
// RTS
case 0x60:
state.cycle == 2 ? immediate() :
state.cycle == 3 ? implied2() :
state.cycle == 4 ? rtsImplied() :
state.cycle == 5 ? rtsImplied2() : rtsImplied3()
// SBC
case 0xE9:
sbcImmediate()
case 0xE5:
state.cycle == 2 ? zeroPage() : sbcZeroPage()
case 0xF5:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : sbcZeroPage()
case 0xED:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() :
state.cycle == 4 ? sbcAbsolute() : sbcAbsolute2()
case 0xFD:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? sbcAbsolute() : sbcAbsolute2()
case 0xF9:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? sbcAbsolute() : sbcAbsolute2()
case 0xF1:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? sbcAbsolute() : sbcAbsolute2()
// SEC
case 0x38:
secImplied()
case 0xF8:
sedImplied()
// SEI
case 0x78:
seiImplied()
// STA
case 0x85:
state.cycle == 2 ? zeroPage() : staZeroPage()
case 0x95:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : staZeroPage()
case 0x8D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : staAbsolute()
case 0x9D:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteX() :
state.cycle == 4 ? absoluteFixPage() : staAbsolute()
case 0x99:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absoluteY() :
state.cycle == 4 ? absoluteFixPage() : staAbsolute()
case 0x81:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectX() :
state.cycle == 4 ? indirectIndex2() :
state.cycle == 5 ? indirectX2() : staAbsolute()
case 0x91:
state.cycle == 2 ? indirectIndex() :
state.cycle == 3 ? indirectIndex2() :
state.cycle == 4 ? indirectY() :
state.cycle == 5 ? absoluteFixPage() : staAbsolute()
// STX
case 0x86:
state.cycle == 2 ? zeroPage() : stxZeroPage()
case 0x96:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageY() : styZeroPage()
case 0x8E:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : stxAbsolute()
// STY
case 0x84:
state.cycle == 2 ? zeroPage() : styZeroPage()
case 0x94:
state.cycle == 2 ? zeroPage() :
state.cycle == 3 ? zeroPageX() : styZeroPage()
case 0x8C:
state.cycle == 2 ? absolute() :
state.cycle == 3 ? absolute2() : styAbsolute()
// TAX
case 0xAA:
taxImplied()
// TAY
case 0xA8:
tayImplied()
// TSX
case 0xBA:
tsxImplied()
// TXA
case 0x8A:
txaImplied()
// TXS
case 0x9a:
txsImplied()
// TYA
case 0x98:
tyaImplied()
// NMI
case 0xFFFE:
state.cycle == 2 ? implied() :
state.cycle == 3 ? pushPch() :
state.cycle == 4 ? pushPcl() :
state.cycle == 5 ? interrupt() :
state.cycle == 6 ? nmi() : nmi2()
// IRQ
case 0xFFFF:
state.cycle == 2 ? implied() :
state.cycle == 3 ? pushPch() :
state.cycle == 4 ? pushPcl() :
state.cycle == 5 ? interrupt() :
state.cycle == 6 ? irq() : irq2()
default:
let opcodeString = String(state.currentOpcode, radix: 16, uppercase: true)
let pcString = String((state.pc &- UInt16(1)), radix: 16, uppercase: true)
crashHandler?("Unknown opcode: " + opcodeString + " pc: " + pcString)
}
}
@available(*, deprecated) internal func setIRQLine() {
state.irqTriggered = true
}
//TODO: NMI is connected to multiple sources so it should be treated like an actual line (like IEC)
internal func setNMILine(line: Bool) {
if !line && state.nmiLine {
state.nmiTriggered = true
}
state.nmiLine = line
}
internal func setOverflow() {
state.v = true
}
internal func debugInfo() -> [String: String] {
let description: String = {
switch state.currentOpcode {
case 0x69: return String(format: "ADC #%02x", self.memory.readByte(state.pc))
case 0x65: return String(format: "ADC %02x", self.memory.readByte(state.pc))
case 0x75: return String(format: "ADC %02x,X", self.memory.readByte(state.pc))
case 0x6D: return String(format: "ADC %04x", self.memory.readWord(state.pc))
case 0x7D: return String(format: "ADC %04x,X", self.memory.readWord(state.pc))
case 0x79: return String(format: "ADC %04x,Y", self.memory.readWord(state.pc))
case 0x61: return String(format: "ADC (%02x,X)", self.memory.readByte(state.pc))
case 0x71: return String(format: "ADC (%02x),Y", self.memory.readByte(state.pc))
case 0x4B: return String(format: "ALR* #%02x", self.memory.readByte(state.pc))
case 0x0B: return String(format: "ANC* #%02x", self.memory.readByte(state.pc))
case 0x2B: return String(format: "ANC* #%02x", self.memory.readByte(state.pc))
case 0x29: return String(format: "AND #%02x", self.memory.readByte(state.pc))
case 0x25: return String(format: "AND %02x", self.memory.readByte(state.pc))
case 0x35: return String(format: "AND %02x,X", self.memory.readByte(state.pc))
case 0x2D: return String(format: "AND %04x", self.memory.readWord(state.pc))
case 0x3D: return String(format: "AND %04x,X", self.memory.readWord(state.pc))
case 0x39: return String(format: "AND %04x,Y", self.memory.readWord(state.pc))
case 0x21: return String(format: "AND (%02x,X)", self.memory.readByte(state.pc))
case 0x31: return String(format: "AND (%02x),Y", self.memory.readByte(state.pc))
case 0x0A: return "ASL"
case 0x06: return String(format: "ASL %02x", self.memory.readByte(state.pc))
case 0x16: return String(format: "ASL %02x,X", self.memory.readByte(state.pc))
case 0x0E: return String(format: "ASL %04x", self.memory.readWord(state.pc))
case 0x1E: return String(format: "ASL %04x,X", self.memory.readWord(state.pc))
case 0x90: return String(format: "BCC %02x", self.memory.readByte(state.pc))
case 0xB0: return String(format: "BCS %02x", self.memory.readByte(state.pc))
case 0xF0: return String(format: "BEQ %02x", self.memory.readByte(state.pc))
case 0x24: return String(format: "BIT %02x", self.memory.readByte(state.pc))
case 0x2C: return String(format: "BIT %04x", self.memory.readWord(state.pc))
case 0x30: return String(format: "BMI %02x", self.memory.readByte(state.pc))
case 0xD0: return String(format: "BNE %02x", self.memory.readByte(state.pc))
case 0x10: return String(format: "BPL %02x", self.memory.readByte(state.pc))
case 0x00: return "BRK"
case 0x50: return String(format: "BVC %02x", self.memory.readByte(state.pc))
case 0x70: return String(format: "BVS %02x", self.memory.readByte(state.pc))
case 0x18: return "CLC"
case 0xD8: return "CLD"
case 0x58: return "CLI"
case 0xB8: return "CLV"
case 0xC9: return String(format: "CMP #%02x", self.memory.readByte(state.pc))
case 0xC5: return String(format: "CMP %02x", self.memory.readByte(state.pc))
case 0xD5: return String(format: "CMP %02x,X", self.memory.readByte(state.pc))
case 0xCD: return String(format: "CMP %04x", self.memory.readWord(state.pc))
case 0xDD: return String(format: "CMP %04x,X", self.memory.readWord(state.pc))
case 0xD9: return String(format: "CMP %04x,Y", self.memory.readWord(state.pc))
case 0xC1: return String(format: "CMP (%02x,X)", self.memory.readByte(state.pc))
case 0xD1: return String(format: "CMP (%02x),Y", self.memory.readByte(state.pc))
case 0xE0: return String(format: "CPX #%02x", self.memory.readByte(state.pc))
case 0xE4: return String(format: "CPX %02x", self.memory.readByte(state.pc))
case 0xEC: return String(format: "CPX %04x", self.memory.readWord(state.pc))
case 0xC0: return String(format: "CPY #%02x", self.memory.readByte(state.pc))
case 0xC4: return String(format: "CPY %02x", self.memory.readByte(state.pc))
case 0xCC: return String(format: "CPY %04x", self.memory.readWord(state.pc))
case 0xC6: return String(format: "DEC %02x", self.memory.readByte(state.pc))
case 0xD6: return String(format: "DEC %02x,X", self.memory.readByte(state.pc))
case 0xCE: return String(format: "DEC %04x", self.memory.readWord(state.pc))
case 0xDE: return String(format: "DEC %04x,X", self.memory.readWord(state.pc))
case 0xCA: return "DEX"
case 0x88: return "DEY"
case 0x49: return String(format: "EOR #%02x", self.memory.readByte(state.pc))
case 0x45: return String(format: "EOR %02x", self.memory.readByte(state.pc))
case 0x55: return String(format: "EOR %02x,X", self.memory.readByte(state.pc))
case 0x4D: return String(format: "EOR %04x", self.memory.readWord(state.pc))
case 0x5D: return String(format: "EOR %04x,X", self.memory.readWord(state.pc))
case 0x59: return String(format: "EOR %04x,Y", self.memory.readWord(state.pc))
case 0x41: return String(format: "EOR (%02x,Y)", self.memory.readByte(state.pc))
case 0x51: return String(format: "EOR (%02x),Y", self.memory.readByte(state.pc))
case 0xE6: return String(format: "INC %02x", self.memory.readByte(state.pc))
case 0xF6: return String(format: "INC %02x,X", self.memory.readByte(state.pc))
case 0xEE: return String(format: "INC %04x", self.memory.readWord(state.pc))
case 0xFE: return String(format: "INC %04x,X", self.memory.readWord(state.pc))
case 0xE8: return "INX"
case 0xC8: return "INY"
case 0x4C: return String(format: "JMP %04x", self.memory.readWord(state.pc))
case 0x6C: return String(format: "JMP (%04x)", self.memory.readWord(state.pc))
case 0x20: return String(format: "JSR %04x", self.memory.readWord(state.pc))
case 0xAF: return String(format: "LAX* %04x", self.memory.readWord(state.pc))
case 0xA9: return String(format: "LDA #%02x", self.memory.readByte(state.pc))
case 0xA5: return String(format: "LDA %02x", self.memory.readByte(state.pc))
case 0xB5: return String(format: "LDA %02x,X", self.memory.readByte(state.pc))
case 0xAD: return String(format: "LDA %04x", self.memory.readWord(state.pc))
case 0xBD: return String(format: "LDA %04x,X", self.memory.readWord(state.pc))
case 0xB9: return String(format: "LDA %04x,Y", self.memory.readWord(state.pc))
case 0xA1: return String(format: "LDA (%02x,X)", self.memory.readByte(state.pc))
case 0xB1: return String(format: "LDA (%02x),Y", self.memory.readByte(state.pc))
case 0xA2: return String(format: "LDX #%02x", self.memory.readByte(state.pc))
case 0xA6: return String(format: "LDX %02x", self.memory.readByte(state.pc))
case 0xB6: return String(format: "LDX %02x,Y", self.memory.readByte(state.pc))
case 0xAE: return String(format: "LDX %04x", self.memory.readWord(state.pc))
case 0xBE: return String(format: "LDX %04x,Y", self.memory.readWord(state.pc))
case 0xA0: return String(format: "LDY #%02x", self.memory.readByte(state.pc))
case 0xA4: return String(format: "LDY %02x", self.memory.readByte(state.pc))
case 0xB4: return String(format: "LDY %02x,X", self.memory.readByte(state.pc))
case 0xAC: return String(format: "LDY %04x", self.memory.readWord(state.pc))
case 0xBC: return String(format: "LDY %04x,X", self.memory.readWord(state.pc))
case 0x4A: return "LSR"
case 0x46: return String(format: "LSR %02x", self.memory.readByte(state.pc))
case 0x56: return String(format: "LSR %02x,X", self.memory.readByte(state.pc))
case 0x4E: return String(format: "LSR %04x", self.memory.readWord(state.pc))
case 0xEA: return "NOP"
case 0x5A: return "NOP*"
case 0x7A: return "NOP*"
case 0x44: return String(format: "NOP* %02x", self.memory.readByte(state.pc))
case 0x14: return String(format: "NOP* %02x,X", self.memory.readByte(state.pc))
case 0x82: return String(format: "NOP* #%02x", self.memory.readByte(state.pc))
case 0xE2: return String(format: "NOP* #%02x", self.memory.readByte(state.pc))
case 0x09: return String(format: "ORA #%02x", self.memory.readByte(state.pc))
case 0x05: return String(format: "ORA %02x", self.memory.readByte(state.pc))
case 0x0D: return String(format: "ORA %04x", self.memory.readWord(state.pc))
case 0x3D: return String(format: "ORA %04x,X", self.memory.readWord(state.pc))
case 0x48: return "PHA"
case 0x08: return "PHP"
case 0x68: return "PLA"
case 0x28: return "PLP"
case 0x2A: return "ROL"
case 0x26: return String(format: "ROL %02x", self.memory.readByte(state.pc))
case 0x2E: return String(format: "ROL %04x", self.memory.readWord(state.pc))
case 0x6A: return "ROR"
case 0x66: return String(format: "ROR %02x", self.memory.readByte(state.pc))
case 0x76: return String(format: "ROR %02x,X", self.memory.readByte(state.pc))
case 0x6E: return String(format: "ROR %04x", self.memory.readWord(state.pc))
case 0x40: return "RTI"
case 0x60: return "RTS"
case 0xE9: return String(format: "SBC #%02x", self.memory.readByte(state.pc))
case 0xE5: return String(format: "SBC %02x", self.memory.readByte(state.pc))
case 0xF5: return String(format: "SBC %02x,X", self.memory.readByte(state.pc))
case 0xED: return String(format: "SBC %04x", self.memory.readWord(state.pc))
case 0xFD: return String(format: "SBC %04x,X", self.memory.readWord(state.pc))
case 0xF9: return String(format: "SBC %04x,Y", self.memory.readWord(state.pc))
case 0xF1: return String(format: "SBC (%02x),Y", self.memory.readByte(state.pc))
case 0x38: return "SEC"
case 0xF8: return "SED"
case 0x78: return "SEI"
case 0x85: return String(format: "STA %02x", self.memory.readByte(state.pc))
case 0x95: return String(format: "STA %02x,X", self.memory.readByte(state.pc))
case 0x8D: return String(format: "STA %04x", self.memory.readWord(state.pc))
case 0x9D: return String(format: "STA %04x,X", self.memory.readWord(state.pc))
case 0x99: return String(format: "STA %04x,Y", self.memory.readWord(state.pc))
case 0x81: return String(format: "STA (%02x,X)", self.memory.readByte(state.pc))
case 0x91: return String(format: "STA (%02x),Y", self.memory.readByte(state.pc))
case 0x86: return String(format: "STX %02x", self.memory.readByte(state.pc))
case 0x96: return String(format: "STX %02x,Y", self.memory.readByte(state.pc))
case 0x8E: return String(format: "STX %04x", self.memory.readWord(state.pc))
case 0x84: return String(format: "STY %02x", self.memory.readByte(state.pc))
case 0x94: return String(format: "STY %02x,X", self.memory.readByte(state.pc))
case 0x8C: return String(format: "STY %04x", self.memory.readWord(state.pc))
case 0xAA: return "TAX"
case 0xA8: return "TAY"
case 0xBA: return "TSX"
case 0x8A: return "TXA"
case 0x9a: return "TXS"
case 0x98: return "TYA"
default: return String(format: "Unknown opcode: %02x", state.currentOpcode)
}
}()
return ["pc": String(format: "%04x", state.pc &- UInt16(1)),
"a": String(format: "%02x", state.a),
"x": String(format: "%02x", state.x),
"y": String(format: "%02x", state.y),
"sp": String(format: "%02x", state.sp),
"sr.n": state.n ? "✓" : " ",
"sr.v": state.v ? "✓" : " ",
"sr.b": state.b ? "✓" : " ",
"sr.d": state.d ? "✓" : " ",
"sr.i": state.i ? "✓" : " ",
"sr.z": state.z ? "✓" : " ",
"sr.c": state.c ? "✓" : " ",
"description": description
]
}
//MARK: Helpers
private func updateNFlag(value: UInt8) {
state.n = (value & 0x80 != 0)
}
private func updateZFlag(value: UInt8) {
state.z = (value == 0)
}
private func loadA(value: UInt8) {
state.a = value
state.z = (value == 0)
state.n = (value & 0x80 != 0)
}
private func loadX(value: UInt8) {
state.x = value
state.z = (value == 0)
state.n = (value & 0x80 != 0)
}
private func loadY(value: UInt8) {
state.y = value
state.z = (value == 0)
state.n = (value & 0x80 != 0)
}
private func fetch() {
if state.nmiTriggered {
state.nmiTriggered = false
state.currentOpcode = 0xFFFE
return
}
//IRQ is level sensitive, so it's always trigger as long as the line is pulled down
if !irqLine.state && !state.i {
state.currentOpcode = 0xFFFF
return
}
if state.irqTriggered && !state.i {
state.irqTriggered = false
state.currentOpcode = 0xFFFF
return
}
state.isAtFetch = true
state.currentOpcode = UInt16(memory.readByte(state.pc))
state.pc = state.pc &+ UInt16(1)
}
private func pushPch() {
memory.writeByte(0x100 &+ state.sp, byte: pch)
state.sp = state.sp &- 1
}
private func pushPcl() {
memory.writeByte(0x100 &+ state.sp, byte: pcl)
state.sp = state.sp &- 1
}
//MARK: Interrupts
private func interrupt() {
let p = UInt8((state.c ? 0x01 : 0) |
(state.z ? 0x02 : 0) |
(state.i ? 0x04 : 0) |
(state.d ? 0x08 : 0) |
// (b ? 0x10 : 0) | b is 0 on IRQ
0x20 |
(state.v ? 0x40 : 0) |
(state.n ? 0x80 : 0))
memory.writeByte(0x100 &+ state.sp, byte: p)
state.sp = state.sp &- 1
state.i = true
}
private func irq() {
state.data = memory.readByte(0xFFFE)
}
private func irq2() {
pcl = state.data
pch = memory.readByte(0xFFFF)
state.cycle = 0
}
private func nmi() {
state.data = memory.readByte(0xFFFA)
}
private func nmi2() {
pcl = state.data
pch = memory.readByte(0xFFFB)
state.cycle = 0
}
//MARK: Opcodes
//MARK: Addressing
private func zeroPage() {
state.addressLow = memory.readByte(state.pc++)
}
private func zeroPage2() {
state.data = memory.readByte(UInt16(state.addressLow))
}
private func zeroPageWriteUpdateNZ() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.z = (state.data == 0)
state.n = (state.data & 0x80 != 0)
state.cycle = 0
}
private func zeroPageX() {
state.data = memory.readByte(UInt16(state.addressLow))
state.addressLow = state.addressLow &+ state.x
}
private func zeroPageY() {
state.data = memory.readByte(UInt16(state.addressLow))
state.addressLow = state.addressLow &+ state.y
}
private func absolute() {
state.addressLow = memory.readByte(state.pc++)
}
private func absolute2() {
state.addressHigh = memory.readByte(state.pc++)
}
private func absolute3() {
state.data = memory.readByte(address)
}
private func absoluteWriteUpdateNZ() {
memory.writeByte(address, byte: state.data)
state.z = (state.data == 0)
state.n = (state.data & 0x80 != 0)
state.cycle = 0
}
private func absoluteX() {
state.addressHigh = memory.readByte(state.pc++)
state.pageBoundaryCrossed = (UInt16(state.addressLow) &+ state.x >= 0x100)
state.addressLow = state.addressLow &+ state.x
}
private func absoluteY() {
state.addressHigh = memory.readByte(state.pc++)
state.pageBoundaryCrossed = (UInt16(state.addressLow) &+ state.y >= 0x100)
state.addressLow = state.addressLow &+ state.y
}
private func absoluteFixPage() {
memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
}
}
private func indirect() {
state.data = memory.readByte(address)
}
private func indirectIndex() {
state.pointer = memory.readByte(state.pc++)
}
private func indirectIndex2() {
state.addressLow = memory.readByte(UInt16(state.pointer))
state.pointer = state.pointer &+ 1
}
private func indirectX() {
memory.readByte(UInt16(state.pointer))
state.pointer = state.pointer &+ state.x
}
private func indirectX2() {
state.addressHigh = memory.readByte(UInt16(state.pointer))
state.pointer = state.pointer &+ 1
}
private func indirectY() {
state.addressHigh = memory.readByte(UInt16(state.pointer))
state.pointer = state.pointer &+ 1
state.pageBoundaryCrossed = (UInt16(state.addressLow) &+ state.y >= 0x100)
state.addressLow = state.addressLow &+ state.y
}
private func implied() {
memory.readByte(state.pc)
}
private func implied2() {
state.sp = state.sp &+ 1
}
private func immediate() {
memory.readByte(state.pc)
state.pc = state.pc &+ UInt16(1)
}
//MARK: ADC
private func adc(value: UInt8) {
if state.d {
var lowNybble = (state.a & 0x0F) &+ (value & 0x0F) &+ (state.c ? 1 : 0)
var highNybble = (state.a >> 4) &+ (value >> 4)
if lowNybble > 9 {
lowNybble = lowNybble &+ 6
}
if lowNybble > 0x0F {
highNybble = highNybble &+ 1
}
state.z = ((state.a &+ value &+ (state.c ? 1 : 0)) & 0xFF == 0)
state.n = (highNybble & 0x08 != 0)
state.v = ((((highNybble << 4) ^ state.a) & 0x80) != 0 && ((state.a ^ value) & 0x80) == 0)
if highNybble > 9 {
highNybble = highNybble &+ 6
}
state.c = (highNybble > 0x0F)
state.a = (highNybble << 4) | (lowNybble & 0x0F)
} else {
let tempA = UInt16(state.a)
let sum = (tempA + UInt16(value) + (state.c ? 1 : 0))
state.c = (sum > 0xFF)
state.v = (((tempA ^ UInt16(value)) & 0x80) == 0 && ((tempA ^ sum) & 0x80) != 0)
loadA(UInt8(truncatingBitPattern: sum))
}
}
private func adcImmediate() {
state.data = memory.readByte(state.pc++)
adc(state.data)
state.cycle = 0
}
private func adcZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
adc(state.data)
state.cycle = 0
}
private func adcPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
adc(state.data)
state.cycle = 0
}
}
private func adcAbsolute() {
state.data = memory.readByte(address)
adc(state.data)
state.cycle = 0
}
//MARK: ALR*
private func alrImmediate() {
state.data = memory.readByte(state.pc++)
let a = state.a & state.data
state.c = ((a & 1) != 0)
loadA(a >> 1)
state.cycle = 0
}
//MARK: ANC*
private func ancImmediate() {
state.data = memory.readByte(state.pc++)
loadA(state.a & state.data)
state.c = state.n
state.cycle = 0
}
//MARK: AND
private func andImmediate() {
state.data = memory.readByte(state.pc++)
loadA(state.a & state.data)
state.cycle = 0
}
private func andZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
loadA(state.a & state.data)
state.cycle = 0
}
private func andPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadA(state.a & state.data)
state.cycle = 0
}
}
private func andAbsolute() {
state.data = memory.readByte(address)
loadA(state.a & state.data)
state.cycle = 0
}
//MARK: ASL
private func aslAccumulator() {
memory.readByte(state.pc)
state.c = ((state.a & 0x80) != 0)
loadA(state.a << 1)
state.cycle = 0
}
private func aslZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.c = ((state.data & 0x80) != 0)
state.data = state.data << 1
}
private func aslAbsolute() {
memory.writeByte(address, byte: state.data)
state.c = ((state.data & 0x80) != 0)
state.data = state.data << 1
}
//MARK: BCC
private func branch() {
memory.readByte(state.pc)
let oldPch = pch
state.pc = state.pc &+ Int8(bitPattern: state.data)
if pch == oldPch {
//TODO: delay IRQs
state.cycle = 0
}
}
private func branchOverflow() {
if state.data & 0x80 != 0 {
memory.readByte(state.pc &+ UInt16(0x100))
} else {
memory.readByte(state.pc &- UInt16(0x100))
}
state.cycle = 0
}
private func bccRelative() {
state.data = memory.readByte(state.pc++)
if state.c {
state.cycle = 0
}
}
//MARK: BCS
private func bcsRelative() {
state.data = memory.readByte(state.pc++)
if !state.c {
state.cycle = 0
}
}
//MARK: BEQ
private func beqRelative() {
state.data = memory.readByte(state.pc++)
if !state.z {
state.cycle = 0
}
}
//MARK: BIT
private func bitZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
state.n = ((state.data & 128) != 0)
state.v = ((state.data & 64) != 0)
state.z = ((state.data & state.a) == 0)
state.cycle = 0
}
private func bitAbsolute() {
state.data = memory.readByte(address)
state.n = ((state.data & 128) != 0)
state.v = ((state.data & 64) != 0)
state.z = ((state.data & state.a) == 0)
state.cycle = 0
}
//MARK: BMI
private func bmiRelative() {
state.data = memory.readByte(state.pc++)
if !state.n {
state.cycle = 0
}
}
//MARK: BNE
private func bneRelative() {
state.data = memory.readByte(state.pc++)
if state.z {
state.cycle = 0
}
}
//MARK: BPL
private func bplRelative() {
state.data = memory.readByte(state.pc++)
if state.n {
state.cycle = 0
}
}
//MARK: BRK
private func brkImplied() {
state.b = true
pushPch()
}
private func brkImplied2() {
pushPcl()
//TODO: handle NMI during BRK here
}
private func brkImplied3() {
let p = UInt8((state.c ? 0x01 : 0) |
(state.z ? 0x02 : 0) |
(state.i ? 0x04 : 0) |
(state.d ? 0x08 : 0) |
(state.b ? 0x10 : 0) |
0x20 |
(state.v ? 0x40 : 0) |
(state.n ? 0x80 : 0))
memory.writeByte(0x100 &+ state.sp, byte: p)
state.sp = state.sp &- 1
}
private func brkImplied4() {
state.data = memory.readByte(0xFFFE)
}
private func brkImplied5() {
pcl = state.data
pch = memory.readByte(0xFFFF)
state.i = true
state.cycle = 0
}
//MARK: BVC
private func bvcRelative() {
state.data = memory.readByte(state.pc++)
if state.v {
state.cycle = 0
}
}
//MARK: BVS
private func bvsRelative() {
state.data = memory.readByte(state.pc++)
if !state.v {
state.cycle = 0
}
}
//MARK: CLC
private func clcImplied() {
memory.readByte(state.pc)
state.c = false
state.cycle = 0
}
//MARK: CLD
private func cldImplied() {
memory.readByte(state.pc)
state.d = false
state.cycle = 0
}
//MARK: CLI
private func cliImplied() {
memory.readByte(state.pc)
state.i = false
state.cycle = 0
}
//MARK: CLV
private func clvImplied() {
memory.readByte(state.pc)
state.v = false
state.cycle = 0
}
//MARK: CMP
private func cmp(value1: UInt8, _ value2: UInt8) {
let diff = value1 &- value2
state.z = (diff == 0)
state.n = (diff & 0x80 != 0)
state.c = (value1 >= value2)
}
private func cmpImmediate() {
state.data = memory.readByte(state.pc++)
cmp(state.a, state.data)
state.cycle = 0
}
private func cmpZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
cmp(state.a, state.data)
state.cycle = 0
}
private func cmpAbsolute() {
state.data = memory.readByte(address)
cmp(state.a, state.data)
state.cycle = 0
}
private func cmpPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
cmp(state.a, state.data)
state.cycle = 0
}
}
//MARK: CPX
private func cpxImmediate() {
state.data = memory.readByte(state.pc++)
cmp(state.x, state.data)
state.cycle = 0
}
private func cpxZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
cmp(state.x, state.data)
state.cycle = 0
}
private func cpxAbsolute() {
state.data = memory.readByte(address)
cmp(state.x, state.data)
state.cycle = 0
}
//MARK: CPY
private func cpyImmediate() {
state.data = memory.readByte(state.pc++)
cmp(state.y, state.data)
state.cycle = 0
}
private func cpyZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
cmp(state.y, state.data)
state.cycle = 0
}
private func cpyAbsolute() {
state.data = memory.readByte(address)
cmp(state.y, state.data)
state.cycle = 0
}
//MARK: DEC
private func decZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.data = state.data &- 1
}
private func decAbsolute() {
memory.writeByte(address, byte: state.data)
state.data = state.data &- 1
}
//MARK: DEX
private func dexImplied() {
loadX(state.x &- 1)
state.cycle = 0
}
//MARK: DEY
private func deyImplied() {
loadY(state.y &- 1)
state.cycle = 0
}
//MARK: EOR
private func eorImmediate() {
state.data = memory.readByte(state.pc++)
loadA(state.a ^ state.data)
state.cycle = 0
}
private func eorZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
loadA(state.a ^ state.data)
state.cycle = 0
}
private func eorAbsolute() {
state.data = memory.readByte(address)
loadA(state.a ^ state.data)
state.cycle = 0
}
private func eorPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadA(state.a ^ state.data)
state.cycle = 0
}
}
//MARK: INC
private func incZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.data = state.data &+ 1
}
private func incAbsolute() {
memory.writeByte(address, byte: state.data)
state.data = state.data &+ 1
}
//MARK: INX
private func inxImplied() {
memory.readByte(state.pc)
loadX(state.x &+ 1)
state.cycle = 0
}
//MARK: INY
private func inyImplied() {
memory.readByte(state.pc)
loadY(state.y &+ 1)
state.cycle = 0
}
//MARK: JMP
private func jmpAbsolute() {
state.addressHigh = memory.readByte(state.pc)
state.pc = address
state.cycle = 0
}
private func jmpIndirect() {
pcl = state.data
state.addressLow = state.addressLow &+ 1
pch = memory.readByte(address)
state.cycle = 0
}
//MARK: JSR
private func jsrAbsolute() {
state.addressHigh = memory.readByte(state.pc)
state.pc = address
state.cycle = 0
}
//MARK: LAX
private func laxAbsolute() {
state.data = memory.readByte(address)
loadA(state.data)
loadX(state.data)
state.cycle = 0
}
//MARK: LDA
private func ldaImmediate() {
loadA(memory.readByte(state.pc++))
state.cycle = 0
}
private func ldaZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
loadA(state.data)
state.cycle = 0
}
private func ldaAbsolute() {
state.data = memory.readByte(address)
loadA(state.data)
state.cycle = 0
}
private func ldaPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadA(state.data)
state.cycle = 0
}
}
//MARK: LDX
private func ldxImmediate() {
loadX(memory.readByte(state.pc++))
state.cycle = 0
}
private func ldxZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
loadX(state.data)
state.cycle = 0
}
private func ldxAbsolute() {
state.data = memory.readByte(address)
loadX(state.data)
state.cycle = 0
}
private func ldxPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadX(state.data)
state.cycle = 0
}
}
//MARK: LDY
private func ldyImmediate() {
loadY(memory.readByte(state.pc++))
state.cycle = 0
}
private func ldyZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
loadY(state.data)
state.cycle = 0
}
private func ldyAbsolute() {
state.data = memory.readByte(address)
loadY(state.data)
state.cycle = 0
}
private func ldyPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadY(state.data)
state.cycle = 0
}
}
//MARK: LSR
private func lsrAccumulator() {
memory.readByte(state.pc)
state.c = ((state.a & 1) != 0)
loadA(state.a >> 1)
state.cycle = 0
}
private func lsrZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.c = ((state.data & 1) != 0)
state.data = state.data >> 1
}
private func lsrAbsolute() {
memory.writeByte(address, byte: state.data)
state.c = ((state.data & 1) != 0)
state.data = state.data >> 1
}
//MARK: NOP
private func nop() {
memory.readByte(state.pc)
state.cycle = 0
}
private func nopZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
state.cycle = 0
}
private func nopImmediate() {
state.data = memory.readByte(state.pc++)
state.cycle = 0
}
//MARK: ORA
private func oraImmediate() {
state.data = memory.readByte(state.pc++)
loadA(state.a | state.data)
state.cycle = 0
}
private func oraZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
loadA(state.a | state.data)
state.cycle = 0
}
private func oraPageBoundary() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadA(state.a | state.data)
state.cycle = 0
}
}
private func oraAbsolute() {
state.data = memory.readByte(address)
loadA(state.a | state.data)
state.cycle = 0
}
//MARK: PHA
private func phaImplied() {
memory.writeByte(0x100 &+ state.sp, byte: state.a)
state.sp = state.sp &- 1
state.cycle = 0
}
//MARK: PHP
private func phpImplied() {
let p = UInt8((state.c ? 0x01 : 0) |
(state.z ? 0x02 : 0) |
(state.i ? 0x04 : 0) |
(state.d ? 0x08 : 0) |
(state.b ? 0x10 : 0) |
0x20 |
(state.v ? 0x40 : 0) |
(state.n ? 0x80 : 0))
memory.writeByte(0x100 &+ state.sp, byte: p)
state.sp = state.sp &- 1
state.cycle = 0
}
//MARK: PLA
private func plaImplied() {
loadA(memory.readByte(0x100 &+ state.sp))
state.cycle = 0
}
//MARK: PLP
private func plpImplied() {
let p = memory.readByte(0x100 &+ state.sp)
state.c = ((p & 0x01) != 0)
state.z = ((p & 0x02) != 0)
state.i = ((p & 0x04) != 0)
state.d = ((p & 0x08) != 0)
state.v = ((p & 0x40) != 0)
state.n = ((p & 0x80) != 0)
state.cycle = 0
}
//MARK: ROL
private func rolAccumulator() {
memory.readByte(state.pc)
let hasCarry = state.c
state.c = ((state.a & 0x80) != 0)
loadA((state.a << 1) + (hasCarry ? 1 : 0))
state.cycle = 0
}
private func rolZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
let hasCarry = state.c
state.c = ((state.data & 0x80) != 0)
state.data = (state.data << 1) + (hasCarry ? 1 : 0)
}
private func rolAbsolute() {
memory.writeByte(address, byte: state.data)
let hasCarry = state.c
state.c = ((state.data & 0x80) != 0)
state.data = (state.data << 1) + (hasCarry ? 1 : 0)
}
//MARK: ROR
private func rorAccumulator() {
memory.readByte(state.pc)
let hasCarry = state.c
state.c = ((state.a & 1) != 0)
loadA((state.a >> 1) + (hasCarry ? 0x80 : 0))
state.cycle = 0
}
private func rorZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
let hasCarry = state.c
state.c = ((state.data & 1) != 0)
state.data = (state.data >> 1) + (hasCarry ? 0x80 : 0)
}
private func rorAbsolute() {
memory.writeByte(address, byte: state.data)
let hasCarry = state.c
state.c = ((state.data & 1) != 0)
state.data = (state.data >> 1) + (hasCarry ? 0x80 : 0)
}
//MARK: RTI
private func rtiImplied() {
let p = memory.readByte(0x100 &+ state.sp)
state.c = (p & 0x01 != 0)
state.z = (p & 0x02 != 0)
state.i = (p & 0x04 != 0)
state.d = (p & 0x08 != 0)
state.v = (p & 0x40 != 0)
state.n = (p & 0x80 != 0)
state.sp = state.sp &+ 1
}
private func rtiImplied2() {
pcl = memory.readByte(0x100 &+ state.sp)
state.sp = state.sp &+ 1
}
private func rtiImplied3() {
pch = memory.readByte(0x100 &+ state.sp)
state.cycle = 0
}
//MARK: RTS
private func rtsImplied() {
pcl = memory.readByte(0x100 &+ state.sp)
state.sp = state.sp &+ 1
}
private func rtsImplied2() {
pch = memory.readByte(0x100 &+ state.sp)
}
private func rtsImplied3() {
++state.pc
state.cycle = 0
}
//MARK: SBC
private func sbc(value: UInt8) {
if state.d {
let tempA = UInt16(state.a)
let sum = (tempA &- UInt16(value) &- (state.c ? 0 : 1))
var lowNybble = (state.a & 0x0F) &- (value & 0x0F) &- (state.c ? 0 : 1)
var highNybble = (state.a >> 4) &- (value >> 4)
if lowNybble & 0x10 != 0 {
lowNybble = lowNybble &- 6
highNybble = highNybble &- 1
}
if highNybble & 0x10 != 0 {
highNybble = highNybble &- 6
}
state.c = (sum < 0x100)
state.v = (((tempA ^ sum) & 0x80) != 0 && ((tempA ^ UInt16(value)) & 0x80) != 0)
state.z = (UInt8(truncatingBitPattern: sum) == 0)
state.n = (sum & 0x80 != 0)
state.a = (highNybble << 4) | (lowNybble & 0x0F)
} else {
let tempA = UInt16(state.a)
let sum = (tempA &- UInt16(value) &- (state.c ? 0 : 1))
state.c = (sum <= 0xFF)
state.v = (((UInt16(state.a) ^ sum) & 0x80) != 0 && ((UInt16(state.a) ^ UInt16(value)) & 0x80) != 0)
loadA(UInt8(truncatingBitPattern: sum))
}
}
private func sbcImmediate() {
state.data = memory.readByte(state.pc++)
sbc(state.data)
state.cycle = 0
}
private func sbcZeroPage() {
state.data = memory.readByte(UInt16(state.addressLow))
sbc(state.data)
state.cycle = 0
}
private func sbcAbsolute() {
state.data = memory.readByte(address)
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
sbc(state.data)
state.cycle = 0
}
}
private func sbcAbsolute2() {
state.data = memory.readByte(address)
sbc(state.data)
state.cycle = 0
}
//MARK: SEC
private func secImplied() {
memory.readByte(state.pc)
state.c = true
state.cycle = 0
}
//MARK: SED
private func sedImplied() {
memory.readByte(state.pc)
state.d = true
state.cycle = 0
}
//MARK: SEI
private func seiImplied() {
memory.readByte(state.pc)
state.i = true
state.cycle = 0
}
//MARK: STA
private func staZeroPage() {
state.data = state.a
memory.writeByte(UInt16(state.addressLow), byte: state.a)
state.cycle = 0
}
private func staAbsolute() {
state.data = state.a
memory.writeByte(address, byte: state.data)
state.cycle = 0
}
//MARK: STX
private func stxZeroPage() {
state.data = state.x
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.cycle = 0
}
private func stxAbsolute() {
state.data = state.x
memory.writeByte(address, byte: state.data)
state.cycle = 0
}
//MARK: STY
private func styZeroPage() {
state.data = state.y
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.cycle = 0
}
private func styAbsolute() {
state.data = state.y
memory.writeByte(address, byte: state.data)
state.cycle = 0
}
//MARK: TAX
private func taxImplied() {
memory.readByte(state.pc)
loadX(state.a)
state.cycle = 0
}
//MARK: TAY
private func tayImplied() {
memory.readByte(state.pc)
loadY(state.a)
state.cycle = 0
}
//MARK: TSX
private func tsxImplied() {
memory.readByte(state.pc)
loadX(state.sp)
state.cycle = 0
}
//MARK: TXA
private func txaImplied() {
memory.readByte(state.pc)
loadA(state.x)
state.cycle = 0
}
//MARK: TXS
private func txsImplied() {
memory.readByte(state.pc)
state.sp = state.x
state.cycle = 0
}
//MARK: TYA
private func tyaImplied() {
memory.readByte(state.pc)
loadA(state.y)
state.cycle = 0
}
}
|
//
// KVObserver.swift
// Anna_iOS
//
// Created by William on 2018/5/3.
//
import Foundation
class
KeyPathsObserver<Observee> : NSObject
where Observee : NSObject
{
let
keyPaths :[String: NSKeyValueObservingOptions]
weak var
observee :Observee?
init(
keyPaths :[String: NSKeyValueObservingOptions],
observee :Observee
) {
self.keyPaths = keyPaths
self.observee = observee
}
deinit {
self.detach()
}
func
observe(_ observee :Observee) {
for (keyPath, options) in self.keyPaths {
observee.addObserver(
self,
forKeyPath: keyPath,
options: options,
context: nil
)
}
}
func
deobserve(_ observee :Observee) {
for (keyPath, _) in self.keyPaths {
observee.removeObserver(
self,
forKeyPath: keyPath
)
}
}
func
detach() {
if let observee = self.observeeBeingDeobserved() {
self.deobserve(observee)
self.observee = nil
}
}
func
observeeBeingDeobserved() -> Observee? {
return self.observee
}
override func
observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?
) { }
}
class
ReportingObserver<Observee> : KeyPathsObserver<Observee>, Reporting
where Observee : NSObject
{
weak var
recorder: Reporting.Recorder? {
willSet {
guard let observee = self.observee else { return }
if let _ = self.recorder {
self.deobserve(observee)
}
}
didSet {
guard let observee = self.observee else { return }
if let _ = self.recorder {
self.observe(observee)
}
}
}
override func
detach() {
super.detach()
self.recorder = nil
}
}
class
KVObserver<Observee> : ReportingObserver<Observee>
where Observee : NSObject
{
init(
keyPath :String,
observee :Observee
) {
super.init(
keyPaths: [keyPath: [.initial, .new, .old]],
observee: observee
)
}
override func
observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?
) {
guard
keyPath == self.keyPaths.first?.key
else {
return super.observeValue(
forKeyPath: keyPath,
of: object,
change: change,
context: context
)
}
guard
let
keyPath = keyPath,
let
change = change,
let
after = change[.newKey]
else { return }
let
name = "ana-updated"
let
properties = [
"key-path" : keyPath,
"value" : after
]
guard let before = change[.oldKey] else {
self.recorder?.recordEvent(
named: name,
with: properties
)
return
}
if
let before = before as? NSObject,
let after = after as? NSObject,
before == after
{ return }
self.recorder?.recordEvent(
named: name,
with: properties
)
}
}
recovered it to use NSValue to remove observations to owner
//
// KVObserver.swift
// Anna_iOS
//
// Created by William on 2018/5/3.
//
import Foundation
class
KeyPathsObserver<Observee> : NSObject
where Observee : NSObject
{
let
keyPaths :[String: NSKeyValueObservingOptions],
observeeRef :NSValue
var
isObserving = false
var
observee :Observee {
return self.observeeRef.nonretainedObjectValue as! Observee
}
init(
keyPaths :[String: NSKeyValueObservingOptions],
observee :Observee
) {
self.keyPaths = keyPaths
self.observeeRef = NSValue(nonretainedObject: observee)
}
deinit {
self.detach()
}
func
observe(_ observee :Observee) {
guard self.isObserving == false else { return }
self.isObserving = true
for (keyPath, options) in self.keyPaths {
observee.addObserver(
self,
forKeyPath: keyPath,
options: options,
context: nil
)
}
}
func
deobserve(_ observee :Observee) {
guard self.isObserving else { return }
for (keyPath, _) in self.keyPaths {
observee.removeObserver(
self,
forKeyPath: keyPath
)
}
self.isObserving = false
}
func
detach() {
let observee = self.observee
self.deobserve(observee)
}
override func
observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?
) { }
}
class
ReportingObserver<Observee> : KeyPathsObserver<Observee>, Reporting
where Observee : NSObject
{
weak var
recorder: Reporting.Recorder? {
willSet {
let observee = self.observee
if let _ = self.recorder {
self.deobserve(observee)
}
}
didSet {
let observee = self.observee
if let _ = self.recorder {
self.observe(observee)
}
}
}
override func
detach() {
super.detach()
self.recorder = nil
}
}
class
KVObserver<Observee> : ReportingObserver<Observee>
where Observee : NSObject
{
init(
keyPath :String,
observee :Observee
) {
super.init(
keyPaths: [keyPath: [.initial, .new, .old]],
observee: observee
)
}
override func
observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?
) {
guard
keyPath == self.keyPaths.first?.key
else {
return super.observeValue(
forKeyPath: keyPath,
of: object,
change: change,
context: context
)
}
guard
let
keyPath = keyPath,
let
change = change,
let
after = change[.newKey]
else { return }
let
name = "ana-updated"
let
properties = [
"key-path" : keyPath,
"value" : after
]
guard let before = change[.oldKey] else {
self.recorder?.recordEvent(
named: name,
with: properties
)
return
}
if
let before = before as? NSObject,
let after = after as? NSObject,
before == after
{ return }
self.recorder?.recordEvent(
named: name,
with: properties
)
}
}
|
import UIKit
func addTransformAnimation(_ animation: BasicAnimation, sceneLayer: CALayer, animationCache: AnimationCache, completion: @escaping (() -> ())) {
guard let transformAnimation = animation as? TransformAnimation else {
return
}
guard let node = animation.node else {
return
}
// Creating proper animation
var generatedAnimation: CAAnimation?
generatedAnimation = transformAnimationByFunc(node, valueFunc: transformAnimation.getVFunc(), duration: animation.getDuration(), fps: transformAnimation.logicalFps)
guard let generatedAnim = generatedAnimation else {
return
}
generatedAnim.autoreverses = animation.autoreverses
generatedAnim.repeatCount = Float(animation.repeatCount)
generatedAnim.timingFunction = caTimingFunction(animation.easing)
generatedAnim.completion = { finished in
if !animation.manualStop {
animation.progress = 1.0
node.placeVar.value = transformAnimation.getVFunc()(1.0)
} else {
node.placeVar.value = transformAnimation.getVFunc()(animation.progress)
}
animationCache.freeLayer(node)
animation.completion?()
if !finished {
animationRestorer.addRestoreClosure(completion)
return
}
completion()
}
generatedAnim.progress = { progress in
let t = Double(progress)
node.placeVar.value = transformAnimation.getVFunc()(t)
animation.progress = t
animation.onProgressUpdate?(t)
}
let layer = animationCache.layerForNode(node, animation: animation)
layer.add(generatedAnim, forKey: animation.ID)
animation.removeFunc = {
layer.removeAnimation(forKey: animation.ID)
}
}
func transfomToCG(_ transform: Transform) -> CGAffineTransform {
return CGAffineTransform(
a: CGFloat(transform.m11),
b: CGFloat(transform.m12),
c: CGFloat(transform.m21),
d: CGFloat(transform.m22),
tx: CGFloat(transform.dx),
ty: CGFloat(transform.dy))
}
func transformAnimationByFunc(_ node: Node, valueFunc: (Double) -> Transform, duration: Double, fps: UInt) -> CAAnimation {
var scaleXValues = [CGFloat]()
var scaleYValues = [CGFloat]()
var xValues = [CGFloat]()
var yValues = [CGFloat]()
var rotationValues = [CGFloat]()
var timeValues = [Double]()
let step = 1.0 / (duration * Double(fps))
var dt = 0.0
var tValue = Array(stride(from: 0.0, to: 1.0, by: step))
tValue.append(1.0)
for t in tValue {
dt = t
if 1.0 - dt < step {
dt = 1.0
}
let value = AnimationUtils.absoluteTransform(node, pos: valueFunc(dt))
let dx = value.dx
let dy = value.dy
let a = value.m11
let b = value.m12
let c = value.m21
let d = value.m22
let sx = a / fabs(a) * sqrt(a * a + b * b)
let sy = d / fabs(d) * sqrt(c * c + d * d)
let angle = atan2(b, a)
timeValues.append(dt)
xValues.append(CGFloat(dx))
yValues.append(CGFloat(dy))
scaleXValues.append(CGFloat(sx))
scaleYValues.append(CGFloat(sy))
rotationValues.append(CGFloat(angle))
}
let xAnimation = CAKeyframeAnimation(keyPath: "transform.translation.x")
xAnimation.duration = duration
xAnimation.values = xValues
xAnimation.keyTimes = timeValues as [NSNumber]?
let yAnimation = CAKeyframeAnimation(keyPath: "transform.translation.y")
yAnimation.duration = duration
yAnimation.values = yValues
yAnimation.keyTimes = timeValues as [NSNumber]?
let scaleXAnimation = CAKeyframeAnimation(keyPath: "transform.scale.x")
scaleXAnimation.duration = duration
scaleXAnimation.values = scaleXValues
scaleXAnimation.keyTimes = timeValues as [NSNumber]?
let scaleYAnimation = CAKeyframeAnimation(keyPath: "transform.scale.y")
scaleYAnimation.duration = duration
scaleYAnimation.values = scaleYValues
scaleYAnimation.keyTimes = timeValues as [NSNumber]?
let rotationAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotationAnimation.duration = duration
rotationAnimation.values = rotationValues
rotationAnimation.keyTimes = timeValues as [NSNumber]?
let group = CAAnimationGroup()
group.fillMode = kCAFillModeForwards
group.isRemovedOnCompletion = false
group.animations = [scaleXAnimation, scaleYAnimation, rotationAnimation, xAnimation, yAnimation]
group.duration = duration
return group
}
func fixedAngle(_ angle: CGFloat) -> CGFloat {
return angle > -0.0000000000000000000000001 ? angle : CGFloat(2.0 * M_PI) + angle
}
Proper transform animation generator implementation
import UIKit
func addTransformAnimation(_ animation: BasicAnimation, sceneLayer: CALayer, animationCache: AnimationCache, completion: @escaping (() -> ())) {
guard let transformAnimation = animation as? TransformAnimation else {
return
}
guard let node = animation.node else {
return
}
// Creating proper animation
var generatedAnimation: CAAnimation?
generatedAnimation = transformAnimationByFunc(node, valueFunc: transformAnimation.getVFunc(), duration: animation.getDuration(), fps: transformAnimation.logicalFps)
guard let generatedAnim = generatedAnimation else {
return
}
generatedAnim.autoreverses = animation.autoreverses
generatedAnim.repeatCount = Float(animation.repeatCount)
generatedAnim.timingFunction = caTimingFunction(animation.easing)
generatedAnim.completion = { finished in
if !animation.manualStop {
animation.progress = 1.0
node.placeVar.value = transformAnimation.getVFunc()(1.0)
} else {
node.placeVar.value = transformAnimation.getVFunc()(animation.progress)
}
animationCache.freeLayer(node)
animation.completion?()
if !finished {
animationRestorer.addRestoreClosure(completion)
return
}
completion()
}
generatedAnim.progress = { progress in
let t = Double(progress)
node.placeVar.value = transformAnimation.getVFunc()(t)
animation.progress = t
animation.onProgressUpdate?(t)
}
let layer = animationCache.layerForNode(node, animation: animation)
layer.add(generatedAnim, forKey: animation.ID)
animation.removeFunc = {
layer.removeAnimation(forKey: animation.ID)
}
}
func transfomToCG(_ transform: Transform) -> CGAffineTransform {
return CGAffineTransform(
a: CGFloat(transform.m11),
b: CGFloat(transform.m12),
c: CGFloat(transform.m21),
d: CGFloat(transform.m22),
tx: CGFloat(transform.dx),
ty: CGFloat(transform.dy))
}
func transformAnimationByFunc(_ node: Node, valueFunc: (Double) -> Transform, duration: Double, fps: UInt) -> CAAnimation {
var transformValues = [CATransform3D]()
var timeValues = [Double]()
let step = 1.0 / (duration * Double(fps))
var dt = 0.0
var tValue = Array(stride(from: 0.0, to: 1.0, by: step))
tValue.append(1.0)
for t in tValue {
dt = t
if 1.0 - dt < step {
dt = 1.0
}
let value = AnimationUtils.absoluteTransform(node, pos: valueFunc(dt))
let cgValue = CATransform3DMakeAffineTransform(RenderUtils.mapTransform(value))
transformValues.append(cgValue)
}
let transformAnimation = CAKeyframeAnimation(keyPath: "transform")
transformAnimation.duration = duration
transformAnimation.values = transformValues
transformAnimation.keyTimes = timeValues as [NSNumber]?
transformAnimation.fillMode = kCAFillModeForwards
transformAnimation.isRemovedOnCompletion = false
return transformAnimation
}
func fixedAngle(_ angle: CGFloat) -> CGFloat {
return angle > -0.0000000000000000000000001 ? angle : CGFloat(2.0 * M_PI) + angle
}
|
// SocketClient.swift
// Copyright (c) 2022 FastlaneTools
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
import Dispatch
import Foundation
public enum SocketClientResponse: Error {
case alreadyClosedSockets
case malformedRequest
case malformedResponse
case serverError
case clientInitiatedCancelAcknowledged
case commandTimeout(seconds: Int)
case connectionFailure
case success(returnedObject: String?, closureArgumentValue: String?)
}
class SocketClient: NSObject {
enum SocketStatus {
case ready
case closed
}
static let connectTimeoutSeconds = 2
static let defaultCommandTimeoutSeconds = 10800 // 3 hours
static let doneToken = "done" // TODO: remove these
static let cancelToken = "cancelFastlaneRun"
fileprivate var inputStream: InputStream!
fileprivate var outputStream: OutputStream!
fileprivate var cleaningUpAfterDone = false
fileprivate let dispatchGroup = DispatchGroup()
fileprivate let readSemaphore = DispatchSemaphore(value: 1)
fileprivate let writeSemaphore = DispatchSemaphore(value: 1)
fileprivate let commandTimeoutSeconds: Int
private let writeQueue: DispatchQueue
private let readQueue: DispatchQueue
private let streamQueue: DispatchQueue
private let host: String
private let port: UInt32
let maxReadLength = 65536 // max for ipc on 10.12 is kern.ipc.maxsockbuf: 8388608 ($sysctl kern.ipc.maxsockbuf)
private(set) weak var socketDelegate: SocketClientDelegateProtocol?
public private(set) var socketStatus: SocketStatus
// localhost only, this prevents other computers from connecting
init(host: String = "localhost", port: UInt32 = 2000, commandTimeoutSeconds: Int = defaultCommandTimeoutSeconds, socketDelegate: SocketClientDelegateProtocol) {
self.host = host
self.port = port
self.commandTimeoutSeconds = commandTimeoutSeconds
readQueue = DispatchQueue(label: "readQueue", qos: .background, attributes: .concurrent)
writeQueue = DispatchQueue(label: "writeQueue", qos: .background, attributes: .concurrent)
streamQueue = DispatchQueue.global(qos: .background)
socketStatus = .closed
self.socketDelegate = socketDelegate
super.init()
}
func connectAndOpenStreams() {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
streamQueue.sync {
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, self.host as CFString, self.port, &readStream, &writeStream)
self.inputStream = readStream!.takeRetainedValue()
self.outputStream = writeStream!.takeRetainedValue()
self.inputStream.delegate = self
self.outputStream.delegate = self
self.inputStream.schedule(in: .main, forMode: .defaultRunLoopMode)
self.outputStream.schedule(in: .main, forMode: .defaultRunLoopMode)
}
dispatchGroup.enter()
readQueue.sync {
self.inputStream.open()
}
dispatchGroup.enter()
writeQueue.sync {
self.outputStream.open()
}
let secondsToWait = DispatchTimeInterval.seconds(SocketClient.connectTimeoutSeconds)
let connectTimeout = DispatchTime.now() + secondsToWait
let timeoutResult = dispatchGroup.wait(timeout: connectTimeout)
let failureMessage = "Couldn't connect to ruby process within: \(SocketClient.connectTimeoutSeconds) seconds"
let success = testDispatchTimeoutResult(timeoutResult, failureMessage: failureMessage, timeToWait: secondsToWait)
guard success else {
socketDelegate?.commandExecuted(serverResponse: .connectionFailure) { _ in }
return
}
socketStatus = .ready
socketDelegate?.connectionsOpened()
}
public func send(rubyCommand: RubyCommandable) {
verbose(message: "sending: \(rubyCommand.json)")
send(string: rubyCommand.json)
writeSemaphore.signal()
}
public func sendComplete() {
closeSession(sendAbort: true)
}
private func testDispatchTimeoutResult(_ timeoutResult: DispatchTimeoutResult, failureMessage: String, timeToWait: DispatchTimeInterval) -> Bool {
switch timeoutResult {
case .success:
return true
case .timedOut:
log(message: "Timeout: \(failureMessage)")
if case let .seconds(seconds) = timeToWait {
socketDelegate?.commandExecuted(serverResponse: .commandTimeout(seconds: seconds)) { _ in }
}
return false
}
}
private func stopInputSession() {
inputStream.close()
}
private func stopOutputSession() {
outputStream.close()
}
private func sendThroughQueue(string: String) {
let data = string.data(using: .utf8)!
data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
if let buffer = buffer.baseAddress {
self.outputStream.write(buffer.assumingMemoryBound(to: UInt8.self), maxLength: data.count)
}
}
}
private func privateSend(string: String) {
writeQueue.sync {
writeSemaphore.wait()
self.sendThroughQueue(string: string)
writeSemaphore.signal()
let timeoutSeconds = self.cleaningUpAfterDone ? 1 : self.commandTimeoutSeconds
let timeToWait = DispatchTimeInterval.seconds(timeoutSeconds)
let commandTimeout = DispatchTime.now() + timeToWait
let timeoutResult = writeSemaphore.wait(timeout: commandTimeout)
_ = self.testDispatchTimeoutResult(timeoutResult, failureMessage: "Ruby process didn't return after: \(SocketClient.connectTimeoutSeconds) seconds", timeToWait: timeToWait)
}
}
private func send(string: String) {
guard !cleaningUpAfterDone else {
// This will happen after we abort if there are commands waiting to be executed
// Need to check state of SocketClient in command runner to make sure we can accept `send`
socketDelegate?.commandExecuted(serverResponse: .alreadyClosedSockets) { _ in }
return
}
if string == SocketClient.doneToken {
cleaningUpAfterDone = true
}
privateSend(string: string)
}
func closeSession(sendAbort: Bool = true) {
socketStatus = .closed
stopInputSession()
if sendAbort {
send(rubyCommand: ControlCommand(commandType: .done))
}
stopOutputSession()
socketDelegate?.connectionsClosed()
}
public func enter() {
dispatchGroup.enter()
}
public func leave() {
readSemaphore.signal()
writeSemaphore.signal()
}
}
extension SocketClient: StreamDelegate {
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
guard !cleaningUpAfterDone else {
// Still getting response from server even though we are done.
// No big deal, we're closing the streams anyway.
// That being said, we need to balance out the dispatchGroups
dispatchGroup.leave()
return
}
if aStream === inputStream {
switch eventCode {
case Stream.Event.openCompleted:
dispatchGroup.leave()
case Stream.Event.errorOccurred:
verbose(message: "input stream error occurred")
closeSession(sendAbort: true)
case Stream.Event.hasBytesAvailable:
read()
case Stream.Event.endEncountered:
// nothing special here
break
case Stream.Event.hasSpaceAvailable:
// we don't care about this
break
default:
verbose(message: "input stream caused unrecognized event: \(eventCode)")
}
} else if aStream === outputStream {
switch eventCode {
case Stream.Event.openCompleted:
dispatchGroup.leave()
case Stream.Event.errorOccurred:
// probably safe to close all the things because Ruby already disconnected
verbose(message: "output stream received error")
case Stream.Event.endEncountered:
// nothing special here
break
case Stream.Event.hasSpaceAvailable:
// we don't care about this
break
default:
verbose(message: "output stream caused unrecognized event: \(eventCode)")
}
}
}
func read() {
readQueue.sync {
self.readSemaphore.wait()
var buffer = [UInt8](repeating: 0, count: maxReadLength)
var output = ""
while self.inputStream!.hasBytesAvailable {
let bytesRead: Int = inputStream!.read(&buffer, maxLength: buffer.count)
if bytesRead >= 0 {
guard let read = String(bytes: buffer[..<bytesRead], encoding: .utf8) else {
fatalError("Unable to decode bytes from buffer \(buffer[..<bytesRead])")
}
output.append(contentsOf: read)
} else {
verbose(message: "Stream read() error")
}
}
self.processResponse(string: output)
readSemaphore.signal()
}
}
func handleFailure(message: [String]) {
log(message: "Encountered a problem: \(message.joined(separator: "\n"))")
let shutdownCommand = ControlCommand(commandType: .cancel(cancelReason: .serverError))
send(rubyCommand: shutdownCommand)
}
func processResponse(string: String) {
guard !string.isEmpty else {
socketDelegate?.commandExecuted(serverResponse: .malformedResponse) {
self.handleFailure(message: ["empty response from ruby process"])
$0.writeSemaphore.signal()
}
return
}
let responseString = string.trimmingCharacters(in: .whitespacesAndNewlines)
let socketResponse = SocketResponse(payload: responseString)
verbose(message: "response is: \(responseString)")
switch socketResponse.responseType {
case .clientInitiatedCancel:
socketDelegate?.commandExecuted(serverResponse: .clientInitiatedCancelAcknowledged) {
$0.writeSemaphore.signal()
self.closeSession(sendAbort: false)
}
case let .failure(failureInformation, failureClass, failureMessage):
LaneFile.fastfileInstance?.onError(currentLane: ArgumentProcessor(args: CommandLine.arguments).currentLane, errorInfo: failureInformation.joined(), errorClass: failureClass, errorMessage: failureMessage)
socketDelegate?.commandExecuted(serverResponse: .serverError) {
$0.writeSemaphore.signal()
self.handleFailure(message: failureInformation)
}
case let .parseFailure(failureInformation):
socketDelegate?.commandExecuted(serverResponse: .malformedResponse) {
$0.writeSemaphore.signal()
self.handleFailure(message: failureInformation)
}
case let .readyForNext(returnedObject, closureArgumentValue):
socketDelegate?.commandExecuted(serverResponse: .success(returnedObject: returnedObject, closureArgumentValue: closureArgumentValue)) {
$0.writeSemaphore.signal()
}
}
}
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.2]
Show http error message from AppStore (#20397)
Currently, Fastlane swift only shows a ruby stacktrace when a http error message rises, which is useless:
```
FastlaneCore::Interface::FastlaneError:
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane_core/lib/fastlane_core/ui/interface.rb:141:in `user_error!'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane_core/lib/fastlane_core/ui/ui.rb:17:in `method_missing'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/pilot/lib/pilot/build_manager.rb:19:in `upload'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/actions/upload_to_testflight.rb:34:in `run'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/runner.rb:263:in `block (2 levels) in execute_action'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/actions/actions_helper.rb:69:in `execute_action'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/runner.rb:255:in `block in execute_action'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/runner.rb:229:in `chdir'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/runner.rb:229:in `execute_action'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/server/socket_server_action_command_executor.rb:73:in `run'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/server/socket_server_action_command_executor.rb:42:in `execute'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/server/socket_server.rb:181:in `execute_action_command'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/server/socket_server.rb:176:in `process_action_command'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/server/socket_server.rb:123:in `handle_action_command'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/server/socket_server.rb:86:in `parse_and_execute_command'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/server/socket_server.rb:62:in `block in receive_and_process_commands'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/server/socket_server.rb:49:in `loop'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/server/socket_server.rb:49:in `receive_and_process_commands'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/server/socket_server.rb:158:in `listen'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/server/socket_server.rb:38:in `start'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/commands_generator.rb:167:in `block (2 levels) in run'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/commander-4.6.0/lib/commander/command.rb:187:in `call'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/commander-4.6.0/lib/commander/command.rb:157:in `run'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/commander-4.6.0/lib/commander/runner.rb:444:in `run_active_command'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane_core/lib/fastlane_core/ui/fastlane_runner.rb:124:in `run!'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/commander-4.6.0/lib/commander/delegates.rb:18:in `run!'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/commands_generator.rb:354:in `run'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/commands_generator.rb:43:in `start'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/fastlane/lib/fastlane/cli_tools_distributor.rb:123:in `take_off'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/gems/fastlane-2.206.2/bin/fastlane:23:in `<top (required)>'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/bin/fastlane:25:in `load'
/Users/julian/.brew/Cellar/fastlane/2.206.2/libexec/bin/fastlane:25:in `<main>'
[1655712352.5108628]: Done running lane: deliverAppStore 🚀
```
With this change, the important http message "No ipa or pkg file given" is added to the beginning of the error output, too.
// SocketClient.swift
// Copyright (c) 2022 FastlaneTools
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
import Dispatch
import Foundation
public enum SocketClientResponse: Error {
case alreadyClosedSockets
case malformedRequest
case malformedResponse
case serverError
case clientInitiatedCancelAcknowledged
case commandTimeout(seconds: Int)
case connectionFailure
case success(returnedObject: String?, closureArgumentValue: String?)
}
class SocketClient: NSObject {
enum SocketStatus {
case ready
case closed
}
static let connectTimeoutSeconds = 2
static let defaultCommandTimeoutSeconds = 10800 // 3 hours
static let doneToken = "done" // TODO: remove these
static let cancelToken = "cancelFastlaneRun"
fileprivate var inputStream: InputStream!
fileprivate var outputStream: OutputStream!
fileprivate var cleaningUpAfterDone = false
fileprivate let dispatchGroup = DispatchGroup()
fileprivate let readSemaphore = DispatchSemaphore(value: 1)
fileprivate let writeSemaphore = DispatchSemaphore(value: 1)
fileprivate let commandTimeoutSeconds: Int
private let writeQueue: DispatchQueue
private let readQueue: DispatchQueue
private let streamQueue: DispatchQueue
private let host: String
private let port: UInt32
let maxReadLength = 65536 // max for ipc on 10.12 is kern.ipc.maxsockbuf: 8388608 ($sysctl kern.ipc.maxsockbuf)
private(set) weak var socketDelegate: SocketClientDelegateProtocol?
public private(set) var socketStatus: SocketStatus
// localhost only, this prevents other computers from connecting
init(host: String = "localhost", port: UInt32 = 2000, commandTimeoutSeconds: Int = defaultCommandTimeoutSeconds, socketDelegate: SocketClientDelegateProtocol) {
self.host = host
self.port = port
self.commandTimeoutSeconds = commandTimeoutSeconds
readQueue = DispatchQueue(label: "readQueue", qos: .background, attributes: .concurrent)
writeQueue = DispatchQueue(label: "writeQueue", qos: .background, attributes: .concurrent)
streamQueue = DispatchQueue.global(qos: .background)
socketStatus = .closed
self.socketDelegate = socketDelegate
super.init()
}
func connectAndOpenStreams() {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
streamQueue.sync {
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, self.host as CFString, self.port, &readStream, &writeStream)
self.inputStream = readStream!.takeRetainedValue()
self.outputStream = writeStream!.takeRetainedValue()
self.inputStream.delegate = self
self.outputStream.delegate = self
self.inputStream.schedule(in: .main, forMode: .defaultRunLoopMode)
self.outputStream.schedule(in: .main, forMode: .defaultRunLoopMode)
}
dispatchGroup.enter()
readQueue.sync {
self.inputStream.open()
}
dispatchGroup.enter()
writeQueue.sync {
self.outputStream.open()
}
let secondsToWait = DispatchTimeInterval.seconds(SocketClient.connectTimeoutSeconds)
let connectTimeout = DispatchTime.now() + secondsToWait
let timeoutResult = dispatchGroup.wait(timeout: connectTimeout)
let failureMessage = "Couldn't connect to ruby process within: \(SocketClient.connectTimeoutSeconds) seconds"
let success = testDispatchTimeoutResult(timeoutResult, failureMessage: failureMessage, timeToWait: secondsToWait)
guard success else {
socketDelegate?.commandExecuted(serverResponse: .connectionFailure) { _ in }
return
}
socketStatus = .ready
socketDelegate?.connectionsOpened()
}
public func send(rubyCommand: RubyCommandable) {
verbose(message: "sending: \(rubyCommand.json)")
send(string: rubyCommand.json)
writeSemaphore.signal()
}
public func sendComplete() {
closeSession(sendAbort: true)
}
private func testDispatchTimeoutResult(_ timeoutResult: DispatchTimeoutResult, failureMessage: String, timeToWait: DispatchTimeInterval) -> Bool {
switch timeoutResult {
case .success:
return true
case .timedOut:
log(message: "Timeout: \(failureMessage)")
if case let .seconds(seconds) = timeToWait {
socketDelegate?.commandExecuted(serverResponse: .commandTimeout(seconds: seconds)) { _ in }
}
return false
}
}
private func stopInputSession() {
inputStream.close()
}
private func stopOutputSession() {
outputStream.close()
}
private func sendThroughQueue(string: String) {
let data = string.data(using: .utf8)!
data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
if let buffer = buffer.baseAddress {
self.outputStream.write(buffer.assumingMemoryBound(to: UInt8.self), maxLength: data.count)
}
}
}
private func privateSend(string: String) {
writeQueue.sync {
writeSemaphore.wait()
self.sendThroughQueue(string: string)
writeSemaphore.signal()
let timeoutSeconds = self.cleaningUpAfterDone ? 1 : self.commandTimeoutSeconds
let timeToWait = DispatchTimeInterval.seconds(timeoutSeconds)
let commandTimeout = DispatchTime.now() + timeToWait
let timeoutResult = writeSemaphore.wait(timeout: commandTimeout)
_ = self.testDispatchTimeoutResult(timeoutResult, failureMessage: "Ruby process didn't return after: \(SocketClient.connectTimeoutSeconds) seconds", timeToWait: timeToWait)
}
}
private func send(string: String) {
guard !cleaningUpAfterDone else {
// This will happen after we abort if there are commands waiting to be executed
// Need to check state of SocketClient in command runner to make sure we can accept `send`
socketDelegate?.commandExecuted(serverResponse: .alreadyClosedSockets) { _ in }
return
}
if string == SocketClient.doneToken {
cleaningUpAfterDone = true
}
privateSend(string: string)
}
func closeSession(sendAbort: Bool = true) {
socketStatus = .closed
stopInputSession()
if sendAbort {
send(rubyCommand: ControlCommand(commandType: .done))
}
stopOutputSession()
socketDelegate?.connectionsClosed()
}
public func enter() {
dispatchGroup.enter()
}
public func leave() {
readSemaphore.signal()
writeSemaphore.signal()
}
}
extension SocketClient: StreamDelegate {
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
guard !cleaningUpAfterDone else {
// Still getting response from server even though we are done.
// No big deal, we're closing the streams anyway.
// That being said, we need to balance out the dispatchGroups
dispatchGroup.leave()
return
}
if aStream === inputStream {
switch eventCode {
case Stream.Event.openCompleted:
dispatchGroup.leave()
case Stream.Event.errorOccurred:
verbose(message: "input stream error occurred")
closeSession(sendAbort: true)
case Stream.Event.hasBytesAvailable:
read()
case Stream.Event.endEncountered:
// nothing special here
break
case Stream.Event.hasSpaceAvailable:
// we don't care about this
break
default:
verbose(message: "input stream caused unrecognized event: \(eventCode)")
}
} else if aStream === outputStream {
switch eventCode {
case Stream.Event.openCompleted:
dispatchGroup.leave()
case Stream.Event.errorOccurred:
// probably safe to close all the things because Ruby already disconnected
verbose(message: "output stream received error")
case Stream.Event.endEncountered:
// nothing special here
break
case Stream.Event.hasSpaceAvailable:
// we don't care about this
break
default:
verbose(message: "output stream caused unrecognized event: \(eventCode)")
}
}
}
func read() {
readQueue.sync {
self.readSemaphore.wait()
var buffer = [UInt8](repeating: 0, count: maxReadLength)
var output = ""
while self.inputStream!.hasBytesAvailable {
let bytesRead: Int = inputStream!.read(&buffer, maxLength: buffer.count)
if bytesRead >= 0 {
guard let read = String(bytes: buffer[..<bytesRead], encoding: .utf8) else {
fatalError("Unable to decode bytes from buffer \(buffer[..<bytesRead])")
}
output.append(contentsOf: read)
} else {
verbose(message: "Stream read() error")
}
}
self.processResponse(string: output)
readSemaphore.signal()
}
}
func handleFailure(message: [String]) {
log(message: "Encountered a problem: \(message.joined(separator: "\n"))")
let shutdownCommand = ControlCommand(commandType: .cancel(cancelReason: .serverError))
send(rubyCommand: shutdownCommand)
}
func processResponse(string: String) {
guard !string.isEmpty else {
socketDelegate?.commandExecuted(serverResponse: .malformedResponse) {
self.handleFailure(message: ["empty response from ruby process"])
$0.writeSemaphore.signal()
}
return
}
let responseString = string.trimmingCharacters(in: .whitespacesAndNewlines)
let socketResponse = SocketResponse(payload: responseString)
verbose(message: "response is: \(responseString)")
switch socketResponse.responseType {
case .clientInitiatedCancel:
socketDelegate?.commandExecuted(serverResponse: .clientInitiatedCancelAcknowledged) {
$0.writeSemaphore.signal()
self.closeSession(sendAbort: false)
}
case let .failure(failureInformation, failureClass, failureMessage):
LaneFile.fastfileInstance?.onError(currentLane: ArgumentProcessor(args: CommandLine.arguments).currentLane, errorInfo: failureInformation.joined(), errorClass: failureClass, errorMessage: failureMessage)
socketDelegate?.commandExecuted(serverResponse: .serverError) {
$0.writeSemaphore.signal()
self.handleFailure(message: failureMessage.map {m in [m] + failureInformation} ?? failureInformation)
}
case let .parseFailure(failureInformation):
socketDelegate?.commandExecuted(serverResponse: .malformedResponse) {
$0.writeSemaphore.signal()
self.handleFailure(message: failureInformation)
}
case let .readyForNext(returnedObject, closureArgumentValue):
socketDelegate?.commandExecuted(serverResponse: .success(returnedObject: returnedObject, closureArgumentValue: closureArgumentValue)) {
$0.writeSemaphore.signal()
}
}
}
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.2]
|
//
// PullRequestReviewCommentsViewController.swift
// Freetime
//
// Created by Ryan Nystrom on 11/4/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import IGListKit
import MessageViewController
final class PullRequestReviewCommentsViewController: MessageViewController,
ListAdapterDataSource,
FeedDelegate,
PullRequestReviewReplySectionControllerDelegate {
private let model: IssueDetailsModel
private let client: GithubClient
private let autocomplete: IssueCommentAutocomplete
private var results = [ListDiffable]()
private let textActionsController = TextActionsController()
private var autocompleteController: AutocompleteController!
private var focusedReplyModel: PullRequestReviewReplyModel?
lazy private var feed: Feed = {
let f = Feed(viewController: self, delegate: self, managesLayout: false)
f.collectionView.contentInset = Styles.Sizes.threadInset
return f
}()
init(model: IssueDetailsModel, client: GithubClient, autocomplete: IssueCommentAutocomplete) {
self.model = model
self.client = client
self.autocomplete = autocomplete
super.init(nibName: nil, bundle: nil)
title = NSLocalizedString("Review Comments", comment: "")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
feed.viewDidLoad()
feed.adapter.dataSource = self
// setup after feed is lazy loaded
setup(scrollView: feed.collectionView)
setMessageView(hidden: true, animated: false)
// override Feed bg color setting
view.backgroundColor = Styles.Colors.background
// setup message view properties
configure(target: self, action: #selector(didPressButton(_:)))
let getMarkdownBlock = { [weak self] () -> (String) in
return self?.messageView.text ?? ""
}
let actions = IssueTextActionsView.forMarkdown(
viewController: self,
getMarkdownBlock: getMarkdownBlock,
repo: model.repo,
owner: model.owner,
addBorder: false,
supportsImageUpload: true
)
// text input bar uses UIVisualEffectView, don't try to match it
actions.backgroundColor = .clear
textActionsController.configure(client: client, textView: messageView.textView, actions: actions)
textActionsController.viewController = self
actions.frame = CGRect(x: 0, y: 0, width: 0, height: 40)
messageView.add(contentView: actions)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
feed.viewWillLayoutSubviews(view: view)
}
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
feed.collectionView.updateSafeInset(container: view, base: Styles.Sizes.threadInset)
}
// MARK: FeedDelegate
func loadFromNetwork(feed: Feed) {
fetch()
}
func loadNextPage(feed: Feed) -> Bool {
return false
}
// MARK: Private API
var insetWidth: CGFloat {
let contentInset = feed.collectionView.contentInset
return view.bounds.width - contentInset.left - contentInset.right
}
func fetch() {
client.fetchPRComments(
owner: model.owner,
repo: model.repo,
number: model.number,
width: insetWidth
) { [weak self] (result) in
switch result {
case .error: ToastManager.showGenericError()
case .success(let models):
self?.results = models
self?.feed.finishLoading(dismissRefresh: true, animated: true)
}
}
}
@objc func didPressButton(_ sender: Any) {
guard let reply = focusedReplyModel else { return }
let text = messageView.text
messageView.text = ""
messageView.textView.resignFirstResponder()
setMessageView(hidden: true, animated: true)
client.sendComment(
body: text,
inReplyTo: reply.replyID,
owner: model.owner,
repo: model.repo,
number: model.number,
width: insetWidth
) { [weak self] result in
switch result {
case .error: break
case .success(let comment): self?.insertComment(model: comment, reply: reply)
}
}
}
func insertComment(model: IssueCommentModel, reply: PullRequestReviewReplyModel) {
let section = feed.adapter.section(for: reply)
guard section < NSNotFound && section < results.count else { return }
results.insert(model, at: section)
feed.adapter.performUpdates(animated: true)
}
// MARK: ListAdapterDataSource
func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
return results
}
func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
switch object {
case is NSAttributedStringSizing: return IssueTitleSectionController()
case is IssueCommentModel: return IssueCommentSectionController(
model: self.model,
client: client,
autocomplete: autocomplete
)
case is IssueDiffHunkModel: return IssueDiffHunkSectionController()
case is PullRequestReviewReplyModel: return PullRequestReviewReplySectionController(delegate: self)
// add case for reply model + SC. connect SC.delegate = self
default: fatalError("Unhandled object: \(model)")
}
}
func emptyView(for listAdapter: ListAdapter) -> UIView? {
switch feed.status {
case .idle:
let emptyView = EmptyView()
emptyView.label.text = NSLocalizedString("Error loading review comments.", comment: "")
return emptyView
case .loading, .loadingNext:
return nil
}
}
// MARK: PullRequestReviewReplySectionControllerDelegate
func didSelect(replySectionController: PullRequestReviewReplySectionController, reply: PullRequestReviewReplyModel) {
setMessageView(hidden: false, animated: true)
messageView.textView.becomeFirstResponder()
feed.adapter.scroll(to: reply, padding: Styles.Sizes.rowSpacing)
focusedReplyModel = reply
}
}
add feed.viewDidAppear(animated) in viewDidAppear.
//
// PullRequestReviewCommentsViewController.swift
// Freetime
//
// Created by Ryan Nystrom on 11/4/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import IGListKit
import MessageViewController
final class PullRequestReviewCommentsViewController: MessageViewController,
ListAdapterDataSource,
FeedDelegate,
PullRequestReviewReplySectionControllerDelegate {
private let model: IssueDetailsModel
private let client: GithubClient
private let autocomplete: IssueCommentAutocomplete
private var results = [ListDiffable]()
private let textActionsController = TextActionsController()
private var autocompleteController: AutocompleteController!
private var focusedReplyModel: PullRequestReviewReplyModel?
lazy private var feed: Feed = {
let f = Feed(viewController: self, delegate: self, managesLayout: false)
f.collectionView.contentInset = Styles.Sizes.threadInset
return f
}()
init(model: IssueDetailsModel, client: GithubClient, autocomplete: IssueCommentAutocomplete) {
self.model = model
self.client = client
self.autocomplete = autocomplete
super.init(nibName: nil, bundle: nil)
title = NSLocalizedString("Review Comments", comment: "")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
feed.viewDidLoad()
feed.adapter.dataSource = self
// setup after feed is lazy loaded
setup(scrollView: feed.collectionView)
setMessageView(hidden: true, animated: false)
// override Feed bg color setting
view.backgroundColor = Styles.Colors.background
// setup message view properties
configure(target: self, action: #selector(didPressButton(_:)))
let getMarkdownBlock = { [weak self] () -> (String) in
return self?.messageView.text ?? ""
}
let actions = IssueTextActionsView.forMarkdown(
viewController: self,
getMarkdownBlock: getMarkdownBlock,
repo: model.repo,
owner: model.owner,
addBorder: false,
supportsImageUpload: true
)
// text input bar uses UIVisualEffectView, don't try to match it
actions.backgroundColor = .clear
textActionsController.configure(client: client, textView: messageView.textView, actions: actions)
textActionsController.viewController = self
actions.frame = CGRect(x: 0, y: 0, width: 0, height: 40)
messageView.add(contentView: actions)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
feed.viewDidAppear(animated)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
feed.viewWillLayoutSubviews(view: view)
}
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
feed.collectionView.updateSafeInset(container: view, base: Styles.Sizes.threadInset)
}
// MARK: FeedDelegate
func loadFromNetwork(feed: Feed) {
fetch()
}
func loadNextPage(feed: Feed) -> Bool {
return false
}
// MARK: Private API
var insetWidth: CGFloat {
let contentInset = feed.collectionView.contentInset
return view.bounds.width - contentInset.left - contentInset.right
}
func fetch() {
client.fetchPRComments(
owner: model.owner,
repo: model.repo,
number: model.number,
width: insetWidth
) { [weak self] (result) in
switch result {
case .error: ToastManager.showGenericError()
case .success(let models):
self?.results = models
self?.feed.finishLoading(dismissRefresh: true, animated: true)
}
}
}
@objc func didPressButton(_ sender: Any) {
guard let reply = focusedReplyModel else { return }
let text = messageView.text
messageView.text = ""
messageView.textView.resignFirstResponder()
setMessageView(hidden: true, animated: true)
client.sendComment(
body: text,
inReplyTo: reply.replyID,
owner: model.owner,
repo: model.repo,
number: model.number,
width: insetWidth
) { [weak self] result in
switch result {
case .error: break
case .success(let comment): self?.insertComment(model: comment, reply: reply)
}
}
}
func insertComment(model: IssueCommentModel, reply: PullRequestReviewReplyModel) {
let section = feed.adapter.section(for: reply)
guard section < NSNotFound && section < results.count else { return }
results.insert(model, at: section)
feed.adapter.performUpdates(animated: true)
}
// MARK: ListAdapterDataSource
func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
return results
}
func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
switch object {
case is NSAttributedStringSizing: return IssueTitleSectionController()
case is IssueCommentModel: return IssueCommentSectionController(
model: self.model,
client: client,
autocomplete: autocomplete
)
case is IssueDiffHunkModel: return IssueDiffHunkSectionController()
case is PullRequestReviewReplyModel: return PullRequestReviewReplySectionController(delegate: self)
// add case for reply model + SC. connect SC.delegate = self
default: fatalError("Unhandled object: \(model)")
}
}
func emptyView(for listAdapter: ListAdapter) -> UIView? {
switch feed.status {
case .idle:
let emptyView = EmptyView()
emptyView.label.text = NSLocalizedString("Error loading review comments.", comment: "")
return emptyView
case .loading, .loadingNext:
return nil
}
}
// MARK: PullRequestReviewReplySectionControllerDelegate
func didSelect(replySectionController: PullRequestReviewReplySectionController, reply: PullRequestReviewReplyModel) {
setMessageView(hidden: false, animated: true)
messageView.textView.becomeFirstResponder()
feed.adapter.scroll(to: reply, padding: Styles.Sizes.rowSpacing)
focusedReplyModel = reply
}
}
|
import Foundation
import ReactiveSwift
import Tentacle
import Result
final class Counter {
private let c = Client(.dotCom, token: ProcessInfo.processInfo.environment["GITHUB_API_TOKEN"]!)
enum CounterError: Error {
case githubError(wrapped: Client.Error)
case invalidDirectory
case fetchingError
case downloadError
}
func count() -> SignalProducer<Int, CounterError> {
return fetch().map { content in
let options: NSLinguisticTagger.Options = [.omitWhitespace, .omitPunctuation, .joinNames]
let schemes = NSLinguisticTagger.availableTagSchemes(forLanguage: "en")
let tagger = NSLinguisticTagger(tagSchemes: schemes, options: Int(options.rawValue))
tagger.string = content
let tags = tagger.tags(in: NSMakeRange(0, (content as NSString).length), scheme: NSLinguisticTagSchemeTokenType, options: options, tokenRanges: nil)
return tags.count
}
.reduce(0, +)
}
func fetch() -> SignalProducer<String, CounterError> {
return c
.content(atPath: "_drafts", in: Repository(owner: "palleas", name: "romain-pouclet.com"))
.mapError { CounterError.githubError(wrapped: $0) }
.flatMap(.latest) { response, content -> SignalProducer<String, CounterError> in
guard case let .directory(files) = content else {
return SignalProducer(error: .invalidDirectory)
}
return SignalProducer(files)
.flatMap(.concat) { file -> SignalProducer<String, CounterError> in
guard case let .file(_, url) = file.content, let downloadUrl = url else { return .empty }
let download = URLSession.shared.reactive.data(with: URLRequest(url: downloadUrl))
.mapError { _ in CounterError.downloadError }
.map { data, _ in data }
.map { String(data: $0, encoding: .utf8)! }
return download
}
}
}
}
Add debug for each file
import Foundation
import ReactiveSwift
import Tentacle
import Result
final class Counter {
private let c = Client(.dotCom, token: ProcessInfo.processInfo.environment["GITHUB_API_TOKEN"]!)
enum CounterError: Error {
case githubError(wrapped: Client.Error)
case invalidDirectory
case fetchingError
case downloadError
}
func count() -> SignalProducer<Int, CounterError> {
return fetch().map { name, content in
let options: NSLinguisticTagger.Options = [.omitWhitespace, .omitPunctuation, .joinNames]
let schemes = NSLinguisticTagger.availableTagSchemes(forLanguage: "en")
let tagger = NSLinguisticTagger(tagSchemes: schemes, options: Int(options.rawValue))
tagger.string = content
let tags = tagger.tags(in: NSMakeRange(0, (content as NSString).length), scheme: NSLinguisticTagSchemeTokenType, options: options, tokenRanges: nil)
print("\(name): \(tags.count) words")
return tags.count
}
.reduce(0, +)
}
func fetch() -> SignalProducer<(String, String), CounterError> {
return c
.content(atPath: "_drafts", in: Repository(owner: "palleas", name: "romain-pouclet.com"))
.mapError { CounterError.githubError(wrapped: $0) }
.flatMap(.latest) { response, content -> SignalProducer<(String, String), CounterError> in
guard case let .directory(files) = content else {
return SignalProducer(error: .invalidDirectory)
}
return SignalProducer(files)
.flatMap(.concat) { file -> SignalProducer<(String, String), CounterError> in
guard case let .file(_, url) = file.content, let downloadUrl = url else { return .empty }
let download = URLSession.shared.reactive.data(with: URLRequest(url: downloadUrl))
.mapError { _ in CounterError.downloadError }
.map { data, _ in data }
.map { (file.name, String(data: $0, encoding: .utf8)!) }
return download
}
}
}
}
|
//
// WebService.swift
// NABase
//
// Created by Wain on 29/09/2016.
// Copyright © 2017 Nice Agency. All rights reserved.
//
import Foundation
public protocol UnauthorizedResponseHandler {
func authorizedRequestDidFail(request: URLRequest, response: HTTPURLResponse, data: Data?, retry: () -> Void)
}
public final class Webservice {
let baseURL: URL
let session: URLSession
private let unauthorizedResponseHandler: UnauthorizedResponseHandler?
private let defaultHeaders: HeaderProvider?
public var behavior: RequestBehavior = EmptyRequestBehavior()
init(baseURL: URL, unauthorizedResponseHandler: UnauthorizedResponseHandler? = nil, defaultHeaders: HeaderProvider? = nil, session: URLSession = URLSession.shared) {
self.baseURL = baseURL
self.session = session
self.unauthorizedResponseHandler = unauthorizedResponseHandler
self.defaultHeaders = defaultHeaders
}
static let validResponseCodes = [200,201,204]
public func request<A>(_ resource: Resource<A>,
withBehavior additionalBehavior: RequestBehavior = EmptyRequestBehavior(),
completion: @escaping (Result<A>) -> ()) {
let behavior = CompositeRequestBehavior(behaviors: [ self.behavior, additionalBehavior ])
var headers = behavior.additionalHeaders
headers.append(contentsOf: self.defaultHeaders?.headers() ?? [])
let request = URLRequest(resource: resource, baseURL: self.baseURL, additionalHeaders: headers)
BaseLog.network.log(.trace, request)
let session = self.session
let cancel = resource.cancellationPolicy
let matchURL = request.url!
session.getAllTasks { tasks in
for running in tasks {
if cancel.matches(url: matchURL, with: running.originalRequest!.url!) {
if running.state != .completed && running.state != .canceling {
BaseLog.network.log(.trace, "Cancelling \(running) as a result of starting \(request)")
running.cancel()
}
}
}
}
behavior.beforeSend()
let success: ((A) -> ()) = { result in
DispatchQueue.main.async {
completion(.success(result))
behavior.afterComplete()
}
}
let failure: ((Error) -> ()) = { error in
DispatchQueue.main.async {
completion(.error(error))
behavior.afterFailure(error: error)
}
}
let task = session.dataTask(with: request) { data, response, error in
BaseLog.network.log(.trace, "done")
if let error = error as NSError? {
let isCancelled = error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled
// Surpress all cancelled request errors
guard !isCancelled else {
behavior.afterComplete()
return
}
let noConnectivity = error.domain == NSURLErrorDomain && error.code == NSURLErrorNotConnectedToInternet
guard !noConnectivity else {
let failingURL = error.userInfo[NSURLErrorFailingURLStringErrorKey]! as! String
BaseLog.network.log(.trace, "No connectivity available for request: \(failingURL)")
failure(NAError(type: NetworkError.noConnection(error.code, failingURL)))
return
}
}
if let response = response as? HTTPURLResponse {
let statusCode = response.statusCode
if !Webservice.validResponseCodes.contains(statusCode) {
// Default to an HTTP error in case caller did not provide a response error handler
var error: Error = NAError(type: NetworkError.httpError(statusCode))
if let errorResponseHandler = resource.errorResponseHandler {
let responseError = errorResponseHandler(statusCode, data)
if responseError != nil {
error = responseError!
}
}
failure(error)
if statusCode == 401 {
let retry = {
self.request(resource, withBehavior: behavior, completion: completion)
}
DispatchQueue.main.async {
self.unauthorizedResponseHandler?.authorizedRequestDidFail(request: request, response: response, data: data, retry: retry)
}
}
return
}
}
if let data = data {
BaseLog.network.log(.trace, "data to parse")
let result = resource.parse(data)
switch result {
case .success(let value):
success(value)
case .error(let error):
failure(error)
}
} else {
BaseLog.network.log(.trace, "no data returned")
failure(error ?? NAError(type: NetworkError.httpError(-1)))
}
}
task.resume()
BaseLog.network.log(.trace, "Started \(task) for \(request)")
}
}
fileprivate extension Resource {
func url(for baseURL: URL) -> URL {
var urlComponents = URLComponents()
urlComponents.scheme = baseURL.scheme!
urlComponents.host = baseURL.host
urlComponents.port = baseURL.port
urlComponents.path = baseURL.path.appending(self.endpoint)
if let query = self.query, !query.isEmpty {
urlComponents.queryItems = query
}
return urlComponents.url!
}
}
fileprivate extension HttpMethod {
var name: String {
switch self {
case .get: return "GET"
case .post: return "POST"
case .put: return "PUT"
case .delete: return "DELETE"
}
}
func map<B>(f: (Body) -> B) -> HttpMethod<B> {
switch self {
case .get(let body):
if let b = body {
return .get(f(b))
}
return .get(nil)
case .post(let body):
if let b = body {
return .post(f(b))
}
return .post(nil)
case .put(let body):
if let b = body {
return .put(f(b))
}
return .put(nil)
case .delete(let body):
if let b = body {
return .delete(f(b))
}
return .delete(nil)
}
}
}
fileprivate extension CancellationPolicy {
func matches(url: URL, with: URL) -> Bool {
var cancel: ((URL, URL) -> Bool)!
switch self {
case .none:
cancel = { _, _ in
return false
}
case .path:
cancel = { matchURL, withURL in
return (matchURL.path == withURL.path)
}
case .uri:
cancel = { matchURL, withURL in
let match = URLComponents(url: matchURL, resolvingAgainstBaseURL: false)
let with = URLComponents(url: withURL, resolvingAgainstBaseURL: false)
return (match?.path == with?.path && match?.query == with?.query)
}
case .pattern(let pattern):
cancel = { _, withURL in
let matchRange = withURL.absoluteString.range(of: pattern, options: .regularExpression, range: nil, locale: nil)
return (matchRange != nil && !matchRange!.isEmpty)
}
}
return cancel(url, with)
}
}
fileprivate extension URLRequest {
init<A>(resource: Resource<A>, baseURL: URL, additionalHeaders: [(String, String)]) {
self.init(url: resource.url(for: baseURL))
let method = resource.method.map { input -> Data in
if input is Data {
return input as! Data
}
return try! JSONSerialization.data(withJSONObject: input, options: [])
}
httpMethod = method.name
switch method {
case let .get(data):
httpBody = data
case let .post(data):
httpBody = data
case let .put(data):
httpBody = data
case let .delete(data):
httpBody = data
}
if let provider = resource.headerProvider {
for (header, value) in provider.headers() {
addValue(value, forHTTPHeaderField: header)
}
}
for (header, value) in additionalHeaders {
addValue(value, forHTTPHeaderField: header)
}
}
}
Updated the failure handling for 401 so all 401s are redirected to the unauth handler if it exists rather than being sent to both it and the original requester.
//
// WebService.swift
// NABase
//
// Created by Wain on 29/09/2016.
// Copyright © 2017 Nice Agency. All rights reserved.
//
import Foundation
public protocol UnauthorizedResponseHandler {
func authorizedRequestDidFail(request: URLRequest, response: HTTPURLResponse, data: Data?, retry: () -> Void)
}
public final class Webservice {
let baseURL: URL
let session: URLSession
private let unauthorizedResponseHandler: UnauthorizedResponseHandler?
private let defaultHeaders: HeaderProvider?
public var behavior: RequestBehavior = EmptyRequestBehavior()
init(baseURL: URL, unauthorizedResponseHandler: UnauthorizedResponseHandler? = nil, defaultHeaders: HeaderProvider? = nil, session: URLSession = URLSession.shared) {
self.baseURL = baseURL
self.session = session
self.unauthorizedResponseHandler = unauthorizedResponseHandler
self.defaultHeaders = defaultHeaders
}
static let validResponseCodes = [200,201,204]
public func request<A>(_ resource: Resource<A>,
withBehavior additionalBehavior: RequestBehavior = EmptyRequestBehavior(),
completion: @escaping (Result<A>) -> ()) {
let behavior = CompositeRequestBehavior(behaviors: [ self.behavior, additionalBehavior ])
var headers = behavior.additionalHeaders
headers.append(contentsOf: self.defaultHeaders?.headers() ?? [])
let request = URLRequest(resource: resource, baseURL: self.baseURL, additionalHeaders: headers)
BaseLog.network.log(.trace, request)
let session = self.session
let cancel = resource.cancellationPolicy
let matchURL = request.url!
session.getAllTasks { tasks in
for running in tasks {
if cancel.matches(url: matchURL, with: running.originalRequest!.url!) {
if running.state != .completed && running.state != .canceling {
BaseLog.network.log(.trace, "Cancelling \(running) as a result of starting \(request)")
running.cancel()
}
}
}
}
behavior.beforeSend()
let success: ((A) -> ()) = { result in
DispatchQueue.main.async {
completion(.success(result))
behavior.afterComplete()
}
}
let failure: ((Error) -> ()) = { error in
DispatchQueue.main.async {
completion(.error(error))
behavior.afterFailure(error: error)
}
}
let task = session.dataTask(with: request) { data, response, error in
BaseLog.network.log(.trace, "done")
if let error = error as NSError? {
let isCancelled = error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled
// Surpress all cancelled request errors
guard !isCancelled else {
behavior.afterComplete()
return
}
let noConnectivity = error.domain == NSURLErrorDomain && error.code == NSURLErrorNotConnectedToInternet
guard !noConnectivity else {
let failingURL = error.userInfo[NSURLErrorFailingURLStringErrorKey]! as! String
BaseLog.network.log(.trace, "No connectivity available for request: \(failingURL)")
failure(NAError(type: NetworkError.noConnection(error.code, failingURL)))
return
}
}
if let response = response as? HTTPURLResponse {
let statusCode = response.statusCode
if !Webservice.validResponseCodes.contains(statusCode) {
// Default to an HTTP error in case caller did not provide a response error handler
var error: Error = NAError(type: NetworkError.httpError(statusCode))
if let errorResponseHandler = resource.errorResponseHandler {
let responseError = errorResponseHandler(statusCode, data)
if responseError != nil {
error = responseError!
}
}
if statusCode == 401, let handler = self.unauthorizedResponseHandler {
let retry = {
self.request(resource, withBehavior: behavior, completion: completion)
}
DispatchQueue.main.async {
handler.authorizedRequestDidFail(request: request, response: response, data: data, retry: retry)
}
} else {
failure(error)
}
return
}
}
if let data = data {
BaseLog.network.log(.trace, "data to parse")
let result = resource.parse(data)
switch result {
case .success(let value):
success(value)
case .error(let error):
failure(error)
}
} else {
BaseLog.network.log(.trace, "no data returned")
failure(error ?? NAError(type: NetworkError.httpError(-1)))
}
}
task.resume()
BaseLog.network.log(.trace, "Started \(task) for \(request)")
}
}
fileprivate extension Resource {
func url(for baseURL: URL) -> URL {
var urlComponents = URLComponents()
urlComponents.scheme = baseURL.scheme!
urlComponents.host = baseURL.host
urlComponents.port = baseURL.port
urlComponents.path = baseURL.path.appending(self.endpoint)
if let query = self.query, !query.isEmpty {
urlComponents.queryItems = query
}
return urlComponents.url!
}
}
fileprivate extension HttpMethod {
var name: String {
switch self {
case .get: return "GET"
case .post: return "POST"
case .put: return "PUT"
case .delete: return "DELETE"
}
}
func map<B>(f: (Body) -> B) -> HttpMethod<B> {
switch self {
case .get(let body):
if let b = body {
return .get(f(b))
}
return .get(nil)
case .post(let body):
if let b = body {
return .post(f(b))
}
return .post(nil)
case .put(let body):
if let b = body {
return .put(f(b))
}
return .put(nil)
case .delete(let body):
if let b = body {
return .delete(f(b))
}
return .delete(nil)
}
}
}
fileprivate extension CancellationPolicy {
func matches(url: URL, with: URL) -> Bool {
var cancel: ((URL, URL) -> Bool)!
switch self {
case .none:
cancel = { _, _ in
return false
}
case .path:
cancel = { matchURL, withURL in
return (matchURL.path == withURL.path)
}
case .uri:
cancel = { matchURL, withURL in
let match = URLComponents(url: matchURL, resolvingAgainstBaseURL: false)
let with = URLComponents(url: withURL, resolvingAgainstBaseURL: false)
return (match?.path == with?.path && match?.query == with?.query)
}
case .pattern(let pattern):
cancel = { _, withURL in
let matchRange = withURL.absoluteString.range(of: pattern, options: .regularExpression, range: nil, locale: nil)
return (matchRange != nil && !matchRange!.isEmpty)
}
}
return cancel(url, with)
}
}
fileprivate extension URLRequest {
init<A>(resource: Resource<A>, baseURL: URL, additionalHeaders: [(String, String)]) {
self.init(url: resource.url(for: baseURL))
let method = resource.method.map { input -> Data in
if input is Data {
return input as! Data
}
return try! JSONSerialization.data(withJSONObject: input, options: [])
}
httpMethod = method.name
switch method {
case let .get(data):
httpBody = data
case let .post(data):
httpBody = data
case let .put(data):
httpBody = data
case let .delete(data):
httpBody = data
}
if let provider = resource.headerProvider {
for (header, value) in provider.headers() {
addValue(value, forHTTPHeaderField: header)
}
}
for (header, value) in additionalHeaders {
addValue(value, forHTTPHeaderField: header)
}
}
}
|
//
// GMSearchTextDropdown.swift
// GMSearchTextWithDropdown
//
// Created by Gina Mullins on 1/5/17.
// Copyright © 2017 Gina Mullins. All rights reserved.
//
import UIKit
enum DropDownDirection {
case DropDownDirectionDown
case DropDownDirectionUp
}
protocol GMSearchTextDropdownDelegate: class {
func textDidChange(searchText: String)
func didSelectRow(searchText: String)
func searchTextCancelClicked()
}
class GMSearchTextDropdown: UIView, UITableViewDelegate, UITableViewDataSource, GMSearchTextDelegate {
// public
var searchText: GMSearchText!
var data = [String]() {
didSet {
self.searchData = data;
filterTableViewWith(searchText: self.searchText.text)
}
}
var hidesOnSelection: Bool = true
var shouldHandleFilter: Bool = true
var direction: DropDownDirection!
weak var delegate: GMSearchTextDropdownDelegate?
// private
let kDropdownCell = "SearchCell"
let kXMargin = 8
let kYMargin = 5
let ksearchTextHeight = 50
var tableView = UITableView()
var searchData = [String]()
func configureWithSearch(data: [String], title: String, placeholder: String) {
self.searchText.title = title;
self.searchText.placeholder = placeholder;
self.data = data;
hideSearchTable(hide: false)
}
/// - Initializers
private func commonInit() {
self.backgroundColor = UIColor.clear
let boundsWidth = self.bounds.size.width
// searchText
let searchTextFrame = CGRect(x: CGFloat(kXMargin), y: CGFloat(kYMargin), width: boundsWidth - CGFloat(2*kXMargin), height: CGFloat(ksearchTextHeight))
searchText = GMSearchText(frame: searchTextFrame)
searchText.delegate = self;
searchText.becomeFirstResponder()
self.addSubview(searchText)
// tableview
let textFieldFrame = self.searchText.textField.frame
let tableViewWidth = searchTextFrame.size.width - CGFloat(2*kXMargin)
let posX = searchTextFrame.size.width/2 - tableViewWidth/2 + CGFloat(kXMargin)
let posY = textFieldFrame.origin.y + textFieldFrame.size.height + CGFloat(2*kYMargin);
let tableViewFrame = CGRect(x: posX, y: posY, width: tableViewWidth, height: 0.0)
self.tableView = UITableView(frame: tableViewFrame, style: .plain)
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: kDropdownCell)
self.tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.tableView.keyboardDismissMode = .onDrag
self.tableView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
self.tableView.isHidden = true;
self.addSubview(self.tableView)
// add a subtle border to table
let borderColor = UIColor.lightGray
self.tableView.layer.borderWidth = 1;
self.tableView.layer.borderColor = borderColor.cgColor;
self.tableView.clipsToBounds = true;
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
var frame = self.tableView.frame
frame.size = self.tableView.contentSize
if frame.size.height > self.frame.size.height - CGFloat(2*kYMargin) {
frame.size.height = self.frame.size.height - CGFloat(2*kYMargin)
}
self.tableView.frame = frame
}
func hideSearchTable(hide: Bool) {
self.tableView.isHidden = hide
}
func filterTableViewWith(searchText: String) {
self.tableView.isHidden = (searchText.characters.count > 0) ? false : true;
if (self.shouldHandleFilter) {
if searchText.isEmpty {
self.searchData = self.data
} else {
self.searchData = self.data.filter { item in
return item.lowercased().contains(searchText.lowercased())
}
}
}
self.tableView.reloadData()
}
/// Default initializer
override init(frame: CGRect) {
var newFrame = frame
newFrame.size.height = CGFloat(ksearchTextHeight)
super.init(frame: newFrame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
/// - Cleanup
deinit {
self.tableView.removeObserver(self, forKeyPath: "contentSize", context: nil)
}
/// tableview
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.searchData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kDropdownCell, for: indexPath)
cell.textLabel?.text = self.searchData[indexPath.row]
cell.textLabel?.font = UIFont.systemFont(ofSize: 15.0)
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.searchText.text = self.searchData[indexPath.row]
self.delegate?.didSelectRow(searchText: self.searchText.text)
self.tableView.isHidden = true
}
/// searchText delegate
func searchTextCancelButtonClicked(searchText: GMSearchText) {
self.searchText.text = ""
self.filterTableViewWith(searchText: self.searchText.text)
self.delegate?.searchTextCancelClicked()
}
func searchTextSearchButtonClicked(searchText: GMSearchText) {
self.tableView.isHidden = (searchText.text.isEmpty) ? true : false
self.searchText.textField.resignFirstResponder()
}
func textDidChange(searchText: String) {
self.filterTableViewWith(searchText: self.searchText.text)
self.delegate?.textDidChange(searchText: self.searchText.text)
}
}
Update GMSearchTextDropdown.swift
//
// GMSearchTextDropdown.swift
// GMSearchTextWithDropdown
//
// Created by Gina Mullins on 1/5/17.
// Copyright © 2017 Gina Mullins. All rights reserved.
//
// MIT License
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
enum DropDownDirection {
case DropDownDirectionDown
case DropDownDirectionUp
}
protocol GMSearchTextDropdownDelegate: class {
func textDidChange(searchText: String)
func didSelectRow(searchText: String)
func searchTextCancelClicked()
}
class GMSearchTextDropdown: UIView, UITableViewDelegate, UITableViewDataSource, GMSearchTextDelegate {
// public
var searchText: GMSearchText!
var data = [String]() {
didSet {
self.searchData = data;
filterTableViewWith(searchText: self.searchText.text)
}
}
var hidesOnSelection: Bool = true
var shouldHandleFilter: Bool = true
var direction: DropDownDirection!
weak var delegate: GMSearchTextDropdownDelegate?
// private
let kDropdownCell = "SearchCell"
let kXMargin = 8
let kYMargin = 5
let ksearchTextHeight = 50
var tableView = UITableView()
var searchData = [String]()
func configureWithSearch(data: [String], title: String, placeholder: String) {
self.searchText.title = title;
self.searchText.placeholder = placeholder;
self.data = data;
hideSearchTable(hide: false)
}
/// - Initializers
private func commonInit() {
self.backgroundColor = UIColor.clear
let boundsWidth = self.bounds.size.width
// searchText
let searchTextFrame = CGRect(x: CGFloat(kXMargin), y: CGFloat(kYMargin), width: boundsWidth - CGFloat(2*kXMargin), height: CGFloat(ksearchTextHeight))
searchText = GMSearchText(frame: searchTextFrame)
searchText.delegate = self;
searchText.becomeFirstResponder()
self.addSubview(searchText)
// tableview
let textFieldFrame = self.searchText.textField.frame
let tableViewWidth = searchTextFrame.size.width - CGFloat(2*kXMargin)
let posX = searchTextFrame.size.width/2 - tableViewWidth/2 + CGFloat(kXMargin)
let posY = textFieldFrame.origin.y + textFieldFrame.size.height + CGFloat(2*kYMargin);
let tableViewFrame = CGRect(x: posX, y: posY, width: tableViewWidth, height: 0.0)
self.tableView = UITableView(frame: tableViewFrame, style: .plain)
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: kDropdownCell)
self.tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.tableView.keyboardDismissMode = .onDrag
self.tableView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
self.tableView.isHidden = true;
self.addSubview(self.tableView)
// add a subtle border to table
let borderColor = UIColor.lightGray
self.tableView.layer.borderWidth = 1;
self.tableView.layer.borderColor = borderColor.cgColor;
self.tableView.clipsToBounds = true;
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
var frame = self.tableView.frame
frame.size = self.tableView.contentSize
if frame.size.height > self.frame.size.height - CGFloat(2*kYMargin) {
frame.size.height = self.frame.size.height - CGFloat(2*kYMargin)
}
self.tableView.frame = frame
}
func hideSearchTable(hide: Bool) {
self.tableView.isHidden = hide
}
func filterTableViewWith(searchText: String) {
self.tableView.isHidden = (searchText.characters.count > 0) ? false : true;
if (self.shouldHandleFilter) {
if searchText.isEmpty {
self.searchData = self.data
} else {
self.searchData = self.data.filter { item in
return item.lowercased().contains(searchText.lowercased())
}
}
}
self.tableView.reloadData()
}
/// Default initializer
override init(frame: CGRect) {
var newFrame = frame
newFrame.size.height = CGFloat(ksearchTextHeight)
super.init(frame: newFrame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
/// - Cleanup
deinit {
self.tableView.removeObserver(self, forKeyPath: "contentSize", context: nil)
}
/// tableview
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.searchData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kDropdownCell, for: indexPath)
cell.textLabel?.text = self.searchData[indexPath.row]
cell.textLabel?.font = UIFont.systemFont(ofSize: 15.0)
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.searchText.text = self.searchData[indexPath.row]
self.delegate?.didSelectRow(searchText: self.searchText.text)
self.tableView.isHidden = true
}
/// searchText delegate
func searchTextCancelButtonClicked(searchText: GMSearchText) {
self.searchText.text = ""
self.filterTableViewWith(searchText: self.searchText.text)
self.delegate?.searchTextCancelClicked()
}
func searchTextSearchButtonClicked(searchText: GMSearchText) {
self.tableView.isHidden = (searchText.text.isEmpty) ? true : false
self.searchText.textField.resignFirstResponder()
}
func textDidChange(searchText: String) {
self.filterTableViewWith(searchText: self.searchText.text)
self.delegate?.textDidChange(searchText: self.searchText.text)
}
}
|
//
// ElongationViewController.swift
// ElongationPreview
//
// Created by Abdurahim Jauzee on 08/02/2017.
// Copyright © 2017 Ramotion. All rights reserved.
//
import UIKit
@available(iOS 10, *)
fileprivate var interaction: UIPreviewInteraction!
/**
UITableViewController subclass.
This is the `root` view controller which displays vertical stack of cards.
Each card in stack can be expanded.
*/
open class ElongationViewController: SwipableTableViewController {
// MARK: Public properties
/// `IndexPath` of expanded cell.
public var expandedIndexPath: IndexPath?
/// Should cell change it's state to `expand` on tap.
/// Default value: `true`
public var shouldExpand = true
/// Represents view state.
public enum State {
/// View in normal state. All cells `collapsed`.
case normal
/// View in `expanded` state. One of the cells is in `expanded` state.
case expanded
}
/// Current view state.
/// Default value: `.normal`
public var state: State = .normal {
didSet {
let expanded = state == .expanded
tapGesture.isEnabled = expanded
tableView.allowsSelection = !expanded
tableView.panGestureRecognizer.isEnabled = !expanded
}
}
// MARK: Private properties
fileprivate var cellStatesDictionary: [IndexPath: Bool] = [:]
fileprivate var tapGesture: UITapGestureRecognizer!
fileprivate var longPressGesture: UILongPressGestureRecognizer!
fileprivate var config: ElongationConfig {
return ElongationConfig.shared
}
fileprivate var parallaxConfigured = false
fileprivate var shouldCommitPreviewAction = false
}
// MARK: - Lifecycle 🌎
extension ElongationViewController {
override open func viewDidLoad() {
super.viewDidLoad()
setup()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// We need to call this method to set parallax start offset
guard config.isParallaxEnabled, !parallaxConfigured else { return }
parallaxConfigured = true
scrollViewDidScroll(tableView)
}
}
// MARK: - Setup ⛏
private extension ElongationViewController {
func setup() {
setupTableView()
setupTapGesture()
if #available(iOS 10, *), traitCollection.forceTouchCapability == .available, config.forceTouchPreviewInteractionEnabled {
interaction = UIPreviewInteraction(view: view)
interaction.delegate = self
} else if config.forceTouchPreviewInteractionEnabled {
setupLongPressGesture()
}
}
private func setupTableView() {
tableView.separatorStyle = .none
}
private func setupTapGesture() {
tapGesture = UITapGestureRecognizer(target: self, action: #selector(tableViewTapped(_:)))
tapGesture.isEnabled = false
tableView.addGestureRecognizer(tapGesture)
}
private func setupLongPressGesture() {
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressGestureAction(_:)))
tableView.addGestureRecognizer(longPressGesture)
}
}
// MARK: - Actions ⚡
extension ElongationViewController {
// MARK: Public
/// Collapse expanded cell.
///
/// - Parameter animated: should animate changing tableView's frame.
public func collapseCells(animated: Bool = true) {
for (path, state) in cellStatesDictionary where state {
moveCells(from: path, force: false, animated: animated)
}
}
/// Expand cell at given `IndexPath`.
/// View must be in `normal` state.
///
/// - Parameter indexPath: IndexPath of target cell
public func expandCell(at indexPath: IndexPath) {
guard state == .normal else {
print("The view is in `expanded` state already. You must collapse the cells before calling this method.")
return
}
moveCells(from: indexPath, force: true)
}
/// Present modal view controller for cell at given `IndexPath`.
///
/// - Parameter indexPath: IndexPath of source cell.
open func openDetailView(for indexPath: IndexPath) {
let viewController = ElongationDetailViewController(nibName: nil, bundle: nil)
expand(viewController: viewController)
}
/// Expand given `ElongationDetailViewController`
///
/// - Parameters:
/// - viewController: `ElongationDetailViewController` subclass which will be added to view hierarchy.
/// - animated: Should the transition be animated.
/// - completion: Optional callback which will be called when transition completes.
public func expand(viewController: ElongationDetailViewController, animated: Bool = true, completion: (() -> Void)? = nil) {
viewController.modalPresentationStyle = .custom
viewController.transitioningDelegate = self
present(viewController, animated: animated, completion: completion)
}
// MARK: Private
@objc fileprivate func tableViewTapped(_ gesture: UITapGestureRecognizer) {
guard let path = expandedIndexPath else { return }
let location = gesture.location(in: tableView)
let realPoint = tableView.convert(location, to: UIScreen.main.coordinateSpace)
let cellFrame = tableView.rectForRow(at: path).offsetBy(dx: -tableView.contentOffset.x, dy: -tableView.contentOffset.y)
if realPoint.y < cellFrame.minY || realPoint.y > cellFrame.maxY {
collapseCells()
return
}
guard let indexPath = tableView.indexPathForRow(at: location), let cell = tableView.cellForRow(at: indexPath) as? ElongationCell else { return }
let point = cell.convert(location, from: tableView)
let elongationCellTouchAction = config.cellTouchAction
guard let touchedView = cell.hitTest(point, with: nil) else {
collapseCells()
return
}
switch touchedView {
case cell.bottomView:
switch elongationCellTouchAction {
case .expandOnBoth, .expandOnBottom, .collapseOnTopExpandOnBottom:
openDetailView(for: path)
case .collapseOnBoth, .collapseOnBottomExpandOnTop: collapseCells()
default: break
}
case cell.scalableView:
switch elongationCellTouchAction {
case .collapseOnBoth, .collapseOnTopExpandOnBottom: collapseCells()
case .collapseOnBottomExpandOnTop, .expandOnBoth, .expandOnTop: openDetailView(for: path)
default: break
}
default:
switch elongationCellTouchAction {
case .expandOnBoth: openDetailView(for: path)
case .collapseOnBoth: collapseCells()
default: break
}
}
}
fileprivate func moveCells(from indexPath: IndexPath, force: Bool? = nil, animated: Bool = true) {
guard let cell = tableView.cellForRow(at: indexPath) as? ElongationCell else { return }
let shouldExpand = force ?? !(cellStatesDictionary[indexPath] ?? false)
shouldCommitPreviewAction = false
cell.expand(shouldExpand, animated: animated) { _ in
self.shouldCommitPreviewAction = true
}
cellStatesDictionary[indexPath] = shouldExpand
// Change `self` properties
state = shouldExpand ? .expanded : .normal
expandedIndexPath = shouldExpand ? indexPath : nil
// Fade in overlay view on visible cells except expanding one
for case let elongationCell as ElongationCell in tableView.visibleCells where elongationCell != cell {
elongationCell.dim(shouldExpand)
elongationCell.hideSeparator(shouldExpand, animated: animated)
}
if !animated {
UIView.setAnimationsEnabled(false)
}
tableView.beginUpdates()
tableView.endUpdates()
if !animated {
UIView.setAnimationsEnabled(true)
}
// Scroll to calculated rect only if it's not going to collapse whole tableView
if force == nil {
switch config.expandingBehaviour {
case .centerInView: tableView.scrollToRow(at: indexPath, at: .middle, animated: animated)
case .scrollToBottom: tableView.scrollToRow(at: indexPath, at: .bottom, animated: animated)
case .scrollToTop: tableView.scrollToRow(at: indexPath, at: .top, animated: animated)
default: break
}
}
guard !shouldExpand else { return }
for case let elongationCell as ElongationCell in tableView.visibleCells where elongationCell != cell {
elongationCell.parallaxOffset(offsetY: tableView.contentOffset.y, height: tableView.bounds.height)
}
}
override func gestureRecognizerSwiped(_ gesture: UIPanGestureRecognizer) {
let point = gesture.location(in: tableView)
guard let path = tableView.indexPathForRow(at: point), path == expandedIndexPath, let cell = tableView.cellForRow(at: path) as? ElongationCell else { return }
let convertedPoint = cell.convert(point, from: tableView)
guard let view = cell.hitTest(convertedPoint, with: nil) else { return }
if gesture.state == .began {
startY = convertedPoint.y
}
let newY = convertedPoint.y
let goingToBottom = startY < newY
let rangeReached = abs(startY - newY) > 50
switch view {
case cell.scalableView where swipedView == cell.scalableView && rangeReached:
if goingToBottom {
collapseCells(animated: true)
} else {
openDetailView(for: path)
}
startY = newY
case cell.bottomView where swipedView == cell.bottomView && rangeReached:
if goingToBottom {
openDetailView(for: path)
} else {
collapseCells(animated: true)
}
startY = newY
default: break
}
swipedView = view
}
@objc fileprivate func longPressGestureAction(_ sender: UILongPressGestureRecognizer) {
let location = sender.location(in: tableView)
guard sender.state == .began, let path = tableView.indexPathForRow(at: location) else { return }
expandedIndexPath = path
moveCells(from: path)
}
}
// MARK: - TableView 📚
extension ElongationViewController {
/// Must call `super` if you override this method in subclass.
open override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let cell = cell as? ElongationCell else { return }
let expanded = state == .expanded
cell.dim(expanded, animated: expanded)
// Remove separators from top and bottom cells.
guard config.customSeparatorEnabled else { return }
cell.hideSeparator(expanded, animated: expanded)
let numberOfRowsInSection = tableView.numberOfRows(inSection: indexPath.section)
if indexPath.row == 0 || indexPath.row == numberOfRowsInSection - 1 {
let separator = indexPath.row == 0 ? cell.topSeparatorLine : cell.bottomSeparatorLine
separator?.backgroundColor = UIColor.black
} else {
cell.topSeparatorLine?.backgroundColor = config.separatorColor
cell.bottomSeparatorLine?.backgroundColor = config.separatorColor
}
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard shouldExpand else { return }
DispatchQueue.main.async {
self.expandedIndexPath = indexPath
self.openDetailView(for: indexPath)
}
}
open override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let isExpanded = cellStatesDictionary[indexPath] ?? false
let frontViewHeight = config.topViewHeight
let expandedCellHeight = config.bottomViewHeight + frontViewHeight - config.bottomViewOffset
return isExpanded ? expandedCellHeight : frontViewHeight
}
/// Must call `super` if you override this method in subclass.
open override func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard scrollView === tableView, config.isParallaxEnabled else { return }
for case let cell as ElongationCell in tableView.visibleCells {
cell.parallaxOffset(offsetY: tableView.contentOffset.y, height: tableView.bounds.height)
}
}
}
// MARK: - 3D Touch Preview Interaction
@available(iOS 10.0, *)
extension ElongationViewController: UIPreviewInteractionDelegate {
public func previewInteractionDidCancel(_ previewInteraction: UIPreviewInteraction) {
collapseCells()
panGestureRecognizer.isEnabled = true
// This trick will prevent expanding cell in `didSelectRowAt indexPath` method
tableView.allowsSelection = false
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
self.tableView.allowsSelection = true
}
}
public func previewInteraction(_ previewInteraction: UIPreviewInteraction, didUpdatePreviewTransition transitionProgress: CGFloat, ended: Bool) {
guard ended else { return }
panGestureRecognizer.isEnabled = false
let location = previewInteraction.location(in: tableView)
guard let path = tableView.indexPathForRow(at: location) else { return }
if path == expandedIndexPath {
openDetailView(for: path)
previewInteraction.cancel()
} else {
moveCells(from: path)
}
}
public func previewInteraction(_ previewInteraction: UIPreviewInteraction, didUpdateCommitTransition transitionProgress: CGFloat, ended: Bool) {
guard ended else { return }
guard let path = expandedIndexPath else { return }
panGestureRecognizer.isEnabled = false
if shouldCommitPreviewAction {
openDetailView(for: path)
} else {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
self.openDetailView(for: path)
}
}
}
}
// MARK: - Transition
extension ElongationViewController: UIViewControllerTransitioningDelegate {
/// This transition object will be used while dismissing `ElongationDetailViewController`.
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ElongationTransition(presenting: false)
}
/// This transition object will be used while presenting `ElongationDetailViewController`.
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ElongationTransition(presenting: true)
}
}
changed tableView behaviour when `ElongationCell` goes to expanded cell
//
// ElongationViewController.swift
// ElongationPreview
//
// Created by Abdurahim Jauzee on 08/02/2017.
// Copyright © 2017 Ramotion. All rights reserved.
//
import UIKit
@available(iOS 10, *)
fileprivate var interaction: UIPreviewInteraction!
/**
UITableViewController subclass.
This is the `root` view controller which displays vertical stack of cards.
Each card in stack can be expanded.
*/
open class ElongationViewController: SwipableTableViewController {
// MARK: Public properties
/// `IndexPath` of expanded cell.
public var expandedIndexPath: IndexPath?
/// Should cell change it's state to `expand` on tap.
/// Default value: `true`
public var shouldExpand = true
/// Represents view state.
public enum State {
/// View in normal state. All cells `collapsed`.
case normal
/// View in `expanded` state. One of the cells is in `expanded` state.
case expanded
}
/// Current view state.
/// Default value: `.normal`
public var state: State = .normal {
didSet {
let expanded = state == .expanded
tapGesture.isEnabled = expanded
tableView.allowsSelection = !expanded
tableView.panGestureRecognizer.isEnabled = !expanded
}
}
// MARK: Private properties
fileprivate var cellStatesDictionary: [IndexPath: Bool] = [:]
fileprivate var tapGesture: UITapGestureRecognizer!
fileprivate var longPressGesture: UILongPressGestureRecognizer!
fileprivate var config: ElongationConfig {
return ElongationConfig.shared
}
fileprivate var parallaxConfigured = false
fileprivate var shouldCommitPreviewAction = false
}
// MARK: - Lifecycle 🌎
extension ElongationViewController {
override open func viewDidLoad() {
super.viewDidLoad()
setup()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// We need to call this method to set parallax start offset
guard config.isParallaxEnabled, !parallaxConfigured else { return }
parallaxConfigured = true
scrollViewDidScroll(tableView)
}
}
// MARK: - Setup ⛏
private extension ElongationViewController {
func setup() {
setupTableView()
setupTapGesture()
if #available(iOS 10, *), traitCollection.forceTouchCapability == .available, config.forceTouchPreviewInteractionEnabled {
interaction = UIPreviewInteraction(view: view)
interaction.delegate = self
} else if config.forceTouchPreviewInteractionEnabled {
setupLongPressGesture()
}
}
private func setupTableView() {
tableView.separatorStyle = .none
}
private func setupTapGesture() {
tapGesture = UITapGestureRecognizer(target: self, action: #selector(tableViewTapped(_:)))
tapGesture.isEnabled = false
tableView.addGestureRecognizer(tapGesture)
}
private func setupLongPressGesture() {
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressGestureAction(_:)))
tableView.addGestureRecognizer(longPressGesture)
}
}
// MARK: - Actions ⚡
extension ElongationViewController {
// MARK: Public
/// Collapse expanded cell.
///
/// - Parameter animated: should animate changing tableView's frame.
public func collapseCells(animated: Bool = true) {
for (path, state) in cellStatesDictionary where state {
moveCells(from: path, force: false, animated: animated)
}
}
/// Expand cell at given `IndexPath`.
/// View must be in `normal` state.
///
/// - Parameter indexPath: IndexPath of target cell
public func expandCell(at indexPath: IndexPath) {
guard state == .normal else {
print("The view is in `expanded` state already. You must collapse the cells before calling this method.")
return
}
moveCells(from: indexPath, force: true)
}
/// Present modal view controller for cell at given `IndexPath`.
///
/// - Parameter indexPath: IndexPath of source cell.
open func openDetailView(for indexPath: IndexPath) {
let viewController = ElongationDetailViewController(nibName: nil, bundle: nil)
expand(viewController: viewController)
}
/// Expand given `ElongationDetailViewController`
///
/// - Parameters:
/// - viewController: `ElongationDetailViewController` subclass which will be added to view hierarchy.
/// - animated: Should the transition be animated.
/// - completion: Optional callback which will be called when transition completes.
public func expand(viewController: ElongationDetailViewController, animated: Bool = true, completion: (() -> Void)? = nil) {
viewController.modalPresentationStyle = .custom
viewController.transitioningDelegate = self
present(viewController, animated: animated, completion: completion)
}
// MARK: Private
@objc fileprivate func tableViewTapped(_ gesture: UITapGestureRecognizer) {
guard let path = expandedIndexPath else { return }
let location = gesture.location(in: tableView)
let realPoint = tableView.convert(location, to: UIScreen.main.coordinateSpace)
let cellFrame = tableView.rectForRow(at: path).offsetBy(dx: -tableView.contentOffset.x, dy: -tableView.contentOffset.y)
if realPoint.y < cellFrame.minY || realPoint.y > cellFrame.maxY {
collapseCells()
return
}
guard let indexPath = tableView.indexPathForRow(at: location), let cell = tableView.cellForRow(at: indexPath) as? ElongationCell else { return }
let point = cell.convert(location, from: tableView)
let elongationCellTouchAction = config.cellTouchAction
guard let touchedView = cell.hitTest(point, with: nil) else {
collapseCells()
return
}
switch touchedView {
case cell.bottomView:
switch elongationCellTouchAction {
case .expandOnBoth, .expandOnBottom, .collapseOnTopExpandOnBottom:
openDetailView(for: path)
case .collapseOnBoth, .collapseOnBottomExpandOnTop: collapseCells()
default: break
}
case cell.scalableView:
switch elongationCellTouchAction {
case .collapseOnBoth, .collapseOnTopExpandOnBottom: collapseCells()
case .collapseOnBottomExpandOnTop, .expandOnBoth, .expandOnTop: openDetailView(for: path)
default: break
}
default:
switch elongationCellTouchAction {
case .expandOnBoth: openDetailView(for: path)
case .collapseOnBoth: collapseCells()
default: break
}
}
}
fileprivate func moveCells(from indexPath: IndexPath, force: Bool? = nil, animated: Bool = true) {
guard let cell = tableView.cellForRow(at: indexPath) as? ElongationCell else { return }
let shouldExpand = force ?? !(cellStatesDictionary[indexPath] ?? false)
shouldCommitPreviewAction = false
cell.expand(shouldExpand, animated: animated) { _ in
self.shouldCommitPreviewAction = true
}
cellStatesDictionary[indexPath] = shouldExpand
// Change `self` properties
state = shouldExpand ? .expanded : .normal
expandedIndexPath = shouldExpand ? indexPath : nil
// Fade in overlay view on visible cells except expanding one
for case let elongationCell as ElongationCell in tableView.visibleCells where elongationCell != cell {
elongationCell.dim(shouldExpand)
elongationCell.hideSeparator(shouldExpand, animated: animated)
}
if !animated {
UIView.setAnimationsEnabled(false)
}
tableView.beginUpdates()
tableView.endUpdates()
if !animated {
UIView.setAnimationsEnabled(true)
}
// Scroll to calculated rect only if it's not going to collapse whole tableView
if force == nil {
let cellFrame = cell.frame
let scrollToFrame = cellFrame
if scrollToFrame.maxY > tableView.contentSize.height {
tableView.scrollToRow(at: indexPath, at: .bottom, animated: animated)
} else {
tableView.scrollRectToVisible(scrollToFrame, animated: animated)
}
}
guard !shouldExpand else { return }
for case let elongationCell as ElongationCell in tableView.visibleCells where elongationCell != cell {
elongationCell.parallaxOffset(offsetY: tableView.contentOffset.y, height: tableView.bounds.height)
}
}
override func gestureRecognizerSwiped(_ gesture: UIPanGestureRecognizer) {
let point = gesture.location(in: tableView)
guard let path = tableView.indexPathForRow(at: point), path == expandedIndexPath, let cell = tableView.cellForRow(at: path) as? ElongationCell else { return }
let convertedPoint = cell.convert(point, from: tableView)
guard let view = cell.hitTest(convertedPoint, with: nil) else { return }
if gesture.state == .began {
startY = convertedPoint.y
}
let newY = convertedPoint.y
let goingToBottom = startY < newY
let rangeReached = abs(startY - newY) > 50
switch view {
case cell.scalableView where swipedView == cell.scalableView && rangeReached:
if goingToBottom {
collapseCells(animated: true)
} else {
openDetailView(for: path)
}
startY = newY
case cell.bottomView where swipedView == cell.bottomView && rangeReached:
if goingToBottom {
openDetailView(for: path)
} else {
collapseCells(animated: true)
}
startY = newY
default: break
}
swipedView = view
}
@objc fileprivate func longPressGestureAction(_ sender: UILongPressGestureRecognizer) {
let location = sender.location(in: tableView)
guard sender.state == .began, let path = tableView.indexPathForRow(at: location) else { return }
expandedIndexPath = path
moveCells(from: path)
}
}
// MARK: - TableView 📚
extension ElongationViewController {
/// Must call `super` if you override this method in subclass.
open override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let cell = cell as? ElongationCell else { return }
let expanded = state == .expanded
cell.dim(expanded, animated: true)
// Remove separators from top and bottom cells.
guard config.customSeparatorEnabled else { return }
cell.hideSeparator(expanded, animated: expanded)
let numberOfRowsInSection = tableView.numberOfRows(inSection: indexPath.section)
if indexPath.row == 0 || indexPath.row == numberOfRowsInSection - 1 {
let separator = indexPath.row == 0 ? cell.topSeparatorLine : cell.bottomSeparatorLine
separator?.backgroundColor = UIColor.black
} else {
cell.topSeparatorLine?.backgroundColor = config.separatorColor
cell.bottomSeparatorLine?.backgroundColor = config.separatorColor
}
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard shouldExpand else { return }
DispatchQueue.main.async {
self.expandedIndexPath = indexPath
self.openDetailView(for: indexPath)
}
}
open override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let isExpanded = cellStatesDictionary[indexPath] ?? false
let frontViewHeight = config.topViewHeight
let expandedCellHeight = config.bottomViewHeight + frontViewHeight - config.bottomViewOffset
return isExpanded ? expandedCellHeight : frontViewHeight
}
/// Must call `super` if you override this method in subclass.
open override func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard scrollView === tableView, config.isParallaxEnabled else { return }
for case let cell as ElongationCell in tableView.visibleCells {
cell.parallaxOffset(offsetY: tableView.contentOffset.y, height: tableView.bounds.height)
}
}
}
// MARK: - 3D Touch Preview Interaction
@available(iOS 10.0, *)
extension ElongationViewController: UIPreviewInteractionDelegate {
public func previewInteractionDidCancel(_ previewInteraction: UIPreviewInteraction) {
collapseCells()
panGestureRecognizer.isEnabled = true
// This trick will prevent expanding cell in `didSelectRowAt indexPath` method
tableView.allowsSelection = false
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
self.tableView.allowsSelection = true
}
}
public func previewInteraction(_ previewInteraction: UIPreviewInteraction, didUpdatePreviewTransition transitionProgress: CGFloat, ended: Bool) {
guard ended else { return }
panGestureRecognizer.isEnabled = false
let location = previewInteraction.location(in: tableView)
guard let path = tableView.indexPathForRow(at: location) else { return }
if path == expandedIndexPath {
openDetailView(for: path)
previewInteraction.cancel()
} else {
moveCells(from: path)
}
}
public func previewInteraction(_ previewInteraction: UIPreviewInteraction, didUpdateCommitTransition transitionProgress: CGFloat, ended: Bool) {
guard ended else { return }
guard let path = expandedIndexPath else { return }
panGestureRecognizer.isEnabled = false
if shouldCommitPreviewAction {
openDetailView(for: path)
} else {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
self.openDetailView(for: path)
}
}
}
}
// MARK: - Transition
extension ElongationViewController: UIViewControllerTransitioningDelegate {
/// This transition object will be used while dismissing `ElongationDetailViewController`.
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ElongationTransition(presenting: false)
}
/// This transition object will be used while presenting `ElongationDetailViewController`.
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ElongationTransition(presenting: true)
}
}
|
public final class MarshroutePrintManager {
private static var sharedInstance: MarshroutePrintPlugin = DefaultMarshroutePrintPlugin()
public static func setupPrintPlugin(_ plugin: MarshroutePrintPlugin) {
sharedInstance = plugin
}
static func print(_ item: Any, separator: String, terminator: String) {
sharedInstance.print(item, separator: separator, terminator: terminator)
}
static func debugPrint(_ item: Any, separator: String, terminator: String) {
sharedInstance.print(item, separator: separator, terminator: terminator)
}
}
AI-7358: Refactor print manager
public final class MarshroutePrintManager {
private static var instance: MarshroutePrintPlugin = DefaultMarshroutePrintPlugin()
public static func setUpPrintPlugin(_ plugin: MarshroutePrintPlugin) {
instance = plugin
}
static func print(_ item: Any, separator: String, terminator: String) {
instance.print(item, separator: separator, terminator: terminator)
}
static func debugPrint(_ item: Any, separator: String, terminator: String) {
instance.print(item, separator: separator, terminator: terminator)
}
}
|
//
// GeneralPreferencePane.swift
// Pock
//
// Created by Pierluigi Galdi on 12/10/2018.
// Copyright © 2018 Pierluigi Galdi. All rights reserved.
//
import Foundation
import Preferences
import Defaults
import LaunchAtLogin
final class GeneralPreferencePane: NSViewController, Preferenceable {
/// UI
@IBOutlet weak var versionLabel: NSTextField!
@IBOutlet weak var notificationBadgeRefreshRatePicker: NSPopUpButton!
@IBOutlet weak var launchAtLoginCheckbox: NSButton!
@IBOutlet weak var checkForUpdatesButton: NSButton!
/// Core
private var appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String ?? "Unknown"
/// Preferenceable
let toolbarItemTitle: String = "General"
let toolbarItemIcon: NSImage = NSImage(named: NSImage.Name("pock-icon"))!
override var nibName: NSNib.Name? {
return NSNib.Name(rawValue: "GeneralPreferencePane")
}
override func viewWillAppear() {
super.viewWillAppear()
self.loadVersionNumber()
self.populatePopUpButton()
self.setupLaunchAtLoginCheckbox()
}
private func loadVersionNumber() {
self.versionLabel.stringValue = appVersion
}
private func populatePopUpButton() {
self.notificationBadgeRefreshRatePicker.removeAllItems()
self.notificationBadgeRefreshRatePicker.addItems(withTitles: NotificationBadgeRefreshRateKeys.allCases.map({ $0.toString() }))
self.notificationBadgeRefreshRatePicker.selectItem(withTitle: defaults[.notificationBadgeRefreshInterval].toString())
}
private func setupLaunchAtLoginCheckbox() {
self.launchAtLoginCheckbox.state = LaunchAtLogin.isEnabled ? .on : .off
}
@IBAction private func didSelectNotificationBadgeRefreshRate(_: NSButton) {
defaults[.notificationBadgeRefreshInterval] = NotificationBadgeRefreshRateKeys.allCases[self.notificationBadgeRefreshRatePicker.indexOfSelectedItem]
NSWorkspace.shared.notificationCenter.post(name: .didChangeNotificationBadgeRefreshRate, object: nil)
}
@IBAction private func didChangeLaunchAtLoginValue(button: NSButton) {
LaunchAtLogin.isEnabled = button.state == .on
}
@IBAction private func checkForUpdates(_: NSButton) {
self.checkForUpdatesButton.isEnabled = false
self.checkForUpdatesButton.title = "Checking..."
let latestVersionURL: URL = URL(string: "http://pock.pigigaldi.com/api/latestRelease.json")!
URLSession.shared.dataTask(with: latestVersionURL, completionHandler: { [weak self] data, response, error in
guard let _self = self else { return }
defer {
DispatchQueue.main.async { [weak self] in
self?.checkForUpdatesButton.isEnabled = true
self?.checkForUpdatesButton.title = "Check for updates"
}
}
if let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [String: String] {
if let latestVersionNumber = json?["version_number"] {
DispatchQueue.main.async {
let alert: NSAlert = NSAlert()
alert.alertStyle = NSAlert.Style.informational
if let downloadLink = json?["download_link"], let downloadURL = URL(string: downloadLink), _self.appVersion < latestVersionNumber {
alert.messageText = "New version available!"
alert.informativeText = "Do you want to download version \"\(latestVersionNumber)\" now?"
alert.addButton(withTitle: "Download")
alert.addButton(withTitle: "Later")
alert.beginSheetModal(for: _self.view.window!, completionHandler: { modalResponse in
if modalResponse == .alertFirstButtonReturn {
NSWorkspace.shared.open(downloadURL)
}
})
}else {
alert.messageText = "Installed version: \(_self.appVersion)"
alert.informativeText = "Already on latest version"
alert.addButton(withTitle: "Ok")
alert.beginSheetModal(for: _self.view.window!, completionHandler: nil)
}
}
}
}
}).resume()
}
}
Use class fun to retrieve latest version
//
// GeneralPreferencePane.swift
// Pock
//
// Created by Pierluigi Galdi on 12/10/2018.
// Copyright © 2018 Pierluigi Galdi. All rights reserved.
//
import Foundation
import Preferences
import Defaults
import LaunchAtLogin
final class GeneralPreferencePane: NSViewController, Preferenceable {
/// UI
@IBOutlet weak var versionLabel: NSTextField!
@IBOutlet weak var notificationBadgeRefreshRatePicker: NSPopUpButton!
@IBOutlet weak var launchAtLoginCheckbox: NSButton!
@IBOutlet weak var checkForUpdatesButton: NSButton!
/// Core
private static let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String ?? "Unknown"
/// Preferenceable
let toolbarItemTitle: String = "General"
let toolbarItemIcon: NSImage = NSImage(named: NSImage.Name("pock-icon"))!
override var nibName: NSNib.Name? {
return NSNib.Name(rawValue: "GeneralPreferencePane")
}
override func viewWillAppear() {
super.viewWillAppear()
self.loadVersionNumber()
self.populatePopUpButton()
self.setupLaunchAtLoginCheckbox()
}
private func loadVersionNumber() {
self.versionLabel.stringValue = GeneralPreferencePane.appVersion
}
private func populatePopUpButton() {
self.notificationBadgeRefreshRatePicker.removeAllItems()
self.notificationBadgeRefreshRatePicker.addItems(withTitles: NotificationBadgeRefreshRateKeys.allCases.map({ $0.toString() }))
self.notificationBadgeRefreshRatePicker.selectItem(withTitle: defaults[.notificationBadgeRefreshInterval].toString())
}
private func setupLaunchAtLoginCheckbox() {
self.launchAtLoginCheckbox.state = LaunchAtLogin.isEnabled ? .on : .off
}
@IBAction private func didSelectNotificationBadgeRefreshRate(_: NSButton) {
defaults[.notificationBadgeRefreshInterval] = NotificationBadgeRefreshRateKeys.allCases[self.notificationBadgeRefreshRatePicker.indexOfSelectedItem]
NSWorkspace.shared.notificationCenter.post(name: .didChangeNotificationBadgeRefreshRate, object: nil)
}
@IBAction private func didChangeLaunchAtLoginValue(button: NSButton) {
LaunchAtLogin.isEnabled = button.state == .on
}
@IBAction private func checkForUpdates(_: NSButton) {
self.checkForUpdatesButton.isEnabled = false
self.checkForUpdatesButton.title = "Checking..."
GeneralPreferencePane.hasLatestVersion(completion: { [weak self] latestVersion, latestVersionDownloadURL in
guard let _self = self else { return }
DispatchQueue.main.async {
let alert: NSAlert = NSAlert()
alert.alertStyle = NSAlert.Style.informational
if let latestVersion = latestVersion, let latestVersionDownloadURL = latestVersionDownloadURL {
alert.messageText = "New version available!"
alert.informativeText = "Do you want to download version \"\(latestVersion)\" now?"
alert.addButton(withTitle: "Download")
alert.addButton(withTitle: "Later")
alert.beginSheetModal(for: _self.view.window!, completionHandler: { modalResponse in
if modalResponse == .alertFirstButtonReturn {
NSWorkspace.shared.open(latestVersionDownloadURL)
}
})
}else {
alert.messageText = "Installed version: \(GeneralPreferencePane.appVersion)"
alert.informativeText = "Already on latest version"
alert.addButton(withTitle: "Ok")
alert.beginSheetModal(for: _self.view.window!, completionHandler: nil)
}
self?.checkForUpdatesButton.isEnabled = true
self?.checkForUpdatesButton.title = "Check for updates"
}
})
}
}
extension GeneralPreferencePane {
class func hasLatestVersion(completion: @escaping (String?, URL?) -> Void) {
let latestVersionURL: URL = URL(string: "http://pock.pigigaldi.com/api/latestRelease.json")!
URLSession.shared.dataTask(with: latestVersionURL, completionHandler: { data, response, error in
guard let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [String: String],
let latestVersionNumber = json?["version_number"], GeneralPreferencePane.appVersion < latestVersionNumber,
let downloadLink = json?["download_link"],
let downloadURL = URL(string: downloadLink) else {
completion(nil, nil)
return
}
completion(latestVersionNumber, downloadURL)
}).resume()
}
}
|
//
// Copyright 2020 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
/// Controller for custom sized presentations. By default, presented view controller will be sized as both half of the screen in width and height, and will be centered to the screen. Implement `CustomSizedPresentable` in presented view controller to change that if needed. This class can also be set as `transitioningDelegate` as presented view controller, as it's conforming `UIViewControllerTransitioningDelegate`.
@objcMembers
class CustomSizedPresentationController: UIPresentationController {
// MARK: - Public Properties
/// Corner radius for presented view controller's view. Default value is `8.0`.
var cornerRadius: CGFloat = 8.0
/// Background color of dimming view, which is located behind the presented view controller's view. Default value is `white with 0.5 alpha`.
var dimColor: UIColor = UIColor(white: 0.0, alpha: 0.5)
/// Dismiss view controller when background tapped. Default value is `true`.
var dismissOnBackgroundTap: Bool = true
// MARK: - Private Properties
/// Dim view
private var dimmingView: UIView!
/// Wrapper view for presentation. It's introduced to handle corner radius on presented view controller's view and it's superview of all other views.
private var presentationWrappingView: UIView!
// MARK: - Initializer
override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) {
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
presentedViewController.modalPresentationStyle = .custom
}
// MARK: - Actions
@objc private func dimmingViewTapped(_ sender: UITapGestureRecognizer) {
if dismissOnBackgroundTap {
presentedViewController.dismiss(animated: true, completion: nil)
}
}
// MARK: - Presentation
override func presentationTransitionWillBegin() {
guard let presentedViewControllerView = super.presentedView else { return }
// Wrap the presented view controller's view in an intermediate hierarchy
// that applies a shadow and rounded corners to the top-left and top-right
// edges. The final effect is built using three intermediate views.
//
// presentationWrapperView <- shadow
// |- presentationRoundedCornerView <- rounded corners (masksToBounds)
// |- presentedViewControllerWrapperView
// |- presentedViewControllerView (presentedViewController.view)
//
// SEE ALSO: The note in AAPLCustomPresentationSecondViewController.m.
do {
let presentationWrapperView = UIView(frame: frameOfPresentedViewInContainerView)
presentationWrapperView.layer.shadowOffset = CGSize(width: 0, height: -2)
presentationWrapperView.layer.shadowRadius = 10
presentationWrapperView.layer.shadowColor = UIColor(white: 0, alpha: 0.5).cgColor
presentationWrappingView = presentationWrapperView
// presentationRoundedCornerView is CORNER_RADIUS points taller than the
// height of the presented view controller's view. This is because
// the cornerRadius is applied to all corners of the view. Since the
// effect calls for only the top two corners to be rounded we size
// the view such that the bottom CORNER_RADIUS points lie below
// the bottom edge of the screen.
let cornerViewRect = presentationWrapperView.bounds//.inset(by: UIEdgeInsets(top: 0, left: 0, bottom: -cornerRadius, right: 0))
let presentationRoundedCornerView = UIView(frame: cornerViewRect)
presentationRoundedCornerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
presentationRoundedCornerView.layer.cornerRadius = cornerRadius
presentationRoundedCornerView.layer.masksToBounds = true
// To undo the extra height added to presentationRoundedCornerView,
// presentedViewControllerWrapperView is inset by CORNER_RADIUS points.
// This also matches the size of presentedViewControllerWrapperView's
// bounds to the size of -frameOfPresentedViewInContainerView.
let wrapperRect = presentationRoundedCornerView.bounds
let presentedViewControllerWrapperView = UIView(frame: wrapperRect)
presentedViewControllerWrapperView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Add presentedViewControllerView -> presentedViewControllerWrapperView.
presentedViewControllerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
presentedViewControllerView.frame = presentedViewControllerWrapperView.bounds
presentedViewControllerWrapperView.addSubview(presentedViewControllerView)
// Add presentedViewControllerWrapperView -> presentationRoundedCornerView.
presentationRoundedCornerView.addSubview(presentedViewControllerWrapperView)
// Add presentationRoundedCornerView -> presentationWrapperView.
presentationWrapperView.addSubview(presentationRoundedCornerView)
}
// Add a dimming view behind presentationWrapperView. self.presentedView
// is added later (by the animator) so any views added here will be
// appear behind the -presentedView.
do {
let dimmingView = UIView(frame: containerView?.bounds ?? .zero)
dimmingView.backgroundColor = dimColor
dimmingView.isOpaque = false
dimmingView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dimmingViewTapped(_:)))
dimmingView.addGestureRecognizer(tapGestureRecognizer)
self.dimmingView = dimmingView
containerView?.addSubview(dimmingView)
// Get the transition coordinator for the presentation so we can
// fade in the dimmingView alongside the presentation animation.
let transitionCoordinator = self.presentingViewController.transitionCoordinator
dimmingView.alpha = 0.0
transitionCoordinator?.animate(alongsideTransition: { _ in
self.dimmingView?.alpha = 1.0
}, completion: nil)
}
}
override func presentationTransitionDidEnd(_ completed: Bool) {
if !completed {
presentationWrappingView = nil
dimmingView = nil
}
}
// MARK: - Dismissal
override func dismissalTransitionWillBegin() {
guard let coordinator = presentingViewController.transitionCoordinator else {
dimmingView.alpha = 0.0
return
}
coordinator.animate(alongsideTransition: { _ in
self.dimmingView.alpha = 0.0
})
}
override func dismissalTransitionDidEnd(_ completed: Bool) {
if completed {
presentationWrappingView = nil
dimmingView = nil
}
}
// MARK: - Overrides
override var presentedView: UIView? {
return presentationWrappingView
}
override func size(forChildContentContainer container: UIContentContainer,
withParentContainerSize parentSize: CGSize) -> CGSize {
guard container === presentedViewController else {
return super.size(forChildContentContainer: container, withParentContainerSize: parentSize)
}
// return value from presentable if implemented
if let presentable = presentedViewController as? CustomSizedPresentable, let customSize = presentable.customSize?(withParentContainerSize: parentSize) {
return customSize
}
// half of the width/height by default
return CGSize(width: parentSize.width/2.0, height: parentSize.height/2.0)
}
override var frameOfPresentedViewInContainerView: CGRect {
guard let containerView = containerView else {
return super.frameOfPresentedViewInContainerView
}
let size = self.size(forChildContentContainer: presentedViewController,
withParentContainerSize: containerView.bounds.size)
// use origin value from presentable if implemented
if let presentable = presentedViewController as? CustomSizedPresentable, let origin = presentable.position?(withParentContainerSize: containerView.bounds.size) {
return CGRect(origin: origin, size: size)
}
// center presented view by default
let origin = CGPoint(x: (containerView.bounds.width - size.width)/2,
y: (containerView.bounds.height - size.height)/2)
return CGRect(origin: origin, size: size)
}
override func containerViewWillLayoutSubviews() {
super.containerViewWillLayoutSubviews()
self.dimmingView?.frame = containerView?.bounds ?? .zero
self.presentationWrappingView?.frame = frameOfPresentedViewInContainerView
}
override func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer) {
super.preferredContentSizeDidChange(forChildContentContainer: container)
if container === presentedViewController {
self.containerView?.setNeedsLayout()
}
}
}
// MARK: - UIViewControllerTransitioningDelegate
extension CustomSizedPresentationController: UIViewControllerTransitioningDelegate {
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
return CustomSizedPresentationController(presentedViewController: presented, presenting: presenting)
}
}
Fix warnings, pass properties to new instance
//
// Copyright 2020 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
/// Controller for custom sized presentations.
/// By default, presented view controller will be sized as both half of the screen in width and height, and will be centered to the screen.
/// Implement `CustomSizedPresentable` in presented view controller to change that if needed.
/// This class can also be set as `transitioningDelegate` as presented view controller, as it's conforming `UIViewControllerTransitioningDelegate`.
@objcMembers
class CustomSizedPresentationController: UIPresentationController {
// MARK: - Public Properties
/// Corner radius for presented view controller's view. Default value is `8.0`.
var cornerRadius: CGFloat = 8.0
/// Background color of dimming view, which is located behind the presented view controller's view. Default value is `white with 0.5 alpha`.
var dimColor: UIColor = UIColor(white: 0.0, alpha: 0.5)
/// Dismiss view controller when background tapped. Default value is `true`.
var dismissOnBackgroundTap: Bool = true
// MARK: - Private Properties
/// Dim view
private var dimmingView: UIView!
/// Wrapper view for presentation. It's introduced to handle corner radius on presented view controller's view and it's superview of all other views.
private var presentationWrappingView: UIView!
// MARK: - Initializer
override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) {
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
presentedViewController.modalPresentationStyle = .custom
}
// MARK: - Actions
@objc private func dimmingViewTapped(_ sender: UITapGestureRecognizer) {
if dismissOnBackgroundTap {
presentedViewController.dismiss(animated: true, completion: nil)
}
}
// MARK: - Presentation
override func presentationTransitionWillBegin() {
guard let presentedViewControllerView = super.presentedView else { return }
// Wrap the presented view controller's view in an intermediate hierarchy
// that applies a shadow and rounded corners to the top-left and top-right
// edges. The final effect is built using three intermediate views.
//
// presentationWrapperView <- shadow
// |- presentationRoundedCornerView <- rounded corners (masksToBounds)
// |- presentedViewControllerWrapperView
// |- presentedViewControllerView (presentedViewController.view)
//
// SEE ALSO: The note in AAPLCustomPresentationSecondViewController.m.
do {
let presentationWrapperView = UIView(frame: frameOfPresentedViewInContainerView)
presentationWrapperView.layer.shadowOffset = CGSize(width: 0, height: -2)
presentationWrapperView.layer.shadowRadius = 10
presentationWrapperView.layer.shadowColor = UIColor(white: 0, alpha: 0.5).cgColor
presentationWrappingView = presentationWrapperView
// presentationRoundedCornerView is CORNER_RADIUS points taller than the
// height of the presented view controller's view. This is because
// the cornerRadius is applied to all corners of the view. Since the
// effect calls for only the top two corners to be rounded we size
// the view such that the bottom CORNER_RADIUS points lie below
// the bottom edge of the screen.
let cornerViewRect = presentationWrapperView.bounds//.inset(by: UIEdgeInsets(top: 0, left: 0, bottom: -cornerRadius, right: 0))
let presentationRoundedCornerView = UIView(frame: cornerViewRect)
presentationRoundedCornerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
presentationRoundedCornerView.layer.cornerRadius = cornerRadius
presentationRoundedCornerView.layer.masksToBounds = true
// To undo the extra height added to presentationRoundedCornerView,
// presentedViewControllerWrapperView is inset by CORNER_RADIUS points.
// This also matches the size of presentedViewControllerWrapperView's
// bounds to the size of -frameOfPresentedViewInContainerView.
let wrapperRect = presentationRoundedCornerView.bounds
let presentedViewControllerWrapperView = UIView(frame: wrapperRect)
presentedViewControllerWrapperView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Add presentedViewControllerView -> presentedViewControllerWrapperView.
presentedViewControllerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
presentedViewControllerView.frame = presentedViewControllerWrapperView.bounds
presentedViewControllerWrapperView.addSubview(presentedViewControllerView)
// Add presentedViewControllerWrapperView -> presentationRoundedCornerView.
presentationRoundedCornerView.addSubview(presentedViewControllerWrapperView)
// Add presentationRoundedCornerView -> presentationWrapperView.
presentationWrapperView.addSubview(presentationRoundedCornerView)
}
// Add a dimming view behind presentationWrapperView. self.presentedView
// is added later (by the animator) so any views added here will be
// appear behind the -presentedView.
do {
let dimmingView = UIView(frame: containerView?.bounds ?? .zero)
dimmingView.backgroundColor = dimColor
dimmingView.isOpaque = false
dimmingView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dimmingViewTapped(_:)))
dimmingView.addGestureRecognizer(tapGestureRecognizer)
self.dimmingView = dimmingView
containerView?.addSubview(dimmingView)
// Get the transition coordinator for the presentation so we can
// fade in the dimmingView alongside the presentation animation.
let transitionCoordinator = self.presentingViewController.transitionCoordinator
dimmingView.alpha = 0.0
transitionCoordinator?.animate(alongsideTransition: { _ in
self.dimmingView?.alpha = 1.0
}, completion: nil)
}
}
override func presentationTransitionDidEnd(_ completed: Bool) {
if !completed {
presentationWrappingView = nil
dimmingView = nil
}
}
// MARK: - Dismissal
override func dismissalTransitionWillBegin() {
guard let coordinator = presentingViewController.transitionCoordinator else {
dimmingView.alpha = 0.0
return
}
coordinator.animate(alongsideTransition: { _ in
self.dimmingView.alpha = 0.0
})
}
override func dismissalTransitionDidEnd(_ completed: Bool) {
if completed {
presentationWrappingView = nil
dimmingView = nil
}
}
// MARK: - Overrides
override var presentedView: UIView? {
return presentationWrappingView
}
override func size(forChildContentContainer container: UIContentContainer,
withParentContainerSize parentSize: CGSize) -> CGSize {
guard container === presentedViewController else {
return super.size(forChildContentContainer: container, withParentContainerSize: parentSize)
}
// return value from presentable if implemented
if let presentable = presentedViewController as? CustomSizedPresentable, let customSize = presentable.customSize?(withParentContainerSize: parentSize) {
return customSize
}
// half of the width/height by default
return CGSize(width: parentSize.width/2.0, height: parentSize.height/2.0)
}
override var frameOfPresentedViewInContainerView: CGRect {
guard let containerView = containerView else {
return super.frameOfPresentedViewInContainerView
}
let size = self.size(forChildContentContainer: presentedViewController,
withParentContainerSize: containerView.bounds.size)
// use origin value from presentable if implemented
if let presentable = presentedViewController as? CustomSizedPresentable, let origin = presentable.position?(withParentContainerSize: containerView.bounds.size) {
return CGRect(origin: origin, size: size)
}
// center presented view by default
let origin = CGPoint(x: (containerView.bounds.width - size.width)/2,
y: (containerView.bounds.height - size.height)/2)
return CGRect(origin: origin, size: size)
}
override func containerViewWillLayoutSubviews() {
super.containerViewWillLayoutSubviews()
self.dimmingView?.frame = containerView?.bounds ?? .zero
self.presentationWrappingView?.frame = frameOfPresentedViewInContainerView
}
override func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer) {
super.preferredContentSizeDidChange(forChildContentContainer: container)
if container === presentedViewController {
self.containerView?.setNeedsLayout()
}
}
}
// MARK: - UIViewControllerTransitioningDelegate
extension CustomSizedPresentationController: UIViewControllerTransitioningDelegate {
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
let controller = CustomSizedPresentationController(presentedViewController: presented, presenting: presenting)
controller.cornerRadius = cornerRadius
controller.dimColor = dimColor
controller.dismissOnBackgroundTap = dismissOnBackgroundTap
return controller
}
}
|
/**
* Copyright IBM Corporation 2018
*
* 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
/**
Analyze various features of text content at scale. Provide text, raw HTML, or a public URL, and
IBM Watson Natural Language Understanding will give you results for the features you request. The
service cleans HTML content before analysis by default, so the results can ignore most
advertisements and other unwanted content.
### Concepts
Identify general concepts that are referenced or alluded to in your content. Concepts that are
detected typically have an associated link to a DBpedia resource.
### Entities
Detect important people, places, geopolitical entities and other types of entities in your
content. Entity detection recognizes consecutive coreferences of each entity. For example,
analysis of the following text would count "Barack Obama" and "He" as the same entity:
"Barack Obama was the 44th President of the United States. He took office in January 2009."
### Keywords
Determine the most important keywords in your content. Keyword phrases are organized by relevance
in the results.
### Categories
Categorize your content into a hierarchical 5-level taxonomy. For example, "Leonardo DiCaprio won
an Oscar" returns "/art and entertainment/movies and tv/movies" as the most confident
classification.
### Sentiment
Determine whether your content conveys postive or negative sentiment. Sentiment information can be
returned for detected entities, keywords, or user-specified target phrases found in the text.
### Emotion
Detect anger, disgust, fear, joy, or sadness that is conveyed by your content. Emotion information
can be returned for detected entities, keywords, or user-specified target phrases found in the
text.
### Relations
Recognize when two entities are related, and identify the type of relation. For example, you can
identify an "awardedTo" relation between an award and its recipient.
### Semantic Roles
Parse sentences into subject-action-object form, and identify entities and keywords that are
subjects or objects of an action.
### Metadata
Get author information, publication date, and the title of your text/HTML content.
*/
public class NaturalLanguageUnderstanding {
/// The base URL to use when contacting the service.
public var serviceURL = "https://gateway.watsonplatform.net/natural-language-understanding/api"
/// The default HTTP headers for all requests to the service.
public var defaultHeaders = [String: String]()
private let credentials: Credentials
private let domain = "com.ibm.watson.developer-cloud.NaturalLanguageUnderstandingV1"
private let version: String
/**
Create a `NaturalLanguageUnderstanding` object.
- parameter username: The username used to authenticate with the service.
- parameter password: The password used to authenticate with the service.
- parameter version: The release date of the version of the API to use. Specify the date
in "YYYY-MM-DD" format.
*/
public init(username: String, password: String, version: String) {
self.credentials = .basicAuthentication(username: username, password: password)
self.version = version
}
/**
If the response or data represents an error returned by the Natural Language Understanding service,
then return NSError with information about the error that occured. Otherwise, return nil.
- parameter response: the URL response returned from the service.
- parameter data: Raw data returned from the service that may represent an error.
*/
private func responseToError(response: HTTPURLResponse?, data: Data?) -> NSError? {
// First check http status code in response
if let response = response {
if (200..<300).contains(response.statusCode) {
return nil
}
}
// ensure data is not nil
guard let data = data else {
if let code = response?.statusCode {
return NSError(domain: domain, code: code, userInfo: nil)
}
return nil // RestKit will generate error for this case
}
do {
let json = try JSONWrapper(data: data)
let code = response?.statusCode ?? 400
let message = try json.getString(at: "error")
var userInfo = [NSLocalizedDescriptionKey: message]
if let description = try? json.getString(at: "description") {
userInfo[NSLocalizedRecoverySuggestionErrorKey] = description
}
return NSError(domain: domain, code: code, userInfo: userInfo)
} catch {
return nil
}
}
/**
Analyze text, HTML, or a public webpage.
Analyzes text, HTML, or a public webpage with one or more text analysis features.
- parameter parameters: An object containing request parameters. The `features` object and one of the `text`, `html`, or `url` attributes are required.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func analyze(
parameters: Parameters,
failure: ((Error) -> Void)? = nil,
success: @escaping (AnalysisResults) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encode(parameters) else {
failure?(RestError.serializationError)
return
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let request = RestRequest(
method: "POST",
url: serviceURL + "/v1/analyze",
credentials: credentials,
headerParameters: defaultHeaders,
acceptType: "application/json",
contentType: "application/json",
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<AnalysisResults>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Delete model.
Deletes a custom model.
- parameter modelID: modelID of the model to delete.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func deleteModel(
modelID: String,
failure: ((Error) -> Void)? = nil,
success: @escaping (DeleteModelResults) -> Void)
{
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/models/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "DELETE",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: defaultHeaders,
acceptType: "application/json",
contentType: nil,
queryItems: queryParameters,
messageBody: nil
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<DeleteModelResults>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
List models.
Lists available models for Relations and Entities features, including Watson Knowledge Studio custom models that you have created and linked to your Natural Language Understanding service.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func listModels(
failure: ((Error) -> Void)? = nil,
success: @escaping (ListModelsResults) -> Void)
{
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let request = RestRequest(
method: "GET",
url: serviceURL + "/v1/models",
credentials: credentials,
headerParameters: defaultHeaders,
acceptType: "application/json",
contentType: nil,
queryItems: queryParameters,
messageBody: nil
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<ListModelsResults>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
}
Update function documentation
/**
* Copyright IBM Corporation 2018
*
* 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
/**
Analyze various features of text content at scale. Provide text, raw HTML, or a public URL, and IBM Watson Natural
Language Understanding will give you results for the features you request. The service cleans HTML content before
analysis by default, so the results can ignore most advertisements and other unwanted content.
You can create <a target="_blank"
href="https://www.ibm.com/watson/developercloud/doc/natural-language-understanding/customizing.html">custom models</a>
with Watson Knowledge Studio that can be used to detect custom entities and relations in Natural Language
Understanding.
*/
public class NaturalLanguageUnderstanding {
/// The base URL to use when contacting the service.
public var serviceURL = "https://gateway.watsonplatform.net/natural-language-understanding/api"
/// The default HTTP headers for all requests to the service.
public var defaultHeaders = [String: String]()
private let credentials: Credentials
private let domain = "com.ibm.watson.developer-cloud.NaturalLanguageUnderstandingV1"
private let version: String
/**
Create a `NaturalLanguageUnderstanding` object.
- parameter username: The username used to authenticate with the service.
- parameter password: The password used to authenticate with the service.
- parameter version: The release date of the version of the API to use. Specify the date
in "YYYY-MM-DD" format.
*/
public init(username: String, password: String, version: String) {
self.credentials = .basicAuthentication(username: username, password: password)
self.version = version
}
/**
If the response or data represents an error returned by the Natural Language Understanding service,
then return NSError with information about the error that occured. Otherwise, return nil.
- parameter response: the URL response returned from the service.
- parameter data: Raw data returned from the service that may represent an error.
*/
private func responseToError(response: HTTPURLResponse?, data: Data?) -> NSError? {
// First check http status code in response
if let response = response {
if (200..<300).contains(response.statusCode) {
return nil
}
}
// ensure data is not nil
guard let data = data else {
if let code = response?.statusCode {
return NSError(domain: domain, code: code, userInfo: nil)
}
return nil // RestKit will generate error for this case
}
do {
let json = try JSONWrapper(data: data)
let code = response?.statusCode ?? 400
let message = try json.getString(at: "error")
var userInfo = [NSLocalizedDescriptionKey: message]
if let description = try? json.getString(at: "description") {
userInfo[NSLocalizedRecoverySuggestionErrorKey] = description
}
return NSError(domain: domain, code: code, userInfo: userInfo)
} catch {
return nil
}
}
/**
Analyze text, HTML, or a public webpage.
Analyzes text, HTML, or a public webpage with one or more text analysis features. ### Concepts Identify general
concepts that are referenced or alluded to in your content. Concepts that are detected typically have an associated
link to a DBpedia resource. ### Emotion Detect anger, disgust, fear, joy, or sadness that is conveyed by your
content. Emotion information can be returned for detected entities, keywords, or user-specified target phrases
found in the text. ### Entities Detect important people, places, geopolitical entities and other types of entities
in your content. Entity detection recognizes consecutive coreferences of each entity. For example, analysis of the
following text would count \"Barack Obama\" and \"He\" as the same entity: \"Barack Obama was the 44th President
of the United States. He took office in January 2009.\" ### Keywords Determine the most important keywords in your
content. Keyword phrases are organized by relevance in the results. ### Metadata Get author information,
publication date, and the title of your text/HTML content. ### Relations Recognize when two entities are related,
and identify the type of relation. For example, you can identify an \"awardedTo\" relation between an award and
its recipient. ### Semantic Roles Parse sentences into subject-action-object form, and identify entities and
keywords that are subjects or objects of an action. ### Sentiment Determine whether your content conveys postive
or negative sentiment. Sentiment information can be returned for detected entities, keywords, or user-specified
target phrases found in the text. ### Categories Categorize your content into a hierarchical 5-level taxonomy.
For example, \"Leonardo DiCaprio won an Oscar\" returns \"/art and entertainment/movies and tv/movies\" as the most
confident classification.
- parameter parameters: An object containing request parameters. The `features` object and one of the `text`, `html`, or `url` attributes
are required.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func analyze(
parameters: Parameters,
failure: ((Error) -> Void)? = nil,
success: @escaping (AnalysisResults) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encode(parameters) else {
failure?(RestError.serializationError)
return
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let request = RestRequest(
method: "POST",
url: serviceURL + "/v1/analyze",
credentials: credentials,
headerParameters: defaultHeaders,
acceptType: "application/json",
contentType: "application/json",
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<AnalysisResults>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Delete model.
Deletes a custom model.
- parameter modelID: model_id of the model to delete.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func deleteModel(
modelID: String,
failure: ((Error) -> Void)? = nil,
success: @escaping (DeleteModelResults) -> Void)
{
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/models/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "DELETE",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: defaultHeaders,
acceptType: "application/json",
contentType: nil,
queryItems: queryParameters,
messageBody: nil
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<DeleteModelResults>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
List models.
Lists available models for Relations and Entities features, including Watson Knowledge Studio custom models that
you have created and linked to your Natural Language Understanding service.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func listModels(
failure: ((Error) -> Void)? = nil,
success: @escaping (ListModelsResults) -> Void)
{
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let request = RestRequest(
method: "GET",
url: serviceURL + "/v1/models",
credentials: credentials,
headerParameters: defaultHeaders,
acceptType: "application/json",
contentType: nil,
queryItems: queryParameters,
messageBody: nil
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<ListModelsResults>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
}
|
//
// WidgetsManagerViewController.swift
// Pock
//
// Created by Pierluigi Galdi on 30/04/21.
//
import Cocoa
import PockKit
import TinyConstraints
class WidgetsManagerViewController: NSViewController {
// MARK: Cell Identifiers
private enum CellIdentifiers {
static let widgetCell: NSUserInterfaceItemIdentifier = NSUserInterfaceItemIdentifier("widgetCellIdentifier")
}
// MARK: UI Elements
///
/// Common UI elements
@IBOutlet private weak var tableView: NSTableView!
/// Selected widget's UI elements
@IBOutlet private weak var widgetNameLabel: NSTextField!
@IBOutlet private weak var widgetAuthorLabel: NSTextField!
@IBOutlet private weak var widgetVersionLabel: NSTextField!
@IBOutlet private weak var widgetUpdateButton: NSButton!
@IBOutlet private weak var widgetUninstallButton: NSButton!
@IBOutlet private weak var widgetUpdateStatusLabel: NSTextField!
@IBOutlet private weak var widgetPreferencesContainer: NSView!
@IBOutlet private weak var widgetPreferencesStatusLabel: NSTextField!
// MARK: Data
private var widgets: [PKWidgetInfo] {
return WidgetsLoader.installedWidgets.sorted(by: { $0.name < $1.name })
}
private var selectedWidget: PKWidgetInfo? {
didSet {
updateUIElementsForSelectedWidget()
updatePreferencesContainerForSelectedPreferences()
}
}
private var selectedPreferences: PKWidgetPreference?
/// Set of disabled widget's `bundleIdentifier` to avoid user selection
private var disabledWidgets: Set<String> = []
// MARK: Overrides
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(NSNib(nibNamed: "PKWidgetCellView", bundle: .main), forIdentifier: CellIdentifiers.widgetCell)
self.selectedWidget = widgets.first
}
override func viewWillAppear() {
super.viewWillAppear()
NSApp.activate(ignoringOtherApps: true)
}
override func viewWillDisappear() {
super.viewWillDisappear()
NSApp.deactivate()
}
}
// MARK: Methods
extension WidgetsManagerViewController {
private func updatePreferredContentSize() {
let frame = widgetPreferencesContainer.convert(widgetPreferencesContainer.visibleRect, to: view)
self.preferredContentSize = NSSize(
width: frame.origin.x + frame.size.width,
height: frame.origin.y + frame.size.height
)
self.view.layout()
}
private func updateUIElementsForSelectedWidget() {
guard let widget = selectedWidget else {
widgetNameLabel.stringValue = "widgets-manager.list.select-widget".localized
widgetAuthorLabel.stringValue = "--"
widgetVersionLabel.stringValue = "--"
widgetUninstallButton.isEnabled = false
widgetUpdateButton.isEnabled = false
widgetUpdateStatusLabel.isHidden = true
return
}
widgetNameLabel.stringValue = widget.name
widgetAuthorLabel.stringValue = widget.author
widgetVersionLabel.stringValue = widget.version
widgetUninstallButton.isEnabled = true
// TODO: Add check for `update` UI elements (button, label)
widgetUpdateButton.isEnabled = false
widgetUpdateStatusLabel.isHidden = true
}
private func updatePreferencesContainerForSelectedPreferences() {
guard let widget = selectedWidget, let clss = widget.preferencesClass as? PKWidgetPreference.Type else {
unloadPreferencesContainerWithTitle("widgets-manager.list.no-preferences".localized)
selectedPreferences = nil
return
}
if disabledWidgets.contains(where: { $0 == widget.bundleIdentifier }) {
unloadPreferencesContainerWithTitle("widgets-manager.list.did-update".localized)
} else {
selectedPreferences = clss.init(nibName: clss.nibName, bundle: Bundle(for: clss))
loadPreferencesContainerForSelectedPreferences()
}
}
private func loadPreferencesContainerForSelectedPreferences() {
guard let preferences = selectedPreferences else {
return
}
widgetPreferencesStatusLabel.stringValue = ""
widgetPreferencesStatusLabel.isHidden = true
addChild(preferences)
widgetPreferencesContainer.addSubview(preferences.view)
preferences.view.edgesToSuperview()
async { [weak self] in
self?.updatePreferredContentSize()
}
}
private func unloadPreferencesContainerWithTitle(_ title: String) {
selectedPreferences?.view.removeFromSuperview()
selectedPreferences?.removeFromParent()
selectedPreferences = nil
widgetPreferencesStatusLabel.stringValue = title
widgetPreferencesStatusLabel.isHidden = false
}
}
// MARK: Table - Data Source
extension WidgetsManagerViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return widgets.count
}
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 44
}
func tableView(_ tableView: NSTableView, sizeToFitWidthOfColumn column: Int) -> CGFloat {
return 220
}
}
// MARK: Table - Delegate
extension WidgetsManagerViewController: NSTableViewDelegate {
/// View for cell in row
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
/// Check for cell
guard row < widgets.count, let cell = tableView.makeView(withIdentifier: CellIdentifiers.widgetCell, owner: nil) as? PKWidgetCellView else {
return nil
}
/// Get item
let widget = widgets[row]
let disabled = disabledWidgets.contains(where: { $0 == widget.bundleIdentifier })
/// Setup cell
cell.status.image = NSImage(named: widget.loaded ? NSImage.statusAvailableName : NSImage.statusUnavailableName)
cell.name.stringValue = widget.name
cell.name.alphaValue = disabled ? 0.475 : 1
cell.badge.isHidden = disabled // TODO: || PockUpdater.default.newVersion(for: widget) == nil
/// Return
return cell
}
func tableViewSelectionDidChange(_ notification: Notification) {
self.selectedWidget = tableView.selectedRow > -1 ? widgets[tableView.selectedRow] : nil
}
}
fix: dealloc selectedWidget on manager list deinit
//
// WidgetsManagerViewController.swift
// Pock
//
// Created by Pierluigi Galdi on 30/04/21.
//
import Cocoa
import PockKit
import TinyConstraints
class WidgetsManagerViewController: NSViewController {
// MARK: Cell Identifiers
private enum CellIdentifiers {
static let widgetCell: NSUserInterfaceItemIdentifier = NSUserInterfaceItemIdentifier("widgetCellIdentifier")
}
// MARK: UI Elements
///
/// Common UI elements
@IBOutlet private weak var tableView: NSTableView!
/// Selected widget's UI elements
@IBOutlet private weak var widgetNameLabel: NSTextField!
@IBOutlet private weak var widgetAuthorLabel: NSTextField!
@IBOutlet private weak var widgetVersionLabel: NSTextField!
@IBOutlet private weak var widgetUpdateButton: NSButton!
@IBOutlet private weak var widgetUninstallButton: NSButton!
@IBOutlet private weak var widgetUpdateStatusLabel: NSTextField!
@IBOutlet private weak var widgetPreferencesContainer: NSView!
@IBOutlet private weak var widgetPreferencesStatusLabel: NSTextField!
// MARK: Data
private var widgets: [PKWidgetInfo] {
return WidgetsLoader.installedWidgets.sorted(by: { $0.name < $1.name })
}
private var selectedWidget: PKWidgetInfo? {
didSet {
updateUIElementsForSelectedWidget()
updatePreferencesContainerForSelectedPreferences()
}
}
private var selectedPreferences: PKWidgetPreference?
/// Set of disabled widget's `bundleIdentifier` to avoid user selection
private var disabledWidgets: Set<String> = []
// MARK: Overrides
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(NSNib(nibNamed: "PKWidgetCellView", bundle: .main), forIdentifier: CellIdentifiers.widgetCell)
self.selectedWidget = widgets.first
}
override func viewWillAppear() {
super.viewWillAppear()
NSApp.activate(ignoringOtherApps: true)
}
override func viewWillDisappear() {
super.viewWillDisappear()
NSApp.deactivate()
}
deinit {
selectedWidget = nil
Roger.debug("[WidgetsManager][List] - deinit")
}
}
// MARK: Methods
extension WidgetsManagerViewController {
private func updatePreferredContentSize() {
let frame = widgetPreferencesContainer.convert(widgetPreferencesContainer.visibleRect, to: view)
self.preferredContentSize = NSSize(
width: frame.origin.x + frame.size.width,
height: frame.origin.y + frame.size.height
)
self.view.layout()
}
private func updateUIElementsForSelectedWidget() {
guard let widget = selectedWidget else {
widgetNameLabel.stringValue = "widgets-manager.list.select-widget".localized
widgetAuthorLabel.stringValue = "--"
widgetVersionLabel.stringValue = "--"
widgetUninstallButton.isEnabled = false
widgetUpdateButton.isEnabled = false
widgetUpdateStatusLabel.isHidden = true
return
}
widgetNameLabel.stringValue = widget.name
widgetAuthorLabel.stringValue = widget.author
widgetVersionLabel.stringValue = widget.version
widgetUninstallButton.isEnabled = true
// TODO: Add check for `update` UI elements (button, label)
widgetUpdateButton.isEnabled = false
widgetUpdateStatusLabel.isHidden = true
}
private func updatePreferencesContainerForSelectedPreferences() {
guard let widget = selectedWidget, let clss = widget.preferencesClass as? PKWidgetPreference.Type else {
unloadPreferencesContainerWithTitle("widgets-manager.list.no-preferences".localized)
selectedPreferences = nil
return
}
if disabledWidgets.contains(where: { $0 == widget.bundleIdentifier }) {
unloadPreferencesContainerWithTitle("widgets-manager.list.did-update".localized)
} else {
selectedPreferences = clss.init(nibName: clss.nibName, bundle: Bundle(for: clss))
loadPreferencesContainerForSelectedPreferences()
}
}
private func loadPreferencesContainerForSelectedPreferences() {
guard let preferences = selectedPreferences else {
return
}
widgetPreferencesStatusLabel.stringValue = ""
widgetPreferencesStatusLabel.isHidden = true
addChild(preferences)
widgetPreferencesContainer.addSubview(preferences.view)
preferences.view.edgesToSuperview()
async { [weak self] in
self?.updatePreferredContentSize()
}
}
private func unloadPreferencesContainerWithTitle(_ title: String) {
selectedPreferences?.view.removeFromSuperview()
selectedPreferences?.removeFromParent()
selectedPreferences = nil
widgetPreferencesStatusLabel.stringValue = title
widgetPreferencesStatusLabel.isHidden = false
}
}
// MARK: Table - Data Source
extension WidgetsManagerViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return widgets.count
}
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 44
}
func tableView(_ tableView: NSTableView, sizeToFitWidthOfColumn column: Int) -> CGFloat {
return 220
}
}
// MARK: Table - Delegate
extension WidgetsManagerViewController: NSTableViewDelegate {
/// View for cell in row
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
/// Check for cell
guard row < widgets.count, let cell = tableView.makeView(withIdentifier: CellIdentifiers.widgetCell, owner: nil) as? PKWidgetCellView else {
return nil
}
/// Get item
let widget = widgets[row]
let disabled = disabledWidgets.contains(where: { $0 == widget.bundleIdentifier })
/// Setup cell
cell.status.image = NSImage(named: widget.loaded ? NSImage.statusAvailableName : NSImage.statusUnavailableName)
cell.name.stringValue = widget.name
cell.name.alphaValue = disabled ? 0.475 : 1
cell.badge.isHidden = disabled // TODO: || PockUpdater.default.newVersion(for: widget) == nil
/// Return
return cell
}
func tableViewSelectionDidChange(_ notification: Notification) {
self.selectedWidget = tableView.selectedRow > -1 ? widgets[tableView.selectedRow] : nil
}
}
|
//
// Player.swift
// Game
//
// Created by Nicholas Pettas on 11/10/15.
// Copyright © 2015 Nicholas Pettas. All rights reserved.
//
import SpriteKit
class Player: SKSpriteNode {
// Character setup
var charPushFrames = [SKTexture]()
var charCrashFrames = [SKTexture]()
var charOllieFrames = [SKTexture]()
var charFlipFrames = [SKTexture]()
var isJumping = false
var isOllieTrick = false
var isFlipTrick = false
convenience init() {
self.init(imageNamed: "push0")
createCharacter()
}
override func update() {
if isJumping {
if floor((self.physicsBody?.velocity.dy)!) == 0 {
isJumping = false
isOllieTrick = false
isFlipTrick = false
}
}
}
func createCharacter() {
self.zPosition = GameManager.sharedInstance.PLAYER_Z_POSITION
for var x = 0; x < 12; x++ {
charPushFrames.append(SKTexture(imageNamed: "push\(x)"))
}
for var x = 0; x < 9; x++ {
charCrashFrames.append(SKTexture(imageNamed: "crash\(x)"))
}
for var x = 0; x < 10; x++ {
charOllieFrames.append(SKTexture(imageNamed: "ollie\(x)"))
}
for var x = 0; x < 12; x++ {
charFlipFrames.append(SKTexture(imageNamed: "flip\(x)"))
}
self.position = CGPointMake(GameManager.sharedInstance.CHAR_X_POSITION, GameManager.sharedInstance.CHAR_Y_POSITION)
self.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.size.width - 50, self.size.height - 20))
self.physicsBody?.restitution = 0
self.physicsBody?.linearDamping = 0.1
self.physicsBody?.allowsRotation = false
self.physicsBody?.mass = 0.1
self.physicsBody?.dynamic = true
self.physicsBody?.categoryBitMask = GameManager.sharedInstance.COLLIDER_PLAYER
self.physicsBody?.contactTestBitMask = GameManager.sharedInstance.COLLIDER_OBSTACLE
playPushAnim()
}
func jump() {
if !isJumping && !GameManager.sharedInstance.gameOver {
isJumping = true
self.physicsBody?.applyImpulse(CGVectorMake(0.0, 70.0))
AudioManager.sharedInstance.playJumpSoundEffect(self)
}
}
func ollie() {
if isJumping && !GameManager.sharedInstance.gameOver && !isOllieTrick {
isOllieTrick = true;
playOllieAnim()
AudioManager.sharedInstance.playJumpSoundEffect(self)
self.physicsBody?.applyImpulse(CGVectorMake(0.0, 20))
GameManager.sharedInstance.score++
}
}
func flip() {
if isJumping && !GameManager.sharedInstance.gameOver && !isFlipTrick {
isFlipTrick = true;
playFlipAnim()
AudioManager.sharedInstance.playJumpSoundEffect(self)
self.physicsBody?.applyImpulse(CGVectorMake(0.0, 20))
GameManager.sharedInstance.score++
}
}
func playFlipAnim() {
if !GameManager.sharedInstance.gameOver {
self.removeAllActions()
self.runAction(SKAction.animateWithTextures(charFlipFrames, timePerFrame: 0.05))
let wait = SKAction.waitForDuration(0.55)
self.runAction(wait, completion: {() -> Void in
self.isOllieTrick = false
self.isFlipTrick = false
self.playPushAnim()
})
}
}
func playCrashAnim() {
if !GameManager.sharedInstance.gameOver {
self.removeAllActions()
AudioManager.sharedInstance.playGameOverSoundEffect(self)
self.runAction(SKAction.animateWithTextures(charCrashFrames, timePerFrame: 0.05))
}
}
func playPushAnim() {
self.removeAllActions()
self.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(charPushFrames, timePerFrame: 0.1)))
}
func playOllieAnim() {
self.removeAllActions()
self.runAction(SKAction.animateWithTextures(charOllieFrames, timePerFrame: 0.05))
let wait = SKAction.waitForDuration(0.6)
self.runAction(wait, completion: {() -> Void in
self.isOllieTrick = false
self.isFlipTrick = false
self.playPushAnim()
})
}
}
Modify players tricks and jumps to make the jump more challenging
//
// Player.swift
// Game
//
// Created by Nicholas Pettas on 11/10/15.
// Copyright © 2015 Nicholas Pettas. All rights reserved.
//
import SpriteKit
class Player: SKSpriteNode {
// Character setup
var charPushFrames = [SKTexture]()
var charCrashFrames = [SKTexture]()
var charOllieFrames = [SKTexture]()
var charFlipFrames = [SKTexture]()
var isJumping = false
var isOllieTrick = false
var isFlipTrick = false
convenience init() {
self.init(imageNamed: "push0")
createCharacter()
}
override func update() {
if isJumping {
if floor((self.physicsBody?.velocity.dy)!) == 0 {
isJumping = false
isOllieTrick = false
isFlipTrick = false
}
}
}
func createCharacter() {
self.zPosition = GameManager.sharedInstance.PLAYER_Z_POSITION
for var x = 0; x < 12; x++ {
charPushFrames.append(SKTexture(imageNamed: "push\(x)"))
}
for var x = 0; x < 9; x++ {
charCrashFrames.append(SKTexture(imageNamed: "crash\(x)"))
}
for var x = 0; x < 10; x++ {
charOllieFrames.append(SKTexture(imageNamed: "ollie\(x)"))
}
for var x = 0; x < 12; x++ {
charFlipFrames.append(SKTexture(imageNamed: "flip\(x)"))
}
self.position = CGPointMake(GameManager.sharedInstance.CHAR_X_POSITION, GameManager.sharedInstance.CHAR_Y_POSITION)
self.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.size.width - 50, self.size.height - 20))
self.physicsBody?.restitution = 0
self.physicsBody?.linearDamping = 0.1
self.physicsBody?.allowsRotation = false
self.physicsBody?.mass = 0.1
self.physicsBody?.dynamic = true
self.physicsBody?.categoryBitMask = GameManager.sharedInstance.COLLIDER_PLAYER
self.physicsBody?.contactTestBitMask = GameManager.sharedInstance.COLLIDER_OBSTACLE
playPushAnim()
}
func jump() {
if !isJumping && !GameManager.sharedInstance.gameOver {
isJumping = true
self.physicsBody?.applyImpulse(CGVectorMake(0.0, 55))
AudioManager.sharedInstance.playJumpSoundEffect(self)
}
}
func ollie() {
if isJumping && !GameManager.sharedInstance.gameOver && !isOllieTrick {
isOllieTrick = true;
playOllieAnim()
AudioManager.sharedInstance.playJumpSoundEffect(self)
self.physicsBody?.applyImpulse(CGVectorMake(0.0, 25))
GameManager.sharedInstance.score++
}
}
func flip() {
if isJumping && !GameManager.sharedInstance.gameOver && !isFlipTrick {
isFlipTrick = true;
playFlipAnim()
AudioManager.sharedInstance.playJumpSoundEffect(self)
self.physicsBody?.applyImpulse(CGVectorMake(0.0, 25))
GameManager.sharedInstance.score++
}
}
func playFlipAnim() {
if !GameManager.sharedInstance.gameOver {
self.removeAllActions()
self.runAction(SKAction.animateWithTextures(charFlipFrames, timePerFrame: 0.05))
let wait = SKAction.waitForDuration(0.55)
self.runAction(wait, completion: {() -> Void in
self.isOllieTrick = false
self.isFlipTrick = false
self.playPushAnim()
})
}
}
func playCrashAnim() {
if !GameManager.sharedInstance.gameOver {
self.removeAllActions()
AudioManager.sharedInstance.playGameOverSoundEffect(self)
self.runAction(SKAction.animateWithTextures(charCrashFrames, timePerFrame: 0.05))
}
}
func playPushAnim() {
self.removeAllActions()
self.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(charPushFrames, timePerFrame: 0.1)))
}
func playOllieAnim() {
self.removeAllActions()
self.runAction(SKAction.animateWithTextures(charOllieFrames, timePerFrame: 0.04))
let wait = SKAction.waitForDuration(0.48)
self.runAction(wait, completion: {() -> Void in
self.isOllieTrick = false
self.isFlipTrick = false
self.playPushAnim()
})
}
} |
//
// HAL.swift
// HAL
//
// Created by Colin Harris on 2/12/14.
// Copyright (c) 2014 Colin Harris. All rights reserved.
//
import Foundation
import Alamofire
public class HAL {
var _attributes: [String: AnyObject] = [String: AnyObject]()
var _links: [String: AnyObject] = [String: AnyObject]()
var _embedded: [String: AnyObject] = [String: AnyObject]()
internal init(response: [String: AnyObject]) {
if let links = response["_links"] as? [String: AnyObject] {
self._links = links
}
if let embedded = response["_embedded"] as? [String: AnyObject] {
self._embedded = embedded
}
self._attributes = response
self._attributes.removeValueForKey("_links")
self._attributes.removeValueForKey("_embedded")
}
public class func get(url: String) -> Promise<HAL> {
return HAL._loadRequest( Alamofire.request(.GET, url, parameters: nil) )
}
private class func _loadRequest(request: Alamofire.Request) -> Promise<HAL> {
return Promise<HAL> { (success, failure) in
request.responseJSON { (request, response, data, error) in
if( error != nil ) {
failure( error! )
} else {
var client = HAL(response: data as Dictionary)
success( client )
}
}
return
}
}
public func get() -> Promise<HAL> {
return get("self")
}
public func get(key: String, params: [String: AnyObject] = [String: AnyObject]()) -> Promise<HAL> {
var url = self.link_url(key, params: params)
return HAL._loadRequest( Alamofire.request(.GET, url) )
}
public func post(params: [String: AnyObject]) -> Promise<HAL> {
return post("self", params: params)
}
public func post(key: String, params: [String: AnyObject]) -> Promise<HAL> {
var url = self.link_url(key)
return HAL._loadRequest( Alamofire.request(.POST, url, parameters: params) )
}
public func put(params: [String: AnyObject]) -> Promise<HAL> {
return put("self", params: params)
}
public func put(key: String, params: [String: AnyObject]) -> Promise<HAL> {
var url = self.link_url(key)
return HAL._loadRequest( Alamofire.request(.PUT, url, parameters: params) )
}
public func patch(params: [String: AnyObject]) -> Promise<HAL> {
return patch("self", params: params)
}
public func patch(key: String, params: [String: AnyObject]) -> Promise<HAL> {
var url = self.link_url(key)
return HAL._loadRequest( Alamofire.request(.PATCH, url, parameters: params) )
}
public func delete() -> Promise<HAL> {
return delete("self")
}
public func delete(key: String) -> Promise<HAL> {
var url = self.link_url(key)
return HAL._loadRequest( Alamofire.request(.DELETE, url) )
}
public func attributes() -> [String: AnyObject] {
return _attributes
}
public func attribute(key: String) -> AnyObject! {
return _attributes[key]
}
public func links() -> [String: AnyObject] {
return _links
}
public func link(key: String) -> AnyObject? {
return _links[key]
}
public func isTemplated(key: String) -> Bool {
var link: AnyObject = self.link(key)!
if link is [String: AnyObject] {
let templated = link["templated"]
return templated as? Bool != nil
}
return false
}
public func link_url(key: String, params: [String: AnyObject] = [String: AnyObject]()) -> String {
var link: AnyObject = self.link(key)!
if link is String {
return link as String
} else if link is [String: AnyObject] {
if self.isTemplated(key) {
return ExpandURITemplate(link["href"] as String, values: params)
} else {
return link["href"] as String
}
}
return ""
}
public func embedded() -> [String: AnyObject] {
return _embedded
}
public func embedded(key: String) -> AnyObject? {
let value: AnyObject? = _embedded[key]?
if value != nil {
if value is Array<[String: AnyObject]> {
let values = value as Array<[String: AnyObject]>
return values.map { (object) -> HAL in
return HAL(response: object)
}
}
else {
return HAL(response: value as Dictionary)
}
}
return nil
}
}
Added some util methods for post, put and patch to send the object own attributes as parameters.
This allows the HAL objects to be edited directly then posted back to the server.
//
// HAL.swift
// HAL
//
// Created by Colin Harris on 2/12/14.
// Copyright (c) 2014 Colin Harris. All rights reserved.
//
import Foundation
import Alamofire
public class HAL {
var _attributes: [String: AnyObject] = [String: AnyObject]()
var _links: [String: AnyObject] = [String: AnyObject]()
var _embedded: [String: AnyObject] = [String: AnyObject]()
public init(response: [String: AnyObject]) {
if let links = response["_links"] as? [String: AnyObject] {
self._links = links
}
if let embedded = response["_embedded"] as? [String: AnyObject] {
self._embedded = embedded
}
self._attributes = response
self._attributes.removeValueForKey("_links")
self._attributes.removeValueForKey("_embedded")
}
public class func get(url: String) -> Promise<HAL> {
return HAL._loadRequest( Alamofire.request(.GET, url, parameters: nil) )
}
private class func _loadRequest(request: Alamofire.Request) -> Promise<HAL> {
return Promise<HAL> { (success, failure) in
request.responseJSON { (request, response, data, error) in
if( error != nil ) {
failure( error! )
} else {
var client = HAL(response: data as Dictionary)
success( client )
}
}
return
}
}
public func get() -> Promise<HAL> {
return get("self")
}
public func get(key: String, params: [String: AnyObject] = [String: AnyObject]()) -> Promise<HAL> {
var url = self.link_url(key, params: params)
return HAL._loadRequest( Alamofire.request(.GET, url) )
}
public func post() -> Promise<HAL> {
return post("self", params: attributes())
}
public func post(params: [String: AnyObject]) -> Promise<HAL> {
return post("self", params: params)
}
public func post(key: String, params: [String: AnyObject]) -> Promise<HAL> {
var url = self.link_url(key)
return HAL._loadRequest( Alamofire.request(.POST, url, parameters: params) )
}
public func put() -> Promise<HAL> {
return put("self", params: attributes())
}
public func put(params: [String: AnyObject]) -> Promise<HAL> {
return put("self", params: params)
}
public func put(key: String, params: [String: AnyObject]) -> Promise<HAL> {
var url = self.link_url(key)
return HAL._loadRequest( Alamofire.request(.PUT, url, parameters: params) )
}
public func patch() -> Promise<HAL> {
return patch("self", params: attributes())
}
public func patch(params: [String: AnyObject]) -> Promise<HAL> {
return patch("self", params: params)
}
public func patch(key: String, params: [String: AnyObject]) -> Promise<HAL> {
var url = self.link_url(key)
return HAL._loadRequest( Alamofire.request(.PATCH, url, parameters: params) )
}
public func delete() -> Promise<HAL> {
return delete("self")
}
public func delete(key: String) -> Promise<HAL> {
var url = self.link_url(key)
return HAL._loadRequest( Alamofire.request(.DELETE, url) )
}
public func attributes() -> [String: AnyObject] {
return _attributes
}
public func attribute(key: String) -> AnyObject! {
return _attributes[key]
}
public func setAttribute(key: String, value: AnyObject?) {
_attributes[key] = value
}
public func links() -> [String: AnyObject] {
return _links
}
public func link(key: String) -> AnyObject? {
return _links[key]
}
public func isTemplated(key: String) -> Bool {
var link: AnyObject = self.link(key)!
if link is [String: AnyObject] {
let templated = link["templated"]
return templated as? Bool != nil
}
return false
}
public func link_url(key: String, params: [String: AnyObject] = [String: AnyObject]()) -> String {
var link: AnyObject = self.link(key)!
if link is String {
return link as String
} else if link is [String: AnyObject] {
if self.isTemplated(key) {
return ExpandURITemplate(link["href"] as String, values: params)
} else {
return link["href"] as String
}
}
return ""
}
public func embedded() -> [String: AnyObject] {
return _embedded
}
public func embedded(key: String) -> AnyObject? {
let value: AnyObject? = _embedded[key]?
if value != nil {
if value is Array<[String: AnyObject]> {
let values = value as Array<[String: AnyObject]>
return values.map { (object) -> HAL in
return HAL(response: object)
}
}
else {
return HAL(response: value as Dictionary)
}
}
return nil
}
}
|
import Foundation
public typealias Composer = NSAttributedString -> NSAttributedString
public func thongs_string(string: String) -> NSAttributedString {
return NSAttributedString(string: string)
}
public func thongs_font(font: UIFont) -> Composer {
return { attributedString in
var s = attributedString.mutableCopy() as! NSMutableAttributedString
s.beginEditing()
s.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, attributedString.length))
s.endEditing()
return s
}
}
public func thongs_color(color: UIColor) -> Composer {
return { attributedString in
var s = attributedString.mutableCopy() as! NSMutableAttributedString
s.addAttribute(NSForegroundColorAttributeName, value: color, range: NSMakeRange(0, attributedString.length))
return s
}
}
public func thongs_kerning(kerning: Double) -> Composer {
return { attributedString in
var s = attributedString.mutableCopy() as! NSMutableAttributedString
s.addAttribute(NSKernAttributeName, value: kerning, range: NSMakeRange(0, attributedString.length))
return s
}
}
public func thongs_underline(color: UIColor, style: NSUnderlineStyle) -> Composer {
return { attributedString in
var s = attributedString.mutableCopy() as! NSMutableAttributedString
s.addAttribute(NSUnderlineColorAttributeName, value: color, range: NSMakeRange(0, attributedString.length))
s.addAttribute(NSUnderlineStyleAttributeName, value: style.rawValue, range: NSMakeRange(0, attributedString.length))
return s
}
}
public func thongs_strikethrough(color: UIColor, style: NSUnderlineStyle) -> Composer {
return { attributedString in
var s = attributedString.mutableCopy() as! NSMutableAttributedString
s.addAttribute(NSStrikethroughColorAttributeName, value: color, range: NSMakeRange(0, attributedString.length))
s.addAttribute(NSStrikethroughStyleAttributeName, value: style.rawValue, range: NSMakeRange(0, attributedString.length))
return s
}
}
public func thongs_concat(comp1: NSAttributedString) -> Composer {
return { comp2 in
var s = comp1.mutableCopy() as! NSMutableAttributedString
s.appendAttributedString(comp2)
return s
}
}
// Operators
infix operator ~~> { associativity left precedence 100}
public func ~~> (composer: Composer, text: String) -> NSAttributedString {
return { composer(thongs_string(text)) }()
}
infix operator <*> { associativity left precedence 200 }
public func <*> (composer1: Composer, composer2: Composer) -> Composer {
return { str in
composer2(composer1(str))
}
}
//concat(a)(b)
infix operator <+> { associativity right precedence 30 }
public func <+> (text1: NSAttributedString, text2: NSAttributedString) -> NSAttributedString {
return thongs_concat(text1)(text2)
}
fix warnings
import Foundation
public typealias Composer = NSAttributedString -> NSAttributedString
public func thongs_string(string: String) -> NSAttributedString {
return NSAttributedString(string: string)
}
public func thongs_font(font: UIFont) -> Composer {
return { attributedString in
let s = attributedString.mutableCopy() as! NSMutableAttributedString
s.beginEditing()
s.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, attributedString.length))
s.endEditing()
return s
}
}
public func thongs_color(color: UIColor) -> Composer {
return { attributedString in
let s = attributedString.mutableCopy() as! NSMutableAttributedString
s.addAttribute(NSForegroundColorAttributeName, value: color, range: NSMakeRange(0, attributedString.length))
return s
}
}
public func thongs_kerning(kerning: Double) -> Composer {
return { attributedString in
let s = attributedString.mutableCopy() as! NSMutableAttributedString
s.addAttribute(NSKernAttributeName, value: kerning, range: NSMakeRange(0, attributedString.length))
return s
}
}
public func thongs_underline(color: UIColor, style: NSUnderlineStyle) -> Composer {
return { attributedString in
let s = attributedString.mutableCopy() as! NSMutableAttributedString
s.addAttribute(NSUnderlineColorAttributeName, value: color, range: NSMakeRange(0, attributedString.length))
s.addAttribute(NSUnderlineStyleAttributeName, value: style.rawValue, range: NSMakeRange(0, attributedString.length))
return s
}
}
public func thongs_strikethrough(color: UIColor, style: NSUnderlineStyle) -> Composer {
return { attributedString in
let s = attributedString.mutableCopy() as! NSMutableAttributedString
s.addAttribute(NSStrikethroughColorAttributeName, value: color, range: NSMakeRange(0, attributedString.length))
s.addAttribute(NSStrikethroughStyleAttributeName, value: style.rawValue, range: NSMakeRange(0, attributedString.length))
return s
}
}
public func thongs_concat(comp1: NSAttributedString) -> Composer {
return { comp2 in
let s = comp1.mutableCopy() as! NSMutableAttributedString
s.appendAttributedString(comp2)
return s
}
}
// Operators
infix operator ~~> { associativity left precedence 100}
public func ~~> (composer: Composer, text: String) -> NSAttributedString {
return { composer(thongs_string(text)) }()
}
infix operator <*> { associativity left precedence 200 }
public func <*> (composer1: Composer, composer2: Composer) -> Composer {
return { str in
composer2(composer1(str))
}
}
//concat(a)(b)
infix operator <+> { associativity right precedence 30 }
public func <+> (text1: NSAttributedString, text2: NSAttributedString) -> NSAttributedString {
return thongs_concat(text1)(text2)
}
|
import Foundation
public class Post: NSObject {
public var author: User?
public var date: NSDate
public var group: Group?
public var location: Location?
public var text: String?
public var attachments: [Attachment]?
public var likes: Int = 0
public var seen: Int = 0
public var parent: Post?
public var comments = [Post]()
public init(text: String, date: NSDate, author: User? = nil, attachments: [Attachment]? = nil) {
self.text = text
self.date = date
self.author = author
self.attachments = attachments
}
}
Add post title
import Foundation
public class Post: NSObject {
public var title: String?
public var author: User?
public var date: NSDate
public var group: Group?
public var location: Location?
public var text: String?
public var attachments: [Attachment]?
public var likes: Int = 0
public var seen: Int = 0
public var parent: Post?
public var comments = [Post]()
public init(text: String, date: NSDate, author: User? = nil, attachments: [Attachment]? = nil) {
self.text = text
self.date = date
self.author = author
self.attachments = attachments
}
}
|
import Foundation
import AVFoundation
import Pitchy
public protocol PitchEngineDelegate: class {
func pitchEngineDidRecievePitch(pitchEngine: PitchEngine, pitch: Pitch)
func pitchEngineDidRecieveError(pitchEngine: PitchEngine, error: ErrorType)
}
public class PitchEngine {
public weak var delegate: PitchEngineDelegate?
public var active = false
private let bufferSize: AVAudioFrameCount
private var frequencies = [Float]()
public var pitches = [Pitch]()
public var currentPitch: Pitch!
private lazy var signalTracker: SignalTrackingAware = { [unowned self] in
let inputMonitor = InputSignalTracker(
bufferSize: self.bufferSize,
delegate: self
)
return inputMonitor
}()
private var transformer: TransformAware = FFTTransformer()
private var estimator: EstimationAware = HPSEstimator()
// MARK: - Initialization
public init(bufferSize: AVAudioFrameCount = 4096, delegate: PitchEngineDelegate?) {
self.bufferSize = bufferSize
self.delegate = delegate
}
// MARK: - Processing
public func start() {
do {
try signalTracker.start()
active = true
} catch {}
}
public func stop() {
signalTracker.stop()
frequencies = [Float]()
active = false
}
// MARK: - Helpers
private func averagePitch(pitch: Pitch) -> Pitch {
if let first = pitches.first where first.note.letter != pitch.note.letter {
pitches = []
}
pitches.append(pitch)
if pitches.count == 1 {
currentPitch = pitch
return currentPitch
}
let pts1 = pitches.filter({ $0.note.index == pitch.note.index }).count
let pts2 = pitches.filter({ $0.note.index == currentPitch.note.index }).count
currentPitch = pts1 >= pts2 ? pitch : pitches[pitches.count - 1]
return currentPitch
}
}
// MARK: - SignalTrackingDelegate
extension PitchEngine: SignalTrackingDelegate {
public func signalTracker(signalTracker: SignalTrackingAware,
didReceiveBuffer buffer: AVAudioPCMBuffer, atTime time: AVAudioTime) {
let transformedBuffer = transformer.transformBuffer(buffer)
do {
let frequency = try estimator.estimateFrequency(Float(time.sampleRate),
buffer: transformedBuffer)
let pitch = Pitch(frequency: Double(frequency))
delegate?.pitchEngineDidRecievePitch(self, pitch: pitch)
} catch {
delegate?.pitchEngineDidRecieveError(self, error: error)
}
}
}
Ask for record permissions
import Foundation
import AVFoundation
import Pitchy
public protocol PitchEngineDelegate: class {
func pitchEngineDidRecievePitch(pitchEngine: PitchEngine, pitch: Pitch)
func pitchEngineDidRecieveError(pitchEngine: PitchEngine, error: ErrorType)
}
public class PitchEngine {
public enum Error: ErrorType {
case RecordPermissionDenied
}
public enum Mode {
case Record, Play
}
public let mode: Mode
public let bufferSize: AVAudioFrameCount
public var active = false
public weak var delegate: PitchEngineDelegate?
private lazy var signalTracker: SignalTrackingAware = { [unowned self] in
let inputMonitor = InputSignalTracker(
bufferSize: self.bufferSize,
delegate: self
)
return inputMonitor
}()
private var transformer: TransformAware = FFTTransformer()
private var estimator: EstimationAware = HPSEstimator()
// MARK: - Initialization
public init(mode: Mode, bufferSize: AVAudioFrameCount = 4096, delegate: PitchEngineDelegate?) {
self.mode = mode
self.bufferSize = bufferSize
self.delegate = delegate
}
// MARK: - Processing
public func start() {
guard mode == .Play else {
activate()
return
}
AVAudioSession.sharedInstance().requestRecordPermission { [weak self] granted in
guard let weakSelf = self else { return }
guard granted else {
weakSelf.delegate?.pitchEngineDidRecieveError(weakSelf,
error: Error.RecordPermissionDenied)
return
}
dispatch_async(dispatch_get_main_queue()) {
weakSelf.activate()
}
}
}
public func stop() {
signalTracker.stop()
active = false
}
private func activate() {
do {
try signalTracker.start()
active = true
} catch {
delegate?.pitchEngineDidRecieveError(self, error: error)
}
}
}
// MARK: - SignalTrackingDelegate
extension PitchEngine: SignalTrackingDelegate {
public func signalTracker(signalTracker: SignalTrackingAware,
didReceiveBuffer buffer: AVAudioPCMBuffer, atTime time: AVAudioTime) {
let transformedBuffer = transformer.transformBuffer(buffer)
do {
let frequency = try estimator.estimateFrequency(Float(time.sampleRate),
buffer: transformedBuffer)
let pitch = Pitch(frequency: Double(frequency))
delegate?.pitchEngineDidRecievePitch(self, pitch: pitch)
} catch {
delegate?.pitchEngineDidRecieveError(self, error: error)
}
}
}
|
/*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public enum EditorPlaceholderAnimation {
case `default`
case hidden
}
open class Editor: View, Themeable {
/// Reference to textView.
public let textView = TextView()
/// A boolean indicating whether the textView is in edit mode.
open var isEditing: Bool {
return textView.isEditing
}
/// A boolean indicating whether the text is empty.
open var isEmpty: Bool {
return textView.isEmpty
}
/// The placeholder UILabel.
@IBInspectable
open var placeholderLabel: UILabel {
return textView.placeholderLabel
}
/// A Boolean that indicates if the placeholder label is animated.
@IBInspectable
open var isPlaceholderAnimated = true
/// Set the placeholder animation value.
open var placeholderAnimation = EditorPlaceholderAnimation.default {
didSet {
updatePlaceholderVisibility()
}
}
/// Placeholder normal text color.
@IBInspectable
open var placeholderNormalColor = Color.darkText.others {
didSet {
updatePlaceholderLabelColor()
}
}
/// Placeholder active text color.
@IBInspectable
open var placeholderActiveColor = Color.blue.base {
didSet {
updatePlaceholderLabelColor()
}
}
/// The scale of the active placeholder in relation to the inactive.
@IBInspectable
open var placeholderActiveScale: CGFloat = 0.75 {
didSet {
layoutPlaceholderLabel()
}
}
/// This property adds a padding to placeholder y position animation
@IBInspectable
open var placeholderVerticalOffset: CGFloat = 0
/// This property adds a padding to placeholder x position animation
@IBInspectable
open var placeholderHorizontalOffset: CGFloat = 0
/// Divider normal height.
@IBInspectable
open var dividerNormalHeight: CGFloat = 1 {
didSet {
updateDividerHeight()
}
}
/// Divider active height.
@IBInspectable
open var dividerActiveHeight: CGFloat = 2 {
didSet {
updateDividerHeight()
}
}
/// Divider normal color.
@IBInspectable
open var dividerNormalColor = Color.grey.lighten2 {
didSet {
updateDividerColor()
}
}
/// Divider active color.
@IBInspectable
open var dividerActiveColor = Color.blue.base {
didSet {
updateDividerColor()
}
}
/// The detailLabel UILabel that is displayed.
@IBInspectable
public let detailLabel = UILabel()
/// The detailLabel text value.
@IBInspectable
open var detail: String? {
get {
return detailLabel.text
}
set(value) {
detailLabel.text = value
layoutSubviews()
}
}
/// The detailLabel text color.
@IBInspectable
open var detailColor = Color.darkText.others {
didSet {
updateDetailLabelColor()
}
}
/// Vertical distance for the detailLabel from the divider.
@IBInspectable
open var detailVerticalOffset: CGFloat = 8 {
didSet {
layoutSubviews()
}
}
/// A reference to titleLabel.textAlignment observation.
private var placeholderLabelTextObserver: NSKeyValueObservation!
/**
A reference to textView.text observation.
Only observes programmatic changes.
*/
private var textViewTextObserver: NSKeyValueObservation!
open override func prepare() {
super.prepare()
backgroundColor = nil
prepareDivider()
prepareTextView()
preparePlaceholderLabel()
prepareDetailLabel()
prepareNotificationHandlers()
applyCurrentTheme()
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutPlaceholderLabel()
layoutDivider()
layoutBottomLabel(label: detailLabel, verticalOffset: detailVerticalOffset)
}
open func apply(theme: Theme) {
placeholderActiveColor = theme.secondary
placeholderNormalColor = theme.onSurface.withAlphaComponent(0.38)
dividerActiveColor = theme.secondary
dividerNormalColor = theme.onSurface.withAlphaComponent(0.12)
detailColor = theme.onSurface.withAlphaComponent(0.38)
textView.tintColor = theme.secondary
}
@discardableResult
open override func becomeFirstResponder() -> Bool {
return textView.becomeFirstResponder()
}
@discardableResult
open override func resignFirstResponder() -> Bool {
return textView.resignFirstResponder()
}
open override var inputAccessoryView: UIView? {
get {
return textView.inputAccessoryView
}
set(value) {
textView.inputAccessoryView = value
}
}
}
private extension Editor {
/// Prepares the divider.
func prepareDivider() {
dividerColor = dividerNormalColor
}
/// Prepares the textView.
func prepareTextView() {
layout(textView).edges()
textView.isPlaceholderLabelEnabled = false
textViewTextObserver = textView.observe(\.text) { [weak self] _, _ in
self?.updateEditorState()
}
}
/// Prepares the placeholderLabel.
func preparePlaceholderLabel() {
addSubview(placeholderLabel)
placeholderLabelTextObserver = placeholderLabel.observe(\.text) { [weak self] _, _ in
self?.layoutPlaceholderLabel()
}
}
/// Prepares the detailLabel.
func prepareDetailLabel() {
detailLabel.font = RobotoFont.regular(with: 12)
detailLabel.numberOfLines = 0
detailColor = Color.darkText.others
addSubview(detailLabel)
}
/// Prepares the Notification handlers.
func prepareNotificationHandlers() {
let center = NotificationCenter.default
center.addObserver(self, selector: #selector(handleTextViewTextDidBegin), name: UITextView.textDidBeginEditingNotification, object: textView)
center.addObserver(self, selector: #selector(handleTextViewTextDidChange), name: UITextView.textDidChangeNotification, object: textView)
center.addObserver(self, selector: #selector(handleTextViewTextDidEnd), name: UITextView.textDidEndEditingNotification, object: textView)
}
}
private extension Editor {
/// Updates the placeholderLabel text color.
func updatePlaceholderLabelColor() {
tintColor = placeholderActiveColor
placeholderLabel.textColor = isEditing ? placeholderActiveColor : placeholderNormalColor
}
/// Updates the placeholder visibility.
func updatePlaceholderVisibility() {
guard isEditing else {
placeholderLabel.isHidden = !isEmpty && .hidden == placeholderAnimation
return
}
placeholderLabel.isHidden = .hidden == placeholderAnimation
}
/// Updates the dividerColor.
func updateDividerColor() {
dividerColor = isEditing ? dividerActiveColor : dividerNormalColor
}
/// Updates the dividerThickness.
func updateDividerHeight() {
dividerThickness = isEditing ? dividerActiveHeight : dividerNormalHeight
}
/// Updates the detailLabel text color.
func updateDetailLabelColor() {
detailLabel.textColor = detailColor
}
}
private extension Editor {
/// Layout the placeholderLabel.
func layoutPlaceholderLabel() {
let inset = textView.textContainerInsets
let leftPadding = inset.left + textView.textContainer.lineFragmentPadding
let rightPadding = inset.right + textView.textContainer.lineFragmentPadding
let w = bounds.width - leftPadding - rightPadding
var h = placeholderLabel.sizeThatFits(CGSize(width: w, height: .greatestFiniteMagnitude)).height
h = max(h, textView.minimumTextHeight)
h = min(h, bounds.height - inset.top - inset.bottom)
placeholderLabel.bounds.size = CGSize(width: w, height: h)
guard isEditing || !isEmpty || !isPlaceholderAnimated else {
placeholderLabel.transform = CGAffineTransform.identity
placeholderLabel.frame.origin = CGPoint(x: leftPadding, y: inset.top)
return
}
placeholderLabel.transform = CGAffineTransform(scaleX: placeholderActiveScale, y: placeholderActiveScale)
placeholderLabel.frame.origin.y = -placeholderLabel.frame.height + placeholderVerticalOffset
switch placeholderLabel.textAlignment {
case .left, .natural:
placeholderLabel.frame.origin.x = leftPadding + placeholderHorizontalOffset
case .right:
let scaledWidth = w * placeholderActiveScale
placeholderLabel.frame.origin.x = bounds.width - scaledWidth - rightPadding + placeholderHorizontalOffset
default:break
}
}
/// Layout given label at the bottom with the vertical offset provided.
func layoutBottomLabel(label: UILabel, verticalOffset: CGFloat) {
let c = dividerContentEdgeInsets
label.frame.origin.x = c.left
label.frame.origin.y = bounds.height + verticalOffset
label.frame.size.width = bounds.width - c.left - c.right
label.frame.size.height = label.sizeThatFits(CGSize(width: label.bounds.width, height: .greatestFiniteMagnitude)).height
}
}
private extension Editor {
/// Notification handler for when text editing began.
@objc
func handleTextViewTextDidBegin() {
updateEditorState(isAnimated: true)
}
/// Notification handler for when text changed.
@objc
func handleTextViewTextDidChange() {
updateEditorState()
}
/// Notification handler for when text editing ended.
@objc
func handleTextViewTextDidEnd() {
updateEditorState(isAnimated: true)
}
/// Updates editor.
func updateEditorState(isAnimated: Bool = false) {
updatePlaceholderVisibility()
updatePlaceholderLabelColor()
updateDividerHeight()
updateDividerColor()
guard isAnimated && isPlaceholderAnimated else {
layoutPlaceholderLabel()
return
}
UIView.animate(withDuration: 0.15, animations: layoutPlaceholderLabel)
}
}
public extension Editor {
/// A reference to the textView text.
var text: String! {
get {
return textView.text
}
set(value) {
textView.text = value
}
}
/// A reference to the textView font.
var font: UIFont? {
get {
return textView.font
}
set(value) {
textView.font = value
}
}
/// A reference to the textView placeholder.
var placeholder: String? {
get {
return textView.placeholder
}
set(value) {
textView.placeholder = value
}
}
/// A reference to the textView textAlignment.
var textAlignment: NSTextAlignment {
get {
return textView.textAlignment
}
set(value) {
textView.textAlignment = value
detailLabel.textAlignment = value
}
}
}
Fixed infinite recursion in Editor
/*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public enum EditorPlaceholderAnimation {
case `default`
case hidden
}
open class Editor: View, Themeable {
/// Reference to textView.
public let textView = TextView()
/// A boolean indicating whether the textView is in edit mode.
open var isEditing: Bool {
return textView.isEditing
}
/// A boolean indicating whether the text is empty.
open var isEmpty: Bool {
return textView.isEmpty
}
/// The placeholder UILabel.
@IBInspectable
open var placeholderLabel: UILabel {
return textView.placeholderLabel
}
/// A Boolean that indicates if the placeholder label is animated.
@IBInspectable
open var isPlaceholderAnimated = true
/// Set the placeholder animation value.
open var placeholderAnimation = EditorPlaceholderAnimation.default {
didSet {
updatePlaceholderVisibility()
}
}
/// Placeholder normal text color.
@IBInspectable
open var placeholderNormalColor = Color.darkText.others {
didSet {
updatePlaceholderLabelColor()
}
}
/// Placeholder active text color.
@IBInspectable
open var placeholderActiveColor = Color.blue.base {
didSet {
updatePlaceholderLabelColor()
}
}
/// The scale of the active placeholder in relation to the inactive.
@IBInspectable
open var placeholderActiveScale: CGFloat = 0.75 {
didSet {
layoutPlaceholderLabel()
}
}
/// This property adds a padding to placeholder y position animation
@IBInspectable
open var placeholderVerticalOffset: CGFloat = 0
/// This property adds a padding to placeholder x position animation
@IBInspectable
open var placeholderHorizontalOffset: CGFloat = 0
/// Divider normal height.
@IBInspectable
open var dividerNormalHeight: CGFloat = 1 {
didSet {
updateDividerHeight()
}
}
/// Divider active height.
@IBInspectable
open var dividerActiveHeight: CGFloat = 2 {
didSet {
updateDividerHeight()
}
}
/// Divider normal color.
@IBInspectable
open var dividerNormalColor = Color.grey.lighten2 {
didSet {
updateDividerColor()
}
}
/// Divider active color.
@IBInspectable
open var dividerActiveColor = Color.blue.base {
didSet {
updateDividerColor()
}
}
/// The detailLabel UILabel that is displayed.
@IBInspectable
public let detailLabel = UILabel()
/// The detailLabel text value.
@IBInspectable
open var detail: String? {
get {
return detailLabel.text
}
set(value) {
detailLabel.text = value
layoutSubviews()
}
}
/// The detailLabel text color.
@IBInspectable
open var detailColor = Color.darkText.others {
didSet {
updateDetailLabelColor()
}
}
/// Vertical distance for the detailLabel from the divider.
@IBInspectable
open var detailVerticalOffset: CGFloat = 8 {
didSet {
layoutSubviews()
}
}
/// A reference to titleLabel.textAlignment observation.
private var placeholderLabelTextObserver: NSKeyValueObservation!
/**
A reference to textView.text observation.
Only observes programmatic changes.
*/
private var textViewTextObserver: NSKeyValueObservation!
open override func prepare() {
super.prepare()
backgroundColor = nil
prepareDivider()
prepareTextView()
preparePlaceholderLabel()
prepareDetailLabel()
prepareNotificationHandlers()
applyCurrentTheme()
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutPlaceholderLabel()
layoutDivider()
layoutBottomLabel(label: detailLabel, verticalOffset: detailVerticalOffset)
}
open func apply(theme: Theme) {
placeholderActiveColor = theme.secondary
placeholderNormalColor = theme.onSurface.withAlphaComponent(0.38)
dividerActiveColor = theme.secondary
dividerNormalColor = theme.onSurface.withAlphaComponent(0.12)
detailColor = theme.onSurface.withAlphaComponent(0.38)
textView.tintColor = theme.secondary
}
@discardableResult
open override func becomeFirstResponder() -> Bool {
return textView.becomeFirstResponder()
}
@discardableResult
open override func resignFirstResponder() -> Bool {
return textView.resignFirstResponder()
}
}
private extension Editor {
/// Prepares the divider.
func prepareDivider() {
dividerColor = dividerNormalColor
}
/// Prepares the textView.
func prepareTextView() {
layout(textView).edges()
textView.isPlaceholderLabelEnabled = false
textViewTextObserver = textView.observe(\.text) { [weak self] _, _ in
self?.updateEditorState()
}
}
/// Prepares the placeholderLabel.
func preparePlaceholderLabel() {
addSubview(placeholderLabel)
placeholderLabelTextObserver = placeholderLabel.observe(\.text) { [weak self] _, _ in
self?.layoutPlaceholderLabel()
}
}
/// Prepares the detailLabel.
func prepareDetailLabel() {
detailLabel.font = RobotoFont.regular(with: 12)
detailLabel.numberOfLines = 0
detailColor = Color.darkText.others
addSubview(detailLabel)
}
/// Prepares the Notification handlers.
func prepareNotificationHandlers() {
let center = NotificationCenter.default
center.addObserver(self, selector: #selector(handleTextViewTextDidBegin), name: UITextView.textDidBeginEditingNotification, object: textView)
center.addObserver(self, selector: #selector(handleTextViewTextDidChange), name: UITextView.textDidChangeNotification, object: textView)
center.addObserver(self, selector: #selector(handleTextViewTextDidEnd), name: UITextView.textDidEndEditingNotification, object: textView)
}
}
private extension Editor {
/// Updates the placeholderLabel text color.
func updatePlaceholderLabelColor() {
tintColor = placeholderActiveColor
placeholderLabel.textColor = isEditing ? placeholderActiveColor : placeholderNormalColor
}
/// Updates the placeholder visibility.
func updatePlaceholderVisibility() {
guard isEditing else {
placeholderLabel.isHidden = !isEmpty && .hidden == placeholderAnimation
return
}
placeholderLabel.isHidden = .hidden == placeholderAnimation
}
/// Updates the dividerColor.
func updateDividerColor() {
dividerColor = isEditing ? dividerActiveColor : dividerNormalColor
}
/// Updates the dividerThickness.
func updateDividerHeight() {
dividerThickness = isEditing ? dividerActiveHeight : dividerNormalHeight
}
/// Updates the detailLabel text color.
func updateDetailLabelColor() {
detailLabel.textColor = detailColor
}
}
private extension Editor {
/// Layout the placeholderLabel.
func layoutPlaceholderLabel() {
let inset = textView.textContainerInsets
let leftPadding = inset.left + textView.textContainer.lineFragmentPadding
let rightPadding = inset.right + textView.textContainer.lineFragmentPadding
let w = bounds.width - leftPadding - rightPadding
var h = placeholderLabel.sizeThatFits(CGSize(width: w, height: .greatestFiniteMagnitude)).height
h = max(h, textView.minimumTextHeight)
h = min(h, bounds.height - inset.top - inset.bottom)
placeholderLabel.bounds.size = CGSize(width: w, height: h)
guard isEditing || !isEmpty || !isPlaceholderAnimated else {
placeholderLabel.transform = CGAffineTransform.identity
placeholderLabel.frame.origin = CGPoint(x: leftPadding, y: inset.top)
return
}
placeholderLabel.transform = CGAffineTransform(scaleX: placeholderActiveScale, y: placeholderActiveScale)
placeholderLabel.frame.origin.y = -placeholderLabel.frame.height + placeholderVerticalOffset
switch placeholderLabel.textAlignment {
case .left, .natural:
placeholderLabel.frame.origin.x = leftPadding + placeholderHorizontalOffset
case .right:
let scaledWidth = w * placeholderActiveScale
placeholderLabel.frame.origin.x = bounds.width - scaledWidth - rightPadding + placeholderHorizontalOffset
default:break
}
}
/// Layout given label at the bottom with the vertical offset provided.
func layoutBottomLabel(label: UILabel, verticalOffset: CGFloat) {
let c = dividerContentEdgeInsets
label.frame.origin.x = c.left
label.frame.origin.y = bounds.height + verticalOffset
label.frame.size.width = bounds.width - c.left - c.right
label.frame.size.height = label.sizeThatFits(CGSize(width: label.bounds.width, height: .greatestFiniteMagnitude)).height
}
}
private extension Editor {
/// Notification handler for when text editing began.
@objc
func handleTextViewTextDidBegin() {
updateEditorState(isAnimated: true)
}
/// Notification handler for when text changed.
@objc
func handleTextViewTextDidChange() {
updateEditorState()
}
/// Notification handler for when text editing ended.
@objc
func handleTextViewTextDidEnd() {
updateEditorState(isAnimated: true)
}
/// Updates editor.
func updateEditorState(isAnimated: Bool = false) {
updatePlaceholderVisibility()
updatePlaceholderLabelColor()
updateDividerHeight()
updateDividerColor()
guard isAnimated && isPlaceholderAnimated else {
layoutPlaceholderLabel()
return
}
UIView.animate(withDuration: 0.15, animations: layoutPlaceholderLabel)
}
}
public extension Editor {
/// A reference to the textView text.
var text: String! {
get {
return textView.text
}
set(value) {
textView.text = value
}
}
/// A reference to the textView font.
var font: UIFont? {
get {
return textView.font
}
set(value) {
textView.font = value
}
}
/// A reference to the textView placeholder.
var placeholder: String? {
get {
return textView.placeholder
}
set(value) {
textView.placeholder = value
}
}
/// A reference to the textView textAlignment.
var textAlignment: NSTextAlignment {
get {
return textView.textAlignment
}
set(value) {
textView.textAlignment = value
detailLabel.textAlignment = value
}
}
}
|
/*
* Released under the MIT License (MIT), http://opensource.org/licenses/MIT
*
* Copyright (c) 2015 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com)
*
*/
import Foundation
public struct Context {
// TODO: get encoding from environmental variable LC_CTYPE
public var encoding = NSUTF8StringEncoding
public lazy var env = NSProcessInfo.processInfo().environment as [String: String]
public var stdin = NSFileHandle.fileHandleWithStandardInput() //as ReadableStreamType
public var stdout = NSFileHandle.fileHandleWithStandardOutput() //as WriteableStreamType
public var stderror = NSFileHandle.fileHandleWithStandardError() //as WriteableStreamType
/**
The current working directory.
Must be used instead of `run("cd ...")` because all the `run` commands are executed in a
separate process and changing the directory there will not affect the rest of the Swift script.
This directory is also used as the base for relative URL's.
*/
public var currentdirectory: String {
get { return Files.currentDirectoryPath }
set {
if !Files.changeCurrentDirectoryPath(newValue) {
printErrorAndExit("Could not change the working directory to \(newValue)")
}
}
}
public lazy var arguments: [String] = Process.arguments.isEmpty ? [] : Array(dropFirst(Process.arguments))
public lazy var name: String = Process.arguments.first ?? ""
}
public var main = Context()
Add protocol ShellContextType and let “main” implement it.
- make “main” a true singleton.
/*
* Released under the MIT License (MIT), http://opensource.org/licenses/MIT
*
* Copyright (c) 2015 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com)
*
*/
import Foundation
public protocol ShellContextType {
var encoding: UInt {get set}
var env: [String: String] {get set}
var stdin: NSFileHandle {get set}
var stdout: NSFileHandle {get set}
var stderror: NSFileHandle {get set}
/**
The current working directory.
Must be used instead of `run("cd ...")` because all the `run` commands are executed in a
separate process and changing the directory there will not affect the rest of the Swift script.
This directory is also used as the base for relative URL's.
*/
var currentdirectory: String {get set}
}
public struct MainShellContext: ShellContextType {
// TODO: get encoding from environmental variable LC_CTYPE
public var encoding = NSUTF8StringEncoding
public var env = NSProcessInfo.processInfo().environment as [String: String]
public var stdin = NSFileHandle.fileHandleWithStandardInput() //as ReadableStreamType
public var stdout = NSFileHandle.fileHandleWithStandardOutput() //as WriteableStreamType
public var stderror = NSFileHandle.fileHandleWithStandardError() //as WriteableStreamType
/**
The current working directory.
Must be used instead of `run("cd ...")` because all the `run` commands are executed in a
separate process and changing the directory there will not affect the rest of the Swift script.
This directory is also used as the base for relative URL's.
*/
public var currentdirectory: String {
get { return Files.currentDirectoryPath }
set {
if !Files.changeCurrentDirectoryPath(newValue) {
printErrorAndExit("Could not change the working directory to \(newValue)")
}
}
}
public lazy var arguments: [String] = Process.arguments.isEmpty ? [] : Array(dropFirst(Process.arguments))
public lazy var name: String = Process.arguments.first ?? ""
private init() {
}
}
public var main = MainShellContext()
|
//
// MercadoPagoCheckoutViewModel+Plugins.swift
// MercadoPagoSDK
//
// Created by Eden Torres on 12/14/17.
// Copyright © 2017 MercadoPago. All rights reserved.
//
import Foundation
internal extension MercadoPagoCheckoutViewModel {
func needToShowPaymentMethodConfigPlugin() -> Bool {
guard let paymentMethodPluginSelected = paymentOptionSelected as? PXPaymentMethodPlugin else {
return false
}
populateCheckoutStore()
if let shouldSkip = paymentMethodPluginSelected.paymentMethodConfigPlugin?.shouldSkip(store: PXCheckoutStore.sharedInstance) {
if !shouldSkip {
willShowPaymentMethodConfigPlugin()
}
return !shouldSkip
}
if wasPaymentMethodConfigPluginShowed() {
return false
}
return paymentMethodPluginSelected.paymentMethodConfigPlugin != nil
}
func needToCreatePaymentForPaymentMethodPlugin() -> Bool {
return needToCreatePayment() && self.paymentOptionSelected is PXPaymentMethodPlugin
}
func wasPaymentMethodConfigPluginShowed() -> Bool {
return paymentMethodConfigPluginShowed
}
func willShowPaymentMethodConfigPlugin() {
paymentMethodConfigPluginShowed = true
}
func resetPaymentMethodConfigPlugin() {
paymentMethodConfigPluginShowed = false
}
func paymentMethodPluginToPaymentMethod(plugin: PXPaymentMethodPlugin) {
let paymentMethod = PaymentMethod()
paymentMethod.paymentMethodId = plugin.getId()
paymentMethod.name = plugin.getTitle()
paymentMethod.paymentTypeId = PXPaymentMethodPlugin.PAYMENT_METHOD_TYPE_ID
paymentMethod.setExternalPaymentMethodImage(externalImage: plugin.getImage())
paymentMethod.paymentMethodDescription = plugin.paymentMethodPluginDescription
self.paymentData.paymentMethod = paymentMethod
}
}
// MARK: Payment Plugin
internal extension MercadoPagoCheckoutViewModel {
func needToCreatePaymentForPaymentPlugin() -> Bool {
if paymentPlugin == nil {
return false
}
populateCheckoutStore()
paymentPlugin?.didReceive?(checkoutStore: PXCheckoutStore.sharedInstance)
if let shouldSupport = paymentPlugin?.support() {
return shouldSupport
}
return needToCreatePayment()
}
}
SCREEN_PAYMENT_METHOD_PLUGIN_CONFIG step fix
//
// MercadoPagoCheckoutViewModel+Plugins.swift
// MercadoPagoSDK
//
// Created by Eden Torres on 12/14/17.
// Copyright © 2017 MercadoPago. All rights reserved.
//
import Foundation
internal extension MercadoPagoCheckoutViewModel {
func needToShowPaymentMethodConfigPlugin() -> Bool {
guard let paymentMethodPluginSelected = paymentOptionSelected as? PXPaymentMethodPlugin else {
return false
}
if wasPaymentMethodConfigPluginShowed() {
return false
}
populateCheckoutStore()
if let shouldSkip = paymentMethodPluginSelected.paymentMethodConfigPlugin?.shouldSkip(store: PXCheckoutStore.sharedInstance) {
return !shouldSkip
}
return paymentMethodPluginSelected.paymentMethodConfigPlugin != nil
}
func needToCreatePaymentForPaymentMethodPlugin() -> Bool {
return needToCreatePayment() && self.paymentOptionSelected is PXPaymentMethodPlugin
}
func wasPaymentMethodConfigPluginShowed() -> Bool {
return paymentMethodConfigPluginShowed
}
func willShowPaymentMethodConfigPlugin() {
paymentMethodConfigPluginShowed = true
}
func resetPaymentMethodConfigPlugin() {
paymentMethodConfigPluginShowed = false
}
func paymentMethodPluginToPaymentMethod(plugin: PXPaymentMethodPlugin) {
let paymentMethod = PaymentMethod()
paymentMethod.paymentMethodId = plugin.getId()
paymentMethod.name = plugin.getTitle()
paymentMethod.paymentTypeId = PXPaymentMethodPlugin.PAYMENT_METHOD_TYPE_ID
paymentMethod.setExternalPaymentMethodImage(externalImage: plugin.getImage())
paymentMethod.paymentMethodDescription = plugin.paymentMethodPluginDescription
self.paymentData.paymentMethod = paymentMethod
}
}
// MARK: Payment Plugin
internal extension MercadoPagoCheckoutViewModel {
func needToCreatePaymentForPaymentPlugin() -> Bool {
if paymentPlugin == nil {
return false
}
populateCheckoutStore()
paymentPlugin?.didReceive?(checkoutStore: PXCheckoutStore.sharedInstance)
if let shouldSupport = paymentPlugin?.support() {
return shouldSupport
}
return needToCreatePayment()
}
}
|
//
// CalendarDaysVC.swift
// TastyTomato
//
// Created by Jan Nash (resmio) on 08.12.17.
// Copyright © 2017 resmio. All rights reserved.
//
import UIKit
import SwiftDate
// MARK: // Internal
// MARK: - CalendarDaysVCDelegate
protocol CalendarDaysVCDelegate: class {
func shouldSelect(_ date: Date, on calendarDaysVC: CalendarDaysVC) -> Bool
func didSelect(_ date: Date, on calendarDaysVC: CalendarDaysVC)
}
// MARK: - CalendarDaysVCDesign
struct CalendarDaysVCDesign {
var monthNameAndYearFont: UIFont = CalendarVCDesign.defaultDesign.monthNameAndYearFont
var dayNumberFont: UIFont = CalendarVCDesign.defaultDesign.dayNumberFont
var todayDayNumberFont: UIFont = CalendarVCDesign.defaultDesign.todayDayNumberFont
var monthNameAndYearTextColor: UIColor = CalendarVCDesign.defaultDesign.monthNameAndYearTextColor
var normalDayNumberTextColor: UIColor = CalendarVCDesign.defaultDesign.normalDayNumberTextColor
var todayDayNumberTextColor: UIColor = CalendarVCDesign.defaultDesign.todayDayNumberTextColor
var differentMonthDayNumberTextColor: UIColor = CalendarVCDesign.defaultDesign.differentMonthDayNumberTextColor
var pastDayNumberTextColor: UIColor = CalendarVCDesign.defaultDesign.pastDayNumberTextColor
}
// MARK: - CalendarDaysVC
// MARK: Interface
extension CalendarDaysVC {
// Readonly
var month: Date {
return self._month
}
// ReadWrite
var delegate: CalendarDaysVCDelegate? {
get {
return self._delegate
}
set(newDelegate) {
self._delegate = newDelegate
}
}
var topInset: CGFloat {
get {
return self._calendarDaysView.topInset
}
set(newTopInset) {
self._calendarDaysView.topInset = newTopInset
}
}
var titleLabelFrame: CGRect {
get {
return self._calendarDaysView.titleLabelFrame
}
set(newTitleLabelFrame) {
self._calendarDaysView.titleLabelFrame = newTitleLabelFrame
}
}
// Functions
func selectDate(_ date: Date?) {
self._selectDate(date)
}
func setDesign(_ design: CalendarDaysVCDesign) {
self._setDesign(design)
}
}
// MARK: Class Declaration
class CalendarDaysVC: UIViewController {
// Required Init
required init?(coder aDecoder: NSCoder) {
let month: Date = Date().dateAtStartOf(.month)
self._month = month
super.init(coder: aDecoder)
self._calendarDaysView.title = month.toString(.custom("MMMM YYYY"))
}
// Init
init(month: Date) {
self._month = month
super.init(nibName: nil, bundle: nil)
self._calendarDaysView.title = month.toString(.custom("MMMM YYYY"))
}
// Private Weak Variables
fileprivate weak var _delegate: CalendarDaysVCDelegate?
// Private Lazy Variables
fileprivate lazy var _calendarDaysView: CalendarDaysView = self._createCalendarDaysView()
// Private Variables
fileprivate var _month: Date
fileprivate var _design: CalendarDaysVCDesign = CalendarDaysVCDesign()
// Lifecycle Override
override func loadView() {
self.view = self._calendarDaysView
}
}
// MARK: Delegates / DataSources
// MARK: CalendarDaysViewDelegate
extension CalendarDaysVC: CalendarDaysViewDelegate {
func configure(_ dateCell: DateCell, for indexPath: IndexPath, on calendarDaysView: CalendarDaysView) {
self._configure(dateCell, for: indexPath, on: calendarDaysView)
}
func shouldSelect(_ dateCell: DateCell, at indexPath: IndexPath, on calendarDaysView: CalendarDaysView) -> Bool {
return self._shouldSelect(dateCell, at: indexPath, on: calendarDaysView)
}
func didSelect(_ dateCell: DateCell, at indexPath: IndexPath, on calendarDaysView: CalendarDaysView) {
self._didSelect(dateCell, at: indexPath, on: calendarDaysView)
}
}
// MARK: // Private
// MARK: Lazy Variable Creation
private extension CalendarDaysVC {
func _createCalendarDaysView() -> CalendarDaysView {
let design: CalendarDaysVCDesign = self._design
let calendarDaysView: CalendarDaysView = CalendarDaysView()
calendarDaysView.delegate = self
calendarDaysView.titleFont = design.monthNameAndYearFont
calendarDaysView.titleColor = design.monthNameAndYearTextColor
return calendarDaysView
}
}
// MARK: Delegate / DataSource Implementations
// MARK: CalendarDaysViewDelegate
private extension CalendarDaysVC/*: CalendarDaysViewDelegate*/ {
func _configure(_ dateCell: DateCell, for indexPath: IndexPath, on calendarDaysView: CalendarDaysView) {
let date: Date = self.month.dateAtStartOf(.weekOfMonth) + indexPath.row.days
dateCell.title = date.toString(.custom("d"))
let design: CalendarDaysVCDesign = self._design
let dateIsToday: Bool = date.isToday
let dateIsInCurrentMonth: Bool = date.isInside(date: self.month, granularity: .month)
var titleColor: UIColor = design.normalDayNumberTextColor
var titleFont: UIFont = design.dayNumberFont
if dateIsToday {
titleColor = design.todayDayNumberTextColor
titleFont = design.todayDayNumberFont
} else if !dateIsInCurrentMonth {
titleColor = design.differentMonthDayNumberTextColor
} else if date.isBefore(date: Date(), granularity: .day) {
titleColor = design.pastDayNumberTextColor
}
dateCell.titleColor = titleColor
dateCell.titleFont = titleFont
}
func _shouldSelect(_ dateCell: DateCell, at indexPath: IndexPath, on calendarDaysView: CalendarDaysView) -> Bool {
guard let delegate: CalendarDaysVCDelegate = self.delegate else { return true }
let date: Date = self.month.dateAtStartOf(.weekOfMonth) + indexPath.row.days
return delegate.shouldSelect(date, on: self)
}
func _didSelect(_ dateCell: DateCell, at indexPath: IndexPath, on calendarDaysView: CalendarDaysView) {
guard let delegate: CalendarDaysVCDelegate = self.delegate else { return }
let date: Date = self.month.dateAtStartOf(.weekOfMonth) + indexPath.row.days
delegate.didSelect(date, on: self)
}
}
// MARK: Select Date
private extension CalendarDaysVC {
func _selectDate(_ date: Date?) {
var indexPath: IndexPath? = nil
hasDate: if let date: Date = date {
let firstDisplayedDay: Date = self.month.dateAtStartOf(.weekOfMonth)
let lastDisplayedDay: Date = firstDisplayedDay + 41.days
guard date.isInRange(date: firstDisplayedDay, and: lastDisplayedDay) else { break hasDate }
guard let row: Int = (date - self.month.dateAtStartOf(.weekOfMonth)).day else { break hasDate }
indexPath = IndexPath(row: row, section: 0)
}
self._calendarDaysView.selectDateCell(at: indexPath)
}
}
// MARK: Set Design
private extension CalendarDaysVC {
func _setDesign(_ design: CalendarDaysVCDesign) {
self._design = design
let calendarDaysView: CalendarDaysView = self._calendarDaysView
calendarDaysView.reloadCells()
calendarDaysView.titleFont = design.monthNameAndYearFont
calendarDaysView.titleColor = design.monthNameAndYearTextColor
}
}
Update isBefore usage
//
// CalendarDaysVC.swift
// TastyTomato
//
// Created by Jan Nash (resmio) on 08.12.17.
// Copyright © 2017 resmio. All rights reserved.
//
import UIKit
import SwiftDate
// MARK: // Internal
// MARK: - CalendarDaysVCDelegate
protocol CalendarDaysVCDelegate: class {
func shouldSelect(_ date: Date, on calendarDaysVC: CalendarDaysVC) -> Bool
func didSelect(_ date: Date, on calendarDaysVC: CalendarDaysVC)
}
// MARK: - CalendarDaysVCDesign
struct CalendarDaysVCDesign {
var monthNameAndYearFont: UIFont = CalendarVCDesign.defaultDesign.monthNameAndYearFont
var dayNumberFont: UIFont = CalendarVCDesign.defaultDesign.dayNumberFont
var todayDayNumberFont: UIFont = CalendarVCDesign.defaultDesign.todayDayNumberFont
var monthNameAndYearTextColor: UIColor = CalendarVCDesign.defaultDesign.monthNameAndYearTextColor
var normalDayNumberTextColor: UIColor = CalendarVCDesign.defaultDesign.normalDayNumberTextColor
var todayDayNumberTextColor: UIColor = CalendarVCDesign.defaultDesign.todayDayNumberTextColor
var differentMonthDayNumberTextColor: UIColor = CalendarVCDesign.defaultDesign.differentMonthDayNumberTextColor
var pastDayNumberTextColor: UIColor = CalendarVCDesign.defaultDesign.pastDayNumberTextColor
}
// MARK: - CalendarDaysVC
// MARK: Interface
extension CalendarDaysVC {
// Readonly
var month: Date {
return self._month
}
// ReadWrite
var delegate: CalendarDaysVCDelegate? {
get {
return self._delegate
}
set(newDelegate) {
self._delegate = newDelegate
}
}
var topInset: CGFloat {
get {
return self._calendarDaysView.topInset
}
set(newTopInset) {
self._calendarDaysView.topInset = newTopInset
}
}
var titleLabelFrame: CGRect {
get {
return self._calendarDaysView.titleLabelFrame
}
set(newTitleLabelFrame) {
self._calendarDaysView.titleLabelFrame = newTitleLabelFrame
}
}
// Functions
func selectDate(_ date: Date?) {
self._selectDate(date)
}
func setDesign(_ design: CalendarDaysVCDesign) {
self._setDesign(design)
}
}
// MARK: Class Declaration
class CalendarDaysVC: UIViewController {
// Required Init
required init?(coder aDecoder: NSCoder) {
let month: Date = Date().dateAtStartOf(.month)
self._month = month
super.init(coder: aDecoder)
self._calendarDaysView.title = month.toString(.custom("MMMM YYYY"))
}
// Init
init(month: Date) {
self._month = month
super.init(nibName: nil, bundle: nil)
self._calendarDaysView.title = month.toString(.custom("MMMM YYYY"))
}
// Private Weak Variables
fileprivate weak var _delegate: CalendarDaysVCDelegate?
// Private Lazy Variables
fileprivate lazy var _calendarDaysView: CalendarDaysView = self._createCalendarDaysView()
// Private Variables
fileprivate var _month: Date
fileprivate var _design: CalendarDaysVCDesign = CalendarDaysVCDesign()
// Lifecycle Override
override func loadView() {
self.view = self._calendarDaysView
}
}
// MARK: Delegates / DataSources
// MARK: CalendarDaysViewDelegate
extension CalendarDaysVC: CalendarDaysViewDelegate {
func configure(_ dateCell: DateCell, for indexPath: IndexPath, on calendarDaysView: CalendarDaysView) {
self._configure(dateCell, for: indexPath, on: calendarDaysView)
}
func shouldSelect(_ dateCell: DateCell, at indexPath: IndexPath, on calendarDaysView: CalendarDaysView) -> Bool {
return self._shouldSelect(dateCell, at: indexPath, on: calendarDaysView)
}
func didSelect(_ dateCell: DateCell, at indexPath: IndexPath, on calendarDaysView: CalendarDaysView) {
self._didSelect(dateCell, at: indexPath, on: calendarDaysView)
}
}
// MARK: // Private
// MARK: Lazy Variable Creation
private extension CalendarDaysVC {
func _createCalendarDaysView() -> CalendarDaysView {
let design: CalendarDaysVCDesign = self._design
let calendarDaysView: CalendarDaysView = CalendarDaysView()
calendarDaysView.delegate = self
calendarDaysView.titleFont = design.monthNameAndYearFont
calendarDaysView.titleColor = design.monthNameAndYearTextColor
return calendarDaysView
}
}
// MARK: Delegate / DataSource Implementations
// MARK: CalendarDaysViewDelegate
private extension CalendarDaysVC/*: CalendarDaysViewDelegate*/ {
func _configure(_ dateCell: DateCell, for indexPath: IndexPath, on calendarDaysView: CalendarDaysView) {
let date: Date = self.month.dateAtStartOf(.weekOfMonth) + indexPath.row.days
dateCell.title = date.toString(.custom("d"))
let design: CalendarDaysVCDesign = self._design
let dateIsToday: Bool = date.isToday
let dateIsInCurrentMonth: Bool = date.isInside(date: self.month, granularity: .month)
var titleColor: UIColor = design.normalDayNumberTextColor
var titleFont: UIFont = design.dayNumberFont
if dateIsToday {
titleColor = design.todayDayNumberTextColor
titleFont = design.todayDayNumberFont
} else if !dateIsInCurrentMonth {
titleColor = design.differentMonthDayNumberTextColor
} else if date.isBeforeDate(Date(), granularity: .day) {
titleColor = design.pastDayNumberTextColor
}
dateCell.titleColor = titleColor
dateCell.titleFont = titleFont
}
func _shouldSelect(_ dateCell: DateCell, at indexPath: IndexPath, on calendarDaysView: CalendarDaysView) -> Bool {
guard let delegate: CalendarDaysVCDelegate = self.delegate else { return true }
let date: Date = self.month.dateAtStartOf(.weekOfMonth) + indexPath.row.days
return delegate.shouldSelect(date, on: self)
}
func _didSelect(_ dateCell: DateCell, at indexPath: IndexPath, on calendarDaysView: CalendarDaysView) {
guard let delegate: CalendarDaysVCDelegate = self.delegate else { return }
let date: Date = self.month.dateAtStartOf(.weekOfMonth) + indexPath.row.days
delegate.didSelect(date, on: self)
}
}
// MARK: Select Date
private extension CalendarDaysVC {
func _selectDate(_ date: Date?) {
var indexPath: IndexPath? = nil
hasDate: if let date: Date = date {
let firstDisplayedDay: Date = self.month.dateAtStartOf(.weekOfMonth)
let lastDisplayedDay: Date = firstDisplayedDay + 41.days
guard date.isInRange(date: firstDisplayedDay, and: lastDisplayedDay) else { break hasDate }
guard let row: Int = (date - self.month.dateAtStartOf(.weekOfMonth)).day else { break hasDate }
indexPath = IndexPath(row: row, section: 0)
}
self._calendarDaysView.selectDateCell(at: indexPath)
}
}
// MARK: Set Design
private extension CalendarDaysVC {
func _setDesign(_ design: CalendarDaysVCDesign) {
self._design = design
let calendarDaysView: CalendarDaysView = self._calendarDaysView
calendarDaysView.reloadCells()
calendarDaysView.titleFont = design.monthNameAndYearFont
calendarDaysView.titleColor = design.monthNameAndYearTextColor
}
}
|
/*
The MIT License (MIT)
Copyright (c) 2016 - 2017 Gregory Higley (Prosumma)
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
// MARK: -
/**
`Name.default` is used for the default name of a container or type when one is not specified.
*/
public enum Name {
/**
`Name.default` is used for the default name of a container or type when one is not specified.
*/
case `default`
}
// MARK: - Keys
/**
The protocol shared by `Key<T>` and `AnyKey`.
Registration in Guise associates a unique `Keyed` with
a dependency. Any registration using the same `Keyed`
overwrites any previous registration.
A `Keyed` consists of a `type`, `name`, and `container`.
The only truly required attribute is `type`. While the
others cannot be `nil`, they can be defaulted to `Name.default`.
Any `Hashable` value can be used for `name` and `container`.
All three of these attributes together are what make a `Keyed`
unique.
*/
public protocol Keyed {
/**
The fully qualified name of a type produced by `String(reflecting: type)`.
*/
var type: String { get }
/**
The name of a registration. Defaults to `Name.default`.
Names can be used to disambiguate registrations of the same type.
*/
var name: AnyHashable { get }
/**
The container of a registration. Defaults to `Name.default`.
A container may be used to group registrations together for
any purpose. One common use is to quickly _unregister_ many
registrations at once:
```
Guise.unregister(container: Container.plugins)
```
*/
var container: AnyHashable { get }
}
public protocol EquatableKeyed: Keyed, Hashable, Equatable {
}
public func ==<K: EquatableKeyed>(lhs: K, rhs: K) -> Bool {
if lhs.hashValue != rhs.hashValue { return false }
if lhs.type != rhs.type { return false }
if lhs.name != rhs.name { return false }
if lhs.container != rhs.container { return false }
return true
}
/**
A type-erasing unique key under which to register a block in Guise.
This type is used primarily when keys must be stored heterogeneously,
e.g., in `Set<AnyKey>` returned from a `filter` overload.
This is also the type that Guise uses under the hood to associate
keys with registered dependencies.
*/
public struct AnyKey: EquatableKeyed {
public let type: String
public let name: AnyHashable
public let container: AnyHashable
public let hashValue: Int
public init(_ key: Keyed) {
self.type = key.type
self.name = key.name
self.container = key.container
self.hashValue = hash(self.type, self.name, self.container)
}
public init<T, N: Hashable, C: Hashable>(type: T.Type, name: N, container: C) {
self.type = String(reflecting: T.self)
self.name = name
self.container = container
self.hashValue = hash(self.type, self.name, self.container)
}
public init<T, N: Hashable>(type: T.Type, name: N) {
self.init(type: type, name: name, container: Name.default)
}
public init<T, C: Hashable>(type: T.Type, container: C) {
self.init(type: type, name: Name.default, container: container)
}
public init<T>(type: T.Type) {
self.init(type: type, name: Name.default, container: Name.default)
}
}
/**
A type-safe registration key.
This type is used wherever type-safety is needed or
wherever keys are requested by type.
*/
public struct Key<T>: EquatableKeyed {
public let type: String
public let name: AnyHashable
public let container: AnyHashable
public let hashValue: Int
public init<N: Hashable, C: Hashable>(name: N, container: C) {
self.type = String(reflecting: T.self)
self.name = name
self.container = container
self.hashValue = hash(self.type, self.name, self.container)
}
public init<N: Hashable>(name: N) {
self.init(name: name, container: Name.default)
}
public init<C: Hashable>(container: C) {
self.init(name: Name.default, container: container)
}
public init() {
self.init(name: Name.default, container: Name.default)
}
public init?(_ key: Keyed) {
if key.type != String(reflecting: T.self) { return nil }
self.type = key.type
self.name = key.name
self.container = key.container
self.hashValue = hash(self.type, self.name, self.container)
}
}
// MARK: -
/**
This class creates and holds a type-erasing thunk over a registration block.
Guise creates a mapping between a `Keyed` and a `Dependency`. `Keyed` holds
the `type`, `name`, and `container`, while `Dependency` holds the resolution
block, metadata, caching preference, and any cached instance.
*/
private class Dependency {
/** Default lifecycle for the dependency. */
let cached: Bool
/** Registered block. */
private let resolution: (Any) -> Any
/** Cached instance, if any. */
private var instance: Any?
/** Metadata */
let metadata: Any
init<P, T>(metadata: Any, cached: Bool, resolution: @escaping Resolution<P, T>) {
self.metadata = metadata
self.cached = cached
self.resolution = { param in resolution(param as! P) }
}
func resolve<T>(parameter: Any, cached: Bool?) -> T {
var result: T
if cached ?? self.cached {
if instance == nil {
instance = resolution(parameter)
}
result = instance! as! T
} else {
result = resolution(parameter) as! T
}
return result
}
}
// MARK: -
/**
The type of a resolution block.
These are what actually get registered. Guise does not register
types or instances directly.
*/
public typealias Resolution<P, T> = (P) -> T
/**
The type of a metadata filter.
*/
public typealias Metafilter<M> = (M) -> Bool
/**
Used in filters.
This type exists primarily to emphasize that the `metathunk` method should be applied to
`Metafilter<M>` before the metafilter is passed to the master `filter` or `exists` method.
*/
private typealias Metathunk = Metafilter<Any>
/**
Guise is a simple dependency resolution framework.
Guise does not register types or instances directly. Instead,
it registers a resolution block which returns the needed dependency.
Guise manages a thread-safe dictionary mapping keys to resolution
blocks.
The key with which each dependency is associated consists of the
return type of the resolution block, a `Hashable` name, and a `Hashable`
container. The name and container default to `Name.default`, so
they do not need to be specified unless required.
In addition, it is common to alias the return type of the resolution
block using a protocol to achieve abstraction.
This simple, flexible system can accommodate many scenarios. Some of
these scenarios are so common that overloads exist to handle them
concisely.
- note: Instances of this type cannot be created. Use its static methods.
*/
public struct Guise {
private init() {}
private static var lock = Lock()
private static var registrations = [AnyKey: Dependency]()
/**
All keys.
*/
public static var keys: Set<AnyKey> {
return lock.read { Set(registrations.keys) }
}
// MARK: Registration
/**
Register the `resolution` block with the result type `T` and the parameter `P`.
- returns: The `key` that was passed in.
- parameters:
- key: The `Key` under which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- cached: Whether or not to cache the result of the registration block.
- resolution: The block to register with Guise.
*/
public static func register<P, T>(key: Key<T>, metadata: Any = (), cached: Bool = false, resolution: @escaping Resolution<P, T>) -> Key<T> {
lock.write { registrations[AnyKey(key)] = Dependency(metadata: metadata, cached: cached, resolution: resolution) }
return key
}
/**
Multiply register the `resolution` block with the result type `T` and the parameter `P`.
- returns: The passed-in `keys`.
- parameters:
- key: The `Key` under which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- cached: Whether or not to cache the result of the registration block.
- resolution: The block to register with Guise.
*/
public static func register<P, T>(keys: Set<Key<T>>, metadata: Any = (), cached: Bool = false, resolution: @escaping Resolution<P, T>) -> Set<Key<T>> {
return lock.write {
for key in keys {
registrations[AnyKey(key)] = Dependency(metadata: metadata, cached: cached, resolution: resolution)
}
return keys
}
}
/**
Register the `resolution` block with the result type `T` and the parameter `P`.
- returns: The unique `Key<T>` for this registration.
- parameters:
- name: The name under which to register the block.
- container: The container in which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- cached: Whether or not to cache the result of the registration block after first use.
- resolution: The block to register with Guise.
*/
public static func register<P, T, N: Hashable, C: Hashable>(name: N, container: C, metadata: Any = (), cached: Bool = false, resolution: @escaping Resolution<P, T>) -> Key<T> {
return register(key: Key(name: name, container: container), metadata: metadata, cached: cached, resolution: resolution)
}
/**
Register the `resolution` block with the result type `T` and the parameter `P`.
- returns: The unique `Key<T>` for this registration.
- parameters:
- name: The name under which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- cached: Whether or not to cache the result of the registration block.
- resolution: The block to register with Guise.
- note: The registration is made in the default container, `Name.default`.
*/
public static func register<P, T, N: Hashable>(name: N, metadata: Any = (), cached: Bool = false, resolution: @escaping Resolution<P, T>) -> Key<T> {
return register(key: Key(name: name, container: Name.default), metadata: metadata, cached: cached, resolution: resolution)
}
/**
Register the `resolution` block with the result type `T` and the parameter `P`.
- returns: The unique `Key<T>` for this registration.
- parameters:
- container: The container in which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- cached: Whether or not to cache the result of the registration block.
- resolution: The block to register with Guise.
- note: The registration is made with the default name, `Name.default`.
*/
public static func register<P, T, C: Hashable>(container: C, metadata: Any = (), cached: Bool = false, resolution: @escaping Resolution<P, T>) -> Key<T> {
return register(key: Key(name: Name.default, container: container), metadata: metadata, cached: cached, resolution: resolution)
}
/**
Register the `resolution` block with the result type `T` and the parameter `P`.
- returns: The unique `Key<T>` for this registration.
- parameters:
- metadata: Arbitrary metadata associated with this registration.
- cached: Whether or not to cache the result of the registration block.
- resolution: The block to register with Guise.
- note: The registration is made in the default container, `Name.default` and under the default name, `Name.default`.
*/
public static func register<P, T>(metadata: Any = (), cached: Bool = false, resolution: @escaping Resolution<P, T>) -> Key<T> {
return register(key: Key(name: Name.default, container: Name.default), metadata: metadata, cached: cached, resolution: resolution)
}
/**
Register an instance.
- returns: The unique `Key<T>` for this registration.
- parameters:
- instance: The instance to register.
- name: The name under which to register the block.
- container: The container in which to register the block.
- metadata: Arbitrary metadata associated with this registration.
*/
public static func register<T, N: Hashable, C: Hashable>(instance: T, name: N, container: C, metadata: Any = ()) -> Key<T> {
return register(key: Key(name: name, container: container), metadata: metadata, cached: true) { instance }
}
/**
Register an instance.
- returns: The unique `Key<T>` for this registration.
- parameters:
- instance: The instance to register.
- name: The name under which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- note: The registration is made in the default container, `Name.default`.
*/
public static func register<T, N: Hashable>(instance: T, name: N, metadata: Any = ()) -> Key<T> {
return register(key: Key(name: name, container: Name.default), metadata: metadata, cached: true) { instance }
}
/**
Register an instance.
- returns: The unique `Key<T>` for this registration.
- parameters:
- instance: The instance to register.
- container: The container in which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- note: The registration is made with the default name, `Name.default`.
*/
public static func register<T, C: Hashable>(instance: T, container: C, metadata: Any = ()) -> Key<T> {
return register(key: Key(name: Name.default, container: container), metadata: metadata, cached: true) { instance }
}
/**
Register an instance.
- returns: The unique `Key<T>` for this registration.
- parameters:
- instance: The instance to register.
- metadata: Arbitrary metadata associated with this registration.
- note: The registration is made with the default name, `Name.default`, and in the default container, `Name.default`.
*/
public static func register<T>(instance: T, metadata: Any = ()) -> Key<T> {
return register(key: Key(name: Name.default, container: Name.default), metadata: metadata, cached: true) { instance }
}
// MARK: Resolution
/**
Resolve a dependency registered with `key`.
- returns: The resolved dependency or `nil` if it is not found.
- parameters:
- key: The key to resolve.
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the block again.
- note: Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T>(key: Key<T>, parameter: Any = (), cached: Bool? = nil) -> T? {
guard let dependency = lock.read({ registrations[AnyKey(key)] }) else { return nil }
return dependency.resolve(parameter: parameter, cached: cached)
}
/**
Resolve multiple registrations at the same time.
- returns: An array of the resolved dependencies.
- parameters:
- keys: The keys to resolve.
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the resolution block again.
- note: Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T>(keys: Set<Key<T>>, parameter: Any = (), cached: Bool? = nil) -> [T] {
let dependencies: [Dependency] = lock.read {
var dependencies = [Dependency]()
for (key, dependency) in registrations {
guard let key = Key<T>(key) else { continue }
if !keys.contains(key) { continue }
dependencies.append(dependency)
}
return dependencies
}
return dependencies.map{ $0.resolve(parameter: parameter, cached: cached) }
}
/**
Resolve multiple registrations at the same time.
- returns: A dictionary mapping each supplied `Key` to its resolved dependency of type `T`.
- parameters:
- keys: The keys to resolve.
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the resolution block again.
; - note: Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T>(keys: Set<Key<T>>, parameter: Any = (), cached: Bool? = nil) -> [Key<T>: T] {
let dependencies: Dictionary<Key<T>, Dependency> = lock.read {
var dependencies = Dictionary<Key<T>, Dependency>()
for (key, dependency) in registrations {
guard let key = Key<T>(key) else { continue }
if !keys.contains(key) { continue }
dependencies[key] = dependency
}
return dependencies
}
return dependencies.map{ (key: $0.key, value: $0.value.resolve(parameter: parameter, cached: cached)) }.dictionary()
}
/**
Resolve a dependency registered with the given key.
- returns: The resolved dependency or `nil` if it is not found.
- parameters:
- name: The name under which the block was registered.
- container: The container in which the block was registered.
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the block again.
Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T, N: Hashable, C: Hashable>(name: N, container: C, parameter: Any = (), cached: Bool? = nil) -> T? {
return resolve(key: Key(name: name, container: container), parameter: parameter, cached: cached)
}
/**
Resolve a dependency registered with the given type `T` and `name`.
- returns: The resolved dependency or `nil` if it is not found.
- parameters:
- name: The name under which the block was registered.
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the block again.
Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T, N: Hashable>(name: N, parameter: Any = (), cached: Bool? = nil) -> T? {
return resolve(key: Key(name: name, container: Name.default), parameter: parameter, cached: cached)
}
/**
Resolve a dependency registered with the given type `T` in the given `container`.
- returns: The resolved dependency or `nil` if it is not found.
- parameters:
- container: The container in which the block was registered.
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the block again.
Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T, C: Hashable>(container: C, parameter: Any = (), cached: Bool? = nil) -> T? {
return resolve(key: Key(name: Name.default, container: container), parameter: parameter, cached: cached)
}
/**
Resolve a registered dependency.
- returns: The resolved dependency or `nil` if it is not found.
- parameters:
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the block again.
Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T>(parameter: Any = (), cached: Bool? = nil) -> T? {
return resolve(key: Key(name: Name.default, container: Name.default), parameter: parameter, cached: cached)
}
// MARK: Key Filtering
/**
Provides a thunk between `Metafilter<M>` and `Metafilter<Any>`.
Checks to make sure that the metadata being checked actually is of type `M`.
*/
private static func metathunk<M>(_ metafilter: @escaping Metafilter<M>) -> Metathunk {
return {
guard let metadata = $0 as? M else { return false }
return metafilter(metadata)
}
}
/**
Most of the typed `filter` overloads end up here.
*/
private static func filter<T>(name: AnyHashable?, container: AnyHashable?, metathunk: Metathunk? = nil) -> Set<Key<T>> {
return lock.read {
var keys = Set<Key<T>>()
for (key, dependency) in registrations {
guard let key = Key<T>(key) else { continue }
if let name = name, name != key.name { continue }
if let container = container, container != key.container { continue }
if let metathunk = metathunk, !metathunk(dependency.metadata) { continue }
keys.insert(key)
}
return keys
}
}
/**
Most of the untyped `filter` overloads end up here.
*/
private static func filter(name: AnyHashable?, container: AnyHashable?, metathunk: Metathunk? = nil) -> Set<AnyKey> {
return lock.read {
var keys = Set<AnyKey>()
for (key, dependency) in registrations {
if let name = name, name != key.name { continue }
if let container = container, container != key.container { continue }
if let metathunk = metathunk, !metathunk(dependency.metadata) { continue }
keys.insert(key)
}
return keys
}
}
/**
Find the given key matching the metafilter query.
This method will always return either an empty set or a set with one element.
*/
public static func filter<T, M>(key: Key<T>, metafilter: @escaping Metafilter<M>) -> Set<Key<T>> {
guard let dependency = lock.read({ registrations[AnyKey(key)] }) else { return [] }
return metathunk(metafilter)(dependency.metadata) ? [key] : []
}
/**
Find the given key.
*/
public static func filter<T>(key: Key<T>) -> Set<Key<T>> {
return lock.read{ registrations[AnyKey(key)] == nil ? [] : [key] }
}
/**
Find all keys for the given type, name, and container, matching the given metadata filter.
Because all of type, name, and container are specified, this method will return either
an empty array or an array with a single value.
*/
public static func filter<T, N: Hashable, C: Hashable, M>(type: T.Type, name: N, container: C, metafilter: @escaping Metafilter<M>) -> Set<Key<T>> {
let key = Key<T>(name: name, container: container)
return filter(key: key, metafilter: metafilter)
}
/**
Find all keys for the given type, name, and container, having the specified metadata.
Because all of type, name, and container are specified, this method will return either
an empty array or an array with a single value.
*/
public static func filter<T, N: Hashable, C: Hashable, M: Equatable>(type: T.Type, name: N, container: C, metadata: M) -> Set<Key<T>> {
return filter(type: type, name: name, container: container) { $0 == metadata }
}
/**
Find all keys for the given type, name, and container.
Because all of type, name, and container are specified, this method will return either
an empty array or an array with a single value.
*/
public static func filter<T, N: Hashable, C: Hashable>(type: T.Type, name: N, container: C) -> Set<Key<T>> {
let key = Key<T>(name: name, container: container)
return filter(key: key)
}
/**
Find all keys for the given type and name, matching the given metadata filter.
*/
public static func filter<T, N: Hashable, M>(type: T.Type, name: N, metafilter: @escaping Metafilter<M>) -> Set<Key<T>> {
return filter(name: name, container: nil, metathunk: metathunk(metafilter))
}
/**
Find all keys for the given type and name, having the specified metadata.
*/
public static func filter<T, N: Hashable, M: Equatable>(type: T.Type, name: N, metadata: M) -> Set<Key<T>> {
return filter(type: type, name: name) { $0 == metadata }
}
/**
Find all keys for the given type and name.
*/
public static func filter<T, N: Hashable>(type: T.Type, name: N) -> Set<Key<T>> {
return filter(name: name, container: nil)
}
/**
Find all keys for the given type and container, matching the given metadata filter.
*/
public static func filter<T, C: Hashable, M>(type: T.Type, container: C, metafilter: @escaping Metafilter<M>) -> Set<Key<T>> {
return filter(name: nil, container: container, metathunk: metathunk(metafilter))
}
/**
Find all keys for the given type and container, having the specified metadata.
*/
public static func filter<T, C: Hashable, M: Equatable>(type: T.Type, container: C, metadata: M) -> Set<Key<T>> {
return filter(type: type, container: container) { $0 == metadata }
}
/**
Find all keys for the given type and container, independent of name.
*/
public static func filter<T, C: Hashable>(type: T.Type, container: C) -> Set<Key<T>> {
return filter(name: nil, container: container)
}
/**
Find all keys for the given name and container, independent of type.
*/
public static func filter<N: Hashable, C: Hashable, M>(name: N, container: C, metafilter: @escaping Metafilter<M>) -> Set<AnyKey> {
return filter(name: name, container: container, metafilter: metathunk(metafilter))
}
public static func filter<N: Hashable, C: Hashable, M: Equatable>(name: N, container: C, metadata: M) -> Set<AnyKey> {
return filter(name: name, container: container) { $0 == metadata }
}
/**
Find all keys for the given name and container, independent of type.
*/
public static func filter<N: Hashable, C: Hashable>(name: N, container: C) -> Set<AnyKey> {
return filter(name: name, container: container)
}
/**
Find all keys for the given name, independent of the given type and container.
*/
public static func filter<N: Hashable, M>(name: N, metafilter: @escaping Metafilter<M>) -> Set<AnyKey> {
return filter(name: name, container: nil, metathunk: metathunk(metafilter))
}
public static func filter<N: Hashable, M: Equatable>(name: N, metadata: M) -> Set<AnyKey> {
return filter(name: name) { $0 == metadata }
}
/**
Find all keys for the given name, independent of the given type and container.
*/
public static func filter<N: Hashable>(name: N) -> Set<AnyKey> {
return filter(name: name, container: nil)
}
/**
Find all keys for the given container, independent of given type and name.
*/
public static func filter<C: Hashable, M>(container: C, metafilter: @escaping Metafilter<M>) -> Set<AnyKey> {
return filter(name: nil, container: container, metathunk: metathunk(metafilter))
}
public static func filter<C: Hashable, M: Equatable>(container: C, metadata: M) -> Set<AnyKey> {
return filter(container: container) { $0 == metadata }
}
/**
Find all keys for the given container, independent of type and name.
*/
public static func filter<C: Hashable>(container: C) -> Set<AnyKey> {
return filter(name: nil, container: container)
}
/**
Find all keys for the given type, independent of name and container.
*/
public static func filter<T, M>(type: T.Type, metafilter: @escaping Metafilter<M>) -> Set<Key<T>> {
return filter(name: nil, container: nil, metathunk: metathunk(metafilter))
}
public static func filter<T, M: Equatable>(type: T.Type, metadata: M) -> Set<Key<T>> {
return filter(type: type) { $0 == metadata }
}
/**
Find all keys for the given type, independent of name and container.
*/
public static func filter<T>(type: T.Type) -> Set<Key<T>> {
return filter(name: nil, container: nil)
}
/**
Find all keys with registrations matching the metafilter query.
*/
public static func filter<M>(metafilter: @escaping Metafilter<M>) -> Set<AnyKey> {
return filter(name: nil, container: nil, metathunk: metathunk(metafilter))
}
public static func filter<M: Equatable>(metadata: M) -> Set<AnyKey> {
return filter{ $0 == metadata }
}
// MARK: Key Presence
/**
Helper method for filtering.
*/
private static func exists(type: String?, name: AnyHashable?, container: AnyHashable?, metathunk: Metathunk? = nil) -> Bool {
return lock.read {
for (key, dependency) in registrations {
if let type = type, type != key.type { continue }
if let name = name, name != key.name { continue }
if let container = container, container != key.container { continue }
if let methathunk = metathunk, !methathunk(dependency.metadata) { continue }
return true
}
return false
}
}
/**
Returns true if a registration exists for `key` and matching the `metafilter` query.
*/
public static func exists<M>(key: Keyed, metafilter: @escaping Metafilter<M>) -> Bool {
guard let dependency = lock.read({ registrations[AnyKey(key)] }) else { return false }
return metathunk(metafilter)(dependency.metadata)
}
public static func exists<M: Equatable>(key: Keyed, metadata: M) -> Bool {
return exists(key: key) { $0 == metadata }
}
/**
Returns true if a registration exists for the given key.
*/
public static func exists(key: Keyed) -> Bool {
return lock.read { return registrations[AnyKey(key)] != nil }
}
/**
Returns true if a key with the given type, name, and container exists.
*/
public static func exists<T, N: Hashable, C: Hashable, M>(type: T.Type, name: N, container: C, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(key: Key<T>(name: name, container: container), metafilter: metathunk(metafilter))
}
public static func exists<T, N: Hashable, C: Hashable, M: Equatable>(type: T.Type, name: N, container: C, metadata: M) -> Bool {
return exists(key: Key<T>(name: name, container: container)) { $0 == metadata }
}
/**
Returns true if a key with the given type, name, and container exists.
*/
public static func exists<T, N: Hashable, C: Hashable>(type: T.Type, name: N, container: C) -> Bool {
return exists(key: AnyKey(type: type, name: name, container: container))
}
/**
Returns true if any keys with the given type and name exist in any containers.
*/
public static func exists<T, N: Hashable, M>(type: T.Type, name: N, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: String(reflecting: type), name: name, container: nil, metathunk: metathunk(metafilter))
}
public static func exists<T, N: Hashable, M: Equatable>(type: T.Type, name: N, metadata: M) -> Bool {
return exists(type: type, name: name) { $0 == metadata }
}
/**
Returns true if any keys with the given type and name exist in any containers.
*/
public static func exists<T, N: Hashable>(type: T.Type, name: N) -> Bool {
return exists(type: String(reflecting: type), name: name, container: nil)
}
/**
Returns true if any keys with the given type exist in the given container, independent of name.
*/
public static func exists<T, C: Hashable, M>(type: T.Type, container: C, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: String(reflecting: type), name: nil, container: container, metathunk: metathunk(metafilter))
}
public static func exists<T, C: Hashable, M: Equatable>(type: T.Type, container: C, metadata: M) -> Bool {
return exists(type: type, container: container) { $0 == metadata }
}
/**
Returns true if any keys with the given type exist in the given container, independent of name.
*/
public static func exists<T, C: Hashable>(type: T.Type, container: C) -> Bool {
return exists(type: String(reflecting: type), name: nil, container: container)
}
/**
Returns true if any keys with the given name exist in the given container, independent of type.
*/
public static func exists<N: Hashable, C: Hashable, M>(name: N, container: C, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: nil, name: name, container: container, metathunk: metathunk(metafilter))
}
public static func exists<N: Hashable, C: Hashable, M: Equatable>(name: N, container: C, metadata: M) -> Bool {
return exists(name: name, container: container) { $0 == metadata }
}
/**
Returns true if any keys with the given name exist in the given container, independent of type.
*/
public static func exists<N: Hashable, C: Hashable>(name: N, container: C) -> Bool {
return exists(type: nil, name: name, container: container)
}
/**
Return true if any keys with the given name exist in any container, independent of type.
*/
public static func exists<N: Hashable, M>(name: N, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: nil, name: name, container: nil, metathunk: metathunk(metafilter))
}
public static func exists<N: Hashable, M: Equatable>(name: N, metadata: M) -> Bool {
return exists(name: name) { $0 == metadata }
}
/**
Returns true if any registrations exist under the given name.
*/
public static func exists<N: Hashable>(name: N) -> Bool {
return exists(type: nil, name: name, container: nil)
}
/**
Returns true if there are any keys registered in the given container, matching the given metafilter query.
*/
public static func exists<C: Hashable, M>(container: C, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: nil, name: nil, container: container, metathunk: metathunk(metafilter))
}
public static func exists<C: Hashable, M: Equatable>(container: C, metadata: M) -> Bool {
return exists(container: container) { $0 == metadata }
}
/**
Returns true if there are any keys registered in the given container.
*/
public static func exists<C: Hashable>(container: C) -> Bool {
return exists(type: nil, name: nil, container: container)
}
/**
Returns true if there are any keys registered with the given type and matching the metafilter query in any container, independent of name.
*/
public static func exists<T, M>(type: T.Type, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: String(reflecting: type), name: nil, container: nil, metathunk: metathunk(metafilter))
}
public static func exists<T, M: Equatable>(type: T.Type, metadata: M) -> Bool {
return exists(type: type) { $0 == metadata }
}
/**
Returns true if there are any keys registered with the given type in any container, independent of name.
*/
public static func exists<T>(type: T.Type) -> Bool {
return exists(type: String(reflecting: type), name: nil, container: nil)
}
/**
Returns true if any registrations exist matching the given metafilter, regardless of type, name, or container.
*/
public static func exists<M>(metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: nil, name: nil, container: nil, metathunk: metathunk(metafilter))
}
public static func exists<M: Equatable>(metadata: M) -> Bool {
return exists{ $0 == metadata }
}
// MARK: Metadata
/**
Retrieve metadata for the dependency registered under `key`.
*/
public static func metadata<M>(for key: Keyed) -> M? {
guard let dependency = lock.read({ registrations[AnyKey(key)] }) else { return nil }
guard let metadata = dependency.metadata as? M else { return nil }
return metadata
}
/**
Retrieve metadata for multiple keys.
*/
public static func metadata<M>(for keys: Set<AnyKey>) -> [AnyKey: M] {
return lock.read {
var metadatas = [AnyKey: M]()
for (key, dependency) in registrations {
if !keys.contains(key) { continue }
guard let metadata = dependency.metadata as? M else { continue }
metadatas[key] = metadata
}
return metadatas
}
}
/**
Retrieve metadata for multiple keys.
*/
public static func metadata<T, M>(for keys: Set<Key<T>>) -> [Key<T>: M] {
return lock.read {
var metadatas = Dictionary<Key<T>, M>()
for (key, dependency) in registrations {
guard let key = Key<T>(key) else { continue }
if !keys.contains(key) { continue }
guard let metadata = dependency.metadata as? M else { continue }
metadatas[key] = metadata
}
return metadatas
}
}
// MARK: Unregistration
/**
Remove the dependencies registered under the given key(s).
*/
public static func unregister(key: AnyKey...) {
unregister(keys: key.untypedKeys())
}
/**
Remove the dependencies registered under the given key(s).
*/
public static func unregister<T>(key: Key<T>...) {
unregister(keys: key.untypedKeys())
}
/**
Remove the dependencies registered under the given keys.
*/
public static func unregister(keys: Set<AnyKey>) {
lock.write { registrations = registrations.filter{ !keys.contains($0.key) }.dictionary() }
}
/**
Remove the dependencies registered under the given keys.
*/
public static func unregister<T>(keys: Set<Key<T>>) {
unregister(keys: keys.untypedKeys())
}
public static func unregister<T>(type: T.Type) {
unregister(keys: Guise.filter(type: type))
}
public static func unregister<C: Hashable>(container: C) {
unregister(keys: Guise.filter(container: container))
}
public static func unregister<T, C: Hashable>(type: T.Type, container: C) {
unregister(keys: Guise.filter(type: type, container: container))
}
/**
Remove all dependencies. Reset Guise completely.
*/
public static func clear() {
lock.write { registrations = [:] }
}
}
// MARK: -
/**
A simple non-reentrant lock allowing one writer and multiple readers.
*/
private class Lock {
private let lock: UnsafeMutablePointer<pthread_rwlock_t> = {
var lock = UnsafeMutablePointer<pthread_rwlock_t>.allocate(capacity: 1)
let status = pthread_rwlock_init(lock, nil)
assert(status == 0)
return lock
}()
private func lock<T>(_ acquire: (UnsafeMutablePointer<pthread_rwlock_t>) -> Int32, block: () -> T) -> T {
let _ = acquire(lock)
defer { pthread_rwlock_unlock(lock) }
return block()
}
func read<T>(_ block: () -> T) -> T {
return lock(pthread_rwlock_rdlock, block: block)
}
func write<T>(_ block: () -> T) -> T {
return lock(pthread_rwlock_wrlock, block: block)
}
deinit {
pthread_rwlock_destroy(lock)
}
}
// MARK: - Extensions
extension Array {
/**
Reconstruct a dictionary after it's been reduced to an array of key-value pairs by `filter` and the like.
```
var dictionary = [1: "ok", 2: "crazy", 99: "abnormal"]
dictionary = dictionary.filter{ $0.value == "ok" }.dictionary()
```
*/
func dictionary<K: Hashable, V>() -> [K: V] where Element == Dictionary<K, V>.Element {
var dictionary = [K: V]()
for element in self {
dictionary[element.key] = element.value
}
return dictionary
}
}
extension Sequence where Iterator.Element: Keyed {
/**
Returns a set up of typed `Key<T>`.
Any of the underlying keys whose type is not `T`
will simply be omitted, so this is also a way
to filter a sequence of keys by type.
*/
public func typedKeys<T>() -> Set<Key<T>> {
return Set<Key<T>>(flatMap{ Key($0) })
}
/**
Returns a set of untyped `AnyKey`.
This is a convenient way to turn a set of typed
keys into a set of untyped keys.
*/
public func untypedKeys() -> Set<AnyKey> {
return Set(map{ AnyKey($0) })
}
}
/**
This typealias exists to disambiguate Guise's `Key<T>`
from the `Key` generic type parameter in `Dictionary`.
It is exactly equivalent to `Key<T>` and can be safely
ignored.
*/
public typealias GuiseKey<T> = Key<T>
extension Dictionary where Key: Keyed {
/**
Returns a dictionary in which the keys hold the type `T`.
Any key which does not hold `T` is simply skipped, along with
its corresponding value, so this is also a way to filter
a sequence of keys by type.
*/
public func typedKeys<T>() -> Dictionary<GuiseKey<T>, Value> {
return flatMap {
guard let key = GuiseKey<T>($0.key) else { return nil }
return (key: key, value: $0.value)
}.dictionary()
}
/**
Returns a dictionary in which the keys are `AnyKey`.
This is a convenient way to turn a dictionary with typed keys
into a dictionary with type-erased keys.
*/
public func untypedKeys() -> Dictionary<AnyKey, Value> {
return map{ (key: AnyKey($0.key), value: $0.value) }.dictionary()
}
}
// Miscellanea: -
/**
Generates a hash value for one or more hashable values.
*/
private func hash<H: Hashable>(_ hashables: H...) -> Int {
// djb2 hash algorithm: http://www.cse.yorku.ca/~oz/hash.html
// &+ operator handles Int overflow
return hashables.reduce(5381) { (result, hashable) in ((result << 5) &+ result) &+ hashable.hashValue }
}
infix operator ??= : AssignmentPrecedence
private func ??=<T>(lhs: inout T?, rhs: @autoclosure () -> T?) {
if lhs != nil { return }
lhs = rhs()
}
Documented `unregister` overloads.
/*
The MIT License (MIT)
Copyright (c) 2016 - 2017 Gregory Higley (Prosumma)
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
// MARK: -
/**
`Name.default` is used for the default name of a container or type when one is not specified.
*/
public enum Name {
/**
`Name.default` is used for the default name of a container or type when one is not specified.
*/
case `default`
}
// MARK: - Keys
/**
The protocol shared by `Key<T>` and `AnyKey`.
Registration in Guise associates a unique `Keyed` with
a dependency. Any registration using the same `Keyed`
overwrites any previous registration.
A `Keyed` consists of a `type`, `name`, and `container`.
The only truly required attribute is `type`. While the
others cannot be `nil`, they can be defaulted to `Name.default`.
Any `Hashable` value can be used for `name` and `container`.
All three of these attributes together are what make a `Keyed`
unique.
*/
public protocol Keyed {
/**
The fully qualified name of a type produced by `String(reflecting: type)`.
*/
var type: String { get }
/**
The name of a registration. Defaults to `Name.default`.
Names can be used to disambiguate registrations of the same type.
*/
var name: AnyHashable { get }
/**
The container of a registration. Defaults to `Name.default`.
A container may be used to group registrations together for
any purpose. One common use is to quickly _unregister_ many
registrations at once:
```
Guise.unregister(container: Container.plugins)
```
*/
var container: AnyHashable { get }
}
public protocol EquatableKeyed: Keyed, Hashable, Equatable {
}
public func ==<K: EquatableKeyed>(lhs: K, rhs: K) -> Bool {
if lhs.hashValue != rhs.hashValue { return false }
if lhs.type != rhs.type { return false }
if lhs.name != rhs.name { return false }
if lhs.container != rhs.container { return false }
return true
}
/**
A type-erasing unique key under which to register a block in Guise.
This type is used primarily when keys must be stored heterogeneously,
e.g., in `Set<AnyKey>` returned from a `filter` overload.
This is also the type that Guise uses under the hood to associate
keys with registered dependencies.
*/
public struct AnyKey: EquatableKeyed {
public let type: String
public let name: AnyHashable
public let container: AnyHashable
public let hashValue: Int
public init(_ key: Keyed) {
self.type = key.type
self.name = key.name
self.container = key.container
self.hashValue = hash(self.type, self.name, self.container)
}
public init<T, N: Hashable, C: Hashable>(type: T.Type, name: N, container: C) {
self.type = String(reflecting: T.self)
self.name = name
self.container = container
self.hashValue = hash(self.type, self.name, self.container)
}
public init<T, N: Hashable>(type: T.Type, name: N) {
self.init(type: type, name: name, container: Name.default)
}
public init<T, C: Hashable>(type: T.Type, container: C) {
self.init(type: type, name: Name.default, container: container)
}
public init<T>(type: T.Type) {
self.init(type: type, name: Name.default, container: Name.default)
}
}
/**
A type-safe registration key.
This type is used wherever type-safety is needed or
wherever keys are requested by type.
*/
public struct Key<T>: EquatableKeyed {
public let type: String
public let name: AnyHashable
public let container: AnyHashable
public let hashValue: Int
public init<N: Hashable, C: Hashable>(name: N, container: C) {
self.type = String(reflecting: T.self)
self.name = name
self.container = container
self.hashValue = hash(self.type, self.name, self.container)
}
public init<N: Hashable>(name: N) {
self.init(name: name, container: Name.default)
}
public init<C: Hashable>(container: C) {
self.init(name: Name.default, container: container)
}
public init() {
self.init(name: Name.default, container: Name.default)
}
public init?(_ key: Keyed) {
if key.type != String(reflecting: T.self) { return nil }
self.type = key.type
self.name = key.name
self.container = key.container
self.hashValue = hash(self.type, self.name, self.container)
}
}
// MARK: -
/**
This class creates and holds a type-erasing thunk over a registration block.
Guise creates a mapping between a `Keyed` and a `Dependency`. `Keyed` holds
the `type`, `name`, and `container`, while `Dependency` holds the resolution
block, metadata, caching preference, and any cached instance.
*/
private class Dependency {
/** Default lifecycle for the dependency. */
let cached: Bool
/** Registered block. */
private let resolution: (Any) -> Any
/** Cached instance, if any. */
private var instance: Any?
/** Metadata */
let metadata: Any
init<P, T>(metadata: Any, cached: Bool, resolution: @escaping Resolution<P, T>) {
self.metadata = metadata
self.cached = cached
self.resolution = { param in resolution(param as! P) }
}
func resolve<T>(parameter: Any, cached: Bool?) -> T {
var result: T
if cached ?? self.cached {
if instance == nil {
instance = resolution(parameter)
}
result = instance! as! T
} else {
result = resolution(parameter) as! T
}
return result
}
}
// MARK: -
/**
The type of a resolution block.
These are what actually get registered. Guise does not register
types or instances directly.
*/
public typealias Resolution<P, T> = (P) -> T
/**
The type of a metadata filter.
*/
public typealias Metafilter<M> = (M) -> Bool
/**
Used in filters.
This type exists primarily to emphasize that the `metathunk` method should be applied to
`Metafilter<M>` before the metafilter is passed to the master `filter` or `exists` method.
*/
private typealias Metathunk = Metafilter<Any>
/**
Guise is a simple dependency resolution framework.
Guise does not register types or instances directly. Instead,
it registers a resolution block which returns the needed dependency.
Guise manages a thread-safe dictionary mapping keys to resolution
blocks.
The key with which each dependency is associated consists of the
return type of the resolution block, a `Hashable` name, and a `Hashable`
container. The name and container default to `Name.default`, so
they do not need to be specified unless required.
In addition, it is common to alias the return type of the resolution
block using a protocol to achieve abstraction.
This simple, flexible system can accommodate many scenarios. Some of
these scenarios are so common that overloads exist to handle them
concisely.
- note: Instances of this type cannot be created. Use its static methods.
*/
public struct Guise {
private init() {}
private static var lock = Lock()
private static var registrations = [AnyKey: Dependency]()
/**
All keys.
*/
public static var keys: Set<AnyKey> {
return lock.read { Set(registrations.keys) }
}
// MARK: Registration
/**
Register the `resolution` block with the result type `T` and the parameter `P`.
- returns: The `key` that was passed in.
- parameters:
- key: The `Key` under which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- cached: Whether or not to cache the result of the registration block.
- resolution: The block to register with Guise.
*/
public static func register<P, T>(key: Key<T>, metadata: Any = (), cached: Bool = false, resolution: @escaping Resolution<P, T>) -> Key<T> {
lock.write { registrations[AnyKey(key)] = Dependency(metadata: metadata, cached: cached, resolution: resolution) }
return key
}
/**
Multiply register the `resolution` block with the result type `T` and the parameter `P`.
- returns: The passed-in `keys`.
- parameters:
- key: The `Key` under which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- cached: Whether or not to cache the result of the registration block.
- resolution: The block to register with Guise.
*/
public static func register<P, T>(keys: Set<Key<T>>, metadata: Any = (), cached: Bool = false, resolution: @escaping Resolution<P, T>) -> Set<Key<T>> {
return lock.write {
for key in keys {
registrations[AnyKey(key)] = Dependency(metadata: metadata, cached: cached, resolution: resolution)
}
return keys
}
}
/**
Register the `resolution` block with the result type `T` and the parameter `P`.
- returns: The unique `Key<T>` for this registration.
- parameters:
- name: The name under which to register the block.
- container: The container in which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- cached: Whether or not to cache the result of the registration block after first use.
- resolution: The block to register with Guise.
*/
public static func register<P, T, N: Hashable, C: Hashable>(name: N, container: C, metadata: Any = (), cached: Bool = false, resolution: @escaping Resolution<P, T>) -> Key<T> {
return register(key: Key(name: name, container: container), metadata: metadata, cached: cached, resolution: resolution)
}
/**
Register the `resolution` block with the result type `T` and the parameter `P`.
- returns: The unique `Key<T>` for this registration.
- parameters:
- name: The name under which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- cached: Whether or not to cache the result of the registration block.
- resolution: The block to register with Guise.
- note: The registration is made in the default container, `Name.default`.
*/
public static func register<P, T, N: Hashable>(name: N, metadata: Any = (), cached: Bool = false, resolution: @escaping Resolution<P, T>) -> Key<T> {
return register(key: Key(name: name, container: Name.default), metadata: metadata, cached: cached, resolution: resolution)
}
/**
Register the `resolution` block with the result type `T` and the parameter `P`.
- returns: The unique `Key<T>` for this registration.
- parameters:
- container: The container in which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- cached: Whether or not to cache the result of the registration block.
- resolution: The block to register with Guise.
- note: The registration is made with the default name, `Name.default`.
*/
public static func register<P, T, C: Hashable>(container: C, metadata: Any = (), cached: Bool = false, resolution: @escaping Resolution<P, T>) -> Key<T> {
return register(key: Key(name: Name.default, container: container), metadata: metadata, cached: cached, resolution: resolution)
}
/**
Register the `resolution` block with the result type `T` and the parameter `P`.
- returns: The unique `Key<T>` for this registration.
- parameters:
- metadata: Arbitrary metadata associated with this registration.
- cached: Whether or not to cache the result of the registration block.
- resolution: The block to register with Guise.
- note: The registration is made in the default container, `Name.default` and under the default name, `Name.default`.
*/
public static func register<P, T>(metadata: Any = (), cached: Bool = false, resolution: @escaping Resolution<P, T>) -> Key<T> {
return register(key: Key(name: Name.default, container: Name.default), metadata: metadata, cached: cached, resolution: resolution)
}
/**
Register an instance.
- returns: The unique `Key<T>` for this registration.
- parameters:
- instance: The instance to register.
- name: The name under which to register the block.
- container: The container in which to register the block.
- metadata: Arbitrary metadata associated with this registration.
*/
public static func register<T, N: Hashable, C: Hashable>(instance: T, name: N, container: C, metadata: Any = ()) -> Key<T> {
return register(key: Key(name: name, container: container), metadata: metadata, cached: true) { instance }
}
/**
Register an instance.
- returns: The unique `Key<T>` for this registration.
- parameters:
- instance: The instance to register.
- name: The name under which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- note: The registration is made in the default container, `Name.default`.
*/
public static func register<T, N: Hashable>(instance: T, name: N, metadata: Any = ()) -> Key<T> {
return register(key: Key(name: name, container: Name.default), metadata: metadata, cached: true) { instance }
}
/**
Register an instance.
- returns: The unique `Key<T>` for this registration.
- parameters:
- instance: The instance to register.
- container: The container in which to register the block.
- metadata: Arbitrary metadata associated with this registration.
- note: The registration is made with the default name, `Name.default`.
*/
public static func register<T, C: Hashable>(instance: T, container: C, metadata: Any = ()) -> Key<T> {
return register(key: Key(name: Name.default, container: container), metadata: metadata, cached: true) { instance }
}
/**
Register an instance.
- returns: The unique `Key<T>` for this registration.
- parameters:
- instance: The instance to register.
- metadata: Arbitrary metadata associated with this registration.
- note: The registration is made with the default name, `Name.default`, and in the default container, `Name.default`.
*/
public static func register<T>(instance: T, metadata: Any = ()) -> Key<T> {
return register(key: Key(name: Name.default, container: Name.default), metadata: metadata, cached: true) { instance }
}
// MARK: Resolution
/**
Resolve a dependency registered with `key`.
- returns: The resolved dependency or `nil` if it is not found.
- parameters:
- key: The key to resolve.
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the block again.
- note: Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T>(key: Key<T>, parameter: Any = (), cached: Bool? = nil) -> T? {
guard let dependency = lock.read({ registrations[AnyKey(key)] }) else { return nil }
return dependency.resolve(parameter: parameter, cached: cached)
}
/**
Resolve multiple registrations at the same time.
- returns: An array of the resolved dependencies.
- parameters:
- keys: The keys to resolve.
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the resolution block again.
- note: Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T>(keys: Set<Key<T>>, parameter: Any = (), cached: Bool? = nil) -> [T] {
let dependencies: [Dependency] = lock.read {
var dependencies = [Dependency]()
for (key, dependency) in registrations {
guard let key = Key<T>(key) else { continue }
if !keys.contains(key) { continue }
dependencies.append(dependency)
}
return dependencies
}
return dependencies.map{ $0.resolve(parameter: parameter, cached: cached) }
}
/**
Resolve multiple registrations at the same time.
- returns: A dictionary mapping each supplied `Key` to its resolved dependency of type `T`.
- parameters:
- keys: The keys to resolve.
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the resolution block again.
; - note: Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T>(keys: Set<Key<T>>, parameter: Any = (), cached: Bool? = nil) -> [Key<T>: T] {
let dependencies: Dictionary<Key<T>, Dependency> = lock.read {
var dependencies = Dictionary<Key<T>, Dependency>()
for (key, dependency) in registrations {
guard let key = Key<T>(key) else { continue }
if !keys.contains(key) { continue }
dependencies[key] = dependency
}
return dependencies
}
return dependencies.map{ (key: $0.key, value: $0.value.resolve(parameter: parameter, cached: cached)) }.dictionary()
}
/**
Resolve a dependency registered with the given key.
- returns: The resolved dependency or `nil` if it is not found.
- parameters:
- name: The name under which the block was registered.
- container: The container in which the block was registered.
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the block again.
Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T, N: Hashable, C: Hashable>(name: N, container: C, parameter: Any = (), cached: Bool? = nil) -> T? {
return resolve(key: Key(name: name, container: container), parameter: parameter, cached: cached)
}
/**
Resolve a dependency registered with the given type `T` and `name`.
- returns: The resolved dependency or `nil` if it is not found.
- parameters:
- name: The name under which the block was registered.
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the block again.
Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T, N: Hashable>(name: N, parameter: Any = (), cached: Bool? = nil) -> T? {
return resolve(key: Key(name: name, container: Name.default), parameter: parameter, cached: cached)
}
/**
Resolve a dependency registered with the given type `T` in the given `container`.
- returns: The resolved dependency or `nil` if it is not found.
- parameters:
- container: The container in which the block was registered.
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the block again.
Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T, C: Hashable>(container: C, parameter: Any = (), cached: Bool? = nil) -> T? {
return resolve(key: Key(name: Name.default, container: container), parameter: parameter, cached: cached)
}
/**
Resolve a registered dependency.
- returns: The resolved dependency or `nil` if it is not found.
- parameters:
- parameter: A parameter to pass to the resolution block.
- cached: Whether to use the cached value or to call the block again.
Passing `nil` for the `cached` parameter causes Guise to use the value of `cached` recorded
when the dependency was registered. In most cases, this is what you want.
*/
public static func resolve<T>(parameter: Any = (), cached: Bool? = nil) -> T? {
return resolve(key: Key(name: Name.default, container: Name.default), parameter: parameter, cached: cached)
}
// MARK: Key Filtering
/**
Provides a thunk between `Metafilter<M>` and `Metafilter<Any>`.
Checks to make sure that the metadata being checked actually is of type `M`.
*/
private static func metathunk<M>(_ metafilter: @escaping Metafilter<M>) -> Metathunk {
return {
guard let metadata = $0 as? M else { return false }
return metafilter(metadata)
}
}
/**
Most of the typed `filter` overloads end up here.
*/
private static func filter<T>(name: AnyHashable?, container: AnyHashable?, metathunk: Metathunk? = nil) -> Set<Key<T>> {
return lock.read {
var keys = Set<Key<T>>()
for (key, dependency) in registrations {
guard let key = Key<T>(key) else { continue }
if let name = name, name != key.name { continue }
if let container = container, container != key.container { continue }
if let metathunk = metathunk, !metathunk(dependency.metadata) { continue }
keys.insert(key)
}
return keys
}
}
/**
Most of the untyped `filter` overloads end up here.
*/
private static func filter(name: AnyHashable?, container: AnyHashable?, metathunk: Metathunk? = nil) -> Set<AnyKey> {
return lock.read {
var keys = Set<AnyKey>()
for (key, dependency) in registrations {
if let name = name, name != key.name { continue }
if let container = container, container != key.container { continue }
if let metathunk = metathunk, !metathunk(dependency.metadata) { continue }
keys.insert(key)
}
return keys
}
}
/**
Find the given key matching the metafilter query.
This method will always return either an empty set or a set with one element.
*/
public static func filter<T, M>(key: Key<T>, metafilter: @escaping Metafilter<M>) -> Set<Key<T>> {
guard let dependency = lock.read({ registrations[AnyKey(key)] }) else { return [] }
return metathunk(metafilter)(dependency.metadata) ? [key] : []
}
/**
Find the given key.
*/
public static func filter<T>(key: Key<T>) -> Set<Key<T>> {
return lock.read{ registrations[AnyKey(key)] == nil ? [] : [key] }
}
/**
Find all keys for the given type, name, and container, matching the given metadata filter.
Because all of type, name, and container are specified, this method will return either
an empty array or an array with a single value.
*/
public static func filter<T, N: Hashable, C: Hashable, M>(type: T.Type, name: N, container: C, metafilter: @escaping Metafilter<M>) -> Set<Key<T>> {
let key = Key<T>(name: name, container: container)
return filter(key: key, metafilter: metafilter)
}
/**
Find all keys for the given type, name, and container, having the specified metadata.
Because all of type, name, and container are specified, this method will return either
an empty array or an array with a single value.
*/
public static func filter<T, N: Hashable, C: Hashable, M: Equatable>(type: T.Type, name: N, container: C, metadata: M) -> Set<Key<T>> {
return filter(type: type, name: name, container: container) { $0 == metadata }
}
/**
Find all keys for the given type, name, and container.
Because all of type, name, and container are specified, this method will return either
an empty array or an array with a single value.
*/
public static func filter<T, N: Hashable, C: Hashable>(type: T.Type, name: N, container: C) -> Set<Key<T>> {
let key = Key<T>(name: name, container: container)
return filter(key: key)
}
/**
Find all keys for the given type and name, matching the given metadata filter.
*/
public static func filter<T, N: Hashable, M>(type: T.Type, name: N, metafilter: @escaping Metafilter<M>) -> Set<Key<T>> {
return filter(name: name, container: nil, metathunk: metathunk(metafilter))
}
/**
Find all keys for the given type and name, having the specified metadata.
*/
public static func filter<T, N: Hashable, M: Equatable>(type: T.Type, name: N, metadata: M) -> Set<Key<T>> {
return filter(type: type, name: name) { $0 == metadata }
}
/**
Find all keys for the given type and name.
*/
public static func filter<T, N: Hashable>(type: T.Type, name: N) -> Set<Key<T>> {
return filter(name: name, container: nil)
}
/**
Find all keys for the given type and container, matching the given metadata filter.
*/
public static func filter<T, C: Hashable, M>(type: T.Type, container: C, metafilter: @escaping Metafilter<M>) -> Set<Key<T>> {
return filter(name: nil, container: container, metathunk: metathunk(metafilter))
}
/**
Find all keys for the given type and container, having the specified metadata.
*/
public static func filter<T, C: Hashable, M: Equatable>(type: T.Type, container: C, metadata: M) -> Set<Key<T>> {
return filter(type: type, container: container) { $0 == metadata }
}
/**
Find all keys for the given type and container, independent of name.
*/
public static func filter<T, C: Hashable>(type: T.Type, container: C) -> Set<Key<T>> {
return filter(name: nil, container: container)
}
/**
Find all keys for the given name and container, independent of type.
*/
public static func filter<N: Hashable, C: Hashable, M>(name: N, container: C, metafilter: @escaping Metafilter<M>) -> Set<AnyKey> {
return filter(name: name, container: container, metafilter: metathunk(metafilter))
}
public static func filter<N: Hashable, C: Hashable, M: Equatable>(name: N, container: C, metadata: M) -> Set<AnyKey> {
return filter(name: name, container: container) { $0 == metadata }
}
/**
Find all keys for the given name and container, independent of type.
*/
public static func filter<N: Hashable, C: Hashable>(name: N, container: C) -> Set<AnyKey> {
return filter(name: name, container: container)
}
/**
Find all keys for the given name, independent of the given type and container.
*/
public static func filter<N: Hashable, M>(name: N, metafilter: @escaping Metafilter<M>) -> Set<AnyKey> {
return filter(name: name, container: nil, metathunk: metathunk(metafilter))
}
public static func filter<N: Hashable, M: Equatable>(name: N, metadata: M) -> Set<AnyKey> {
return filter(name: name) { $0 == metadata }
}
/**
Find all keys for the given name, independent of the given type and container.
*/
public static func filter<N: Hashable>(name: N) -> Set<AnyKey> {
return filter(name: name, container: nil)
}
/**
Find all keys for the given container, independent of given type and name.
*/
public static func filter<C: Hashable, M>(container: C, metafilter: @escaping Metafilter<M>) -> Set<AnyKey> {
return filter(name: nil, container: container, metathunk: metathunk(metafilter))
}
public static func filter<C: Hashable, M: Equatable>(container: C, metadata: M) -> Set<AnyKey> {
return filter(container: container) { $0 == metadata }
}
/**
Find all keys for the given container, independent of type and name.
*/
public static func filter<C: Hashable>(container: C) -> Set<AnyKey> {
return filter(name: nil, container: container)
}
/**
Find all keys for the given type, independent of name and container.
*/
public static func filter<T, M>(type: T.Type, metafilter: @escaping Metafilter<M>) -> Set<Key<T>> {
return filter(name: nil, container: nil, metathunk: metathunk(metafilter))
}
public static func filter<T, M: Equatable>(type: T.Type, metadata: M) -> Set<Key<T>> {
return filter(type: type) { $0 == metadata }
}
/**
Find all keys for the given type, independent of name and container.
*/
public static func filter<T>(type: T.Type) -> Set<Key<T>> {
return filter(name: nil, container: nil)
}
/**
Find all keys with registrations matching the metafilter query.
*/
public static func filter<M>(metafilter: @escaping Metafilter<M>) -> Set<AnyKey> {
return filter(name: nil, container: nil, metathunk: metathunk(metafilter))
}
public static func filter<M: Equatable>(metadata: M) -> Set<AnyKey> {
return filter{ $0 == metadata }
}
// MARK: Key Presence
/**
Helper method for filtering.
*/
private static func exists(type: String?, name: AnyHashable?, container: AnyHashable?, metathunk: Metathunk? = nil) -> Bool {
return lock.read {
for (key, dependency) in registrations {
if let type = type, type != key.type { continue }
if let name = name, name != key.name { continue }
if let container = container, container != key.container { continue }
if let methathunk = metathunk, !methathunk(dependency.metadata) { continue }
return true
}
return false
}
}
/**
Returns true if a registration exists for `key` and matching the `metafilter` query.
*/
public static func exists<M>(key: Keyed, metafilter: @escaping Metafilter<M>) -> Bool {
guard let dependency = lock.read({ registrations[AnyKey(key)] }) else { return false }
return metathunk(metafilter)(dependency.metadata)
}
public static func exists<M: Equatable>(key: Keyed, metadata: M) -> Bool {
return exists(key: key) { $0 == metadata }
}
/**
Returns true if a registration exists for the given key.
*/
public static func exists(key: Keyed) -> Bool {
return lock.read { return registrations[AnyKey(key)] != nil }
}
/**
Returns true if a key with the given type, name, and container exists.
*/
public static func exists<T, N: Hashable, C: Hashable, M>(type: T.Type, name: N, container: C, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(key: Key<T>(name: name, container: container), metafilter: metathunk(metafilter))
}
public static func exists<T, N: Hashable, C: Hashable, M: Equatable>(type: T.Type, name: N, container: C, metadata: M) -> Bool {
return exists(key: Key<T>(name: name, container: container)) { $0 == metadata }
}
/**
Returns true if a key with the given type, name, and container exists.
*/
public static func exists<T, N: Hashable, C: Hashable>(type: T.Type, name: N, container: C) -> Bool {
return exists(key: AnyKey(type: type, name: name, container: container))
}
/**
Returns true if any keys with the given type and name exist in any containers.
*/
public static func exists<T, N: Hashable, M>(type: T.Type, name: N, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: String(reflecting: type), name: name, container: nil, metathunk: metathunk(metafilter))
}
public static func exists<T, N: Hashable, M: Equatable>(type: T.Type, name: N, metadata: M) -> Bool {
return exists(type: type, name: name) { $0 == metadata }
}
/**
Returns true if any keys with the given type and name exist in any containers.
*/
public static func exists<T, N: Hashable>(type: T.Type, name: N) -> Bool {
return exists(type: String(reflecting: type), name: name, container: nil)
}
/**
Returns true if any keys with the given type exist in the given container, independent of name.
*/
public static func exists<T, C: Hashable, M>(type: T.Type, container: C, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: String(reflecting: type), name: nil, container: container, metathunk: metathunk(metafilter))
}
public static func exists<T, C: Hashable, M: Equatable>(type: T.Type, container: C, metadata: M) -> Bool {
return exists(type: type, container: container) { $0 == metadata }
}
/**
Returns true if any keys with the given type exist in the given container, independent of name.
*/
public static func exists<T, C: Hashable>(type: T.Type, container: C) -> Bool {
return exists(type: String(reflecting: type), name: nil, container: container)
}
/**
Returns true if any keys with the given name exist in the given container, independent of type.
*/
public static func exists<N: Hashable, C: Hashable, M>(name: N, container: C, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: nil, name: name, container: container, metathunk: metathunk(metafilter))
}
public static func exists<N: Hashable, C: Hashable, M: Equatable>(name: N, container: C, metadata: M) -> Bool {
return exists(name: name, container: container) { $0 == metadata }
}
/**
Returns true if any keys with the given name exist in the given container, independent of type.
*/
public static func exists<N: Hashable, C: Hashable>(name: N, container: C) -> Bool {
return exists(type: nil, name: name, container: container)
}
/**
Return true if any keys with the given name exist in any container, independent of type.
*/
public static func exists<N: Hashable, M>(name: N, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: nil, name: name, container: nil, metathunk: metathunk(metafilter))
}
public static func exists<N: Hashable, M: Equatable>(name: N, metadata: M) -> Bool {
return exists(name: name) { $0 == metadata }
}
/**
Returns true if any registrations exist under the given name.
*/
public static func exists<N: Hashable>(name: N) -> Bool {
return exists(type: nil, name: name, container: nil)
}
/**
Returns true if there are any keys registered in the given container, matching the given metafilter query.
*/
public static func exists<C: Hashable, M>(container: C, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: nil, name: nil, container: container, metathunk: metathunk(metafilter))
}
public static func exists<C: Hashable, M: Equatable>(container: C, metadata: M) -> Bool {
return exists(container: container) { $0 == metadata }
}
/**
Returns true if there are any keys registered in the given container.
*/
public static func exists<C: Hashable>(container: C) -> Bool {
return exists(type: nil, name: nil, container: container)
}
/**
Returns true if there are any keys registered with the given type and matching the metafilter query in any container, independent of name.
*/
public static func exists<T, M>(type: T.Type, metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: String(reflecting: type), name: nil, container: nil, metathunk: metathunk(metafilter))
}
public static func exists<T, M: Equatable>(type: T.Type, metadata: M) -> Bool {
return exists(type: type) { $0 == metadata }
}
/**
Returns true if there are any keys registered with the given type in any container, independent of name.
*/
public static func exists<T>(type: T.Type) -> Bool {
return exists(type: String(reflecting: type), name: nil, container: nil)
}
/**
Returns true if any registrations exist matching the given metafilter, regardless of type, name, or container.
*/
public static func exists<M>(metafilter: @escaping Metafilter<M>) -> Bool {
return exists(type: nil, name: nil, container: nil, metathunk: metathunk(metafilter))
}
public static func exists<M: Equatable>(metadata: M) -> Bool {
return exists{ $0 == metadata }
}
// MARK: Metadata
/**
Retrieve metadata for the dependency registered under `key`.
*/
public static func metadata<M>(for key: Keyed) -> M? {
guard let dependency = lock.read({ registrations[AnyKey(key)] }) else { return nil }
guard let metadata = dependency.metadata as? M else { return nil }
return metadata
}
/**
Retrieve metadata for multiple keys.
*/
public static func metadata<M>(for keys: Set<AnyKey>) -> [AnyKey: M] {
return lock.read {
var metadatas = [AnyKey: M]()
for (key, dependency) in registrations {
if !keys.contains(key) { continue }
guard let metadata = dependency.metadata as? M else { continue }
metadatas[key] = metadata
}
return metadatas
}
}
/**
Retrieve metadata for multiple keys.
*/
public static func metadata<T, M>(for keys: Set<Key<T>>) -> [Key<T>: M] {
return lock.read {
var metadatas = Dictionary<Key<T>, M>()
for (key, dependency) in registrations {
guard let key = Key<T>(key) else { continue }
if !keys.contains(key) { continue }
guard let metadata = dependency.metadata as? M else { continue }
metadatas[key] = metadata
}
return metadatas
}
}
// MARK: Unregistration
/**
Remove the dependencies registered under the given keys.
- parameter keys: The keys to remove.
- returns: The number of dependencies removed.
*/
public static func unregister(keys: Set<AnyKey>) -> Int {
return lock.write {
let count = registrations.count
registrations = registrations.filter{ !keys.contains($0.key) }.dictionary()
return count - registrations.count
}
}
/**
Remove the dependencies registered under the given keys.
- parameter keys: The keys to remove.
- returns: The number of dependencies removed.
*/
public static func unregister<T>(keys: Set<Key<T>>) -> Int {
return unregister(keys: keys.untypedKeys())
}
/**
Remove the dependencies registered under the given key(s).
- parameter key: One or more keys to remove
- returns: The number of dependencies removed.
*/
public static func unregister(key: AnyKey...) -> Int {
return unregister(keys: key.untypedKeys())
}
/**
Remove the dependencies registered under the given key(s).
- parameter key: One or more keys to remove
- returns: The number of dependencies removed.
*/
public static func unregister<T>(key: Key<T>...) -> Int {
return unregister(keys: key.untypedKeys())
}
/**
Remove all dependencies of the given type, irrespective of name and container.
- parameter type: The registered type of the dependencies to remove.
- returns: The number of dependencies removed.
*/
public static func unregister<T>(type: T.Type) -> Int {
return unregister(keys: Guise.filter(type: type))
}
/**
Remove all dependencies in the specified container.
- parameter container: The container to empty.
- returns: The number of dependencies removed.
*/
public static func unregister<C: Hashable>(container: C) -> Int {
return unregister(keys: Guise.filter(container: container))
}
/**
Remove all dependencies of the given type in the specified container.
- parameters:
- type: The registered type of the dependencies to remove.
- container: The container in which to search for dependencies to remove.
- returns: The number of dependencies removed.
*/
public static func unregister<T, C: Hashable>(type: T.Type, container: C) -> Int {
return unregister(keys: Guise.filter(type: type, container: container))
}
/**
Remove the dependency with the specified type, name, and container.
- parameters:
- type: The type of the dependency to remove.
- name: The name of the dependency to remove.
- container: The container of the dependency to remove.
- returns: The number of dependencies removed, which for this method will be either 0 or 1.
- note: This can affect only one registered dependency.
*/
public static func unregister<T, N: Hashable, C: Hashable>(type: T.Type, name: N, container: C) -> Int {
return unregister(key: Key<T>(name: name, container: container))
}
/**
Remove all dependencies. Reset Guise completely.
*/
public static func clear() {
lock.write { registrations = [:] }
}
}
// MARK: -
/**
A simple non-reentrant lock allowing one writer and multiple readers.
*/
private class Lock {
private let lock: UnsafeMutablePointer<pthread_rwlock_t> = {
var lock = UnsafeMutablePointer<pthread_rwlock_t>.allocate(capacity: 1)
let status = pthread_rwlock_init(lock, nil)
assert(status == 0)
return lock
}()
private func lock<T>(_ acquire: (UnsafeMutablePointer<pthread_rwlock_t>) -> Int32, block: () -> T) -> T {
let _ = acquire(lock)
defer { pthread_rwlock_unlock(lock) }
return block()
}
func read<T>(_ block: () -> T) -> T {
return lock(pthread_rwlock_rdlock, block: block)
}
func write<T>(_ block: () -> T) -> T {
return lock(pthread_rwlock_wrlock, block: block)
}
deinit {
pthread_rwlock_destroy(lock)
}
}
// MARK: - Extensions
extension Array {
/**
Reconstruct a dictionary after it's been reduced to an array of key-value pairs by `filter` and the like.
```
var dictionary = [1: "ok", 2: "crazy", 99: "abnormal"]
dictionary = dictionary.filter{ $0.value == "ok" }.dictionary()
```
*/
func dictionary<K: Hashable, V>() -> [K: V] where Element == Dictionary<K, V>.Element {
var dictionary = [K: V]()
for element in self {
dictionary[element.key] = element.value
}
return dictionary
}
}
extension Sequence where Iterator.Element: Keyed {
/**
Returns a set up of typed `Key<T>`.
Any of the underlying keys whose type is not `T`
will simply be omitted, so this is also a way
to filter a sequence of keys by type.
*/
public func typedKeys<T>() -> Set<Key<T>> {
return Set<Key<T>>(flatMap{ Key($0) })
}
/**
Returns a set of untyped `AnyKey`.
This is a convenient way to turn a set of typed
keys into a set of untyped keys.
*/
public func untypedKeys() -> Set<AnyKey> {
return Set(map{ AnyKey($0) })
}
}
/**
This typealias exists to disambiguate Guise's `Key<T>`
from the `Key` generic type parameter in `Dictionary`.
It is exactly equivalent to `Key<T>` and can be safely
ignored.
*/
public typealias GuiseKey<T> = Key<T>
extension Dictionary where Key: Keyed {
/**
Returns a dictionary in which the keys hold the type `T`.
Any key which does not hold `T` is simply skipped, along with
its corresponding value, so this is also a way to filter
a sequence of keys by type.
*/
public func typedKeys<T>() -> Dictionary<GuiseKey<T>, Value> {
return flatMap {
guard let key = GuiseKey<T>($0.key) else { return nil }
return (key: key, value: $0.value)
}.dictionary()
}
/**
Returns a dictionary in which the keys are `AnyKey`.
This is a convenient way to turn a dictionary with typed keys
into a dictionary with type-erased keys.
*/
public func untypedKeys() -> Dictionary<AnyKey, Value> {
return map{ (key: AnyKey($0.key), value: $0.value) }.dictionary()
}
}
// Miscellanea: -
/**
Generates a hash value for one or more hashable values.
*/
private func hash<H: Hashable>(_ hashables: H...) -> Int {
// djb2 hash algorithm: http://www.cse.yorku.ca/~oz/hash.html
// &+ operator handles Int overflow
return hashables.reduce(5381) { (result, hashable) in ((result << 5) &+ result) &+ hashable.hashValue }
}
infix operator ??= : AssignmentPrecedence
private func ??=<T>(lhs: inout T?, rhs: @autoclosure () -> T?) {
if lhs != nil { return }
lhs = rhs()
}
|
//
// Copyright (c) 2015 Algolia
// http://www.algolia.com/
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import AlgoliaSearch
/// Tests for the network logic.
///
/// NOTE: We use `listIndexes()` to test, but we could use roughly any other function, since we don't really care
/// about the result.
///
class NetworkTests: XCTestCase {
let expectationTimeout: NSTimeInterval = 100
var client: Client!
var index: Index!
let FAKE_APP_ID = "FAKE_APPID"
let FAKE_API_KEY = "FAKE_API_KEY"
let FAKE_INDEX_NAME = "FAKE_INDEX_NAME"
let session: MockURLSession = MockURLSession()
// Well-known errors:
let TIMEOUT_ERROR = NSError(domain: NSURLErrorDomain, code: NSURLErrorTimedOut, userInfo: nil)
override func setUp() {
super.setUp()
client = AlgoliaSearch.Client(appID: FAKE_APP_ID, apiKey: FAKE_API_KEY)
client.session = session
index = client.getIndex(FAKE_INDEX_NAME)
}
override func tearDown() {
super.tearDown()
}
/// In case of time-out on one host, check that the next host is tried.
func testTimeout_OneHost() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(error: TIMEOUT_ERROR)
session.responses["https://\(client.writeHosts[1])/1/indexes"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(error)
XCTAssertNotNil(content)
XCTAssertEqual(content?["hello"] as? String, "world")
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// In case of time-out on all hosts, check that the error is returned.
func testTimeout_AllHosts() {
let expectation = expectationWithDescription(#function)
for i in 0..<client.writeHosts.count {
session.responses["https://\(client.writeHosts[i])/1/indexes"] = MockResponse(error: TIMEOUT_ERROR)
}
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(content)
XCTAssertNotNil(error)
XCTAssert(error?.domain == NSURLErrorDomain)
XCTAssert(error?.code == NSURLErrorTimedOut)
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// In case of DNS error on one host, check that the next host is tried.
func testDNSError() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(error: NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotFindHost, userInfo: nil))
session.responses["https://\(client.writeHosts[1])/1/indexes"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(error)
XCTAssertNotNil(content)
XCTAssertEqual(content?["hello"] as? String, "world")
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// In case of server error on one host, check that the next host is tried.
func testServerError() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(statusCode: 500, jsonBody: ["message": "Mind your own business"])
session.responses["https://\(client.writeHosts[1])/1/indexes"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(error)
XCTAssertNotNil(content)
XCTAssertEqual(content?["hello"] as? String, "world")
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// In case of client error, check that the next host is *not* tried.
func testClientError() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(statusCode: 403, jsonBody: ["message": "Mind your own business"])
session.responses["https://\(client.writeHosts[1])/1/indexes"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(content)
XCTAssertNotNil(error)
XCTAssertEqual(error?.domain, AlgoliaSearchErrorDomain)
XCTAssertEqual(error?.code, 403)
XCTAssertEqual(error?.userInfo[NSLocalizedDescriptionKey] as? String, "Mind your own business")
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// Test when the server returns a success, but no JSON.
func testEmptyResponse() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(statusCode: 200, data: NSData())
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(content)
XCTAssertNotNil(error)
XCTAssertEqual(error?.domain, AlgoliaSearchErrorDomain)
XCTAssertEqual(error?.code, StatusCode.InvalidJSONResponse.rawValue)
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// Test when the server returns an error status code, but no JSON.
func testEmptyErrorResponse() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(statusCode: 403, data: NSData())
session.responses["https://\(client.writeHosts[1])/1/indexes"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(content)
XCTAssertNotNil(error)
XCTAssertEqual(error?.domain, AlgoliaSearchErrorDomain)
XCTAssertEqual(error?.code, StatusCode.InvalidJSONResponse.rawValue)
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// Test when the server returns an error status code and valid JSON, but no error message in the JSON.
func testEmptyErrorMessage() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(statusCode: 403, jsonBody: ["something": "else"])
session.responses["https://\(client.writeHosts[1])/1/indexes"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(content)
XCTAssertNotNil(error)
XCTAssertEqual(error?.domain, AlgoliaSearchErrorDomain)
XCTAssertEqual(error?.code, 403)
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// Test cancelling a request.
func testCancel() {
// NOTE: We use a search request here because it is more complex (in-memory cache involved).
session.responses["https://\(client.writeHosts[0])/1/indexes/\(FAKE_INDEX_NAME)"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
let request1 = index.search(Query()) {
(content, error) -> Void in
XCTFail("Completion handler should not be called when a request has been cancelled")
}
request1.cancel()
// Manually run the run loop for a while to leave a chance to the completion handler to be called.
// WARNING: We cannot use `waitForExpectationsWithTimeout()`, because a timeout always results in failure.
NSRunLoop.mainRunLoop().runUntilDate(NSDate().dateByAddingTimeInterval(3))
// Run the test again, but this time the session won't actually cancel the (mock) network call.
// This checks that the `Request` class still mutes the completion handler when cancelled.
session.cancellable = false
let request2 = index.search(Query()) {
(content, error) -> Void in
XCTFail("Completion handler should not be called when a request has been cancelled")
}
request2.cancel()
NSRunLoop.mainRunLoop().runUntilDate(NSDate().dateByAddingTimeInterval(3))
}
}
Add test case for ill-formed JSON returned by server
//
// Copyright (c) 2015 Algolia
// http://www.algolia.com/
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import AlgoliaSearch
/// Tests for the network logic.
///
/// NOTE: We use `listIndexes()` to test, but we could use roughly any other function, since we don't really care
/// about the result.
///
class NetworkTests: XCTestCase {
let expectationTimeout: NSTimeInterval = 100
var client: Client!
var index: Index!
let FAKE_APP_ID = "FAKE_APPID"
let FAKE_API_KEY = "FAKE_API_KEY"
let FAKE_INDEX_NAME = "FAKE_INDEX_NAME"
let session: MockURLSession = MockURLSession()
// Well-known errors:
let TIMEOUT_ERROR = NSError(domain: NSURLErrorDomain, code: NSURLErrorTimedOut, userInfo: nil)
override func setUp() {
super.setUp()
client = AlgoliaSearch.Client(appID: FAKE_APP_ID, apiKey: FAKE_API_KEY)
client.session = session
index = client.getIndex(FAKE_INDEX_NAME)
}
override func tearDown() {
super.tearDown()
}
/// In case of time-out on one host, check that the next host is tried.
func testTimeout_OneHost() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(error: TIMEOUT_ERROR)
session.responses["https://\(client.writeHosts[1])/1/indexes"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(error)
XCTAssertNotNil(content)
XCTAssertEqual(content?["hello"] as? String, "world")
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// In case of time-out on all hosts, check that the error is returned.
func testTimeout_AllHosts() {
let expectation = expectationWithDescription(#function)
for i in 0..<client.writeHosts.count {
session.responses["https://\(client.writeHosts[i])/1/indexes"] = MockResponse(error: TIMEOUT_ERROR)
}
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(content)
XCTAssertNotNil(error)
XCTAssert(error?.domain == NSURLErrorDomain)
XCTAssert(error?.code == NSURLErrorTimedOut)
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// In case of DNS error on one host, check that the next host is tried.
func testDNSError() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(error: NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotFindHost, userInfo: nil))
session.responses["https://\(client.writeHosts[1])/1/indexes"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(error)
XCTAssertNotNil(content)
XCTAssertEqual(content?["hello"] as? String, "world")
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// In case of server error on one host, check that the next host is tried.
func testServerError() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(statusCode: 500, jsonBody: ["message": "Mind your own business"])
session.responses["https://\(client.writeHosts[1])/1/indexes"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(error)
XCTAssertNotNil(content)
XCTAssertEqual(content?["hello"] as? String, "world")
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// In case of client error, check that the next host is *not* tried.
func testClientError() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(statusCode: 403, jsonBody: ["message": "Mind your own business"])
session.responses["https://\(client.writeHosts[1])/1/indexes"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(content)
XCTAssertNotNil(error)
XCTAssertEqual(error?.domain, AlgoliaSearchErrorDomain)
XCTAssertEqual(error?.code, 403)
XCTAssertEqual(error?.userInfo[NSLocalizedDescriptionKey] as? String, "Mind your own business")
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// Test when the server returns a success, but no JSON.
func testEmptyResponse() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(statusCode: 200, data: NSData())
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(content)
XCTAssertNotNil(error)
XCTAssertEqual(error?.domain, AlgoliaSearchErrorDomain)
XCTAssertEqual(error?.code, StatusCode.InvalidJSONResponse.rawValue)
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// Test when the server returns a success, but ill-formed JSON.
func testIllFormedResponse() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(statusCode: 200, data: NSData(base64EncodedString: "U0hPVUxETk9UV09SSw==", options: [])!)
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(content)
XCTAssertNotNil(error)
XCTAssertEqual(error?.domain, AlgoliaSearchErrorDomain)
XCTAssertEqual(error?.code, StatusCode.InvalidJSONResponse.rawValue)
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// Test when the server returns an error status code, but no JSON.
func testEmptyErrorResponse() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(statusCode: 403, data: NSData())
session.responses["https://\(client.writeHosts[1])/1/indexes"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(content)
XCTAssertNotNil(error)
XCTAssertEqual(error?.domain, AlgoliaSearchErrorDomain)
XCTAssertEqual(error?.code, StatusCode.InvalidJSONResponse.rawValue)
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// Test when the server returns an error status code and valid JSON, but no error message in the JSON.
func testEmptyErrorMessage() {
let expectation = expectationWithDescription(#function)
session.responses["https://\(client.writeHosts[0])/1/indexes"] = MockResponse(statusCode: 403, jsonBody: ["something": "else"])
session.responses["https://\(client.writeHosts[1])/1/indexes"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
client.listIndexes {
(content, error) -> Void in
XCTAssertNil(content)
XCTAssertNotNil(error)
XCTAssertEqual(error?.domain, AlgoliaSearchErrorDomain)
XCTAssertEqual(error?.code, 403)
expectation.fulfill()
}
waitForExpectationsWithTimeout(expectationTimeout, handler: nil)
}
/// Test cancelling a request.
func testCancel() {
// NOTE: We use a search request here because it is more complex (in-memory cache involved).
session.responses["https://\(client.writeHosts[0])/1/indexes/\(FAKE_INDEX_NAME)"] = MockResponse(statusCode: 200, jsonBody: ["hello": "world"])
let request1 = index.search(Query()) {
(content, error) -> Void in
XCTFail("Completion handler should not be called when a request has been cancelled")
}
request1.cancel()
// Manually run the run loop for a while to leave a chance to the completion handler to be called.
// WARNING: We cannot use `waitForExpectationsWithTimeout()`, because a timeout always results in failure.
NSRunLoop.mainRunLoop().runUntilDate(NSDate().dateByAddingTimeInterval(3))
// Run the test again, but this time the session won't actually cancel the (mock) network call.
// This checks that the `Request` class still mutes the completion handler when cancelled.
session.cancellable = false
let request2 = index.search(Query()) {
(content, error) -> Void in
XCTFail("Completion handler should not be called when a request has been cancelled")
}
request2.cancel()
NSRunLoop.mainRunLoop().runUntilDate(NSDate().dateByAddingTimeInterval(3))
}
}
|
//
// Maintenance.swift
// masamon
//
// Created by 岩見建汰 on 2016/08/22.
// Copyright © 2016年 Kenta. All rights reserved.
//
import UIKit
import RealmSwift
class Maintenance {
func FileRemove() {
//クラッシュ等で参照されずに残ってしまったファイルを手動で削除する(保守用)
let documentspath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let Inboxpath = documentspath + "/Inbox/" //Inboxまでのパス
let Libralypath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as String + "/"
let filepath = Libralypath + "85.11〜.pdf"
let ABC = Libralypath + "8.11〜.pdf"
let filemanager:NSFileManager = NSFileManager()
do{
//try filemanager.removeItemAtPath(filepath)
try NSFileManager.defaultManager().moveItemAtURL(NSURL(fileURLWithPath: filepath), toURL: NSURL(fileURLWithPath: ABC))
}catch{
print(error)
}
}
func DBAdd() {
let AAA = HourlyPayDB()
AAA.id = 0
AAA.timefrom = 4.5
AAA.timeto = 10.0
AAA.pay = 100
let AAA1 = HourlyPayDB()
AAA1.id = 1
AAA1.timefrom = 4.5
AAA1.timeto = 10.0
AAA1.pay = 200
let AAA2 = UserNameDB()
AAA2.id = 0
AAA2.name = "Aさん"
let AAA3 = StaffNumberDB()
AAA3.id = 0
AAA3.number = 22
DBmethod().AddandUpdate(AAA, update: true)
DBmethod().AddandUpdate(AAA1, update: true)
DBmethod().AddandUpdate(AAA2, update: true)
DBmethod().AddandUpdate(AAA3, update: true)
}
func DBUpdate() {
let realm = try! Realm()
try! realm.write {
realm.create(Book.self, value: ["id": 1, "price": 9000.0], update: true)
// タイトルはそのままで値段のプロパティだけを更新することができます。
}
}
}
エラーをコメントアウト
//
// Maintenance.swift
// masamon
//
// Created by 岩見建汰 on 2016/08/22.
// Copyright © 2016年 Kenta. All rights reserved.
//
import UIKit
import RealmSwift
class Maintenance {
func FileRemove() {
//クラッシュ等で参照されずに残ってしまったファイルを手動で削除する(保守用)
let documentspath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let Inboxpath = documentspath + "/Inbox/" //Inboxまでのパス
let Libralypath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as String + "/"
let filepath = Libralypath + "85.11〜.pdf"
let ABC = Libralypath + "8.11〜.pdf"
let filemanager:NSFileManager = NSFileManager()
do{
//try filemanager.removeItemAtPath(filepath)
try NSFileManager.defaultManager().moveItemAtURL(NSURL(fileURLWithPath: filepath), toURL: NSURL(fileURLWithPath: ABC))
}catch{
print(error)
}
}
func DBAdd() {
let AAA = HourlyPayDB()
AAA.id = 0
AAA.timefrom = 4.5
AAA.timeto = 10.0
AAA.pay = 100
let AAA1 = HourlyPayDB()
AAA1.id = 1
AAA1.timefrom = 4.5
AAA1.timeto = 10.0
AAA1.pay = 200
let AAA2 = UserNameDB()
AAA2.id = 0
AAA2.name = "Aさん"
let AAA3 = StaffNumberDB()
AAA3.id = 0
AAA3.number = 22
DBmethod().AddandUpdate(AAA, update: true)
DBmethod().AddandUpdate(AAA1, update: true)
DBmethod().AddandUpdate(AAA2, update: true)
DBmethod().AddandUpdate(AAA3, update: true)
}
func DBUpdate() {
let realm = try! Realm()
try! realm.write {
// realm.create(Book.self, value: ["id": 1, "price": 9000.0], update: true)
// タイトルはそのままで値段のプロパティだけを更新することができます。
}
}
}
|
import UIKit
class VHelpCell:UICollectionViewCell
{
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
isUserInteractionEnabled = false
}
required init?(coder:NSCoder)
{
fatalError()
}
//MARK: public
func config(model:MHelpItem)
{
}
}
image view in help cell
import UIKit
class VHelpCell:UICollectionViewCell
{
private weak var imageView:UIImageView!
private let kImageTop:CGFloat = 20
private let kImageHeight:CGFloat = 180
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
isUserInteractionEnabled = false
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = UIViewContentMode.center
imageView.clipsToBounds = true
self.imageView = imageView
addSubview(imageView)
let layoutImageTop:NSLayoutConstraint = NSLayoutConstraint.topToTop(
view:imageView,
toView:self,
constant:kImageTop)
let layoutImageHeight:NSLayoutConstraint = NSLayoutConstraint.height(
view:imageView,
constant:kImageHeight)
let layoutImageLeft:NSLayoutConstraint = NSLayoutConstraint.leftToLeft(
view:imageView,
toView:self)
let layoutImageRight:NSLayoutConstraint = NSLayoutConstraint.rightToRight(
view:imageView,
toView:self)
addConstraints([
layoutImageTop,
layoutImageHeight,
layoutImageLeft,
layoutImageRight])
}
required init?(coder:NSCoder)
{
fatalError()
}
//MARK: public
func config(model:MHelpItem)
{
imageView.image = model.image
}
}
|
//
// ShiftImport.swift
// masamon
//
// Created by 岩見建汰 on 2015/11/04.
// Copyright © 2015年 Kenta. All rights reserved.
//
import UIKit
class ShiftImport: UIViewController{
@IBOutlet weak var Label: UILabel!
@IBOutlet weak var textfield: UITextField!
let filemanager:NSFileManager = NSFileManager()
let documentspath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let Libralypath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as String
let filename = DBmethod().FilePathTmpGet().lastPathComponent //ファイル名の抽出
let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate //AppDelegateのインスタンスを取得
override func viewDidLoad() {
super.viewDidLoad()
if(DBmethod().FilePathTmpGet() != ""){
Label.text = DBmethod().FilePathTmpGet() as String
textfield.text = DBmethod().FilePathTmpGet().lastPathComponent
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func ShiftImportViewActived(){
Label.text = DBmethod().FilePathTmpGet() as String
}
//取り込むボタンを押したら動作
@IBAction func xlsximport(sender: AnyObject) {
if(textfield.text != ""){
let Inboxpath = documentspath + "/Inbox/" //Inboxまでのパス
let filemanager = NSFileManager()
do{
try filemanager.moveItemAtPath(Inboxpath+filename, toPath: Libralypath+"/"+textfield.text!)
self.dismissViewControllerAnimated(true, completion: nil)
appDelegate.filesavealert = true
}catch{
print(error)
}
}else{
let alertController = UIAlertController(title: "取り込みエラー", message: "ファイル名を入力して下さい", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
//キャンセルボタンをタップしたら動作
@IBAction func cancel(sender: AnyObject) {
let inboxpath = documentspath + "/Inbox/" //Inboxまでのパス
//コピーしたファイルの削除
do{
try filemanager.removeItemAtPath(inboxpath + filename)
//データベースに記録しているファイル数を1減らして更新
let InboxFileCountRecord = InboxFileCount()
InboxFileCountRecord.id = 0
InboxFileCountRecord.counts = DBmethod().InboxFileCountsGet()-1
DBmethod().AddandUpdate(InboxFileCountRecord)
}catch{
print(error)
}
self.dismissViewControllerAnimated(true, completion: nil)
}
}
InboxFileCountsの数を減らす処理を追加
//
// ShiftImport.swift
// masamon
//
// Created by 岩見建汰 on 2015/11/04.
// Copyright © 2015年 Kenta. All rights reserved.
//
import UIKit
class ShiftImport: UIViewController{
@IBOutlet weak var Label: UILabel!
@IBOutlet weak var textfield: UITextField!
let filemanager:NSFileManager = NSFileManager()
let documentspath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let Libralypath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as String
let filename = DBmethod().FilePathTmpGet().lastPathComponent //ファイル名の抽出
let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate //AppDelegateのインスタンスを取得
override func viewDidLoad() {
super.viewDidLoad()
if(DBmethod().FilePathTmpGet() != ""){
Label.text = DBmethod().FilePathTmpGet() as String
textfield.text = DBmethod().FilePathTmpGet().lastPathComponent
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func ShiftImportViewActived(){
Label.text = DBmethod().FilePathTmpGet() as String
}
//取り込むボタンを押したら動作
@IBAction func xlsximport(sender: AnyObject) {
if(textfield.text != ""){
let Inboxpath = documentspath + "/Inbox/" //Inboxまでのパス
let filemanager = NSFileManager()
do{
try filemanager.moveItemAtPath(Inboxpath+filename, toPath: Libralypath+"/"+textfield.text!)
self.InboxFileCountsMinusOne()
self.dismissViewControllerAnimated(true, completion: nil)
appDelegate.filesavealert = true
}catch{
print(error)
}
}else{
let alertController = UIAlertController(title: "取り込みエラー", message: "ファイル名を入力して下さい", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
//キャンセルボタンをタップしたら動作
@IBAction func cancel(sender: AnyObject) {
let inboxpath = documentspath + "/Inbox/" //Inboxまでのパス
//コピーしたファイルの削除
do{
try filemanager.removeItemAtPath(inboxpath + filename)
self.InboxFileCountsMinusOne()
}catch{
print(error)
}
self.dismissViewControllerAnimated(true, completion: nil)
}
//InboxFileCountsの数を1つ減らす
func InboxFileCountsMinusOne(){
let InboxFileCountRecord = InboxFileCount()
InboxFileCountRecord.id = 0
InboxFileCountRecord.counts = DBmethod().InboxFileCountsGet()-1
DBmethod().AddandUpdate(InboxFileCountRecord)
}
}
|
import Foundation
public class Request: Equatable {
public typealias SuccessClosure = ((body: String, data: NSData, response: NSURLResponse, request: Request)->())?
public typealias ErrorClosure = ((error: NSError, body: String, data: NSData, response: NSURLResponse?, request: Request)->())?
var manager: SilkManager
internal(set) var successClosure: SuccessClosure
internal(set) var errorClosure: ErrorClosure
private(set) var tag: String = NSUUID().UUIDString
private(set) var group = "Requests"
var compoundContext = [String: AnyObject]()
func context(context: [String: AnyObject]) -> Self {
compoundContext = context
return self
}
init(manager: SilkManager) {
self.manager = manager
}
public func tag(requestTag: String) -> Self {
tag = requestTag
return self
}
public func group(requestGroup: String) -> Self {
group = requestGroup
return self
}
public func completion(success: SuccessClosure, error: ErrorClosure) -> Self {
successClosure = success
errorClosure = error
return self
}
public func execute() -> Bool {
// empty implementation, for subclasses to override
return true
}
public func cancel() {
manager.unregisterRequest(self)
// empty implementation, for subclasses to override
}
func appendResponseData(data: NSData, task: NSURLSessionTask) {
// empty implementation, for subclasses to override
}
func handleResponse(response: NSHTTPURLResponse, error: NSError?, task: NSURLSessionTask) {
// empty implementation, for subclasses to override
}
}
// MARK: - Equatable
public func ==(lhs: Request, rhs: Request) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
made compoundContext public
import Foundation
public class Request: Equatable {
public typealias SuccessClosure = ((body: String, data: NSData, response: NSURLResponse, request: Request)->())?
public typealias ErrorClosure = ((error: NSError, body: String, data: NSData, response: NSURLResponse?, request: Request)->())?
var manager: SilkManager
internal(set) var successClosure: SuccessClosure
internal(set) var errorClosure: ErrorClosure
private(set) var tag: String = NSUUID().UUIDString
private(set) var group = "Requests"
public var compoundContext = [String: AnyObject]()
func context(context: [String: AnyObject]) -> Self {
compoundContext = context
return self
}
init(manager: SilkManager) {
self.manager = manager
}
public func tag(requestTag: String) -> Self {
tag = requestTag
return self
}
public func group(requestGroup: String) -> Self {
group = requestGroup
return self
}
public func completion(success: SuccessClosure, error: ErrorClosure) -> Self {
successClosure = success
errorClosure = error
return self
}
public func execute() -> Bool {
// empty implementation, for subclasses to override
return true
}
public func cancel() {
manager.unregisterRequest(self)
// empty implementation, for subclasses to override
}
func appendResponseData(data: NSData, task: NSURLSessionTask) {
// empty implementation, for subclasses to override
}
func handleResponse(response: NSHTTPURLResponse, error: NSError?, task: NSURLSessionTask) {
// empty implementation, for subclasses to override
}
}
// MARK: - Equatable
public func ==(lhs: Request, rhs: Request) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
} |
//
// PDFmethod2.swift
// masamon
//
// Created by 岩見建汰 on 2016/08/13.
// Copyright © 2016年 Kenta. All rights reserved.
//
import UIKit
/**
* pdfから抽出したテキスト情報を格納する構造体
*/
struct CharInfo {
var text = ""
var x = 0.0
var y = 0.0
var size = 0.0
}
class PDFmethod2: UIViewController {
let tolerance = 3.0 //同じ行と判定させるための許容誤差
/**
実行用のメソッド
*/
func RunPDFmethod() {
let charinfoArray = GetPDFGlyphInfo()
let removed_overlap = RemoveOverlapArray(charinfoArray)
var sorted = SortcharinfoArray(removed_overlap)
//各配列のY座標の平均値を求める
var YaverageArray: [Double] = []
for i in 0..<sorted.count {
YaverageArray.append(Get_Y_Average(sorted[i]))
}
let unioned = UnionArrayByY(YaverageArray, charinfo: sorted)
//スタッフ名が登録されている場合のみ処理を進める
if CheckStaffNameDB() == true {
let removed_unnecessary = RemoveUnnecessaryLines(unioned)
GetSplitShiftAllStaffByDay(removed_unnecessary)
}
}
/**
pdfのテキスト情報を2次元配列に行ごとに格納する
- returns: y座標が近似しているCharInfo同士を2次元配列に格納したもの
*/
func GetPDFGlyphInfo() -> [[CharInfo]] {
var charinfoArray: [[CharInfo]] = []
var prev_y = -99.99
var currentArrayIndex = -1
let path: NSString
//path = DBmethod().FilePathTmpGet()
path = NSBundle.mainBundle().pathForResource("8.11〜", ofType: "pdf")!
let tet = TET()
let document = tet.open_document(path as String, optlist: "")
let page = tet.open_page(document, pagenumber: 1, optlist: "granularity=glyph")
var text = tet.get_text(page)
//全テキストを検査するループ
while(text != nil && text.characters.count > 0){
while(tet.get_char_info(page) > 0){
var charinfo = CharInfo()
charinfo.text = text.hankakuOnly
charinfo.text = ReplaceHankakuSymbol(charinfo.text)
charinfo.size = tet.fontsize()
charinfo.x = tet.x()
charinfo.y = tet.y()
if !(prev_y-tolerance...prev_y+tolerance ~= tet.y()) {
prev_y = tet.y()
charinfoArray.append([])
currentArrayIndex += 1
}
charinfoArray[currentArrayIndex].append(charinfo)
}
text = tet.get_text(page)
}
tet.close_page(page)
tet.close_document(document)
return charinfoArray
}
/**
- parameter text: 全角記号を半角記号に置き換える
- returns: 半角記号に置き換えた後の文字列
*/
func ReplaceHankakuSymbol(text: String) -> String {
let pattern_zenkaku = ["(", ")", "/"]
let pattern_hankaku = ["(", ")", "/"]
var hankaku_text = text
for i in 0..<pattern_hankaku.count {
hankaku_text = hankaku_text.stringByReplacingOccurrencesOfString(pattern_zenkaku[i], withString: pattern_hankaku[i])
}
return hankaku_text
}
/**
内容が重複している配列を削除する
- parameter charinfoArray: CharInfoを格納した2次元配列
- returns: テキストは完全一致,y座標は近似している配列(余分に存在する配列)を削除した配列
*/
func RemoveOverlapArray(charinfoArray: [[CharInfo]]) -> [[CharInfo]] {
var removedcharinfoArray = charinfoArray
var matchKeyArray: [Int] = [] //比較対象元(添字が小さい)
var matchValueArray: [Int] = [] //比較対象先(添字が大きい)
var match_count = 0
//テキストが重複している配列の中身を検出する
for i in 0..<charinfoArray.count - 1 {
for j in i+1..<charinfoArray.count {
if charinfoArray[i].count == charinfoArray[j].count {
for k in 0..<charinfoArray[i].count {
let charinfo1 = charinfoArray[i][k]
let charinfo2 = charinfoArray[j][k]
if charinfo1.text == charinfo2.text {
match_count += 1
}else {
break
}
}
//テキストが全て一致したかを判断する
if match_count == charinfoArray[i].count {
matchKeyArray.append(i)
matchValueArray.append(j)
}
match_count = 0
}
}
}
//matchkey,value配列からY座標の平均値が全く異なるものを外す処理
for i in (0..<matchKeyArray.count).reverse() {
let key_Yave = Get_Y_Average(charinfoArray[matchKeyArray[i]])
let value_Yave = Get_Y_Average(charinfoArray[matchValueArray[i]])
//テキストは完全一致でもY座標が近似でない場合
if !(value_Yave-tolerance...value_Yave+tolerance ~= key_Yave) {
matchKeyArray.removeAtIndex(i)
matchValueArray.removeAtIndex(i)
}
}
//matchValueArray内の重複を削除
let orderedSet = NSOrderedSet(array: matchValueArray)
let removedArray = orderedSet.array as! [Int]
matchValueArray = removedArray
//重複と判断されたcharinfoArrayの添字をもとに削除する
for i in (0..<matchValueArray.count).reverse() {
removedcharinfoArray.removeAtIndex(matchValueArray[i])
}
return removedcharinfoArray
}
/**
xは昇順,y座標は降順(PDFテキストの上から順)に並び替える
- parameter charinfo: ソートを行いたいCharInfoが格納された2次元配列
- returns: ソート後のCharInfoが格納された2次元配列
*/
func SortcharinfoArray(charinfo: [[CharInfo]]) -> [[CharInfo]] {
var sorted = charinfo
sorted.sortInPlace { $0[0].y > $1[0].y }
for i in 0..<sorted.count {
sorted[i].sortInPlace { $0.x < $1.x }
}
return sorted
}
/**
引数で渡された配列のy座標の平均を求めて返す
- parameter charinfo: y座標の平均を求めたいCharInfoが格納された1次元配列
- returns: y座標の平均値
*/
func Get_Y_Average(charinfo: [CharInfo]) -> Double {
var sum = 0.0
for i in 0..<charinfo.count {
sum += charinfo[i].y
}
return (sum/Double(charinfo.count))
}
/**
平均値の配列をもとに誤差許容範囲内同士の配列を結合する関数
- parameter aveArray: 平均値が格納された1次元配列(aveArray[i]の値はcharinfo[i]の平均値)
- parameter charinfo: CharInfoが格納された2次元配列
- returns: y座標が近似している配列を結合した2次元配列
*/
func UnionArrayByY(aveArray: [Double], charinfo: [[CharInfo]]) -> [[CharInfo]]{
var unionedArray = charinfo
var pivot_index = 0
var pivot = 0.0
var grouping: [[Int]] = [[]]
var grouping_index = 0
//aveArrayの値が近いもの同士を記録する
for i in 0..<charinfo.count - 1 {
pivot = aveArray[pivot_index]
if (pivot-tolerance...pivot+tolerance ~= aveArray[i+1]) {
grouping[grouping_index].append(i)
grouping[grouping_index].append(i+1)
}else {
pivot_index = i+1
grouping_index += 1
grouping.append([])
}
}
//grouping内の空配列を削除する
for i in (0..<grouping.count).reverse() {
if grouping[i].isEmpty {
grouping.removeAtIndex(i)
}
}
//grouping内で重複している要素を削除
for i in 0..<grouping.count {
let groupingArray = grouping[i]
let orderedSet = NSOrderedSet(array: groupingArray)
let removedArray = orderedSet.array as! [Int]
grouping[i] = removedArray
}
//groupingをもとにunionedArrayの配列同士を結合する
for i in (0..<grouping.count).reverse() {
for j in (0..<grouping[i].count - 1).reverse() {
let index1 = grouping[i][j]
let index2 = grouping[i][j+1]
unionedArray[index1] += unionedArray[index2]
unionedArray.removeAtIndex(index2)
}
}
//順番を整える
unionedArray = SortcharinfoArray(unionedArray)
return unionedArray
}
/**
CharInfoのテキストをわかりやすく表示するテスト関数
- parameter charinfo: 表示したいCharInfoが格納された2次元配列
*/
func ShowAllcharinfoArray(charinfo: [[CharInfo]]) {
for i in 0..<charinfo.count {
print(String(i) + ": ", terminator: "")
for j in 0..<charinfo[i].count {
let charinfo = charinfo[i][j]
print(charinfo.text, terminator: "")
}
print("")
}
}
/**
CharInfoの1オブジェクトを受け取ってテキストを結合した文字列を取得する
- parameter charinfo: 結合した文字列を取得したいCharInfoオブジェクト
- returns: 結合した文字列
*/
func GetLineText(charinfo: [CharInfo]) -> String {
var linetext = ""
for i in 0..<charinfo.count {
linetext += charinfo[i].text
}
return linetext
}
/**
不要な行の削除をする
- parameter charinfo: 不要な行が含まれたCharInfoを格納している2次元配列
- returns: 不要な行を削除したCharInfoを格納している2次元配列
*/
func RemoveUnnecessaryLines(charinfo: [[CharInfo]]) -> [[CharInfo]] {
var removed = charinfo
var pivot_index = 0
//平成xx年度の行を見つける
for i in 0..<charinfo.count {
let linetext = GetLineText(charinfo[i])
if linetext.containsString("平成") {
pivot_index = i
break
}
}
//平成xx年度の行より上の行を取り除く
for i in (0..<pivot_index).reverse() {
removed.removeAtIndex(i)
}
//スタッフ名が含まれている行を記録する
let staffnameArray = DBmethod().StaffNameArrayGet()
//各行にスタッフ名が含まれているかを検索
var contains_staffname_line:[Int] = []
for i in 0..<removed.count {
let linetext = GetLineText(removed[i])
for j in 0..<staffnameArray!.count {
if linetext.containsString(staffnameArray![j]) {
contains_staffname_line.append(i)
break
}
}
}
//スタッフ名が含まれていない行を削除
for i in (1..<removed.count).reverse() {
if contains_staffname_line.indexOf(i) == nil {
removed.removeAtIndex(i)
}
}
//先頭文字が数字でない行を削除
for i in (1..<removed.count).reverse() {
if Int(removed[i][0].text) == nil {
removed.removeAtIndex(i)
}
}
return removed
}
/**
スタッフがデータベースに登録されているかチェック
- returns: 1名でも登録されていたらtrue、未登録ならfalse
*/
func CheckStaffNameDB() -> Bool {
let number_of_people = DBmethod().StaffNameAllRecordGet()
if number_of_people != nil {
return true
}else{
//アラート表示
let alert: UIAlertController = UIAlertController(title: "取り込みエラー", message: "設定画面でスタッフを登録して下さい", preferredStyle: UIAlertControllerStyle.Alert)
let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{
(action: UIAlertAction!) -> Void in
})
alert.addAction(defaultAction)
self.presentViewController(alert, animated: true, completion: nil)
return false
}
}
/**
1クールが何日あるか、取り込んだシフトの年月を取得する
- parameter text: 平成xx年度が記述された文字列
- returns: year: シフトの年度(和暦)
startcoursmonth: 10日〜30日(31日)までの月
startcoursmonthyear: 10日〜30日(31日)までの年(和暦)
endcoursmonth: 1日〜10日までの月
endcoursmonthyear: 1日〜10日までの年(和暦)
length: 1クールの日数
*/
func GetShiftYearMonth(text: String) -> ((year: Int, startcoursmonth: Int, startcoursmonthyear: Int, endcoursmonth: Int, endcoursmonthyear: Int), length: Int){
//1クールが全部で何日間あるかを判断するため
let shiftyearandmonth = CommonMethod().JudgeYearAndMonth(text)
let monthrange = CommonMethod().GetShiftCoursMonthRange(shiftyearandmonth.startcoursmonthyear, shiftstartmonth: shiftyearandmonth.startcoursmonth)
let length = monthrange.length
return (shiftyearandmonth,length)
}
/**
全スタッフ分の1ごとのシフトを取得する
- parameter charinfo: 平成xx年度とスタッフのシフトが記述された行が格納されたcharinfo2次元配列
- returns: スタッフごとにシフト名を格納したString2次元配列
*/
func GetSplitShiftAllStaffByDay(charinfo: [[CharInfo]]) -> [[String]]{
var splitdayshift: [[String]] = []
let staffnumber = DBmethod().StaffNumberGet()
let staffnameDBArray = DBmethod().StaffNameArrayGet()
//登録したスタッフの人数分だけループする
for i in 1...staffnumber {
var staffname = ""
let one_person_charinfo = charinfo[i]
let one_person_textline = GetLineText(one_person_charinfo)
//名前検索
for j in 0..<staffnameDBArray!.count {
if one_person_textline.containsString(staffnameDBArray![j]) == true {
staffname = staffnameDBArray![j]
break
}
}
//シフト文字の始まりの場所を記録する
var shift_start = 0
let staffname_end_char = staffname[staffname.endIndex.predecessor()]
for j in 0..<one_person_charinfo.count {
let text = one_person_charinfo[j].text
if text == String(staffname_end_char) {
shift_start = j+1
break
}
}
//TODO: ここからx座標をもとに判断していく
}
return splitdayshift
}
}
脱字を修正
//
// PDFmethod2.swift
// masamon
//
// Created by 岩見建汰 on 2016/08/13.
// Copyright © 2016年 Kenta. All rights reserved.
//
import UIKit
/**
* pdfから抽出したテキスト情報を格納する構造体
*/
struct CharInfo {
var text = ""
var x = 0.0
var y = 0.0
var size = 0.0
}
class PDFmethod2: UIViewController {
let tolerance = 3.0 //同じ行と判定させるための許容誤差
/**
実行用のメソッド
*/
func RunPDFmethod() {
let charinfoArray = GetPDFGlyphInfo()
let removed_overlap = RemoveOverlapArray(charinfoArray)
var sorted = SortcharinfoArray(removed_overlap)
//各配列のY座標の平均値を求める
var YaverageArray: [Double] = []
for i in 0..<sorted.count {
YaverageArray.append(Get_Y_Average(sorted[i]))
}
let unioned = UnionArrayByY(YaverageArray, charinfo: sorted)
//スタッフ名が登録されている場合のみ処理を進める
if CheckStaffNameDB() == true {
let removed_unnecessary = RemoveUnnecessaryLines(unioned)
GetSplitShiftAllStaffByDay(removed_unnecessary)
}
}
/**
pdfのテキスト情報を2次元配列に行ごとに格納する
- returns: y座標が近似しているCharInfo同士を2次元配列に格納したもの
*/
func GetPDFGlyphInfo() -> [[CharInfo]] {
var charinfoArray: [[CharInfo]] = []
var prev_y = -99.99
var currentArrayIndex = -1
let path: NSString
//path = DBmethod().FilePathTmpGet()
path = NSBundle.mainBundle().pathForResource("8.11〜", ofType: "pdf")!
let tet = TET()
let document = tet.open_document(path as String, optlist: "")
let page = tet.open_page(document, pagenumber: 1, optlist: "granularity=glyph")
var text = tet.get_text(page)
//全テキストを検査するループ
while(text != nil && text.characters.count > 0){
while(tet.get_char_info(page) > 0){
var charinfo = CharInfo()
charinfo.text = text.hankakuOnly
charinfo.text = ReplaceHankakuSymbol(charinfo.text)
charinfo.size = tet.fontsize()
charinfo.x = tet.x()
charinfo.y = tet.y()
if !(prev_y-tolerance...prev_y+tolerance ~= tet.y()) {
prev_y = tet.y()
charinfoArray.append([])
currentArrayIndex += 1
}
charinfoArray[currentArrayIndex].append(charinfo)
}
text = tet.get_text(page)
}
tet.close_page(page)
tet.close_document(document)
return charinfoArray
}
/**
- parameter text: 全角記号を半角記号に置き換える
- returns: 半角記号に置き換えた後の文字列
*/
func ReplaceHankakuSymbol(text: String) -> String {
let pattern_zenkaku = ["(", ")", "/"]
let pattern_hankaku = ["(", ")", "/"]
var hankaku_text = text
for i in 0..<pattern_hankaku.count {
hankaku_text = hankaku_text.stringByReplacingOccurrencesOfString(pattern_zenkaku[i], withString: pattern_hankaku[i])
}
return hankaku_text
}
/**
内容が重複している配列を削除する
- parameter charinfoArray: CharInfoを格納した2次元配列
- returns: テキストは完全一致,y座標は近似している配列(余分に存在する配列)を削除した配列
*/
func RemoveOverlapArray(charinfoArray: [[CharInfo]]) -> [[CharInfo]] {
var removedcharinfoArray = charinfoArray
var matchKeyArray: [Int] = [] //比較対象元(添字が小さい)
var matchValueArray: [Int] = [] //比較対象先(添字が大きい)
var match_count = 0
//テキストが重複している配列の中身を検出する
for i in 0..<charinfoArray.count - 1 {
for j in i+1..<charinfoArray.count {
if charinfoArray[i].count == charinfoArray[j].count {
for k in 0..<charinfoArray[i].count {
let charinfo1 = charinfoArray[i][k]
let charinfo2 = charinfoArray[j][k]
if charinfo1.text == charinfo2.text {
match_count += 1
}else {
break
}
}
//テキストが全て一致したかを判断する
if match_count == charinfoArray[i].count {
matchKeyArray.append(i)
matchValueArray.append(j)
}
match_count = 0
}
}
}
//matchkey,value配列からY座標の平均値が全く異なるものを外す処理
for i in (0..<matchKeyArray.count).reverse() {
let key_Yave = Get_Y_Average(charinfoArray[matchKeyArray[i]])
let value_Yave = Get_Y_Average(charinfoArray[matchValueArray[i]])
//テキストは完全一致でもY座標が近似でない場合
if !(value_Yave-tolerance...value_Yave+tolerance ~= key_Yave) {
matchKeyArray.removeAtIndex(i)
matchValueArray.removeAtIndex(i)
}
}
//matchValueArray内の重複を削除
let orderedSet = NSOrderedSet(array: matchValueArray)
let removedArray = orderedSet.array as! [Int]
matchValueArray = removedArray
//重複と判断されたcharinfoArrayの添字をもとに削除する
for i in (0..<matchValueArray.count).reverse() {
removedcharinfoArray.removeAtIndex(matchValueArray[i])
}
return removedcharinfoArray
}
/**
xは昇順,y座標は降順(PDFテキストの上から順)に並び替える
- parameter charinfo: ソートを行いたいCharInfoが格納された2次元配列
- returns: ソート後のCharInfoが格納された2次元配列
*/
func SortcharinfoArray(charinfo: [[CharInfo]]) -> [[CharInfo]] {
var sorted = charinfo
sorted.sortInPlace { $0[0].y > $1[0].y }
for i in 0..<sorted.count {
sorted[i].sortInPlace { $0.x < $1.x }
}
return sorted
}
/**
引数で渡された配列のy座標の平均を求めて返す
- parameter charinfo: y座標の平均を求めたいCharInfoが格納された1次元配列
- returns: y座標の平均値
*/
func Get_Y_Average(charinfo: [CharInfo]) -> Double {
var sum = 0.0
for i in 0..<charinfo.count {
sum += charinfo[i].y
}
return (sum/Double(charinfo.count))
}
/**
平均値の配列をもとに誤差許容範囲内同士の配列を結合する関数
- parameter aveArray: 平均値が格納された1次元配列(aveArray[i]の値はcharinfo[i]の平均値)
- parameter charinfo: CharInfoが格納された2次元配列
- returns: y座標が近似している配列を結合した2次元配列
*/
func UnionArrayByY(aveArray: [Double], charinfo: [[CharInfo]]) -> [[CharInfo]]{
var unionedArray = charinfo
var pivot_index = 0
var pivot = 0.0
var grouping: [[Int]] = [[]]
var grouping_index = 0
//aveArrayの値が近いもの同士を記録する
for i in 0..<charinfo.count - 1 {
pivot = aveArray[pivot_index]
if (pivot-tolerance...pivot+tolerance ~= aveArray[i+1]) {
grouping[grouping_index].append(i)
grouping[grouping_index].append(i+1)
}else {
pivot_index = i+1
grouping_index += 1
grouping.append([])
}
}
//grouping内の空配列を削除する
for i in (0..<grouping.count).reverse() {
if grouping[i].isEmpty {
grouping.removeAtIndex(i)
}
}
//grouping内で重複している要素を削除
for i in 0..<grouping.count {
let groupingArray = grouping[i]
let orderedSet = NSOrderedSet(array: groupingArray)
let removedArray = orderedSet.array as! [Int]
grouping[i] = removedArray
}
//groupingをもとにunionedArrayの配列同士を結合する
for i in (0..<grouping.count).reverse() {
for j in (0..<grouping[i].count - 1).reverse() {
let index1 = grouping[i][j]
let index2 = grouping[i][j+1]
unionedArray[index1] += unionedArray[index2]
unionedArray.removeAtIndex(index2)
}
}
//順番を整える
unionedArray = SortcharinfoArray(unionedArray)
return unionedArray
}
/**
CharInfoのテキストをわかりやすく表示するテスト関数
- parameter charinfo: 表示したいCharInfoが格納された2次元配列
*/
func ShowAllcharinfoArray(charinfo: [[CharInfo]]) {
for i in 0..<charinfo.count {
print(String(i) + ": ", terminator: "")
for j in 0..<charinfo[i].count {
let charinfo = charinfo[i][j]
print(charinfo.text, terminator: "")
}
print("")
}
}
/**
CharInfoの1オブジェクトを受け取ってテキストを結合した文字列を取得する
- parameter charinfo: 結合した文字列を取得したいCharInfoオブジェクト
- returns: 結合した文字列
*/
func GetLineText(charinfo: [CharInfo]) -> String {
var linetext = ""
for i in 0..<charinfo.count {
linetext += charinfo[i].text
}
return linetext
}
/**
不要な行の削除をする
- parameter charinfo: 不要な行が含まれたCharInfoを格納している2次元配列
- returns: 不要な行を削除したCharInfoを格納している2次元配列
*/
func RemoveUnnecessaryLines(charinfo: [[CharInfo]]) -> [[CharInfo]] {
var removed = charinfo
var pivot_index = 0
//平成xx年度の行を見つける
for i in 0..<charinfo.count {
let linetext = GetLineText(charinfo[i])
if linetext.containsString("平成") {
pivot_index = i
break
}
}
//平成xx年度の行より上の行を取り除く
for i in (0..<pivot_index).reverse() {
removed.removeAtIndex(i)
}
//スタッフ名が含まれている行を記録する
let staffnameArray = DBmethod().StaffNameArrayGet()
//各行にスタッフ名が含まれているかを検索
var contains_staffname_line:[Int] = []
for i in 0..<removed.count {
let linetext = GetLineText(removed[i])
for j in 0..<staffnameArray!.count {
if linetext.containsString(staffnameArray![j]) {
contains_staffname_line.append(i)
break
}
}
}
//スタッフ名が含まれていない行を削除
for i in (1..<removed.count).reverse() {
if contains_staffname_line.indexOf(i) == nil {
removed.removeAtIndex(i)
}
}
//先頭文字が数字でない行を削除
for i in (1..<removed.count).reverse() {
if Int(removed[i][0].text) == nil {
removed.removeAtIndex(i)
}
}
return removed
}
/**
スタッフがデータベースに登録されているかチェック
- returns: 1名でも登録されていたらtrue、未登録ならfalse
*/
func CheckStaffNameDB() -> Bool {
let number_of_people = DBmethod().StaffNameAllRecordGet()
if number_of_people != nil {
return true
}else{
//アラート表示
let alert: UIAlertController = UIAlertController(title: "取り込みエラー", message: "設定画面でスタッフを登録して下さい", preferredStyle: UIAlertControllerStyle.Alert)
let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{
(action: UIAlertAction!) -> Void in
})
alert.addAction(defaultAction)
self.presentViewController(alert, animated: true, completion: nil)
return false
}
}
/**
1クールが何日あるか、取り込んだシフトの年月を取得する
- parameter text: 平成xx年度が記述された文字列
- returns: year: シフトの年度(和暦)
startcoursmonth: 10日〜30日(31日)までの月
startcoursmonthyear: 10日〜30日(31日)までの年(和暦)
endcoursmonth: 1日〜10日までの月
endcoursmonthyear: 1日〜10日までの年(和暦)
length: 1クールの日数
*/
func GetShiftYearMonth(text: String) -> ((year: Int, startcoursmonth: Int, startcoursmonthyear: Int, endcoursmonth: Int, endcoursmonthyear: Int), length: Int){
//1クールが全部で何日間あるかを判断するため
let shiftyearandmonth = CommonMethod().JudgeYearAndMonth(text)
let monthrange = CommonMethod().GetShiftCoursMonthRange(shiftyearandmonth.startcoursmonthyear, shiftstartmonth: shiftyearandmonth.startcoursmonth)
let length = monthrange.length
return (shiftyearandmonth,length)
}
/**
全スタッフ分の1日ごとのシフトを取得する
- parameter charinfo: 平成xx年度とスタッフのシフトが記述された行が格納されたcharinfo2次元配列
- returns: スタッフごとにシフト名を格納したString2次元配列
*/
func GetSplitShiftAllStaffByDay(charinfo: [[CharInfo]]) -> [[String]]{
var splitdayshift: [[String]] = []
let staffnumber = DBmethod().StaffNumberGet()
let staffnameDBArray = DBmethod().StaffNameArrayGet()
//登録したスタッフの人数分だけループする
for i in 1...staffnumber {
var staffname = ""
let one_person_charinfo = charinfo[i]
let one_person_textline = GetLineText(one_person_charinfo)
//名前検索
for j in 0..<staffnameDBArray!.count {
if one_person_textline.containsString(staffnameDBArray![j]) == true {
staffname = staffnameDBArray![j]
break
}
}
//シフト文字の始まりの場所を記録する
var shift_start = 0
let staffname_end_char = staffname[staffname.endIndex.predecessor()]
for j in 0..<one_person_charinfo.count {
let text = one_person_charinfo[j].text
if text == String(staffname_end_char) {
shift_start = j+1
break
}
}
//TODO: ここからx座標をもとに判断していく
}
return splitdayshift
}
}
|
import PackageDescription
let package = Package(
name: "CLibpq"
)
fix indentation
import PackageDescription
let package = Package(
name: "CLibpq"
) |
/**
* Copyright IBM Corporation 2016
*
* 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 PackageDescription
let package = Package(
name: "Kitura",
targets: [
Target(
name: "KituraSample",
dependencies: [])
],
dependencies: [
.Package(url: "https://github.com/IBM-Swift/Kitura-router.git", majorVersion: 0),
//.Package(url: "git@github.com:IBM-Swift/Kitura-router.git", majorVersion: 0),
.Package(url: "https://github.com/IBM-Swift/HeliumLogger.git", versions: Version(0,0,0)..<Version(0,1,0)),
//.Package(url: "git@github.com:IBM-Swift/HeliumLogger.git", versions: Version(0,0,0)..<Version(0,1,0)),
.Package(url: "https://github.com/IBM-Swift/LoggerAPI.git", majorVersion: 0),
//.Package(url: "git@github.com:IBM-Swift/LoggerAPI.git", majorVersion: 0),
.Package(url: "https://github.com/IBM-Swift/Kitura-TestFramework.git", majorVersion: 0),
//.Package(url: "git@github.com:IBM-Swift/Kitura-TestFramework.git", majorVersion: 0),
]
)
#if os(OSX)
//package.dependencies.append(.Package(url: "git@github.com:IBM-Swift/GRMustache.swift.git", majorVersion: 1))
package.dependencies.append(.Package(url: "https://github.com/IBM-Swift/GRMustache.swift.git", majorVersion: 1))
#endif
Updated dependency version numbers.
/**
* Copyright IBM Corporation 2016
*
* 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 PackageDescription
let package = Package(
name: "Kitura",
targets: [
Target(
name: "KituraSample",
dependencies: [])
],
dependencies: [
.Package(url: "https://github.com/IBM-Swift/Kitura-router.git", versions: Version(0,2,0)..<Version(0,3,0)),
//.Package(url: "git@github.com:IBM-Swift/Kitura-router.git", majorVersion: 0),
.Package(url: "https://github.com/IBM-Swift/HeliumLogger.git", versions: Version(0,2,0)..<Version(0,3,0)),
//.Package(url: "git@github.com:IBM-Swift/HeliumLogger.git", versions: Version(0,0,0)..<Version(0,1,0)),
.Package(url: "https://github.com/IBM-Swift/LoggerAPI.git", versions: Version(0,2,0)..<Version(0,3,0)),
//.Package(url: "git@github.com:IBM-Swift/LoggerAPI.git", majorVersion: 0),
.Package(url: "https://github.com/IBM-Swift/Kitura-TestFramework.git", versions: Version(0,2,0)..<Version(0,3,0)),
//.Package(url: "git@github.com:IBM-Swift/Kitura-TestFramework.git", majorVersion: 0),
]
)
#if os(OSX)
//package.dependencies.append(.Package(url: "git@github.com:IBM-Swift/GRMustache.swift.git", majorVersion: 1))
package.dependencies.append(.Package(url: "https://github.com/IBM-Swift/GRMustache.swift.git", majorVersion: 1))
#endif
|
import PackageDescription
let package = Package(
name: "langserver-swift",
targets: [
Target(name: "JSONRPC"),
Target(name: "LanguageServerProtocol", dependencies: ["JSONRPC"]),
Target(name: "LanguageServer", dependencies: ["LanguageServerProtocol", "JSONRPC"])
],
dependencies: [
.Package(url: "https://github.com/IBM-Swift/BlueSocket.git", majorVersion: 0, minor: 11),
.Package(url: "https://github.com/RLovelett/SourceKitten.git", majorVersion: 0),
.Package(url: "https://github.com/thoughtbot/Argo.git", majorVersion: 4),
.Package(url: "https://github.com/thoughtbot/Curry.git", majorVersion: 3)
]
)
Remove BlueSocket as a dependency (no longer support TCP)
import PackageDescription
let package = Package(
name: "langserver-swift",
targets: [
Target(name: "JSONRPC"),
Target(name: "LanguageServerProtocol", dependencies: ["JSONRPC"]),
Target(name: "LanguageServer", dependencies: ["LanguageServerProtocol", "JSONRPC"])
],
dependencies: [
.Package(url: "https://github.com/RLovelett/SourceKitten.git", majorVersion: 0),
.Package(url: "https://github.com/thoughtbot/Argo.git", majorVersion: 4),
.Package(url: "https://github.com/thoughtbot/Curry.git", majorVersion: 3)
]
)
|
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "GitignoreIO",
dependencies: [
.package(
url: "https://github.com/vapor/vapor.git",
from: "3.1.0"
),
.package(
url: "https://github.com/vapor/leaf.git",
from: "3.0.0"
),
.package(
url: "https://github.com/vapor-community/lingo-vapor.git",
from: "3.0.0"
)
],
targets: [
.target(
name: "App",
dependencies: ["Vapor", "Leaf", "LingoVapor"],
path:
exclude: ["Config", "Localization", "Public", "Resources", "data", "wiki"]
),
.target(
name: "Run",
dependencies: ["App"],
exclude: ["Config", "Localization", "Public", "Resources", "data", "wiki"]
),
.testTarget(
name: "AppTests",
dependencies: ["App"]
)
]
)
Fix package.swift
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "GitignoreIO",
dependencies: [
.package(
url: "https://github.com/vapor/vapor.git",
from: "3.1.0"
),
.package(
url: "https://github.com/vapor/leaf.git",
from: "3.0.0"
),
.package(
url: "https://github.com/vapor-community/lingo-vapor.git",
from: "3.0.0"
)
],
targets: [
.target(
name: "App",
dependencies: ["Vapor", "Leaf", "LingoVapor"],
exclude: ["Config", "Localization", "Public", "Resources", "data", "wiki"]
),
.target(
name: "Run",
dependencies: ["App"],
exclude: ["Config", "Localization", "Public", "Resources", "data", "wiki"]
),
.testTarget(
name: "AppTests",
dependencies: ["App"]
)
]
)
|
import PackageDescription
let package = Package(
name: "MySQL",
dependencies: [
// Module map for `libmysql`
.Package(url: "https://github.com/collinhundley/CMariaDB.git", majorVersion: 0),
// Data structure for converting between multiple representations
.Package(url: "https://github.com/vapor/node.git", majorVersion: 0, minor: 4),
// Core extensions, type-aliases, and functions that facilitate common tasks
.Package(url: "https://github.com/vapor/core.git", majorVersion: 0, minor: 3),
// JSON parsing and serialization for storing arrays and objects in MySQL
.Package(url: "https://github.com/vapor/json.git", majorVersion: 0, minor: 4)
]
)
MariaDB test
import PackageDescription
let package = Package(
name: "MySQL",
dependencies: [
// Module map for `libmysql`
.Package(url: "https://github.com/collinhundley/cmysql.git", majorVersion: 0),
// Data structure for converting between multiple representations
.Package(url: "https://github.com/vapor/node.git", majorVersion: 0, minor: 4),
// Core extensions, type-aliases, and functions that facilitate common tasks
.Package(url: "https://github.com/vapor/core.git", majorVersion: 0, minor: 3),
// JSON parsing and serialization for storing arrays and objects in MySQL
.Package(url: "https://github.com/vapor/json.git", majorVersion: 0, minor: 4)
]
)
|
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "Web",
products: [
.library(name: "ApplicativeRouter", targets: ["ApplicativeRouter"]),
.library(name: "ApplicativeRouterHttpPipelineSupport",
targets: ["ApplicativeRouterHttpPipelineSupport"]),
.library(name: "Css", targets: ["Css"]),
.library(name: "CssReset", targets: ["CssReset"]),
.library(name: "CssTestSupport", targets: ["CssTestSupport"]),
.library(name: "HtmlCssSupport", targets: ["HtmlCssSupport"]),
.library(name: "HtmlPlainTextPrint", targets: ["HtmlPlainTextPrint"]),
.library(name: "HttpPipeline", targets: ["HttpPipeline"]),
// .executable(name: "HttpPipelineExample", targets: ["HttpPipelineExample"]),
.library(name: "HttpPipelineHtmlSupport", targets: ["HttpPipelineHtmlSupport"]),
.library(name: "HttpPipelineTestSupport", targets: ["HttpPipelineTestSupport"]),
.library(name: "UrlFormEncoding", targets: ["UrlFormEncoding"]),
.library(name: "View", targets: ["View"])
],
dependencies: [
.package(url: "https://github.com/pointfreeco/swift-html", from: "0.2.1"),
.package(url: "https://github.com/pointfreeco/swift-prelude.git", .revision("6e426b0")),
.package(url: "https://github.com/pointfreeco/swift-snapshot-testing.git", .exact("1.1.0")),
.package(url: "https://github.com/apple/swift-nio.git", from: "1.13.0"),
.package(url: "https://github.com/IBM-Swift/BlueCryptor.git", .exact("1.0.23")),
],
targets: [
.target(name: "ApplicativeRouter", dependencies: ["Either", "Optics", "Prelude", "UrlFormEncoding"]),
.testTarget(name: "ApplicativeRouterTests", dependencies: ["ApplicativeRouter", "Optics", "SnapshotTesting", "HttpPipelineTestSupport"]),
.target(name: "ApplicativeRouterHttpPipelineSupport",
dependencies: ["ApplicativeRouter", "HttpPipeline", "Prelude"]),
.testTarget(name: "ApplicativeRouterHttpPipelineSupportTests",
dependencies: ["ApplicativeRouterHttpPipelineSupport", "HttpPipelineTestSupport", "SnapshotTesting"]),
.target(name: "Css", dependencies: ["Either", "Prelude"]),
.testTarget(name: "CssTests", dependencies: ["Css", "CssTestSupport"]),
.target(name: "CssReset", dependencies: ["Css"]),
.testTarget(name: "CssResetTests", dependencies: ["CssReset", "CssTestSupport"]),
.target(name: "CssTestSupport", dependencies: ["Css", "SnapshotTesting"]),
.target(name: "HtmlCssSupport", dependencies: ["Css", "Html"]),
.testTarget(name: "HtmlCssSupportTests", dependencies: ["HtmlCssSupport", "CssTestSupport", "HtmlSnapshotTesting"]),
.target(name: "HtmlPlainTextPrint", dependencies: ["Html", "Prelude"]),
.testTarget(name: "HtmlPlainTextPrintTests", dependencies: ["HtmlPlainTextPrint", "Css", "Html", "HtmlCssSupport", "SnapshotTesting"]),
.target(name: "HttpPipeline",
dependencies: ["Cryptor", "Html", "NIO", "NIOHTTP1", "Prelude", "Optics"]),
// .target(name: "HttpPipelineExample",
// dependencies: ["HttpPipeline", "HttpPipelineHtmlSupport"]),
.testTarget(name: "HttpPipelineTests",
dependencies: ["HttpPipeline", "SnapshotTesting", "HttpPipelineTestSupport"]),
.target(name: "HttpPipelineHtmlSupport", dependencies: ["Html", "HttpPipeline", "View"]),
.testTarget(name: "HttpPipelineHtmlSupportTests", dependencies: ["HttpPipelineHtmlSupport", "SnapshotTesting"]),
.target(name: "HttpPipelineTestSupport", dependencies: ["HttpPipeline", "Html", "SnapshotTesting"]),
.target(name: "UrlFormEncoding", dependencies: ["Prelude", "Optics"]),
.testTarget(name: "UrlFormEncodingTests", dependencies: ["UrlFormEncoding", "SnapshotTesting"]),
.target(name: "View", dependencies: ["Html", "Prelude"]),
]
)
Bump SnapshotTesting
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "Web",
products: [
.library(name: "ApplicativeRouter", targets: ["ApplicativeRouter"]),
.library(name: "ApplicativeRouterHttpPipelineSupport",
targets: ["ApplicativeRouterHttpPipelineSupport"]),
.library(name: "Css", targets: ["Css"]),
.library(name: "CssReset", targets: ["CssReset"]),
.library(name: "CssTestSupport", targets: ["CssTestSupport"]),
.library(name: "HtmlCssSupport", targets: ["HtmlCssSupport"]),
.library(name: "HtmlPlainTextPrint", targets: ["HtmlPlainTextPrint"]),
.library(name: "HttpPipeline", targets: ["HttpPipeline"]),
// .executable(name: "HttpPipelineExample", targets: ["HttpPipelineExample"]),
.library(name: "HttpPipelineHtmlSupport", targets: ["HttpPipelineHtmlSupport"]),
.library(name: "HttpPipelineTestSupport", targets: ["HttpPipelineTestSupport"]),
.library(name: "UrlFormEncoding", targets: ["UrlFormEncoding"]),
.library(name: "View", targets: ["View"])
],
dependencies: [
.package(url: "https://github.com/pointfreeco/swift-html", from: "0.2.1"),
.package(url: "https://github.com/pointfreeco/swift-prelude.git", .revision("6e426b0")),
.package(url: "https://github.com/pointfreeco/swift-snapshot-testing.git", .exact("1.2.0")),
.package(url: "https://github.com/apple/swift-nio.git", from: "1.13.0"),
.package(url: "https://github.com/IBM-Swift/BlueCryptor.git", .exact("1.0.23")),
],
targets: [
.target(name: "ApplicativeRouter", dependencies: ["Either", "Optics", "Prelude", "UrlFormEncoding"]),
.testTarget(name: "ApplicativeRouterTests", dependencies: ["ApplicativeRouter", "Optics", "SnapshotTesting", "HttpPipelineTestSupport"]),
.target(name: "ApplicativeRouterHttpPipelineSupport",
dependencies: ["ApplicativeRouter", "HttpPipeline", "Prelude"]),
.testTarget(name: "ApplicativeRouterHttpPipelineSupportTests",
dependencies: ["ApplicativeRouterHttpPipelineSupport", "HttpPipelineTestSupport", "SnapshotTesting"]),
.target(name: "Css", dependencies: ["Either", "Prelude"]),
.testTarget(name: "CssTests", dependencies: ["Css", "CssTestSupport"]),
.target(name: "CssReset", dependencies: ["Css"]),
.testTarget(name: "CssResetTests", dependencies: ["CssReset", "CssTestSupport"]),
.target(name: "CssTestSupport", dependencies: ["Css", "SnapshotTesting"]),
.target(name: "HtmlCssSupport", dependencies: ["Css", "Html"]),
.testTarget(name: "HtmlCssSupportTests", dependencies: ["HtmlCssSupport", "CssTestSupport", "HtmlSnapshotTesting"]),
.target(name: "HtmlPlainTextPrint", dependencies: ["Html", "Prelude"]),
.testTarget(name: "HtmlPlainTextPrintTests", dependencies: ["HtmlPlainTextPrint", "Css", "Html", "HtmlCssSupport", "SnapshotTesting"]),
.target(name: "HttpPipeline",
dependencies: ["Cryptor", "Html", "NIO", "NIOHTTP1", "Prelude", "Optics"]),
// .target(name: "HttpPipelineExample",
// dependencies: ["HttpPipeline", "HttpPipelineHtmlSupport"]),
.testTarget(name: "HttpPipelineTests",
dependencies: ["HttpPipeline", "SnapshotTesting", "HttpPipelineTestSupport"]),
.target(name: "HttpPipelineHtmlSupport", dependencies: ["Html", "HttpPipeline", "View"]),
.testTarget(name: "HttpPipelineHtmlSupportTests", dependencies: ["HttpPipelineHtmlSupport", "SnapshotTesting"]),
.target(name: "HttpPipelineTestSupport", dependencies: ["HttpPipeline", "Html", "SnapshotTesting"]),
.target(name: "UrlFormEncoding", dependencies: ["Prelude", "Optics"]),
.testTarget(name: "UrlFormEncodingTests", dependencies: ["UrlFormEncoding", "SnapshotTesting"]),
.target(name: "View", dependencies: ["Html", "Prelude"]),
]
)
|
// swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Segment",
platforms: [
.iOS(.v10), .tvOS(.v10), .macOS(.v10_13)
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "Segment",
targets: ["Segment"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "Segment",
dependencies: [],
path: "Segment/",
exclude: ["SwiftSources"],
sources: ["Classes", "Internal"],
publicHeadersPath: "Classes",
cSettings: [
.headerSearchPath("Internal"),
.headerSearchPath("Classes")
]
)
]
)
removed unused exclude (#1016)
// swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Segment",
platforms: [
.iOS(.v10), .tvOS(.v10), .macOS(.v10_13)
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "Segment",
targets: ["Segment"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "Segment",
dependencies: [],
path: "Segment/",
sources: ["Classes", "Internal"],
publicHeadersPath: "Classes",
cSettings: [
.headerSearchPath("Internal"),
.headerSearchPath("Classes")
]
)
]
)
|
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "MixCache",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "MixCache",
targets: ["MixCache"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "MixCache",
dependencies: [],
path: "MixCache/MixCache",),
.testTarget(
name: "MixCacheTests",
dependencies: ["MixCache"],
path: "MixCache/MixCacheTests",),
]
)
fix package
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "MixCache",
platforms: [.iOS(.v9)],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(name: "MixCache", targets: ["MixCache"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "MixCache",
dependencies: [],
path: "MixCache/MixCache"),
.testTarget(
name: "MixCacheTests",
dependencies: ["MixCache"],
path: "MixCache/MixCacheTests"),
],
swiftLanguageVersions: [.v5])
)
|
// swift-tools-version:5.3
import PackageDescription
let rocketIfNeeded: [Package.Dependency]
#if os(OSX) || os(Linux)
rocketIfNeeded = [
// .package(url: "https://github.com/shibapm/Rocket", .upToNextMajor(from: "1.2.0")) // dev
]
#else
rocketIfNeeded = []
#endif
let package = Package(
name: "Moya",
platforms: [
.macOS(.v10_12),
.iOS(.v10),
.tvOS(.v10),
.watchOS(.v3)
],
products: [
.library(name: "Moya", targets: ["Moya"]),
.library(name: "CombineMoya", targets: ["CombineMoya"]),
.library(name: "ReactiveMoya", targets: ["ReactiveMoya"]),
.library(name: "RxMoya", targets: ["RxMoya"])
],
dependencies: [
.package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.0.0")),
.package(url: "https://github.com/ReactiveCocoa/ReactiveSwift.git", .upToNextMajor(from: "6.0.0")),
.package(url: "https://github.com/ReactiveX/RxSwift.git", .upToNextMajor(from: "6.0.0")),
// .package(url: "https://github.com/Quick/Quick.git", .upToNextMajor(from: "4.0.0")), // dev
// .package(url: "https://github.com/Quick/Nimble.git", .upToNextMajor(from: "9.0.0")), // dev
// .package(url: "https://github.com/AliSoftware/OHHTTPStubs.git", .upToNextMajor(from: "9.0.0")) // dev
] + rocketIfNeeded,
targets: [
.target(
name: "Moya",
dependencies: [
.product(name: "Alamofire", package: "Alamofire")
],
exclude: [
"Supporting Files/Info.plist"
]
),
.target(
name: "CombineMoya",
dependencies: [
"Moya"
]
),
.target(
name: "ReactiveMoya",
dependencies: [
"Moya",
.product(name: "ReactiveSwift", package: "ReactiveSwift")
]
),
.target(
name: "RxMoya",
dependencies: [
"Moya",
.product(name: "RxSwift", package: "RxSwift")
]
),
// .testTarget( // dev
// name: "MoyaTests", // dev
// dependencies: [ // dev
// "Moya", // dev
// "CombineMoya", // dev
// "ReactiveMoya", // dev
// "RxMoya", // dev
// .product(name: "Quick", package: "Quick"), // dev
// .product(name: "Nimble", package: "Nimble"), // dev
// .product(name: "OHHTTPStubsSwift", package: "OHHTTPStubs") // dev
// ] // dev
// ) // dev
]
)
#if canImport(PackageConfig)
import PackageConfig
let config = PackageConfiguration([
"rocket": [
"before": [
"scripts/update_changelog.sh",
"scripts/update_podspec.sh"
],
"after": [
"rake create_release\\[\"$VERSION\"\\]",
"scripts/update_docs_website.sh"
]
]
]).write()
#endif
Unhide dependencies
// swift-tools-version:5.3
import PackageDescription
let rocketIfNeeded: [Package.Dependency]
#if os(OSX) || os(Linux)
rocketIfNeeded = [
.package(url: "https://github.com/shibapm/Rocket", .upToNextMajor(from: "1.2.0")) // dev
]
#else
rocketIfNeeded = []
#endif
let package = Package(
name: "Moya",
platforms: [
.macOS(.v10_12),
.iOS(.v10),
.tvOS(.v10),
.watchOS(.v3)
],
products: [
.library(name: "Moya", targets: ["Moya"]),
.library(name: "CombineMoya", targets: ["CombineMoya"]),
.library(name: "ReactiveMoya", targets: ["ReactiveMoya"]),
.library(name: "RxMoya", targets: ["RxMoya"])
],
dependencies: [
.package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.0.0")),
.package(url: "https://github.com/ReactiveCocoa/ReactiveSwift.git", .upToNextMajor(from: "6.0.0")),
.package(url: "https://github.com/ReactiveX/RxSwift.git", .upToNextMajor(from: "6.0.0")),
.package(url: "https://github.com/Quick/Quick.git", .upToNextMajor(from: "4.0.0")), // dev
.package(url: "https://github.com/Quick/Nimble.git", .upToNextMajor(from: "9.0.0")), // dev
.package(url: "https://github.com/AliSoftware/OHHTTPStubs.git", .upToNextMajor(from: "9.0.0")) // dev
] + rocketIfNeeded,
targets: [
.target(
name: "Moya",
dependencies: [
.product(name: "Alamofire", package: "Alamofire")
],
exclude: [
"Supporting Files/Info.plist"
]
),
.target(
name: "CombineMoya",
dependencies: [
"Moya"
]
),
.target(
name: "ReactiveMoya",
dependencies: [
"Moya",
.product(name: "ReactiveSwift", package: "ReactiveSwift")
]
),
.target(
name: "RxMoya",
dependencies: [
"Moya",
.product(name: "RxSwift", package: "RxSwift")
]
),
.testTarget( // dev
name: "MoyaTests", // dev
dependencies: [ // dev
"Moya", // dev
"CombineMoya", // dev
"ReactiveMoya", // dev
"RxMoya", // dev
.product(name: "Quick", package: "Quick"), // dev
.product(name: "Nimble", package: "Nimble"), // dev
.product(name: "OHHTTPStubsSwift", package: "OHHTTPStubs") // dev
] // dev
) // dev
]
)
#if canImport(PackageConfig)
import PackageConfig
let config = PackageConfiguration([
"rocket": [
"before": [
"scripts/update_changelog.sh",
"scripts/update_podspec.sh"
],
"after": [
"rake create_release\\[\"$VERSION\"\\]",
"scripts/update_docs_website.sh"
]
]
]).write()
#endif
|
import PackageDescription
let package = Package(
name: "Vapor",
dependencies: [
//Standards package. Contains protocols for cross-project compatability.
.Package(url: "https://github.com/open-swift/S4.git", majorVersion: 0, minor: 6),
//Provides critical String functions Foundation is missing on Linux
.Package(url: "https://github.com/Zewo/String.git", majorVersion: 0, minor: 7),
//Parses and serializes JSON - using fork until update core library
.Package(url: "https://github.com/qutheory/pure-json.git", majorVersion: 2, minor: 0),
//Swift wrapper around Sockets, used for built-in HTTP server
.Package(url: "https://github.com/ketzusaka/Hummingbird.git", majorVersion: 1, minor: 7),
//SHA2 + HMAC hashing. Used by the core to create session identifiers.
.Package(url: "https://github.com/CryptoKitten/HMAC.git", majorVersion: 0, minor: 7),
.Package(url: "https://github.com/CryptoKitten/SHA2.git", majorVersion: 0, minor: 7),
//Determines Content-Type for file extensions
.Package(url: "https://github.com/Zewo/MediaType.git", majorVersion: 0, minor: 6)
],
exclude: [
"XcodeProject"
],
targets: [
Target(
name: "Vapor",
dependencies: [
.Target(name: "libc")
]
),
Target(
name: "Development",
dependencies: [
.Target(name: "Vapor")
]
),
Target(
name: "Performance",
dependencies: [
.Target(name: "Vapor")
]
),
Target(
name: "Generator"
)
]
)
add fluent to package
import PackageDescription
let package = Package(
name: "Vapor",
dependencies: [
//Standards package. Contains protocols for cross-project compatability.
.Package(url: "https://github.com/open-swift/S4.git", majorVersion: 0, minor: 6),
//Provides critical String functions Foundation is missing on Linux
.Package(url: "https://github.com/Zewo/String.git", majorVersion: 0, minor: 7),
//Parses and serializes JSON - using fork until update core library
.Package(url: "https://github.com/qutheory/pure-json.git", majorVersion: 2, minor: 0),
//Swift wrapper around Sockets, used for built-in HTTP server
.Package(url: "https://github.com/ketzusaka/Hummingbird.git", majorVersion: 1, minor: 7),
//SHA2 + HMAC hashing. Used by the core to create session identifiers.
.Package(url: "https://github.com/CryptoKitten/HMAC.git", majorVersion: 0, minor: 7),
.Package(url: "https://github.com/CryptoKitten/SHA2.git", majorVersion: 0, minor: 7),
//Determines Content-Type for file extensions
.Package(url: "https://github.com/Zewo/MediaType.git", majorVersion: 0, minor: 6),
//ORM for interacting with databases
.Package(url: "https://github.com/qutheory/fluent.git", majorVersion: 0, minor: 3)
],
exclude: [
"XcodeProject"
],
targets: [
Target(
name: "Vapor",
dependencies: [
.Target(name: "libc")
]
),
Target(
name: "Development",
dependencies: [
.Target(name: "Vapor")
]
),
Target(
name: "Performance",
dependencies: [
.Target(name: "Vapor")
]
),
Target(
name: "Generator"
)
]
)
|
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "DKPhotoGallery",
products: [
.library(
name: "DKPhotoGallery",
targets: ["DKPhotoGallery"]),
],
dependencies: [
.package(url: "https://github.com/kirualex/SwiftyGif.git", from: "5.3.0"),
],
targets: [
.target(
name: "DKPhotoGallery",
dependencies: ["SwiftyGif"],
path: "DKPhotoGallery",
),
]
)
Fix syntax
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "DKPhotoGallery",
products: [
.library(
name: "DKPhotoGallery",
targets: ["DKPhotoGallery"]),
],
dependencies: [
.package(url: "https://github.com/kirualex/SwiftyGif.git", from: "5.3.0"),
],
targets: [
.target(
name: "DKPhotoGallery",
dependencies: ["SwiftyGif"],
path: "DKPhotoGallery"),
]
)
|
import PackageDescription
let package = Package(
name: "Vapor",
dependencies: [
//Standards package. Contains protocols for cross-project compatability.
.Package(url: "https://github.com/open-swift/S4.git", majorVersion: 0, minor: 8),
//Provides critical String functions Foundation is missing on Linux
.Package(url: "https://github.com/Zewo/String.git", majorVersion: 0, minor: 7),
//Parses and serializes JSON - using fork until update core library
.Package(url: "https://github.com/qutheory/pure-json.git", majorVersion: 2, minor: 2),
//Swift wrapper around Sockets, used for built-in HTTP server
.Package(url: "https://github.com/ketzusaka/Hummingbird.git", majorVersion: 1, minor: 9),
//SHA2 + HMAC hashing. Used by the core to create session identifiers.
.Package(url: "https://github.com/CryptoKitten/HMAC.git", majorVersion: 0, minor: 7),
.Package(url: "https://github.com/CryptoKitten/SHA2.git", majorVersion: 0, minor: 7),
//Determines Content-Type for file extensions
.Package(url: "https://github.com/Zewo/MediaType.git", majorVersion: 0, minor: 0), // will be 0.7
//ORM for interacting with databases
.Package(url: "https://github.com/qutheory/fluent.git", majorVersion: 0, minor: 3),
// Allows complex key path subscripts
.Package(url: "https://github.com/qutheory/path-indexable.git", majorVersion: 0, minor: 1)
],
exclude: [
"XcodeProject"
],
targets: [
Target(
name: "Vapor",
dependencies: [
.Target(name: "libc")
]
),
Target(
name: "Development",
dependencies: [
.Target(name: "Vapor")
]
),
Target(
name: "Performance",
dependencies: [
.Target(name: "Vapor")
]
),
Target(
name: "Generator"
)
]
)
media type tagged
import PackageDescription
let package = Package(
name: "Vapor",
dependencies: [
//Standards package. Contains protocols for cross-project compatability.
.Package(url: "https://github.com/open-swift/S4.git", majorVersion: 0, minor: 8),
//Provides critical String functions Foundation is missing on Linux
.Package(url: "https://github.com/Zewo/String.git", majorVersion: 0, minor: 7),
//Parses and serializes JSON - using fork until update core library
.Package(url: "https://github.com/qutheory/pure-json.git", majorVersion: 2, minor: 2),
//Swift wrapper around Sockets, used for built-in HTTP server
.Package(url: "https://github.com/ketzusaka/Hummingbird.git", majorVersion: 1, minor: 9),
//SHA2 + HMAC hashing. Used by the core to create session identifiers.
.Package(url: "https://github.com/CryptoKitten/HMAC.git", majorVersion: 0, minor: 7),
.Package(url: "https://github.com/CryptoKitten/SHA2.git", majorVersion: 0, minor: 7),
//Determines Content-Type for file extensions
.Package(url: "https://github.com/Zewo/MediaType.git", majorVersion: 0, minor: 7),
//ORM for interacting with databases
.Package(url: "https://github.com/qutheory/fluent.git", majorVersion: 0, minor: 3),
// Allows complex key path subscripts
.Package(url: "https://github.com/qutheory/path-indexable.git", majorVersion: 0, minor: 1)
],
exclude: [
"XcodeProject"
],
targets: [
Target(
name: "Vapor",
dependencies: [
.Target(name: "libc")
]
),
Target(
name: "Development",
dependencies: [
.Target(name: "Vapor")
]
),
Target(
name: "Performance",
dependencies: [
.Target(name: "Vapor")
]
),
Target(
name: "Generator"
)
]
)
|