hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
f597fc8e82763c88ca366468b0263cca7933df98 | 1,408 | import Foundation
public protocol CrashReporter {
var hasCrashReporter: Bool { get }
var hasAnalytics: Bool { get }
func setUserProperty(value: String?, name: String)
func logEvent(event: String, params: [String: Any])
func logError(_ error: NSError)
}
public class CrashReporterImpl: CrashReporter {
public var hasCrashReporter: Bool = false
public var hasAnalytics: Bool = false
internal func setup() {
guard Current.settingsStore.privacy.crashes else {
return
}
guard Constants.BundleID.starts(with: "com.aispeaker.") else {
return
}
// no current crash reporter
hasCrashReporter = false
hasAnalytics = false
}
public func setUserProperty(value: String?, name: String) {
// no current analytics/crash reporter
}
public func logEvent(event: String, params: [String: Any]) {
guard Current.settingsStore.privacy.analytics else { return }
Current.Log.verbose("event \(event): \(params)")
// no current analytics logger
}
public func logError(_ error: NSError) {
// crash reporting is controlled by the crashes key, but this is more like analytics
guard Current.settingsStore.privacy.analytics else { return }
Current.Log.error("error: \(error.debugDescription)")
// no current error logger
}
}
| 28.734694 | 92 | 0.651989 |
483f81ea28dfcb60eb4a7f9e00ce04f3538664bd | 2,917 | //
// TokamakHTMLFunctionBuilder.swift
// TokamakHTMLFunctionBuilder
//
// Created by evdwarf on 2021/04/26.
//
import Foundation
import TokamakDOM
import TokamakStaticHTML
import TokamakCore
import JavaScriptKit
public func html<Content: View>(
_ tag: String,
attributes: [HTMLAttribute : String] = [:],
content: Content) -> some View
{
HTML(tag, attributes) {
content
}
}
public func html<Content: StringProtocol>(
_ tag: String,
attributes: [HTMLAttribute : String] = [:],
content: Content) -> some View
{
HTML(tag, attributes, content: content)
}
public func html<Content: View>(
_ tag: String,
attributes: [HTMLAttribute : String] = [:],
@ViewBuilder content: () -> Content) -> some View
{
HTML(tag, attributes) {
content()
}
}
public func html(
_ tag: String,
attributes: [HTMLAttribute : String] = [:]) -> some View
{
HTML(tag, attributes) {
EmptyView()
}
}
public typealias Listener = (JSObject) -> ()
public func html<Content: View>(
_ tag: String,
attributes: [HTMLAttribute : String] = [:],
listeners: [GlobalEventHandler : Listener],
content: Content) -> some View
{
DynamicHTML(tag,
attributes,
listeners: listeners.reduce(into: Dictionary<String, Listener>(), { (ret, dict) in
ret[dict.key.rawValue] = dict.value
}),
content: {
content
})
}
public func html<Content: StringProtocol>(
_ tag: String,
attributes: [HTMLAttribute : String] = [:],
listeners: [GlobalEventHandler : Listener],
content: Content) -> some View
{
DynamicHTML(tag,
attributes,
listeners: listeners.reduce(into: Dictionary<String, Listener>(), { (ret, dict) in
ret[dict.key.rawValue] = dict.value
}),
content: content)
}
public func html<Content: View>(
_ tag: String,
attributes: [HTMLAttribute : String] = [:],
listeners: [GlobalEventHandler : Listener],
@ViewBuilder content: () -> Content) -> some View
{
DynamicHTML(tag,
attributes,
listeners: listeners.reduce(into: Dictionary<String, Listener>(), { (ret, dict) in
ret[dict.key.rawValue] = dict.value
}),
content: {
content()
})
}
public func html(
_ tag: String,
listeners: [GlobalEventHandler : Listener],
attributes: [HTMLAttribute : String] = [:]) -> some View
{
DynamicHTML(tag,
attributes,
listeners: listeners.reduce(into: Dictionary<String, Listener>(), { (ret, dict) in
ret[dict.key.rawValue] = dict.value
}),
content: {
EmptyView()
})
}
| 25.814159 | 98 | 0.56085 |
76f03fd61069d2f57d81599675d842a1c10ae162 | 849 | //import Prefix from './prefix';
//import IpBits from './ip_bits';
public class Prefix128 {
// #[derive(Ord,PartialOrd,Eq,PartialEq,Debug,Copy,Clone)]
// pub struct Prefix128 {
// }
//
// impl Prefix128 {
//
// Creates a new prefix object for 128 bits IPv6 addresses
//
// prefix = IPAddressPrefix128.new 64
// // => 64
//
//#[allow(unused_comparisons)]
public class func create(_ num: UInt8) -> Prefix? {
if (num <= 128) {
let ip_bits = IpBits.v6();
let bits = ip_bits.bits;
return Prefix(
num: num,
ip_bits: ip_bits,
net_mask: Prefix.new_netmask(num, bits),
vt_from: Prefix128.from // vt_to_ip_str: _TO_IP_STR
);
}
return nil;
}
public class func from(_ my: Prefix, _ num: UInt8) -> Prefix? {
return Prefix128.create(num);
}
}
| 22.945946 | 65 | 0.591284 |
2160ea10a4128bca533e7ec4e1b3948b3f83365f | 1,239 | //
// ViewController.swift
// CHStatusBarNoticeDemo
//
// Created by Jiao Liu on 3/1/15.
// Copyright (c) 2015 Jiao Liu. All rights reserved.
//
import UIKit
class ViewController: UIViewController , CHBarNoticeViewDelegate{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var btn = UIButton(frame: CGRectMake(UIScreen.mainScreen().bounds.size.width / 2.0 - 100, UIScreen.mainScreen().bounds.size.height / 2.0 - 20, 200, 40))
btn.addTarget(self, action: "showNotice", forControlEvents: UIControlEvents.TouchUpInside)
btn.setTitle("Show Notice", forState: UIControlState.Normal)
btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
self.view.addSubview(btn)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showNotice()
{
CHBarNoticeView.sharedView.showNotice("hello world")
CHBarNoticeView.sharedView.delegate = self
CHBarNoticeView.sharedView.tag = 100
}
func openViewWithTag(tag: Int) {
println(tag)
}
}
| 31.769231 | 160 | 0.682002 |
14632999c59fb937ddea0bdb6d5b30485d9edcbb | 7,080 | import Foundation
import ObjectMapper
import Alamofire
open class CallLogPath: PathSegment {
public override var pathSegment: String {
get{
return "call-log"
}
}
// Get Account Call Log
open func list(callback: @escaping (_ t: ListResponse?, _ error: HTTPError?) -> Void) {
rc.get(self.endpoint(withId: false)) { (t: ListResponse?, error) in
callback(t, error)
}
}
// Get Account Call Log
open func list(parameters: Parameters, callback: @escaping (_ t: ListResponse?, _ error: HTTPError?) -> Void) {
rc.get(self.endpoint(withId: false), parameters: parameters) { (t: ListResponse?, error) in
callback(t, error)
}
}
// Get Account Call Log
open func list(parameters: ListParameters, callback: @escaping (_ t: ListResponse?, _ error: HTTPError?) -> Void) {
list(parameters: parameters.toParameters(), callback: callback)
}
open class ListParameters: Mappable {
// Extension number of a user. If specified, returns call log for a particular extension only. Cannot be specified together with the phoneNumber filter
open var `extensionNumber`: String?
// Phone number of a caller/call recipient. If specified, returns all calls (both incoming and outcoming) with the mentioned phone number. Cannot be specified together with the extensionNumber filter
open var `phoneNumber`: String?
// The direction for the result records. It is allowed to specify more than one direction. If not specified, both inbound and outbound records are returned. Multiple values are accepted
open var `direction`: String?
// Call type of a record. It is allowed to specify more than one type. If not specified, all call types are returned. Multiple values are accepted
open var `type`: String?
// The default value is 'Simple' for both account and extension call log
open var `view`: String?
// 'True' if only recorded calls have to be returned
open var `withRecording`: Bool?
// The start datetime for resulting records in ISO 8601 format including timezone, for example 2016-03-10T18:07:52.534Z. The default value is dateTo minus 24 hours
open var `dateFrom`: String?
// The end datetime for resulting records in ISO 8601 format including timezone, for example 2016-03-10T18:07:52.534Z. The default value is current time
open var `dateTo`: String?
// Indicates the page number to retrieve. Only positive number values are allowed. The default value is '1'
open var `page`: Int?
// Indicates the page size (number of items). If not specified, the value is '100' by default.
open var `perPage`: Int?
public init() {
}
convenience public init(extensionNumber: String? = nil, phoneNumber: String? = nil, direction: String? = nil, type: String? = nil, view: String? = nil, withRecording: Bool? = nil, dateFrom: String? = nil, dateTo: String? = nil, page: Int? = nil, perPage: Int? = nil) {
self.init()
self.extensionNumber = `extensionNumber`
self.phoneNumber = `phoneNumber`
self.direction = `direction`
self.type = `type`
self.view = `view`
self.withRecording = `withRecording`
self.dateFrom = `dateFrom`
self.dateTo = `dateTo`
self.page = `page`
self.perPage = `perPage`
}
required public init?(map: Map) {
}
open func mapping(map: Map) {
`extensionNumber` <- map["extensionNumber"]
`phoneNumber` <- map["phoneNumber"]
`direction` <- map["direction"]
`type` <- map["type"]
`view` <- map["view"]
`withRecording` <- map["withRecording"]
`dateFrom` <- map["dateFrom"]
`dateTo` <- map["dateTo"]
`page` <- map["page"]
`perPage` <- map["perPage"]
}
open func toParameters() -> Parameters {
var result = [String: String]()
result["json-string"] = self.toJSONString(prettyPrint: false)!
return result
}
}
open class ListResponse: Mappable {
// Canonical URI
open var `uri`: String?
// List of call log records
open var `records`: [CallLogRecord]?
// Information on navigation
open var `navigation`: NavigationInfo?
// Information on paging
open var `paging`: PagingInfo?
public init() {
}
convenience public init(uri: String? = nil, records: [CallLogRecord]? = nil, navigation: NavigationInfo? = nil, paging: PagingInfo? = nil) {
self.init()
self.uri = `uri`
self.records = `records`
self.navigation = `navigation`
self.paging = `paging`
}
required public init?(map: Map) {
}
open func mapping(map: Map) {
`uri` <- map["uri"]
`records` <- map["records"]
`navigation` <- map["navigation"]
`paging` <- map["paging"]
}
open func toParameters() -> Parameters {
var result = [String: String]()
result["json-string"] = self.toJSONString(prettyPrint: false)!
return result
}
}
// Get Account Call Log Record by ID
open func get(callback: @escaping (_ t: CallLogInfo?, _ error: HTTPError?) -> Void) {
rc.get(self.endpoint()) { (t: CallLogInfo?, error) in
callback(t, error)
}
}
// Delete Extension Call Log
open func delete(callback: @escaping (_ error: HTTPError?) -> Void) {
rc.deleteString(self.endpoint()) { string, error in
callback(error)
}
}
// Delete Extension Call Log
open func delete(parameters: Parameters, callback: @escaping (_ error: HTTPError?) -> Void) {
rc.deleteString(self.endpoint(), parameters: parameters) { string, error in
callback(error)
}
}
// Delete Extension Call Log
open func delete(parameters: DeleteParameters, callback: @escaping (_ error: HTTPError?) -> Void) {
delete(parameters: parameters.toParameters(), callback: callback)
}
open class DeleteParameters: Mappable {
// The end datetime for records deletion in ISO 8601 format including timezone, for example 2016-03-10T18:07:52.534Z. The default value is current time
open var `dateTo`: String?
public init() {
}
convenience public init(dateTo: String? = nil) {
self.init()
self.dateTo = `dateTo`
}
required public init?(map: Map) {
}
open func mapping(map: Map) {
`dateTo` <- map["dateTo"]
}
open func toParameters() -> Parameters {
var result = [String: String]()
result["json-string"] = self.toJSONString(prettyPrint: false)!
return result
}
}
}
| 45.095541 | 276 | 0.598305 |
f8acfc0936ab0c165f5052be1ee593b781a08464 | 69,447 | // This file is autogenerated.
// Take a look at `Preprocessor` target in RxSwift project
//
// Observable+MultipleTest+CombineLatest.tt
// RxSwift
//
// Created by Krunoslav Zaher on 4/25/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import XCTest
import RxSwift
// combine latest
extension ObservableMultipleTest {
// 2
func testCombineLatest_Never2() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1)
])
let e1 = scheduler.createHotObservable([
next(150, 1)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1) { (_, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [])
let subscriptions = [Subscription(200, 1000)]
XCTAssertEqual(e0.subscriptions, subscriptions)
XCTAssertEqual(e1.subscriptions, subscriptions)
}
func testCombineLatest_Empty2() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(210)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(220)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1) { (_, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [completed(220)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 210)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_SelectorThrows2() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
completed(400)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
completed(400)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1) { (_, _) throws -> Int in
throw testError
}
return result
}
XCTAssertEqual(res.messages, [
error(220, testError)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_WillNeverBeAbleToCombine2() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(250)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(500, 2),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1) { (_, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [
completed(500)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 500)])
}
func testCombineLatest_Typical2() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
next(410, 3),
completed(800)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
next(420, 4),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1) {
return ($0 + $1)
}
return result
}
XCTAssertEqual(res.messages, [
next(220, 3),
next(410, 5),
next(420, 7),
completed(800)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 800)])
}
// 3
func testCombineLatest_Never3() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1)
])
let e1 = scheduler.createHotObservable([
next(150, 1)
])
let e2 = scheduler.createHotObservable([
next(150, 1)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2) { (_, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [])
let subscriptions = [Subscription(200, 1000)]
XCTAssertEqual(e0.subscriptions, subscriptions)
XCTAssertEqual(e1.subscriptions, subscriptions)
XCTAssertEqual(e2.subscriptions, subscriptions)
}
func testCombineLatest_Empty3() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(210)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(220)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
completed(230)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2) { (_, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [completed(230)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 210)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 230)])
}
func testCombineLatest_SelectorThrows3() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
completed(400)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
completed(400)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
next(230, 3),
completed(400)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2) { (_, _, _) throws -> Int in
throw testError
}
return result
}
XCTAssertEqual(res.messages, [
error(230, testError)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 230)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 230)])
}
func testCombineLatest_WillNeverBeAbleToCombine3() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(250)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(260)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
next(500, 2),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2) { (_, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [
completed(500)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 260)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 500)])
}
func testCombineLatest_Typical3() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
next(410, 4),
completed(800)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
next(420, 5),
completed(800)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
next(230, 3),
next(430, 6),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2) {
return ($0 + $1 + $2)
}
return result
}
XCTAssertEqual(res.messages, [
next(230, 6),
next(410, 9),
next(420, 12),
next(430, 15),
completed(800)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 800)])
}
// 4
func testCombineLatest_Never4() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1)
])
let e1 = scheduler.createHotObservable([
next(150, 1)
])
let e2 = scheduler.createHotObservable([
next(150, 1)
])
let e3 = scheduler.createHotObservable([
next(150, 1)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3) { (_, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [])
let subscriptions = [Subscription(200, 1000)]
XCTAssertEqual(e0.subscriptions, subscriptions)
XCTAssertEqual(e1.subscriptions, subscriptions)
XCTAssertEqual(e2.subscriptions, subscriptions)
XCTAssertEqual(e3.subscriptions, subscriptions)
}
func testCombineLatest_Empty4() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(210)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(220)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
completed(230)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
completed(240)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3) { (_, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [completed(240)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 210)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 230)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 240)])
}
func testCombineLatest_SelectorThrows4() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
completed(400)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
completed(400)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
next(230, 3),
completed(400)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
next(240, 4),
completed(400)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3) { (_, _, _, _) throws -> Int in
throw testError
}
return result
}
XCTAssertEqual(res.messages, [
error(240, testError)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 240)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 240)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 240)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 240)])
}
func testCombineLatest_WillNeverBeAbleToCombine4() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(250)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(260)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
completed(270)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
next(500, 2),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3) { (_, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [
completed(500)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 260)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 270)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 500)])
}
func testCombineLatest_Typical4() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
next(410, 5),
completed(800)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
next(420, 6),
completed(800)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
next(230, 3),
next(430, 7),
completed(800)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
next(240, 4),
next(440, 8),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3) {
return ($0 + $1 + $2 + $3)
}
return result
}
XCTAssertEqual(res.messages, [
next(240, 10),
next(410, 14),
next(420, 18),
next(430, 22),
next(440, 26),
completed(800)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 800)])
}
// 5
func testCombineLatest_Never5() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1)
])
let e1 = scheduler.createHotObservable([
next(150, 1)
])
let e2 = scheduler.createHotObservable([
next(150, 1)
])
let e3 = scheduler.createHotObservable([
next(150, 1)
])
let e4 = scheduler.createHotObservable([
next(150, 1)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4) { (_, _, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [])
let subscriptions = [Subscription(200, 1000)]
XCTAssertEqual(e0.subscriptions, subscriptions)
XCTAssertEqual(e1.subscriptions, subscriptions)
XCTAssertEqual(e2.subscriptions, subscriptions)
XCTAssertEqual(e3.subscriptions, subscriptions)
XCTAssertEqual(e4.subscriptions, subscriptions)
}
func testCombineLatest_Empty5() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(210)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(220)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
completed(230)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
completed(240)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
completed(250)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4) { (_, _, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [completed(250)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 210)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 230)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 240)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 250)])
}
func testCombineLatest_SelectorThrows5() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
completed(400)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
completed(400)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
next(230, 3),
completed(400)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
next(240, 4),
completed(400)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
next(250, 5),
completed(400)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4) { (_, _, _, _, _) throws -> Int in
throw testError
}
return result
}
XCTAssertEqual(res.messages, [
error(250, testError)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 250)])
}
func testCombineLatest_WillNeverBeAbleToCombine5() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(250)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(260)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
completed(270)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
completed(280)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
next(500, 2),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4) { (_, _, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [
completed(500)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 260)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 270)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 280)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 500)])
}
func testCombineLatest_Typical5() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
next(410, 6),
completed(800)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
next(420, 7),
completed(800)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
next(230, 3),
next(430, 8),
completed(800)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
next(240, 4),
next(440, 9),
completed(800)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
next(250, 5),
next(450, 10),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4) {
return ($0 + $1 + $2 + $3 + $4)
}
return result
}
XCTAssertEqual(res.messages, [
next(250, 15),
next(410, 20),
next(420, 25),
next(430, 30),
next(440, 35),
next(450, 40),
completed(800)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 800)])
}
// 6
func testCombineLatest_Never6() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1)
])
let e1 = scheduler.createHotObservable([
next(150, 1)
])
let e2 = scheduler.createHotObservable([
next(150, 1)
])
let e3 = scheduler.createHotObservable([
next(150, 1)
])
let e4 = scheduler.createHotObservable([
next(150, 1)
])
let e5 = scheduler.createHotObservable([
next(150, 1)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5) { (_, _, _, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [])
let subscriptions = [Subscription(200, 1000)]
XCTAssertEqual(e0.subscriptions, subscriptions)
XCTAssertEqual(e1.subscriptions, subscriptions)
XCTAssertEqual(e2.subscriptions, subscriptions)
XCTAssertEqual(e3.subscriptions, subscriptions)
XCTAssertEqual(e4.subscriptions, subscriptions)
XCTAssertEqual(e5.subscriptions, subscriptions)
}
func testCombineLatest_Empty6() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(210)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(220)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
completed(230)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
completed(240)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
completed(250)
])
let e5 = scheduler.createHotObservable([
next(150, 1),
completed(260)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5) { (_, _, _, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [completed(260)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 210)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 230)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 240)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e5.subscriptions, [Subscription(200, 260)])
}
func testCombineLatest_SelectorThrows6() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
completed(400)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
completed(400)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
next(230, 3),
completed(400)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
next(240, 4),
completed(400)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
next(250, 5),
completed(400)
])
let e5 = scheduler.createHotObservable([
next(150, 1),
next(260, 6),
completed(400)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5) { (_, _, _, _, _, _) throws -> Int in
throw testError
}
return result
}
XCTAssertEqual(res.messages, [
error(260, testError)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 260)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 260)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 260)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 260)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 260)])
XCTAssertEqual(e5.subscriptions, [Subscription(200, 260)])
}
func testCombineLatest_WillNeverBeAbleToCombine6() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(250)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(260)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
completed(270)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
completed(280)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
completed(290)
])
let e5 = scheduler.createHotObservable([
next(150, 1),
next(500, 2),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5) { (_, _, _, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [
completed(500)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 260)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 270)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 280)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 290)])
XCTAssertEqual(e5.subscriptions, [Subscription(200, 500)])
}
func testCombineLatest_Typical6() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
next(410, 7),
completed(800)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
next(420, 8),
completed(800)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
next(230, 3),
next(430, 9),
completed(800)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
next(240, 4),
next(440, 10),
completed(800)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
next(250, 5),
next(450, 11),
completed(800)
])
let e5 = scheduler.createHotObservable([
next(150, 1),
next(260, 6),
next(460, 12),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5) {
return ($0 + $1 + $2 + $3 + $4 + $5)
}
return result
}
XCTAssertEqual(res.messages, [
next(260, 21),
next(410, 27),
next(420, 33),
next(430, 39),
next(440, 45),
next(450, 51),
next(460, 57),
completed(800)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e5.subscriptions, [Subscription(200, 800)])
}
// 7
func testCombineLatest_Never7() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1)
])
let e1 = scheduler.createHotObservable([
next(150, 1)
])
let e2 = scheduler.createHotObservable([
next(150, 1)
])
let e3 = scheduler.createHotObservable([
next(150, 1)
])
let e4 = scheduler.createHotObservable([
next(150, 1)
])
let e5 = scheduler.createHotObservable([
next(150, 1)
])
let e6 = scheduler.createHotObservable([
next(150, 1)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5, e6) { (_, _, _, _, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [])
let subscriptions = [Subscription(200, 1000)]
XCTAssertEqual(e0.subscriptions, subscriptions)
XCTAssertEqual(e1.subscriptions, subscriptions)
XCTAssertEqual(e2.subscriptions, subscriptions)
XCTAssertEqual(e3.subscriptions, subscriptions)
XCTAssertEqual(e4.subscriptions, subscriptions)
XCTAssertEqual(e5.subscriptions, subscriptions)
XCTAssertEqual(e6.subscriptions, subscriptions)
}
func testCombineLatest_Empty7() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(210)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(220)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
completed(230)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
completed(240)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
completed(250)
])
let e5 = scheduler.createHotObservable([
next(150, 1),
completed(260)
])
let e6 = scheduler.createHotObservable([
next(150, 1),
completed(270)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5, e6) { (_, _, _, _, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [completed(270)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 210)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 230)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 240)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e5.subscriptions, [Subscription(200, 260)])
XCTAssertEqual(e6.subscriptions, [Subscription(200, 270)])
}
func testCombineLatest_SelectorThrows7() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
completed(400)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
completed(400)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
next(230, 3),
completed(400)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
next(240, 4),
completed(400)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
next(250, 5),
completed(400)
])
let e5 = scheduler.createHotObservable([
next(150, 1),
next(260, 6),
completed(400)
])
let e6 = scheduler.createHotObservable([
next(150, 1),
next(270, 7),
completed(400)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5, e6) { (_, _, _, _, _, _, _) throws -> Int in
throw testError
}
return result
}
XCTAssertEqual(res.messages, [
error(270, testError)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 270)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 270)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 270)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 270)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 270)])
XCTAssertEqual(e5.subscriptions, [Subscription(200, 270)])
XCTAssertEqual(e6.subscriptions, [Subscription(200, 270)])
}
func testCombineLatest_WillNeverBeAbleToCombine7() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(250)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(260)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
completed(270)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
completed(280)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
completed(290)
])
let e5 = scheduler.createHotObservable([
next(150, 1),
completed(300)
])
let e6 = scheduler.createHotObservable([
next(150, 1),
next(500, 2),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5, e6) { (_, _, _, _, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [
completed(500)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 260)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 270)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 280)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 290)])
XCTAssertEqual(e5.subscriptions, [Subscription(200, 300)])
XCTAssertEqual(e6.subscriptions, [Subscription(200, 500)])
}
func testCombineLatest_Typical7() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
next(410, 8),
completed(800)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
next(420, 9),
completed(800)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
next(230, 3),
next(430, 10),
completed(800)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
next(240, 4),
next(440, 11),
completed(800)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
next(250, 5),
next(450, 12),
completed(800)
])
let e5 = scheduler.createHotObservable([
next(150, 1),
next(260, 6),
next(460, 13),
completed(800)
])
let e6 = scheduler.createHotObservable([
next(150, 1),
next(270, 7),
next(470, 14),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5, e6) {
return ($0 + $1 + $2 + $3 + $4 + $5 + $6)
}
return result
}
XCTAssertEqual(res.messages, [
next(270, 28),
next(410, 35),
next(420, 42),
next(430, 49),
next(440, 56),
next(450, 63),
next(460, 70),
next(470, 77),
completed(800)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e5.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e6.subscriptions, [Subscription(200, 800)])
}
// 8
func testCombineLatest_Never8() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1)
])
let e1 = scheduler.createHotObservable([
next(150, 1)
])
let e2 = scheduler.createHotObservable([
next(150, 1)
])
let e3 = scheduler.createHotObservable([
next(150, 1)
])
let e4 = scheduler.createHotObservable([
next(150, 1)
])
let e5 = scheduler.createHotObservable([
next(150, 1)
])
let e6 = scheduler.createHotObservable([
next(150, 1)
])
let e7 = scheduler.createHotObservable([
next(150, 1)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5, e6, e7) { (_, _, _, _, _, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [])
let subscriptions = [Subscription(200, 1000)]
XCTAssertEqual(e0.subscriptions, subscriptions)
XCTAssertEqual(e1.subscriptions, subscriptions)
XCTAssertEqual(e2.subscriptions, subscriptions)
XCTAssertEqual(e3.subscriptions, subscriptions)
XCTAssertEqual(e4.subscriptions, subscriptions)
XCTAssertEqual(e5.subscriptions, subscriptions)
XCTAssertEqual(e6.subscriptions, subscriptions)
XCTAssertEqual(e7.subscriptions, subscriptions)
}
func testCombineLatest_Empty8() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(210)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(220)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
completed(230)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
completed(240)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
completed(250)
])
let e5 = scheduler.createHotObservable([
next(150, 1),
completed(260)
])
let e6 = scheduler.createHotObservable([
next(150, 1),
completed(270)
])
let e7 = scheduler.createHotObservable([
next(150, 1),
completed(280)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5, e6, e7) { (_, _, _, _, _, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [completed(280)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 210)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 230)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 240)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e5.subscriptions, [Subscription(200, 260)])
XCTAssertEqual(e6.subscriptions, [Subscription(200, 270)])
XCTAssertEqual(e7.subscriptions, [Subscription(200, 280)])
}
func testCombineLatest_SelectorThrows8() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
completed(400)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
completed(400)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
next(230, 3),
completed(400)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
next(240, 4),
completed(400)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
next(250, 5),
completed(400)
])
let e5 = scheduler.createHotObservable([
next(150, 1),
next(260, 6),
completed(400)
])
let e6 = scheduler.createHotObservable([
next(150, 1),
next(270, 7),
completed(400)
])
let e7 = scheduler.createHotObservable([
next(150, 1),
next(280, 8),
completed(400)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5, e6, e7) { (_, _, _, _, _, _, _, _) throws -> Int in
throw testError
}
return result
}
XCTAssertEqual(res.messages, [
error(280, testError)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 280)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 280)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 280)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 280)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 280)])
XCTAssertEqual(e5.subscriptions, [Subscription(200, 280)])
XCTAssertEqual(e6.subscriptions, [Subscription(200, 280)])
XCTAssertEqual(e7.subscriptions, [Subscription(200, 280)])
}
func testCombineLatest_WillNeverBeAbleToCombine8() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(250)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(260)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
completed(270)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
completed(280)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
completed(290)
])
let e5 = scheduler.createHotObservable([
next(150, 1),
completed(300)
])
let e6 = scheduler.createHotObservable([
next(150, 1),
completed(310)
])
let e7 = scheduler.createHotObservable([
next(150, 1),
next(500, 2),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5, e6, e7) { (_, _, _, _, _, _, _, _) -> Int in
return (42)
}
return result
}
XCTAssertEqual(res.messages, [
completed(500)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 250)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 260)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 270)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 280)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 290)])
XCTAssertEqual(e5.subscriptions, [Subscription(200, 300)])
XCTAssertEqual(e6.subscriptions, [Subscription(200, 310)])
XCTAssertEqual(e7.subscriptions, [Subscription(200, 500)])
}
func testCombineLatest_Typical8() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 1),
next(410, 9),
completed(800)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 2),
next(420, 10),
completed(800)
])
let e2 = scheduler.createHotObservable([
next(150, 1),
next(230, 3),
next(430, 11),
completed(800)
])
let e3 = scheduler.createHotObservable([
next(150, 1),
next(240, 4),
next(440, 12),
completed(800)
])
let e4 = scheduler.createHotObservable([
next(150, 1),
next(250, 5),
next(450, 13),
completed(800)
])
let e5 = scheduler.createHotObservable([
next(150, 1),
next(260, 6),
next(460, 14),
completed(800)
])
let e6 = scheduler.createHotObservable([
next(150, 1),
next(270, 7),
next(470, 15),
completed(800)
])
let e7 = scheduler.createHotObservable([
next(150, 1),
next(280, 8),
next(480, 16),
completed(800)
])
let res = scheduler.start { () -> Observable<Int> in
let result: Observable<Int> = combineLatest(e0, e1, e2, e3, e4, e5, e6, e7) {
return ($0 + $1 + $2 + $3 + $4 + $5 + $6 + $7)
}
return result
}
XCTAssertEqual(res.messages, [
next(280, 36),
next(410, 44),
next(420, 52),
next(430, 60),
next(440, 68),
next(450, 76),
next(460, 84),
next(470, 92),
next(480, 100),
completed(800)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e2.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e3.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e4.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e5.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e6.subscriptions, [Subscription(200, 800)])
XCTAssertEqual(e7.subscriptions, [Subscription(200, 800)])
}
func testCombineLatest_NeverEmpty() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(210)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 1000)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 210)])
}
func testCombineLatest_EmptyNever() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(210)
])
let e1 = scheduler.createHotObservable([
next(150, 1)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 210)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 1000)])
}
func testCombineLatest_EmptyReturn() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(210)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
completed(220)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [completed(215)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 210)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 215)])
}
func testCombineLatest_ReturnEmpty() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
completed(220)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(210)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [completed(215)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 215)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 210)])
}
func testCombineLatest_NeverReturn() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
completed(220)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 1000)])
}
func testCombineLatest_ReturnNever() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
completed(220)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 1000)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_ReturnReturn1() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
completed(230)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 3),
completed(240)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [next(220, (2 + 3)), completed(240)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 240)])
}
func testCombineLatest_ReturnReturn2() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(220, 3),
completed(240)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
completed(230)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [next(220, (2 + 3)), completed(240)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 240)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 230)])
}
func testCombineLatest_EmptyError() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
completed(230)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
error(220, testError)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [error(220, testError)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_ErrorEmpty() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
error(220, testError)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
completed(230)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [error(220, testError)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_ReturnThrow() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 2),
completed(230)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
error(220, testError)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [error(220, testError)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_ThrowReturn() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
error(220, testError)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(210, 2),
completed(230)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [error(220, testError)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_ThrowThrow1() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
error(220, testError1),
])
let e1 = scheduler.createHotObservable([
next(150, 1),
error(230, testError2),
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [error(220, testError1)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_ThrowThrow2() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
error(230, testError1),
])
let e1 = scheduler.createHotObservable([
next(150, 1),
error(220, testError2),
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [error(220, testError2)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_ErrorThrow() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(210, 2),
error(220, testError1),
])
let e1 = scheduler.createHotObservable([
next(150, 1),
error(230, testError2),
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [error(220, testError1)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_ThrowError() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
error(230, testError2),
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(210, 2),
error(220, testError1),
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [error(220, testError1)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_SomeThrow() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
completed(230)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
error(220, testError),
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [error(220, testError)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_ThrowSome() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
error(220, testError),
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
completed(230)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [error(220, testError)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_ThrowAfterCompleteLeft() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
completed(220)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
error(230, testError),
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [error(230, testError)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 220)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 230)])
}
func testCombineLatest_ThrowAfterCompleteRight() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
error(230, testError),
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
completed(220)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [error(230, testError)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 220)])
}
func testCombineLatest_TestInterleavedWithTail() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
next(225, 4),
completed(230)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(220, 3),
next(230, 5),
next(235, 6),
next(240, 7),
completed(250)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
let messages = [
next(220, 2 + 3),
next(225, 3 + 4),
next(230, 4 + 5),
next(235, 4 + 6),
next(240, 4 + 7),
completed(250)
]
XCTAssertEqual(res.messages, messages)
XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 250)])
}
func testCombineLatest_Consecutive() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
next(225, 4),
completed(230)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(235, 6),
next(240, 7),
completed(250)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
let messages = [
next(235, 4 + 6),
next(240, 4 + 7),
completed(250)
]
XCTAssertEqual(res.messages, messages)
XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 250)])
}
func testCombineLatest_ConsecutiveEndWithErrorLeft() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
next(225, 4),
error(230, testError)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(235, 6),
next(240, 7),
completed(250)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [error(230, testError)])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 230)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 230)])
}
func testCombineLatest_ConsecutiveEndWithErrorRight() {
let scheduler = TestScheduler(initialClock: 0)
let e0 = scheduler.createHotObservable([
next(150, 1),
next(215, 2),
next(225, 4),
completed(250)
])
let e1 = scheduler.createHotObservable([
next(150, 1),
next(235, 6),
next(240, 7),
error(245, testError)
])
let res = scheduler.start {
combineLatest(e0, e1) { (x1, x2) -> Int in
return (x1 + x2)
}
}
XCTAssertEqual(res.messages, [
next(235, 4 + 6),
next(240, 4 + 7),
error(245, testError)
])
XCTAssertEqual(e0.subscriptions, [Subscription(200, 245)])
XCTAssertEqual(e1.subscriptions, [Subscription(200, 245)])
}
} | 25.797548 | 131 | 0.513384 |
eb67f5751eef57c689206096bad41cfa78a51849 | 1,780 | import UIKit
import XCTest
import Nimble
import Alamofire
import AlamofireImage
import ImageValet
class ImageValetTests: XCTestCase {
var sut: ImageValet!
var image: UIImage!
override func setUp() {
super.setUp()
image = UIImage()
}
}
/*
* MARK: - In Memory
*/
class InMemoryImageValetTests: ImageValetTests {
override func setUp() {
super.setUp()
sut = ImageValet(source:.inMemory(image: image))
}
func test__deliverToImageView__setsImageViewImage() {
// given
let imageView = UIImageView()
// when
sut.deliverToImageView(imageView)
// then
expect(imageView.image).to(beIdenticalTo(image))
}
func test__deliver__callsCompletion() {
// given
var imageDelivered: UIImage?
// when
sut.deliver { result in
imageDelivered = result.value
}
// then
expect(imageDelivered).to(beIdenticalTo(image))
}
func test__image__returnsSourceImage() {
expect(self.sut.image).to(beIdenticalTo(image))
}
}
/*
* MARK: - URL
*/
class URLImageValetTests: ImageValetTests {
let URL = Foundation.URL(string: "http://www.example.com")!
override func setUp() {
super.setUp()
sut = ImageValet(source:.url(URL, placeholder: nil))
}
}
/*
* MARK: - URL Request
*/
class URLRequestImageValetTests: ImageValetTests {
let request = URLRequest(url: URL(string: "http://www.example.com")!)
override func setUp() {
super.setUp()
sut = ImageValet(source:.urlRequest(request, placeholder: nil))
}
}
| 18.541667 | 73 | 0.575281 |
4a1fd5d9d6799a870fcbddf3bbd6ef9f74846c2d | 915 | //
// FilmsViewModel.swift
// BlueStudios
//
// Created by Gonzalo Gonzalez on 09/11/2018.
// Copyright © 2018 Gonzalo Gonzalez . All rights reserved.
//
import Foundation
class FilmsViewModel {
var filmService: FilmService!
//MARK: Events
var didFilmsLoaded: (([Film]) -> Void)?
init (filmService: FilmService) {
self.filmService = filmService
}
func loadFilms () {
filmService.getFilms(onSuccess: { (films) in
print(films)
self.didFilmsLoaded!(films)
}) { (error) in
print(error)
}
}
func changeFilmStatus (filmId: String, filmStatus: FilmStatus) {
filmService.changeFilmStatus(filmId: filmId, filmStatus: filmStatus, onSuccess: { (films) in
self.didFilmsLoaded!(films)
}) { (error) in
print(error)
}
}
}
| 21.27907 | 100 | 0.569399 |
f914ad5b77ebf215402910397a9c572d5b9bd384 | 1,153 | // RUN: %target-swift-ide-test -print-indexed-symbols -source-filename %s | %FileCheck -check-prefix=CHECK %s
struct Tagged<Tag, Entity> {
let tag: Tag
let entity: Entity
}
protocol Taggable {
}
extension Taggable {
func tag<Tag>(_ tag: Tag) -> Tagged<Tag, Self> {
return Tagged(tag: tag, entity: self)
}
}
extension Int: Taggable { }
extension String: Taggable { }
extension Double: Taggable { }
@_functionBuilder
struct TaggedBuilder<Tag> {
static func buildBlock() -> () { }
static func buildBlock<T1>(_ t1: Tagged<Tag, T1>) -> Tagged<Tag, T1> {
return t1
}
static func buildBlock<T1, T2>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>) -> (Tagged<Tag, T1>, Tagged<Tag, T2>) {
return (t1, t2)
}
static func buildIf<T>(_ value: Tagged<Tag, T>?) -> Tagged<Tag, T>? { return value }
}
enum Color {
case red, green, blue
}
func acceptColorTagged<Result>(@TaggedBuilder<Color> body: () -> Result) {
print(body())
}
// CHECK: 40:33 | struct/Swift | TaggedBuilder | s:14swift_ide_test13TaggedBuilderV | Ref,RelCont | rel: 1
// CHECK: 40:47 | enum/Swift | Color | s:14swift_ide_test5ColorO | Ref,RelCont | rel: 1
| 25.065217 | 118 | 0.663487 |
7661c67bb662a45797f0fabce7478761ae34c0d6 | 289 | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "CJavaVM",
products: [
.library(
name: "CJavaVM",
targets: ["CJavaVM"]
),
],
targets: [
.target(
name: "CJavaVM"
)
]
) | 17 | 32 | 0.467128 |
29600cce6b0262703f15ed5d4379c6fa5f21f1e8 | 580 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "HNScraper",
platforms: [.macOS(.v11), .iOS(.v11)],
products: [
.library(name: "HNScraper", targets: ["HNScraper"]),
],
dependencies: [],
targets: [
.target(
name: "HNScraper",
dependencies: [], path: "Sources"),
.testTarget(
name: "HNScraperTests",
dependencies: ["HNScraper"], path: "Tests"),
]
)
| 26.363636 | 96 | 0.581034 |
f4b0c13555de424303ac9c25e79847762ecac686 | 2,936 | //
// RealmTranslator.swift
// DAO
//
// Created by Ivan Vavilov on 06.02.16.
// Copyright © 2016 RedMadRobot LLC. All rights reserved.
//
import Foundation
import CoreData
/// Parent class for `CoreData` translators.
/// Translators fill properties of new/existant entities from entries and other way.
open class CoreDataTranslator<CDModel: NSManagedObject, Model: Entity> {
/// Helper property for `CoreDataDAO`.
open var entryClassName: String {
return NSStringFromClass(CDModel.self).components(separatedBy: ".").last!
}
/// Creates an instance of class.
required public init() { }
/// All properties of entity will be overridden by entry properties.
///
/// - Parameters:
/// - entity: instance of `Model` type.
/// - fromEntry: instance of `CDModel` type.
open func fill(_ entity: Model, fromEntry: CDModel) {
fatalError("Abstact method")
}
/// All properties of entry will be overridden by entity properties.
///
/// - Parameters:
/// - entry: instance of `CDModel` type.
/// - fromEntity: instance of `Model` type.
/// - context: managed object context for current transaction.
open func fill(_ entry: CDModel, fromEntity: Model, in context: NSManagedObjectContext) {
fatalError("Abstact method")
}
/// All properties of entities will be overridden by entries properties.
/// For simplicity create new entries w/o changing existent.
///
/// - Parameters:
/// - entries: array of instances of `CDModel` type.
/// - fromEntities: array of instances of `Model` type.
/// - context: managed object context for current transaction.
open func fill(
_ entries: inout Set<CDModel>,
fromEntities: [Model],
in context: NSManagedObjectContext) {
fromEntities
.flatMap { entity -> (CDModel, Model)? in
if let entry = NSEntityDescription.insertNewObject(
forEntityName: self.entryClassName,
into: context) as? CDModel {
entries.insert(entry)
return (entry, entity)
} else {
return nil
}
}
.forEach {
self.fill($0.0, fromEntity: $0.1, in: context)
}
}
/// All properties of entries will be overridden by entities properties.
///
/// - Parameters:
/// - entities: array of instances of `CDModel` type.
/// - fromEntries: array of instances of `CDModel` type.
open func fill(_ entities: inout [Model], fromEntries: Set<CDModel>?) {
entities.removeAll()
fromEntries?.forEach {
let model = Model()
entities.append(model)
self.fill(model, fromEntry: $0)
}
}
}
| 31.234043 | 93 | 0.583447 |
f57e2db3b9a4a72223653085bde442807ab6b01a | 639 | //
// Sprint.swift
// ThryvUXComponents_Example
//
// Created by Elliot Schrock on 6/9/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
struct Sprint {
let startDate: Date
init(startDate: Date) {
self.startDate = startDate
}
}
extension Sprint: Decodable {
enum SprintKeys: String, CodingKey {
case startDate = "start_date"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: SprintKeys.self)
let startDate = try container.decode(Date.self, forKey: .startDate)
self.init(startDate: startDate)
}
}
| 21.3 | 75 | 0.651017 |
215ee93be0ab5ce14b850acaace26e815c222196 | 1,129 | //
// ModalTransition.swift
// RickAndMortyFlexx
//
// Created by Даниил on 29.03.2021.
//
import UIKit
final class ModalTransition: NSObject {
var isAnimated: Bool = true
var modalTransitionStyle: UIModalTransitionStyle
var modalPresentationStyle: UIModalPresentationStyle
init(isAnimated: Bool = true,
modalTransitionStyle: UIModalTransitionStyle = .coverVertical,
modalPresentationStyle: UIModalPresentationStyle = .automatic) {
self.isAnimated = isAnimated
self.modalTransitionStyle = modalTransitionStyle
self.modalPresentationStyle = modalPresentationStyle
}
}
extension ModalTransition: Transition {
func open(_ viewController: UIViewController, from: UIViewController, completion: (() -> Void)?) {
viewController.modalPresentationStyle = modalPresentationStyle
viewController.modalTransitionStyle = modalTransitionStyle
from.present(viewController, animated: isAnimated, completion: completion)
}
func close(_ viewController: UIViewController, completion: (() -> Void)?) {
viewController.dismiss(animated: isAnimated, completion: completion)
}
}
| 31.361111 | 100 | 0.765279 |
d94b22c5dfccf4a056847cfa91ba450737b1728b | 360 | //
// String+Extension.swift
// Solver
//
// Created by Evgeniy on 05.04.18.
// Copyright © 2018 Evgeniy. All rights reserved.
//
import Foundation
public extension String {
public static var space: String {
return " "
}
public var spaceRemoved: String {
return self.replacingOccurrences(of: String.space, with: "")
}
}
| 17.142857 | 68 | 0.638889 |
3a3ba0ca7bdfc8f085198acfe655b2b9fb115081 | 3,274 | import Foundation
import FigmaExportCore
extension NameStyle: Decodable {}
struct Params: Decodable {
struct Figma: Decodable {
let lightFileId: String
let darkFileId: String?
}
struct Common: Decodable {
struct Colors: Decodable {
let nameValidateRegexp: String?
let nameReplaceRegexp: String?
}
struct Icons: Decodable {
let nameValidateRegexp: String?
let figmaFrameName: String?
let nameReplaceRegexp: String?
}
struct Images: Decodable {
let nameValidateRegexp: String?
let figmaFrameName: String?
let nameReplaceRegexp: String?
}
let colors: Colors?
let icons: Icons?
let images: Images?
}
enum VectorFormat: String, Decodable {
case pdf
case svg
}
struct iOS: Decodable {
struct Colors: Decodable {
let useColorAssets: Bool
let assetsFolder: String?
let nameStyle: NameStyle
let colorSwift: URL?
let swiftuiColorSwift: URL?
}
struct Icons: Decodable {
let nameStyle: NameStyle
let format: VectorFormat
let assetsFolder: String
let preservesVectorRepresentation: Bool
let preservesVectorRepresentationIcons: [String]?
let renderIntent: RenderIntent?
let renderAsOriginalIcons: [String]?
let renderAsTemplateIcons: [String]?
let imageSwift: URL?
let swiftUIImageSwift: URL?
}
struct Images: Decodable {
let assetsFolder: String
let nameStyle: NameStyle
let imageSwift: URL?
let swiftUIImageSwift: URL?
}
struct Typography: Decodable {
let fontSwift: URL?
let swiftUIFontSwift: URL?
let generateLabels: Bool
let labelsDirectory: URL?
}
let xcodeprojPath: String
let target: String
let xcassetsPathImages: URL
let xcassetsPathColors: URL
let xcassetsInMainBundle: Bool
let colors: Colors
let icons: Icons
let images: Images
let typography: Typography
}
struct Android: Decodable {
struct Icons: Decodable {
let output: String
}
struct Images: Decodable {
enum Format: String, Decodable {
case svg
case png
case webp
}
struct FormatOptions: Decodable {
enum Encoding: String, Decodable {
case lossy
case lossless
}
let encoding: Encoding
let quality: Int?
}
let output: String
let format: Format
let webpOptions: FormatOptions?
}
let mainRes: URL
let icons: Icons?
let images: Images?
}
let figma: Figma
let common: Common?
let ios: iOS?
let android: Android?
}
| 25.779528 | 61 | 0.52474 |
fcd86575c2527394345f6eb0a558263d1a04b40f | 216 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct c<T where h: B
struct B<T {
var f: B<c>
| 27 | 87 | 0.740741 |
720735832de25e4ead9e28b019c185f7731b3cdf | 56 | @_exported import Foundation
@_exported import ShellKit
| 18.666667 | 28 | 0.857143 |
6a7002479331b3fd42166a4f9b0d6c5dbf96bb89 | 9,749 | //
// FloatRatingView.swift
// Rating Demo
//
// Created by Glen Yi on 2014-09-05.
// Copyright (c) 2014 On The Pursuit. All rights reserved.
//
import Foundation
import UIKit
import CoreGraphics
@objc public protocol FloatRatingViewDelegate {
/// Returns the rating value when touch events end
@objc optional func floatRatingView(_ ratingView: FloatRatingView, didUpdate rating: Double)
/// Returns the rating value as the user pans
@objc optional func floatRatingView(_ ratingView: FloatRatingView, isUpdating rating: Double)
}
/// A simple rating view that can set whole, half or floating point ratings.
@IBDesignable
@objcMembers
open class FloatRatingView: UIView {
// MARK: Properties
open weak var delegate: FloatRatingViewDelegate?
/// Array of empty image views
private var emptyImageViews: [UIImageView] = []
/// Array of full image views
private var fullImageViews: [UIImageView] = []
/// Sets the empty image (e.g. a star outline)
@IBInspectable open var emptyImage: UIImage? {
didSet {
// Update empty image views
for imageView in emptyImageViews {
imageView.image = emptyImage
}
refresh()
}
}
/// Sets the full image that is overlayed on top of the empty image.
/// Should be same size and shape as the empty image.
@IBInspectable open var fullImage: UIImage? {
didSet {
// Update full image views
for imageView in fullImageViews {
imageView.image = fullImage
}
refresh()
}
}
/// Sets the empty and full image view content mode.
open var imageContentMode: UIView.ContentMode = .scaleAspectFit
/// Minimum rating.
@IBInspectable open var minRating: Int = 0 {
didSet {
// Update current rating if needed
if rating < Double(minRating) {
rating = Double(minRating)
refresh()
}
}
}
/// Max rating value.
@IBInspectable open var maxRating: Int = 5 {
didSet {
if maxRating != oldValue {
removeImageViews()
initImageViews()
// Relayout and refresh
setNeedsLayout()
refresh()
}
}
}
/// Minimum image size.
@IBInspectable open var minImageSize = CGSize(width: 5.0, height: 5.0)
/// Set the current rating.
@IBInspectable open var rating: Double = 0 {
didSet {
if rating != oldValue {
refresh()
}
}
}
/// Sets whether or not the rating view can be changed by panning.
@IBInspectable open var editable = true
// MARK: Type
@objc public enum FloatRatingViewType: Int {
/// Integer rating
case wholeRatings
/// Double rating in increments of 0.5
case halfRatings
/// Double rating
case floatRatings
/// Returns true if rating can contain decimal places
func supportsFractions() -> Bool {
return self == .halfRatings || self == .floatRatings
}
}
/// Float rating view type
@IBInspectable open var type: FloatRatingViewType = .wholeRatings
// MARK: Initializations
required override public init(frame: CGRect) {
super.init(frame: frame)
initImageViews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initImageViews()
}
// MARK: Helper methods
private func initImageViews() {
guard emptyImageViews.isEmpty && fullImageViews.isEmpty else {
return
}
// Add new image views
for _ in 0..<maxRating {
let emptyImageView = UIImageView()
emptyImageView.contentMode = imageContentMode
emptyImageView.image = emptyImage
emptyImageViews.append(emptyImageView)
addSubview(emptyImageView)
let fullImageView = UIImageView()
fullImageView.contentMode = imageContentMode
fullImageView.image = fullImage
fullImageViews.append(fullImageView)
addSubview(fullImageView)
}
}
private func removeImageViews() {
// Remove old image views
for i in 0..<emptyImageViews.count {
var imageView = emptyImageViews[i]
imageView.removeFromSuperview()
imageView = fullImageViews[i]
imageView.removeFromSuperview()
}
emptyImageViews.removeAll(keepingCapacity: false)
fullImageViews.removeAll(keepingCapacity: false)
}
// Refresh hides or shows full images
private func refresh() {
for i in 0..<fullImageViews.count {
let imageView = fullImageViews[i]
if rating >= Double(i+1) {
imageView.layer.mask = nil
imageView.isHidden = false
} else if rating > Double(i) && rating < Double(i+1) {
// Set mask layer for full image
let maskLayer = CALayer()
maskLayer.frame = CGRect(x: 0, y: 0, width: CGFloat(rating-Double(i))*imageView.frame.size.width, height: imageView.frame.size.height)
maskLayer.backgroundColor = UIColor.black.cgColor
imageView.layer.mask = maskLayer
imageView.isHidden = false
} else {
imageView.layer.mask = nil;
imageView.isHidden = true
}
}
}
// Calculates the ideal ImageView size in a given CGSize
private func sizeForImage(_ image: UIImage, inSize size: CGSize) -> CGSize {
let imageRatio = image.size.width / image.size.height
let viewRatio = size.width / size.height
if imageRatio < viewRatio {
let scale = size.height / image.size.height
let width = scale * image.size.width
return CGSize(width: width, height: size.height)
} else {
let scale = size.width / image.size.width
let height = scale * image.size.height
return CGSize(width: size.width, height: height)
}
}
// Calculates new rating based on touch location in view
private func updateLocation(_ touch: UITouch) {
guard editable else {
return
}
let touchLocation = touch.location(in: self)
var newRating: Double = 0
for i in stride(from: (maxRating-1), through: 0, by: -1) {
let imageView = emptyImageViews[i]
guard touchLocation.x > imageView.frame.origin.x else {
continue
}
// Find touch point in image view
let newLocation = imageView.convert(touchLocation, from: self)
// Find decimal value for float or half rating
if imageView.point(inside: newLocation, with: nil) && (type.supportsFractions()) {
let decimalNum = Double(newLocation.x / imageView.frame.size.width)
newRating = Double(i) + decimalNum
if type == .halfRatings {
newRating = Double(i) + (decimalNum > 0.75 ? 1 : (decimalNum > 0.25 ? 0.5 : 0))
}
} else {
// Whole rating
newRating = Double(i) + 1.0
}
break
}
// Check min rating
rating = newRating < Double(minRating) ? Double(minRating) : newRating
// Update delegate
delegate?.floatRatingView?(self, isUpdating: rating)
}
// MARK: UIView
// Override to calculate ImageView frames
override open func layoutSubviews() {
super.layoutSubviews()
guard let emptyImage = emptyImage else {
return
}
let desiredImageWidth = frame.size.width / CGFloat(emptyImageViews.count)
let maxImageWidth = max(minImageSize.width, desiredImageWidth)
let maxImageHeight = max(minImageSize.height, frame.size.height)
let imageViewSize = sizeForImage(emptyImage, inSize: CGSize(width: maxImageWidth, height: maxImageHeight))
let imageXOffset = (frame.size.width - (imageViewSize.width * CGFloat(emptyImageViews.count))) /
CGFloat((emptyImageViews.count - 1))
for i in 0..<maxRating {
let imageFrame = CGRect(x: i == 0 ? 0 : CGFloat(i)*(imageXOffset+imageViewSize.width), y: 0, width: imageViewSize.width, height: imageViewSize.height)
var imageView = emptyImageViews[i]
imageView.frame = imageFrame
imageView = fullImageViews[i]
imageView.frame = imageFrame
}
refresh()
}
// MARK: Touch events
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
updateLocation(touch)
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
updateLocation(touch)
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
// Update delegate
delegate?.floatRatingView?(self, didUpdate: rating)
}
override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
// Update delegate
delegate?.floatRatingView?(self, didUpdate: rating)
}
}
| 31.859477 | 162 | 0.583137 |
14886a37577d2b03b98c929e9bb413c9c15c47b6 | 9,019 | import XCTest
import Foundation
@testable import Library
@testable import KsApi
final class AppEnvironmentTests: XCTestCase {
func testPushAndPopEnvironment() {
let lang = AppEnvironment.current.language
AppEnvironment.pushEnvironment()
XCTAssertEqual(lang, AppEnvironment.current.language)
AppEnvironment.pushEnvironment(language: .es)
XCTAssertEqual(Language.es, AppEnvironment.current.language)
AppEnvironment.pushEnvironment(Environment(language: .en))
XCTAssertEqual(Language.en, AppEnvironment.current.language)
AppEnvironment.popEnvironment()
XCTAssertEqual(Language.es, AppEnvironment.current.language)
AppEnvironment.popEnvironment()
XCTAssertEqual(lang, AppEnvironment.current.language)
AppEnvironment.popEnvironment()
}
func testReplaceCurrentEnvironment() {
AppEnvironment.pushEnvironment(language: .es)
XCTAssertEqual(AppEnvironment.current.language, Language.es)
AppEnvironment.pushEnvironment(language: .fr)
XCTAssertEqual(AppEnvironment.current.language, Language.fr)
AppEnvironment.replaceCurrentEnvironment(language: Language.de)
XCTAssertEqual(AppEnvironment.current.language, Language.de)
AppEnvironment.popEnvironment()
XCTAssertEqual(AppEnvironment.current.language, Language.es)
AppEnvironment.popEnvironment()
}
func testPersistenceKey() {
XCTAssertEqual("com.kickstarter.AppEnvironment.current", AppEnvironment.environmentStorageKey,
"Failing this test means users will get logged out, so you better have a good reason.")
XCTAssertEqual("com.kickstarter.AppEnvironment.oauthToken", AppEnvironment.oauthTokenStorageKey,
"Failing this means user's token will be lost, so you better have a good reason.")
}
func testUserSession() {
AppEnvironment.pushEnvironment()
XCTAssertNil(AppEnvironment.current.apiService.oauthToken)
XCTAssertNil(AppEnvironment.current.currentUser)
AppEnvironment.login(AccessTokenEnvelope(accessToken: "deadbeef", user: User.template))
XCTAssertEqual("deadbeef", AppEnvironment.current.apiService.oauthToken?.token)
XCTAssertEqual(User.template, AppEnvironment.current.currentUser)
AppEnvironment.updateCurrentUser(User.template)
XCTAssertEqual("deadbeef", AppEnvironment.current.apiService.oauthToken?.token)
XCTAssertEqual(User.template, AppEnvironment.current.currentUser)
AppEnvironment.logout()
XCTAssertNil(AppEnvironment.current.apiService.oauthToken)
XCTAssertNil(AppEnvironment.current.currentUser)
AppEnvironment.popEnvironment()
}
func testFromStorage_WithNothingStored() {
let userDefaults = MockKeyValueStore()
let ubiquitousStore = MockKeyValueStore()
let env = AppEnvironment.fromStorage(ubiquitousStore: ubiquitousStore, userDefaults: userDefaults)
XCTAssertNil(env.apiService.oauthToken?.token)
XCTAssertEqual(nil, env.currentUser)
}
func testFromStorage_WithFullDataStored() {
let userDefaults = MockKeyValueStore()
let ubiquitousStore = MockKeyValueStore()
let user = User.template
userDefaults.set(
[
"apiService.oauthToken.token": "deadbeef",
"apiService.serverConfig.apiBaseUrl": "http://api.ksr.com",
"apiService.serverConfig.apiClientAuth.clientId": "cafebeef",
"apiService.serverConfig.basicHTTPAuth.username": "hola",
"apiService.serverConfig.basicHTTPAuth.password": "mundo",
"apiService.serverConfig.webBaseUrl": "http://ksr.com",
"apiService.language": "en",
"currentUser": user.encode()
],
forKey: AppEnvironment.environmentStorageKey)
let env = AppEnvironment.fromStorage(ubiquitousStore: ubiquitousStore, userDefaults: userDefaults)
XCTAssertEqual("deadbeef", env.apiService.oauthToken?.token)
XCTAssertEqual("http://api.ksr.com", env.apiService.serverConfig.apiBaseUrl.absoluteString)
XCTAssertEqual("cafebeef", env.apiService.serverConfig.apiClientAuth.clientId)
XCTAssertEqual("hola", env.apiService.serverConfig.basicHTTPAuth?.username)
XCTAssertEqual("mundo", env.apiService.serverConfig.basicHTTPAuth?.password)
XCTAssertEqual("http://ksr.com", env.apiService.serverConfig.webBaseUrl.absoluteString)
XCTAssertEqual(user, env.currentUser)
XCTAssertEqual(user, env.koala.loggedInUser)
let differentEnv = AppEnvironment.fromStorage(ubiquitousStore: MockKeyValueStore(),
userDefaults: MockKeyValueStore())
XCTAssertNil(differentEnv.apiService.oauthToken?.token)
XCTAssertEqual(nil, differentEnv.currentUser)
}
func testFromStorage_LegacyUserDefaults() {
let userDefaults = MockKeyValueStore()
userDefaults.set("deadbeef", forKey: "com.kickstarter.access_token")
let env = AppEnvironment.fromStorage(ubiquitousStore: MockKeyValueStore(), userDefaults: userDefaults)
XCTAssertEqual("deadbeef", env.apiService.oauthToken?.token)
XCTAssertTrue(env.apiService.isAuthenticated)
XCTAssertNil(userDefaults.object(forKey: "com.kickstarter.access_token"))
}
func testSaveEnvironment() {
// swiftlint:disable force_unwrapping
let apiService = MockService(
serverConfig: ServerConfig(
apiBaseUrl: URL(string: "http://api.ksr.com")!,
webBaseUrl: URL(string: "http://ksr.com")!,
apiClientAuth: ClientAuth(clientId: "cafebeef"),
basicHTTPAuth: nil,
graphQLEndpointUrl: URL(string: "http://ksr.dev/graph")!
),
oauthToken: OauthToken(token: "deadbeef")
)
// swiftlint:enable force_unwrapping
let currentUser = User.template
let userDefaults = MockKeyValueStore()
let ubiquitousStore = MockKeyValueStore()
AppEnvironment.saveEnvironment(environment: Environment(apiService: apiService, currentUser: currentUser),
ubiquitousStore: ubiquitousStore,
userDefaults: userDefaults)
// swiftlint:disable:next force_unwrapping
let result = userDefaults.dictionary(forKey: AppEnvironment.environmentStorageKey)!
XCTAssertEqual("deadbeef", result["apiService.oauthToken.token"] as? String)
XCTAssertEqual("http://api.ksr.com", result["apiService.serverConfig.apiBaseUrl"] as? String)
XCTAssertEqual("cafebeef", result["apiService.serverConfig.apiClientAuth.clientId"] as? String)
XCTAssertEqual("http://ksr.com", result["apiService.serverConfig.webBaseUrl"] as? String)
XCTAssertEqual("en", result["apiService.language"] as? String)
XCTAssertEqual(User.template.id, (result["currentUser"] as? [String: AnyObject])?["id"] as? Int)
XCTAssertEqual(nil, ubiquitousStore.string(forKey: AppEnvironment.oauthTokenStorageKey),
"No token stored.")
}
func testRestoreFromEnvironment() {
let apiService = MockService(serverConfig: ServerConfig.production,
oauthToken: OauthToken(token: "deadbeef"))
let currentUser = User.template
let userDefaults = MockKeyValueStore()
let ubiquitousStore = MockKeyValueStore()
AppEnvironment.saveEnvironment(environment: Environment(apiService: apiService, currentUser: currentUser),
ubiquitousStore: ubiquitousStore,
userDefaults: userDefaults)
let env = AppEnvironment.fromStorage(ubiquitousStore: ubiquitousStore, userDefaults: userDefaults)
XCTAssertEqual("deadbeef", env.apiService.oauthToken?.token)
XCTAssertEqual(ServerConfig.production.apiBaseUrl.absoluteString,
env.apiService.serverConfig.apiBaseUrl.absoluteString)
XCTAssertEqual(ServerConfig.production.apiClientAuth.clientId,
env.apiService.serverConfig.apiClientAuth.clientId)
XCTAssertNil(ServerConfig.production.basicHTTPAuth)
XCTAssertEqual(ServerConfig.production.webBaseUrl.absoluteString,
env.apiService.serverConfig.webBaseUrl.absoluteString)
XCTAssertEqual(currentUser, env.currentUser)
XCTAssertEqual(currentUser, env.koala.loggedInUser)
}
func testPushPopSave() {
AppEnvironment.pushEnvironment(ubiquitousStore: MockKeyValueStore(),
userDefaults: MockKeyValueStore())
AppEnvironment.pushEnvironment(currentUser: User.template)
var currentUserId = AppEnvironment.current.userDefaults
.dictionary(forKey: AppEnvironment.environmentStorageKey)
.flatMap { $0["currentUser"] as? [String: AnyObject] }
.flatMap { $0["id"] as? Int }
XCTAssertEqual(User.template.id, currentUserId, "Current user is saved.")
AppEnvironment.popEnvironment()
currentUserId = AppEnvironment.current.userDefaults
.dictionary(forKey: AppEnvironment.environmentStorageKey)
.flatMap { $0["currentUser"] as? [String: AnyObject] }
.flatMap { $0["id"] as? Int }
XCTAssertEqual(nil, currentUserId, "Current user is cleared.")
AppEnvironment.popEnvironment()
}
}
| 41.75463 | 110 | 0.735337 |
3a4924a8409710faa29c81c77065531433858967 | 1,206 | //
// ThemeManagerMock.swift
// Deluge
//
// Created by Yotam Ohayon on 17/05/2017.
// Copyright © 2017 Yotam Ohayon. All rights reserved.
//
import UIKit
import Delugion
@testable import Deluge
/*
class ThemeManagerMock: ThemeServicing {
let trackColor = UIColor(red: 239, green: 239, blue: 244)
func progressColor(forTorrentState state: TorrentState) -> UIColor {
switch state {
case .downloading, .seeding: return UIColor(red: 0, green: 122.0, blue: 255.0)
case .paused: return UIColor(red: 199.0, green: 199.0, blue: 204.0)
default: return UIColor(red: 239.0, green: 239.0, blue: 244.0)
}
}
func progressNumericColor(forTorrentState state: TorrentState) -> UIColor {
switch state {
case .downloading: return UIColor(red: 0, green: 122.0, blue: 255.0)
case .paused: return UIColor(red: 178, green: 178, blue: 178)
default: return .clear
}
}
func progressBackgroundColor(forTorrentState state: TorrentState) -> UIColor {
switch state {
case .seeding: return UIColor(red: 0, green: 117.0, blue: 255.0)
default: return .clear
}
}
}
*/
| 28.714286 | 86 | 0.628524 |
1a5ff38fae760c8ab77d99dcb5f7f2a27abe383f | 527 | //
// CourseStatistic.swift
// QLDD
//
// Created by Bui Nhat Khoi on 1/25/18.
// Copyright © 2018 Bui Nhat Khoi. All rights reserved.
//
import Foundation
struct CourseStatistic {
var code : String
var name : String
var attendanceCounts : Int
var absenceCounts : Int
var attendanceDetails : [AttendanceDetail]
init(){
self.code = ""
self.name = ""
self.attendanceCounts = 0
self.absenceCounts = 0
self.attendanceDetails = [AttendanceDetail]()
}
}
| 20.269231 | 56 | 0.622391 |
0a9004afea6cbb72c0ce470c72ab484faa6d0748 | 1,738 | import Foundation
open class StandardLoggerFormatter: FieldBasedLoggerFormatter {
/// Initializes a new `StandardLoggerFormatter` instance.
/// - Parameters:
/// - timestampStyle: Governs the formatting of the timestamp in the log output. Pass `nil` to suppress output of the timestamp.
/// - severityStyle: Governs the formatting of the `LoggerSeverity` in the log output. Pass `nil` to suppress output of the severity.
/// - delimiterStyle: If provided, overrides the default field separator delimiters. Pass `nil` to use the default delimiters.
/// - callingThreadStyle: If provided, specifies a `CallingThreadStyle` to use for representing the calling thread. If `nil`, the calling thread is not shown.
/// - showCallSite: If `true`, the source file and line indicating the call site of the log request will be added to formatted log messages.
public init(
timestampStyle: TimestampStyle? = .default,
severityStyle: SeverityStyle? = .simple,
delimiterStyle: DelimiterStyle? = nil,
callingThreadStyle: CallingThreadStyle? = .hex,
showCallSite: Bool = true
) {
var fields: [Field] = []
if let timestampStyle = timestampStyle {
fields += [
.timestamp(timestampStyle),
.delimiter(delimiterStyle ?? .spacedPipe),
]
}
if let severityStyle = severityStyle {
fields += [
.severity(severityStyle),
.delimiter(delimiterStyle ?? .spacedPipe),
]
}
if let callingThreadStyle = callingThreadStyle {
fields += [
.callingThread(callingThreadStyle),
.delimiter(delimiterStyle ?? .spacedPipe),
]
}
if showCallSite {
fields += [
.callSite,
.delimiter(delimiterStyle ?? .spacedHyphen),
]
}
fields += [.payload]
super.init(fields: fields)
}
}
| 36.208333 | 161 | 0.710012 |
213e7de42bd7cdea4c4b95e49a4afa86cff328bd | 8,392 | //
// Copyright (C) 2005-2020 Alfresco Software Limited.
//
// This file is part of the Alfresco Content Mobile iOS App.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import AlfrescoContent
import Alamofire
import MaterialComponents.MaterialDialogs
protocol CreateNodeViewModelDelegate: AnyObject {
func handleCreatedNode(node: ListNode?, error: Error?)
}
class CreateNodeViewModel {
private var coordinatorServices: CoordinatorServices?
private let nodeOperations: NodeOperations
private var actionMenu: ActionMenu
private var parentListNode: ListNode
private var nodeName: String?
private var nodeDescription: String?
private weak var delegate: CreateNodeViewModelDelegate?
private var uploadDialog: MDCAlertController?
private var uploadRequest: UploadRequest?
// MARK: - Init
init(with actionMenu: ActionMenu,
parentListNode: ListNode,
coordinatorServices: CoordinatorServices?,
delegate: CreateNodeViewModelDelegate?) {
self.coordinatorServices = coordinatorServices
self.nodeOperations = NodeOperations(accountService: coordinatorServices?.accountService)
self.actionMenu = actionMenu
self.parentListNode = parentListNode
self.delegate = delegate
}
// MARK: - Public
func createNode(with name: String, description: String?) {
self.nodeName = name
self.nodeDescription = description
if actionMenu.type != .createFolder {
uploadDialog = showUploadDialog(actionHandler: { [weak self] _ in
guard let sSelf = self else { return }
sSelf.uploadRequest?.cancel()
})
}
updateNodeDetails { [weak self] (listNode, _) in
guard let sSelf = self, let listNode = listNode else { return }
let shouldAutorename = (ListNode.getExtension(from: sSelf.actionMenu.type) != nil)
switch sSelf.actionMenu.type {
case .createFolder:
sSelf.createNewFolder(nodeId: listNode.guid,
autoRename: shouldAutorename)
case .createMSWord, .createMSExcel, .createMSPowerPoint:
sSelf.createMSOfficeNode(nodeId: listNode.guid,
autoRename: shouldAutorename)
case .createMedia, .uploadMedia: break
default: break
}
}
}
func creatingNewFolder() -> Bool {
return actionMenu.type == .createFolder
}
func createAction() -> String {
return actionMenu.title
}
// MARK: - Create Nodes
private func createNewFolder(nodeId: String,
autoRename: Bool) {
if let name = nodeName {
nodeOperations.createNode(nodeId: nodeId,
name: name,
description: nodeDescription,
autoRename: autoRename) { [weak self] (result, error) in
guard let sSelf = self else { return }
if let error = error {
sSelf.delegate?.handleCreatedNode(node: nil,
error: error)
AlfrescoLog.error(error)
} else if let listNode = result {
sSelf.delegate?.handleCreatedNode(node: listNode, error: nil)
sSelf.publishEventBus(with: listNode)
}
}
}
}
private func createMSOfficeNode(nodeId: String,
autoRename: Bool) {
if let dataTemplate = dataFromTemplateFile(),
let name = nodeName,
let nodeExtension = ListNode.getExtension(from: actionMenu.type) {
nodeOperations.createNode(nodeId: nodeId,
name: name,
description: nodeDescription,
nodeExtension: nodeExtension,
fileData: dataTemplate,
autoRename: autoRename) { [weak self] (result, error) in
guard let sSelf = self else { return }
sSelf.uploadDialog?.dismiss(animated: true)
if let transferError = error {
sSelf.handle(error: transferError)
} else if let listNode = result {
sSelf.delegate?.handleCreatedNode(node: listNode, error: nil)
sSelf.publishEventBus(with: listNode)
}
}
}
}
// MARK: - Private Utils
private func updateNodeDetails(handle: @escaping (ListNode?, Error?) -> Void) {
guard parentListNode.nodeType == .site else { return handle(parentListNode, nil)}
nodeOperations.fetchNodeDetails(for: parentListNode.guid,
relativePath: APIConstants.Path.relativeSites) { (result, error) in
var listNode: ListNode?
if let error = error {
AlfrescoLog.error(error)
} else if let entry = result?.entry {
listNode = NodeChildMapper.create(from: entry)
}
handle(listNode, error)
}
}
private func publishEventBus(with listNode: ListNode) {
let moveEvent = MoveEvent(node: parentListNode, eventType: .created)
let eventBusService = coordinatorServices?.eventBusService
eventBusService?.publish(event: moveEvent, on: .mainQueue)
}
private func dataFromTemplateFile() -> Data? {
guard let stringPath = ListNode.templateFileBundlePath(from: actionMenu.type)
else { return nil }
do {
return try Data(contentsOf: URL(fileURLWithPath: stringPath))
} catch {}
return nil
}
private func showUploadDialog(actionHandler: @escaping (MDCAlertAction) -> Void) -> MDCAlertController? {
if let uploadDialogView: DownloadDialog = .fromNib() {
let themingService = coordinatorServices?.themingService
let nodeExtension = ListNode.getExtension(from: actionMenu.type) ?? ""
let nodeNameWithExtension = ( nodeName ?? "" ) + nodeExtension
uploadDialogView.messageLabel.text =
String(format: LocalizationConstants.Dialog.uploadMessage,
nodeNameWithExtension)
uploadDialogView.activityIndicator.startAnimating()
uploadDialogView.applyTheme(themingService?.activeTheme)
let cancelAction =
MDCAlertAction(title: LocalizationConstants.General.cancel) { action in
actionHandler(action)
}
cancelAction.accessibilityIdentifier = "cancelActionButton"
if let presentationContext = UIViewController.applicationTopMostPresented {
let downloadDialog = presentationContext.showDialog(title: nil,
message: nil,
actions: [cancelAction],
accesoryView: uploadDialogView,
completionHandler: {})
return downloadDialog
}
}
return nil
}
private func handle(error: Error) {
if error.code == NSURLErrorNetworkConnectionLost ||
error.code == NSURLErrorCancelled {
delegate?.handleCreatedNode(node: nil, error: nil)
return
}
delegate?.handleCreatedNode(node: nil, error: error)
AlfrescoLog.error(error)
}
}
| 40.15311 | 109 | 0.580076 |
3aaf5a649feef2c723e1550390395ca5882d48e4 | 2,372 | //
// MultilineTableViewCell.swift
//
// Created by Daniel Loewenherz on 10/21/17.
// Copyright © 2017 Lionheart Software. All rights reserved.
//
import UIKit
import QuickTableView
import SuperLayout
final class MultilineTableViewCell: UITableViewCell {
var theTextLabel: UILabel!
var theDetailTextLabel: UILabel!
override var textLabel: UILabel? { return theTextLabel }
override var detailTextLabel: UILabel? { return theDetailTextLabel }
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
theTextLabel = UILabel()
theTextLabel.numberOfLines = 0
theTextLabel.lineBreakMode = .byWordWrapping
theTextLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
theTextLabel.translatesAutoresizingMaskIntoConstraints = false
theTextLabel.textColor = .black
theTextLabel.textAlignment = .left
theDetailTextLabel = UILabel()
theDetailTextLabel.numberOfLines = 0
theDetailTextLabel.lineBreakMode = .byWordWrapping
theDetailTextLabel.font = UIFont.systemFont(ofSize: 14, weight: .regular)
theDetailTextLabel.translatesAutoresizingMaskIntoConstraints = false
theDetailTextLabel.textColor = .darkGray
theDetailTextLabel.textAlignment = .left
contentView.addSubview(theTextLabel)
contentView.addSubview(theDetailTextLabel)
let margins = contentView.layoutMarginsGuide
theTextLabel.topAnchor ~~ margins.topAnchor
theTextLabel.leadingAnchor ~~ margins.leadingAnchor
theDetailTextLabel.topAnchor ~~ theTextLabel.bottomAnchor
theDetailTextLabel.leadingAnchor ~~ margins.leadingAnchor
theDetailTextLabel.bottomAnchor ~~ margins.bottomAnchor
theTextLabel.trailingAnchor ~~ margins.trailingAnchor
theDetailTextLabel.trailingAnchor ~~ margins.trailingAnchor
updateConstraintsIfNeeded()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension MultilineTableViewCell: QuickTableViewCellIdentifiable {
static var identifier: String { return "MultilineTableViewCellIdentifier" }
}
| 36.492308 | 81 | 0.713322 |
56169ec8e0e0b603295f99f25ababcfac2e2f02a | 2,164 | //===--- UTF8Decode.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
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let UTF8Decode = BenchmarkInfo(
name: "UTF8Decode",
runFunction: run_UTF8Decode,
tags: [.validation, .api, .String])
@inline(never)
public func run_UTF8Decode(_ N: Int) {
// 1-byte sequences
// This test case is the longest as it's the most performance sensitive.
let ascii = "Swift is a multi-paradigm, compiled programming language created for iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (\"safer\") than Objective-C and also more concise. It is built with the LLVM compiler framework included in Xcode 6 and later and uses the Objective-C runtime, which allows C, Objective-C, C++ and Swift code to run within a single program."
// 2-byte sequences
let russian = "Ру́сский язы́к один из восточнославянских языков, национальный язык русского народа."
// 3-byte sequences
let japanese = "日本語(にほんご、にっぽんご)は、主に日本国内や日本人同士の間で使われている言語である。"
// 4-byte sequences
// Most commonly emoji, which are usually mixed with other text.
let emoji = "Panda 🐼, Dog 🐶, Cat 🐱, Mouse 🐭."
let strings = [ascii, russian, japanese, emoji].map { Array($0.utf8) }
func isEmpty(_ result: UnicodeDecodingResult) -> Bool {
switch result {
case .emptyInput:
return true
default:
return false
}
}
for _ in 1...200*N {
for string in strings {
var it = string.makeIterator()
var utf8 = UTF8()
while !isEmpty(utf8.decode(&it)) { }
}
}
}
| 41.615385 | 591 | 0.667745 |
def191d17e6a68d211148ebc4af806754df18bb8 | 238 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a {
protocol d {
struct B {
{
}
let c = [ {
}
var {
class
case ,
| 15.866667 | 87 | 0.701681 |
e0d7d482808d3f445fd9b470d187c77511440401 | 2,690 | // --------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------
import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length
extension Queries {
/// User-configurable options for the `AutoRestUrlTestService.ArrayStringCsvNull` operation.
public struct ArrayStringCsvNullOptions: RequestOptions {
/// a null array of string using the csv-array format
public let arrayQuery: [String]?
/// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
/// Highly recommended for correlating client-side activites with requests received by the server.
public let clientRequestId: String?
/// A token used to make a best-effort attempt at canceling a request.
public let cancellationToken: CancellationToken?
/// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
public var dispatchQueue: DispatchQueue?
/// A `PipelineContext` object to associate with the request.
public var context: PipelineContext?
/// Initialize a `ArrayStringCsvNullOptions` structure.
/// - Parameters:
/// - arrayQuery: a null array of string using the csv-array format
/// - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
/// - cancellationToken: A token used to make a best-effort attempt at canceling a request.
/// - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
/// - context: A `PipelineContext` object to associate with the request.
public init(
arrayQuery: [String]? = nil,
clientRequestId: String? = nil,
cancellationToken: CancellationToken? = nil,
dispatchQueue: DispatchQueue? = nil,
context: PipelineContext? = nil
) {
self.arrayQuery = arrayQuery
self.clientRequestId = clientRequestId
self.cancellationToken = cancellationToken
self.dispatchQueue = dispatchQueue
self.context = context
}
}
}
| 45.59322 | 126 | 0.648699 |
718a5a1b07257244eb8d48628740291d079885d6 | 4,061 | //
// StackedBarChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
import UIKit
import Charts
class StackedBarChartViewController: DemoBaseViewController {
@IBOutlet var chartView: BarChartView!
@IBOutlet var sliderX: UISlider!
@IBOutlet var sliderY: UISlider!
@IBOutlet var sliderTextX: UITextField!
@IBOutlet var sliderTextY: UITextField!
lazy var formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
formatter.negativeSuffix = " $"
formatter.positiveSuffix = " $"
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Stacked Bar Chart"
self.options = [.toggleValues,
.toggleIcons,
.toggleHighlight,
.animateX,
.animateY,
.animateXY,
.saveToGallery,
.togglePinchZoom,
.toggleAutoScaleMinMax,
.toggleData,
.toggleBarBorders]
chartView.delegate = self
chartView.chartDescription?.enabled = false
chartView.maxVisibleCount = 40
chartView.drawBarShadowEnabled = false
chartView.drawValueAboveBarEnabled = false
chartView.highlightFullBarEnabled = false
let leftAxis = chartView.leftAxis
leftAxis.valueFormatter = DefaultAxisValueFormatter(formatter: formatter)
leftAxis.axisMinimum = 0
chartView.rightAxis.enabled = false
let xAxis = chartView.xAxis
xAxis.labelPosition = .top
let l = chartView.legend
l.horizontalAlignment = .right
l.verticalAlignment = .bottom
l.orientation = .horizontal
l.drawInside = false
l.form = .square
l.formToTextSpace = 4
l.xEntrySpace = 6
// chartView.legend = l
sliderX.value = 12
sliderY.value = 100
slidersValueChanged(nil)
self.updateChartData()
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setChartData(count: Int(sliderX.value + 1), range: UInt32(sliderY.value))
}
func setChartData(count: Int, range: UInt32) {
let yVals = (0..<count).map { (i) -> BarChartDataEntry in
let mult = range + 1
let val1 = Double(arc4random_uniform(mult) + mult / 3)
let val2 = Double(arc4random_uniform(mult) + mult / 3)
let val3 = Double(arc4random_uniform(mult) + mult / 3)
return BarChartDataEntry(x: Double(i), yValues: [val1, val2, val3], icon: #imageLiteral(resourceName: "icon"))
}
let set = BarChartDataSet(values: yVals, label: "Statistics Vienna 2014")
set.drawIconsEnabled = false
set.colors = [ChartColorTemplates.material()[0], ChartColorTemplates.material()[1], ChartColorTemplates.material()[2]]
set.stackLabels = ["Births", "Divorces", "Marriages"]
let data = BarChartData(dataSet: set)
data.setValueFont(.systemFont(ofSize: 7, weight: .light))
data.setValueFormatter(DefaultValueFormatter(formatter: formatter))
data.setValueTextColor(.white)
chartView.fitBars = true
chartView.data = data
}
override func optionTapped(_ option: Option) {
super.handleOption(option, forChartView: chartView)
}
@IBAction func slidersValueChanged(_ sender: Any?) {
sliderTextX.text = "\(Int(sliderX.value))"
sliderTextY.text = "\(Int(sliderY.value))"
updateChartData()
}
}
| 32.230159 | 126 | 0.584339 |
562f07f56cbc11328444a243854a1c0652ed59f8 | 2,764 | //
// Tesseract+Layout.swift
//
//
// Created by Winston Chen on 11/3/21.
//
import Foundation
import libtesseract
public typealias PageSegmentationMode = TessPageSegMode
public extension PageSegmentationMode {
static let osdOnly = PSM_OSD_ONLY
static let autoOsd = PSM_AUTO_OSD
static let autoOnly = PSM_AUTO_ONLY
static let auto = PSM_AUTO
static let singleColumn = PSM_SINGLE_COLUMN
static let singleBlockVerticalText = PSM_SINGLE_BLOCK_VERT_TEXT
static let singleBlock = PSM_SINGLE_BLOCK
static let singleLine = PSM_SINGLE_LINE
static let singleWord = PSM_SINGLE_WORD
static let circleWord = PSM_CIRCLE_WORD
static let singleCharacter = PSM_SINGLE_CHAR
static let sparseText = PSM_SPARSE_TEXT
static let sparseTextOsd = PSM_SPARSE_TEXT_OSD
static let count = PSM_COUNT
}
public extension Tesseract {
var pageSegmentationMode: PageSegmentationMode {
get {
perform { tessPointer in
TessBaseAPIGetPageSegMode(tessPointer)
}
}
set {
perform { tessPointer in
TessBaseAPISetPageSegMode(tessPointer, newValue)
}
}
}
func analyseLayout(on data: Data) -> [RecognizedBlock] {
return perform { tessPointer -> [RecognizedBlock] in
var pix = createPix(from: data)
defer { pixDestroy(&pix) }
TessBaseAPISetImage2(tessPointer, pix)
if TessBaseAPIGetSourceYResolution(tessPointer) < 70 {
TessBaseAPISetSourceResolution(tessPointer, 300)
}
guard TessBaseAPIAnalyseLayout(tessPointer) != nil else {
print("Tesseract: Error Analyzing Layout")
return []
}
let results = recognizedLayoutBlocks(with: tessPointer)
do {
let blocks = try results.get()
return blocks
} catch {
print("Error retrieving the value: \(error)")
return []
}
}
}
private func recognizedLayoutBlocks(with pointer: TessBaseAPI) -> Result<[RecognizedBlock], Error> {
guard let resultIterator = TessBaseAPIGetIterator(pointer)
else { return .failure(Tesseract.Error.unableToRetrieveIterator) }
defer { TessPageIteratorDelete(resultIterator) }
var results = [RecognizedBlock]()
repeat {
var box = BoundingBox()
TessPageIteratorBoundingBox(resultIterator, .block, &box.left, &box.top, &box.right, &box.bottom)
results.append(RecognizedBlock(text: "", boundingBox: box, confidence: 0))
} while (TessPageIteratorNext(resultIterator, .block) > 0)
return .success(results)
}
}
| 34.55 | 109 | 0.641462 |
89d6c8e6cd7f779db95a5b758e1d97b0ff928ae0 | 692 | //
// Type1HeaderView.swift
// AppStoreTransitionAnimation
//
// Created by Razvan Chelemen on 15/05/2019.
// Copyright © 2019 appssemble. All rights reserved.
//
import UIKit
class Type1HeaderView: UIView {
@IBOutlet weak var topContainerView: UIView!
@IBOutlet weak var playerImageView: UIImageView!
@IBOutlet weak var subtitleLabel: UILabel!
@IBOutlet weak var backgroundImage: UIImageView!
@IBOutlet weak var topContainerHeight: NSLayoutConstraint!
@IBOutlet weak var textWidth: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
textWidth.constant = UIScreen.main.bounds.width - 32.0
}
}
| 25.62963 | 62 | 0.705202 |
d7c2ce2d36b9fc969a57c85a90b1f36f8d4488d2 | 3,082 | import Foundation
//Given the root of a binary tree, return the preorder traversal of its nodes' values.
//
//
//
//Example 1:
//
//
//Input: root = [1,null,2,3]
//Output: [1,2,3]
//Example 2:
//
//Input: root = []
//Output: []
//Example 3:
//
//Input: root = [1]
//Output: [1]
//Example 4:
//
//
//Input: root = [1,2]
//Output: [1,2]
//Example 5:
//
//
//Input: root = [1,null,2]
//Output: [1,2]
//
//
//ConstraTs:
//
//The number of nodes in the tree is in the range [0, 100].
//-100 <= Node.val <= 100
//
//
//Follow up: Recursive solution is trivial, could you do it iteratively?
//
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int = 0,
_ left: TreeNode? = nil,
_ right: TreeNode? = nil) {
self.val = val
self.left = left
self.right = right
}
}
//class Solution {
// func preorderTraversal(_ root: TreeNode?) -> [Int] {
// var result: [Int] = []
// traversePreOrder(current: root) { value in
// result.append(value)
// }
// return result
// }
//
// public func traversePreOrder(current: TreeNode?, visit: (Int) -> Void) {
// guard let cur = current else { return }
// visit(cur.val)
// traversePreOrder(current: cur.left, visit: visit)
// traversePreOrder(current: cur.right, visit: visit)
//
// }
//}
class Solution {
func preorderTraversal(_ root: TreeNode?) -> [Int] {
let stack = MyStack<TreeNode>()
var result: [Int] = []
guard let node = root else { return result }
stack.push(node)
while !stack.empty() {
guard let topNode = stack.pop() else {
break
}
result.append(topNode.val)
if let rightNode = topNode.right {
stack.push(rightNode)
}
if let leftNode = topNode.left {
stack.push(leftNode)
}
}
return result
}
public func stackPreOrder(current: TreeNode?, visit: (Int) -> Void) {
guard let cur = current else { return }
// visit(cur.val)
// traversePreOrder(current: cur.left, visit: visit)
// traversePreOrder(current: cur.right, visit: visit)
}
}
class MyStack<T> {
var array: [T] = []
/** Initialize your data structure here. */
init() {
}
/** Push element x onto stack. */
func push(_ x: T) {
array.append(x)
}
/** Removes the element on top of the stack and returns that element. */
func pop() -> T? {
array.popLast()
}
/** Get the top element. */
func top() -> T? {
array.last
}
/** Returns whether the stack is empty. */
func empty() -> Bool {
array.isEmpty
}
}
| 21.552448 | 86 | 0.528553 |
e0df2e425cc3d8f1e5a3fbc83f1508a808ff7138 | 3,898 | import VioletCore
import VioletParser
import VioletBytecode
extension CodeObjectBuilder {
// MARK: - Variables
internal func appendName(name: MangledName, context: ExpressionContext) {
switch context {
case .store: self.appendStoreName(name)
case .load: self.appendLoadName(name)
case .del: self.appendDeleteName(name)
}
}
internal func appendGlobal(name: String, context: ExpressionContext) {
switch context {
case .store: self.appendStoreGlobal(name)
case .load: self.appendLoadGlobal(name)
case .del: self.appendDeleteGlobal(name)
}
}
internal func appendGlobal(name: MangledName, context: ExpressionContext) {
switch context {
case .store: self.appendStoreGlobal(name)
case .load: self.appendLoadGlobal(name)
case .del: self.appendDeleteGlobal(name)
}
}
internal func appendFast(name: MangledName, context: ExpressionContext) {
switch context {
case .store: self.appendStoreFast(name)
case .load: self.appendLoadFast(name)
case .del: self.appendDeleteFast(name)
}
}
internal func appendCell(name: MangledName, context: ExpressionContext) {
switch context {
case .store: self.appendStoreCell(name)
case .load: self.appendLoadCell(name)
case .del: self.appendDeleteCell(name)
}
}
internal func appendFree(name: MangledName, context: ExpressionContext) {
switch context {
case .store: self.appendStoreFree(name)
case .load: self.appendLoadFree(name)
case .del: self.appendDeleteFree(name)
}
}
// MARK: - Operators
internal func appendUnaryOperator(_ op: UnaryOpExpr.Operator) {
switch op {
case .invert: self.appendUnaryInvert()
case .not: self.appendUnaryNot()
case .plus: self.appendUnaryPositive()
case .minus: self.appendUnaryNegative()
}
}
internal func appendBinaryOperator(_ op: BinaryOpExpr.Operator) {
switch op {
case .add: self.appendBinaryAdd()
case .sub: self.appendBinarySubtract()
case .mul: self.appendBinaryMultiply()
case .matMul: self.appendBinaryMatrixMultiply()
case .div: self.appendBinaryTrueDivide()
case .modulo: self.appendBinaryModulo()
case .pow: self.appendBinaryPower()
case .leftShift: self.appendBinaryLShift()
case .rightShift: self.appendBinaryRShift()
case .bitOr: self.appendBinaryOr()
case .bitXor: self.appendBinaryXor()
case .bitAnd: self.appendBinaryAnd()
case .floorDiv: self.appendBinaryFloorDivide()
}
}
internal func appendInPlaceOperator(_ op: BinaryOpExpr.Operator) {
switch op {
case .add: self.appendInPlaceAdd()
case .sub: self.appendInPlaceSubtract()
case .mul: self.appendInPlaceMultiply()
case .matMul: self.appendInPlaceMatrixMultiply()
case .div: self.appendInPlaceTrueDivide()
case .modulo: self.appendInPlaceModulo()
case .pow: self.appendInPlacePower()
case .leftShift: self.appendInPlaceLShift()
case .rightShift: self.appendInPlaceRShift()
case .bitOr: self.appendInPlaceOr()
case .bitXor: self.appendInPlaceXor()
case .bitAnd: self.appendInPlaceAnd()
case .floorDiv: self.appendInPlaceFloorDivide()
}
}
// MARK: - Compare
/// Append a `compareOp` instruction to code object.
internal func appendCompareOp(operator: CompareExpr.Operator) {
switch `operator` {
case .equal: self.appendCompareOp(type: .equal)
case .notEqual: self.appendCompareOp(type: .notEqual)
case .less: self.appendCompareOp(type: .less)
case .lessEqual: self.appendCompareOp(type: .lessEqual)
case .greater: self.appendCompareOp(type: .greater)
case .greaterEqual: self.appendCompareOp(type: .greaterEqual)
case .is: self.appendCompareOp(type: .is)
case .isNot: self.appendCompareOp(type: .isNot)
case .in: self.appendCompareOp(type: .in)
case .notIn: self.appendCompareOp(type: .notIn)
}
}
}
| 31.95082 | 77 | 0.712417 |
72e2aad2a87090dbde1923a6e65fdb60e0c42a1e | 8,462 | // swiftlint:disable all
// Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen
#if os(macOS)
import AppKit
#elseif os(iOS)
import ARKit
import UIKit
#elseif os(tvOS) || os(watchOS)
import UIKit
#endif
// Deprecated typealiases
@available(*, deprecated, renamed: "XCTColorAsset.Color", message: "This typealias will be removed in SwiftGen 7.0")
internal typealias XCTColor = XCTColorAsset.Color
@available(*, deprecated, renamed: "XCTImageAsset.Image", message: "This typealias will be removed in SwiftGen 7.0")
internal typealias XCTImage = XCTImageAsset.Image
// swiftlint:disable superfluous_disable_command file_length implicit_return
// MARK: - Asset Catalogs
// swiftlint:disable identifier_name line_length nesting type_body_length type_name
internal enum XCTAssets {
internal enum Files {
internal static let data = XCTDataAsset(name: "Data")
internal enum Json {
internal static let data = XCTDataAsset(name: "Json/Data")
}
internal static let readme = XCTDataAsset(name: "README")
}
internal enum Food {
internal enum Exotic {
internal static let banana = XCTImageAsset(name: "Exotic/Banana")
internal static let mango = XCTImageAsset(name: "Exotic/Mango")
}
internal enum Round {
internal static let apricot = XCTImageAsset(name: "Round/Apricot")
internal static let apple = XCTImageAsset(name: "Round/Apple")
internal enum Double {
internal static let cherry = XCTImageAsset(name: "Round/Double/Cherry")
}
internal static let tomato = XCTImageAsset(name: "Round/Tomato")
}
internal static let `private` = XCTImageAsset(name: "private")
}
internal enum Other {
}
internal enum Styles {
internal enum _24Vision {
internal static let background = XCTColorAsset(name: "24Vision/Background")
internal static let primary = XCTColorAsset(name: "24Vision/Primary")
}
internal static let orange = XCTImageAsset(name: "Orange")
internal enum Vengo {
internal static let primary = XCTColorAsset(name: "Vengo/Primary")
internal static let tint = XCTColorAsset(name: "Vengo/Tint")
}
}
internal enum Symbols {
internal static let exclamationMark = XCTSymbolAsset(name: "Exclamation Mark")
internal static let plus = XCTSymbolAsset(name: "Plus")
}
internal enum Targets {
internal static let bottles = XCTARResourceGroup(name: "Bottles")
internal static let paintings = XCTARResourceGroup(name: "Paintings")
internal static let posters = XCTARResourceGroup(name: "Posters")
}
}
// swiftlint:enable identifier_name line_length nesting type_body_length type_name
// MARK: - Implementation Details
internal struct XCTARResourceGroup {
internal fileprivate(set) var name: String
#if os(iOS)
@available(iOS 11.3, *)
internal var referenceImages: Set<ARReferenceImage> {
return ARReferenceImage.referenceImages(in: self)
}
@available(iOS 12.0, *)
internal var referenceObjects: Set<ARReferenceObject> {
return ARReferenceObject.referenceObjects(in: self)
}
#endif
}
#if os(iOS)
@available(iOS 11.3, *)
internal extension ARReferenceImage {
static func referenceImages(in asset: XCTARResourceGroup) -> Set<ARReferenceImage> {
let bundle = BundleToken.bundle
return referenceImages(inGroupNamed: asset.name, bundle: bundle) ?? Set()
}
}
@available(iOS 12.0, *)
internal extension ARReferenceObject {
static func referenceObjects(in asset: XCTARResourceGroup) -> Set<ARReferenceObject> {
let bundle = BundleToken.bundle
return referenceObjects(inGroupNamed: asset.name, bundle: bundle) ?? Set()
}
}
#endif
internal final class XCTColorAsset {
internal fileprivate(set) var name: String
#if os(macOS)
internal typealias Color = NSColor
#elseif os(iOS) || os(tvOS) || os(watchOS)
internal typealias Color = UIColor
#endif
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *)
internal private(set) lazy var color: Color = Color(asset: self)
#if os(iOS) || os(tvOS)
@available(iOS 11.0, tvOS 11.0, *)
internal func color(compatibleWith traitCollection: UITraitCollection) -> Color {
let bundle = BundleToken.bundle
guard let color = Color(named: name, in: bundle, compatibleWith: traitCollection) else {
fatalError("Unable to load color asset named \(name).")
}
return color
}
#endif
fileprivate init(name: String) {
self.name = name
}
}
internal extension XCTColorAsset.Color {
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *)
convenience init!(asset: XCTColorAsset) {
let bundle = BundleToken.bundle
#if os(iOS) || os(tvOS)
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(macOS)
self.init(named: NSColor.Name(asset.name), bundle: bundle)
#elseif os(watchOS)
self.init(named: asset.name)
#endif
}
}
internal struct XCTDataAsset {
internal fileprivate(set) var name: String
@available(iOS 9.0, tvOS 9.0, watchOS 6.0, macOS 10.11, *)
internal var data: NSDataAsset {
return NSDataAsset(asset: self)
}
}
@available(iOS 9.0, tvOS 9.0, watchOS 6.0, macOS 10.11, *)
internal extension NSDataAsset {
convenience init!(asset: XCTDataAsset) {
let bundle = BundleToken.bundle
#if os(iOS) || os(tvOS) || os(watchOS)
self.init(name: asset.name, bundle: bundle)
#elseif os(macOS)
self.init(name: NSDataAsset.Name(asset.name), bundle: bundle)
#endif
}
}
internal struct XCTImageAsset {
internal fileprivate(set) var name: String
#if os(macOS)
internal typealias Image = NSImage
#elseif os(iOS) || os(tvOS) || os(watchOS)
internal typealias Image = UIImage
#endif
@available(iOS 8.0, tvOS 9.0, watchOS 2.0, macOS 10.7, *)
internal var image: Image {
let bundle = BundleToken.bundle
#if os(iOS) || os(tvOS)
let image = Image(named: name, in: bundle, compatibleWith: nil)
#elseif os(macOS)
let name = NSImage.Name(self.name)
let image = (bundle == .main) ? NSImage(named: name) : bundle.image(forResource: name)
#elseif os(watchOS)
let image = Image(named: name)
#endif
guard let result = image else {
fatalError("Unable to load image asset named \(name).")
}
return result
}
#if os(iOS) || os(tvOS)
@available(iOS 8.0, tvOS 9.0, *)
internal func image(compatibleWith traitCollection: UITraitCollection) -> Image {
let bundle = BundleToken.bundle
guard let result = Image(named: name, in: bundle, compatibleWith: traitCollection) else {
fatalError("Unable to load image asset named \(name).")
}
return result
}
#endif
}
internal extension XCTImageAsset.Image {
@available(iOS 8.0, tvOS 9.0, watchOS 2.0, *)
@available(macOS, deprecated,
message: "This initializer is unsafe on macOS, please use the XCTImageAsset.image property")
convenience init!(asset: XCTImageAsset) {
#if os(iOS) || os(tvOS)
let bundle = BundleToken.bundle
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(macOS)
self.init(named: NSImage.Name(asset.name))
#elseif os(watchOS)
self.init(named: asset.name)
#endif
}
}
internal struct XCTSymbolAsset {
internal fileprivate(set) var name: String
#if os(iOS) || os(tvOS) || os(watchOS)
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, *)
internal typealias Configuration = UIImage.SymbolConfiguration
internal typealias Image = UIImage
@available(iOS 12.0, tvOS 12.0, watchOS 5.0, *)
internal var image: Image {
let bundle = BundleToken.bundle
#if os(iOS) || os(tvOS)
let image = Image(named: name, in: bundle, compatibleWith: nil)
#elseif os(watchOS)
let image = Image(named: name)
#endif
guard let result = image else {
fatalError("Unable to load symbol asset named \(name).")
}
return result
}
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, *)
internal func image(with configuration: Configuration) -> Image {
let bundle = BundleToken.bundle
guard let result = Image(named: name, in: bundle, with: configuration) else {
fatalError("Unable to load symbol asset named \(name).")
}
return result
}
#endif
}
// swiftlint:disable convenience_type
private final class BundleToken {
static let bundle: Bundle = {
#if SWIFT_PACKAGE
return Bundle.module
#else
return Bundle(for: BundleToken.self)
#endif
}()
}
// swiftlint:enable convenience_type
| 31.457249 | 116 | 0.699126 |
8f8d4c3c4dbed743f8d632164de3df78df21cc84 | 2,122 | //
// ViewController.swift
// UIDatePickerEx
//
// Created by Domino on 08/05/2019.
// Copyright © 2019 MinominoDomino. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate{
@IBOutlet weak var datePickerLabel: UILabel!
@IBOutlet weak var myDatePicker: UIDatePicker!
@IBOutlet weak var dateStylePicker: UIPickerView!
let formatter: DateFormatter = DateFormatter()
let pickerStyle: [String] = ["none", "short", "medium", "long", "full"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerStyle.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerStyle[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if (component == 0) {
formatter.dateStyle = DateFormatter.Style(rawValue: UInt(row))!
} else {
formatter.timeStyle = DateFormatter.Style(rawValue: UInt(row))!
}
datePickerLabel.text = nil
self.viewDidLoad()
}
@IBAction func datePicker(_ sender: UIDatePicker) {
let date = formatter.string(from: sender.date)
datePickerLabel.text = date
}
@IBAction func touchUpChangeModeButton(_ sender: UIButton) {
switch myDatePicker.datePickerMode {
case .countDownTimer:
myDatePicker.datePickerMode = .date
case .date:
myDatePicker.datePickerMode = .dateAndTime
case .dateAndTime:
myDatePicker.datePickerMode = .time
case .time:
myDatePicker.datePickerMode = .countDownTimer
default:
print("error")
}
self.viewDidLoad()
}
}
| 30.753623 | 111 | 0.639491 |
cc705d713015ab3815c290a4c49c3c3ba4fbd973 | 723 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Defines test to make sure that the `Dream` type has value semantics.
*/
import XCTest
class DreamValueSemanticsTestCase: XCTestCase {
func testDreamHasValueSemantics() {
let dream = Dream(description: "Saw the light", creature: .unicorn(.yellow), effects: [.fireBreathing])
testValueSemantics(initial: dream, mutations: { (copy: inout Dream) in
/*
Change the copy's description to something different than the
original dream.
*/
copy.description = "Saw the light (copy)"
})
}
}
| 30.125 | 111 | 0.633472 |
1ecbd5b1c1a5ca8b7ea051a471df4053d60ae8da | 3,297 | //
//
// XWallet
//
// Created by May on 2020/12/18.
// Copyright © 2020 May All rights reserved.
//
import WKKit
import RxSwift
import RxCocoa
extension WKWrapper where Base == SetBiometricsViewController {
var view: SetBiometricsViewController.View { return base.view as! SetBiometricsViewController.View }
}
extension SetBiometricsViewController {
class override func instance(with context: [String : Any]) -> UIViewController? {
guard let wallet = context["wallet"] as? WKWallet else { return nil }
let vc = SetBiometricsViewController(wallet: wallet)
return vc
}
}
extension SetBiometricsViewController: NotificationToastProtocol {
func allowToast(notif: FxNotification) -> Bool { false }
}
class SetBiometricsViewController: WKViewController {
private let wallet: WKWallet
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
init(wallet: WKWallet) {
self.wallet = wallet
super.init(nibName: nil, bundle: nil)
}
override func navigationItems(_ navigationBar: WKNavigationBar) { navigationBar.isHidden = true }
override func loadView() { view = View(frame: ScreenBounds) }
override func viewDidLoad() {
super.viewDidLoad()
bind()
logWhenDeinit()
}
private func bind() {
wk.view.backUpButton.action { [weak self] in
self?.enableBiometrics()
}
wk.view.notNowButton.action { [weak self] in
self?.goBackUpNow()
}
wk.view.closeButton.action {
Router.showBackAlert()
}
wallet.createCompleted = .setBio
}
//MARK: Action
@objc private func enableBiometrics() {
guard LocalAuthManager.shared.isEnabled else {
let authId = TR(LocalAuthManager.shared.isAuthFace ? "FaceId" : "TouchId")
self.hud?.error(m: TR("Settings.$BiometricsDisable",authId))
return
}
Router.showSetBioAlert { [weak self](error) in
guard let wallet = self?.wallet else { return }
guard let this = self else { return }
if error == nil {
this.wallet.createCompleted = .setSecurity
LocalAuthManager.shared.userAllowed = true
if let type = wallet.registerType, type == .importT {
wallet.createCompleted = .completed
wallet.isBackuped = true
Router.resetRootController(wallet: wallet.rawValue, animated: true)
} else {
Router.pushToBackUpNow(wallet: wallet)
}
}
}
}
@objc private func goBackUpNow() {
if let type = wallet.registerType, type == .importT {
wallet.createCompleted = .completed
wallet.isBackuped = true
Router.resetRootController(wallet: wallet.rawValue, animated: true)
} else {
Router.pushToBackUpNow(wallet: wallet)
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
override var interactivePopIsEnabled: Bool {
return false
}
}
| 29.702703 | 104 | 0.599636 |
bbac8fda3ad95811a8e36e14248947d1caabe45b | 1,012 | //: [Previous](@previous)
// Rydberg's formula
let λ = Variable(identifier: "λ", value: 5000)
let R = Variable(identifier: "R", value: 1.0973731569e7)
let n1 = Variable(identifier: "n_1", value: 2)
let n2 = Variable(identifier: "n_2", value: 3)
// TODO: Constraint to integers, solve for multiple variables and regression and stuff
let rydbergsFormula = 1 / λ == R * (1 / n1 ** 2 - 1 / n2 ** 2)
let s = rydbergsFormula.solving(for: λ).value
let data: [(Double, Double?)] = [
(-22.2547, nil),
(-46.5711, nil),
(-68.5552, 5790.663),
(-69.7995, 5769.598),
(-88.2639, 5460.735),
(-110.6789, 5085.822),
(-127.7708, 4799.912),
(-135.0529, 4678.149),
(-154.1858, 4358.328),
(-155.2243, nil),
(-172.8485, nil),
(-195.8549, nil),
(-196.3301, nil),
(-196.6079, nil)
]
// Filter data
let calibrationData = data.flatMap { (x, y) in y.map { (x: x, y: $0) }}
let curve = LinearRegression(data: calibrationData).function
data.map { curve($0.0) }
//: [Next](@next)
| 26.631579 | 86 | 0.600791 |
8a849023448ab8f0df021f022140c0d06ac558fc | 2,652 | //
// Pipeline.swift
// SwiftyScraper
//
// Created by Stanislav Novacek on 14/11/2018.
// Copyright © 2018 Stanislav Novacek. All rights reserved.
//
import Foundation
/**
Pipeline consists of a scraper and a persistor (optional).
The basic idea is that a scraper is fed response data and after parsing
some info from this data this info is passed to a persistor that takes
care of persisting this formatted info to a database, file, remote server, etc.
*/
open class Pipeline<Entity: IdentifiableType>: PipelineType {
/** Pipeline identifier. */
public let id: String = UUID().uuidString
/** Content-Type this pipeline is able to parse. */
open var contentType: String? { return scraper.contentType }
/** URL template (regex) that this pipeline is able to handle. */
open var urlTemplate: String? { return scraper.urlTemplate }
/** Whether or not the pipeline is running (processing data). */
public private(set) var isRunning: Bool = false
/** Scraper. */
public let scraper: AnyScraper<[Entity]>
/** Persistor. */
public let persistor: AnyPersistor<Entity>?
/** Initializes a new instance with given scraper and persistor. */
public init(scraper: AnyScraper<[Entity]>, persistor: AnyPersistor<Entity>?) {
self.scraper = scraper
self.persistor = persistor
}
/**
Feeds given response and data to the pipeline. Callback is called when the pipeline finishes.
*/
public func feed(response: HTTPURLResponse, data: Data, callback: ((Result<Any>) -> Void)?) {
// Scrape -> feed to persistor
isRunning = true
scraper.scrape(response: response, data: data) { [weak self] (result) in
// Scraping done
switch result {
case .success(let entities):
if let persistor = self?.persistor {
// Persis
persistor.persist(entities: entities, callback: { (result) in
self?.isRunning = false
switch result {
case .success(_): callback?(.success(entities))
case .error(let error): callback?(.error(error))
}
})
} else {
callback?(.success(entities))
}
case .error(let error):
Log.error { Log.message("Error while scraping \(response.url?.absoluteString ?? "-unknown-") \(error)") }
self?.isRunning = false
callback?(.error(error))
}
}
}
}
| 36.833333 | 121 | 0.585973 |
76497873a77f67d622e644f6374c30e9d0d3be32 | 129,323 | // This file was dynamically generated from 'KeyedEncodingContainerProtocol+BasicCodableHelpers.dswift' by Dynamic Swift. Please do not modify directly.
// Dynamic Swift can be found at https://github.com/TheAngryDarling/dswift.
//
// KeyedEncodingContainerProtocol+BasicCodableHelpers.dwift
// BasicCodableHelpers
//
// Created by Tyler Anger on 2021-02-20.
//
import Foundation
#if swift(>=4.2)
#if canImport(CustomInts)
import CustomInts
#endif
#endif
//Ints
public extension KeyedEncodingContainerProtocol {
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int8,
forKey key: Self.Key,
where condition: (Int8) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int8?,
forKey key: Self.Key,
where condition: (Int8) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int8,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int8) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int8?,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int8) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int8,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int8) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int8?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int8) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: Int8?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int16,
forKey key: Self.Key,
where condition: (Int16) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int16?,
forKey key: Self.Key,
where condition: (Int16) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int16,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int16) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int16?,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int16) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int16,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int16) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int16?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int16) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: Int16?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int32,
forKey key: Self.Key,
where condition: (Int32) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int32?,
forKey key: Self.Key,
where condition: (Int32) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int32,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int32) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int32?,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int32) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int32,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int32) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int32?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int32) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: Int32?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int64,
forKey key: Self.Key,
where condition: (Int64) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int64?,
forKey key: Self.Key,
where condition: (Int64) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int64,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int64) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int64?,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int64) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int64,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int64) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int64?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int64) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: Int64?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int,
forKey key: Self.Key,
where condition: (Int) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int?,
forKey key: Self.Key,
where condition: (Int) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int?,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: Int?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
}
}
//UInts
public extension KeyedEncodingContainerProtocol {
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt8,
forKey key: Self.Key,
where condition: (UInt8) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt8?,
forKey key: Self.Key,
where condition: (UInt8) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt8,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt8) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt8?,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt8) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt8,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt8) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt8?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt8) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: UInt8?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt16,
forKey key: Self.Key,
where condition: (UInt16) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt16?,
forKey key: Self.Key,
where condition: (UInt16) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt16,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt16) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt16?,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt16) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt16,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt16) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt16?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt16) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: UInt16?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt32,
forKey key: Self.Key,
where condition: (UInt32) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt32?,
forKey key: Self.Key,
where condition: (UInt32) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt32,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt32) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt32?,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt32) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt32,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt32) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt32?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt32) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: UInt32?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt64,
forKey key: Self.Key,
where condition: (UInt64) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt64?,
forKey key: Self.Key,
where condition: (UInt64) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt64,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt64) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt64?,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt64) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt64,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt64) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt64?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt64) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: UInt64?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt,
forKey key: Self.Key,
where condition: (UInt) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt?,
forKey key: Self.Key,
where condition: (UInt) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt?,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: UInt?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
}
}
//Other
public extension KeyedEncodingContainerProtocol {
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Bool,
forKey key: Self.Key,
where condition: (Bool) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Bool?,
forKey key: Self.Key,
where condition: (Bool) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Bool,
forKey key: Self.Key,
if nValue: @autoclosure () -> Bool) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Bool?,
forKey key: Self.Key,
if nValue: @autoclosure () -> Bool) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Bool,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Bool) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Bool?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Bool) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: Bool?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Double,
forKey key: Self.Key,
where condition: (Double) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Double?,
forKey key: Self.Key,
where condition: (Double) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Double,
forKey key: Self.Key,
if nValue: @autoclosure () -> Double) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Double?,
forKey key: Self.Key,
if nValue: @autoclosure () -> Double) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Double,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Double) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Double?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Double) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: Double?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Float,
forKey key: Self.Key,
where condition: (Float) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Float?,
forKey key: Self.Key,
where condition: (Float) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Float,
forKey key: Self.Key,
if nValue: @autoclosure () -> Float) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Float?,
forKey key: Self.Key,
if nValue: @autoclosure () -> Float) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Float,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Float) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Float?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Float) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: Float?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: String,
forKey key: Self.Key,
where condition: (String) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: String?,
forKey key: Self.Key,
where condition: (String) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: String,
forKey key: Self.Key,
if nValue: @autoclosure () -> String) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: String?,
forKey key: Self.Key,
if nValue: @autoclosure () -> String) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: String,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> String) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: String?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> String) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: String?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode<T>(_ value: T,
forKey key: Self.Key,
where condition: (T) -> Bool) throws -> Bool where T: Encodable {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent<T>(_ value: T?,
forKey key: Self.Key,
where condition: (T) -> Bool) throws -> Bool where T: Encodable {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode<T>(_ value: T,
forKey key: Self.Key,
if nValue: @autoclosure () -> T) throws -> Bool where T: Encodable, T: Equatable {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent<T>(_ value: T?,
forKey key: Self.Key,
if nValue: @autoclosure () -> T) throws -> Bool where T: Encodable, T: Equatable {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode<T>(_ value: T,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> T) throws -> Bool where T: Encodable, T: Equatable {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent<T>(_ value: T?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> T) throws -> Bool where T: Encodable, T: Equatable {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil<T>(_ value: T?,
forKey key: Self.Key) throws -> EncodedAs where T: Encodable {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
}
}
#if swift(>=4.2)
#if canImport(CustomInts)
//Custom Ints
public extension KeyedEncodingContainerProtocol {
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int24,
forKey key: Self.Key,
where condition: (Int24) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int24?,
forKey key: Self.Key,
where condition: (Int24) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int24,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int24) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int24?,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int24) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int24,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int24) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int24?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int24) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: Int24?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int40,
forKey key: Self.Key,
where condition: (Int40) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int40?,
forKey key: Self.Key,
where condition: (Int40) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int40,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int40) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int40?,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int40) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int40,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int40) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int40?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int40) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: Int40?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int48,
forKey key: Self.Key,
where condition: (Int48) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int48?,
forKey key: Self.Key,
where condition: (Int48) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int48,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int48) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int48?,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int48) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int48,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int48) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int48?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int48) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: Int48?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int56,
forKey key: Self.Key,
where condition: (Int56) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int56?,
forKey key: Self.Key,
where condition: (Int56) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int56,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int56) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int56?,
forKey key: Self.Key,
if nValue: @autoclosure () -> Int56) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: Int56,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int56) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: Int56?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> Int56) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: Int56?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
}
}
//Custom UInts
public extension KeyedEncodingContainerProtocol {
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt24,
forKey key: Self.Key,
where condition: (UInt24) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt24?,
forKey key: Self.Key,
where condition: (UInt24) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt24,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt24) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt24?,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt24) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt24,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt24) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt24?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt24) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: UInt24?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt40,
forKey key: Self.Key,
where condition: (UInt40) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt40?,
forKey key: Self.Key,
where condition: (UInt40) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt40,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt40) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt40?,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt40) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt40,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt40) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt40?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt40) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: UInt40?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt48,
forKey key: Self.Key,
where condition: (UInt48) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt48?,
forKey key: Self.Key,
where condition: (UInt48) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt48,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt48) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt48?,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt48) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt48,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt48) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt48?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt48) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: UInt48?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
} /// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt56,
forKey key: Self.Key,
where condition: (UInt56) -> Bool) throws -> Bool {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter condition: The condition to test if the value should be encoded
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt56?,
forKey key: Self.Key,
where condition: (UInt56) -> Bool) throws -> Bool {
guard let val = value else { return false }
return (try self.encode(val, forKey: key, where: condition))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt56,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt56) throws -> Bool {
return (try self.encode(value, forKey: key, where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt56?,
forKey key: Self.Key,
if nValue: @autoclosure () -> UInt56) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 == nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode(_ value: UInt56,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt56) throws -> Bool {
return (try self.encode(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - parameter nValue: The value it should not be for encoding to occur
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent(_ value: UInt56?,
forKey key: Self.Key,
ifNot nValue: @autoclosure () -> UInt56) throws -> Bool {
return (try self.encodeIfPresent(value,
forKey: key,
where: { $0 != nValue() }))
}
/// Encodes the given value for the given key or nil of no value
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or if nil was encoded
@discardableResult
mutating func encodeIfPresentOrNil(_ value: UInt56?,
forKey key: Self.Key) throws -> EncodedAs {
if let v = value {
try self.encode(v, forKey: key)
return .value
} else {
try self.encodeNil(forKey: key)
return .nil
}
}
}
#endif
#endif
public extension KeyedEncodingContainerProtocol {
/*
/// Encode a collection of objects if the collection has any objects
/// - Parameters:
/// - value: The collection of objects to encode
/// - key: The key to associate the value with.
/// - condition: test condition to indicate if encoding should occur
/// - Throws: `EncodingError.invalidValue` if the given value is invalid in
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encode<C>(_ value: C,
forKey key: Self.Key,
where condition: (C) -> Bool) throws -> Bool where C: Encodable, C: Collection {
guard condition(value) else { return false }
try self.encode(value, forKey: key)
return true
}
/// Encode a collection of objects if the collection has any objects
/// - Parameters:
/// - value: The collection of objects to encode
/// - key: The key to associate the value with.
/// - condition: test condition to indicate if encoding should occur
/// - Throws: `EncodingError.invalidValue` if the given value is invalid in
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresent<C>(_ value: C?,
forKey key: Self.Key,
where condition: (C) -> Bool) throws -> Bool where C: Encodable, C: Collection {
guard let val = value else { return false }
return try self.encode(val, forKey: key, where: condition)
}
*/
/// Encode a collection of objects if the collection has any objects
/// - Parameters:
/// - value: The collection of objects to encode
/// - key: The key to associate the value with.
/// - Throws: `EncodingError.invalidValue` if the given value is invalid in
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfNotEmpty<C>(_ value: C,
forKey key: Self.Key) throws -> Bool where C: Encodable, C: Collection {
return try self.encode(value,
forKey: key,
where: { return !$0.isEmpty })
}
/// Encode a collection of objects if the collection has any objects
/// - Parameters:
/// - value: The collection of objects to encode
/// - key: The key to associate the value with.
/// - Throws: `EncodingError.invalidValue` if the given value is invalid in
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeIfPresentAndNotEmpty<C>(_ value: C?,
forKey key: Self.Key) throws -> Bool where C: Encodable, C: Collection {
guard let v = value else { return false }
return try encodeIfNotEmpty(v, forKey: key)
}
}
public extension KeyedEncodingContainerProtocol {
/// Provides an easy method to encode an array of encodable objects in a dynamic way
///
/// The following rules apply when encoding:
/// 1. If collection count is 0, An empty array gets encoded
/// 2. If collection count is 1, encodes the object as a single value and not an array
/// 3. Encodes as a regular array
///
/// - Parameters:
/// - collection: The collection to encode
/// - key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeToSingleOrArray<C>(_ collection: C,
forKey key: Self.Key) throws -> SingleOrArrayEncodedAs where C: Collection, C.Element: Encodable {
if canEncodeSingleFromArray(collection, at: self.codingPath.appending(key)) {
try self.encode(collection[collection.startIndex], forKey: key)
return .single
} else {
var container = self.nestedUnkeyedContainer(forKey: key)
for o in collection {
try container.encode(o)
}
return .array
}
}
/// Provides an easy method to encode an array of encodable objects in a dynamic way
///
/// The following rules apply when encoding:
/// 1. If collection is nil, nothing gets encoded
/// 2. If collection count is 0, An empty array gets encoded
/// 3. If collection count is 1, encodes the object as a single value and not an array
/// 4. Encodes as a regular array
///
/// - Parameters:
/// - collection: The collection to encode
/// - key: The key to associate the value with.
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeToSingleOrArrayIfPresent<C>(_ collection: C?,
forKey key: Self.Key) throws -> SingleOrArrayEncodedAsIfPresent where C: Collection, C.Element: Encodable {
guard let collection = collection else { return .none }
return SingleOrArrayEncodedAsIfPresent(try self.encodeToSingleOrArray(collection, forKey: key))
}
}
public extension KeyedEncodingContainerProtocol {
/// Provides an easy method for encoding dictionaries
///
/// When the key is encoded it must be transformed to one of te following base types: String, Int, UInt, Bool
/// - Parameter dictionary: The dictionary to encode
mutating func encodeDictionary<Key, Value>(_ dictionary: [Key: Value],
forKey key: Self.Key) throws where Key: Encodable, Value: Encodable {
var container = self.nestedContainer(keyedBy: CodableKey.self, forKey: key)
for(key, val) in dictionary {
let sEncoder = SimpleSingleValueEncoder(container: self)
try key.encode(to: sEncoder)
guard let keyValue = sEncoder.value else {
throw DecodingError.valueNotFound(Any.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Missing Key encoded value"))
}
if let k = keyValue as? String {
let codingKey = CodableKey(stringValue: k)
try container.encode(val, forKey: codingKey)
} else {
let codingKey = CodableKey(stringValue: "\(keyValue)")
try container.encode(val, forKey: codingKey)
}
}
}
/// Provides an easy method for encoding dictionaries
///
/// When the key is encoded it must be transformed to one of te following base types: String, Int, UInt, Bool
/// - Parameter dictionary: The dictionary to encode
/// - returns: Returns an indicator if the object was encoded or not
@discardableResult
mutating func encodeDictionaryIfPresent<Key, Value>(_ dictionary: [Key: Value]?,
forKey key: Self.Key) throws -> Bool where Key: Encodable, Value: Encodable {
guard let dictionary = dictionary else { return false }
try self.encodeDictionary(dictionary, forKey: key)
return true
}
}
| 48.417447 | 159 | 0.592161 |
e8e2f0f19a02ab55461358ab0a0547ed4c546b44 | 814 | //
// ContentView.swift
// Canvas-Performance-Test
//
// Created by Philip on 2022/03/13.
//
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
List {
NavigationLink(destination: MultipleShapeView()) {
Text("Multiple Shape")
}
NavigationLink(destination: MultiCanvasView()) {
Text("Multiple Canvas")
}
NavigationLink(destination: MultiImageView()) {
Text("Multiple Image")
}
}
.navigationTitle("Card Views")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 22.611111 | 66 | 0.495086 |
23f2369b2f09f2060083577aaca6473d952124bf | 1,365 | //
// AppDelegate.swift
// To-do_List_Assignment_4
//
// Created by Abdeali Mody on 2020-11-11.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.891892 | 179 | 0.747985 |
e015fcdacdbb7882010bd3d1b8d1cd6bcd3728d4 | 2,706 | /// Copyright © 2019 Zaid M. Said
///
/// 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
protocol FileManagerDirectoryNames {
func documentsDirectoryURL() -> URL
func inboxDirectoryURL() -> URL
func libraryDirectoryURL() -> URL
func tempDirectoryURL() -> URL
func getURL(for directory: FileManagerDirectories) -> URL
func buildFullPath(forFileName name: String, inDirectory directory: FileManagerDirectories) -> URL
}
extension FileManagerDirectoryNames {
func documentsDirectoryURL() -> URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}
func inboxDirectoryURL() -> URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(FileManagerDirectories.Inbox.rawValue)
}
func libraryDirectoryURL() -> URL {
return FileManager.default.urls(for: FileManager.SearchPathDirectory.libraryDirectory, in: .userDomainMask).first!
}
func tempDirectoryURL() -> URL {
return FileManager.default.temporaryDirectory
}
func getURL(for directory: FileManagerDirectories) -> URL {
switch directory {
case .Documents:
return documentsDirectoryURL()
case .Inbox:
return inboxDirectoryURL()
case .Library:
return libraryDirectoryURL()
case .Temp:
return tempDirectoryURL()
}
}
func buildFullPath(forFileName name: String, inDirectory directory: FileManagerDirectories) -> URL {
return getURL(for: directory).appendingPathComponent(name)
}
}
| 41 | 150 | 0.712121 |
030892f82887662b4626e99fd29aa3262966e3ce | 329 | //
// YSCategoryViewAnimationType.swift
// YSCategoryView
//
// Created by 姚帅 on 2018/6/29.
// Copyright © 2018年 YS. All rights reserved.
//
import UIKit
/// 标识线拖动动画
///
/// - stretch: 拉伸
/// - translation: 平移
public enum YSCategoryViewAnimationType{
/// 拉伸
case stretch
/// 平移
case translation
}
| 14.304348 | 46 | 0.62614 |
2f034d18aaf256d04e41b7d5644a8373138aff9c | 9,903 | import UIKit
public protocol RenderViewDelegate: class {
func willDisplayFramebuffer(renderView: RenderView, framebuffer: Framebuffer)
func didDisplayFramebuffer(renderView: RenderView, framebuffer: Framebuffer)
// Only use this if you need to do layout in willDisplayFramebuffer before the framebuffer actually gets displayed
// Typically should only be used for one frame otherwise will cause serious playback issues
// When true the above delegate methods will be called from the main thread instead of the sharedImageProcessing que
// Default is false
func shouldDisplayNextFramebufferAfterMainThreadLoop() -> Bool
}
// TODO: Add support for transparency
public class RenderView:UIView, ImageConsumer {
public weak var delegate:RenderViewDelegate?
public var backgroundRenderColor = Color.black
public var fillMode = FillMode.preserveAspectRatio
public var orientation:ImageOrientation = .portrait
public var sizeInPixels:Size { get { return Size(width:Float(frame.size.width * contentScaleFactor), height:Float(frame.size.height * contentScaleFactor))}}
public let sources = SourceContainer()
public let maximumInputs:UInt = 1
var displayFramebuffer:GLuint?
var displayRenderbuffer:GLuint?
var backingSize = GLSize(width:0, height:0)
private var isAppForeground: Bool = true
private lazy var displayShader:ShaderProgram = {
return sharedImageProcessingContext.passthroughShader
}()
private var internalLayer: CAEAGLLayer!
required public init?(coder:NSCoder) {
super.init(coder:coder)
self.commonInit()
}
public override init(frame:CGRect) {
super.init(frame:frame)
self.commonInit()
}
override public class var layerClass:Swift.AnyClass {
get {
return CAEAGLLayer.self
}
}
override public var bounds: CGRect {
didSet {
// Check if the size changed
if(oldValue.size != self.bounds.size) {
// Destroy the displayFramebuffer so we render at the correct size for the next frame
sharedImageProcessingContext.runOperationAsynchronously{
self.destroyDisplayFramebuffer()
}
}
}
}
func commonInit() {
self.contentScaleFactor = UIScreen.main.scale
let eaglLayer = self.layer as! CAEAGLLayer
eaglLayer.isOpaque = true
eaglLayer.drawableProperties = [kEAGLDrawablePropertyRetainedBacking: NSNumber(value:false), kEAGLDrawablePropertyColorFormat: kEAGLColorFormatRGBA8]
eaglLayer.contentsGravity = CALayerContentsGravity.resizeAspectFill // Just for safety to prevent distortion
NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in
self?.isAppForeground = true
}
NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in
self?.isAppForeground = false
}
self.internalLayer = eaglLayer
}
deinit {
sharedImageProcessingContext.runOperationSynchronously{
destroyDisplayFramebuffer()
}
}
func createDisplayFramebuffer() -> Bool {
// Fix crash when calling OpenGL when app is not foreground
guard isAppForeground else { return false }
var newDisplayFramebuffer:GLuint = 0
glGenFramebuffers(1, &newDisplayFramebuffer)
displayFramebuffer = newDisplayFramebuffer
glBindFramebuffer(GLenum(GL_FRAMEBUFFER), displayFramebuffer!)
var newDisplayRenderbuffer:GLuint = 0
glGenRenderbuffers(1, &newDisplayRenderbuffer)
displayRenderbuffer = newDisplayRenderbuffer
glBindRenderbuffer(GLenum(GL_RENDERBUFFER), displayRenderbuffer!)
// Without the flush you will occasionally get a warning from UIKit and when that happens the RenderView just stays black.
// "CoreAnimation: [EAGLContext renderbufferStorage:fromDrawable:] was called from a non-main thread in an implicit transaction!
// Note that this may be unsafe without an explicit CATransaction or a call to [CATransaction flush]."
// I tried a transaction and that doesn't work and this is probably why --> http://danielkbx.com/post/108060601989/catransaction-flush
// Using flush is important because it guarantees the view is layed out at the correct size before it is drawn to since this is being done on a background thread.
// Its possible the size of the view was changed right before we got here and would result in us drawing to the view at the old size
// and then the view size would change to the new size at the next layout pass and distort our already drawn image.
// Since we do not call this function often we do not need to worry about the performance impact of calling flush.
CATransaction.flush()
sharedImageProcessingContext.context.renderbufferStorage(Int(GL_RENDERBUFFER), from:self.internalLayer)
var backingWidth:GLint = 0
var backingHeight:GLint = 0
glGetRenderbufferParameteriv(GLenum(GL_RENDERBUFFER), GLenum(GL_RENDERBUFFER_WIDTH), &backingWidth)
glGetRenderbufferParameteriv(GLenum(GL_RENDERBUFFER), GLenum(GL_RENDERBUFFER_HEIGHT), &backingHeight)
backingSize = GLSize(width:backingWidth, height:backingHeight)
guard (backingWidth > 0 && backingHeight > 0) else {
print("WARNING: View had a zero size")
if(self.internalLayer.bounds.width > 0 && self.internalLayer.bounds.height > 0) {
print("WARNING: View size \(self.internalLayer.bounds) may be too large ")
}
return false
}
glFramebufferRenderbuffer(GLenum(GL_FRAMEBUFFER), GLenum(GL_COLOR_ATTACHMENT0), GLenum(GL_RENDERBUFFER), displayRenderbuffer!)
let status = glCheckFramebufferStatus(GLenum(GL_FRAMEBUFFER))
if (status != GLenum(GL_FRAMEBUFFER_COMPLETE)) {
print("WARNING: Display framebuffer creation failed with error: \(FramebufferCreationError(errorCode:status))")
return false
}
return true
}
func destroyDisplayFramebuffer() {
if let displayFramebuffer = self.displayFramebuffer {
var temporaryFramebuffer = displayFramebuffer
glDeleteFramebuffers(1, &temporaryFramebuffer)
self.displayFramebuffer = nil
}
if let displayRenderbuffer = self.displayRenderbuffer {
var temporaryRenderbuffer = displayRenderbuffer
glDeleteRenderbuffers(1, &temporaryRenderbuffer)
self.displayRenderbuffer = nil
}
}
func activateDisplayFramebuffer() {
glBindFramebuffer(GLenum(GL_FRAMEBUFFER), displayFramebuffer!)
glViewport(0, 0, backingSize.width, backingSize.height)
}
public func newFramebufferAvailable(_ framebuffer:Framebuffer, fromSourceIndex:UInt) {
let cleanup: () -> Void = {
if(self.delegate?.shouldDisplayNextFramebufferAfterMainThreadLoop() ?? false) {
DispatchQueue.main.async {
self.delegate?.didDisplayFramebuffer(renderView: self, framebuffer: framebuffer)
framebuffer.unlock()
}
}
else {
self.delegate?.didDisplayFramebuffer(renderView: self, framebuffer: framebuffer)
framebuffer.unlock()
}
}
let work: () -> Void = {
// Fix crash when calling OpenGL when app is not foreground
guard self.isAppForeground else { return }
if (self.displayFramebuffer == nil && !self.createDisplayFramebuffer()) {
cleanup()
// Bail if we couldn't successfully create the displayFramebuffer
return
}
self.activateDisplayFramebuffer()
clearFramebufferWithColor(self.backgroundRenderColor)
let scaledVertices = self.fillMode.transformVertices(verticallyInvertedImageVertices, fromInputSize:framebuffer.sizeForTargetOrientation(self.orientation), toFitSize:self.backingSize)
renderQuadWithShader(self.displayShader, vertices:scaledVertices, inputTextures:[framebuffer.texturePropertiesForTargetOrientation(self.orientation)])
glBindRenderbuffer(GLenum(GL_RENDERBUFFER), self.displayRenderbuffer!)
sharedImageProcessingContext.presentBufferForDisplay()
cleanup()
}
if(self.delegate?.shouldDisplayNextFramebufferAfterMainThreadLoop() ?? false) {
// CAUTION: Never call sync from the sharedImageProcessingContext, it will cause cyclic thread deadlocks
// If you are curious, change this to sync, then try trimming/scrubbing a video
// Before that happens you will get a deadlock when someone calls runOperationSynchronously since the main thread is blocked
// There is a way to get around this but then the first thing mentioned will happen
DispatchQueue.main.async {
self.delegate?.willDisplayFramebuffer(renderView: self, framebuffer: framebuffer)
sharedImageProcessingContext.runOperationAsynchronously {
work()
}
}
}
else {
self.delegate?.willDisplayFramebuffer(renderView: self, framebuffer: framebuffer)
work()
}
}
}
| 46.275701 | 195 | 0.668585 |
9007c0a929e297e950b6466638830ef8972f48f6 | 23,582 | //
// FTPopOverMenu.swift
// FTPopOverMenu
//
// Created by liufengting on 16/11/2016.
// Copyright © 2016 LiuFengting (https://github.com/liufengting) . All rights reserved.
//
import UIKit
extension FTPopOverMenu {
public static func showForSender(sender : UIView, with menuArray: [FTMenuObject], menuImageArray: [Imageable]? = nil, popOverPosition: FTPopOverPosition = .automatic, config: FTConfiguration? = nil, done: @escaping (NSInteger) -> Void, cancel: (() -> Void)? = nil) {
FTPopOverMenu().showForSender(sender: sender, or: nil, with: menuArray, menuImageArray: menuImageArray, popOverPosition: popOverPosition, config: config, done: done, cancel: cancel)
}
public static func showForEvent(event : UIEvent, with menuArray: [FTMenuObject], menuImageArray: [Imageable]? = nil, popOverPosition: FTPopOverPosition = .automatic, config: FTConfiguration? = nil, done: @escaping (NSInteger) -> Void, cancel: (() -> Void)? = nil) {
FTPopOverMenu().showForSender(sender: event.allTouches?.first?.view!, or: nil, with: menuArray, menuImageArray: menuImageArray, popOverPosition: popOverPosition, config: config, done: done, cancel: cancel)
}
public static func showFromSenderFrame(senderFrame : CGRect, with menuArray: [FTMenuObject], menuImageArray: [Imageable]? = nil,popOverPosition: FTPopOverPosition = .automatic, config: FTConfiguration? = nil, done: @escaping (NSInteger) -> Void, cancel: (() -> Void)? = nil) {
FTPopOverMenu().showForSender(sender: nil, or: senderFrame, with: menuArray, menuImageArray: menuImageArray, popOverPosition: popOverPosition, config: config, done: done, cancel: cancel)
}
}
fileprivate enum FTPopOverMenuArrowDirection {
case up
case down
}
public enum FTPopOverPosition{
case automatic
case alwaysAboveSender
case alwaysUnderSender
}
public class FTPopOverMenu : NSObject {
var sender : UIView?
var senderFrame : CGRect?
var menuNameArray : [FTMenuObject]!
var menuImageArray : [Imageable]!
var done : ((_ selectedIndex : NSInteger) -> Void)!
var cancel : (() -> Void)!
var configuration = FTConfiguration()
var popOverPosition : FTPopOverPosition = .automatic
fileprivate lazy var backgroundView : UIView = {
let view = UIView(frame: UIScreen.main.bounds)
if self.configuration.globalShadow {
view.backgroundColor = UIColor.black.withAlphaComponent(self.configuration.shadowAlpha)
}
view.addGestureRecognizer(self.tapGesture)
return view
}()
fileprivate lazy var popOverMenu : FTPopOverMenuView = {
let menu = FTPopOverMenuView(frame: CGRect.zero)
menu.alpha = 0
self.backgroundView.addSubview(menu)
return menu
}()
fileprivate var isOnScreen : Bool = false {
didSet {
if isOnScreen {
self.addOrientationChangeNotification()
} else {
self.removeOrientationChangeNotification()
}
}
}
fileprivate lazy var tapGesture : UITapGestureRecognizer = {
let gesture = UITapGestureRecognizer(target: self, action: #selector(onBackgroudViewTapped(gesture:)))
gesture.delegate = self
return gesture
}()
public func showForSender(sender: UIView?, or senderFrame: CGRect?, with menuNameArray: [FTMenuObject]!, menuImageArray: [Imageable]? = nil, popOverPosition: FTPopOverPosition = .automatic, config: FTConfiguration? = nil, done: @escaping (NSInteger) -> Void, cancel: (() -> Void)? = nil) {
if sender == nil && senderFrame == nil {
return
}
if menuNameArray.count == 0 {
return
}
self.sender = sender
self.senderFrame = senderFrame
self.menuNameArray = menuNameArray
self.menuImageArray = menuImageArray
self.popOverPosition = popOverPosition
self.configuration = config ?? FTConfiguration()
self.done = done
self.cancel = cancel
UIApplication.shared.keyWindow?.addSubview(self.backgroundView)
self.adjustPostionForPopOverMenu()
}
public func dismiss() {
self.doneActionWithSelectedIndex(selectedIndex: -1)
}
fileprivate func adjustPostionForPopOverMenu() {
self.backgroundView.frame = CGRect(x: 0, y: 0, width: UIScreen.ft_width(), height: UIScreen.ft_height())
self.setupPopOverMenu()
self.showIfNeeded()
}
fileprivate func setupPopOverMenu() {
popOverMenu.transform = CGAffineTransform(scaleX: 1, y: 1)
self.configurePopMenuFrame()
popOverMenu.showWithAnglePoint(point: menuArrowPoint,
frame: popMenuFrame,
menuNameArray: menuNameArray,
menuImageArray: menuImageArray,
config: configuration,
arrowDirection: arrowDirection,
done: { (selectedIndex: NSInteger) in
self.doneActionWithSelectedIndex(selectedIndex: selectedIndex)
})
popOverMenu.setAnchorPoint(anchorPoint: self.getAnchorPointForPopMenu())
}
fileprivate func getAnchorPointForPopMenu() -> CGPoint {
var anchorPoint = CGPoint(x: menuArrowPoint.x/popMenuFrame.size.width, y: 0)
if arrowDirection == .down {
anchorPoint = CGPoint(x: menuArrowPoint.x/popMenuFrame.size.width, y: 1)
}
return anchorPoint
}
fileprivate var senderRect : CGRect = CGRect.zero
fileprivate var popMenuOriginX : CGFloat = 0
fileprivate var popMenuFrame : CGRect = CGRect.zero
fileprivate var menuArrowPoint : CGPoint = CGPoint.zero
fileprivate var arrowDirection : FTPopOverMenuArrowDirection = .up
fileprivate var popMenuHeight : CGFloat {
return configuration.menuRowHeight * CGFloat(self.menuNameArray.count) + FT.DefaultMenuArrowHeight
}
fileprivate func configureSenderRect() {
if let sender = self.sender {
if let superView = sender.superview {
senderRect = superView.convert(sender.frame, to: backgroundView)
}
} else if let frame = senderFrame {
senderRect = frame
}
senderRect.origin.y = min(UIScreen.ft_height(), senderRect.origin.y)
if popOverPosition == .alwaysAboveSender {
arrowDirection = .down
} else if popOverPosition == .alwaysUnderSender {
arrowDirection = .up
} else {
if senderRect.origin.y + senderRect.size.height/2 < UIScreen.ft_height()/2 {
arrowDirection = .up
} else {
arrowDirection = .down
}
}
}
fileprivate func configurePopMenuOriginX() {
var senderXCenter : CGPoint = CGPoint(x: senderRect.origin.x + (senderRect.size.width)/2, y: 0)
let menuCenterX : CGFloat = configuration.menuWidth/2 + FT.DefaultMargin
var menuX : CGFloat = 0
if senderXCenter.x + menuCenterX > UIScreen.ft_width() {
senderXCenter.x = min(senderXCenter.x - (UIScreen.ft_width() - configuration.menuWidth - FT.DefaultMargin), configuration.menuWidth - FT.DefaultMenuArrowWidth - FT.DefaultMargin)
menuX = UIScreen.ft_width() - configuration.menuWidth - FT.DefaultMargin
} else if senderXCenter.x - menuCenterX < 0 {
senderXCenter.x = max(FT.DefaultMenuCornerRadius + FT.DefaultMenuArrowWidth, senderXCenter.x - FT.DefaultMargin)
menuX = FT.DefaultMargin
} else {
senderXCenter.x = configuration.menuWidth/2
menuX = senderRect.origin.x + (senderRect.size.width)/2 - configuration.menuWidth/2
}
popMenuOriginX = menuX
}
fileprivate func configurePopMenuFrame() {
self.configureSenderRect()
self.configureMenuArrowPoint()
self.configurePopMenuOriginX()
var safeAreaInset = UIEdgeInsets.zero
if #available(iOS 11.0, *) {
safeAreaInset = UIApplication.shared.keyWindow?.safeAreaInsets ?? UIEdgeInsets.zero
}
if arrowDirection == .up {
popMenuFrame = CGRect(x: popMenuOriginX, y: (senderRect.origin.y + senderRect.size.height), width: configuration.menuWidth, height: popMenuHeight)
if (popMenuFrame.origin.y + popMenuFrame.size.height > UIScreen.ft_height() - safeAreaInset.bottom) {
popMenuFrame = CGRect(x: popMenuOriginX, y: (senderRect.origin.y + senderRect.size.height), width: configuration.menuWidth, height: UIScreen.ft_height() - popMenuFrame.origin.y - FT.DefaultMargin - safeAreaInset.bottom)
}
} else {
popMenuFrame = CGRect(x: popMenuOriginX, y: (senderRect.origin.y - popMenuHeight), width: configuration.menuWidth, height: popMenuHeight)
if popMenuFrame.origin.y < safeAreaInset.top {
popMenuFrame = CGRect(x: popMenuOriginX, y: FT.DefaultMargin + safeAreaInset.top, width: configuration.menuWidth, height: senderRect.origin.y - FT.DefaultMargin - safeAreaInset.top)
}
}
}
fileprivate func configureMenuArrowPoint() {
var point : CGPoint = CGPoint(x: senderRect.origin.x + (senderRect.size.width)/2, y: 0)
let menuCenterX : CGFloat = configuration.menuWidth/2 + FT.DefaultMargin
if senderRect.origin.y + senderRect.size.height/2 < UIScreen.ft_height()/2 {
point.y = 0
} else {
point.y = popMenuHeight
}
if point.x + menuCenterX > UIScreen.ft_width() {
point.x = min(point.x - (UIScreen.ft_width() - configuration.menuWidth - FT.DefaultMargin), configuration.menuWidth - FT.DefaultMenuArrowWidth - FT.DefaultMargin)
} else if point.x - menuCenterX < 0 {
point.x = max(FT.DefaultMenuCornerRadius + FT.DefaultMenuArrowWidth, point.x - FT.DefaultMargin)
} else {
point.x = configuration.menuWidth/2
}
menuArrowPoint = point
}
@objc fileprivate func onBackgroudViewTapped(gesture : UIGestureRecognizer) {
self.dismiss()
}
fileprivate func showIfNeeded() {
if self.isOnScreen == false {
self.isOnScreen = true
popOverMenu.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
UIView.animate(withDuration: FT.DefaultAnimationDuration, animations: {
self.popOverMenu.alpha = 1
self.popOverMenu.transform = CGAffineTransform(scaleX: 1, y: 1)
})
}
}
fileprivate func doneActionWithSelectedIndex(selectedIndex: NSInteger) {
self.isOnScreen = false
UIView.animate(withDuration: FT.DefaultAnimationDuration,
animations: {
self.popOverMenu.alpha = 0
self.popOverMenu.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
}) { (isFinished) in
if isFinished {
self.backgroundView.removeFromSuperview()
if selectedIndex < 0 {
if (self.cancel != nil) {
self.cancel()
}
} else {
if self.done != nil {
self.done(selectedIndex)
}
}
}
}
}
}
extension FTPopOverMenu {
fileprivate func addOrientationChangeNotification() {
NotificationCenter.default.addObserver(self,selector: #selector(onChangeStatusBarOrientationNotification(notification:)),
name: UIApplication.didChangeStatusBarOrientationNotification,
object: nil)
}
fileprivate func removeOrientationChangeNotification() {
NotificationCenter.default.removeObserver(self)
}
@objc fileprivate func onChangeStatusBarOrientationNotification(notification : Notification) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.2 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {
self.adjustPostionForPopOverMenu()
})
}
}
extension FTPopOverMenu: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
let touchPoint = touch.location(in: backgroundView)
let touchClass : String = NSStringFromClass((touch.view?.classForCoder)!) as String
if touchClass == "UITableViewCellContentView" {
return false
} else if CGRect(x: 0, y: 0, width: configuration.menuWidth, height: configuration.menuRowHeight).contains(touchPoint){
// when showed at the navgation-bar-button-item, there is a chance of not respond around the top arrow, so :
self.doneActionWithSelectedIndex(selectedIndex: 0)
return false
}
return true
}
}
private class FTPopOverMenuView: UIControl {
fileprivate var menuNameArray : [FTMenuObject]!
fileprivate var menuImageArray : [Imageable]?
fileprivate var arrowDirection : FTPopOverMenuArrowDirection = .up
fileprivate var done : ((NSInteger) -> Void)!
fileprivate var configuration = FTConfiguration()
lazy var menuTableView : UITableView = {
let tableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
tableView.backgroundColor = UIColor.clear
tableView.delegate = self
tableView.dataSource = self
tableView.separatorColor = self.configuration.menuSeparatorColor
tableView.layer.cornerRadius = self.configuration.cornerRadius
tableView.clipsToBounds = true
if #available(iOS 11.0, *) {
tableView.contentInsetAdjustmentBehavior = .never
}
return tableView
}()
fileprivate func showWithAnglePoint(point: CGPoint, frame: CGRect, menuNameArray: [FTMenuObject]!, menuImageArray: [Imageable]?, config: FTConfiguration? = nil, arrowDirection: FTPopOverMenuArrowDirection, done: @escaping ((NSInteger) -> Void)) {
self.frame = frame
self.menuNameArray = menuNameArray
self.menuImageArray = menuImageArray
self.configuration = config ?? FTConfiguration()
self.arrowDirection = arrowDirection
self.done = done
repositionMenuTableView()
drawBackgroundLayerWithArrowPoint(arrowPoint: point)
}
fileprivate func repositionMenuTableView() {
var menuRect : CGRect = CGRect(x: 0, y: FT.DefaultMenuArrowHeight, width: frame.size.width, height: frame.size.height - FT.DefaultMenuArrowHeight)
if (arrowDirection == .down) {
menuRect = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height - FT.DefaultMenuArrowHeight)
}
menuTableView.frame = menuRect
menuTableView.reloadData()
if menuTableView.frame.height < configuration.menuRowHeight * CGFloat(menuNameArray.count) {
menuTableView.isScrollEnabled = true
} else {
menuTableView.isScrollEnabled = false
}
addSubview(self.menuTableView)
}
fileprivate lazy var backgroundLayer : CAShapeLayer = {
let layer : CAShapeLayer = CAShapeLayer()
return layer
}()
fileprivate func drawBackgroundLayerWithArrowPoint(arrowPoint : CGPoint) {
if self.backgroundLayer.superlayer != nil {
self.backgroundLayer.removeFromSuperlayer()
}
backgroundLayer.path = getBackgroundPath(arrowPoint: arrowPoint).cgPath
backgroundLayer.fillColor = configuration.backgoundTintColor.cgColor
backgroundLayer.strokeColor = configuration.borderColor.cgColor
backgroundLayer.lineWidth = configuration.borderWidth
if configuration.localShadow {
backgroundLayer.shadowColor = UIColor.black.cgColor
backgroundLayer.shadowOffset = CGSize(width: 0.0, height: 2.0)
backgroundLayer.shadowRadius = 24.0
backgroundLayer.shadowOpacity = 0.9
backgroundLayer.masksToBounds = false
backgroundLayer.shouldRasterize = true
backgroundLayer.rasterizationScale = UIScreen.main.scale
}
self.layer.insertSublayer(backgroundLayer, at: 0)
// backgroundLayer.transform = CATransform3DMakeAffineTransform(CGAffineTransform(rotationAngle: CGFloat(M_PI))) //CATransform3DMakeRotation(CGFloat(M_PI), 1, 1, 0)
}
func getBackgroundPath(arrowPoint : CGPoint) -> UIBezierPath {
let viewWidth = bounds.size.width
let viewHeight = bounds.size.height
let radius : CGFloat = configuration.cornerRadius
let path : UIBezierPath = UIBezierPath()
path.lineJoinStyle = .round
path.lineCapStyle = .round
if (arrowDirection == .up){
path.move(to: CGPoint(x: arrowPoint.x - FT.DefaultMenuArrowWidth, y: FT.DefaultMenuArrowHeight))
path.addLine(to: CGPoint(x: arrowPoint.x, y: 0))
path.addLine(to: CGPoint(x: arrowPoint.x + FT.DefaultMenuArrowWidth, y: FT.DefaultMenuArrowHeight))
path.addLine(to: CGPoint(x:viewWidth - radius, y: FT.DefaultMenuArrowHeight))
path.addArc(withCenter: CGPoint(x: viewWidth - radius, y: FT.DefaultMenuArrowHeight + radius),
radius: radius,
startAngle: .pi / 2 * 3,
endAngle: 0,
clockwise: true)
path.addLine(to: CGPoint(x: viewWidth, y: viewHeight - radius))
path.addArc(withCenter: CGPoint(x: viewWidth - radius, y: viewHeight - radius),
radius: radius,
startAngle: 0,
endAngle: .pi / 2,
clockwise: true)
path.addLine(to: CGPoint(x: radius, y: viewHeight))
path.addArc(withCenter: CGPoint(x: radius, y: viewHeight - radius),
radius: radius,
startAngle: .pi / 2,
endAngle: .pi,
clockwise: true)
path.addLine(to: CGPoint(x: 0, y: FT.DefaultMenuArrowHeight + radius))
path.addArc(withCenter: CGPoint(x: radius, y: FT.DefaultMenuArrowHeight + radius),
radius: radius,
startAngle: .pi,
endAngle: .pi / 2 * 3,
clockwise: true)
path.close()
// path = UIBezierPath(roundedRect: CGRect.init(x: 0, y: FTDefaultMenuArrowHeight, width: self.bounds.size.width, height: self.bounds.height - FTDefaultMenuArrowHeight), cornerRadius: configuration.cornerRadius)
// path.move(to: CGPoint(x: arrowPoint.x - FTDefaultMenuArrowWidth, y: FTDefaultMenuArrowHeight))
// path.addLine(to: CGPoint(x: arrowPoint.x, y: 0))
// path.addLine(to: CGPoint(x: arrowPoint.x + FTDefaultMenuArrowWidth, y: FTDefaultMenuArrowHeight))
// path.close()
}else{
path.move(to: CGPoint(x: arrowPoint.x - FT.DefaultMenuArrowWidth, y: viewHeight - FT.DefaultMenuArrowHeight))
path.addLine(to: CGPoint(x: arrowPoint.x, y: viewHeight))
path.addLine(to: CGPoint(x: arrowPoint.x + FT.DefaultMenuArrowWidth, y: viewHeight - FT.DefaultMenuArrowHeight))
path.addLine(to: CGPoint(x: viewWidth - radius, y: viewHeight - FT.DefaultMenuArrowHeight))
path.addArc(withCenter: CGPoint(x: viewWidth - radius, y: viewHeight - FT.DefaultMenuArrowHeight - radius),
radius: radius,
startAngle: .pi / 2,
endAngle: 0,
clockwise: false)
path.addLine(to: CGPoint(x: viewWidth, y: radius))
path.addArc(withCenter: CGPoint(x: viewWidth - radius, y: radius),
radius: radius,
startAngle: 0,
endAngle: .pi / 2 * 3,
clockwise: false)
path.addLine(to: CGPoint(x: radius, y: 0))
path.addArc(withCenter: CGPoint(x: radius, y: radius),
radius: radius,
startAngle: .pi / 2 * 3,
endAngle: .pi,
clockwise: false)
path.addLine(to: CGPoint(x: 0, y: viewHeight - FT.DefaultMenuArrowHeight - radius))
path.addArc(withCenter: CGPoint(x: radius, y: viewHeight - FT.DefaultMenuArrowHeight - radius),
radius: radius,
startAngle: .pi,
endAngle: .pi / 2,
clockwise: false)
path.close()
// path = UIBezierPath(roundedRect: CGRect.init(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.height - FTDefaultMenuArrowHeight), cornerRadius: configuration.cornerRadius)
// path.move(to: CGPoint(x: arrowPoint.x - FTDefaultMenuArrowWidth, y: self.bounds.size.height - FTDefaultMenuArrowHeight))
// path.addLine(to: CGPoint(x: arrowPoint.x, y: self.bounds.size.height))
// path.addLine(to: CGPoint(x: arrowPoint.x + FTDefaultMenuArrowWidth, y: self.bounds.size.height - FTDefaultMenuArrowHeight))
// path.close()
}
return path
}
}
extension FTPopOverMenuView : UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return configuration.menuRowHeight
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if (self.done != nil) {
self.done(indexPath.row)
}
}
}
extension FTPopOverMenuView : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.menuNameArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : FTPopOverMenuCell = FTPopOverMenuCell(style: .default, reuseIdentifier: FT.PopOverMenuTableViewCellIndentifier)
var imageObject: Imageable? = nil
if menuImageArray != nil {
if (menuImageArray?.count)! >= indexPath.row + 1 {
imageObject = menuImageArray![indexPath.row]
}
}
cell.setupCellWith(menuName: menuNameArray[indexPath.row], menuImage: imageObject, configuration: self.configuration)
if (indexPath.row == menuNameArray.count-1) {
cell.separatorInset = UIEdgeInsets.init(top: 0, left: bounds.size.width, bottom: 0, right: 0)
} else {
cell.separatorInset = configuration.menuSeparatorInset
}
cell.selectionStyle = configuration.cellSelectionStyle;
return cell
}
}
| 45.790291 | 293 | 0.621321 |
086d4118a849181e9ef9973e11e66d593929c842 | 19,352 | /*
Copyright 2020 Adobe. All rights reserved.
This file is licensed to you 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 REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
import Compression
import Foundation
/// The compression method of a `ZipEntry` in a `ZipArchive`
enum CompressionMethod: UInt16 {
/// Contents were compressed using a zlib compatible Deflate algorithm
case deflate = 8
}
/// A sequence of uncompressed or compressed ZIP entries.
///
/// You use a `ZipArchive` to read existing ZIP files.
///
/// A `ZipArchive` is a sequence of ZipEntries. You can
/// iterate over an archive using a `for`-`in` loop to get access to individual `ZipEntry` objects
final class ZipArchive: Sequence {
/// A DataError for the data within a ZipArchive
enum DataError: Error {
case unreadableFile
case unwritableFile
}
/// An unsigned 32-Bit Integer representing a checksum.
typealias CRC32 = UInt32
/// a custom handler that consumes a `data` object containing partial entry data.
/// - Parameters:
/// - data: a chunk of `data` to consume.
/// - Throws: can throw to indicate errors during data consumption.
typealias EntryDataConsumer = (_ data: Data) throws -> Void
/// A custom handler that receives a position and a size that can be used to provide data from an arbitrary source.
/// - Parameters:
/// - position: The current read position.
/// - size: The size of the chunk to provide.
/// - Returns: A chunk of `Data`.
/// - Throws: Can throw to indicate errors in the data source.
typealias Provider = (_ position: Int, _ size: Int) throws -> Data
typealias LocalFileHeader = ZipEntry.LocalFileHeader
typealias DataDescriptor = ZipEntry.DataDescriptor
typealias CentralDirectoryStructure = ZipEntry.CentralDirectoryStructure
/// An error that occurs during reading, creating or updating a ZIP file.
enum ArchiveError: Error {
/// Thrown when a `ZipEntry` can't be stored in the archive with the proposed compression method.
case invalidCompressionMethod
}
private let LOG_PREFIX = "ZipArchive"
/// An error that occurs during decompression
enum DecompressionError: Error {
case invalidStream
case corruptedData
}
struct EndOfCentralDirectoryRecord: HeaderDataSerializable {
let endOfCentralDirectorySignature = UInt32(FileUnzipperConstants.endOfCentralDirectorySignature)
let numberOfDisk: UInt16
let numberOfDiskStart: UInt16
let totalNumberOfEntriesOnDisk: UInt16
let totalNumberOfEntriesInCentralDirectory: UInt16
let sizeOfCentralDirectory: UInt32
let offsetToStartOfCentralDirectory: UInt32
let zipFileCommentLength: UInt16
let zipFileCommentData: Data
static let size = 22
}
/// URL of a ZipArchive's backing file.
let url: URL
/// Unsafe pointer to archive file for C operations
var archiveFile: UnsafeMutablePointer<FILE>
var endOfCentralDirectoryRecord: EndOfCentralDirectoryRecord
/// Initializes a new `ZipArchive`.
///
/// used to create new archive files or to read existing ones.
/// - Parameter: `url`: File URL to the receivers backing file.
init?(url: URL) {
guard let archiveFile = ZipArchive.getFilePtr(for: url) else {
Log.warning(label: LOG_PREFIX, "Unable to obtain a file pointer for url \(url)")
return nil
}
guard let endOfCentralDirectoryRecord = ZipArchive.getEndOfCentralDirectoryRecord(for: archiveFile) else {
Log.warning(label: LOG_PREFIX, "Unable to obtain end of central directory record for archive file at \(archiveFile.debugDescription)")
return nil
}
self.url = url
self.archiveFile = archiveFile
self.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord
}
deinit {
fclose(self.archiveFile)
}
/// Read a `ZipEntry` from the receiver and write it to `url`.
///
/// - Parameters:
/// - entry: The ZIP `Entry` to read.
/// - url: The destination file URL.
/// - Returns: The checksum of the processed content.
/// - Throws: An error if the destination file cannot be written or the entry contains malformed content.
@discardableResult
func extract(_ entry: ZipEntry, to url: URL) throws -> CRC32 {
let bufferSize = FileUnzipperConstants.defaultReadChunkSize
let fileManager = FileManager()
var checksum = CRC32(0)
switch entry.type {
case .file:
if fileManager.itemExists(at: url) {
do {
try fileManager.removeItem(at: url)
} catch {
throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: url.path])
}
}
try fileManager.createParentDirectoryStructure(for: url)
// Get file system representation for C operations
let destinationRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
// Get destination file C pointer
guard let destinationFile: UnsafeMutablePointer<FILE> = fopen(destinationRepresentation, "wb+") else {
throw CocoaError(.fileNoSuchFile)
}
defer { fclose(destinationFile) }
// Set closure to handle writing data chunks to destination file
let consumer = { try ZipArchive.write(chunk: $0, to: destinationFile) }
// Set file pointer position to the given entry's data offset
fseek(archiveFile, entry.dataOffset, SEEK_SET)
guard let _ = CompressionMethod(rawValue: entry.localFileHeader.compressionMethod) else {
throw ArchiveError.invalidCompressionMethod
}
checksum = try readCompressed(entry: entry, bufferSize: bufferSize, with: consumer)
case .directory:
let consumer = { (_: Data) in
try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
}
fseek(archiveFile, entry.dataOffset, SEEK_SET)
try consumer(Data())
}
let attributes = FileManager.attributes(from: entry)
try fileManager.setAttributes(attributes, ofItemAtPath: url.path)
return checksum
}
///
// MARK: - Sequence Protocol makeIterator implementation
///
func makeIterator() -> AnyIterator<ZipEntry> {
let endOfCentralDirectoryRecord = self.endOfCentralDirectoryRecord
var directoryIndex = Int(endOfCentralDirectoryRecord.offsetToStartOfCentralDirectory)
var index = 0
return AnyIterator {
guard index < Int(endOfCentralDirectoryRecord.totalNumberOfEntriesInCentralDirectory) else { return nil }
guard let centralDirStruct: CentralDirectoryStructure = ZipArchive.readStruct(from: self.archiveFile,
at: directoryIndex) else {
return nil
}
let offset = Int(centralDirStruct.relativeOffsetOfLocalHeader)
guard let localFileHeader: LocalFileHeader = ZipArchive.readStruct(from: self.archiveFile,
at: offset) else { return nil }
var dataDescriptor: DataDescriptor?
if centralDirStruct.usesDataDescriptor {
let additionalSize = Int(localFileHeader.fileNameLength + localFileHeader.extraFieldLength)
let dataSize = centralDirStruct.compressedSize
let descriptorPosition = offset + LocalFileHeader.size + additionalSize + Int(dataSize)
dataDescriptor = ZipArchive.readStruct(from: self.archiveFile, at: descriptorPosition)
}
defer {
directoryIndex += CentralDirectoryStructure.size
directoryIndex += Int(centralDirStruct.fileNameLength)
directoryIndex += Int(centralDirStruct.extraFieldLength)
directoryIndex += Int(centralDirStruct.fileCommentLength)
index += 1
}
return ZipEntry(centralDirectoryStructure: centralDirStruct,
localFileHeader: localFileHeader, dataDescriptor: dataDescriptor)
}
}
//
// MARK: - Helpers
//
///
/// Decompresses the compressed ZipEntry and returns the checksum
/// - Parameters:
/// - entry: The ZipEntry to be decompressed
/// - bufferSize: The bufferSize to be used for the decompression buffer
/// - consumer: The consumer closure which handles the data chunks retrieved from decompression
/// - Returns: The checksum for the decompressed entry
private func readCompressed(entry: ZipEntry, bufferSize: UInt32, with consumer: EntryDataConsumer) throws -> CRC32 {
let size = Int(entry.centralDirectoryStructure.compressedSize)
return try decompress(size: size, bufferSize: Int(bufferSize), provider: { (_, chunkSize) -> Data in
try ZipArchive.readChunk(of: chunkSize, from: self.archiveFile)
}, consumer: { data in
try consumer(data)
})
}
///
/// Gets the file pointer for the file at the given url
/// - Parameter url: The URL to the file
/// - Returns: The C style pointer to the file at the given url
private static func getFilePtr(for url: URL) -> UnsafeMutablePointer<FILE>? {
let fileManager = FileManager()
let fileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
return fopen(fileSystemRepresentation, "rb")
}
///
/// Gets the end of central directory record for the given file
/// - Parameter file: The c style pointer to the file
/// - Returns: The EndOfCentralDirectoryRecord for the given file
private static func getEndOfCentralDirectoryRecord(for file: UnsafeMutablePointer<FILE>)
-> EndOfCentralDirectoryRecord? {
var directoryEnd = 0
var index = FileUnzipperConstants.minDirectoryEndOffset
// Set file pointer position to end of file
fseek(file, 0, SEEK_END)
// Get the length of the file in bytes
let archiveLength = ftell(file)
// Find the end of central directory
while directoryEnd == 0, index < FileUnzipperConstants.maxDirectoryEndOffset, index <= archiveLength {
fseek(file, archiveLength - index, SEEK_SET)
var potentialDirectoryEndTag: UInt32 = UInt32()
fread(&potentialDirectoryEndTag, 1, MemoryLayout<UInt32>.size, file)
if potentialDirectoryEndTag == UInt32(FileUnzipperConstants.endOfCentralDirectorySignature) {
directoryEnd = archiveLength - index
return ZipArchive.readStruct(from: file, at: directoryEnd)
}
index += 1
}
return nil
}
/// Decompress the output of `provider` and pass it to `consumer`.
/// - Parameters:
/// - size: The compressed size of the data to be decompressed.
/// - bufferSize: The maximum size of the decompression buffer.
/// - provider: A closure that accepts a position and a chunk size. Returns a `Data` chunk.
/// - consumer: A closure that processes the result of the decompress operation.
/// - Returns: The checksum of the processed content.
private func decompress(size: Int, bufferSize: Int, provider: Provider, consumer: EntryDataConsumer) throws -> CRC32 {
var crc32 = CRC32(0)
let destPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
defer { destPointer.deallocate() }
let streamPointer = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
defer { streamPointer.deallocate() }
var stream = streamPointer.pointee
var status = compression_stream_init(&stream, COMPRESSION_STREAM_DECODE, COMPRESSION_ZLIB)
guard status != COMPRESSION_STATUS_ERROR else { throw DecompressionError.invalidStream }
defer { compression_stream_destroy(&stream) }
stream.src_size = 0
stream.dst_ptr = destPointer
stream.dst_size = bufferSize
var position = 0
var sourceData: Data?
repeat {
if stream.src_size == 0 {
do {
sourceData = try provider(position, Swift.min(size - position, bufferSize))
if let sourceData = sourceData {
position += sourceData.count
stream.src_size = sourceData.count
}
} catch { throw error }
}
if let sourceData = sourceData {
sourceData.withUnsafeBytes { rawBufferPointer in
if let baseAddress = rawBufferPointer.baseAddress {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
stream.src_ptr = pointer.advanced(by: sourceData.count - stream.src_size)
let flags = sourceData.count < bufferSize ? Int32(COMPRESSION_STREAM_FINALIZE.rawValue) : 0
status = compression_stream_process(&stream, flags)
}
}
}
switch status {
case COMPRESSION_STATUS_OK, COMPRESSION_STATUS_END:
let outputData = Data(bytesNoCopy: destPointer, count: bufferSize - stream.dst_size, deallocator: .none)
try consumer(outputData)
crc32 = calcChecksum(data: outputData, checksum: crc32)
stream.dst_ptr = destPointer
stream.dst_size = bufferSize
default: throw DecompressionError.corruptedData
}
} while status == COMPRESSION_STATUS_OK
return crc32
}
/// Calculate the `CRC32` checksum of the receiver.
///
/// - Parameter checksum: The starting seed.
/// - Returns: The checksum calculated from the bytes of the receiver and the starting seed.
private func calcChecksum(data: Data, checksum: CRC32) -> CRC32 {
// The typecast is necessary on 32-bit platforms because of
// https://bugs.swift.org/browse/SR-1774
let mask = 0xFFFF_FFFF as UInt32
let bufferSize = data.count / MemoryLayout<UInt8>.size
var result = checksum ^ mask
FileUnzipperConstants.crcTable.withUnsafeBufferPointer { crcTablePointer in
data.withUnsafeBytes { bufferPointer in
let bytePointer = bufferPointer.bindMemory(to: UInt8.self)
for bufferIndex in 0 ..< bufferSize {
let byte = bytePointer[bufferIndex]
let index = Int((result ^ UInt32(byte)) & 0xFF)
result = (result >> 8) ^ crcTablePointer[index]
}
}
}
return result ^ mask
}
}
// Data helpers for a ZipArchive
extension ZipArchive {
///
/// Scans the range of subdata from start to the size of T
/// - Parameter start: The start position to start scanning from
/// - Returns: The scanned subdata as T
static func scanValue<T>(start: Int, data: Data) -> T {
let subdata = data.subdata(in: start ..< start + MemoryLayout<T>.size)
return subdata.withUnsafeBytes { $0.load(as: T.self) }
}
///
/// Initializes and returns a DataSerializable from a given file pointer and offset
/// - Parameters:
/// - file: The C style file pointer
/// - offset: The offset to use to start reading data
/// - Returns: The initialized DataSerializable
static func readStruct<T: HeaderDataSerializable>(from file: UnsafeMutablePointer<FILE>, at offset: Int) -> T? {
fseek(file, offset, SEEK_SET)
guard let data = try? readChunk(of: T.size, from: file) else {
return nil
}
let structure = T(data: data, additionalDataProvider: { (additionalDataSize) -> Data in
try self.readChunk(of: additionalDataSize, from: file)
})
return structure
}
///
/// Reads a chunk of data of the given size from the file pointer
/// - Parameters:
/// - size: The size in bytes of the chunk to read as an Int
/// - file: The C style file pointer to read the data from
/// - Returns: The chunk of data read
static func readChunk(of size: Int, from file: UnsafeMutablePointer<FILE>) throws -> Data {
let alignment = MemoryLayout<UInt>.alignment
let bytes = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: alignment)
let bytesRead = fread(bytes, 1, size, file)
let error = ferror(file)
if error > 0 {
throw DataError.unreadableFile
}
return Data(bytesNoCopy: bytes, count: bytesRead, deallocator: .custom { buf, _ in buf.deallocate() })
}
///
/// Writes the chunk of data to the given C file pointer
/// - Parameters:
/// - chunk: The chunk of data to write
/// - file: The C file pointer to write the data to
/// - throws an error
static func write(chunk: Data, to file: UnsafeMutablePointer<FILE>) throws {
chunk.withUnsafeBytes { rawBufferPointer in
if let baseAddress = rawBufferPointer.baseAddress, rawBufferPointer.count > 0 {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
_ = fwrite(pointer, 1, chunk.count, file)
}
}
let error = ferror(file)
if error > 0 {
throw DataError.unwritableFile
}
}
}
extension ZipArchive.EndOfCentralDirectoryRecord {
init?(data: Data, additionalDataProvider provider: (Int) throws -> Data) {
guard data.count == ZipArchive.EndOfCentralDirectoryRecord.size else { return nil }
guard ZipArchive.scanValue(start: 0, data: data) == endOfCentralDirectorySignature else { return nil }
numberOfDisk = ZipArchive.scanValue(start: 4, data: data)
numberOfDiskStart = ZipArchive.scanValue(start: 6, data: data)
totalNumberOfEntriesOnDisk = ZipArchive.scanValue(start: 8, data: data)
totalNumberOfEntriesInCentralDirectory = ZipArchive.scanValue(start: 10, data: data)
sizeOfCentralDirectory = ZipArchive.scanValue(start: 12, data: data)
offsetToStartOfCentralDirectory = ZipArchive.scanValue(start: 16, data: data)
zipFileCommentLength = ZipArchive.scanValue(start: 20, data: data)
guard let commentData = try? provider(Int(zipFileCommentLength)) else { return nil }
guard commentData.count == Int(zipFileCommentLength) else { return nil }
zipFileCommentData = commentData
}
}
| 46.519231 | 146 | 0.647013 |
264a9c004eb53e7aed70f978641153ee56865963 | 982 | //
// Observable.swift
// ChelseabandSDK
//
// Created by Vladyslav Shepitko on 11.03.2021.
//
import RxSwift
extension Observable where Element == Data {
///Filters hex value of data, filter if command starts with `hex` performs guard check for `byteIndex`
/// - Parameter hex: Hex value to check if data starts with this `hex`
/// - Parameter byteIndex: index of byte to determin wether chain could be completed
/// - Parameter mininumBytes: guard check
/// - Returns: completed observable`Observable<Void> `.
public func completeWhenByteEqualsToOne(hexStartWith hex: String, byteIndex: Int = 3) -> Observable<Element> {
filter {
$0.hex.starts(with: hex) && $0.bytes.count >= byteIndex + 1
}.map { data -> Data in
guard data.bytes[byteIndex] == 1 else {
throw CommandError.invalid
}
return data
}.take(1)//NOTE: Wee need to complete observable sequence
}
}
| 33.862069 | 114 | 0.641548 |
9cd2b2bac999660d5dc89bf48df0e04545fd833e | 6,049 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public extension LayoutConstraint {
override public var description: String {
var description = "<"
description += descriptionForObject(self)
if let firstItem = conditionalOptional(from: self.firstItem) {
description += " \(descriptionForObject(firstItem))"
}
if self.firstAttribute != .notAnAttribute {
description += ".\(descriptionForAttribute(self.firstAttribute))"
}
description += " \(descriptionForRelation(self.relation))"
if let secondItem = self.secondItem {
description += " \(descriptionForObject(secondItem))"
}
if self.secondAttribute != .notAnAttribute {
description += ".\(descriptionForAttribute(self.secondAttribute))"
}
if self.multiplier != 1.0 {
description += " * \(self.multiplier)"
}
if self.secondAttribute == .notAnAttribute {
description += " \(self.constant)"
} else {
if self.constant > 0.0 {
description += " + \(self.constant)"
} else if self.constant < 0.0 {
description += " - \(abs(self.constant))"
}
}
if Double((self.priority).rawValue) != 1000.0 {
description += " ^\(self.priority)"
}
description += ">"
return description
}
}
private func descriptionForRelation(_ relation: NSLayoutRelation) -> String {
switch relation {
case .equal: return "=="
case .greaterThanOrEqual: return ">="
case .lessThanOrEqual: return "<="
}
}
private func descriptionForAttribute(_ attribute: NSLayoutAttribute) -> String {
#if os(iOS) || os(tvOS)
switch attribute {
case .notAnAttribute: return "notAnAttribute"
case .top: return "top"
case .left: return "left"
case .bottom: return "bottom"
case .right: return "right"
case .leading: return "leading"
case .trailing: return "trailing"
case .width: return "width"
case .height: return "height"
case .centerX: return "centerX"
case .centerY: return "centerY"
case .lastBaseline: return "lastBaseline"
case .firstBaseline: return "firstBaseline"
case .topMargin: return "topMargin"
case .leftMargin: return "leftMargin"
case .bottomMargin: return "bottomMargin"
case .rightMargin: return "rightMargin"
case .leadingMargin: return "leadingMargin"
case .trailingMargin: return "trailingMargin"
case .centerXWithinMargins: return "centerXWithinMargins"
case .centerYWithinMargins: return "centerYWithinMargins"
}
#else
switch attribute {
case .notAnAttribute: return "notAnAttribute"
case .top: return "top"
case .left: return "left"
case .bottom: return "bottom"
case .right: return "right"
case .leading: return "leading"
case .trailing: return "trailing"
case .width: return "width"
case .height: return "height"
case .centerX: return "centerX"
case .centerY: return "centerY"
case .lastBaseline: return "lastBaseline"
case .firstBaseline: return "firstBaseline"
}
#endif
}
private func conditionalOptional<T>(from object: Optional<T>) -> Optional<T> {
return object
}
private func conditionalOptional<T>(from object: T) -> Optional<T> {
return Optional.some(object)
}
private func descriptionForObject(_ object: AnyObject) -> String {
let pointerDescription = String(format: "%p", UInt(bitPattern: ObjectIdentifier(object)))
var desc = ""
desc += type(of: object).description()
if let object = object as? ConstraintView {
desc += ":\(object.snp.label() ?? pointerDescription)"
} else if let object = object as? LayoutConstraint {
desc += ":\(object.label ?? pointerDescription)"
} else {
desc += ":\(pointerDescription)"
}
if let object = object as? LayoutConstraint, let file = object.constraint?.sourceLocation.0, let line = object.constraint?.sourceLocation.1 {
desc += "@\((file as NSString).lastPathComponent)#\(line)"
}
desc += ""
return desc
}
| 37.571429 | 145 | 0.585717 |
67fe1409c5eb21983e80f534ca916c397bf57b6e | 29,111 | //
// AKMusicSequencer.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on GitHub.
// Copyright © 2018 AudioKit. All rights reserved.
//
/// Sequencer based on tried-and-true CoreAudio/MIDI Sequencing
open class AKSequencer {
/// Music sequence
open var sequence: MusicSequence?
/// Pointer to Music Sequence
open var sequencePointer: UnsafeMutablePointer<MusicSequence>?
/// Array of AudioKit Music Tracks
open var tracks = [AKMusicTrack]()
/// Music Player
var musicPlayer: MusicPlayer?
/// Loop control
open private(set) var loopEnabled: Bool = false
/// Sequencer Initialization
@objc public init() {
NewMusicSequence(&sequence)
if let existingSequence = sequence {
sequencePointer = UnsafeMutablePointer<MusicSequence>(existingSequence)
}
//setup and attach to musicplayer
NewMusicPlayer(&musicPlayer)
if let existingMusicPlayer = musicPlayer {
MusicPlayerSetSequence(existingMusicPlayer, sequence)
}
}
deinit {
AKLog("deinit:")
if let player = musicPlayer {
DisposeMusicPlayer(player)
}
if let seq = sequence {
for track in self.tracks {
if let intTrack = track.internalMusicTrack {
MusicSequenceDisposeTrack(seq, intTrack)
}
}
DisposeMusicSequence(seq)
}
}
/// Initialize the sequence with a MIDI file
///
/// - parameter filename: Location of the MIDI File
///
public convenience init(filename: String) {
self.init()
loadMIDIFile(filename)
}
/// Initialize the sequence with a MIDI file
///
/// - parameter fromURL: URL of MIDI File
///
public convenience init(fromURL fileURL: URL) {
self.init()
loadMIDIFile(fromURL: fileURL)
}
/// Preroll the music player. Call this function in advance of playback to reduce the sequencers
/// startup latency. If you call `play` without first calling this function, the sequencer will
/// call this function before beginning playback.
open func preroll() {
if let existingMusicPlayer = musicPlayer {
MusicPlayerPreroll(existingMusicPlayer)
}
}
// MARK: Looping
/// Set loop functionality of entire sequence
open func toggleLoop() {
(loopEnabled ? disableLooping() : enableLooping())
}
/// Enable looping for all tracks - loops entire sequence
open func enableLooping() {
setLoopInfo(length, numberOfLoops: 0)
loopEnabled = true
}
/// Enable looping for all tracks with specified length
///
/// - parameter loopLength: Loop length in beats
///
open func enableLooping(_ loopLength: AKDuration) {
setLoopInfo(loopLength, numberOfLoops: 0)
loopEnabled = true
}
/// Disable looping for all tracks
open func disableLooping() {
setLoopInfo(AKDuration(beats: 0), numberOfLoops: 0)
loopEnabled = false
}
/// Set looping duration and count for all tracks
///
/// - Parameters:
/// - duration: Duration of the loop in beats
/// - numberOfLoops: The number of time to repeat
///
open func setLoopInfo(_ duration: AKDuration, numberOfLoops: Int) {
for track in tracks {
track.setLoopInfo(duration, numberOfLoops: numberOfLoops)
}
loopEnabled = true
}
// MARK: Length
/// Set length of all tracks
///
/// - parameter length: Length of tracks in beats
///
open func setLength(_ length: AKDuration) {
for track in tracks {
track.setLength(length)
}
let size: UInt32 = 0
var len = length.musicTimeStamp
var tempoTrack: MusicTrack?
if let existingSequence = sequence {
MusicSequenceGetTempoTrack(existingSequence, &tempoTrack)
}
if let existingTempoTrack = tempoTrack {
MusicTrackSetProperty(existingTempoTrack, kSequenceTrackProperty_TrackLength, &len, size)
}
}
/// Length of longest track in the sequence
open var length: AKDuration {
var length: MusicTimeStamp = 0
var tmpLength: MusicTimeStamp = 0
for track in tracks {
tmpLength = track.length
if tmpLength >= length { length = tmpLength }
}
return AKDuration(beats: length, tempo: tempo)
}
// MARK: Tempo and Rate
/// Set the rate of the sequencer
///
/// - parameter rate: Set the rate relative to the tempo of the track
///
open func setRate(_ rate: Double) {
if let existingMusicPlayer = musicPlayer {
MusicPlayerSetPlayRateScalar(existingMusicPlayer, MusicTimeStamp(rate))
}
}
/// Rate relative to the default tempo (BPM) of the track
open var rate: Double {
var rate = MusicTimeStamp(1.0)
if let existingMusicPlayer = musicPlayer {
MusicPlayerGetPlayRateScalar(existingMusicPlayer, &rate)
}
return rate
}
/// Clears all existing tempo events and adds single tempo event at start
/// Will also adjust the tempo immediately if sequence is playing when called
open func setTempo(_ bpm: Double) {
let constrainedTempo = (10...280).clamp(bpm)
var tempoTrack: MusicTrack?
if let existingSequence = sequence {
MusicSequenceGetTempoTrack(existingSequence, &tempoTrack)
}
if isPlaying {
var currTime: MusicTimeStamp = 0
if let existingMusicPlayer = musicPlayer {
MusicPlayerGetTime(existingMusicPlayer, &currTime)
}
currTime = fmod(currTime, length.beats)
if let existingTempoTrack = tempoTrack {
MusicTrackNewExtendedTempoEvent(existingTempoTrack, currTime, constrainedTempo)
}
}
if let existingTempoTrack = tempoTrack {
MusicTrackClear(existingTempoTrack, 0, length.beats)
clearTempoEvents(existingTempoTrack)
MusicTrackNewExtendedTempoEvent(existingTempoTrack, 0, constrainedTempo)
}
}
/// Add a tempo change to the score
///
/// - Parameters:
/// - bpm: Tempo in beats per minute
/// - position: Point in time in beats
///
open func addTempoEventAt(tempo bpm: Double, position: AKDuration) {
let constrainedTempo = (10...280).clamp(bpm)
var tempoTrack: MusicTrack?
if let existingSequence = sequence {
MusicSequenceGetTempoTrack(existingSequence, &tempoTrack)
}
if let existingTempoTrack = tempoTrack {
MusicTrackNewExtendedTempoEvent(existingTempoTrack, position.beats, constrainedTempo)
}
}
/// Tempo retrieved from the sequencer. Defaults to 120
/// NB: It looks at the currentPosition back in time for the last tempo event.
/// If the sequence is not started, it returns default 120
/// A sequence may contain several tempo events.
open var tempo: Double {
var tempoOut: Double = 120.0
var tempoTrack: MusicTrack?
if let existingSequence = sequence {
MusicSequenceGetTempoTrack(existingSequence, &tempoTrack)
}
var tempIterator: MusicEventIterator?
if let existingTempoTrack = tempoTrack {
NewMusicEventIterator(existingTempoTrack, &tempIterator)
}
guard let iterator = tempIterator else {
return 0.0
}
var eventTime: MusicTimeStamp = 0
var eventType: MusicEventType = kMusicEventType_ExtendedTempo
var eventData: UnsafeRawPointer?
var eventDataSize: UInt32 = 0
var hasPreviousEvent: DarwinBoolean = false
MusicEventIteratorSeek(iterator, currentPosition.beats)
MusicEventIteratorHasPreviousEvent(iterator, &hasPreviousEvent)
if hasPreviousEvent.boolValue {
MusicEventIteratorPreviousEvent(iterator)
MusicEventIteratorGetEventInfo(iterator, &eventTime, &eventType, &eventData, &eventDataSize)
if eventType == kMusicEventType_ExtendedTempo {
if let data = eventData?.assumingMemoryBound(to: ExtendedTempoEvent.self) {
let tempoEventPointer: UnsafePointer<ExtendedTempoEvent> = UnsafePointer(data)
tempoOut = tempoEventPointer.pointee.bpm
}
}
}
DisposeMusicEventIterator(iterator)
return tempoOut
}
/// returns an array of (MusicTimeStamp, bpm) tuples
/// for all tempo events on the tempo track
open var allTempoEvents: [(MusicTimeStamp, Double)] {
var tempoTrack: MusicTrack?
guard let existingSequence = sequence else { return [] }
MusicSequenceGetTempoTrack(existingSequence, &tempoTrack)
guard tempoTrack != nil else { return [] }
var tempos = [(MusicTimeStamp, Double)]()
AKMusicTrack.iterateMusicTrack(tempoTrack!) { _, eventTime, eventType, eventData, _, _ in
if eventType == kMusicEventType_ExtendedTempo {
if let data = eventData?.assumingMemoryBound(to: ExtendedTempoEvent.self) {
let tempoEventPointer: UnsafePointer<ExtendedTempoEvent> = UnsafePointer(data)
tempos.append((eventTime, tempoEventPointer.pointee.bpm))
}
}
}
return tempos
}
/// returns the tempo at a given position in beats
/// - parameter at: Position at which the tempo is desired
///
/// if there is more than one event precisely at the requested position
/// it will return the most recently added
/// Will return default 120 if there is no tempo event at or before position
open func getTempo(at position: MusicTimeStamp) -> Double {
// MIDI file with no tempo events defaults to 120 bpm
var tempoAtPosition: Double = 120.0
for event in allTempoEvents {
if event.0 <= position {
tempoAtPosition = event.1
} else {
break
}
}
return tempoAtPosition
}
// Remove existing tempo events
func clearTempoEvents(_ track: MusicTrack) {
AKMusicTrack.iterateMusicTrack(track) {iterator, _, eventType, _, _, isReadyForNextEvent in
isReadyForNextEvent = true
if eventType == kMusicEventType_ExtendedTempo {
MusicEventIteratorDeleteEvent(iterator)
isReadyForNextEvent = false
}
}
}
// MARK: Time Signature
/// Return and array of (MusicTimeStamp, AKTimeSignature) tuples
open var allTimeSignatureEvents: [(MusicTimeStamp, AKTimeSignature)] {
struct TimeSignatureEvent {
var metaEventType: UInt8 = 0
var unused1: UInt8 = 0
var unused2: UInt8 = 0
var unused3: UInt8 = 0
var dataLength: UInt32 = 0
var data: (UInt8, UInt8, UInt8, UInt8) = (0, 0, 0, 0)
}
var tempoTrack: MusicTrack?
var result = [(MusicTimeStamp, AKTimeSignature)]()
if let existingSequence = sequence {
MusicSequenceGetTempoTrack(existingSequence, &tempoTrack)
}
guard let unwrappedTempoTrack = tempoTrack else {
AKLog("Couldn't get tempo track")
return result
}
let timeSignatureMetaEventByte: UInt8 = 0x58
AKMusicTrack.iterateMusicTrack(unwrappedTempoTrack) { _, eventTime, eventType, eventData, dataSize, _ in
guard let eventData = eventData else { return }
guard eventType == kMusicEventType_Meta else { return }
let metaEventPointer = eventData.bindMemory(to: MIDIMetaEvent.self, capacity: Int(dataSize))
let metaEvent = metaEventPointer.pointee
if metaEvent.metaEventType == timeSignatureMetaEventByte {
let timeSigPointer = eventData.bindMemory(to: TimeSignatureEvent.self, capacity: Int(dataSize))
let rawTimeSig = timeSigPointer.pointee
guard let bottomValue = AKTimeSignature.TimeSignatureBottomValue(rawValue: rawTimeSig.data.1) else {
AKLog("Inavlid time signature bottom value")
return
}
let timeSigEvent = AKTimeSignature(topValue: rawTimeSig.data.0,
bottomValue: bottomValue)
result.append((eventTime, timeSigEvent))
}
}
return result
}
/// returns the time signature at a given position in beats
/// - parameter at: Position at which the time signature is desired
///
/// If there is more than one event precisely at the requested position
/// it will return the most recently added.
/// Will return 4/4 if there is no Time Signature event at or before position
open func getTimeSignature(at position: MusicTimeStamp) -> AKTimeSignature {
var outTimeSignature = AKTimeSignature() // 4/4, by default
for event in allTimeSignatureEvents {
if event.0 <= position {
outTimeSignature = event.1
} else {
break
}
}
return outTimeSignature
}
/// Add a time signature event to start of tempo track
/// NB: will affect MIDI file layout but NOT sequencer playback
///
/// - Parameters:
/// - at: MusicTimeStamp where time signature event will be placed
/// - timeSignature: Time signature for added event
/// - ticksPerMetronomeClick: MIDI clocks between metronome clicks (not PPQN), typically 24
/// - thirtySecondNotesPerQuarter: Number of 32nd notes making a quarter, typically 8
/// - clearExistingEvents: Flag that will clear other Time Signature Events from tempo track
///
open func addTimeSignatureEvent(at timeStamp: MusicTimeStamp = 0.0,
timeSignature: AKTimeSignature,
ticksPerMetronomeClick: UInt8 = 24,
thirtySecondNotesPerQuarter: UInt8 = 8,
clearExistingEvents: Bool = true) {
var tempoTrack: MusicTrack?
if let existingSequence = sequence {
MusicSequenceGetTempoTrack(existingSequence, &tempoTrack)
}
guard let unwrappedTempoTrack = tempoTrack else {
AKLog("Couldn't get tempo track")
return
}
if clearExistingEvents {
clearTimeSignatureEvents(unwrappedTempoTrack)
}
let data: [MIDIByte] = [timeSignature.topValue,
timeSignature.bottomValue.rawValue,
ticksPerMetronomeClick,
thirtySecondNotesPerQuarter]
var metaEvent = MIDIMetaEvent()
metaEvent.metaEventType = 0x58 // i.e, set time signature
metaEvent.dataLength = UInt32(data.count)
withUnsafeMutablePointer(to: &metaEvent.data, { pointer in
for i in 0 ..< data.count {
pointer[i] = data[i]
}
})
let result = MusicTrackNewMetaEvent(unwrappedTempoTrack, timeStamp, &metaEvent)
if result != 0 {
AKLog("Unable to set time signature")
}
}
/// Remove existing time signature events from tempo track
func clearTimeSignatureEvents(_ track: MusicTrack) {
let timeSignatureMetaEventByte: UInt8 = 0x58
let metaEventType = kMusicEventType_Meta
AKMusicTrack.iterateMusicTrack(track) {iterator, _, eventType, eventData, _, isReadyForNextEvent in
isReadyForNextEvent = true
guard eventType == metaEventType else { return }
let data = UnsafePointer<MIDIMetaEvent>(eventData?.assumingMemoryBound(to: MIDIMetaEvent.self))
guard let dataMetaEventType = data?.pointee.metaEventType else { return }
if dataMetaEventType == timeSignatureMetaEventByte {
MusicEventIteratorDeleteEvent(iterator)
isReadyForNextEvent = false
}
}
}
// MARK: Duration
/// Convert seconds into AKDuration
///
/// - parameter seconds: time in seconds
///
open func duration(seconds: Double) -> AKDuration {
let sign = seconds > 0 ? 1.0 : -1.0
let absoluteValueSeconds = fabs(seconds)
var outBeats = AKDuration(beats: MusicTimeStamp())
if let existingSequence = sequence {
MusicSequenceGetBeatsForSeconds(existingSequence, Float64(absoluteValueSeconds), &(outBeats.beats))
}
outBeats.beats *= sign
return outBeats
}
/// Convert beats into seconds
///
/// - parameter duration: AKDuration
///
open func seconds(duration: AKDuration) -> Double {
let sign = duration.beats > 0 ? 1.0 : -1.0
let absoluteValueBeats = fabs(duration.beats)
var outSecs: Double = MusicTimeStamp()
if let existingSequence = sequence {
MusicSequenceGetSecondsForBeats(existingSequence, absoluteValueBeats, &outSecs)
}
outSecs *= sign
return outSecs
}
// MARK: Transport Control
/// Play the sequence
open func play() {
if let existingMusicPlayer = musicPlayer {
MusicPlayerStart(existingMusicPlayer)
}
}
/// Stop the sequence
@objc open func stop() {
if let existingMusicPlayer = musicPlayer {
MusicPlayerStop(existingMusicPlayer)
}
}
/// Rewind the sequence
open func rewind() {
if let existingMusicPlayer = musicPlayer {
MusicPlayerSetTime(existingMusicPlayer, 0)
}
}
/// Wheter or not the sequencer is currently playing
open var isPlaying: Bool {
var isPlayingBool: DarwinBoolean = false
if let existingMusicPlayer = musicPlayer {
MusicPlayerIsPlaying(existingMusicPlayer, &isPlayingBool)
}
return isPlayingBool.boolValue
}
/// Current Time
open var currentPosition: AKDuration {
var currentTime = MusicTimeStamp()
if let existingMusicPlayer = musicPlayer {
MusicPlayerGetTime(existingMusicPlayer, ¤tTime)
}
let duration = AKDuration(beats: currentTime)
return duration
}
/// Current Time relative to sequencer length
open var currentRelativePosition: AKDuration {
return currentPosition % length //can switch to modTime func when/if % is removed
}
// MARK: Other Sequence Properties
/// Track count
open var trackCount: Int {
var count: UInt32 = 0
if let existingSequence = sequence {
MusicSequenceGetTrackCount(existingSequence, &count)
}
return Int(count)
}
/// Time Resolution, i.e., Pulses per quarter note
open var timeResolution: UInt32 {
let failedValue: UInt32 = 0
guard let existingSequence = sequence else {
AKLog("Couldn't get sequence for time resolution")
return failedValue
}
var tempoTrack: MusicTrack?
MusicSequenceGetTempoTrack(existingSequence, &tempoTrack)
guard let unwrappedTempoTrack = tempoTrack else {
AKLog("No tempo track for time resolution")
return failedValue
}
var ppqn: UInt32 = 0
var propertyLength: UInt32 = 0
MusicTrackGetProperty(unwrappedTempoTrack,
kSequenceTrackProperty_TimeResolution,
&ppqn,
&propertyLength)
return ppqn
}
// MARK: Loading MIDI files
/// Load a MIDI file from the bundle (removes old tracks, if present)
open func loadMIDIFile(_ filename: String) {
let bundle = Bundle.main
guard let file = bundle.path(forResource: filename, ofType: "mid") else {
AKLog("No midi file found")
return
}
let fileURL = URL(fileURLWithPath: file)
loadMIDIFile(fromURL: fileURL)
}
/// Load a MIDI file given a URL (removes old tracks, if present)
open func loadMIDIFile(fromURL fileURL: URL) {
removeTracks()
if let existingSequence = sequence {
let status: OSStatus = MusicSequenceFileLoad(existingSequence, fileURL as CFURL, .midiType, MusicSequenceLoadFlags())
if status != OSStatus(noErr) {
AKLog("error reading midi file url: \(fileURL), read status: \(status)")
}
}
initTracks()
}
// MARK: Adding MIDI File data to current sequencer
/// Add tracks from MIDI file to existing sequencer
///
/// - Parameters:
/// - filename: Location of the MIDI File
/// - useExistingSequencerLength: flag for automatically setting length of new track to current sequence length
///
/// Will copy only MIDINoteMessage events
open func addMIDIFileTracks(_ filename: String, useExistingSequencerLength: Bool = true) {
let tempSequencer = AKSequencer(filename: filename)
addMusicTrackNoteData(from: tempSequencer, useExistingSequencerLength: useExistingSequencerLength)
}
/// Add tracks from MIDI file to existing sequencer
///
/// - Parameters:
/// - filename: fromURL: URL of MIDI File
/// - useExistingSequencerLength: flag for automatically setting length of new track to current sequence length
///
/// Will copy only MIDINoteMessage events
open func addMIDIFileTracks(_ url: URL, useExistingSequencerLength: Bool = true) {
let tempSequencer = AKSequencer(fromURL: url)
addMusicTrackNoteData(from: tempSequencer, useExistingSequencerLength: useExistingSequencerLength)
}
/// Creates new AKMusicTrack with copied note event data from another AKSequencer
func addMusicTrackNoteData(from tempSequencer: AKSequencer, useExistingSequencerLength: Bool) {
guard !isPlaying else {
AKLog("Can't add tracks during playback")
return }
let oldLength = self.length
for track in tempSequencer.tracks {
let noteData = track.getMIDINoteData()
if noteData.isEmpty { continue }
let addedTrack = newTrack()
addedTrack?.replaceMIDINoteData(with: noteData)
if useExistingSequencerLength {
addedTrack?.setLength(oldLength)
}
}
if loopEnabled {
enableLooping()
}
}
/// Initialize all tracks
///
/// Rebuilds tracks based on actual contents of music sequence
///
func initTracks() {
var count: UInt32 = 0
if let existingSequence = sequence {
MusicSequenceGetTrackCount(existingSequence, &count)
}
for i in 0 ..< count {
var musicTrack: MusicTrack?
if let existingSequence = sequence {
MusicSequenceGetIndTrack(existingSequence, UInt32(i), &musicTrack)
}
if let existingMusicTrack = musicTrack {
tracks.append(AKMusicTrack(musicTrack: existingMusicTrack, name: "InitializedTrack"))
}
}
if loopEnabled {
enableLooping()
}
}
/// Dispose of tracks associated with sequence
func removeTracks() {
if let existingSequence = sequence {
var tempoTrack: MusicTrack?
MusicSequenceGetTempoTrack(existingSequence, &tempoTrack)
if let track = tempoTrack {
MusicTrackClear(track, 0, length.musicTimeStamp)
clearTimeSignatureEvents(track)
clearTempoEvents(track)
}
for track in tracks {
if let internalTrack = track.internalMusicTrack {
MusicSequenceDisposeTrack(existingSequence, internalTrack)
}
}
}
tracks.removeAll()
}
/// Get a new track
open func newTrack(_ name: String = "Unnamed") -> AKMusicTrack? {
var newMusicTrack: MusicTrack?
var count: UInt32 = 0
if let existingSequence = sequence {
MusicSequenceNewTrack(existingSequence, &newMusicTrack)
MusicSequenceGetTrackCount(existingSequence, &count)
}
if let existingNewMusicTrack = newMusicTrack {
tracks.append(AKMusicTrack(musicTrack: existingNewMusicTrack, name: name))
}
return tracks.last
}
// MARK: Delete Tracks
/// Delete track and remove it from the sequence
/// Not to be used during playback
open func deleteTrack(trackIndex: Int) {
guard !isPlaying else {
AKLog("Can't delete sequencer track during playback")
return }
guard trackIndex < tracks.count,
let internalTrack = tracks[trackIndex].internalMusicTrack else {
AKLog("Can't get track for index")
return
}
guard let existingSequence = sequence else {
AKLog("Can't get sequence")
return
}
MusicSequenceDisposeTrack(existingSequence, internalTrack)
tracks.remove(at: trackIndex)
}
/// Clear all non-tempo events from all tracks within the specified range
//
/// - Parameters:
/// - start: Start of the range to clear, in beats (inclusive)
/// - duration: Length of time after the start position to clear, in beats (exclusive)
///
open func clearRange(start: AKDuration, duration: AKDuration) {
for track in tracks {
track.clearRange(start: start, duration: duration)
}
}
/// Set the music player time directly
///
/// - parameter time: Music time stamp to set
///
open func setTime(_ time: MusicTimeStamp) {
if let existingMusicPlayer = musicPlayer {
MusicPlayerSetTime(existingMusicPlayer, time)
}
}
/// Generate NSData from the sequence
open func genData() -> Data? {
var status = noErr
var ns: Data = Data()
var data: Unmanaged<CFData>?
if let existingSequence = sequence {
status = MusicSequenceFileCreateData(existingSequence, .midiType, .eraseFile, 480, &data)
if status != noErr {
AKLog("error creating MusicSequence Data")
return nil
}
}
if let existingData = data {
ns = existingData.takeUnretainedValue() as Data
}
data?.release()
return ns
}
/// Print sequence to console
open func debug() {
if let existingPointer = sequencePointer {
CAShow(existingPointer)
}
}
/// Set the midi output for all tracks
open func setGlobalMIDIOutput(_ midiEndpoint: MIDIEndpointRef) {
for track in tracks {
track.setMIDIOutput(midiEndpoint)
}
}
/// Nearest time of quantized beat
open func nearestQuantizedPosition(quantizationInBeats: Double) -> AKDuration {
let noteOnTimeRel = currentRelativePosition.beats
let quantizationPositions = getQuantizationPositions(quantizationInBeats: quantizationInBeats)
let lastSpot = quantizationPositions[0]
let nextSpot = quantizationPositions[1]
let diffToLastSpot = AKDuration(beats: noteOnTimeRel) - lastSpot
let diffToNextSpot = nextSpot - AKDuration(beats: noteOnTimeRel)
let optimisedQuantTime = (diffToLastSpot < diffToNextSpot ? lastSpot : nextSpot)
//AKLog("last \(lastSpot.beats) - curr \(currentRelativePosition.beats) - next \(nextSpot.beats)")
//AKLog("nearest \(optimisedQuantTime.beats)")
return optimisedQuantTime
}
/// The last quantized beat
open func previousQuantizedPosition(quantizationInBeats: Double) -> AKDuration {
return getQuantizationPositions(quantizationInBeats: quantizationInBeats)[0]
}
/// Next quantized beat
open func nextQuantizedPosition(quantizationInBeats: Double) -> AKDuration {
return getQuantizationPositions(quantizationInBeats: quantizationInBeats)[1]
}
/// An array of all quantization points
func getQuantizationPositions(quantizationInBeats: Double) -> [AKDuration] {
let noteOnTimeRel = currentRelativePosition.beats
let lastSpot = AKDuration(beats:
modTime(noteOnTimeRel - (noteOnTimeRel.truncatingRemainder(dividingBy: quantizationInBeats))))
let nextSpot = AKDuration(beats: modTime(lastSpot.beats + quantizationInBeats))
return [lastSpot, nextSpot]
}
/// Time modulus
func modTime(_ time: Double) -> Double {
return time.truncatingRemainder(dividingBy: length.beats)
}
}
| 35.457978 | 129 | 0.623888 |
ac39a3bcc3cbdd0055bf42d56e59c46798b47b6d | 3,779 | // Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import Alamofire
import Foundation
enum RequestError: Error {
case invalidBaseURL
}
typealias StringDictionary = [String: String]
enum AuthRouter: URLRequestConvertible {
private struct Request {
let method: Alamofire.HTTPMethod
let path: String
let encoding: ParameterEncoding?
let parameters: JSONDictionary?
let headers: [String: String]
init(
method: Alamofire.HTTPMethod,
path: String,
encoding: ParameterEncoding? = nil,
parameters: JSONDictionary? = nil,
headers: [String: String] = [:]
) {
self.method = method
self.path = path
self.encoding = encoding
self.parameters = parameters
self.headers = headers
}
}
case changePassword(params: JSONDictionary, userID: String)
case logout(userID: String)
case forgotPassword(params: JSONDictionary)
case auth(params: JSONDictionary)
case codeGrant(params: JSONDictionary, headers: [String: String])
static let hydraServerURL = API.hydraURL
static let authServerURL = API.authURL
static let redirectURL = authServerURL + "/callback"
static let oauthVersion = "/oauth2"
var baseURLPath: String {
switch self {
case .auth:
return AuthRouter.hydraServerURL + AuthRouter.oauthVersion
case .codeGrant:
return "\(AuthRouter.authServerURL)\(AuthRouter.oauthVersion)"
default:
return AuthRouter.authServerURL
}
}
private var request: Request {
switch self {
case .auth(let parameters):
return Request(
method: .get,
path: "/auth",
encoding: URLEncoding.default,
parameters: parameters
)
case .codeGrant(let params, let headers):
return Request(
method: .post,
path: "/token",
encoding: URLEncoding.httpBody,
parameters: params,
headers: headers
)
case .forgotPassword(let parameters):
return Request(
method: .post,
path: "/user/reset_password",
encoding: JSONEncoding.default,
parameters: parameters
)
case .logout(let userID):
return Request(
method: .post,
path: "/users/\(userID)/logout",
encoding: JSONEncoding.default
)
case .changePassword(let parameters, let userID):
return Request(
method: .put,
path: "/users/\(userID)/change_password",
encoding: JSONEncoding.default,
parameters: parameters
)
}
}
private var defaultHeaders: StringDictionary {
switch self {
case .auth:
return [:]
default:
return SessionService.Audit.headers
}
}
func asURLRequest() throws -> URLRequest {
guard let url = URL(string: baseURLPath) else { throw RequestError.invalidBaseURL }
var mutableUrlRequest = try URLRequest(
url: url.appendingPathComponent(request.path),
method: request.method
)
mutableUrlRequest.timeoutInterval = TimeInterval(30)
for i in request.headers {
mutableUrlRequest.setValue(i.value, forHTTPHeaderField: i.key)
}
for header in defaultHeaders {
mutableUrlRequest.setValue(header.value, forHTTPHeaderField: header.key)
}
if let accessToken = User.currentUser.authToken {
mutableUrlRequest.setValue(accessToken, forHTTPHeaderField: "Authorization")
}
if let encoding = request.encoding {
let finalRequest = try encoding.encode(
mutableUrlRequest,
with: request.parameters
)
return finalRequest
} else {
return mutableUrlRequest as URLRequest
}
}
}
| 24.861842 | 87 | 0.660228 |
752a217d774870a89da2f9cec615d03c2508d229 | 4,758 | //
// WebViewController.swift
//
import UIKit
import WebKit
import MBProgressHUD
import CPEData
open class WebViewController: UIViewController {
fileprivate struct Constants {
static let ScriptMessageHandlerName = "microHTMLMessageHandler"
static let ScriptMessageAppVisible = "AppVisible"
static let ScriptMessageAppShutdown = "AppShutdown"
static let HeaderButtonWidth: CGFloat = (DeviceType.IS_IPAD ? 125 : 100)
static let HeaderButtonHeight: CGFloat = (DeviceType.IS_IPAD ? 90 : 50)
static let HeaderIconPadding: CGFloat = (DeviceType.IS_IPAD ? 30 : 15)
}
private var url: URL!
private var webView: WKWebView!
public var hud: MBProgressHUD?
public var shouldDisplayFullScreen = true
// MARK: Initialization
convenience public init(url: URL, title: String? = nil) {
self.init()
self.url = url
self.title = title
if var components = URLComponents(url: url, resolvingAgainstBaseURL: true), let deviceIdentifier = DeviceType.identifier {
let deviceModelParam = "iphoneModel=\(deviceIdentifier)"
if let query = components.query {
components.query = "\(query)&\(deviceModelParam)"
} else {
components.query = deviceModelParam
}
if let newUrl = components.url {
self.url = newUrl
}
}
}
// MARK: View Lifecycle
override open func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black
self.navigationController?.isNavigationBarHidden = shouldDisplayFullScreen
let configuration = WKWebViewConfiguration()
configuration.userContentController = WKUserContentController()
configuration.userContentController.add(self, name: Constants.ScriptMessageHandlerName)
configuration.allowsInlineMediaPlayback = true
if #available(iOS 9.0, *) {
configuration.requiresUserActionForMediaPlayback = false
} else {
configuration.mediaPlaybackRequiresUserAction = false
}
webView = WKWebView(frame: self.view.bounds, configuration: configuration)
self.view.addSubview(webView)
// Disable caching for now
if #available(iOS 9.0, *) {
if let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache]) as? Set<String> {
let date = Date(timeIntervalSince1970: 0)
WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes, modifiedSince: date, completionHandler: { })
}
} else if let libraryPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, false).first {
do {
try FileManager.default.removeItem(atPath: "\(libraryPath)/Cookies")
} catch {
print("Error clearing cookies folder")
}
URLCache.shared.removeAllCachedResponses()
}
webView.navigationDelegate = self
webView.load(URLRequest(url: url))
hud = MBProgressHUD.showAdded(to: webView, animated: true)
}
override open func prefersHomeIndicatorAutoHidden() -> Bool {
return true
}
// MARK: Actions
open func close() {
webView.configuration.userContentController.removeScriptMessageHandler(forName: Constants.ScriptMessageHandlerName)
webView.navigationDelegate = nil
self.dismiss(animated: true, completion: nil)
}
}
extension WebViewController: WKNavigationDelegate {
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.targetFrame == nil {
navigationAction.request.url?.promptLaunch(withMessage: String.localize("info.leaving_app.message_general"))
return decisionHandler(.cancel)
}
decisionHandler(.allow)
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
hud?.hide(true)
}
}
extension WebViewController: WKScriptMessageHandler {
public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == Constants.ScriptMessageHandlerName, let messageBody = message.body as? String {
if messageBody == Constants.ScriptMessageAppVisible {
} else if messageBody == Constants.ScriptMessageAppShutdown {
close()
}
}
}
}
| 35.774436 | 185 | 0.667087 |
0110fa2af3dac78b5d649872f5195d544cf4c5ae | 4,054 | import UIKit
final class StakingRewardHistoryTableCell: UITableViewCell {
private enum Constants {
static let verticalInset: CGFloat = 11
static let iconSize: CGFloat = 32
}
private let transactionTypeView: UIView = {
UIImageView(image: R.image.iconStakingTransactionType())
}()
private let addressLabel: UILabel = {
let label = UILabel()
label.font = .p1Paragraph
label.lineBreakMode = .byTruncatingMiddle
label.textColor = R.color.colorWhite()
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return label
}()
private let daysLeftLabel: UILabel = {
let label = UILabel()
label.font = .p2Paragraph
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return label
}()
private let tokenAmountLabel: UILabel = {
let label = UILabel()
label.font = .p1Paragraph
label.textColor = R.color.colorWhite()
label.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
return label
}()
private let usdAmountLabel: UILabel = {
let label = UILabel()
label.font = .p2Paragraph
label.textColor = R.color.colorLightGray()
label.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .clear
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = R.color.colorAccent()!.withAlphaComponent(0.3)
self.selectedBackgroundView = selectedBackgroundView
setupLayout()
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupLayout() {
contentView.addSubview(transactionTypeView)
transactionTypeView.snp.makeConstraints { make in
make.leading.equalToSuperview().inset(UIConstants.horizontalInset)
make.centerY.equalToSuperview()
make.width.equalTo(Constants.iconSize)
}
contentView.addSubview(addressLabel)
addressLabel.snp.makeConstraints { make in
make.leading.equalTo(transactionTypeView.snp.trailing).offset(UIConstants.horizontalInset / 2)
make.top.equalToSuperview().inset(Constants.verticalInset)
}
contentView.addSubview(daysLeftLabel)
daysLeftLabel.snp.makeConstraints { make in
make.leading.equalTo(transactionTypeView.snp.trailing).offset(UIConstants.horizontalInset / 2)
make.top.equalTo(addressLabel.snp.bottom)
make.bottom.equalToSuperview().inset(Constants.verticalInset)
}
contentView.addSubview(tokenAmountLabel)
tokenAmountLabel.snp.makeConstraints { make in
make.trailing.equalToSuperview().inset(UIConstants.horizontalInset)
make.top.equalToSuperview().inset(Constants.verticalInset)
make.leading.greaterThanOrEqualTo(addressLabel.snp.trailing).offset(UIConstants.horizontalInset / 2)
}
contentView.addSubview(usdAmountLabel)
usdAmountLabel.snp.makeConstraints { make in
make.trailing.equalToSuperview().inset(UIConstants.horizontalInset)
make.top.equalTo(tokenAmountLabel.snp.bottom)
make.bottom.equalToSuperview().inset(Constants.verticalInset)
}
}
}
extension StakingRewardHistoryTableCell {
func bind(model: StakingRewardHistoryCellViewModel) {
addressLabel.text = model.addressOrName
daysLeftLabel.attributedText = model.daysLeftText
tokenAmountLabel.text = model.tokenAmountText
usdAmountLabel.text = model.usdAmountText
}
func bind(timeLeftText: NSAttributedString) {
daysLeftLabel.attributedText = timeLeftText
}
}
| 37.192661 | 112 | 0.687469 |
11a7954c68884445f5d599c854b75f02b1d2b745 | 1,355 | //
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
import Foundation
public struct ASCBetaTesterAppsLinkagesRequest: AppStoreConnectBaseModel {
public var data: [DataType]
public struct DataType: AppStoreConnectBaseModel {
public enum ASCType: String, Codable, Equatable, CaseIterable {
case apps = "apps"
}
public var _id: String
public var type: ASCType
public init(_id: String, type: ASCType) {
self._id = _id
self.type = type
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
_id = try container.decode("id")
type = try container.decode("type")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(_id, forKey: "id")
try container.encode(type, forKey: "type")
}
}
public init(data: [DataType]) {
self.data = data
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
data = try container.decodeArray("data")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(data, forKey: "data")
}
}
| 22.583333 | 74 | 0.681181 |
03463c93f6308d9f6fd9f83751892d7aca9bd4c3 | 6,460 | //
// FriendshipManager.swift
// Runner
//
// Created by z1u24 on 2021/6/29.
//
import Foundation
import OpenIMCore
public class FriendshipManager: BaseServiceManager {
public override func registerHandlers() {
super.registerHandlers()
self["setFriendListener"] = setFriendListener
self["getFriendsInfo"] = getFriendsInfo
self["addFriend"] = addFriend
self["getFriendApplicationList"] = getFriendApplicationList
self["getFriendList"] = getFriendList
self["setFriendInfo"] = setFriendInfo
self["addToBlackList"] = addToBlackList
self["getBlackList"] = getBlackList
self["deleteFromBlackList"] = deleteFromBlackList
self["checkFriend"] = checkFriend
self["deleteFromFriendList"] = deleteFromFriendList
self["acceptFriendApplication"] = acceptFriendApplication
self["refuseFriendApplication"] = refuseFriendApplication
// self["forceSyncFriendApplication"] = forceSyncFriendApplication
// self["forceSyncFriend"] = forceSyncFriend
// self["forceSyncBlackList"] = forceSyncBlackList
}
func setFriendListener(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
Open_im_sdkSetFriendListener(FriendshipListener(channel: channel))
callBack(result)
}
func getFriendsInfo(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
Open_im_sdkGetFriendsInfo(BaseCallback(result: result), methodCall[jsonString: "uidList"])
}
func addFriend(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
Open_im_sdkAddFriend(BaseCallback(result: result), methodCall.toJsonString())
}
func getFriendApplicationList(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
Open_im_sdkGetFriendApplicationList(BaseCallback(result: result))
}
func getFriendList(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
Open_im_sdkGetFriendList(BaseCallback(result: result))
}
func setFriendInfo(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
Open_im_sdkSetFriendInfo(methodCall.toJsonString(), BaseCallback(result: result))
}
func addToBlackList(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
Open_im_sdkAddToBlackList(BaseCallback(result: result), methodCall[jsonString: "uid"])
}
func getBlackList(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
Open_im_sdkGetBlackList(BaseCallback(result: result))
}
func deleteFromBlackList(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
Open_im_sdkDeleteFromBlackList(BaseCallback(result: result), methodCall[jsonString: "uid"])
}
func checkFriend(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
Open_im_sdkCheckFriend(BaseCallback(result: result), methodCall[jsonString: "uidList"])
}
func deleteFromFriendList(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
Open_im_sdkDeleteFromFriendList(methodCall[jsonString: "uid"], BaseCallback(result: result))
}
func acceptFriendApplication(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
Open_im_sdkAcceptFriendApplication(BaseCallback(result: result), methodCall[jsonString: "uid"])
}
func refuseFriendApplication(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
Open_im_sdkRefuseFriendApplication(BaseCallback(result: result), methodCall[jsonString: "uid"])
}
// func forceSyncFriendApplication(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
// Open_im_sdkForceSyncFriendApplication()
// callBack(result)
// }
//
// func forceSyncFriend(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
// Open_im_sdkForceSyncFriend()
// callBack(result)
// }
//
// func forceSyncBlackList(methodCall: FlutterMethodCall, result: @escaping FlutterResult){
// Open_im_sdkForceSyncBlackList()
// callBack(result)
// }
}
public class FriendshipListener: NSObject, Open_im_sdkOnFriendshipListenerProtocol {
private let channel:FlutterMethodChannel
init(channel:FlutterMethodChannel) {
self.channel = channel
}
public func onBlackListAdd(_ userInfo: String?) {
CommonUtil.emitEvent(channel: channel, method: "friendListener", type: "onBlackListAdd", errCode: nil, errMsg: nil, data: userInfo)
}
public func onBlackListDeleted(_ userInfo: String?) {
CommonUtil.emitEvent(channel: channel, method: "friendListener", type: "onBlackListDeleted", errCode: nil, errMsg: nil, data: userInfo)
}
public func onFriendApplicationListAccept(_ applyUserInfo: String?) {
CommonUtil.emitEvent(channel: channel, method: "friendListener", type: "onFriendApplicationListAccept", errCode: nil, errMsg: nil, data: applyUserInfo)
}
public func onFriendApplicationListAdded(_ applyUserInfo: String?) {
CommonUtil.emitEvent(channel: channel, method: "friendListener", type: "onFriendApplicationListAdded", errCode: nil, errMsg: nil, data: applyUserInfo)
}
public func onFriendApplicationListDeleted(_ applyUserInfo: String?) {
CommonUtil.emitEvent(channel: channel, method: "friendListener", type: "onFriendApplicationListDeleted", errCode: nil, errMsg: nil, data: applyUserInfo)
}
public func onFriendApplicationListReject(_ applyUserInfo: String?) {
CommonUtil.emitEvent(channel: channel, method: "friendListener", type: "onFriendApplicationListReject", errCode: nil, errMsg: nil, data: applyUserInfo)
}
public func onFriendInfoChanged(_ friendInfo: String?) {
CommonUtil.emitEvent(channel: channel, method: "friendListener", type: "onFriendInfoChanged", errCode: nil, errMsg: nil, data: friendInfo)
}
public func onFriendListAdded(_ friendInfo: String?) {
CommonUtil.emitEvent(channel: channel, method: "friendListener", type: "onFriendListAdded", errCode: nil, errMsg: nil, data: friendInfo)
}
public func onFriendListDeleted(_ friendInfo: String?) {
CommonUtil.emitEvent(channel: channel, method: "friendListener", type: "onFriendListDeleted", errCode: nil, errMsg: nil, data: friendInfo)
}
}
| 43.945578 | 160 | 0.721672 |
1848cbff82b7da22d3a33d83515b47a416d0fc85 | 3,346 | //
// Extensions.swift
// Timeless
//
// Created by Joe Speakman on 2/12/22.
//
import Foundation
import SwiftUI
extension UnicodeScalar {
var isEmoji: Bool {
switch value {
case 0x1F600...0x1F64F, // Emoticons
0x1F300...0x1F5FF, // Misc Symbols and Pictographs
0x1F680...0x1F6FF, // Transport and Map
0x1F1E6...0x1F1FF, // Regional country flags
0x2600...0x26FF, // Misc symbols
0x2700...0x27BF, // Dingbats
0xE0020...0xE007F, // Tags
0xFE00...0xFE0F, // Variation Selectors
0x1F900...0x1F9FF, // Supplemental Symbols and Pictographs
0x1F018...0x1F270, // Various asian characters
0x238C...0x2454, // Misc items
0x20D0...0x20FF: // Combining Diacritical Marks for Symbols
return true
default: return false
}
}
var isZeroWidthJoiner: Bool {
return value == 8205
}
}
extension String {
// Not needed anymore in swift 4.2 and later, using `.count` will give you the correct result
var glyphCount: Int {
let richText = NSAttributedString(string: self)
let line = CTLineCreateWithAttributedString(richText)
return CTLineGetGlyphCount(line)
}
var isSingleEmoji: Bool {
return glyphCount == 1 && containsEmoji
}
var containsEmoji: Bool {
return unicodeScalars.contains { $0.isEmoji }
}
var containsOnlyEmoji: Bool {
return !isEmpty
&& !unicodeScalars.contains(where: {
!$0.isEmoji && !$0.isZeroWidthJoiner
})
}
// The next tricks are mostly to demonstrate how tricky it can be to determine emoji's
// If anyone has suggestions how to improve this, please let me know
var emojiString: String {
return emojiScalars.map { String($0) }.reduce("", +)
}
var emojis: [String] {
var scalars: [[UnicodeScalar]] = []
var currentScalarSet: [UnicodeScalar] = []
var previousScalar: UnicodeScalar?
for scalar in emojiScalars {
if let prev = previousScalar, !prev.isZeroWidthJoiner, !scalar.isZeroWidthJoiner {
scalars.append(currentScalarSet)
currentScalarSet = []
}
currentScalarSet.append(scalar)
previousScalar = scalar
}
scalars.append(currentScalarSet)
return scalars.map { $0.map { String($0) }.reduce("", +) }
}
fileprivate var emojiScalars: [UnicodeScalar] {
var chars: [UnicodeScalar] = []
var previous: UnicodeScalar?
for cur in unicodeScalars {
if let previous = previous, previous.isZeroWidthJoiner, cur.isEmoji {
chars.append(previous)
chars.append(cur)
} else if cur.isEmoji {
chars.append(cur)
}
previous = cur
}
return chars
}
}
extension View {
func underlineTextField() -> some View {
self
.padding(.vertical, 10)
.overlay(Rectangle().frame(height: 2).padding(.top, 35))
.foregroundColor(Constants.appColor)
.padding(10)
}
}
| 29.350877 | 97 | 0.564256 |
f86e4db564fc1e068f63d0dae9f34b864120e403 | 307 | //
// Created by Jake Lin on 2/29/16.
// Copyright (c) 2016 Jake Lin. All rights reserved.
//
import Foundation
// Default transition duration.
// The default UIKit transtion animation duration is 0.35, but too fast for most of custom transition animations.
let defaultTransitionDuration: Duration = 0.75
| 27.909091 | 113 | 0.7557 |
2667522c14833a43081c88737be4b70751b6e206 | 73,372 | //
// PreferencesWindowController.swift
// Aerial
//
// Created by John Coates on 10/23/15.
// Copyright © 2015 John Coates. All rights reserved.
//
import Cocoa
import AVKit
import AVFoundation
import ScreenSaver
import VideoToolbox
import CoreLocation
class TimeOfDay {
let title: String
var videos: [AerialVideo] = [AerialVideo]()
init(title: String) {
self.title = title
}
}
class City {
var night: TimeOfDay = TimeOfDay(title: "night")
var day: TimeOfDay = TimeOfDay(title: "day")
let name: String
//var videos: [AerialVideo] = [AerialVideo]()
init(name: String) {
self.name = name
}
func addVideoForTimeOfDay(_ timeOfDay: String, video: AerialVideo) {
if timeOfDay.lowercased() == "night" {
video.arrayPosition = night.videos.count
night.videos.append(video)
} else {
video.arrayPosition = day.videos.count
day.videos.append(video)
}
}
}
@objc(PreferencesWindowController)
// swiftlint:disable:next type_body_length
class PreferencesWindowController: NSWindowController, NSOutlineViewDataSource, NSOutlineViewDelegate {
enum HEVCMain10Support: Int {
case notsupported, unsure, partial, supported
}
@IBOutlet weak var prefTabView: NSTabView!
@IBOutlet var outlineView: NSOutlineView!
@IBOutlet var outlineViewSettings: NSButton!
@IBOutlet var playerView: AVPlayerView!
@IBOutlet var showDescriptionsCheckbox: NSButton!
@IBOutlet weak var useCommunityCheckbox: NSButton!
@IBOutlet var localizeForTvOS12Checkbox: NSButton!
@IBOutlet var projectPageLink: NSButton!
@IBOutlet var secondProjectPageLink: NSButton!
@IBOutlet var cacheLocation: NSPathControl!
@IBOutlet var cacheAerialsAsTheyPlayCheckbox: NSButton!
@IBOutlet var neverStreamVideosCheckbox: NSButton!
@IBOutlet var neverStreamPreviewsCheckbox: NSButton!
@IBOutlet weak var downloadNowButton: NSButton!
@IBOutlet var overrideOnBatteryCheckbox: NSButton!
@IBOutlet var powerSavingOnLowBatteryCheckbox: NSButton!
@IBOutlet var overrideNightOnDarkMode: NSButton!
@IBOutlet var multiMonitorModePopup: NSPopUpButton!
@IBOutlet var popupVideoFormat: NSPopUpButton!
@IBOutlet var alternatePopupVideoFormat: NSPopUpButton!
@IBOutlet var descriptionModePopup: NSPopUpButton!
@IBOutlet var fadeInOutModePopup: NSPopUpButton!
@IBOutlet weak var fadeInOutTextModePopup: NSPopUpButton!
@IBOutlet weak var downloadProgressIndicator: NSProgressIndicator!
@IBOutlet weak var downloadStopButton: NSButton!
@IBOutlet var versionLabel: NSTextField!
@IBOutlet var popover: NSPopover!
@IBOutlet var popoverTime: NSPopover!
@IBOutlet var popoverPower: NSPopover!
@IBOutlet var linkTimeWikipediaButton: NSButton!
@IBOutlet var popoverH264Indicator: NSButton!
@IBOutlet var popoverHEVCIndicator: NSButton!
@IBOutlet var popoverH264Label: NSTextField!
@IBOutlet var popoverHEVCLabel: NSTextField!
@IBOutlet var timeDisabledRadio: NSButton!
@IBOutlet var timeNightShiftRadio: NSButton!
@IBOutlet var timeManualRadio: NSButton!
@IBOutlet var timeLightDarkModeRadio: NSButton!
@IBOutlet var timeCalculateRadio: NSButton!
@IBOutlet var nightShiftLabel: NSTextField!
@IBOutlet var lightDarkModeLabel: NSTextField!
@IBOutlet var latitudeTextField: NSTextField!
@IBOutlet var longitudeTextField: NSTextField!
@IBOutlet var findCoordinatesButton: NSButton!
@IBOutlet var extraLatitudeTextField: NSTextField!
@IBOutlet var extraLongitudeTextField: NSTextField!
@IBOutlet var enterCoordinatesButton: NSButton!
@IBOutlet var enterCoordinatesPanel: NSPanel!
@IBOutlet var calculateCoordinatesLabel: NSTextField!
@IBOutlet var latitudeFormatter: NumberFormatter!
@IBOutlet var longitudeFormatter: NumberFormatter!
@IBOutlet var extraLatitudeFormatter: NumberFormatter!
@IBOutlet var extraLongitudeFormatter: NumberFormatter!
@IBOutlet var solarModePopup: NSPopUpButton!
@IBOutlet var sunriseTime: NSDatePicker!
@IBOutlet var sunsetTime: NSDatePicker!
@IBOutlet var iconTime1: NSImageCell!
@IBOutlet var iconTime2: NSImageCell!
@IBOutlet var iconTime3: NSImageCell!
@IBOutlet var cornerContainer: NSTextField!
@IBOutlet var cornerTopLeft: NSButton!
@IBOutlet var cornerTopRight: NSButton!
@IBOutlet var cornerBottomLeft: NSButton!
@IBOutlet var cornerBottomRight: NSButton!
@IBOutlet var cornerRandom: NSButton!
@IBOutlet var changeCornerMargins: NSButton!
@IBOutlet var marginHorizontalTextfield: NSTextField!
@IBOutlet var marginVerticalTextfield: NSTextField!
@IBOutlet var secondaryMarginHorizontalTextfield: NSTextField!
@IBOutlet var secondaryMarginVerticalTextfield: NSTextField!
@IBOutlet var editMarginButton: NSButton!
@IBOutlet var previewDisabledTextfield: NSTextField!
@IBOutlet var fontPickerButton: NSButton!
@IBOutlet var fontResetButton: NSButton!
@IBOutlet var extraFontPickerButton: NSButton!
@IBOutlet var extraFontResetButton: NSButton!
@IBOutlet var currentFontLabel: NSTextField!
@IBOutlet var currentLocaleLabel: NSTextField!
@IBOutlet var showClockCheckbox: NSButton!
@IBOutlet weak var withSecondsCheckbox: NSButton!
@IBOutlet var showExtraMessage: NSButton!
@IBOutlet var extraMessageTextField: NSTextField!
@IBOutlet var secondaryExtraMessageTextField: NSTextField!
@IBOutlet var extraMessageFontLabel: NSTextField!
@IBOutlet weak var extraCornerPopup: NSPopUpButton!
@IBOutlet var editExtraMessageButton: NSButton!
@IBOutlet var dimBrightness: NSButton!
@IBOutlet var dimStartFrom: NSSlider!
@IBOutlet var dimFadeTo: NSSlider!
@IBOutlet var dimFadeInMinutes: NSTextField!
@IBOutlet var dimFadeInMinutesStepper: NSStepper!
@IBOutlet var dimOnlyAtNight: NSButton!
@IBOutlet var dimOnlyOnBattery: NSButton!
@IBOutlet var overrideDimFadeCheckbox: NSButton!
@IBOutlet var sleepAfterLabel: NSTextField!
@IBOutlet var logPanel: NSPanel!
@IBOutlet var editMarginsPanel: NSPanel!
@IBOutlet var editExtraMessagePanel: NSPanel!
@IBOutlet weak var showLogBottomClick: NSButton!
@IBOutlet weak var logTableView: NSTableView!
@IBOutlet weak var debugModeCheckbox: NSButton!
@IBOutlet weak var logToDiskCheckbox: NSButton!
@IBOutlet weak var cacheSizeTextField: NSTextField!
@IBOutlet var newVideosModePopup: NSPopUpButton!
var player: AVPlayer = AVPlayer()
var videos: [AerialVideo]?
// cities -> time of day -> videos
var cities = [City]()
static var loadedJSON: Bool = false
lazy var preferences = Preferences.sharedInstance
let fontManager: NSFontManager
var fontEditing = 0 // To track the font we are changing
var highestLevel: ErrorLevel? // To track the largest level of error received
var savedBrightness: Float?
var locationManager: CLLocationManager?
public var appMode: Bool = false
// MARK: - Init
required init?(coder decoder: NSCoder) {
self.fontManager = NSFontManager.shared
debugLog("pwc init1")
super.init(coder: decoder)
}
// We start here from SysPref and App mode
override init(window: NSWindow?) {
self.fontManager = NSFontManager.shared
debugLog("pwc init2")
super.init(window: window)
}
// MARK: - Lifecycle
// swiftlint:disable:next cyclomatic_complexity
override func awakeFromNib() {
super.awakeFromNib()
// tmp
let tm = TimeManagement.sharedInstance
debugLog("isonbattery")
debugLog("\(tm.isOnBattery())")
//
let logger = Logger.sharedInstance
logger.addCallback {level in
self.updateLogs(level: level)
}
let videoManager = VideoManager.sharedInstance
videoManager.addCallback { done, total in
self.updateDownloads(done: done, total: total)
}
self.fontManager.target = self
latitudeFormatter.maximumSignificantDigits = 10
longitudeFormatter.maximumSignificantDigits = 10
extraLatitudeFormatter.maximumSignificantDigits = 10
extraLongitudeFormatter.maximumSignificantDigits = 10
updateCacheSize()
outlineView.floatsGroupRows = false
loadJSON() // Async loading
logTableView.delegate = self
logTableView.dataSource = self
if let version = Bundle(identifier: "com.johncoates.Aerial-Test")?.infoDictionary?["CFBundleShortVersionString"] as? String {
versionLabel.stringValue = version
}
if let version = Bundle(identifier: "com.JohnCoates.Aerial")?.infoDictionary?["CFBundleShortVersionString"] as? String {
versionLabel.stringValue = version
}
// Some better icons are 10.12.2+ only
if #available(OSX 10.12.2, *) {
iconTime1.image = NSImage(named: NSImage.touchBarHistoryTemplateName)
iconTime2.image = NSImage(named: NSImage.touchBarComposeTemplateName)
iconTime3.image = NSImage(named: NSImage.touchBarOpenInBrowserTemplateName)
findCoordinatesButton.image = NSImage(named: NSImage.touchBarOpenInBrowserTemplateName)
}
// Help popover, GVA detection requires 10.13
if #available(OSX 10.13, *) {
if !VTIsHardwareDecodeSupported(kCMVideoCodecType_H264) {
popoverH264Label.stringValue = "H264 acceleration not supported"
popoverH264Indicator.image = NSImage(named: NSImage.statusUnavailableName)
}
if !VTIsHardwareDecodeSupported(kCMVideoCodecType_HEVC) {
popoverHEVCLabel.stringValue = "HEVC Main10 acceleration not supported"
popoverHEVCIndicator.image = NSImage(named: NSImage.statusUnavailableName)
} else {
switch isHEVCMain10HWDecodingAvailable() {
case .supported:
popoverHEVCLabel.stringValue = "HEVC Main10 acceleration is supported"
popoverHEVCIndicator.image = NSImage(named: NSImage.statusAvailableName)
case .notsupported:
popoverHEVCLabel.stringValue = "HEVC Main10 acceleration is not supported"
popoverHEVCIndicator.image = NSImage(named: NSImage.statusUnavailableName)
case .partial:
popoverHEVCLabel.stringValue = "HEVC Main10 acceleration is partially supported"
popoverHEVCIndicator.image = NSImage(named: NSImage.statusPartiallyAvailableName)
default:
popoverHEVCLabel.stringValue = "HEVC Main10 acceleration status unknown"
popoverHEVCIndicator.image = NSImage(named: NSImage.cautionName)
}
}
} else {
// Fallback on earlier versions
popoverHEVCIndicator.isHidden = true
popoverH264Indicator.image = NSImage(named: NSImage.cautionName)
popoverH264Label.stringValue = "macOS 10.13 or above required"
popoverHEVCLabel.stringValue = "Hardware acceleration status unknown"
}
// Fonts for descriptions and extra (clock/msg)
currentFontLabel.stringValue = preferences.fontName! + ", \(preferences.fontSize!) pt"
extraMessageFontLabel.stringValue = preferences.extraFontName! + ", \(preferences.extraFontSize!) pt"
// Extra message
extraMessageTextField.stringValue = preferences.showMessageString!
secondaryExtraMessageTextField.stringValue = preferences.showMessageString!
// Grab preferred language as proper string
let printOutputLocale: NSLocale = NSLocale(localeIdentifier: Locale.preferredLanguages[0])
if let deviceLanguageName: String = printOutputLocale.displayName(forKey: NSLocale.Key.identifier, value: Locale.preferredLanguages[0]) {
currentLocaleLabel.stringValue = "Preferred language: \(deviceLanguageName)"
} else {
currentLocaleLabel.stringValue = ""
}
// Videos panel
playerView.player = player
playerView.controlsStyle = .none
if #available(OSX 10.10, *) {
playerView.videoGravity = AVLayerVideoGravity.resizeAspectFill
}
// To loop playback, we catch the end of the video to rewind
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidReachEnd(notification:)),
name: Notification.Name.AVPlayerItemDidPlayToEndTime,
object: player.currentItem)
if #available(OSX 10.12, *) {
} else {
showClockCheckbox.isEnabled = false
}
// Videos panel
if preferences.overrideOnBattery {
overrideOnBatteryCheckbox.state = .on
changeBatteryOverrideState(to: true)
} else {
changeBatteryOverrideState(to: false)
}
if preferences.powerSavingOnLowBattery {
powerSavingOnLowBatteryCheckbox.state = .on
}
// Aerial panel
if preferences.debugMode {
debugModeCheckbox.state = .on
}
if preferences.logToDisk {
logToDiskCheckbox.state = .on
}
// Text panel
if preferences.showClock {
showClockCheckbox.state = .on
withSecondsCheckbox.isEnabled = true
}
if preferences.withSeconds {
withSecondsCheckbox.state = .on
}
if preferences.showMessage {
showExtraMessage.state = .on
editExtraMessageButton.isEnabled = true
extraMessageTextField.isEnabled = true
}
if preferences.showDescriptions {
showDescriptionsCheckbox.state = .on
changeTextState(to: true)
} else {
changeTextState(to: false)
}
if preferences.localizeDescriptions {
localizeForTvOS12Checkbox.state = .on
}
if preferences.overrideMargins {
changeCornerMargins.state = .on
marginHorizontalTextfield.isEnabled = true
marginVerticalTextfield.isEnabled = true
editMarginButton.isEnabled = true
}
// Cache panel
if preferences.neverStreamVideos {
neverStreamVideosCheckbox.state = .on
}
if preferences.neverStreamPreviews {
neverStreamPreviewsCheckbox.state = .on
}
if !preferences.useCommunityDescriptions {
useCommunityCheckbox.state = .off
}
if !preferences.cacheAerials {
cacheAerialsAsTheyPlayCheckbox.state = .off
}
// Brightness panel
if preferences.overrideDimInMinutes {
overrideDimFadeCheckbox.state = .on
}
if preferences.dimBrightness {
dimBrightness.state = .on
changeBrightnessState(to: true)
} else {
changeBrightnessState(to: false)
}
if preferences.dimOnlyOnBattery {
dimOnlyOnBattery.state = .on
}
if preferences.dimOnlyAtNight {
dimOnlyAtNight.state = .on
}
dimStartFrom.doubleValue = preferences.startDim ?? 0.5
dimFadeTo.doubleValue = preferences.endDim ?? 0.1
dimFadeInMinutes.stringValue = String(preferences.dimInMinutes!)
dimFadeInMinutesStepper.intValue = Int32(preferences.dimInMinutes!)
// Time mode
if #available(OSX 10.14, *) {
if preferences.darkModeNightOverride {
overrideNightOnDarkMode.state = .on
}
// We disable the checkbox if we are on nightShift mode
if preferences.timeMode == Preferences.TimeMode.lightDarkMode.rawValue {
overrideNightOnDarkMode.isEnabled = false
}
} else {
overrideNightOnDarkMode.isEnabled = false
}
let timeManagement = TimeManagement.sharedInstance
// Light/Dark mode only available on Mojave+
let (isLDMCapable, reason: LDMReason) = timeManagement.isLightDarkModeAvailable()
if !isLDMCapable {
timeLightDarkModeRadio.isEnabled = false
}
lightDarkModeLabel.stringValue = LDMReason
// Night Shift requires 10.12.4+ and a compatible Mac
let (isNSCapable, reason: NSReason) = timeManagement.isNightShiftAvailable()
if !isNSCapable {
timeNightShiftRadio.isEnabled = false
}
nightShiftLabel.stringValue = NSReason
let (_, reason) = timeManagement.calculateFromCoordinates()
calculateCoordinatesLabel.stringValue = reason
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
if let dateSunrise = dateFormatter.date(from: preferences.manualSunrise!) {
sunriseTime.dateValue = dateSunrise
}
if let dateSunset = dateFormatter.date(from: preferences.manualSunset!) {
sunsetTime.dateValue = dateSunset
}
latitudeTextField.stringValue = preferences.latitude!
longitudeTextField.stringValue = preferences.longitude!
extraLatitudeTextField.stringValue = preferences.latitude!
extraLongitudeTextField.stringValue = preferences.longitude!
marginHorizontalTextfield.stringValue = String(preferences.marginX!)
marginVerticalTextfield.stringValue = String(preferences.marginY!)
secondaryMarginHorizontalTextfield.stringValue = String(preferences.marginX!)
secondaryMarginVerticalTextfield.stringValue = String(preferences.marginY!)
// Handle the time radios
switch preferences.timeMode {
case Preferences.TimeMode.nightShift.rawValue:
timeNightShiftRadio.state = NSControl.StateValue.on
case Preferences.TimeMode.manual.rawValue:
timeManualRadio.state = NSControl.StateValue.on
case Preferences.TimeMode.lightDarkMode.rawValue:
timeLightDarkModeRadio.state = NSControl.StateValue.on
case Preferences.TimeMode.coordinates.rawValue:
timeCalculateRadio.state = .on
default:
timeDisabledRadio.state = NSControl.StateValue.on
}
// Handle the corner radios
switch preferences.descriptionCorner {
case Preferences.DescriptionCorner.topLeft.rawValue:
cornerTopLeft.state = NSControl.StateValue.on
case Preferences.DescriptionCorner.topRight.rawValue:
cornerTopRight.state = NSControl.StateValue.on
case Preferences.DescriptionCorner.bottomLeft.rawValue:
cornerBottomLeft.state = NSControl.StateValue.on
case Preferences.DescriptionCorner.bottomRight.rawValue:
cornerBottomRight.state = NSControl.StateValue.on
default:
cornerRandom.state = NSControl.StateValue.on
}
solarModePopup.selectItem(at: preferences.solarMode!)
multiMonitorModePopup.selectItem(at: preferences.multiMonitorMode!)
popupVideoFormat.selectItem(at: preferences.videoFormat!)
alternatePopupVideoFormat.selectItem(at: preferences.alternateVideoFormat!)
descriptionModePopup.selectItem(at: preferences.showDescriptionsMode!)
fadeInOutModePopup.selectItem(at: preferences.fadeMode!)
fadeInOutTextModePopup.selectItem(at: preferences.fadeModeText!)
extraCornerPopup.selectItem(at: preferences.extraCorner!)
newVideosModePopup.selectItem(at: preferences.newVideosMode!)
colorizeProjectPageLinks()
if let cacheDirectory = VideoCache.cacheDirectory {
cacheLocation.url = URL(fileURLWithPath: cacheDirectory as String)
} else {
cacheLocation.url = nil
}
let sleepTime = timeManagement.getCurrentSleepTime()
if sleepTime != 0 {
sleepAfterLabel.stringValue = "Your Mac currently goes to sleep after \(sleepTime) minutes"
} else {
sleepAfterLabel.stringValue = "Unable to determine your Mac sleep settings"
}
// To workaround our High Sierra issues with textfields, we have separate panels
// that replicate the features and are editable. They are hidden unless needed.
if #available(OSX 10.14, *) {
editMarginButton.isHidden = true
editExtraMessageButton.isHidden = true
enterCoordinatesButton.isHidden = true
} else {
marginHorizontalTextfield.isEnabled = false
marginVerticalTextfield.isEnabled = false
extraMessageTextField.isEnabled = false
latitudeTextField.isEnabled = false
longitudeTextField.isEnabled = false
}
debugLog("appMode : \(appMode)")
}
override func windowDidLoad() {
super.windowDidLoad()
// Workaround for garbled icons on non retina, we force redraw
outlineView.reloadData()
debugLog("wdl")
}
@IBAction func close(_ sender: AnyObject?) {
logPanel.close()
if appMode {
NSApplication.shared.terminate(nil)
} else {
window?.sheetParent?.endSheet(window!)
}
}
// MARK: Video playback
// Rewind preview video when reaching end
@objc func playerItemDidReachEnd(notification: Notification) {
if let playerItem: AVPlayerItem = notification.object as? AVPlayerItem {
let url: URL? = (playerItem.asset as? AVURLAsset)?.url
if url!.absoluteString.starts(with: "file") {
playerItem.seek(to: CMTime.zero, completionHandler: nil)
self.player.play()
}
}
}
// MARK: - Setup
fileprivate func colorizeProjectPageLinks() {
let color = NSColor(calibratedRed: 0.18, green: 0.39, blue: 0.76, alpha: 1)
var coloredLink = NSMutableAttributedString(attributedString: projectPageLink.attributedTitle)
var fullRange = NSRange(location: 0, length: coloredLink.length)
coloredLink.addAttribute(NSAttributedString.Key.foregroundColor,
value: color,
range: fullRange)
projectPageLink.attributedTitle = coloredLink
// We have an extra project link on the video format popover, color it too
coloredLink = NSMutableAttributedString(attributedString: secondProjectPageLink.attributedTitle)
fullRange = NSRange(location: 0, length: coloredLink.length)
coloredLink.addAttribute(NSAttributedString.Key.foregroundColor,
value: color,
range: fullRange)
secondProjectPageLink.attributedTitle = coloredLink
// We have an extra project link on the video format popover, color it too
coloredLink = NSMutableAttributedString(attributedString: linkTimeWikipediaButton.attributedTitle)
fullRange = NSRange(location: 0, length: coloredLink.length)
coloredLink.addAttribute(NSAttributedString.Key.foregroundColor,
value: color,
range: fullRange)
linkTimeWikipediaButton.attributedTitle = coloredLink
}
// MARK: - Video panel
@IBAction func overrideOnBatteryClick(_ sender: NSButton) {
let onState = (sender.state == NSControl.StateValue.on)
preferences.overrideOnBattery = onState
changeBatteryOverrideState(to: onState)
debugLog("UI overrideOnBattery \(onState)")
}
@IBAction func powerSavingOnLowClick(_ sender: NSButton) {
let onState = (sender.state == NSControl.StateValue.on)
preferences.powerSavingOnLowBattery = onState
debugLog("UI powerSavingOnLow \(onState)")
}
@IBAction func alternateVideoFormatChange(_ sender: NSPopUpButton) {
debugLog("UI alternatePopupVideoFormat: \(sender.indexOfSelectedItem)")
preferences.alternateVideoFormat = sender.indexOfSelectedItem
changeBatteryOverrideState(to: true)
}
func changeBatteryOverrideState(to: Bool) {
alternatePopupVideoFormat.isEnabled = to
if !to || (to && preferences.alternateVideoFormat != Preferences.AlternateVideoFormat.powerSaving.rawValue) {
powerSavingOnLowBatteryCheckbox.isEnabled = to
} else {
powerSavingOnLowBatteryCheckbox.isEnabled = false
}
}
@IBAction func popupVideoFormatChange(_ sender: NSPopUpButton) {
debugLog("UI popupVideoFormat: \(sender.indexOfSelectedItem)")
preferences.videoFormat = sender.indexOfSelectedItem
preferences.synchronize()
outlineView.reloadData()
}
@IBAction func helpButtonClick(_ button: NSButton!) {
popover.show(relativeTo: button.preparedContentRect, of: button, preferredEdge: .maxY)
}
@IBAction func helpPowerButtonClick(_ button: NSButton!) {
popoverPower.show(relativeTo: button.preparedContentRect, of: button, preferredEdge: .maxY)
}
@IBAction func multiMonitorModePopupChange(_ sender: NSPopUpButton) {
debugLog("UI multiMonitorMode: \(sender.indexOfSelectedItem)")
preferences.multiMonitorMode = sender.indexOfSelectedItem
preferences.synchronize()
}
@IBAction func fadeInOutModePopupChange(_ sender: NSPopUpButton) {
debugLog("UI fadeInOutMode: \(sender.indexOfSelectedItem)")
preferences.fadeMode = sender.indexOfSelectedItem
preferences.synchronize()
}
func updateDownloads(done: Int, total: Int) {
print("VMQueue: done : \(done) \(total)")
if total == 0 {
downloadProgressIndicator.isHidden = true
downloadStopButton.isHidden = true
downloadNowButton.isEnabled = true
} else {
downloadNowButton.isEnabled = false
downloadProgressIndicator.isHidden = false
downloadStopButton.isHidden = false
downloadProgressIndicator.doubleValue = Double(done)
downloadProgressIndicator.maxValue = Double(total)
}
}
@IBAction func cancelDownloadsClick(_ sender: Any) {
debugLog("UI cancelDownloadsClick")
let videoManager = VideoManager.sharedInstance
videoManager.cancelAll()
}
// MARK: - Mac Model detection and HEVC Main10 detection
private func getMacModel() -> String {
var size = 0
sysctlbyname("hw.model", nil, &size, nil, 0)
var machine = [CChar](repeating: 0, count: size)
sysctlbyname("hw.model", &machine, &size, nil, 0)
return String(cString: machine)
}
private func extractMacVersion(macModel: String, macSubmodel: String) -> NSNumber {
// Substring the thing
let str = macModel.dropFirst(macSubmodel.count)
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "fr_FR")
if let number = formatter.number(from: String(str)) {
return number
} else {
return 0
}
}
private func getHEVCMain10Support(macModel: String, macSubmodel: String, partial: Double, full: Double) -> HEVCMain10Support {
let ver = extractMacVersion(macModel: macModel, macSubmodel: macSubmodel)
if ver.doubleValue > full {
return .supported
} else if ver.doubleValue > partial {
return .partial
} else {
return .notsupported
}
}
private func isHEVCMain10HWDecodingAvailable() -> HEVCMain10Support {
let macModel = getMacModel()
// iMacPro - always
if macModel.starts(with: "iMacPro") {
return .supported
} else if macModel.starts(with: "iMac") {
// iMacs, as far as we know, partial 17+, full 18+
return getHEVCMain10Support(macModel: macModel, macSubmodel: "iMac", partial: 17.0, full: 18.0)
} else if macModel.starts(with: "MacBookPro") {
// MacBookPro full 14+
return getHEVCMain10Support(macModel: macModel, macSubmodel: "MacBookPro", partial: 13.0, full: 14.0)
} else if macModel.starts(with: "MacBookAir") {
// MBA still on haswell/broadwell...
return .notsupported
} else if macModel.starts(with: "MacBook") {
// MacBook 10+
return getHEVCMain10Support(macModel: macModel, macSubmodel: "MacBook", partial: 9.0, full: 10.0)
} else if macModel.starts(with: "Macmini") || macModel.starts(with: "MacPro") {
// Right now no support on these
return .notsupported
}
// Older stuff (power/etc) should not even run this so list should be complete
// Hackintosh/new SKUs may fail this test
return .unsure
}
// MARK: - Text panel
// We have a secondary panel for entering margins as a workaround on < Mojave
@IBAction func openExtraMessagePanelClick(_ sender: Any) {
if editExtraMessagePanel.isVisible {
editExtraMessagePanel.close()
} else {
editExtraMessagePanel.makeKeyAndOrderFront(sender)
}
}
@IBAction func openExtraMarginPanelClick(_ sender: Any) {
if editMarginsPanel.isVisible {
editMarginsPanel.close()
} else {
editMarginsPanel.makeKeyAndOrderFront(sender)
}
}
@IBAction func closeExtraMarginPanelClick(_ sender: Any) {
editMarginsPanel.close()
}
@IBAction func closeExtraMessagePanelClick(_ sender: Any) {
editExtraMessagePanel.close()
}
@IBAction func showDescriptionsClick(button: NSButton?) {
let state = showDescriptionsCheckbox.state
let onState = (state == NSControl.StateValue.on)
preferences.showDescriptions = onState
debugLog("UI showDescriptions: \(onState)")
changeTextState(to: onState)
}
func changeTextState(to: Bool) {
// Location information
useCommunityCheckbox.isEnabled = to
localizeForTvOS12Checkbox.isEnabled = to
descriptionModePopup.isEnabled = to
fadeInOutTextModePopup.isEnabled = to
fontPickerButton.isEnabled = to
fontResetButton.isEnabled = to
currentFontLabel.isEnabled = to
changeCornerMargins.isEnabled = to
if (to && changeCornerMargins.state == .on) || !to {
marginHorizontalTextfield.isEnabled = to
marginVerticalTextfield.isEnabled = to
editExtraMessageButton.isEnabled = to
}
cornerContainer.isEnabled = to
cornerTopLeft.isEnabled = to
cornerTopRight.isEnabled = to
cornerBottomLeft.isEnabled = to
cornerBottomRight.isEnabled = to
cornerRandom.isEnabled = to
// Extra info, linked too
showClockCheckbox.isEnabled = to
if (to && showClockCheckbox.state == .on) || !to {
withSecondsCheckbox.isEnabled = to
}
showExtraMessage.isEnabled = to
if (to && showExtraMessage.state == .on) || !to {
extraMessageTextField.isEnabled = to
editExtraMessageButton.isEnabled = to
}
extraFontPickerButton.isEnabled = to
extraFontResetButton.isEnabled = to
extraMessageFontLabel.isEnabled = to
extraCornerPopup.isEnabled = to
}
@IBAction func useCommunityClick(_ button: NSButton) {
let state = useCommunityCheckbox.state
let onState = (state == NSControl.StateValue.on)
preferences.useCommunityDescriptions = onState
debugLog("UI useCommunity: \(onState)")
}
@IBAction func localizeForTvOS12Click(button: NSButton?) {
let state = localizeForTvOS12Checkbox.state
let onState = (state == NSControl.StateValue.on)
preferences.localizeDescriptions = onState
debugLog("UI localizeDescriptions: \(onState)")
}
@IBAction func descriptionModePopupChange(_ sender: NSPopUpButton) {
debugLog("UI descriptionMode: \(sender.indexOfSelectedItem)")
preferences.showDescriptionsMode = sender.indexOfSelectedItem
preferences.synchronize()
}
@IBAction func fontPickerClick(_ sender: NSButton?) {
// Make a panel
let fp = self.fontManager.fontPanel(true)
// Set current font
if let font = NSFont(name: preferences.fontName!, size: CGFloat(preferences.fontSize!)) {
fp?.setPanelFont(font, isMultiple: false)
} else {
fp?.setPanelFont(NSFont(name: "Helvetica Neue Medium", size: 28)!, isMultiple: false)
}
// push the panel but mark which one we are editing
fontEditing = 0
fp?.makeKeyAndOrderFront(sender)
}
@IBAction func fontResetClick(_ sender: NSButton?) {
preferences.fontName = "Helvetica Neue Medium"
preferences.fontSize = 28
// Update our label
currentFontLabel.stringValue = preferences.fontName! + ", \(preferences.fontSize!) pt"
}
@IBAction func extraFontPickerClick(_ sender: NSButton?) {
// Make a panel
let fp = self.fontManager.fontPanel(true)
// Set current font
if let font = NSFont(name: preferences.extraFontName!, size: CGFloat(preferences.extraFontSize!)) {
fp?.setPanelFont(font, isMultiple: false)
} else {
fp?.setPanelFont(NSFont(name: "Helvetica Neue Medium", size: 28)!, isMultiple: false)
}
// push the panel but mark which one we are editing
fontEditing = 1
fp?.makeKeyAndOrderFront(sender)
}
@IBAction func extraFontResetClick(_ sender: NSButton?) {
preferences.extraFontName = "Helvetica Neue Medium"
preferences.extraFontSize = 28
// Update our label
extraMessageFontLabel.stringValue = preferences.extraFontName! + ", \(preferences.extraFontSize!) pt"
}
@IBAction func extraTextFieldChange(_ sender: NSTextField) {
debugLog("UI extraTextField \(sender.stringValue)")
if sender == secondaryExtraMessageTextField {
extraMessageTextField.stringValue = sender.stringValue
}
preferences.showMessageString = sender.stringValue
}
@IBAction func descriptionCornerChange(_ sender: NSButton?) {
if sender == cornerTopLeft {
preferences.descriptionCorner = Preferences.DescriptionCorner.topLeft.rawValue
} else if sender == cornerTopRight {
preferences.descriptionCorner = Preferences.DescriptionCorner.topRight.rawValue
} else if sender == cornerBottomLeft {
preferences.descriptionCorner = Preferences.DescriptionCorner.bottomLeft.rawValue
} else if sender == cornerBottomRight {
preferences.descriptionCorner = Preferences.DescriptionCorner.bottomRight.rawValue
} else if sender == cornerRandom {
preferences.descriptionCorner = Preferences.DescriptionCorner.random.rawValue
}
}
@IBAction func showClockClick(_ sender: NSButton) {
let onState = (sender.state == NSControl.StateValue.on)
preferences.showClock = onState
withSecondsCheckbox.isEnabled = onState
debugLog("UI showClock: \(onState)")
}
@IBAction func withSecondsClick(_ sender: NSButton) {
let onState = (sender.state == NSControl.StateValue.on)
preferences.withSeconds = onState
debugLog("UI withSeconds: \(onState)")
}
@IBAction func showExtraMessageClick(_ sender: NSButton) {
let onState = (sender.state == NSControl.StateValue.on)
// We also need to enable/disable our message field
extraMessageTextField.isEnabled = onState
editExtraMessageButton.isEnabled = onState
preferences.showMessage = onState
debugLog("UI showExtraMessage: \(onState)")
}
@IBAction func fadeInOutTextModePopupChange(_ sender: NSPopUpButton) {
debugLog("UI fadeInOutTextMode: \(sender.indexOfSelectedItem)")
preferences.fadeModeText = sender.indexOfSelectedItem
preferences.synchronize()
}
@IBAction func extraCornerPopupChange(_ sender: NSPopUpButton) {
debugLog("UI extraCorner: \(sender.indexOfSelectedItem)")
preferences.extraCorner = sender.indexOfSelectedItem
preferences.synchronize()
}
@IBAction func changeMarginsToCornerClick(_ sender: NSButton) {
let onState = (sender.state == NSControl.StateValue.on)
debugLog("UI changeMarginsToCorner: \(onState)")
marginHorizontalTextfield.isEnabled = onState
marginVerticalTextfield.isEnabled = onState
preferences.overrideMargins = onState
editExtraMessageButton.isEnabled = onState
}
@IBAction func marginXChange(_ sender: NSTextField) {
preferences.marginX = Int(sender.stringValue)
if sender == secondaryMarginHorizontalTextfield {
marginHorizontalTextfield.stringValue = sender.stringValue
}
debugLog("UI marginXChange: \(sender.stringValue)")
}
@IBAction func marginYChange(_ sender: NSTextField) {
preferences.marginY = Int(sender.stringValue)
if sender == secondaryMarginVerticalTextfield {
marginVerticalTextfield.stringValue = sender.stringValue
}
debugLog("UI marginYChange: \(sender.stringValue)")
}
// MARK: - Cache panel
func updateCacheSize() {
// get your directory url
let documentsDirectoryURL = URL(fileURLWithPath: VideoCache.cacheDirectory!)
// FileManager.default.urls(for: VideoCache.cacheDirectory, in: .userDomainMask).first!
// check if the url is a directory
if (try? documentsDirectoryURL.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true {
var folderSize = 0
(FileManager.default.enumerator(at: documentsDirectoryURL, includingPropertiesForKeys: nil)?.allObjects as? [URL])?.lazy.forEach {
folderSize += (try? $0.resourceValues(forKeys: [.totalFileAllocatedSizeKey]))?.totalFileAllocatedSize ?? 0
}
let byteCountFormatter = ByteCountFormatter()
byteCountFormatter.allowedUnits = .useGB
byteCountFormatter.countStyle = .file
let sizeToDisplay = byteCountFormatter.string(for: folderSize) ?? ""
debugLog("Cache size : \(sizeToDisplay)")
cacheSizeTextField.stringValue = "Cache all videos (Current cache size \(sizeToDisplay))"
}
}
@IBAction func cacheAerialsAsTheyPlayClick(_ button: NSButton!) {
let onState = (button.state == NSControl.StateValue.on)
preferences.cacheAerials = onState
debugLog("UI cacheAerialAsTheyPlay: \(onState)")
}
@IBAction func neverStreamVideosClick(_ button: NSButton!) {
let onState = (button.state == NSControl.StateValue.on)
preferences.neverStreamVideos = onState
debugLog("UI neverStreamVideos: \(onState)")
}
@IBAction func neverStreamPreviewsClick(_ button: NSButton!) {
let onState = (button.state == NSControl.StateValue.on)
preferences.neverStreamPreviews = onState
debugLog("UI neverStreamPreviews: \(onState)")
}
@IBAction func showInFinder(_ button: NSButton!) {
NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: VideoCache.cacheDirectory!)
}
@IBAction func userSetCacheLocation(_ button: NSButton?) {
let openPanel = NSOpenPanel()
openPanel.canChooseDirectories = true
openPanel.canChooseFiles = false
openPanel.canCreateDirectories = true
openPanel.allowsMultipleSelection = false
openPanel.title = "Choose Aerial Cache Directory"
openPanel.prompt = "Choose"
openPanel.directoryURL = cacheLocation.url
openPanel.begin { result in
guard result.rawValue == NSFileHandlingPanelOKButton, !openPanel.urls.isEmpty else {
return
}
let cacheDirectory = openPanel.urls[0]
self.preferences.customCacheDirectory = cacheDirectory.path
self.cacheLocation.url = cacheDirectory
}
}
@IBAction func resetCacheLocation(_ button: NSButton?) {
preferences.customCacheDirectory = nil
if let cacheDirectory = VideoCache.cacheDirectory {
cacheLocation.url = URL(fileURLWithPath: cacheDirectory as String)
}
}
@IBAction func downloadNowButton(_ sender: Any) {
downloadNowButton.isEnabled = false
prefTabView.selectTabViewItem(at: 0)
downloadAllVideos()
}
@IBAction func newVideosModeChange(_ sender: NSPopUpButton) {
debugLog("UI newVideosMode: \(sender.indexOfSelectedItem)")
preferences.newVideosMode = sender.indexOfSelectedItem
}
// MARK: - Time panel
@IBAction func overrideNightOnDarkModeClick(_ button: NSButton) {
let onState = (button.state == NSControl.StateValue.on)
preferences.darkModeNightOverride = onState
debugLog("UI overrideNightDarkMode: \(onState)")
}
@IBAction func enterCoordinatesButtonClick(_ sender: Any) {
if enterCoordinatesPanel.isVisible {
enterCoordinatesPanel.close()
} else {
enterCoordinatesPanel.makeKeyAndOrderFront(sender)
}
}
@IBAction func closeCoordinatesPanel(_ sender: Any) {
enterCoordinatesPanel.close()
}
@IBAction func timeModeChange(_ sender: NSButton?) {
debugLog("UI timeModeChange")
if sender == timeLightDarkModeRadio {
print("dis")
overrideNightOnDarkMode.isEnabled = false
} else {
if #available(OSX 10.14, *) {
overrideNightOnDarkMode.isEnabled = true
}
}
if sender == timeDisabledRadio {
preferences.timeMode = Preferences.TimeMode.disabled.rawValue
} else if sender == timeNightShiftRadio {
preferences.timeMode = Preferences.TimeMode.nightShift.rawValue
} else if sender == timeManualRadio {
preferences.timeMode = Preferences.TimeMode.manual.rawValue
} else if sender == timeLightDarkModeRadio {
preferences.timeMode = Preferences.TimeMode.lightDarkMode.rawValue
} else if sender == timeCalculateRadio {
preferences.timeMode = Preferences.TimeMode.coordinates.rawValue
}
}
@IBAction func sunriseChange(_ sender: NSDatePicker?) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let sunriseString = dateFormatter.string(from: (sender?.dateValue)!)
preferences.manualSunrise = sunriseString
}
@IBAction func sunsetChange(_ sender: NSDatePicker?) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let sunsetString = dateFormatter.string(from: (sender?.dateValue)!)
preferences.manualSunset = sunsetString
}
@IBAction func latitudeChange(_ sender: NSTextField) {
preferences.latitude = sender.stringValue
if sender == extraLatitudeTextField {
latitudeTextField.stringValue = sender.stringValue
}
updateLatitudeLongitude()
}
@IBAction func longitudeChange(_ sender: NSTextField) {
debugLog("longitudechange")
preferences.longitude = sender.stringValue
if sender == extraLongitudeTextField {
longitudeTextField.stringValue = sender.stringValue
}
updateLatitudeLongitude()
}
func updateLatitudeLongitude() {
let timeManagement = TimeManagement.sharedInstance
let (_, reason) = timeManagement.calculateFromCoordinates()
calculateCoordinatesLabel.stringValue = reason
}
@IBAction func solarModePopupChange(_ sender: NSPopUpButton) {
preferences.solarMode = sender.indexOfSelectedItem
debugLog("UI solarModePopupChange: \(sender.indexOfSelectedItem)")
updateLatitudeLongitude()
}
@IBAction func helpTimeButtonClick(_ button: NSButton) {
popoverTime.show(relativeTo: button.preparedContentRect, of: button, preferredEdge: .maxY)
}
@IBAction func linkToWikipediaTimeClick(_ sender: NSButton) {
let workspace = NSWorkspace.shared
let url = URL(string: "https://en.wikipedia.org/wiki/Twilight")!
workspace.open(url)
}
@IBAction func findCoordinatesButtonClick(_ sender: NSButton) {
debugLog("UI findCoordinatesButton")
locationManager = CLLocationManager()
locationManager!.delegate = self
locationManager!.desiredAccuracy = kCLLocationAccuracyBest
locationManager!.distanceFilter = 100
locationManager!.purpose = "Aerial uses your location to calculate sunrise and sunset times"
if CLLocationManager.locationServicesEnabled() {
debugLog("Location services enabled")
_ = CLLocationManager.authorizationStatus()
locationManager!.startUpdatingLocation()
} else {
errorLog("Location services are disabled, please check your macOS settings!")
return
}
}
func pushCoordinates(_ coordinates: CLLocationCoordinate2D) {
latitudeTextField.stringValue = String(coordinates.latitude)
longitudeTextField.stringValue = String(coordinates.longitude)
preferences.latitude = String(coordinates.latitude)
preferences.longitude = String(coordinates.longitude)
updateLatitudeLongitude()
}
// MARK: - Brightness panel
func changeBrightnessState(to: Bool) {
dimOnlyAtNight.isEnabled = to
dimOnlyOnBattery.isEnabled = to
dimStartFrom.isEnabled = to
dimFadeTo.isEnabled = to
overrideDimFadeCheckbox.isEnabled = to
if (to && preferences.overrideDimInMinutes) || !to {
dimFadeInMinutes.isEnabled = to
dimFadeInMinutesStepper.isEnabled = to
} else {
dimFadeInMinutes.isEnabled = false
dimFadeInMinutesStepper.isEnabled = false
}
}
@IBAction func overrideFadeDurationClick(_ sender: NSButton) {
let onState = (sender.state == .on)
preferences.overrideDimInMinutes = onState
changeBrightnessState(to: preferences.dimBrightness)
debugLog("UI dimBrightness: \(onState)")
}
@IBAction func dimBrightnessClick(_ button: NSButton) {
let onState = (button.state == .on)
preferences.dimBrightness = onState
changeBrightnessState(to: onState)
debugLog("UI dimBrightness: \(onState)")
}
@IBAction func dimOnlyAtNightClick(_ button: NSButton) {
let onState = (button.state == .on)
preferences.dimOnlyAtNight = onState
debugLog("UI dimOnlyAtNight: \(onState)")
}
@IBAction func dimOnlyOnBattery(_ button: NSButton) {
let onState = (button.state == .on)
preferences.dimOnlyOnBattery = onState
debugLog("UI dimOnlyOnBattery: \(onState)")
}
@IBAction func dimStartFromChange(_ sender: NSSliderCell) {
let timeManagement = TimeManagement.sharedInstance
guard let event = NSApplication.shared.currentEvent else {
return
}
if event.type != .leftMouseUp && event.type != .leftMouseDown && event.type != .leftMouseDragged {
//warnLog("Unexepected event type \(event.type)")
return
}
if event.type == .leftMouseUp {
if savedBrightness != nil {
timeManagement.setBrightness(level: savedBrightness!)
savedBrightness = nil
}
preferences.startDim = sender.doubleValue
debugLog("UI startDim: \(sender.doubleValue)")
} else {
if savedBrightness == nil {
savedBrightness = timeManagement.getBrightness()
}
timeManagement.setBrightness(level: sender.floatValue)
}
}
@IBAction func dimFadeToChange(_ sender: NSSliderCell) {
let timeManagement = TimeManagement.sharedInstance
guard let event = NSApplication.shared.currentEvent else {
return
}
if event.type != .leftMouseUp && event.type != .leftMouseDown && event.type != .leftMouseDragged {
//warnLog("Unexepected event type \(event.type)")
}
if event.type == .leftMouseUp {
if savedBrightness != nil {
timeManagement.setBrightness(level: savedBrightness!)
savedBrightness = nil
}
preferences.endDim = sender.doubleValue
debugLog("UI endDim: \(sender.doubleValue)")
} else {
if savedBrightness == nil {
savedBrightness = timeManagement.getBrightness()
}
timeManagement.setBrightness(level: sender.floatValue)
}
}
@IBAction func dimInMinutes(_ sender: NSControl) {
if sender == dimFadeInMinutes {
if let intValue = Int(sender.stringValue) {
preferences.dimInMinutes = intValue
dimFadeInMinutesStepper.intValue = Int32(intValue)
}
} else {
preferences.dimInMinutes = Int(sender.intValue)
dimFadeInMinutes.stringValue = String(sender.intValue)
}
debugLog("UI dimInMinutes \(sender.stringValue)")
}
// MARK: - Advanced panel
@IBAction func logButtonClick(_ sender: NSButton) {
logTableView.reloadData()
if logPanel.isVisible {
logPanel.close()
} else {
logPanel.makeKeyAndOrderFront(sender)
}
}
@IBAction func logCopyToClipboardClick(_ sender: NSButton) {
guard !errorMessages.isEmpty else {
return
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .medium
var clipboard = ""
for log in errorMessages {
clipboard += dateFormatter.string(from: log.date) + " : " + log.message + "\n"
}
let pasteBoard = NSPasteboard.general
pasteBoard.clearContents()
pasteBoard.setString(clipboard, forType: NSPasteboard.PasteboardType.string)
}
@IBAction func logRefreshClick(_ sender: NSButton) {
logTableView.reloadData()
}
@IBAction func debugModeClick(_ button: NSButton) {
let onState = (button.state == NSControl.StateValue.on)
preferences.debugMode = onState
debugLog("UI debugMode: \(onState)")
}
@IBAction func logToDiskClick(_ button: NSButton) {
let onState = (button.state == NSControl.StateValue.on)
preferences.logToDisk = onState
debugLog("UI logToDisk: \(onState)")
}
@IBAction func showLogInFinder(_ button: NSButton!) {
let logfile = VideoCache.cacheDirectory!.appending("/AerialLog.txt")
// If we don't have a log, just show the folder
if FileManager.default.fileExists(atPath: logfile) == false {
NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: VideoCache.cacheDirectory!)
} else {
NSWorkspace.shared.selectFile(logfile, inFileViewerRootedAtPath: VideoCache.cacheDirectory!)
}
}
func updateLogs(level: ErrorLevel) {
logTableView.reloadData()
if highestLevel == nil {
highestLevel = level
} else if level.rawValue > highestLevel!.rawValue {
highestLevel = level
}
switch highestLevel! {
case ErrorLevel.debug:
showLogBottomClick.title = "Show Debug"
showLogBottomClick.image = NSImage.init(named: NSImage.actionTemplateName)
case ErrorLevel.info:
showLogBottomClick.title = "Show Info"
showLogBottomClick.image = NSImage.init(named: NSImage.infoName)
case ErrorLevel.warning:
showLogBottomClick.title = "Show Warning"
showLogBottomClick.image = NSImage.init(named: NSImage.cautionName)
default:
showLogBottomClick.title = "Show Error"
showLogBottomClick.image = NSImage.init(named: NSImage.stopProgressFreestandingTemplateName)
}
showLogBottomClick.isHidden = false
}
// MARK: - Menu
@IBAction func outlineViewSettingsClick(_ button: NSButton) {
let menu = NSMenu()
menu.insertItem(withTitle: "Check Only Cached",
action: #selector(PreferencesWindowController.outlineViewCheckCached(button:)),
keyEquivalent: "",
at: 0)
menu.insertItem(withTitle: "Check Only 4K",
action: #selector(PreferencesWindowController.outlineViewCheck4K(button:)),
keyEquivalent: "",
at: 1)
menu.insertItem(withTitle: "Check All",
action: #selector(PreferencesWindowController.outlineViewCheckAll(button:)),
keyEquivalent: "",
at: 2)
menu.insertItem(withTitle: "Uncheck All",
action: #selector(PreferencesWindowController.outlineViewUncheckAll(button:)),
keyEquivalent: "",
at: 3)
menu.insertItem(NSMenuItem.separator(), at: 4)
menu.insertItem(withTitle: "Download Checked",
action: #selector(PreferencesWindowController.outlineViewDownloadChecked(button:)),
keyEquivalent: "",
at: 5)
menu.insertItem(withTitle: "Download All",
action: #selector(PreferencesWindowController.outlineViewDownloadAll(button:)),
keyEquivalent: "",
at: 6)
let event = NSApp.currentEvent
NSMenu.popUpContextMenu(menu, with: event!, for: button)
}
@objc func outlineViewUncheckAll(button: NSButton) {
setAllVideos(inRotation: false)
}
@objc func outlineViewCheckAll(button: NSButton) {
setAllVideos(inRotation: true)
}
@objc func outlineViewCheck4K(button: NSButton) {
guard let videos = videos else {
return
}
for video in videos {
if video.url4KHEVC != "" {
preferences.setVideo(videoID: video.id,
inRotation: true,
synchronize: false)
} else {
preferences.setVideo(videoID: video.id,
inRotation: false,
synchronize: false)
}
}
preferences.synchronize()
outlineView.reloadData()
}
@objc func outlineViewCheckCached(button: NSButton) {
guard let videos = videos else {
return
}
for video in videos {
if video.isAvailableOffline {
preferences.setVideo(videoID: video.id,
inRotation: true,
synchronize: false)
} else {
preferences.setVideo(videoID: video.id,
inRotation: false,
synchronize: false)
}
}
preferences.synchronize()
outlineView.reloadData()
}
@objc func outlineViewDownloadChecked(button: NSButton) {
guard let videos = videos else {
return
}
let videoManager = VideoManager.sharedInstance
for video in videos {
if preferences.videoIsInRotation(videoID: video.id) && !video.isAvailableOffline {
if !videoManager.isVideoQueued(id: video.id) {
videoManager.queueDownload(video)
}
}
}
}
@objc func outlineViewDownloadAll(button: NSButton) {
downloadAllVideos()
}
func downloadAllVideos() {
guard let videos = videos else {
return
}
let videoManager = VideoManager.sharedInstance
for video in videos where !video.isAvailableOffline {
if !videoManager.isVideoQueued(id: video.id) {
videoManager.queueDownload(video)
}
}
}
func setAllVideos(inRotation: Bool) {
guard let videos = videos else {
return
}
for video in videos {
preferences.setVideo(videoID: video.id,
inRotation: inRotation,
synchronize: false)
}
preferences.synchronize()
outlineView.reloadData()
}
// MARK: - Links
@IBAction func pageProjectClick(_ button: NSButton?) {
let workspace = NSWorkspace.shared
let url = URL(string: "http://github.com/JohnCoates/Aerial")!
workspace.open(url)
}
// MARK: - Manifest
func loadJSON() {
if PreferencesWindowController.loadedJSON {
return
}
PreferencesWindowController.loadedJSON = true
ManifestLoader.instance.addCallback { manifestVideos in
self.loaded(manifestVideos: manifestVideos)
}
}
func loaded(manifestVideos: [AerialVideo]) {
var videos = [AerialVideo]()
var cities = [String: City]()
// First day, then night
for video in manifestVideos {
let name = video.name
if cities.keys.contains(name) == false {
cities[name] = City(name: name)
}
let city = cities[name]!
let timeOfDay = video.timeOfDay
city.addVideoForTimeOfDay(timeOfDay, video: video)
videos.append(video)
}
self.videos = videos
// sort cities by name
let unsortedCities = cities.values
let sortedCities = unsortedCities.sorted { $0.name < $1.name }
self.cities = sortedCities
DispatchQueue.main.async {
self.outlineView.reloadData()
self.outlineView.expandItem(nil, expandChildren: true)
}
}
// MARK: - Outline View Delegate & Data Source
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if item == nil {
return cities.count
}
switch item {
case is TimeOfDay:
let timeOfDay = item as! TimeOfDay
return timeOfDay.videos.count
case is City:
let city = item as! City
var count = 0
if !city.night.videos.isEmpty {
count += 1
}
if !city.day.videos.isEmpty {
count += 1
}
return count
//let city = item as! City
//return city.day.videos.count + city.night.videos.count
default:
return 0
}
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
switch item {
case is TimeOfDay:
return true
case is City:
return true
default:
return false
}
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if item == nil {
return cities[index]
}
switch item {
case is City:
let city = item as! City
if index == 0 && !city.day.videos.isEmpty {
return city.day
} else {
return city.night
}
//let city = item as! City
//return city.videos[index]
case is TimeOfDay:
let timeOfDay = item as! TimeOfDay
return timeOfDay.videos[index]
default:
return false
}
}
func outlineView(_ outlineView: NSOutlineView,
objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? {
switch item {
case is City:
let city = item as! City
return city.name
case is TimeOfDay:
let timeOfDay = item as! TimeOfDay
return timeOfDay.title
default:
return "untitled"
}
}
func outlineView(_ outlineView: NSOutlineView, shouldEdit tableColumn: NSTableColumn?, item: Any) -> Bool {
return false
}
func outlineView(_ outlineView: NSOutlineView, dataCellFor tableColumn: NSTableColumn?, item: Any) -> NSCell? {
let row = outlineView.row(forItem: item)
return tableColumn!.dataCell(forRow: row) as? NSCell
}
func outlineView(_ outlineView: NSOutlineView, isGroupItem item: Any) -> Bool {
switch item {
case is TimeOfDay:
return true
case is City:
return true
default:
return false
}
}
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
switch item {
case is City:
let city = item as! City
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "HeaderCell"),
owner: nil) as! NSTableCellView // if owner = self, awakeFromNib will be called for each created cell !
view.textField?.stringValue = city.name
return view
case is TimeOfDay:
let timeOfDay = item as! TimeOfDay
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "DataCell"),
owner: nil) as! NSTableCellView // if owner = self, awakeFromNib will be called for each created cell !
view.textField?.stringValue = timeOfDay.title.capitalized
let bundle = Bundle(for: PreferencesWindowController.self)
// Use -dark icons in macOS 10.14+ Dark Mode
let timeManagement = TimeManagement.sharedInstance
var postfix = ""
if timeManagement.isDarkModeEnabled() {
postfix = "-dark"
}
if let imagePath = bundle.path(forResource: "icon-\(timeOfDay.title)"+postfix,
ofType: "pdf") {
let image = NSImage(contentsOfFile: imagePath)
image!.size.width = 13
image!.size.height = 13
view.imageView?.image = image
// TODO, change the icons for dark mode
} else {
errorLog("\(#file) failed to find time of day icon")
}
return view
case is AerialVideo:
let video = item as! AerialVideo
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "CheckCell"),
owner: nil) as! CheckCellView // if owner = self, awakeFromNib will be called for each created cell !
// Mark the new view for this video for subsequent callbacks
let videoManager = VideoManager.sharedInstance
videoManager.addCheckCellView(id: video.id, checkCellView: view)
view.setVideo(video: video) // For our Add button
view.adaptIndicators()
if video.secondaryName != "" {
view.textField?.stringValue = video.secondaryName
} else {
// One based index
let number = video.arrayPosition + 1
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.spellOut
guard
let numberString = numberFormatter.string(from: number as NSNumber)
else {
errorLog("outlineView: failed to create number with formatter")
return nil
}
view.textField?.stringValue = numberString.capitalized
}
let isInRotation = preferences.videoIsInRotation(videoID: video.id)
if isInRotation {
view.checkButton.state = NSControl.StateValue.on
} else {
view.checkButton.state = NSControl.StateValue.off
}
view.onCheck = { checked in
self.preferences.setVideo(videoID: video.id,
inRotation: checked)
}
return view
default:
return nil
}
}
func outlineView(_ outlineView: NSOutlineView, shouldSelectItem item: Any) -> Bool {
switch item {
case is AerialVideo:
player = AVPlayer()
playerView.player = player
let video = item as! AerialVideo
debugLog("Playing this preview \(video)")
// Workaround for cached videos generating online traffic
if video.isAvailableOffline {
previewDisabledTextfield.isHidden = true
let localurl = URL(fileURLWithPath: VideoCache.cachePath(forVideo: video)!)
let localitem = AVPlayerItem(url: localurl)
player.replaceCurrentItem(with: localitem)
player.play()
} else if !preferences.neverStreamPreviews {
previewDisabledTextfield.isHidden = true
let asset = cachedOrCachingAsset(video.url)
let item = AVPlayerItem(asset: asset)
player.replaceCurrentItem(with: item)
player.play()
} else {
previewDisabledTextfield.isHidden = false
}
return true
case is TimeOfDay:
return false
default:
return false
}
}
func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
switch item {
case is AerialVideo:
return 19
case is TimeOfDay:
return 18
case is City:
return 17
default:
fatalError("unhandled item in heightOfRowByItem for \(item)")
}
}
func outlineView(_ outlineView: NSOutlineView, sizeToFitWidthOfColumn column: Int) -> CGFloat {
return 0
}
// MARK: - Caching
/*
var currentVideoDownload: VideoDownload?
var manifestVideos: [AerialVideo]?
@IBAction func cacheAllNow(_ button: NSButton) {
cacheStatusLabel.stringValue = "Loading JSON"
currentProgress.maxValue = 1
ManifestLoader.instance.addCallback { (manifestVideos: [AerialVideo]) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
self.manifestVideos = manifestVideos
self.cacheNextVideo()
})
}
}
func cacheNextVideo() {
guard let manifestVideos = self.manifestVideos else {
cacheStatusLabel.stringValue = "Couldn't load manifest!"
return
}
let uncached = manifestVideos.filter { (video) -> Bool in
return video.isAvailableOffline == false
}
debugLog("uncached: \(uncached)")
totalProgress.maxValue = Double(manifestVideos.count)
totalProgress.doubleValue = Double(manifestVideos.count) - Double(uncached.count)
debugLog("total process max value: \(totalProgress.maxValue), current value: \(totalProgress.doubleValue)")
if uncached.count == 0 {
cacheStatusLabel.stringValue = "All videos have been cached"
return
}
let video = uncached[0]
// find video that hasn't been cached
let videoDownload = VideoDownload(video: video, delegate: self)
cacheStatusLabel.stringValue = "Caching video \(video.name) \(video.timeOfDay.capitalized): \(video.url)"
currentVideoDownload = videoDownload
videoDownload.startDownload()
}
// MARK: - Video Download Delegate
func videoDownload(_ videoDownload: VideoDownload,
finished success: Bool, errorMessage: String?) {
if let message = errorMessage {
cacheStatusLabel.stringValue = message
} else {
cacheNextVideo()
}
preferences.synchronize()
outlineView.reloadData()
debugLog("video download finished with success: \(success))")
}
func videoDownload(_ videoDownload: VideoDownload, receivedBytes: Int, progress: Float) {
currentProgress.doubleValue = Double(progress)
}*/
}
// MARK: - Core Location Delegates
extension PreferencesWindowController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
debugLog("LM Coordinates")
let currentLocation = locations[locations.count - 1]
pushCoordinates(currentLocation.coordinate)
locationManager!.stopUpdatingLocation() // We only want them once
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
debugLog("LMauth status change : \(status.rawValue)")
}
/*func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
errorLog("Location Manager error : \(error)")
}*/
}
// MARK: - Font Panel Delegates
extension PreferencesWindowController: NSFontChanging {
func validModesForFontPanel(_ fontPanel: NSFontPanel) -> NSFontPanel.ModeMask {
return [.size, .collection, .face]
}
func changeFont(_ sender: NSFontManager?) {
// Set current font
var oldFont = NSFont(name: "Helvetica Neue Medium", size: 28)
if fontEditing == 0 {
if let tryFont = NSFont(name: preferences.fontName!, size: CGFloat(preferences.fontSize!)) {
oldFont = tryFont
}
} else {
if let tryFont = NSFont(name: preferences.extraFontName!, size: CGFloat(preferences.extraFontSize!)) {
oldFont = tryFont
}
}
let newFont = sender?.convert(oldFont!)
if fontEditing == 0 {
preferences.fontName = newFont?.fontName
preferences.fontSize = Double((newFont?.pointSize)!)
// Update our label
currentFontLabel.stringValue = preferences.fontName! + ", \(preferences.fontSize!) pt"
} else {
preferences.extraFontName = newFont?.fontName
preferences.extraFontSize = Double((newFont?.pointSize)!)
// Update our label
extraMessageFontLabel.stringValue = preferences.extraFontName! + ", \(preferences.extraFontSize!) pt"
}
preferences.synchronize()
}
}
// MARK: - Log TableView Delegates
extension PreferencesWindowController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return errorMessages.count
}
}
extension PreferencesWindowController: NSTableViewDelegate {
fileprivate enum CellIdentifiers {
static let DateCell = "DateCellID"
static let MessageCell = "MessageCellID"
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
var image: NSImage?
var text: String = ""
var cellIdentifier: String = ""
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .medium
let item = errorMessages[row]
if tableColumn == tableView.tableColumns[0] {
text = dateFormatter.string(from: item.date)
cellIdentifier = CellIdentifiers.DateCell
} else if tableColumn == tableView.tableColumns[1] {
switch item.level {
case ErrorLevel.info:
image = NSImage.init(named: NSImage.infoName)
case ErrorLevel.warning:
image = NSImage.init(named: NSImage.cautionName)
case ErrorLevel.error:
image = NSImage.init(named: NSImage.stopProgressFreestandingTemplateName)
default:
image = NSImage.init(named: NSImage.actionTemplateName)
}
//image =
text = item.message
cellIdentifier = CellIdentifiers.MessageCell
}
if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? NSTableCellView {
cell.textField?.stringValue = text
cell.imageView?.image = image ?? nil
return cell
}
return nil
}
} // swiftlint:disable:this file_length
| 37.188039 | 147 | 0.636183 |
ddbb24ccbfebeac7f2946cb134232a29b2f632c3 | 142 | import SwiftUI
@main
struct HitMeApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 10.923077 | 26 | 0.507042 |
e450f24b15b26729784b6516c02270231755c2c5 | 5,024 | //
// SearchController.swift
// MVC
//
// Created by DongHeeKang on 07/12/2018.
// Copyright © 2018 k-lpmg. All rights reserved.
//
import SafariServices
import UIKit
final class SearchViewController: UIViewController {
// MARK: - Constants
enum Const {
static let cellReuseId = "cellId"
}
// MARK: - Properties
private var searchText: String = ""
private var repositories: [RepositoryModel] = [] {
didSet {
tableView.reloadData()
}
}
private var numberOfRepositories: Int {
return repositories.count
}
// MARK: - UI Components
private let searchBar: UISearchBar = {
let searchBar = UISearchBar()
searchBar.translatesAutoresizingMaskIntoConstraints = false
return searchBar
}()
private let tableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = UITableView.automaticDimension
tableView.register(RepositoryTableViewCell.self, forCellReuseIdentifier: Const.cellReuseId)
return tableView
}()
private var searchTimer: Timer?
// MARK: - Overridden: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
setProperties()
view.addSubview(searchBar)
view.addSubview(tableView)
layout()
}
// MARK: - Private methods
private func setProperties() {
title = "MVC"
view.backgroundColor = .white
searchBar.delegate = self
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
}
private func startSearchTimer() {
searchTimer = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(searchTimerCompleted), userInfo: nil, repeats: false)
}
private func removeSearchTimer() {
searchTimer?.invalidate()
searchTimer = nil
}
private func requestRepositories(searchText: String) {
GitHubService().searchRepositories(query: searchText) { (result) in
switch result {
case .value(let value):
self.repositories = value.items
case .error(_):
self.repositories = []
}
}
}
// MARK: - Private selector
@objc private func searchTimerCompleted() {
requestRepositories(searchText: searchText)
}
}
// MARK: - Layout
extension SearchViewController {
private func layout() {
searchBar.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
searchBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
searchBar.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: searchBar.bottomAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
}
// MARK: - UISearchBarDelegate
extension SearchViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
removeSearchTimer()
startSearchTimer()
self.searchText = searchText
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
guard let text = searchBar.text else {return}
removeSearchTimer()
self.searchText = text
searchTimerCompleted()
}
}
// MARK: - UITableViewDataSource
extension SearchViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfRepositories
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Const.cellReuseId, for: indexPath) as! RepositoryTableViewCell
cell.configure(with: repositories[indexPath.row])
return cell
}
}
// MARK: - UITableViewDelegate
extension SearchViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
guard let url = URL(string: repositories[indexPath.row].html_url) else {return}
let controller = SFSafariViewController(url: url)
present(controller, animated: true, completion: nil)
}
}
| 29.727811 | 149 | 0.662818 |
ffe4656644250c0d68e2981dc51397d1b182906b | 2,321 | //
// DBConnected.swift
// Application
//
// Created by Szili Péter on 2018. 10. 13..
//
import Foundation
import Kitura
import SwiftKuery
import SwiftKueryORM
import SwiftKueryMySQL
struct DBConversationModel: Model {
static var tableName = "Conversation"
static var idKeypath = \DBConversationModel.id
var id: Int?
var user1: String
var user2: String
var approved: Int
enum CodingKeys: String, CodingKey {
case id = "conversation_id"
case user1 = "user_1"
case user2 = "user_2"
case approved = "approved"
}
}
extension DBConversationModel {
private struct ConversationFilter: QueryParams {
let user_1: String?
let user_2: String?
let approved: Int?
}
public static func getConversations(forEmail userEmail: String, otherEmail: String? = nil, approved: Int? = nil) -> [DBConversationModel]? {
let wait = DispatchSemaphore(value: 0)
var conversations: [DBConversationModel]?
let filter1 = ConversationFilter(user_1: otherEmail, user_2: userEmail, approved: approved)
let filter2 = ConversationFilter(user_1: userEmail, user_2: otherEmail, approved: approved)
DBConversationModel.findAll(matching: filter1) { results, error in
if let error = error {
print(error)
conversations = []
} else if let results = results {
conversations = results
}
wait.signal()
}
wait.wait()
DBConversationModel.findAll(matching: filter2) { results, error in
if let error = error {
print(error)
} else if let results = results {
conversations?.append(contentsOf: results)
}
wait.signal()
}
wait.wait()
return conversations
}
public static func getUnapprovedConversation(conversationId: Int, email: String) -> DBConversationModel? {
var unapprovedConversation: DBConversationModel?
let dbConversations = getConversations(forEmail: email, approved: 0)
unapprovedConversation = dbConversations?.first(where: { $0.id == conversationId })
return unapprovedConversation
}
public static func getFriendCount(for user: String) -> Int {
var friendCount = 0
if let conversations = DBConversationModel.getConversations(forEmail: user, approved: 1) {
friendCount += conversations.count
}
return friendCount
}
}
| 27.963855 | 142 | 0.696252 |
f5ceff16477930a32c38e5904ee22a42abb33103 | 2,865 | import KituraContracts
func initINodeRoutes(app: Application) {
app.router.get("/inode") { _, response, next in
let data = try INode.getAll();
print(data)
try response.send(data).end()
}
app.router.get("/inode/:id") { request, response, next in
guard let idString = request.parameters["id"],
let id = Int64(idString),
id >= 0
else {
let _ = response.send(status: .badRequest)
return next()
}
let data = try INode.getFromId(id: id);
print(data)
try response.send(data).end()
next()
}
app.router.get("/inode/id/:id") { request, response, next in
guard let idString = request.parameters["id"],
let id = Int64(idString),
id >= 0
else {
let _ = response.send(status: .badRequest)
return next()
}
let data = try INode.getFromId(id: id);
print(data)
try response.send(data).end()
next()
}
app.router.get("/inode/name/:name") { request, response, next in
guard let name = request.parameters["name"]
else {
let _ = response.send(status: .badRequest)
return next()
}
let data = try INode.getFromName(name: name);
print(data)
try response.send(data).end()
next()
}
app.router.get("/inode/ownerId/:ownerId") { request, response, next in
guard let ownerIdString = request.parameters["ownerId"],
let ownerId = Int64(ownerIdString),
ownerId >= 0
else {
let _ = response.send(status: .badRequest)
return next()
}
let data = try INode.getFromOwnerId(id: ownerId);
print(data)
try response.send(data).end()
next()
}
app.router.get("/inode/parentId/:parentId") { request, response, next in
guard let parentIdString = request.parameters["parentId"],
let parentId = Int64(parentIdString),
parentId >= 0
else {
let _ = response.send(status: .badRequest)
return next()
}
let data = try INode.getFromParentId(id: parentId);
print(data)
try response.send(data).end()
next()
}
app.router.post("/inode") { request, response, next in
do {
let inode = try request.read(as: INode.self)
print(inode)
try inode.insert()
response.send(inode)
} catch {
let _ = response.send(status: .badRequest)
}
next()
}
app.router.delete("/inode/:id") { request, response, next in
}
app.router.delete("/inode/id/:id") { request, response, next in
}
} | 28.65 | 76 | 0.523909 |
dd4908c56b583d06ea5b04ed725079e444b9fe83 | 1,061 | //
// HeroController.swift
// Hero and alter egos
//
// Created by Andrew Saeyang on 7/25/21.
//
import UIKit
class HeroController{
static let shared = HeroController()
var heros = [Hero(heroName: "Captain America", alterEgo: "Steve Rogers", heroImage: UIImage(named: "captain"), alterEgoImage: UIImage(named: "steve")),
Hero(heroName: "Iron Man", alterEgo: "Tony Stark", heroImage: UIImage(named: "ironman"), alterEgoImage: UIImage(named: "tony")),
Hero(heroName: "Thor", alterEgo: "Thor", heroImage:UIImage(named: "thor"), alterEgoImage:UIImage(named: "thor2")),
Hero(heroName: "Hulk", alterEgo: "Bruce Banner", heroImage:UIImage(named: "hulk"), alterEgoImage:UIImage(named: "bruce"))]
func getHeroImage(hero: Hero) -> UIImage{
return hero.isHeroForm ? hero.heroImage! : hero.alterEgoImage!
}
func toggleHeroForm(){
heros.forEach { hero in
hero.isHeroForm.toggle()
}
}
} // End of class
| 34.225806 | 156 | 0.609802 |
46313f1afa0e48a51f35b0551ab396d6dc6dbc92 | 1,376 | //
// VideoType.swift
// ThreeSixtyPlayer
//
// Created by Alfred Hanssen on 10/6/16.
// Copyright © 2016 Alfie Hanssen. 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 CoreGraphics
public enum VideoType
{
case monoscopic
case stereoscopic(layout: StereoscopicLayout)
}
| 38.222222 | 81 | 0.751453 |
506f60417b4238566b749fdc5ad94a8ff0ce2bbb | 533 | //
// ViewController.swift
// publicSDKTest
//
// Created by [email protected] on 05/25/2021.
// Copyright (c) 2021 [email protected]. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 21.32 | 80 | 0.681051 |
015b01628f31ba1f73af4161f75d3d4fc3e37994 | 2,162 | //
// AppDelegate.swift
// UICatalog
//
// Created by Massimiliano Bigatti on 22/06/15.
// Copyright © 2015 Massimiliano Bigatti. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46 | 285 | 0.755782 |
d7be154323aede411df2685d2f3f1f8644beea2b | 1,931 | import Foundation
import CommonWallet
import SoraFoundation
import RobinHood
import CoreData
final class TransferConfirmCommandProxy: WalletCommandDecoratorProtocol {
private var commandFactory: WalletCommandFactoryProtocol
private var storage: AnyDataProviderRepository<PhishingItem>
private var locale: Locale
var calleeCommand: WalletCommandDecoratorProtocol & WalletCommandDecoratorDelegateProtocol
var undelyingCommand: WalletCommandProtocol? {
get { calleeCommand.undelyingCommand }
set { calleeCommand.undelyingCommand = newValue }
}
let logger = Logger.shared
init(
payload: ConfirmationPayload,
localizationManager: LocalizationManagerProtocol,
commandFactory: WalletCommandFactoryProtocol,
storage: AnyDataProviderRepository<PhishingItem>
) {
locale = localizationManager.selectedLocale
self.storage = storage
self.commandFactory = commandFactory
calleeCommand = TransferConfirmCommand(
payload: payload,
localizationManager: localizationManager,
commandFactory: commandFactory
)
}
func execute() throws {
let nextAction = {
try? self.calleeCommand.execute()
return
}
let cancelAction = {
let hideCommand = self.commandFactory.prepareHideCommand(with: .pop)
try? hideCommand.execute()
}
let phishingCheckExecutor =
PhishingCheckExecutor(
commandFactory: commandFactory,
storage: storage,
nextAction: nextAction,
cancelAction: cancelAction,
locale: locale,
publicKey: calleeCommand.payload.transferInfo.destination,
walletAddress: calleeCommand.payload.receiverName
)
try? phishingCheckExecutor.execute()
}
}
| 31.145161 | 94 | 0.667012 |
8ab849f504a543279739e2b44fe653d1f7873ee9 | 1,232 | // Generated using SwiftGen, by O.Halligon — https://github.com/SwiftGen/SwiftGen
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// swiftlint:disable explicit_type_interface function_parameter_count identifier_name line_length
// swiftlint:disable nesting type_body_length type_name
public enum L10n {
/// About
public static let about = L10n.tr("Localizable", "about")
/// Home
public static let home = L10n.tr("Localizable", "home")
/// Used libraries
public static let libraries = L10n.tr("Localizable", "libraries")
/// Settings
public static let settings = L10n.tr("Localizable", "settings")
{ADDITIONAL_TAB_STRINGS_WITHOUT_SWIFTGEN}
}
// swiftlint:enable explicit_type_interface function_parameter_count identifier_name line_length
// swiftlint:enable nesting type_body_length type_name
extension L10n {
private static func tr(_ table: String, _ key: String, _ args: CVarArg...) -> String {
let format = NSLocalizedString(key, tableName: table, bundle: Bundle(for: BundleToken.self), comment: "")
return String(format: format, locale: Locale.current, arguments: args)
}
}
private final class BundleToken {}
| 37.333333 | 113 | 0.746753 |
189db272661defb0bdd7b7e61fa62ff2dc024f36 | 5,382 | //
// CNLTimerView.swift
// CNLUIKitTools
//
// Created by Igor Smirnov on 25/11/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import UIKit
import CNLFoundationTools
/// UIView with circular progress bar and label with time
open class CNLTimerView: UIView {
// visual elements
/// UILabel with time text
open var timeLabel: UILabel!
/// Initial text (before timer)
open var timeLabelInitialText: String? = "Initial"
/// Final text (after timer)
open var timeLabelFinalText: String? = "Finished"
// circle sub-layer
/// CAShapeLayer with circular progress bar
open var progressLayer = CAShapeLayer()
/// progressLayer transform (default is rotation on -pi/2.0)
open var progressLayerTransform = CATransform3DMakeRotation(CGFloat(-Double.pi / 2.0), 0.0, 0.0, 1.0)
// time values
/// Timer interval
open var timerInterval: TimeInterval = 0.1
/// Timer start date
open var timerStartDate: Date!
/// Direction of the progress indicator (false - clockwise, true - counterclockwise)
open var backward: Bool = false
/// Fill color of the progress indicator
open var fillColor = UIColor.clear {
didSet {
progressLayer.fillColor = fillColor.cgColor
}
}
/// Stroke color of the progress indicator
open var strokeColor = UIColor.blue {
didSet {
progressLayer.strokeColor = strokeColor.cgColor
}
}
/// Closure with formatting text for progress label (default - number of seconds)
open var timeLabelText: ((_ timerView: CNLTimerView, _ time: TimeInterval) -> String)?
/// Line width of the progress indicator
open var lineWidth: CGFloat = 4.0 {
didSet {
progressLayer.lineWidth = lineWidth
setNeedsLayout()
}
}
/// Current progress (will animate changes)
open var progress: CGFloat {
get { return progressLayer.strokeEnd }
set {
if newValue >= 1.0 {
progressLayer.strokeEnd = 1.0
} else if newValue <= 0.0 {
progressLayer.strokeEnd = 0.0
} else {
if backward {
progressLayer.strokeEnd = 1.0 - newValue
} else {
progressLayer.strokeEnd = newValue
}
}
}
}
// Private variables
private var completion: (() -> Void)?
private var timer: Timer?
private var timerDuration: TimeInterval = 0.0
/// Starts timer, calls completion closure when finished
///
/// - Parameters:
/// - duration: Duration in seconds
/// - completion: Completion closure
open func startTimer(duration: TimeInterval, completion: (() -> Void)? = nil) {
self.completion = completion
timerDuration = duration
timerStartDate = Date()
timer = Timer.scheduledTimer(timeInterval: timerInterval, target: self, selector: #selector(timerFired(timer:)), userInfo: nil, repeats: true)
updateProgress()
}
open func stopTimer() {
timer?.invalidate()
timer = nil
}
/// Updates current progress
open func updateProgress() {
let timePassed = -timerStartDate.timeIntervalSinceNow
if timePassed > timerDuration {
timeLabel.text = timeLabelFinalText
timer?.invalidate()
self.timer = nil
progress = backward ? 0.0 : 1.0
completion?()
} else {
progress = CGFloat(timePassed) / CGFloat(timerDuration)
if let text = timeLabelText?(self, timePassed) {
timeLabel.text = text
} else {
if backward {
timeLabel.text = "\(Int(floor(timerDuration - timePassed)) + 1)"
} else {
timeLabel.text = "\(Int(floor(timePassed)) + 1)"
}
}
}
}
/// Timer function
///
/// - Parameter timer: Source timer
@objc open func timerFired(timer: Timer) {
updateProgress()
}
open override func layoutSubviews() {
super.layoutSubviews()
timeLabel.frame = bounds
progressLayer.frame = bounds
progressLayer.transform = progressLayerTransform
let path = UIBezierPath(ovalIn: bounds.insetBy(dx: lineWidth / 2.0, dy: lineWidth / 2.0))
progressLayer.path = path.cgPath
}
/// Creates objects for the view (label, progress layer)
open func createObjects() {
timeLabel = UILabel() --> {
$0.textAlignment = .center
$0.text = timeLabelInitialText
self.addSubview($0)
return $0
}
progressLayer --> {
$0.lineWidth = lineWidth
$0.bounds = bounds
$0.fillColor = fillColor.cgColor
$0.strokeColor = strokeColor.cgColor
$0.lineCap = kCALineCapRound
self.layer.addSublayer($0)
}
}
override public required init(frame: CGRect) {
super.init(frame: frame)
createObjects()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
createObjects()
}
}
| 30.579545 | 150 | 0.576366 |
f8574e88ac196175636957dd0f70c4501b63e9bf | 17,079 | //
// PackageMenuAction.swift
// Chromatic
//
// Created by Lakr Aream on 2021/8/24.
// Copyright © 2021 Lakr Aream. All rights reserved.
//
import AptRepository
import SPIndicator
import UIKit
class PackageMenuAction {
enum ActionDescriptor: String, CaseIterable {
case directInstall
case install
case reinstall
case downgrade
case update
case remove
case cancelQueue
case versionControl
func describe() -> String {
switch self {
case .directInstall:
return NSLocalizedString("DIRECT_INSTALL", comment: "Direct Install")
case .install:
return NSLocalizedString("INSTALL", comment: "Install")
case .reinstall:
return NSLocalizedString("REINSTALL", comment: "Reinstall")
case .downgrade:
return NSLocalizedString("DOWNGRADE", comment: "Downgrade")
case .update:
return NSLocalizedString("UPDATE", comment: "Update")
case .remove:
return NSLocalizedString("REMOVE", comment: "Remove")
case .cancelQueue:
return NSLocalizedString("CANCEL_QUEUE", comment: "Cancel Queue")
case .versionControl:
return NSLocalizedString("VERSION_CONTROL", comment: "Version Control")
}
}
}
struct MenuAction {
let descriptor: ActionDescriptor
let block: (Package, UIView) -> Void
let elegantForPerform: (Package) -> (Bool)
}
// MARK: - ACTIONS
// MARK: - INSTALL KIND
static let resolveInstallRequest = { (package: Package, view: UIView) in
if let version = package.latestVersion,
let trimmedPackage = PackageCenter
.default
.trim(package: package, toVersion: version),
let action = TaskManager.PackageAction(action: .install,
represent: trimmedPackage,
isUserRequired: true)
{
// MARK: - DIRECT INSTALL
if package.latestMetadata?[DirectInstallInjectedPackageLocationKey] != nil {
let result = TaskManager
.shared
.startPackageResolution(action: action)
resolveAction(result: result, view: view)
return
}
// MARK: - PAID
if let tag = package.latestMetadata?["tag"],
tag.contains("cydia::commercial")
{
// MARK: - GET ACCOUNT
if !DeviceInfo.current.useRealDeviceInfo {
let alert = UIAlertController(title: NSLocalizedString("ERROR", comment: "Error"),
message: NSLocalizedString("CANNOT_SIGNIN_PAYMENT_WITHOUT_REAL_DEVICE_ID", comment: "Cannot sign in without using real device identities, check your settings."),
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("DISMISS", comment: "Dismiss"),
style: .default,
handler: nil))
view.parentViewController?.present(alert, animated: true, completion: nil)
return
}
guard let repoUrl = package.repoRef,
let repo = RepositoryCenter.default.obtainImmutableRepository(withUrl: repoUrl)
else {
let alert = UIAlertController(title: NSLocalizedString("ERROR", comment: "Error"),
message: NSLocalizedString("BROKEN_RESOURCE", comment: "Broken Resource"),
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("DISMISS", comment: "Dismiss"),
style: .default,
handler: nil))
view.parentViewController?.present(alert, animated: true, completion: nil)
return
}
guard let signin = PaymentManager.shared.obtainStoredTokenInfomation(for: repo) else {
PaymentManager.shared.startUserAuthenticate(window: view.window ?? UIWindow(),
controller: view.parentViewController,
repoUrl: repoUrl) {}
return
}
let alert = UIAlertController(title: "⏳",
message: NSLocalizedString("COMMUNICATING_WITH_VENDER",
comment: "Communicating with vender"),
preferredStyle: .alert)
view.parentViewController?.present(alert, animated: true, completion: nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
alert.dismiss(animated: true, completion: nil)
}
// MARK: - GET PACKAGE INFO
DispatchQueue.global().async {
PaymentManager.shared.obtainPackageInfo(for: repoUrl, withPackageIdentity: package.identity) { info in
DispatchQueue.main.async {
guard let info = info else { return }
debugPrint(info)
if info.purchased == true {
// MARK: - OK FOR DOWNLOAD
DispatchQueue.global().async {
let readDownload = PaymentManager
.shared
.queryDownloadLinkAndWait(withPackage: package)
DispatchQueue.main.async {
alert.dismiss(animated: true, completion: nil)
guard let download = readDownload,
let version = trimmedPackage.latestVersion,
var meta = trimmedPackage.latestMetadata
else {
return
}
meta["filename"] = download.absoluteString
let virtualPackage = Package(identity: trimmedPackage.identity,
payload: [version: meta],
repoRef: repoUrl)
guard let newAction = TaskManager.PackageAction(action: .install,
represent: virtualPackage,
isUserRequired: true)
else {
return
}
let result = TaskManager
.shared
.startPackageResolution(action: newAction)
resolveAction(result: result, view: view)
}
}
} else if info.available ?? false {
// MARK: - NEED BUY
let window = view.window ?? UIWindow()
alert.dismiss(animated: true, completion: nil)
DispatchQueue.global().async {
_ = PaymentManager
.shared
.initPurchaseAndWait(for: repoUrl,
withPackageIdentity: package.identity,
window: window)
}
} else {
// MARK: - NOT AVAILABLE
alert.dismiss(animated: true) {
let alert = UIAlertController(title: NSLocalizedString("ERROR", comment: "Error"),
message: NSLocalizedString("VERNDER_PACKAGE_NOT_AVAILABLE", comment: "Package not available, contact vender for support"),
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("DISMISS", comment: "Dismiss"),
style: .default,
handler: nil))
view.parentViewController?.present(alert, animated: true, completion: nil)
}
}
}
}
}
return
}
// MARK: - DO
let result = TaskManager
.shared
.startPackageResolution(action: action)
resolveAction(result: result, view: view)
}
}
static let allMenuActions: [MenuAction] = [
// MARK: - DIRECT INSTALL
.init(descriptor: .directInstall,
block: resolveInstallRequest,
elegantForPerform: { package in
if package.latestMetadata?[DirectInstallInjectedPackageLocationKey] != nil {
return true
}
return false
}),
// MARK: - INSTALL
.init(descriptor: .install,
block: resolveInstallRequest,
elegantForPerform: { package in
if TaskManager
.shared
.isQueueContains(package: package.identity)
{
return false
}
if package.latestMetadata?[DirectInstallInjectedPackageLocationKey] != nil {
return false
}
if package.obtainDownloadLink() == PackageBadUrl {
return false
}
return PackageCenter
.default
.obtainPackageInstallationInfo(with: package.identity)
== nil
}),
// MARK: - UPDATE
.init(descriptor: .update,
block: resolveInstallRequest,
elegantForPerform: { package in
if TaskManager.shared.isQueueContains(package: package.identity) { return false }
if package.obtainDownloadLink() == PackageBadUrl {
return false
}
if package.latestMetadata?[DirectInstallInjectedPackageLocationKey] != nil {
return false
}
if let info = PackageCenter
.default
.obtainPackageInstallationInfo(with: package.identity),
PackageCenter
.default
.obtainUpdateForPackage(with: package.identity,
version: info.version)
.count > 0
{
if let info = PackageCenter
.default
.obtainPackageInstallationInfo(with: package.identity),
let current = package.latestVersion
{
if Package.compareVersion(current, b: info.version)
== .aIsSmallerThenB
{
return false
}
}
return true
}
return false
}),
// MARK: - REINSTALL
.init(descriptor: .reinstall,
block: resolveInstallRequest,
elegantForPerform: { package in
if package.obtainDownloadLink() == PackageBadUrl {
return false
}
if package.latestMetadata?[DirectInstallInjectedPackageLocationKey] != nil {
return false
}
if TaskManager.shared.isQueueContains(package: package.identity) { return false }
let info = PackageCenter
.default
.obtainPackageInstallationInfo(with: package.identity)
return info?.version == package.latestVersion && info?.version != nil
}),
// MARK: - DOWNGRADE
.init(descriptor: .downgrade,
block: resolveInstallRequest,
elegantForPerform: { package in
if TaskManager.shared.isQueueContains(package: package.identity) { return false }
if package.obtainDownloadLink() == PackageBadUrl {
return false
}
if package.latestMetadata?[DirectInstallInjectedPackageLocationKey] != nil {
return false
}
let _info = PackageCenter
.default
.obtainPackageInstallationInfo(with: package.identity)
guard let info = _info, let current = package.latestVersion else { return false }
return Package.compareVersion(current, b: info.version) == .aIsSmallerThenB
}),
// MARK: - REMOVE
.init(descriptor: .remove,
block: { package, view in
if let action = TaskManager.PackageAction(action: .remove,
represent: package,
isUserRequired: true)
{
let result = TaskManager
.shared
.startPackageResolution(action: action)
resolveAction(result: result, view: view)
}
},
elegantForPerform: { package in
if TaskManager.shared.isQueueContains(package: package.identity) { return false }
return PackageCenter
.default
.obtainPackageInstallationInfo(with: package.identity)
!= nil
}),
// MARK: - CANCEL QUEUE
.init(descriptor: .cancelQueue,
block: { package, view in
let result = TaskManager
.shared
.cancelActionWithPackage(identity: package.identity)
resolveAction(result: result, view: view)
},
elegantForPerform: {
TaskManager.shared.isQueueContainsUserRequest(package: $0.identity)
}),
// MARK: - VERSION CONTROL
.init(descriptor: .versionControl,
block: { package, view in
let target = PackageVersionControlController()
target.currentPackage = package
view.parentViewController?.present(next: target)
},
elegantForPerform: { _ in true }),
]
// MARK: ACTIONS -
static func presentPackageActionError(view: UIView) {
let target = PackageDiagnosticController()
view.parentViewController?.present(next: target)
}
static func resolveAction(result: TaskManager.PackageResolutionResult, view: UIView) {
switch result {
case .success:
let text = NSLocalizedString("SUCCESSFULLY_QUEUED", comment: "Successfully Queued")
SPIndicator.present(title: text,
preset: .done)
case .breaksOther, .missingRequired:
presentPackageActionError(view: view)
case .brokenResource, .removeErrorTooManyDependency, .unknownError:
SPIndicator.present(title: NSLocalizedString("UNKNOWN_ERROR_OCCURRED", comment: "Unknown Error Occurred"),
preset: .error)
}
}
}
| 45.422872 | 211 | 0.453598 |
211973f2a7ee16580733dfcdc5244b14510bf2d8 | 1,166 | //
// View.StandardNavigationTitle.swift
// VCore
//
// Created by Vakhtang Kontridze on 9/21/21.
//
#if os(iOS)
import SwiftUI
// MARK: - Extension
extension View {
/// Configures the view’s title for purposes of navigation, using a `String` in a inline display mode.
///
/// var body: some View {
/// Text("Lorem Ipsum")
/// .standardNavigationTitle("Home")
/// }
///
public func standardNavigationTitle(_ title: String) -> some View {
self
.modifier(StandardNavigationTitle(title))
}
}
// MARK: - Standard Navigation Title View Modifier
private struct StandardNavigationTitle: ViewModifier {
// MARK: Properties
private let title: String
// MARK: Initializers
init(_ title: String) {
self.title = title
}
// MARK: Body
func body(content: Content) -> some View {
if #available(iOS 14.0, *) {
content
.navigationTitle(title)
.navigationBarTitleDisplayMode(.inline)
} else {
content
.navigationBarTitle(title)
}
}
}
#endif
| 22.423077 | 106 | 0.572041 |
d6ac0f7f8cd864059945683d5f9f301b5fa45be3 | 1,576 | //
// MovieTableViewCell.swift
// MovieDataBase
//
// Created by Judar Lima on 20/07/19.
// Copyright © 2019 Judar Lima. All rights reserved.
//
import UIKit
class MovieTableViewCell: UITableViewCell {
@IBOutlet private weak var containerView: UIView!
@IBOutlet private weak var movieImageView: UIImageView!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var genreLabel: UILabel!
@IBOutlet private weak var releaseLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
override func prepareForReuse() {
self.titleLabel.text = nil
self.genreLabel.text = nil
self.releaseLabel.text = nil
self.movieImageView.image = UIImage(named: "image_placeholder")
}
private func setup() {
isAccessibilityElement = false
containerView.isAccessibilityElement = true
containerView.accessibilityTraits = .button
containerView.layer.cornerRadius = 8.0
containerView.clipsToBounds = true
}
func bind(viewModel: MovieViewModel) {
self.titleLabel.text = viewModel.title
self.genreLabel.text = viewModel.genre
self.releaseLabel.text = viewModel.releaseDate
self.movieImageView.loadImage(url: viewModel.poster)
containerView.accessibilityLabel = viewModel.accessibilityLabel
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
super.setSelected(false, animated: true)
}
}
| 29.735849 | 71 | 0.690355 |
d5473c3a8c09993d7c25e507bbcf11fef639f9a3 | 1,720 | //
// MeView.swift
// HotProspects
//
// Created by Sebastian Vidrea on 22/12/2019.
// Copyright © 2019 AppCompany. All rights reserved.
//
import SwiftUI
import CoreImage.CIFilterBuiltins
struct MeView: View {
@State private var name = "Anonymous"
@State private var emailAddress = "[email protected]"
let context = CIContext()
let filter = CIFilter.qrCodeGenerator()
var body: some View {
NavigationView {
VStack {
TextField("Name", text: $name)
.textContentType(.name)
.font(.title)
.padding(.horizontal)
TextField("Email address", text: $emailAddress)
.textContentType(.emailAddress)
.font(.title)
.padding([.horizontal, .bottom])
Image(uiImage: generateQRCode(from: "\(name)\n\(emailAddress)"))
.interpolation(.none)
.resizable()
.scaledToFit()
.frame(width: 200, height: 200)
Spacer()
}
.navigationBarTitle("Your code")
}
}
func generateQRCode(from string: String) -> UIImage {
let data = Data(string.utf8)
filter.setValue(data, forKey: "inputMessage")
if let outputImage = filter.outputImage {
if let cgimg = context.createCGImage(outputImage, from: outputImage.extent) {
return UIImage(cgImage: cgimg)
}
}
return UIImage(systemName: "xmark.circle") ?? UIImage()
}
}
struct MeView_Previews: PreviewProvider {
static var previews: some View {
MeView()
}
}
| 27.301587 | 89 | 0.545349 |
87c8b884eb28cd547c049d3cc43193ae0849425a | 18,502 | /*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import CoreBluetooth
/// The approximate mock device proximity.
public enum CBMProximity {
/// The device will have RSSI values around -40 dBm.
case near
/// The device will have RSSI values around -70 dBm.
case immediate
/// The device is far, will have RSSI values around -100 dBm.
case far
/// The device is out of range.
case outOfRange
internal var RSSI: Int {
switch self {
case .near: return -40
case .immediate: return -70
case .far: return -100
case .outOfRange: return 127
}
}
}
/// The peripheral instance specification.
public class CBMPeripheralSpec {
/// The peripheral identifier.
public internal(set) var identifier: UUID
/// The name of the peripheral usually returned by Device Name
/// characteristic.
public internal(set) var name: String?
/// How far the device is.
public internal(set) var proximity: CBMProximity
/// Should the mock peripheral appear in scan results when it's
/// connected.
public let isAdvertisingWhenConnected: Bool
/// A flag indicating that the peripheral can be obtained using
/// `CBMCentralManagerMock.retrievePeripherals(withIdentifiers:)`
/// without scanning. This is set to true whenever the peripheral
/// gets scanned, but can also be forced using `Builder.allowForRetrieval()`
/// or `simulateCached()`.
///
/// When set to true, it means the system has scanned for this device
/// previously and stored its UUID.
public internal(set) var isKnown: Bool
/// The device's advertising data.
/// Make sure to include `CBAdvertisementDataIsConnectable` if
/// the device is connectable.
public let advertisementData: [String : Any]?
/// The advertising interval.
public let advertisingInterval: TimeInterval?
/// List of services with implementation.
public internal(set) var services: [CBMServiceMock]?
/// The connection interval.
public let connectionInterval: TimeInterval?
/// The MTU (Maximum Transfer Unit). Min value is 23, max 517.
/// The maximum value length for Write Without Response is
/// MTU - 3 bytes.
public let mtu: Int?
/// The delegate that will handle connection requests.
public let connectionDelegate: CBMPeripheralSpecDelegate?
/// A flag indicating whether the device is connected.
public var isConnected: Bool {
return virtualConnections > 0
}
/// Number of virtual connections to this peripheral. A peripheral
/// may be connected using multiple central managers in one or
/// multiple apps. When this drops to 0, the device is physically
/// disconnected.
internal var virtualConnections: Int
private init(
identifier: UUID,
name: String?,
proximity: CBMProximity,
isInitiallyConnected: Bool,
isAdvertisingWhenConnected: Bool,
isKnown: Bool,
advertisementData: [String : Any]?,
advertisingInterval: TimeInterval?,
services: [CBMServiceMock]?,
connectionInterval: TimeInterval?,
mtu: Int?,
connectionDelegate: CBMPeripheralSpecDelegate?
) {
self.identifier = identifier
self.name = name
self.proximity = proximity
self.virtualConnections = isInitiallyConnected ? 1 : 0
self.isAdvertisingWhenConnected = isAdvertisingWhenConnected
self.isKnown = isKnown
self.advertisementData = advertisementData
self.advertisingInterval = advertisingInterval
self.services = services
self.connectionInterval = connectionInterval
self.mtu = mtu
self.connectionDelegate = connectionDelegate
}
/// Creates a `MockPeripheral.Builder` instance.
/// Use builder methods to customize your device and call `build()` to
/// return the `MockPeripheral` object.
/// - Parameters:
/// - identifier: The peripheral identifier. If not given, a random
/// UUID will be used.
/// - proximity: Approximate distance to the device. By default set
/// to `.immediate`.
public static func simulatePeripheral(identifier: UUID = UUID(),
proximity: CBMProximity = .immediate) -> Builder {
return Builder(identifier: identifier, proximity: proximity)
}
/// Simulates the situation when another application on the device
/// connects to the device.
///
/// If `isAdvertisingWhenConnected` flag is set to <i>false</i>, the
/// device will stop showing up on scan results.
///
/// A manager registered for connection event will receive an event.
///
/// Connected devices are be available for managers using
/// `retrieveConnectedPeripherals(withServices:)`.
///
/// - Note: The peripheral needs to be in range.
public func simulateConnection() {
guard proximity != .outOfRange else {
return
}
CBMCentralManagerMock.peripheralDidConnect(self)
}
/// Simulates a situation when the peripheral disconnection from
/// the device.
///
/// All connected mock central managers will receive
/// `peripheral(:didDisconnected:error)` callback.
/// - Parameter error: The disconnection reason. Use `CBMError` or
/// `CBMATTError` errors.
public func simulateDisconnection(withError error: Error = CBMError(.peripheralDisconnected)) {
CBMCentralManagerMock.peripheral(self, didDisconnectWithError: error)
}
/// Simulates a reset of the peripheral. The peripheral will start
/// advertising again (if advertising was enabled) immediately.
/// Connected central managers will be notified after the supervision
/// timeout is over.
public func simulateReset() {
connectionDelegate?.reset()
simulateDisconnection(withError: CBMError(.connectionTimeout))
}
/// Simulates a situation when the device changes its services.
/// Only services that were not in the previous list of services
/// will be reported as invalidated.
///
/// The device must be connectable, otherwise this method does
/// nothing.
/// - Important: In the mock implementation the order of services
/// is irrelevant. This is in contrary to the physical
/// Bluetooth LE device, where handle numbers depend
/// on order of the services in the attribute database.
/// - Parameters:
/// - newName: The new device name after change.
/// - newServices: The new services after change.
public func simulateServiceChange(newName: String?,
newServices: [CBMServiceMock]) {
guard let _ = connectionDelegate else {
return
}
CBMCentralManagerMock.peripheral(self, didUpdateName: newName,
andServices: newServices)
}
/// Simulates a situation when the peripheral was moved closer
/// or away from the phone.
///
/// If the proximity is changed to `.outOfRange`, the peripheral will
/// be disconnected and will not appear on scan results.
/// - Parameter proximity: The new peripheral proximity.
public func simulateProximityChange(_ proximity: CBMProximity) {
CBMCentralManagerMock.proximity(of: self, didChangeTo: proximity)
}
/// Simulates a notification/indication sent from the peripheral.
///
/// All central managers that have enabled notifications on it
/// will receive `peripheral(:didUpdateValueFor:error)`.
/// - Parameters:
/// - data: The notification/indication data.
/// - characteristic: The characteristic from which a
/// notification or indication is to be sent.
public func simulateValueUpdate(_ data: Data,
for characteristic: CBMCharacteristicMock) {
guard let services = services,
services.contains(where: {
$0.characteristics?.contains(characteristic) ?? false
}) else {
return
}
characteristic.value = data
CBMCentralManagerMock.peripheral(self, didUpdateValueFor: characteristic)
}
/// Simulates a situation when the iDevice scans for Bluetooth LE devices
/// and caches scanned results. Scanned devices become available for retrieval
/// using `CBMCentralManager.retrievePeripherals(withIdentifiers:)`.
///
/// When scanning is performed by a mock central manager, and the device is
/// in range, this gets called automatically.
public func simulateCaching() {
isKnown = true
}
/// Simulates a change of the devuice's MAC address.
///
/// MAC addresses are not available through iOS API. Each MAC gets
/// assigned a UUID by which the device can be identified and retrieved
/// after it has been scanned and cached.
///
/// If a device is connected, this will not cause disconnection.
/// - Parameter newIdentifier: The new peripheral identifier.
public func simulateMacChange(_ newIdentifier: UUID = UUID()) {
isKnown = false
identifier = newIdentifier
}
public class Builder {
/// The peripheral identifier.
private var identifier: UUID
/// The name of the peripheral cached during previous session.
/// This may be <i>nil<i/> to simulate a newly discovered devices.
private var name: String?
/// How far the device is.
private var proximity: CBMProximity
/// The device's advertising data.
/// Make sure to include `CBAdvertisementDataIsConnectable` with
/// value <i>true</i> if the device is connectable.
private var advertisementData: [String : Any]? = nil
/// The advertising interval, in seconds.
private var advertisingInterval: TimeInterval? = 0.100
/// Should the mock peripheral appear in scan results when it's
/// connected.
private var isAdvertisingWhenConnected: Bool = false
/// A flag indicating whether the device is initially connected
/// to the central (using some other application).
private var isInitiallyConnected: Bool = false
/// A flag indicating that the peripheral can be obtained using
/// `CBMCentralManagerMock.retrievePeripherals(withIdentifiers:)`
/// without scanning.
///
/// When set to true, it means the system has scanned for this device
/// previously and stored its UUID.
private var isKnown: Bool = false
/// List of services with implementation.
private var services: [CBMServiceMock]? = nil
/// The connection interval, in seconds.
private var connectionInterval: TimeInterval? = nil
/// The MTU (Maximul Transfer Unit). Min value is 23, max 517.
/// The maximum value length for Write Without Response is
/// MTU - 3 bytes.
private var mtu: Int? = nil
/// The delegate that will handle connection requests.
private var connectionDelegate: CBMPeripheralSpecDelegate?
fileprivate init(identifier: UUID, proximity: CBMProximity) {
self.identifier = identifier
self.proximity = proximity
}
/// Makes the device advertising given data with specified advertising
/// interval.
/// - Parameters:
/// - advertisementData: The advertising data.
/// - interval: Advertising interval, in seconds.
/// - advertisingWhenConnected: If <i>true</i>, the device will also
/// be returned in scan results when
/// connected. By default set to
/// <i>false</i>.
/// - Returns: The builder.
public func advertising(advertisementData: [String : Any],
withInterval interval: TimeInterval = 0.100,
alsoWhenConnected advertisingWhenConnected: Bool = false) -> Builder {
self.advertisementData = advertisementData
self.advertisingInterval = interval
self.isAdvertisingWhenConnected = advertisingWhenConnected
return self
}
/// Makes the device connectable, but not connected at the moment
/// of initialization.
/// - Parameters:
/// - name: The device name, returned by Device Name characteristic.
/// - services: List of services that will be returned from service
/// discovery.
/// - connectionDelegate: The connection delegate that will handle
/// GATT requests.
/// - connectionInterval: Connection interval, in seconds.
/// - mtu: The MTU (Maximum Transfer Unit). Min 23 (default), max 517.
/// The maximum value length for Write Without Response is
/// MTU - 3 bytes (3 bytes are used by GATT for handle and
/// command).
public func connectable(name: String,
services: [CBMServiceMock],
delegate: CBMPeripheralSpecDelegate?,
connectionInterval: TimeInterval = 0.045,
mtu: Int = 23) -> Builder {
self.name = name
self.services = services
self.connectionDelegate = delegate
self.connectionInterval = connectionInterval
self.mtu = max(23, min(517, mtu))
self.isInitiallyConnected = false
return self
}
/// Makes the device connectable, and also marks already connected
/// by some other application. Such device, if not advertising,
/// can be obtained using `retrieveConnectedPeripherals(withServices:)`.
/// - Note: The peripheral needs to be in range.
/// - Parameters:
/// - name: The device name, returned by Device Name characteristic.
/// - services: List of services that will be returned from service
/// discovery.
/// - connectionDelegate: The connection delegate that will handle
/// GATT requests.
/// - connectionInterval: Connection interval, in seconds.
/// - mtu: The MTU (Maximum Transfer Unit). Min 23 (default), max 517.
/// The maximum value length for Write Without Response is
/// MTU - 3 bytes (3 bytes are used by GATT for handle and
/// command).
public func connected(name: String,
services: [CBMServiceMock],
delegate: CBMPeripheralSpecDelegate?,
connectionInterval: TimeInterval = 0.045,
mtu: Int = 23) -> Builder {
self.name = name
self.services = services
self.connectionDelegate = delegate
self.connectionInterval = connectionInterval
self.mtu = max(23, min(517, mtu))
self.isInitiallyConnected = proximity != .outOfRange
self.isKnown = true
return self
}
/// Make the peripheral available through
/// `CBMCentralManagerMock.retrievePeripherals(withIdentifiers:)`
/// without scanning.
///
/// That means, that the manager has perviously scanned and cached the
/// peripheral and can obtain it by the identfier.
public func allowForRetrieval() -> Builder {
self.isKnown = true
return self
}
/// Builds the `MockPeripheral` object.
public func build() -> CBMPeripheralSpec {
return CBMPeripheralSpec(
identifier: identifier,
name: name,
proximity: proximity,
isInitiallyConnected: isInitiallyConnected,
isAdvertisingWhenConnected: isAdvertisingWhenConnected,
isKnown: isKnown,
advertisementData: advertisementData,
advertisingInterval: advertisingInterval,
services: services,
connectionInterval: connectionInterval,
mtu: mtu,
connectionDelegate: connectionDelegate
)
}
}
}
extension CBMPeripheralSpec: Equatable {
public static func == (lhs: CBMPeripheralSpec, rhs: CBMPeripheralSpec) -> Bool {
return lhs.identifier == rhs.identifier
}
}
| 44.263158 | 102 | 0.629391 |
3a77bd7627c65aa5dd2ac1fcc69cea0a9a0b4975 | 267 | //
// InteractiveCellViewModel.swift
// CellViewModel
//
// Created by Anton Poltoratskyi on 03.04.2019.
// Copyright © 2019 Anton Poltoratskyi. All rights reserved.
//
public protocol InteractiveCellViewModel {
var selectionHandler: (() -> Void)? { get }
}
| 22.25 | 61 | 0.707865 |
722023f8bed3d22b305186dd5772193bf0c32e3e | 4,095 | //
// SandID.swift
// SandID
//
// Created by Aofei Sheng on 2018/11/3.
// Copyright © 2018 Aofei Sheng. All rights reserved.
//
import Foundation
/// The ID of sand.
public class SandID: Comparable, Hashable {
/// Zero SandID.
static let zero = SandID(data: Data(repeating: 0, count: 16))!
/// Lucky nibble.
static let luckyNibble = UInt8.random(in: 0 ... 255)
/// The data representation of the current SandID.
public private(set) var data: Data
/// The string representation of the current SandID.
public var string: String {
return data.base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
}
/// A Boolean value indicating whether the current SandID is zero.
public var isZero: Bool {
return self == SandID.zero
}
/// The hash value.
public var hashValue: Int {
return ObjectIdentifier(self).hashValue
}
/// Initialize.
public init() {
var uuid = [UInt8](repeating: 0, count: 16)
uuid_generate_time(&uuid)
data = Data(repeating: 0, count: 16)
data[0] = uuid[6] << 4 | uuid[7] >> 4
data[1] = uuid[7] << 4 | uuid[4] >> 4
data[2] = uuid[4] << 4 | uuid[5] >> 4
data[3] = uuid[5] << 4 | uuid[0] >> 4
data[4] = uuid[0] << 4 | uuid[1] >> 4
data[5] = uuid[1] << 4 | uuid[2] >> 4
data[6] = uuid[2] << 4 | uuid[3] >> 4
data[7] = uuid[3] << 4 | SandID.luckyNibble >> 4
data.replaceSubrange(8..., with: uuid[8...])
}
/// Initialize.
///
/// - Parameters:
/// - data: The data representation of the SandID to be initialized.
public init?(data: Data) {
guard data.count == 16 else {
return nil
}
self.data = data
}
/// Initialize.
///
/// - Parameters:
/// - string: The string representation of the SandID to be initialized.
public init?(string: String) {
if string.count != 22 {
return nil
}
guard let data = Data(base64Encoded: string.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/").appending("==")) else {
return nil
}
self.data = data
}
/// Reports whether two values are equal.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
///
/// - Returns: The result of the comparison.
public static func == (lhs: SandID, rhs: SandID) -> Bool {
return lhs.data == rhs.data
}
/// Reports whether two values are not equal.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
///
/// - Returns: The result of the comparison.
public static func != (lhs: SandID, rhs: SandID) -> Bool {
return !(lhs == rhs)
}
/// Reports whether the value of the first argument is less than that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
///
/// - Returns: The result of the comparison.
public static func < (lhs: SandID, rhs: SandID) -> Bool {
for index in 0 ..< 16 {
if lhs.data[index] >= rhs.data[index] {
return false
}
}
return true
}
/// Reports whether the value of the first argument is less than or equal to that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
///
/// - Returns: The result of the comparison.
public static func <= (lhs: SandID, rhs: SandID) -> Bool {
return lhs == rhs || lhs < rhs
}
/// Reports whether the value of the first argument is greater than or equal to that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
///
/// - Returns: The result of the comparison.
public static func > (lhs: SandID, rhs: SandID) -> Bool {
return !(lhs <= rhs)
}
/// Reports whether the value of the first argument is greater than that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
///
/// - Returns: The result of the comparison.
public static func >= (lhs: SandID, rhs: SandID) -> Bool {
return !(lhs < rhs)
}
}
| 26.082803 | 151 | 0.618071 |
148b98aef13fc60dc223ef48da02f3124ef8444e | 62,933 | //
// Safari.swift
// OldOS
//
// Created by Zane Kleinberg on 2/20/21.
//
import SwiftUI
import WebKit
import Introspect
import SwiftUIPager
import Combine
struct Safari: View {
@State var current_nav_view: String = "Main"
@State var forward_or_backward = false
@State var url_search: String = ""
@State var google_search: String = ""
@State var editing_state_url: String = "None"
@State var editing_state_google: String = "None"
@State var current_webpage_title: String = ""
@State private var webViewHeight: CGFloat = .zero
@State var offset: CGPoint = CGPoint(0,0)
@State var first_load: Bool = true
@State var selecting_tab: Bool = false
@State var instant_background_change: Bool = false
@State var can_tap_view: Bool = true
@ObservedObject var views: ObservableArray<WebViewStore> = try! ObservableArray(array: [WebViewStore()]).observeChildrenChanges()
@StateObject var page: Page = .first()
@State var will_remove_object: WebViewStore = WebViewStore()
@State var did_add_to_end: Bool = false
@State var show_bookmarks: Bool = false
@State var show_share:Bool = false
@State var bookmark_name: String = ""
@State var show_save_bookmark: Bool = false
@State var is_editing_bookmarks: Bool = false
@State var new_page_delay: Bool = false
@Binding var instant_multitasking_change: Bool
var items = Array(0..<1)
init(instant_multitasking_change: Binding<Bool>) {
_instant_multitasking_change = instant_multitasking_change
let userDefaults = UserDefaults.standard
var webpages = (userDefaults.object(forKey: "webpages") as? [String:String] ?? ["0":"https://"]).sorted(by: >)
if webpages.count > 1 {
for i in 0..<(webpages.count-1) {
views.array.append(WebViewStore())
}
}
for item in webpages {
if let url = URL(string:item.value) {
views.array[Int(item.key) ?? 0].webView.load(URLRequest(url: url))
}
}
}
var body: some View {
GeometryReader { geometry in
ZStack {
VStack(spacing:0) {
Spacer().frame(height:24)
Pager(page: page,
data: views.array,
id: \.id,
content: { index in
ZStack {
ScrollView([]) {
VStack {
Spacer().frame(height:76).offset(y: offset.height < 76 ? -offset.height : -76).drawingGroup()
Webview(dynamicHeight: $webViewHeight, offset: $offset, selecting_tab:$selecting_tab, webview: index.webView)
.frame(height:geometry.size.height - (24+45)).offset(y: offset.height < 76 ? -offset.height : -76)
}
}.disabled(selecting_tab).simultaneousGesture(
TapGesture()
.onEnded({
if selecting_tab == true, can_tap_view == true {
if views.array.firstIndex(of: index) == page.index {
print(page)
if instant_background_change == false {
instant_background_change = true
} else {
DispatchQueue.main.asyncAfter(deadline:.now()+0.25) {
instant_background_change = false
}
}
withAnimation(.linear(duration:0.25)) {
page.update(.new(index: views.array.firstIndex(of: index) ?? 0))//This page update is ensurance if we get stuck
url_search = index.webView.url?.relativeString ?? ""
selecting_tab.toggle()
}
} else {
withAnimation(.linear(duration:0.25)) {
page.update(.new(index: views.array.firstIndex(of: index) ?? 0))
}
}
}
})).shadow(color:Color.black.opacity(0.4), radius: 3, x: 0, y:4).opacity(views.array.firstIndex(of: index) == page.index ? 1 : 0.2)
VStack {
HStack {
Button(action:{
if views.array.count > 1 {
withAnimation(.linear(duration:0.2)) {
will_remove_object = index
}
DispatchQueue.main.asyncAfter(deadline:.now()+0.21) {
if index == views.array.last {
withAnimation {
page.update(.previous)
if let rem_index = views.array.firstIndex(of: index) {
views.array.remove(at: rem_index)
let userDefaults = UserDefaults.standard
var webpage_dict = [String:String]()
var i = 0
for item in views.array {
webpage_dict["\(i)"] = (item.webView.url?.relativeString != nil ? item.webView.url?.relativeString : "http")
i += 1
}
var defaults_webpages = (userDefaults.object(forKey: "webpages") as? [String:String] ?? ["0":"https://"]).sorted(by: >)
if defaults_webpages != webpage_dict.sorted(by: >) {
userDefaults.setValue(webpage_dict, forKey: "webpages")
}
}
}
} else {
withAnimation {
if let rem_index = views.array.firstIndex(of: index) {
views.array.remove(at: rem_index)
let userDefaults = UserDefaults.standard
var webpage_dict = [String:String]()
var i = 0
for item in views.array {
webpage_dict["\(i)"] = (item.webView.url?.relativeString != nil ? item.webView.url?.relativeString : "http")
i += 1
}
var defaults_webpages = (userDefaults.object(forKey: "webpages") as? [String:String] ?? ["0":"https://"]).sorted(by: >)
if defaults_webpages != webpage_dict.sorted(by: >) {
userDefaults.setValue(webpage_dict, forKey: "webpages")
}
}
}
}
}
}
}) {
Image("closebox").resizable().scaledToFill().frame(width:50, height:50)
}.padding([.top], 80).padding([.trailing], 60).frame(width:60, height:60)
Spacer()
}
Spacer()
}.disabled(!selecting_tab).opacity(selecting_tab == true ? views.array.firstIndex(of: index) == page.index ? views.array.count > 1 ? 1 : 0 : 0 : 0) //The magic of the turnery
}.scaleEffect(selecting_tab == true ? 0.55 : views.array.firstIndex(of: index) == page.index ? 1 : 0.55).zIndex(views.array.firstIndex(of: index) == page.index ? 1 : 0).opacity(will_remove_object == index ? 0 : 1).opacity(did_add_to_end == true ? index == views.array.last ? 0 : 1 : 1)}) .itemSpacing( -geometry.size.width*0.30).onDraggingBegan({
can_tap_view = false
}).onDraggingEnded({
can_tap_view = true
}).alignment(.center).preferredItemSize(CGSize(width: geometry.size.width, height: geometry.size.height - (24+45))).sensitivity(.high).allowsDragging(selecting_tab).multiplePagination().background(instant_background_change == true ? LinearGradient([Color(red: 149/255, green: 161/255, blue: 172/255), Color(red: 85/255, green: 105/255, blue: 121/255)], from: .top, to: .bottom) : LinearGradient([Color.clear], from: .top, to: .bottom))
Spacer().frame(minHeight:45, maxHeight:45)
}.clipped()
VStack {
Spacer().frame(height:geometry.size.height*(1/9))
HStack {
Spacer()
Text(views.array[page.index].webView.title != "" ? (views.array[page.index].webView.title ?? "Untitled") : "Untitled").foregroundColor(Color.white).font(.custom("Helvetica Neue Bold", fixedSize: 22)).shadow(color: Color.black.opacity(0.51), radius: 0, x: 0.0, y: -2/3).lineLimit(0).animation(instant_multitasking_change == true ? .default : .none)
Spacer()
}
Spacer().frame(height:10)
HStack {
Spacer()
Text(views.array[page.index].webView.url?.relativeString ?? "Untitled").foregroundColor(Color(red: 182/255, green: 188/255, blue: 192/255)).font(.custom("Helvetica Neue Bold", fixedSize: 16)).shadow(color: Color.black.opacity(0.51), radius: 0, x: 0.0, y: -2/3).lineLimit(0).animation(instant_multitasking_change == true ? .default : .none).opacity(views.array[page.index].webView.url?.relativeString != nil ? 1 : 0)
Spacer()
}.if(!instant_multitasking_change){$0.animationsDisabled()}
Spacer()
}.opacity(selecting_tab == true ? 1 : 0)
VStack {
Spacer()
HStack(spacing: 10) {
Spacer()
ForEach(views.array, id:\.id) { index in
Circle().fill(Color.white).frame(width:7.5, height:7.5).opacity(views.array.firstIndex(of: index) == page.index ? 1 : 0.25)
}.opacity(views.array.count > 1 ? 1 : 0)
Spacer()
}.if(!instant_multitasking_change){$0.animationsDisabled()}
Spacer().frame(height:geometry.size.height*(1.5/9))
}.opacity(selecting_tab == true ? 1 : 0)
ZStack {
if editing_state_url != "None" || editing_state_google != "None" {
Color.black.opacity(0.75)
}
}
VStack(spacing:0) {
status_bar_in_app().frame(minHeight: 24, maxHeight:24).zIndex(2)
safari_title_bar(forward_or_backward: $forward_or_backward, current_nav_view: $current_nav_view, url_search: $url_search, google_search: $google_search, editing_state_url: $editing_state_url, editing_state_google: $editing_state_google, webViewStore: views.array[page.index], current_webpage_title: views.array[page.index].webView.title ?? "").frame(minHeight: 60, maxHeight: 60).padding(.bottom, 5).offset(y: offset.height < 76 ? -offset.height : -76).zIndex(1).opacity(selecting_tab == true ? 0 : 1)
Spacer()
}.clipped()
if show_bookmarks {
bookmarks_view(show_bookmarks: $show_bookmarks, is_editing_bookmarks: $is_editing_bookmarks, webViewStore: views.array[page.index]).transition(.asymmetric(insertion: .move(edge:.bottom), removal: .move(edge:.bottom))).zIndex(1)
}
VStack(spacing:0) {
Spacer()
tool_bar(webViewStore: views.array[page.index], selecting_tab: $selecting_tab, offset:$offset, instant_background_change: $instant_background_change, show_share: $show_share, show_bookmarks: $show_bookmarks, is_editing_bookmarks: $is_editing_bookmarks, new_tab_action: {
if new_page_delay == false {
if views.array.count < 8 {
did_add_to_end = true
new_page_delay = true
views.array.append(WebViewStore())
DispatchQueue.main.asyncAfter(deadline: .now() + 0.21) {
withAnimation {
page.update(.moveToLast)
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.61) {
withAnimation(.linear(duration:0.25)) {
did_add_to_end = false
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.86) {
if instant_background_change == false {
instant_background_change = true
} else {
DispatchQueue.main.asyncAfter(deadline:.now()+0.25) {
instant_background_change = false
}
}
withAnimation(.linear(duration:0.25)) {
selecting_tab.toggle()
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1.12) {
new_page_delay = false
}
}
}
}, editing_bookmarks_action:{
withAnimation() {
is_editing_bookmarks.toggle()
}
}, tab_image: "NavTab\(views.array.count != 1 ? String(views.array.count) : "")").frame(height: 45)
}.zIndex(2)
ZStack {
if show_share == true {
Color.black.opacity(0.35)
VStack(spacing:0) {
Spacer().foregroundColor(.clear).zIndex(0)
share_view(cancel_action:{
withAnimation() {
show_share.toggle()
}
}, bookmark_action:{
withAnimation(.linear(duration:0.25)) {
show_share.toggle()
}
bookmark_name = views.array[page.index].webView.title ?? "Untitled"
DispatchQueue.main.asyncAfter(deadline:.now()+0.25) {
withAnimation(.linear(duration:0.25)) {
show_save_bookmark.toggle()
}
}
}).frame(minHeight: geometry.size.height*(0.58), maxHeight: geometry.size.height*(0.58))
}.transition(.asymmetric(insertion: .move(edge:.bottom), removal: .move(edge:.bottom)))
}//We nest this in a VStack to get around type check errors
}.zIndex(3)
ZStack {
if show_save_bookmark == true {
add_bookmark_view(bookmark_name: $bookmark_name, url: views.array[page.index].webView.url ?? URL(string:"google.com")!, cancel_action:{withAnimation(){show_save_bookmark.toggle()}}, save_action:{
let userDefaults = UserDefaults.standard
// Read/Get Array of Strings
var bookmarks: [String:String] = userDefaults.object(forKey: "bookmarks") as? [String:String] ?? [String: String]()
// Append String to Array of Strings
bookmarks.updateValue(bookmark_name, forKey: views.array[page.index].webView.url?.relativeString ?? "")
// Write/Set Array of Strings
userDefaults.set(bookmarks, forKey: "bookmarks")
withAnimation() {
show_save_bookmark.toggle()
}
}).transition(.asymmetric(insertion: .move(edge:.bottom), removal: .move(edge:.bottom)))
}
}.zIndex(4)
}.compositingGroup().clipped()//Having our view composed of 2 VStacks allows our webviews and titles to work independtly from each other.
}.background(Color(red: 93/255, green: 99/255, blue: 103/255)).onAppear() {
UIScrollView.appearance().bounces = true
}.onDisappear() {
UIScrollView.appearance().bounces = false
}.onReceive(views.array[page.index].objectWillChange) {_ in
if editing_state_url == "None" {
url_search = views.array[page.index].webView.url?.relativeString ?? ""
}
let userDefaults = UserDefaults.standard
var webpage_dict = [String:String]()
var i = 0
for item in views.array {
webpage_dict["\(i)"] = (item.webView.url?.relativeString != nil ? item.webView.url?.relativeString : "http")
i += 1
}
var defaults_webpages = (userDefaults.object(forKey: "webpages") as? [String:String] ?? ["0":"https://"]).sorted(by: >)
if defaults_webpages != webpage_dict.sorted(by: >) {
userDefaults.setValue(webpage_dict, forKey: "webpages")
}
}.onChange(of: page.index) {_ in
if editing_state_url == "None" {
url_search = views.array[page.index].webView.url?.relativeString ?? ""
}
let userDefaults = UserDefaults.standard
var webpage_dict = [String:String]()
var i = 0
for item in views.array {
webpage_dict["\(i)"] = (item.webView.url?.relativeString != nil ? item.webView.url?.relativeString : "http")
i += 1
}
var defaults_webpages = (userDefaults.object(forKey: "webpages") as? [String:String] ?? ["0":"https://"]).sorted(by: >)
if defaults_webpages != webpage_dict.sorted(by: >) {
userDefaults.setValue(webpage_dict, forKey: "webpages")
}
}
}
}
func areEqual (_ left: Any, _ right: Any) -> Bool {
if type(of: left) == type(of: right) &&
String(describing: left) == String(describing: right) { return true }
if let left = left as? [Any], let right = right as? [Any] { return left == right }
if let left = left as? [AnyHashable: Any], let right = right as? [AnyHashable: Any] { return left == right }
return false
}
extension Array where Element: Any {
static func != (left: [Element], right: [Element]) -> Bool { return !(left == right) }
static func == (left: [Element], right: [Element]) -> Bool {
if left.count != right.count { return false }
var right = right
loop: for leftValue in left {
for (rightIndex, rightValue) in right.enumerated() where areEqual(leftValue, rightValue) {
right.remove(at: rightIndex)
continue loop
}
return false
}
return true
}
}
extension Dictionary where Value: Any {
static func != (left: [Key : Value], right: [Key : Value]) -> Bool { return !(left == right) }
static func == (left: [Key : Value], right: [Key : Value]) -> Bool {
if left.count != right.count { return false }
for element in left {
guard let rightValue = right[element.key],
areEqual(rightValue, element.value) else { return false }
}
return true
}
}
struct bookmarks_view: View {
@Binding var show_bookmarks: Bool
@Binding var is_editing_bookmarks: Bool
@State var to_delete: String = ""
var webViewStore: WebViewStore
@ObservedObject var bm_observer = bookmarks_observer()
var body: some View {
VStack(spacing:0) {
Spacer().frame(minHeight: 24, maxHeight:24)
generic_title_bar(title: "Bookmarks", done_action:{withAnimation(){show_bookmarks.toggle()}}, show_done: !is_editing_bookmarks).frame(minHeight: 60, maxHeight: 60)
NoSepratorList {
VStack(alignment: .leading, spacing: 0) {
HStack(alignment: .center) {
Spacer().frame(width:1, height: 44-0.95)
Image("HistoryFolder").frame(width:25, height: 44-0.95)
Text("History").font(.custom("Helvetica Neue Bold", fixedSize: 18)).foregroundColor(.black).lineLimit(1).padding(.leading, 6).padding(.trailing, 40)
Spacer()
Image("UITableNext").padding(.trailing, 12)
}.padding(.leading, 15)
Rectangle().fill(Color(red: 224/255, green: 224/255, blue: 224/255)).frame(height:0.95).edgesIgnoringSafeArea(.all)
}.hideRowSeparator().listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)).frame(height: 44)
ForEach((bm_observer.bookmarks ?? [:]).sorted(by: <), id: \.key) { key, value in
Button(action:{
if let url = URL(string: key) {
webViewStore.webView.load(URLRequest(url: url))
withAnimation() {
show_bookmarks.toggle()
}
}
}) {
VStack(alignment: .leading, spacing: 0) {
//Spacer().frame(height:4.5)
HStack(alignment: .center) {
Spacer().frame(width:1, height: 44-0.95)
if is_editing_bookmarks == true {
Button(action:{
withAnimation(.linear(duration:0.15)) {
if to_delete != key {
to_delete = key
} else {
to_delete = ""
}
}
}) {
ZStack {
Image("UIRemoveControlMinus")
Text("—").foregroundColor(.white).font(.system(size: 15, weight: .heavy, design: .default)).offset(y:to_delete == key ? -0.8 : -2).rotationEffect(.degrees(to_delete == key ? -90 : 0), anchor: .center).offset(y:to_delete == key ? -0.5 : 0)
}
}.transition(AnyTransition.asymmetric(insertion: .move(edge:.leading), removal: .move(edge:.leading)).combined(with: .opacity)).offset(x:-2)
}
Image("Bookmark").frame(width:25, height: 44-0.95)
Text(value).font(.custom("Helvetica Neue Bold", fixedSize: 18)).foregroundColor(.black).lineLimit(1).padding(.leading, 6).padding(.trailing, 12)
if to_delete == key {
Spacer()
tool_bar_rectangle_button(action: {withAnimation() {
bm_observer.bookmarks.removeValue(forKey: key)
}}, button_type: .red, content: "Delete").padding(.trailing, 12).transition(AnyTransition.asymmetric(insertion: .move(edge:.trailing), removal: .move(edge:.trailing)).combined(with: .opacity))
}
}.padding(.leading, 15)
// Spacer().frame(height:9.5)
Rectangle().fill(Color(red: 224/255, green: 224/255, blue: 224/255)).frame(height:0.95).edgesIgnoringSafeArea(.all)
}
}
}.hideRowSeparator().listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)).frame(height: 44).drawingGroup()
}.background(Color.white)
Spacer().frame(minHeight: 45, maxHeight:45)
}
}
}
class bookmarks_observer: ObservableObject {
@Published var bookmarks: [String:String] {
didSet {
UserDefaults.standard.set(bookmarks, forKey: "bookmarks")
}
}
init() {
self.bookmarks = UserDefaults.standard.object(forKey: "bookmarks") as? [String:String] ?? [:]
}
}
struct share_view: View {
public var cancel_action: (() -> Void)?
public var bookmark_action: (() -> Void)?
private let background_gradient = LinearGradient(gradient: Gradient(colors: [Color.init(red: 70/255, green: 73/255, blue: 81/255), Color.init(red: 70/255, green: 73/255, blue: 81/255)]), startPoint: .top, endPoint: .bottom)
var body: some View {
GeometryReader {geometry in
ZStack {
VStack(spacing:0) {
Rectangle().fill(LinearGradient(gradient: Gradient(colors: [Color.init(red: 166/255, green: 171/255, blue: 179/255).opacity(0.88), Color.init(red: 122/255, green: 127/255, blue: 138/255).opacity(0.88)]), startPoint: .top, endPoint: .bottom)).innerShadowBottom(color: Color.white.opacity(0.98), radius: 0.1).border_top(width: 1, edges:[.top], color: Color.black).frame(height:30)
Rectangle().fill(LinearGradient(gradient: Gradient(colors: [Color.init(red: 96/255, green: 101/255, blue: 111/255).opacity(0.88), Color.init(red: 96/255, green: 101/255, blue: 111/255).opacity(0.9)]), startPoint: .top, endPoint: .bottom))
}
VStack {
Button(action:{
bookmark_action?()
}){
ZStack {
RoundedRectangle(cornerRadius: 12).fill(Color.clear).overlay(RoundedRectangle(cornerRadius: 12).stroke(LinearGradient(gradient: Gradient(colors:[Color.init(red: 83/255, green: 83/255, blue: 83/255),Color.init(red: 143/255, green: 143/255, blue: 143/255)]), startPoint: .top, endPoint: .bottom), lineWidth: 0.5)).ps_innerShadow(.roundedRectangle(12, background_gradient), radius:5/3, offset: CGPoint(0, 1/3), intensity: 1)
RoundedRectangle(cornerRadius: 9).fill(LinearGradient(gradient: Gradient(stops: [.init(color: Color(red: 235/255, green: 235/255, blue: 236/255), location: 0), .init(color: Color(red: 208/255, green: 209/255, blue: 211/255), location: 0.52), .init(color: Color(red: 192/255, green: 193/255, blue: 196/255), location: 0.52), .init(color: Color(red: 192/255, green: 193/255, blue: 196/255), location: 1.0)]), startPoint: .top, endPoint: .bottom)).addBorder(LinearGradient(gradient: Gradient(colors:[Color.white.opacity(0.9), Color.white.opacity(0.25)]), startPoint: .top, endPoint: .bottom), width: 0.4, cornerRadius: 9).padding(3)
Text("Add Bookmark").font(.custom("Helvetica Neue Bold", fixedSize: 18)).foregroundColor(Color.black).shadow(color: Color.white.opacity(0.9), radius: 0, x: 0.0, y: 0.9)
}.padding([.leading, .trailing], 25).frame(minHeight: 50, maxHeight:50)
}.padding([.bottom], 2.5).padding(.top, 28)
Button(action:{
}){
ZStack {
RoundedRectangle(cornerRadius: 12).fill(Color.clear).overlay(RoundedRectangle(cornerRadius: 12).stroke(LinearGradient(gradient: Gradient(colors:[Color.init(red: 83/255, green: 83/255, blue: 83/255),Color.init(red: 143/255, green: 143/255, blue: 143/255)]), startPoint: .top, endPoint: .bottom), lineWidth: 0.5)).ps_innerShadow(.roundedRectangle(12, background_gradient), radius:5/3, offset: CGPoint(0, 1/3), intensity: 1)
RoundedRectangle(cornerRadius: 9).fill(LinearGradient(gradient: Gradient(stops: [.init(color: Color(red: 235/255, green: 235/255, blue: 236/255), location: 0), .init(color: Color(red: 208/255, green: 209/255, blue: 211/255), location: 0.52), .init(color: Color(red: 192/255, green: 193/255, blue: 196/255), location: 0.52), .init(color: Color(red: 192/255, green: 193/255, blue: 196/255), location: 1.0)]), startPoint: .top, endPoint: .bottom)).addBorder(LinearGradient(gradient: Gradient(colors:[Color.white.opacity(0.9), Color.white.opacity(0.25)]), startPoint: .top, endPoint: .bottom), width: 0.4, cornerRadius: 9).padding(3)
Text("Add to Home Screen").font(.custom("Helvetica Neue Bold", fixedSize: 18)).foregroundColor(Color.black).shadow(color: Color.white.opacity(0.9), radius: 0, x: 0.0, y: 0.9)
}.padding([.leading, .trailing], 25).frame(minHeight: 50, maxHeight:50)
}.padding([.top, .bottom], 2.5)
Button(action:{
}){
ZStack {
RoundedRectangle(cornerRadius: 12).fill(Color.clear).overlay(RoundedRectangle(cornerRadius: 12).stroke(LinearGradient(gradient: Gradient(colors:[Color.init(red: 83/255, green: 83/255, blue: 83/255),Color.init(red: 143/255, green: 143/255, blue: 143/255)]), startPoint: .top, endPoint: .bottom), lineWidth: 0.5)).ps_innerShadow(.roundedRectangle(12, background_gradient), radius:5/3, offset: CGPoint(0, 1/3), intensity: 1)
RoundedRectangle(cornerRadius: 9).fill(LinearGradient(gradient: Gradient(stops: [.init(color: Color(red: 235/255, green: 235/255, blue: 236/255), location: 0), .init(color: Color(red: 208/255, green: 209/255, blue: 211/255), location: 0.52), .init(color: Color(red: 192/255, green: 193/255, blue: 196/255), location: 0.52), .init(color: Color(red: 192/255, green: 193/255, blue: 196/255), location: 1.0)]), startPoint: .top, endPoint: .bottom)).addBorder(LinearGradient(gradient: Gradient(colors:[Color.white.opacity(0.9), Color.white.opacity(0.25)]), startPoint: .top, endPoint: .bottom), width: 0.4, cornerRadius: 9).padding(3)
Text("Mail Link to this Page").font(.custom("Helvetica Neue Bold", fixedSize: 18)).foregroundColor(Color.black).shadow(color: Color.white.opacity(0.9), radius: 0, x: 0.0, y: 0.9)
}.padding([.leading, .trailing], 25).frame(minHeight: 50, maxHeight:50)
}.padding([.top, .bottom], 2.5)
Button(action:{
}){
ZStack {
RoundedRectangle(cornerRadius: 12).fill(Color.clear).overlay(RoundedRectangle(cornerRadius: 12).stroke(LinearGradient(gradient: Gradient(colors:[Color.init(red: 83/255, green: 83/255, blue: 83/255),Color.init(red: 143/255, green: 143/255, blue: 143/255)]), startPoint: .top, endPoint: .bottom), lineWidth: 0.5)).ps_innerShadow(.roundedRectangle(12, background_gradient), radius:5/3, offset: CGPoint(0, 1/3), intensity: 1)
RoundedRectangle(cornerRadius: 9).fill(LinearGradient(gradient: Gradient(stops: [.init(color: Color(red: 235/255, green: 235/255, blue: 236/255), location: 0), .init(color: Color(red: 208/255, green: 209/255, blue: 211/255), location: 0.52), .init(color: Color(red: 192/255, green: 193/255, blue: 196/255), location: 0.52), .init(color: Color(red: 192/255, green: 193/255, blue: 196/255), location: 1.0)]), startPoint: .top, endPoint: .bottom)).addBorder(LinearGradient(gradient: Gradient(colors:[Color.white.opacity(0.9), Color.white.opacity(0.25)]), startPoint: .top, endPoint: .bottom), width: 0.4, cornerRadius: 9).padding(3)
Text("Print").font(.custom("Helvetica Neue Bold", fixedSize: 18)).foregroundColor(Color.black).shadow(color: Color.white.opacity(0.9), radius: 0, x: 0.0, y: 0.9)
}.padding([.leading, .trailing], 25).frame(minHeight: 50, maxHeight:50)
}.padding([.top, .bottom], 2.5)
Spacer()
Button(action:{
cancel_action?()
}) {
ZStack {
RoundedRectangle(cornerRadius: 12).fill(Color.clear).overlay(RoundedRectangle(cornerRadius: 12).stroke(LinearGradient(gradient: Gradient(colors:[Color.init(red: 83/255, green: 83/255, blue: 83/255),Color.init(red: 143/255, green: 143/255, blue: 143/255)]), startPoint: .top, endPoint: .bottom), lineWidth: 0.5)).ps_innerShadow(.roundedRectangle(12, background_gradient), radius:5/3, offset: CGPoint(0, 1/3), intensity: 1)
RoundedRectangle(cornerRadius: 9).fill(LinearGradient([(color: Color(red: 107/255, green: 113/255, blue:119/255), location: 0), (color: Color(red: 53/255, green: 62/255, blue:69/255), location: 0.50), (color: Color(red: 41/255, green: 48/255, blue:57/255), location: 0.50), (color: Color(red: 56/255, green: 62/255, blue:71/255), location: 1)], from: .top, to: .bottom)).addBorder(LinearGradient(gradient: Gradient(colors:[Color.gray.opacity(0.9), Color.gray.opacity(0.35)]), startPoint: .top, endPoint: .bottom), width: 0.4, cornerRadius: 9).padding(3).opacity(0.6)
Text("Cancel").font(.custom("Helvetica Neue Bold", fixedSize: 18)).foregroundColor(Color.white).shadow(color: Color.black.opacity(0.9), radius: 0, x: 0.0, y: -0.9)
}.padding([.leading, .trailing], 25).frame(minHeight: 50, maxHeight:50)
}.padding([.bottom], 25)
}
}.drawingGroup()
}
}
}
struct add_bookmark_view: View {
@State var current_nav_view: String = ""
@State var forward_or_backward: Bool = false
@Binding var bookmark_name: String
@State var editing_state_title: String = "None"
var url: URL
public var cancel_action: (() -> Void)?
public var save_action: (() -> Void)?
var body: some View {
VStack(spacing:0) {
Spacer().frame(height:24)
ZStack {
settings_main_list()
VStack(spacing:0) {
generic_title_bar_cancel_save(title: "Add Bookmark", cancel_action: {cancel_action?()}, save_action:{save_action?()}, show_cancel: true, show_save: true).frame(height: 60)
ScrollView {
VStack {
Spacer().frame(height:20)
ZStack {
RoundedRectangle(cornerRadius: 10).fill(Color.white).overlay(RoundedRectangle(cornerRadius: 10)
.stroke(Color(red: 171/255, green: 171/255, blue: 171/255), lineWidth: 1.25))
VStack(spacing:0) {
ZStack {
Rectangle().fill(Color.clear).frame(height:50).border_bottom(width: 1.25, edges: [.bottom], color: Color(red: 171/255, green: 171/255, blue: 171/255))
HStack {
TextField("Title", text: $bookmark_name){
save_action?()
}.font(.custom("Helvetica Neue Regular", fixedSize: 18)).foregroundColor(Color(red: 62/255, green: 83/255, blue: 131/255)).padding(.leading, 12)
if bookmark_name.count != 0 {
Button(action:{bookmark_name = ""}) {
Image("UITextFieldClearButton")
}.fixedSize().padding(.trailing,12)
}
}
}.frame(height: 50)
ZStack {
Rectangle().fill(Color.clear).frame(height:50)
HStack {
Text(url.relativeString).font(.custom("Helvetica Neue Regular", fixedSize: 18)).foregroundColor(Color(red: 143/255, green: 143/255, blue: 143/255)).padding(.leading, 12)
Spacer()
}
}.frame(height: 50)
}
}.frame(height: 100).padding([.leading, .trailing], 12)
Spacer().frame(height:20)
list_section_content_only(current_nav_view: $current_nav_view, forward_or_backward: $forward_or_backward, content: [list_row(title: "", content: AnyView(bookmark_content()))])
}
}
}
}
}
}
}
#if canImport(UIKit)
extension View {
func showKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.becomeFirstResponder), to: nil, from: nil, for: nil)
}
}
#endif
struct enter_bookmark_title_content: View {
@Binding var bookmark_name: String
var body: some View {
HStack {
TextField("Title", text: $bookmark_name).font(.custom("Helvetica Neue Regular", fixedSize: 18)).foregroundColor(Color(red: 62/255, green: 83/255, blue: 131/255)).padding(.leading, 12)
}
}
}
struct bookmark_content: View {
var body: some View {
HStack {
Text("Bookmarks").font(.custom("Helvetica Neue Regular", fixedSize: 18)).foregroundColor(Color(red: 62/255, green: 83/255, blue: 131/255)).padding(.leading, 12)
Spacer()
//Image(systemName: "chevron.right").foregroundColor(Color(red: 127/255, green: 127/255, blue: 127/255)).padding(.trailing, 12)
Image("UITableNext").padding(.trailing, 12)
}
}
}
extension View {
func animationsDisabled() -> some View {
return self.transaction { (tx: inout Transaction) in
tx.disablesAnimations = true
tx.animation = nil
}.animation(nil)
}
}
extension View {
public func introspectScrollView2(customize: @escaping (UIScrollView) -> ()) -> some View {
return inject(UIKitIntrospectionView(
selector: { introspectionView in
guard let viewHost = Introspect.findViewHost(from: introspectionView) else {
return nil
}
if let scrollView = Introspect.previousSibling(containing: UIScrollView.self, from: viewHost) {
return scrollView
}else if let superView = viewHost.superview {
return Introspect.previousSibling(containing: UIScrollView.self, from: superView)
}
return nil
},
customize: customize
))
}
}
struct Webview : UIViewRepresentable {
@Binding var dynamicHeight: CGFloat
@Binding var offset: CGPoint
@Binding var selecting_tab: Bool
var webview: WKWebView = WKWebView()
var oldContentOffset = CGPoint.zero
var originalcenter = CGPoint.zero
class Coordinator: NSObject, WKNavigationDelegate, UIScrollViewDelegate {
var parent: Webview
init(_ parent: Webview) {
self.parent = parent
self.parent.originalcenter = parent.webview.scrollView.subviews[0].center
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if parent.selecting_tab == false {
var offset = scrollView.contentOffset
parent.offset = offset
if offset.y < 76 {
parent.webview.scrollView.subviews[0].center.y = parent.originalcenter.y + offset.y
} else if offset.y > 76 {
parent.webview.scrollView.subviews[0].center.y = parent.originalcenter.y + 76
parent.webview.scrollView.contentInset = UIEdgeInsets(0, 0, 76, 0)
}
}
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
decisionHandler(WKNavigationActionPolicy(rawValue: WKNavigationActionPolicy.allow.rawValue + 2)!)
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> WKWebView {
webview.navigationDelegate = context.coordinator
webview.scrollView.delegate = context.coordinator
webview.scrollView.backgroundColor = UIColor(red: 93/255, green: 99/255, blue: 103/255, alpha: 1.0)
webview.configuration.suppressesIncrementalRendering = true
return webview
}
func updateUIView(_ uiView: WKWebView, context: Context) {
webview.scrollView.backgroundColor = UIColor(red: 93/255, green: 99/255, blue: 103/255, alpha: 1.0)
}
}
//Thanks to https://stackoverflow.com/questions/57459727/why-an-observedobject-array-is-not-updated-in-my-swiftui-application for this genius solution to a problem I've encountered on various projects. This let's us be notified of changes to published vars inside an array, which itself is a published var.
class ObservableArray<T>: ObservableObject {
@Published var array:[T] = []
var cancellables = [AnyCancellable]()
init(array: [T]) {
self.array = array
}
func observeChildrenChanges<T: ObservableObject>() -> ObservableArray<T> {
let array2 = array as! [T]
array2.forEach({
let c = $0.objectWillChange.sink(receiveValue: { _ in self.objectWillChange.send() })
// Important: You have to keep the returned value allocated,
// otherwise the sink subscription gets cancelled
self.cancellables.append(c)
})
return self as! ObservableArray<T>
}
}
public class WebViewStore: ObservableObject, Identifiable, Equatable {
public static func == (lhs: WebViewStore, rhs: WebViewStore) -> Bool {
return lhs.webView == rhs.webView
}
@Published public var webView: WKWebView {
didSet {
setupObservers()
}
}
public init(webView: WKWebView = WKWebView()) {
self.webView = webView
setupObservers()
}
private func setupObservers() {
func subscriber<Value>(for keyPath: KeyPath<WKWebView, Value>) -> NSKeyValueObservation {
return webView.observe(keyPath, options: [.prior]) { _, change in
if change.isPrior {
self.objectWillChange.send()
}
}
}
// Setup observers for all KVO compliant properties
observers = [
subscriber(for: \.title),
subscriber(for: \.url),
subscriber(for: \.isLoading),
subscriber(for: \.estimatedProgress),
subscriber(for: \.hasOnlySecureContent),
subscriber(for: \.serverTrust),
subscriber(for: \.canGoBack),
subscriber(for: \.canGoForward),
subscriber(for: \.scrollView.contentSize)
]
}
private var observers: [NSKeyValueObservation] = []
public subscript<T>(dynamicMember keyPath: KeyPath<WKWebView, T>) -> T {
webView[keyPath: keyPath]
}
}
struct tool_bar: View {
var webViewStore: WebViewStore
@Binding var selecting_tab: Bool
@Binding var offset: CGPoint
@Binding var instant_background_change: Bool
@Binding var show_share:Bool
@Binding var show_bookmarks: Bool
@Binding var is_editing_bookmarks:Bool
public var new_tab_action: (() -> Void)?
public var editing_bookmarks_action: (() -> Void)?
var tab_image: String
var body: some View {
ZStack {
LinearGradient([(color: Color(red: 230/255, green: 230/255, blue: 230/255), location: 0), (color: Color(red: 180/255, green: 191/255, blue: 206/255), location: 0.04), (color: Color(red: 136/255, green: 155/255, blue: 179/255), location: 0.51), (color: Color(red: 126/255, green: 148/255, blue: 176/255), location: 0.51), (color: Color(red: 110/255, green: 132/255, blue: 162/255), location: 1)], from: .top, to: .bottom).border_bottom(width: 1, edges: [.top], color: Color(red: 45/255, green: 48/255, blue: 51/255))//I just discovered it was much easier to do this...duh
if !show_bookmarks {
if !selecting_tab {
HStack {
tool_bar_button(image:"NavBack", action: {
webViewStore.webView.goBack()
}).opacity(webViewStore.webView.canGoBack == true ? 1 : 0.25)
tool_bar_button(image:"NavForward", action: {
webViewStore.webView.goForward()
}).opacity(webViewStore.webView.canGoForward == true ? 1 : 0.25)
tool_bar_button(image:"NavAction", action: {
withAnimation() {
show_share.toggle()
}
})
tool_bar_button(image:"NavBookmarks", action: {
withAnimation() {
show_bookmarks.toggle()
}
})
tool_bar_button(image:tab_image) {
offset = CGPoint(0,0)
if instant_background_change == false {
instant_background_change = true
} else {
DispatchQueue.main.asyncAfter(deadline:.now()+0.25) {
instant_background_change = false
}
}
withAnimation(.linear(duration:0.25)) {
selecting_tab.toggle()
}
}
}.transition(.opacity)
} else {
HStack {
tool_bar_rectangle_button(action: {new_tab_action?()}, button_type: .blue_gray, content: "New Page").padding(.leading, 5)
Spacer()
tool_bar_rectangle_button(action: {
offset = CGPoint(0,0)
if instant_background_change == false {
instant_background_change = true
} else {
DispatchQueue.main.asyncAfter(deadline:.now()+0.25) {
instant_background_change = false
}
}
withAnimation(.linear(duration:0.25)) {
selecting_tab.toggle()
}}, button_type: .blue, content: "Done").padding(.trailing, 5)
}.transition(.opacity)
}
} else {
HStack {
tool_bar_rectangle_button(action: {editing_bookmarks_action?()}, button_type: is_editing_bookmarks == false ? .blue_gray : .blue, content: is_editing_bookmarks == false ? " Edit " : "Done").padding(.leading, 5)
Spacer()
if is_editing_bookmarks == true {
tool_bar_rectangle_button(action: {}, button_type: .blue_gray, content: "New Folder").padding(.trailing, 5)
}
}.transition(.opacity)
}
}
}
}
struct safari_title_bar : View {
@Binding var forward_or_backward: Bool
@Binding var current_nav_view: String
@Binding var url_search: String
@Binding var google_search: String
@Binding var editing_state_url: String
@Binding var editing_state_google: String
@State var progress: Double = 1.0
var webViewStore: WebViewStore
var current_webpage_title: String
var no_right_padding: Bool?
private let gradient = LinearGradient([.white, .white], to: .trailing)
private let cancel_gradient = LinearGradient([(color: Color(red: 164/255, green: 175/255, blue:191/255), location: 0), (color: Color(red: 124/255, green: 141/255, blue:164/255), location: 0.51), (color: Color(red: 113/255, green: 131/255, blue:156/255), location: 0.51), (color: Color(red: 112/255, green: 130/255, blue:155/255), location: 1)], from: .top, to: .bottom)
var body :some View {
GeometryReader{ geometry in
ZStack {
LinearGradient(gradient: Gradient(stops: [.init(color:Color(red: 180/255, green: 191/255, blue: 205/255), location: 0.0), .init(color:Color(red: 136/255, green: 155/255, blue: 179/255), location: 0.49), .init(color:Color(red: 128/255, green: 149/255, blue: 175/255), location: 0.49), .init(color:Color(red: 110/255, green: 133/255, blue: 162/255), location: 1.0)]), startPoint: .top, endPoint: .bottom).border_bottom(width: 1, edges: [.bottom], color: Color(red: 45/255, green: 48/255, blue: 51/255)).innerShadowBottom(color: Color(red: 230/255, green: 230/255, blue: 230/255), radius: 0.025)
VStack {
Spacer()
HStack {
Spacer()
Text(current_webpage_title != "" ? current_webpage_title : "Untitled").foregroundColor(Color(red: 62/255, green: 69/255, blue: 79/255)).font(.custom("Helvetica Neue Bold", fixedSize: 14)).shadow(color: Color.white.opacity(0.51), radius: 0, x: 0.0, y: 2/3).padding([.leading, .trailing], 24)
Spacer()
}
HStack {
if editing_state_google == "None" {
ZStack {
RoundedRectangle(cornerRadius:6).fill(progress == 1.0 ? LinearGradient([(color: Color.white, location: 0)], from: .top, to: .bottom) : progress == 0.0 ? LinearGradient([(color: Color.white, location: 0)], from: .top, to: .bottom) : LinearGradient([(color: Color(red: 129/255, green: 184/255, blue:237/255), location: 0), (color: Color(red: 96/255, green: 168/255, blue:236/255), location: 0.50), (color: Color(red: 71/255, green: 148/255, blue:233/255), location: 0.50), (color: Color(red: 104/255, green: 194/255, blue:233/255), location: 1)], from: .top, to: .bottom)).brightness(0.1).frame(width:editing_state_url == "None" ? geometry.size.width*2/3-18.5 : geometry.size.width - 79.5).padding(.leading, 2.5).padding(.trailing, 1)
url_search_bar(url_search: $url_search, editing_state_url: $editing_state_url, progress: $progress, webViewStore: webViewStore).frame(width:editing_state_url == "None" ? geometry.size.width*2/3-15 : geometry.size.width - 76)
}
}
if editing_state_url == "None" {
ZStack {
google_search_bar(google_search: $google_search, url_search: $url_search, editing_state_google: $editing_state_google, webViewStore: webViewStore).frame(width:editing_state_google == "None" ? geometry.size.width*1/3: geometry.size.width - 76)
}
}
if editing_state_url != "None" || editing_state_google != "None" {
Spacer().frame(width:69)
}
}
Spacer()
}
}
}.overlay(
ZStack {
if editing_state_google != "None" || editing_state_url != "None" {
VStack {
Spacer()
HStack {
Spacer()
Button(action:{hideKeyboard()}) {
ZStack {
Text("Cancel").font(.custom("Helvetica Neue Bold", fixedSize: 13.25)).foregroundColor(.white).shadow(color: Color.black.opacity(0.75), radius: 1, x: 0, y: -0.25)
}.frame(width: 59, height: 32).ps_innerShadow(.roundedRectangle(5.5, cancel_gradient), radius:0.8, offset: CGPoint(0, 0.6), intensity: 0.7).shadow(color: Color.white.opacity(0.28), radius: 0, x: 0, y: 0.8)
.padding(.trailing, 12)
}.frame(width: 59, height: 32).padding(.top, 34)
}
}.transition(.asymmetric(insertion: .move(edge: .trailing), removal: .move(edge: .trailing)))
}
})
}
}
struct url_search_bar: View {
@Binding var url_search: String
@Binding var editing_state_url: String
@Binding var progress: Double
var webViewStore: WebViewStore
private let gradient = LinearGradient([.white, .white], to: .trailing)
private let cancel_gradient = LinearGradient([(color: Color(red: 164/255, green: 175/255, blue:191/255), location: 0), (color: Color(red: 124/255, green: 141/255, blue:164/255), location: 0.51), (color: Color(red: 113/255, green: 131/255, blue:156/255), location: 0.51), (color: Color(red: 112/255, green: 130/255, blue:155/255), location: 1)], from: .top, to: .bottom)
var body: some View {
HStack {
Spacer(minLength: 5)
HStack (alignment: .center,
spacing: 10) {
TextField ("", text: $url_search, onEditingChanged: { (changed) in
if changed {
withAnimation() {
if url_search.count == 0 {
editing_state_url = "Active_Empty"
} else {
editing_state_url = "Active"
}
}
} else {
withAnimation() {
editing_state_url = "None"
}
}
}) {
//print(url_search, "here 0")
if url_search.hasPrefix("https://") || url_search.hasPrefix("http://") {
guard let url = URL(string: "\(url_search)") else { return }
// print("here 1")
self.webViewStore.webView.load(URLRequest(url: url))
url_search = self.webViewStore.webView.url?.relativeString ?? ""
} else if url_search.contains("www") {
guard let url = URL(string: "https://\(url_search)") else { return }
// print("here 2")
self.webViewStore.webView.load(URLRequest(url: url))
url_search = self.webViewStore.webView.url?.relativeString ?? ""
} else {
guard let url = URL(string: "https://\(url_search)") else { return }
// print("here 3")
self.webViewStore.webView.load(URLRequest(url: url))
url_search = self.webViewStore.webView.url?.relativeString ?? ""
//searchTextOnGoogle(urlString)
}
withAnimation() {
editing_state_url = "None"
}
}.keyboardType(.URL).disableAutocorrection(true).autocapitalization(.none).foregroundColor(editing_state_url == "None" ? Color(red: 102/255, green: 102/255, blue: 102/255) : Color.black)
if editing_state_url == "Active", url_search.count != 0 {
Button(action:{url_search = ""}) {
Image("UITextFieldClearButton")
}.fixedSize()
}
if editing_state_url == "None" {
Button(action:{webViewStore.webView.reload()}) {
Image("AddressViewReload")
}
}
}
.padding([.top,.bottom], 5)
.padding(.leading, 5)
.cornerRadius(6)
Spacer(minLength: 8)
} .ps_innerShadow(.roundedRectangle(6, LinearGradient([(color: Color.clear, location: progress != 1 ? progress : 0), (color: .white, progress != 1 ? progress : 0)], from: .leading, to: .trailing)), radius:1.8, offset: CGPoint(0, 1), intensity: 0.5).strokeRoundedRectangle(6, Color(red: 84/255, green: 108/255, blue: 138/255), lineWidth: 0.65).padding(.leading, 2.5).padding(.trailing, 1).onReceive(webViewStore.objectWillChange) {_ in
progress = webViewStore.webView.estimatedProgress
}
}
}
extension View {
public func introspectTextField2(customize: @escaping (UITextField) -> ()) -> some View {
return inject(UIKitIntrospectionView(
selector: { introspectionView in
guard let viewHost = Introspect.findViewHost(from: introspectionView) else {
return nil
}
return Introspect.previousSibling(containing: UITextField.self, from: viewHost)
},
customize: customize
))
}
}
struct google_search_bar: View {
@Binding var google_search: String
@Binding var url_search: String
@Binding var editing_state_google: String
var webViewStore: WebViewStore
private let gradient = LinearGradient([.white, .white], to: .trailing)
private let cancel_gradient = LinearGradient([(color: Color(red: 164/255, green: 175/255, blue:191/255), location: 0), (color: Color(red: 124/255, green: 141/255, blue:164/255), location: 0.51), (color: Color(red: 113/255, green: 131/255, blue:156/255), location: 0.51), (color: Color(red: 112/255, green: 130/255, blue:155/255), location: 1)], from: .top, to: .bottom)
var body: some View {
HStack {
Spacer(minLength: 5)
HStack (alignment: .center,
spacing: 10) {
TextField ("Google", text: $google_search, onEditingChanged: { (changed) in
if changed {
withAnimation() {
if editing_state_google.isEmpty {
editing_state_google = "Active_Empty"
} else {
editing_state_google = "Active"
}
}
} else {
withAnimation() {
editing_state_google = "None"
}
}
}) {
let link = google_search.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
guard let url = URL(string: "https://google.com/search?q=\(String(link ?? ""))") else { return }
self.webViewStore.webView.load(URLRequest(url:url))
url_search = self.webViewStore.webView.url?.relativeString ?? ""
google_search = ""
withAnimation() {
editing_state_google = "None"
}
}.keyboardType(.alphabet).disableAutocorrection(true)
if google_search.count != 0, editing_state_google == "Active" {
Button(action:{google_search = ""}) {
Image("UITextFieldClearButton")
}.fixedSize()
}
}
.padding([.top,.bottom], 5)
.padding(.leading, 5)
.cornerRadius(40)
Spacer(minLength: 8)
} .ps_innerShadow(.capsule(gradient), radius:1.8, offset: CGPoint(0, 1), intensity: 0.6).strokeCapsule(Color(red: 84/255, green: 108/255, blue: 138/255), lineWidth: 0.65).padding(.leading, 1).padding(.trailing, 2.5)
}
}
//
//struct Safari_Previews: PreviewProvider {
// static var previews: some View {
// Safari()
// }
//}
//
//
| 61.1 | 764 | 0.510225 |
0922e0c2f06e91dba74ba215bb3aeb10474e0d7f | 2,299 | /**
* Copyright (c) 2019 Razeware LLC
*
* 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.
*
* Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
* distribute, sublicense, create a derivative work, and/or sell copies of the
* Software in any work that is designed, intended, or marketed for pedagogical or
* instructional purposes related to programming, coding, application development,
* or information technology. Permission for such use, copying, modification,
* merger, publication, distribution, sublicensing, creation of derivative works,
* or sale is expressly withheld.
*
* 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
class Camera: Node {
var fovDegrees: Float = 50
var fovRadians: Float {
return fovDegrees.degreesToRadians
}
var aspect: Float = 1
var near: Float = 0.01
var far: Float = 100
var projectionMatrix: float4x4 {
return float4x4(projectionFov: fovRadians,
near: near,
far: far,
aspect: aspect)
}
var viewMatrix: float4x4 {
let translateMatrix = float4x4(translation: position).inverse
let rotateMatrix = float4x4(rotation: rotation)
let scaleMatrix = float4x4(scaling: scale)
return translateMatrix * scaleMatrix * rotateMatrix
}
}
| 41.053571 | 82 | 0.732927 |
89313cfb737fefcb4f06a194cf497f2ade0b22f2 | 3,564 | //
// WorkoutReader.swift
// WODVaultPackageDescription
//
// Created by Merrick Sapsford on 29/11/2017.
//
import Foundation
import FeedKit
import Dispatch
protocol WorkoutReaderDelegate: class {
func reader(_ reader: WorkoutReader, didBeginUpdating feedUrl: URL)
func reader(_ reader: WorkoutReader, didFailToUpdate feedUrl: URL, becauseOf error: Error)
func reader(_ reader: WorkoutReader, didLoad workouts: [Workout], newDiscoveries: Int)
}
enum WorkoutReaderError: Error {
case noResults
}
class WorkoutReader {
// MARK: Properties
let boxId: String
let url: URL
private lazy var parser = FeedParser(URL: self.url)
weak var delegate: WorkoutReaderDelegate?
// MARK: Init
init?(boxId: String, url: String) {
guard let url = URL(string: url) else {
return nil
}
self.boxId = boxId
self.url = url
}
// MARK: Updating
func update() {
delegate?.reader(self, didBeginUpdating: url)
parser?.parseAsync(queue: DispatchQueue.global(qos: .userInitiated), result: { (result) in
if let error = result.error {
self.delegate?.reader(self, didFailToUpdate: self.url, becauseOf: error)
} else {
switch result {
case .rss(let feed):
self.parseResults(feed.items,
success:
{ (workouts, newDiscoveries) in
self.delegate?.reader(self, didLoad: workouts, newDiscoveries: newDiscoveries)
}, failure: { (error) in
self.delegate?.reader(self, didFailToUpdate: self.url, becauseOf: error)
})
default:()
}
}
})
}
private func parseResults(_ results: [RSSFeedItem]?,
success: (_ workouts: [Workout], _ discoveries: Int) -> Void,
failure: (Error) -> Void) {
guard let results = results else {
failure(WorkoutReaderError.noResults)
return
}
var workouts = [Workout]()
var discoveryCount: Int = 0
for result in results {
if let workout = Workout.fromRSSFeedItem(result, boxId: self.boxId) {
do {
let existing = try Workout.makeQuery().filter("guid", .equals, workout.guid).first()
if existing == nil { // ignore duplicates
try workout.save()
discoveryCount += 1
}
workouts.append(workout)
} catch {
failure(error)
}
}
}
success(workouts, discoveryCount)
}
}
private extension Workout {
static func fromRSSFeedItem(_ item: RSSFeedItem, boxId: String) -> Workout? {
guard let guid = item.guid?.value,
let title = item.title,
let description = item.description,
let pubDate = item.pubDate,
let link = item.link else {
return nil
}
return Workout(guid: guid,
boxId: boxId,
title: title,
publishDate: pubDate,
rawDescription: description,
link: link)
}
}
| 29.94958 | 106 | 0.509259 |
91a768f4d2ad52f9ea3b3dee3d100fc247697dad | 2,049 | // Threading.swift
//
// Copyright (c) 2015 Jens Ravens (http://jensravens.de)
//
// 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
#if os(Linux)
public typealias TimeInterval = Double
import Dispatch
#endif
/**
This error is thrown if the signal doesn't complete within the specified timeout in a wait function.
*/
public struct TimeoutError: Error {
internal init() {}
}
public extension Observable {
/**
Wait until the observable updates the next time. This will block the current thread until
there is a new value.
*/
func wait(_ timeout: TimeInterval? = nil) throws -> T {
let group = DispatchGroup()
var value: T! = nil
group.enter()
subscribe {
value = $0
group.leave()
}
let timestamp = timeout.map{ DispatchTime.now() + $0 } ?? DispatchTime.distantFuture
if group.wait(timeout: timestamp) != .success {
throw TimeoutError()
}
return value
}
}
| 35.947368 | 104 | 0.695949 |
c1dfa26238da058ea22f96a1d2c4868a1b1c729d | 582 | //
// SubscribedPodcastsListBarButtonsView.swift
// PodcastPlayer
//
// Created by Paul Wood on 7/15/19.
// Copyright © 2019 Paul Wood. All rights reserved.
//
import SwiftUI
import SFSafeSymbols
struct SubscribedPodcastsListBarButtonsView : View {
var body: some View {
PresentationLink2(destination: Flow.playerView()) {
Image(systemSymbol: .playCircleFill)
}
}
}
#if DEBUG
struct SubscribedPodcastsListBarButtonsView_Previews : PreviewProvider {
static var previews: some View {
SubscribedPodcastsListBarButtonsView()
}
}
#endif
| 22.384615 | 72 | 0.723368 |
b9d1e4c73f894312e2ae25cba410bafc7d76955b | 2,760 | //
// SceneDelegate.swift
// SwiftUI32
//
// Created by Rohit Saini on 09/08/20.
// Copyright © 2020 AccessDenied. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.461538 | 147 | 0.706159 |
e40c955e2d901719bb20a18fe03a95bd0eb69ebf | 982 | //
// ChangeRemoteControlIDMessageBodyTests.swift
// MinimedKitTests
//
// Copyright © 2018 Pete Schwamb. All rights reserved.
//
import XCTest
@testable import MinimedKit
class ChangeRemoteControlIDMessageBodyTests: XCTestCase {
func testEncodeOneRemote() {
let expected = Data(hexadecimalString: "0700313233343536000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")!
let body = ChangeRemoteControlIDMessageBody(id: Data(bytes: [1, 2, 3, 4, 5, 6]), index: 0)!
XCTAssertEqual(expected, body.txData, body.txData.hexadecimalString)
}
func testEncodeZeroRemotes() {
let expected = Data(hexadecimalString: "07022d2d2d2d2d2d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")!
let body = ChangeRemoteControlIDMessageBody(id: nil, index: 2)!
XCTAssertEqual(expected, body.txData)
}
}
| 33.862069 | 181 | 0.774949 |
3984879f54afa09a51f136b8bf2cb64063dcb7ee | 1,019 | //
// _1_CATransformLayerTests.swift
// 21-CATransformLayerTests
//
// Created by FlyElephant on 2017/8/21.
// Copyright © 2017年 FlyElephant. All rights reserved.
//
import XCTest
@testable import _1_CATransformLayer
class _1_CATransformLayerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.540541 | 111 | 0.650638 |
4ba86d3b34aaca96c4f7bca96b87d15c6a1ce40e | 4,156 | //
// PageContentView.swift
// DYZB
//
// Created by shizhi on 17/2/23.
// Copyright © 2017年 shizhi. All rights reserved.
//
import UIKit
private let kContentCellID = "ContentCellID"
protocol PageContentViewDelegate : class {
func pageContentView(contentView : PageContentView, progress : CGFloat)
}
class PageContentView: UIView {
// MARK:- 定义属性
private var childVcs: [UIViewController]
private weak var parentVc: UIViewController?
weak var delegate : PageContentViewDelegate?
private var isForbidScrollDelegate : Bool = false
//懒加载
private lazy var collectionview: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = self.bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .Horizontal
// 2.创建UICollectionView
let collectionview = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
collectionview.backgroundColor = UIColor.whiteColor()
// collectionview.bounces = false
collectionview.dataSource = self
collectionview.delegate = self
collectionview.pagingEnabled = true
collectionview.scrollsToTop = false
collectionview.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: kContentCellID)
return collectionview
}()
// MARK:- 构造函数
init(frame: CGRect, childVcs: [UIViewController], parentVc: UIViewController?) {
self.childVcs = childVcs
self.parentVc = parentVc
super.init(frame: frame)
//设置UI
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK:设置UI界面
extension PageContentView {
//设置UI
private func setUpUI() {
//将所有的子控制器添加到父控制器中
for childVc in childVcs {
parentVc?.addChildViewController(childVc)
}
//添加collectionview
addSubview(collectionview)
collectionview.frame = bounds
}
}
//MARK:UICollectionView数据源方法
extension PageContentView: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionview.dequeueReusableCellWithReuseIdentifier(kContentCellID, forIndexPath: indexPath)
//移除之前的view
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
//添加当前的view
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//MARK:UICollectionView代理方法
extension PageContentView: UICollectionViewDelegate {
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
isForbidScrollDelegate = false
}
func scrollViewDidScroll(scrollView: UIScrollView) {
// 0.判断是否是点击事件
if isForbidScrollDelegate { return }
// 1.定义获取需要的数据
var progress : CGFloat = 0
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
// 1.计算progress
progress = currentOffsetX / scrollViewW
// 3.将progress传递给titleView
delegate?.pageContentView(self, progress: progress)
}
}
// MARK:- 对外暴露的方法
extension PageContentView {
func setCurrentIndex(currentIndex : Int) {
// 1.记录需要进制执行代理方法
isForbidScrollDelegate = true
// 2.滚动正确的位置
let offsetX = CGFloat(currentIndex) * collectionview.frame.width
collectionview.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
}
}
| 26.138365 | 130 | 0.638835 |
2929ad5eb3b9d2449e3559c7650360b6e0384fdf | 22,127 | import Basic
import Foundation
import TuistCore
import XcodeProj
/// Protocol that defines the interface of the schemes generation.
protocol SchemesGenerating {
/// Generates the schemes for the project targets.
///
/// - Parameters:
/// - project: Project manifest.
/// - generatedProject: Generated Xcode project.
/// - Throws: A FatalError if the generation of the schemes fails.
func generateTargetSchemes(project: Project,
generatedProject: GeneratedProject) throws
}
final class SchemesGenerator: SchemesGenerating {
/// Default last upgrade version for generated schemes.
private static let defaultLastUpgradeVersion = "1010"
/// Default version for generated schemes.
private static let defaultVersion = "1.3"
/// Generates the schemes for the project manifest.
///
/// - Parameters:
/// - project: Project manifest.
/// - generatedProject: Generated Xcode project.
/// - Throws: A FatalError if the generation of the schemes fails.
func generateTargetSchemes(project: Project, generatedProject: GeneratedProject) throws {
/// Generate scheme from manifest
try project.schemes.forEach { scheme in
try generateScheme(scheme: scheme, project: project, generatedProject: generatedProject)
}
/// Generate scheme for every targets in Project that is not defined in Manifest
let buildConfiguration = defaultDebugBuildConfigurationName(in: project)
try project.targets.forEach { target in
if !project.schemes.contains(where: { $0.name == target.name }) {
let scheme = Scheme(name: target.name,
shared: true,
buildAction: BuildAction(targets: [target.name]),
testAction: TestAction(targets: [target.name], configurationName: buildConfiguration),
runAction: RunAction(configurationName: buildConfiguration,
executable: target.productName,
arguments: Arguments(environment: target.environment)))
try generateScheme(scheme: scheme,
project: project,
generatedProject: generatedProject)
}
}
}
/// Generates the scheme.
///
/// - Parameters:
/// - scheme: Scheme manifest.
/// - project: Project manifest.
/// - generatedProject: Generated Xcode project.
/// - Throws: An error if the generation fails.
func generateScheme(scheme: Scheme,
project: Project,
generatedProject: GeneratedProject) throws {
let schemesDirectory = try createSchemesDirectory(projectPath: generatedProject.path, shared: scheme.shared)
let schemePath = schemesDirectory.appending(component: "\(scheme.name).xcscheme")
let generatedBuildAction = schemeBuildAction(scheme: scheme, project: project, generatedProject: generatedProject)
let generatedTestAction = schemeTestAction(scheme: scheme, project: project, generatedProject: generatedProject)
let generatedLaunchAction = schemeLaunchAction(scheme: scheme, project: project, generatedProject: generatedProject)
let generatedProfileAction = schemeProfileAction(scheme: scheme, project: project, generatedProject: generatedProject)
let scheme = XCScheme(name: scheme.name,
lastUpgradeVersion: SchemesGenerator.defaultLastUpgradeVersion,
version: SchemesGenerator.defaultVersion,
buildAction: generatedBuildAction,
testAction: generatedTestAction,
launchAction: generatedLaunchAction,
profileAction: generatedProfileAction,
analyzeAction: schemeAnalyzeAction(for: project),
archiveAction: schemeArchiveAction(for: project))
try scheme.write(path: schemePath.path, override: true)
}
/// Returns the build action for the project scheme.
///
/// - Parameters:
/// - project: Project manifest.
/// - generatedProject: Generated Xcode project.
/// - graph: Dependencies graph.
/// - Returns: Scheme build action.
func projectBuildAction(project: Project,
generatedProject: GeneratedProject,
graph: Graphing) -> XCScheme.BuildAction {
let targets = project.sortedTargetsForProjectScheme(graph: graph)
let entries: [XCScheme.BuildAction.Entry] = targets.map { (target) -> XCScheme.BuildAction.Entry in
let pbxTarget = generatedProject.targets[target.name]!
let buildableReference = targetBuildableReference(target: target,
pbxTarget: pbxTarget,
projectName: generatedProject.name)
var buildFor: [XCScheme.BuildAction.Entry.BuildFor] = []
if target.product.testsBundle {
buildFor.append(.testing)
} else {
buildFor.append(contentsOf: [.analyzing, .archiving, .profiling, .running, .testing])
}
return XCScheme.BuildAction.Entry(buildableReference: buildableReference,
buildFor: buildFor)
}
return XCScheme.BuildAction(buildActionEntries: entries,
parallelizeBuild: true,
buildImplicitDependencies: true)
}
/// Generates the test action for the project scheme.
///
/// - Parameters:
/// - project: Project manifest.
/// - generatedProject: Generated Xcode project.
/// - Returns: Scheme test action.
func projectTestAction(project: Project,
generatedProject: GeneratedProject) -> XCScheme.TestAction {
var testables: [XCScheme.TestableReference] = []
let testTargets = project.targets.filter { $0.product.testsBundle }
testTargets.forEach { target in
let pbxTarget = generatedProject.targets[target.name]!
let reference = targetBuildableReference(target: target,
pbxTarget: pbxTarget,
projectName: generatedProject.name)
let testable = XCScheme.TestableReference(skipped: false,
buildableReference: reference)
testables.append(testable)
}
let buildConfiguration = defaultDebugBuildConfigurationName(in: project)
return XCScheme.TestAction(buildConfiguration: buildConfiguration,
macroExpansion: nil,
testables: testables)
}
/// Generates the scheme test action.
///
/// - Parameters:
/// - scheme: Scheme manifest.
/// - project: Project manifest.
/// - generatedProject: Generated Xcode project.
/// - Returns: Scheme test action.
func schemeTestAction(scheme: Scheme,
project: Project,
generatedProject: GeneratedProject) -> XCScheme.TestAction? {
guard let testAction = scheme.testAction else { return nil }
var testables: [XCScheme.TestableReference] = []
var preActions: [XCScheme.ExecutionAction] = []
var postActions: [XCScheme.ExecutionAction] = []
testAction.targets.forEach { name in
guard let target = project.targets.first(where: { $0.name == name }), target.product.testsBundle else { return }
guard let pbxTarget = generatedProject.targets[name] else { return }
let reference = self.targetBuildableReference(target: target,
pbxTarget: pbxTarget,
projectName: generatedProject.name)
let testable = XCScheme.TestableReference(skipped: false, buildableReference: reference)
testables.append(testable)
}
preActions = schemeExecutionActions(actions: testAction.preActions,
project: project,
generatedProject: generatedProject)
postActions = schemeExecutionActions(actions: testAction.postActions,
project: project,
generatedProject: generatedProject)
var args: XCScheme.CommandLineArguments?
var environments: [XCScheme.EnvironmentVariable]?
if let arguments = testAction.arguments {
args = XCScheme.CommandLineArguments(arguments: commandlineArgruments(arguments.launch))
environments = environmentVariables(arguments.environment)
}
let shouldUseLaunchSchemeArgsEnv: Bool = args == nil && environments == nil
return XCScheme.TestAction(buildConfiguration: testAction.configurationName,
macroExpansion: nil,
testables: testables,
preActions: preActions,
postActions: postActions,
shouldUseLaunchSchemeArgsEnv: shouldUseLaunchSchemeArgsEnv,
codeCoverageEnabled: testAction.coverage,
commandlineArguments: args,
environmentVariables: environments)
}
/// Generates the scheme build action.
///
/// - Parameters:
/// - scheme: Scheme manifest.
/// - project: Project manifest.
/// - generatedProject: Generated Xcode project.
/// - Returns: Scheme build action.
func schemeBuildAction(scheme: Scheme,
project: Project,
generatedProject: GeneratedProject) -> XCScheme.BuildAction? {
guard let buildAction = scheme.buildAction else { return nil }
let buildFor: [XCScheme.BuildAction.Entry.BuildFor] = [
.analyzing, .archiving, .profiling, .running, .testing,
]
var entries: [XCScheme.BuildAction.Entry] = []
var preActions: [XCScheme.ExecutionAction] = []
var postActions: [XCScheme.ExecutionAction] = []
buildAction.targets.forEach { name in
guard let target = project.targets.first(where: { $0.name == name }) else { return }
guard let pbxTarget = generatedProject.targets[name] else { return }
let buildableReference = self.targetBuildableReference(target: target,
pbxTarget: pbxTarget,
projectName: generatedProject.name)
entries.append(XCScheme.BuildAction.Entry(buildableReference: buildableReference, buildFor: buildFor))
}
preActions = schemeExecutionActions(actions: buildAction.preActions,
project: project,
generatedProject: generatedProject)
postActions = schemeExecutionActions(actions: buildAction.postActions,
project: project,
generatedProject: generatedProject)
return XCScheme.BuildAction(buildActionEntries: entries,
preActions: preActions,
postActions: postActions,
parallelizeBuild: true,
buildImplicitDependencies: true)
}
/// Generates the scheme launch action.
///
/// - Parameters:
/// - scheme: Scheme manifest.
/// - project: Project manifest.
/// - generatedProject: Generated Xcode project.
/// - Returns: Scheme launch action.
func schemeLaunchAction(scheme: Scheme,
project: Project,
generatedProject: GeneratedProject) -> XCScheme.LaunchAction? {
guard var target = project.targets.first(where: { $0.name == scheme.buildAction?.targets.first }) else { return nil }
if let executable = scheme.runAction?.executable {
guard let runableTarget = project.targets.first(where: { $0.name == executable }) else { return nil }
target = runableTarget
}
guard let pbxTarget = generatedProject.targets[target.name] else { return nil }
var buildableProductRunnable: XCScheme.BuildableProductRunnable?
var macroExpansion: XCScheme.BuildableReference?
let buildableReference = targetBuildableReference(target: target, pbxTarget: pbxTarget, projectName: generatedProject.name)
if target.product.runnable {
buildableProductRunnable = XCScheme.BuildableProductRunnable(buildableReference: buildableReference, runnableDebuggingMode: "0")
} else {
macroExpansion = buildableReference
}
var commandlineArguments: XCScheme.CommandLineArguments?
var environments: [XCScheme.EnvironmentVariable]?
if let arguments = scheme.runAction?.arguments {
commandlineArguments = XCScheme.CommandLineArguments(arguments: commandlineArgruments(arguments.launch))
environments = environmentVariables(arguments.environment)
}
let buildConfiguration = scheme.runAction?.configurationName ?? defaultDebugBuildConfigurationName(in: project)
return XCScheme.LaunchAction(runnable: buildableProductRunnable,
buildConfiguration: buildConfiguration,
macroExpansion: macroExpansion,
commandlineArguments: commandlineArguments,
environmentVariables: environments)
}
/// Generates the scheme profile action for a given target.
///
/// - Parameters:
/// - target: Target manifest.
/// - pbxTarget: Xcode native target.
/// - projectName: Project name with .xcodeproj extension.
/// - Returns: Scheme profile action.
func schemeProfileAction(scheme: Scheme,
project: Project,
generatedProject: GeneratedProject) -> XCScheme.ProfileAction? {
guard var target = project.targets.first(where: { $0.name == scheme.buildAction?.targets.first }) else { return nil }
if let executable = scheme.runAction?.executable {
guard let runableTarget = project.targets.first(where: { $0.name == executable }) else { return nil }
target = runableTarget
}
guard let pbxTarget = generatedProject.targets[target.name] else { return nil }
var buildableProductRunnable: XCScheme.BuildableProductRunnable?
var macroExpansion: XCScheme.BuildableReference?
let buildableReference = targetBuildableReference(target: target, pbxTarget: pbxTarget, projectName: generatedProject.name)
if target.product.runnable {
buildableProductRunnable = XCScheme.BuildableProductRunnable(buildableReference: buildableReference, runnableDebuggingMode: "0")
} else {
macroExpansion = buildableReference
}
let buildConfiguration = defaultReleaseBuildConfigurationName(in: project)
return XCScheme.ProfileAction(buildableProductRunnable: buildableProductRunnable,
buildConfiguration: buildConfiguration,
macroExpansion: macroExpansion)
}
/// Returns the scheme pre/post actions.
///
/// - Parameters:
/// - actions: pre/post action manifest.
/// - project: Project manifest.
/// - generatedProject: Generated Xcode project.
/// - Returns: Scheme actions.
func schemeExecutionActions(actions: [ExecutionAction],
project: Project,
generatedProject: GeneratedProject) -> [XCScheme.ExecutionAction] {
/// Return Buildable Reference for Scheme Action
func schemeBuildableReference(targetName: String?, project: Project, generatedProject: GeneratedProject) -> XCScheme.BuildableReference? {
guard let targetName = targetName else { return nil }
guard let target = project.targets.first(where: { $0.name == targetName }) else { return nil }
guard let pbxTarget = generatedProject.targets[targetName] else { return nil }
return targetBuildableReference(target: target, pbxTarget: pbxTarget, projectName: generatedProject.name)
}
var schemeActions: [XCScheme.ExecutionAction] = []
actions.forEach { action in
let schemeAction = XCScheme.ExecutionAction(scriptText: action.scriptText,
title: action.title,
environmentBuildable: nil)
schemeAction.environmentBuildable = schemeBuildableReference(targetName: action.target,
project: project,
generatedProject: generatedProject)
schemeActions.append(schemeAction)
}
return schemeActions
}
/// Returns the scheme commandline argument passed on launch
///
/// - Parameters:
/// - environments: commandline argument keys.
/// - Returns: XCScheme.CommandLineArguments.CommandLineArgument.
func commandlineArgruments(_ arguments: [String: Bool]) -> [XCScheme.CommandLineArguments.CommandLineArgument] {
return arguments.map { key, enabled in
XCScheme.CommandLineArguments.CommandLineArgument(name: key, enabled: enabled)
}
}
/// Returns the scheme environment variables
///
/// - Parameters:
/// - environments: environment variables
/// - Returns: XCScheme.EnvironmentVariable.
func environmentVariables(_ environments: [String: String]) -> [XCScheme.EnvironmentVariable] {
return environments.map { key, value in
XCScheme.EnvironmentVariable(variable: key, value: value, enabled: true)
}
}
/// Returns the scheme buildable reference for a given target.
///
/// - Parameters:
/// - target: Target manifest.
/// - pbxTarget: Xcode native target.
/// - projectName: Project name with the .xcodeproj extension.
/// - Returns: Buildable reference.
func targetBuildableReference(target: Target, pbxTarget: PBXNativeTarget, projectName: String) -> XCScheme.BuildableReference {
return XCScheme.BuildableReference(referencedContainer: "container:\(projectName)",
blueprint: pbxTarget,
buildableName: target.productNameWithExtension,
blueprintName: target.name,
buildableIdentifier: "primary")
}
/// Returns the scheme analyze action
///
/// - Returns: Scheme analyze action.
func schemeAnalyzeAction(for project: Project) -> XCScheme.AnalyzeAction {
let buildConfiguration = defaultDebugBuildConfigurationName(in: project)
return XCScheme.AnalyzeAction(buildConfiguration: buildConfiguration)
}
/// Returns the scheme archive action
///
/// - Returns: Scheme archive action.
func schemeArchiveAction(for project: Project) -> XCScheme.ArchiveAction {
let buildConfiguration = defaultReleaseBuildConfigurationName(in: project)
return XCScheme.ArchiveAction(buildConfiguration: buildConfiguration,
revealArchiveInOrganizer: true)
}
/// Creates the directory where the schemes are stored inside the project.
/// If the directory exists it does not re-create it.
///
/// - Parameters:
/// - projectPath: Path to the Xcode project.
/// - shared: Scheme should be shared or not
/// - Returns: Path to the schemes directory.
/// - Throws: A FatalError if the creation of the directory fails.
private func createSchemesDirectory(projectPath: AbsolutePath, shared: Bool = true) throws -> AbsolutePath {
var path: AbsolutePath!
if shared {
path = projectPath.appending(RelativePath("xcshareddata/xcschemes"))
} else {
let username = NSUserName()
path = projectPath.appending(RelativePath("xcuserdata/\(username).xcuserdatad/xcschemes"))
}
if !FileHandler.shared.exists(path) {
try FileHandler.shared.createFolder(path)
}
return path
}
private func defaultDebugBuildConfigurationName(in project: Project) -> String {
let debugConfiguration = project.settings.defaultDebugBuildConfiguration()
let buildConfiguration = debugConfiguration ?? project.settings.configurations.keys.first
return buildConfiguration?.name ?? BuildConfiguration.debug.name
}
private func defaultReleaseBuildConfigurationName(in project: Project) -> String {
let releaseConfiguration = project.settings.defaultReleaseBuildConfiguration()
let buildConfiguration = releaseConfiguration ?? project.settings.configurations.keys.first
return buildConfiguration?.name ?? BuildConfiguration.release.name
}
}
| 48.95354 | 146 | 0.603742 |
3aafee0b7c46ee3e5f95960678c50167aa1abb6c | 559 | //
// FeedSpec.swift
// FeedlyKit
//
// Created by Hiroki Kumamoto on 1/18/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import FeedlyKit
import Quick
import Nimble
import SwiftyJSON
class FeedSpec: QuickSpec {
override func spec() {
describe("a feed") {
it ("should be constructed with json") {
let json = JSON(SpecHelper.fixtureJSONObject(fixtureNamed: "feed")!)
let feed: Feed = Feed(json: json)
expect(feed).notTo(beNil())
}
}
}
}
| 21.5 | 84 | 0.586762 |
76d390531abf56783c6831fe7304e45e16fd85ca | 3,664 | import UIKit
protocol ViewControllerProtocol: AnyObject {
func show(models: [CustomModel])
}
final class CustomViewController: UIViewController {
private lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout())
collectionView.register(Cell.self, forCellWithReuseIdentifier: "Cell")
collectionView.layer.borderColor = UIColor.black.cgColor
collectionView.layer.borderWidth = 2
collectionView.clipsToBounds = false
collectionView.backgroundColor = .white
return collectionView
}()
private var presenter: PresenterProtocol
private var dataSource: DataSource<CustomModel>?
init(presenter: PresenterProtocol) {
self.presenter = presenter
super.init(nibName: nil, bundle: nil)
self.presenter.view = self
setupView()
}
override func viewDidLoad() {
super.viewDidLoad()
presenter.fetchData()
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func createLayout() -> UICollectionViewLayout {
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(150))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: 2)
let spacing = CGFloat(10)
group.interItemSpacing = .fixed(spacing)
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = spacing
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)
let layout = UICollectionViewCompositionalLayout(section: section)
return layout
}
private func setupView() {
view.backgroundColor = .lightGray
configureHierarchy()
configureConstraints()
}
private func configureHierarchy() {
view.addSubview(collectionView)
}
private func configureConstraints() {
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true
collectionView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5).isActive = true
collectionView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
}
extension CustomViewController: ViewControllerProtocol {
func show(models: [CustomModel]) {
dataSource = .make(for: models)
// dataSource?.delegate = self
collectionView.dataSource = dataSource
collectionView.prefetchDataSource = dataSource
}
}
// extension ViewController: DataSourceDelegate {
// func fetchData(for model: CustomModel, with cell: Cell) {
// presenter.fetchData(for: model, with: cell)
// }
//
// func checkIfHasAlreadyFetchedData(for model: CustomModel) -> DisplayData<CustomModel>? {
// presenter.checkIfHasAlreadyFetchedData(for: model.identifier)
// }
//
// func fetchAsync(for indexPaths: [IndexPath]) {
// presenter.fetchAsync(for: indexPaths)
// }
//
// func cancelFetch(for indexPaths: [IndexPath]) {
// presenter.cancelFetch(for: indexPaths)
// }
// }
| 36.64 | 125 | 0.700873 |
e947a1a7970e0dfe48f810c6c70e8c2514bbd2d1 | 523 | //
// Bundle.swift
// Assessment
//
import Foundation
extension Bundle {
var applicationName: String? {
return infoDictionary?["CFBundleName"] as? String
}
var applicationDisplayName: String? {
return infoDictionary?["CFBundleDisplayName"] as? String
}
var releaseVersionNumber: String? {
return infoDictionary?["CFBundleShortVersionString"] as? String
}
var buildVersionNumber: String? {
return infoDictionary?["CFBundleVersion"] as? String
}
}
| 22.73913 | 71 | 0.66348 |
db87cdd4f235dbdec0fa27a5addc43d61c47270e | 22,968 | //
// Request.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary.
public protocol RequestAdapter {
/// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result.
///
/// - parameter urlRequest: The URL request to adapt.
///
/// - throws: An `Error` if the adaptation encounters an error.
///
/// - returns: The adapted `URLRequest`.
func adapt(_ urlRequest: URLRequest) throws -> URLRequest
}
// MARK: -
/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not.
public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void
/// A type that determines whether a request should be retried after being executed by the specified session manager
/// and encountering an error.
public protocol RequestRetrier {
/// Determines whether the `Request` should be retried by calling the `completion` closure.
///
/// This operation is fully asychronous. Any amount of time can be taken to determine whether the request needs
/// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
/// cleaned up after.
///
/// - parameter manager: The session manager the request was executed on.
/// - parameter request: The request that failed due to the encountered error.
/// - parameter error: The error encountered when executing the request.
/// - parameter completion: The completion closure to be executed when retry decision has been determined.
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion)
}
// MARK: -
protocol TaskConvertible {
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask
}
/// A dictionary of headers to apply to a `URLRequest`.
public typealias HTTPHeaders = [String: String]
// MARK: -
/// Responsible for sending a request and receiving the response and associated data from the server, as well as
/// managing its underlying `URLSessionTask`.
open class Request {
// MARK: Helper Types
/// A closure executed when monitoring upload or download progress of a request.
public typealias ProgressHandler = (Progress) -> Void
enum RequestTask {
case data(TaskConvertible?, URLSessionTask?)
case download(TaskConvertible?, URLSessionTask?)
case upload(TaskConvertible?, URLSessionTask?)
case stream(TaskConvertible?, URLSessionTask?)
}
// MARK: Properties
/// The delegate for the underlying task.
open internal(set) var delegate: TaskDelegate {
get {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
return taskDelegate
}
set {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
taskDelegate = newValue
}
}
/// The underlying task.
open var task: URLSessionTask? { return delegate.task }
/// The session belonging to the underlying task.
open let session: URLSession
/// The request sent or to be sent to the server.
open var request: URLRequest? { return task?.originalRequest }
/// The response received from the server, if any.
open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse }
/// The number of times the request has been retried.
open internal(set) var retryCount: UInt = 0
let originalTask: TaskConvertible?
var startTime: CFAbsoluteTime?
var endTime: CFAbsoluteTime?
var validations: [() -> Void] = []
private var taskDelegate: TaskDelegate
private var taskDelegateLock = NSLock()
// MARK: Lifecycle
init(session: URLSession, requestTask: RequestTask, error: Error? = nil) {
self.session = session
switch requestTask {
case .data(let originalTask, let task):
taskDelegate = DataTaskDelegate(task: task)
self.originalTask = originalTask
case .download(let originalTask, let task):
taskDelegate = DownloadTaskDelegate(task: task)
self.originalTask = originalTask
case .upload(let originalTask, let task):
taskDelegate = UploadTaskDelegate(task: task)
self.originalTask = originalTask
case .stream(let originalTask, let task):
taskDelegate = TaskDelegate(task: task)
self.originalTask = originalTask
}
delegate.error = error
delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() }
}
// MARK: Authentication
/// Associates an HTTP Basic credential with the request.
///
/// - parameter user: The user.
/// - parameter password: The password.
/// - parameter persistence: The URL credential persistence. `.ForSession` by default.
///
/// - returns: The request.
@discardableResult
open func authenticate(
user: String,
password: String,
persistence: URLCredential.Persistence = .forSession)
-> Self
{
let credential = URLCredential(user: user, password: password, persistence: persistence)
return authenticate(usingCredential: credential)
}
/// Associates a specified credential with the request.
///
/// - parameter credential: The credential.
///
/// - returns: The request.
@discardableResult
open func authenticate(usingCredential credential: URLCredential) -> Self {
delegate.credential = credential
return self
}
/// Returns a base64 encoded basic authentication credential as an authorization header tuple.
///
/// - parameter user: The user.
/// - parameter password: The password.
///
/// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise.
open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? {
guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }
let credential = data.base64EncodedString(options: [])
return (key: "Authorization", value: "Basic \(credential)")
}
// MARK: State
/// Resumes the request.
open func resume() {
guard let task = task else { delegate.queue.isSuspended = false ; return }
if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
task.resume()
NotificationCenter.default.post(
name: Notification.Name.Task.DidResume,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Suspends the request.
open func suspend() {
guard let task = task else { return }
task.suspend()
NotificationCenter.default.post(
name: Notification.Name.Task.DidSuspend,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Cancels the request.
open func cancel() {
guard let task = task else { return }
task.cancel()
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
}
// MARK: - CustomStringConvertible
extension Request: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes the HTTP method and URL, as
/// well as the response status code if a response has been received.
open var description: String {
var components: [String] = []
if let HTTPMethod = request?.httpMethod {
components.append(HTTPMethod)
}
if let urlString = request?.url?.absoluteString {
components.append(urlString)
}
if let response = response {
components.append("(\(response.statusCode))")
}
return components.joined(separator: " ")
}
}
// MARK: - CustomDebugStringConvertible
extension Request: CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, in the form of a cURL command.
open var debugDescription: String {
return cURLRepresentation()
}
func cURLRepresentation() -> String {
var components = ["$ curl -i"]
guard let request = self.request,
let url = request.url,
let host = url.host
else {
return "$ curl command could not be created"
}
if let httpMethod = request.httpMethod, httpMethod != "GET" {
components.append("-X \(httpMethod)")
}
if let credentialStorage = self.session.configuration.urlCredentialStorage {
let protectionSpace = URLProtectionSpace(
host: host,
port: url.port ?? 0,
protocol: url.scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
for credential in credentials {
components.append("-u \(credential.user!):\(credential.password!)")
}
} else {
if let credential = delegate.credential {
components.append("-u \(credential.user!):\(credential.password!)")
}
}
}
if session.configuration.httpShouldSetCookies {
if
let cookieStorage = session.configuration.httpCookieStorage,
let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
{
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" }
components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"")
}
}
var headers: [AnyHashable: Any] = [:]
if let additionalHeaders = session.configuration.httpAdditionalHeaders {
for (field, value) in additionalHeaders where field != AnyHashable("Cookie") {
headers[field] = value
}
}
if let headerFields = request.allHTTPHeaderFields {
for (field, value) in headerFields where field != "Cookie" {
headers[field] = value
}
}
for (field, value) in headers {
components.append("-H \"\(field): \(value)\"")
}
if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(url.absoluteString)\"")
return components.joined(separator: " \\\n\t")
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDataTask`.
open class DataRequest: Request {
// MARK: Helper Types
struct Requestable: TaskConvertible {
let urlRequest: URLRequest
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let urlRequest = try self.urlRequest.adapt(using: adapter)
return queue.syncResult { session.dataTask(with: urlRequest) }
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The progress of fetching the response data from the server for the request.
open var progress: Progress { return dataDelegate.progress }
var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate }
// MARK: Stream
/// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
///
/// This closure returns the bytes most recently received from the server, not including data from previous calls.
/// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
/// also important to note that the server data in any `Response` object will be `nil`.
///
/// - parameter closure: The code to be executed periodically during the lifecycle of the request.
///
/// - returns: The request.
@discardableResult
open func stream(closure: ((Data) -> Void)? = nil) -> Self {
dataDelegate.dataStream = closure
return self
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
dataDelegate.progressHandler = (closure, queue)
return self
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`.
open class DownloadRequest: Request {
// MARK: Helper Types
/// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
/// destination URL.
public struct DownloadOptions: OptionSet {
/// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
public let rawValue: UInt
/// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0)
/// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1)
/// Creates a `DownloadFileDestinationOptions` instance with the specified raw value.
///
/// - parameter rawValue: The raw bitmask value for the option.
///
/// - returns: A new log level instance.
public init(rawValue: UInt) {
self.rawValue = rawValue
}
}
/// A closure executed once a download request has successfully completed in order to determine where to move the
/// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
/// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
/// the options defining how the file should be moved.
public typealias DownloadFileDestination = (
_ temporaryURL: URL,
_ response: HTTPURLResponse)
-> (destinationURL: URL, options: DownloadOptions)
enum Downloadable: TaskConvertible {
case request(URLRequest)
case resumeData(Data)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .request(urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.syncResult { session.downloadTask(with: urlRequest) }
case let .resumeData(resumeData):
task = queue.syncResult { session.downloadTask(withResumeData: resumeData) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The resume data of the underlying download task if available after a failure.
open var resumeData: Data? { return downloadDelegate.resumeData }
/// The progress of downloading the response data from the server for the request.
open var progress: Progress { return downloadDelegate.progress }
var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate }
// MARK: State
/// Cancels the request.
open override func cancel() {
downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task as Any]
)
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
downloadDelegate.progressHandler = (closure, queue)
return self
}
// MARK: Destination
/// Creates a download file destination closure which uses the default file manager to move the temporary file to a
/// file URL in the first available directory with the specified search path directory and search path domain mask.
///
/// - parameter directory: The search path directory. `.DocumentDirectory` by default.
/// - parameter domain: The search path domain mask. `.UserDomainMask` by default.
///
/// - returns: A download file destination closure.
open class func suggestedDownloadDestination(
for directory: FileManager.SearchPathDirectory = .documentDirectory,
in domain: FileManager.SearchPathDomainMask = .userDomainMask)
-> DownloadFileDestination
{
return { temporaryURL, response in
let directoryURLs = FileManager.default.urls(for: directory, in: domain)
if !directoryURLs.isEmpty {
return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [])
}
return (temporaryURL, [])
}
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`.
open class UploadRequest: DataRequest {
// MARK: Helper Types
enum Uploadable: TaskConvertible {
case data(Data, URLRequest)
case file(URL, URLRequest)
case stream(InputStream, URLRequest)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .data(data, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.syncResult { session.uploadTask(with: urlRequest, from: data) }
case let .file(url, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.syncResult { session.uploadTask(with: urlRequest, fromFile: url) }
case let .stream(_, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.syncResult { session.uploadTask(withStreamedRequest: urlRequest) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The progress of uploading the payload to the server for the upload request.
open var uploadProgress: Progress { return uploadDelegate.uploadProgress }
var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate }
// MARK: Upload Progress
/// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to
/// the server.
///
/// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress
/// of data being read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is sent to the server.
///
/// - returns: The request.
@discardableResult
open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
uploadDelegate.uploadProgressHandler = (closure, queue)
return self
}
}
// MARK: -
#if !os(watchOS)
/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`.
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open class StreamRequest: Request {
enum Streamable: TaskConvertible {
case stream(hostName: String, port: Int)
case netService(NetService)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
let task: URLSessionTask
switch self {
case let .stream(hostName, port):
task = queue.syncResult { session.streamTask(withHostName: hostName, port: port) }
case let .netService(netService):
task = queue.syncResult { session.streamTask(with: netService) }
}
return task
}
}
}
#endif
| 37.225284 | 131 | 0.645202 |
e538baea4d43124d79d4477f9e1ae9e922fb48ee | 2,733 | //
// MonsterWidget.swift
// UhooiPicBookWidgets
//
// Created by uhooi on 2020/11/09.
//
import WidgetKit
import SwiftUI
import FirebaseCore
private struct MonsterProvider {
typealias Entry = MonsterEntry
private let monstersRepository: MonstersRepository
private let imageCacheManager: ImageCacheManagerProtocol
init(
imageCacheManager: ImageCacheManagerProtocol,
monstersRepository: MonstersRepository = MonstersFirebaseClient.shared
) {
self.imageCacheManager = imageCacheManager
self.monstersRepository = monstersRepository
}
}
struct MonsterWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(
kind: "Monster",
provider: MonsterProvider(
imageCacheManager: ImageCacheManager()
)
) { entry in
MonsterEntryView(entry: entry)
}
.configurationDisplayName("Configuration display name")
.description("Description")
.supportedFamilies([.systemSmall, .systemMedium])
}
init() {
FirebaseApp.configure()
}
}
extension MonsterProvider: TimelineProvider {
func placeholder(in context: Context) -> Entry {
.createDefault()
}
func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) {
completion(.createDefault())
}
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
Task {
var entries: [Entry] = []
do {
let monsters = try await monstersRepository.loadMonsters()
let currentDate = Date()
var hourOffset = 0
for monster in monsters.sorted(by: { $0.order < $1.order }) {
guard let iconUrl = URL(string: monster.iconUrlString) else {
continue
}
let icon = try await imageCacheManager.cacheImage(imageUrl: iconUrl)
guard let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate) else {
fatalError("Fail to unwrap `entryDate`. hourOffset: \(hourOffset), currentDate: \(currentDate)")
}
let description = monster.description.replacingOccurrences(of: "\\n", with: "\n")
let entry = Entry(date: entryDate, name: monster.name, description: description, icon: icon)
entries.append(entry)
hourOffset += 1
}
} catch {
print(error)
}
completion(Timeline(entries: entries, policy: .atEnd))
}
}
}
| 32.535714 | 123 | 0.592023 |
461bed07e3ce36c99b5a7026c068eb14452d5845 | 1,433 | #if os(OSX)
import AppKit
#else
import UIKit
#endif
/// A color representation containing representations of the `red`, `blue`, `green` and `alpha` values.
public struct SKRGBARepresentation : Equatable, Codable {
public let red : CGFloat
public let green : CGFloat
public let blue : CGFloat
public let alpha : CGFloat
/// Initializes and returns a `UIColor` object using the specified `SKRGBARepresentation`.
public var color : UIColor {
return UIColor(representation: self)
}
/// Initializes and returns a `SKRGBARepresentation` object.
public init(red : CGFloat, green : CGFloat, blue : CGFloat, alpha : CGFloat = 1) {
self.red = red
self.green = green
self.blue = blue
self.alpha = alpha
}
/// Initializes and returns a `SKRGBARepresentation` object.
public init(bitRepresentation : SK8BitRGBARepresentation) {
self.red = CGFloat(bitRepresentation.red)/255
self.green = CGFloat(bitRepresentation.green)/255
self.blue = CGFloat(bitRepresentation.blue)/255
self.alpha = CGFloat(bitRepresentation.alpha)/255
}
public static func ==(left : SKRGBARepresentation, right : SKRGBARepresentation) -> Bool {
return abs(left.red - right.red) < 0.01 && abs(left.green - right.green) < 0.01 && abs(left.blue - right.blue) < 0.01 && abs(left.alpha - right.alpha) < 0.01
}
}
| 36.74359 | 165 | 0.661549 |
629d758cf7efdd6ff81036b3ec748a081cda2e32 | 10,771 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
class TestNSDictionary : XCTestCase {
func test_BasicConstruction() {
let dict = NSDictionary()
let dict2: NSDictionary = ["foo": "bar"]
XCTAssertEqual(dict.count, 0)
XCTAssertEqual(dict2.count, 1)
}
func test_description() {
let d1: NSDictionary = [ "foo": "bar", "baz": "qux"]
XCTAssertTrue(d1.description == "{\n baz = qux;\n foo = bar;\n}" ||
d1.description == "{\n foo = bar;\n baz = qux;\n}")
let d2: NSDictionary = ["1" : ["1" : ["1" : "1"]]]
XCTAssertEqual(d2.description, "{\n 1 = {\n 1 = {\n 1 = 1;\n };\n };\n}")
}
func test_HeterogeneousConstruction() {
let dict2: NSDictionary = [
"foo": "bar",
1 : 2
]
XCTAssertEqual(dict2.count, 2)
XCTAssertEqual(dict2["foo"] as? String, "bar")
XCTAssertEqual(dict2[1] as? NSNumber, NSNumber(value: 2))
}
func test_ArrayConstruction() {
let objects = ["foo", "bar", "baz"]
let keys: [NSString] = ["foo", "bar", "baz"]
let dict = NSDictionary(objects: objects, forKeys: keys)
XCTAssertEqual(dict.count, 3)
}
func test_enumeration() {
let dict : NSDictionary = ["foo" : "bar", "whiz" : "bang", "toil" : "trouble"]
let e = dict.keyEnumerator()
var keys = Set<String>()
keys.insert((e.nextObject()! as! String))
keys.insert((e.nextObject()! as! String))
keys.insert((e.nextObject()! as! String))
XCTAssertNil(e.nextObject())
XCTAssertNil(e.nextObject())
XCTAssertEqual(keys, ["foo", "whiz", "toil"])
let o = dict.objectEnumerator()
var objs = Set<String>()
objs.insert((o.nextObject()! as! String))
objs.insert((o.nextObject()! as! String))
objs.insert((o.nextObject()! as! String))
XCTAssertNil(o.nextObject())
XCTAssertNil(o.nextObject())
XCTAssertEqual(objs, ["bar", "bang", "trouble"])
}
func test_sequenceType() {
let dict : NSDictionary = ["foo" : "bar", "whiz" : "bang", "toil" : "trouble"]
var result = [String:String]()
for (key, value) in dict {
result[key as! String] = (value as! String)
}
XCTAssertEqual(result, ["foo" : "bar", "whiz" : "bang", "toil" : "trouble"])
}
func test_equality() {
let dict1 = NSDictionary(dictionary: [
"foo":"bar",
"whiz":"bang",
"toil":"trouble",
])
let dict2 = NSDictionary(dictionary: [
"foo":"bar",
"whiz":"bang",
"toil":"trouble",
])
let dict3 = NSDictionary(dictionary: [
"foo":"bar",
"whiz":"bang",
"toil":"troubl",
])
XCTAssertTrue(dict1 == dict2)
XCTAssertTrue(dict1.isEqual(dict2))
XCTAssertTrue(dict1.isEqual(to: [
"foo":"bar",
"whiz":"bang",
"toil":"trouble",
]))
XCTAssertEqual(dict1.hash, dict2.hash)
XCTAssertEqual(dict1.hashValue, dict2.hashValue)
XCTAssertFalse(dict1 == dict3)
XCTAssertFalse(dict1.isEqual(dict3))
XCTAssertFalse(dict1.isEqual(to:[
"foo":"bar",
"whiz":"bang",
"toil":"troubl",
]))
XCTAssertFalse(dict1.isEqual(nil))
XCTAssertFalse(dict1.isEqual(NSObject()))
let nestedDict1 = NSDictionary(dictionary: [
"key.entities": [
["key": 0]
]
])
let nestedDict2 = NSDictionary(dictionary: [
"key.entities": [
["key": 1]
]
])
XCTAssertFalse(nestedDict1 == nestedDict2)
XCTAssertFalse(nestedDict1.isEqual(nestedDict2))
XCTAssertFalse(nestedDict1.isEqual(to: [
"key.entities": [
["key": 1]
]
]))
}
func test_copying() {
let inputDictionary : NSDictionary = ["foo" : "bar", "whiz" : "bang", "toil" : "trouble"]
let copy: NSDictionary = inputDictionary.copy() as! NSDictionary
XCTAssertTrue(inputDictionary === copy)
let dictMutableCopy = inputDictionary.mutableCopy() as! NSMutableDictionary
let dictCopy2 = dictMutableCopy.copy() as! NSDictionary
XCTAssertTrue(type(of: dictCopy2) === NSDictionary.self)
XCTAssertFalse(dictMutableCopy === dictCopy2)
XCTAssertTrue(dictMutableCopy == dictCopy2)
}
func test_mutableCopying() {
let inputDictionary : NSDictionary = ["foo" : "bar", "whiz" : "bang", "toil" : "trouble"]
let dictMutableCopy1 = inputDictionary.mutableCopy() as! NSMutableDictionary
XCTAssertTrue(type(of: dictMutableCopy1) === NSMutableDictionary.self)
XCTAssertFalse(inputDictionary === dictMutableCopy1)
XCTAssertTrue(inputDictionary == dictMutableCopy1)
let dictMutableCopy2 = dictMutableCopy1.mutableCopy() as! NSMutableDictionary
XCTAssertTrue(type(of: dictMutableCopy2) === NSMutableDictionary.self)
XCTAssertFalse(dictMutableCopy2 === dictMutableCopy1)
XCTAssertTrue(dictMutableCopy2 == dictMutableCopy1)
}
func test_writeToFile() {
let testFilePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 256))
if let _ = testFilePath {
let d1: NSDictionary = [ "foo": "bar", "baz": "qux"]
let isWritten = d1.write(toFile: testFilePath!, atomically: true)
if isWritten {
do {
let plistDoc = try XMLDocument(contentsOf: URL(fileURLWithPath: testFilePath!, isDirectory: false), options: [])
XCTAssert(plistDoc.rootElement()?.name == "plist")
let plist = try PropertyListSerialization.propertyList(from: plistDoc.xmlData, options: [], format: nil) as! [String: Any]
XCTAssert((plist["foo"] as? String) == d1["foo"] as? String)
XCTAssert((plist["baz"] as? String) == d1["baz"] as? String)
} catch {
XCTFail("Failed to read and parse XMLDocument")
}
} else {
XCTFail("Write to file failed")
}
removeTestFile(testFilePath!)
} else {
XCTFail("Temporary file creation failed")
}
}
func test_initWithContentsOfFile() {
let testFilePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 256))
if let _ = testFilePath {
let d1: NSDictionary = ["Hello":["world":"again"]]
let isWritten = d1.write(toFile: testFilePath!, atomically: true)
if(isWritten) {
let dict = NSDictionary(contentsOfFile: testFilePath!)
XCTAssert(dict == d1)
} else {
XCTFail("Write to file failed")
}
removeTestFile(testFilePath!)
} else {
XCTFail("Temporary file creation failed")
}
}
func test_settingWithStringKey() {
let dict = NSMutableDictionary()
// has crashed in the past
dict["stringKey"] = "value"
}
func test_valueForKey() {
let dict: NSDictionary = ["foo": "bar"]
let result = dict.value(forKey: "foo")
XCTAssertEqual(result as? String, "bar")
}
func test_valueForKeyWithNestedDict() {
let dict: NSDictionary = ["foo": ["bar": "baz"]]
let result = dict.value(forKey: "foo")
let expectedResult: NSDictionary = ["bar": "baz"]
XCTAssertEqual(result as? NSDictionary, expectedResult)
}
private func createTestFile(_ path: String, _contents: Data) -> String? {
let tempDir = NSTemporaryDirectory() + "TestFoundation_Playground_" + NSUUID().uuidString + "/"
do {
try FileManager.default.createDirectory(atPath: tempDir, withIntermediateDirectories: false, attributes: nil)
if FileManager.default.createFile(atPath: tempDir + "/" + path, contents: _contents,
attributes: nil) {
return tempDir + path
} else {
return nil
}
} catch {
return nil
}
}
private func removeTestFile(_ location: String) {
try? FileManager.default.removeItem(atPath: location)
}
func test_sharedKeySets() {
let keys: [NSCopying] = [ "a" as NSString, "b" as NSString, 1 as NSNumber, 2 as NSNumber ]
let keySet = NSDictionary.sharedKeySet(forKeys: keys)
let dictionary = NSMutableDictionary(sharedKeySet: keySet)
dictionary["a" as NSString] = "w"
XCTAssertEqual(dictionary["a" as NSString] as? String, "w")
dictionary["b" as NSString] = "x"
XCTAssertEqual(dictionary["b" as NSString] as? String, "x")
dictionary[1 as NSNumber] = "y"
XCTAssertEqual(dictionary[1 as NSNumber] as? String, "y")
dictionary[2 as NSNumber] = "z"
XCTAssertEqual(dictionary[2 as NSNumber] as? String, "z")
// Keys not in the key set must be supported.
dictionary["c" as NSString] = "h"
XCTAssertEqual(dictionary["c" as NSString] as? String, "h")
dictionary[3 as NSNumber] = "k"
XCTAssertEqual(dictionary[3 as NSNumber] as? String, "k")
}
static var allTests: [(String, (TestNSDictionary) -> () throws -> Void)] {
return [
("test_BasicConstruction", test_BasicConstruction),
("test_ArrayConstruction", test_ArrayConstruction),
("test_description", test_description),
("test_enumeration", test_enumeration),
("test_equality", test_equality),
("test_copying", test_copying),
("test_mutableCopying", test_mutableCopying),
("test_writeToFile", test_writeToFile),
("test_initWithContentsOfFile", test_initWithContentsOfFile),
("test_settingWithStringKey", test_settingWithStringKey),
("test_valueForKey", test_valueForKey),
("test_valueForKeyWithNestedDict", test_valueForKeyWithNestedDict),
("test_sharedKeySets", test_sharedKeySets),
]
}
}
| 39.025362 | 142 | 0.569956 |
03824b2884e641ce60e1cfe8f2fa59900cbfcb09 | 236 | //
// MySegmentsFetcherProtocol.swift
// Pods
//
// Created by Brian Sztamfater on 5/10/17.
//
//
import Foundation
@objc public protocol MySegmentsFetcher {
func fetchAll() -> [String]
func forceRefresh()
}
| 13.111111 | 43 | 0.635593 |
fef207620c1064e8a8b8cfd9ab1c70c6518dedd0 | 2,886 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// 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.
//
public protocol DictionaryIndexType {
typealias Key: Hashable
typealias Value
func successor() -> DictionaryIndex<Key, Value>
}
extension DictionaryIndex: DictionaryIndexType {}
extension ObservableCollectionType where Index: DictionaryIndexType, Collection == Dictionary<Index.Key, Index.Value> {
public func indexForKey(key: Index.Key) -> Collection.Index? {
return collection.indexForKey(key)
}
public subscript (key: Index.Key) -> Index.Value? {
get {
return collection[key]
}
set {
if let value = newValue {
updateValue(value, forKey: key)
} else {
removeValueForKey(key)
}
}
}
public subscript (position: Collection.Index) -> Collection.Generator.Element {
get {
return collection[position]
}
}
public func updateValue(value: Index.Value, forKey key: Index.Key) -> Index.Value? {
var new = collection
if let index = new.indexForKey(key) {
let oldValue = new.updateValue(value, forKey: key)
next(ObservableCollectionEvent(collection: new, inserts: [], deletes: [], updates: [index]))
return oldValue
} else {
new.updateValue(value, forKey: key)
let index = new.indexForKey(key)!
next(ObservableCollectionEvent(collection: new, inserts: [index], deletes: [], updates: []))
return nil
}
}
public func removeValueForKey(key: Index.Key) -> Index.Value? {
if let index = collection.indexForKey(key) {
var new = collection
let oldValue = new.removeValueForKey(key)
next(ObservableCollectionEvent(collection: new, inserts: [], deletes: [index], updates: []))
return oldValue
} else {
return nil
}
}
}
| 34.357143 | 119 | 0.69508 |
e912ba1b8b67decad445383642225bec93b9d4dc | 3,209 | //
// ViewController.swift
// tip_calculator
//
// Created by Abdullah Ridwan on 7/29/20.
// Copyright © 2020 Abdullah Ridwan. All rights reserved.
//
import UIKit
import Lottie
class ViewController: UIViewController {
@IBOutlet weak var TotalLabel: UILabel!
@IBOutlet weak var BillField: UITextField!
@IBOutlet weak var TipLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var splitLabel: UITextField!
@IBOutlet weak var eachPersonLabel: UILabel!
@IBOutlet weak var progressAnimationView: AnimationView!
@IBOutlet weak var card1: UIView!
@IBOutlet weak var card2: UIView!
override func viewDidLoad() {
super.viewDidLoad()
progressAnimationView?.loopMode = .loop
progressAnimationView?.animationSpeed = 2
view.addSubview(progressAnimationView!)
progressAnimationView?.play()
//code for card 1 shadow
card1.layer.shadowColor = UIColor.black.cgColor
card1.layer.shadowOpacity = 0.2
card1.layer.shadowOffset = .zero
card1.layer.shadowRadius = 10
card1.layer.shadowPath = UIBezierPath(rect: card1.bounds).cgPath
card1.layer.shouldRasterize = true
card1.layer.cornerRadius = 10;
//cardview.layer.masksToBounds = true;
//code for card 2 shadow
card2.layer.shadowColor = UIColor.black.cgColor
card2.layer.shadowOpacity = 0.2
card2.layer.shadowOffset = .zero
card2.layer.shadowRadius = 10
card2.layer.shadowPath = UIBezierPath(rect: card2.bounds).cgPath
card2.layer.shouldRasterize = true
card2.layer.cornerRadius = 10;
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
progressAnimationView.play()
}
@IBAction func OnTap(_ sender: Any) {
print("Hello")
view.endEditing(true)
}
@IBAction func CalculateTip(_ sender: Any) {
//Get the bill amount
let billAmount = Double(BillField.text!) ?? 0
//Calculate tip and total
let tipPercentages = [0.05, 0.10, 0.15, 0.20, 0.25]
let tip = billAmount * tipPercentages[tipControl.selectedSegmentIndex]
let total = billAmount + tip
//Update tip and total labels
TipLabel.text = String(format: "$%.2f", tip)
TotalLabel.text = String(format: "$%.2f", total)
}
@IBAction func calculateSplit(_ sender: Any) {
//get split amount
let split = Double(splitLabel.text!) ?? 1
//calculate total amount
let billAmount = Double(BillField.text!) ?? 0
let tipPercentages = [0.05, 0.10, 0.15, 0.20, 0.25]
let tip = billAmount * tipPercentages[tipControl.selectedSegmentIndex]
let total = billAmount + tip
//calculate each person pays
let each = total / split
//update each person pays
eachPersonLabel.text = String(format: "$%.2f", each)
}
}
| 25.267717 | 78 | 0.607043 |
28c7e93dc944c50026e34030240c1c600ff92e54 | 229 | import UIKit
let color = UIColor(red: 0.96, green: 0.96, blue: 0.96, alpha: 1.00)
let lightBlue: UIColor = #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1)
//É possível utilizar imageLiteral
| 25.444444 | 107 | 0.720524 |
644e20866639985053972ab54b18f00dbc6fcc2b | 4,043 | //
// HomeViewModel.swift
// Mesa News
//
// Created by João Vitor Duarte Mariucio on 18/04/21.
//
import Foundation
import RxSwiftExt
enum HomeStatus {
case item_destaque_favoritado, `default`
}
protocol HomeViewModelInput {
func proximaPagina()
func encerrarSessao()
func favoritarNoticia(noticia: NoticiaElementCodable)
}
protocol HomeViewModelOutput {
var feedback: BehaviorRelay<HomeStatus> { get set }
var dataSourceNoticias: BehaviorRelay<[NoticiaModel]> { get set }
var dataSourceNoticiasDestaque: BehaviorRelay<[NoticiaModel]> { get set}
}
class HomeViewModel: BaseViewModel, HomeViewModelInput, HomeViewModelOutput {
// MARK: HomeViewModel Outputs
var dataSourceNoticias: BehaviorRelay<[NoticiaModel]> = BehaviorRelay<[NoticiaModel]>(value: [NoticiaModel]())
var dataSourceNoticiasDestaque: BehaviorRelay<[NoticiaModel]> = BehaviorRelay<[NoticiaModel]>(value: [NoticiaModel]())
var feedback: BehaviorRelay<HomeStatus> = BehaviorRelay<HomeStatus>(value: .default)
// MARK: BaseViewModel e functions
var disposable: DisposeBag = DisposeBag()
var mostrarMensagem: BehaviorRelay<String> = BehaviorRelay<String>(value: "")
var isLoading: BehaviorRelay<Bool> = BehaviorRelay<Bool>(value: false)
var model = HomeModel()
func viewDidLoad() {
buscarListaNoticias(page: model.currentPage)
buscarListaNoticiasDestaque()
}
func buscarListaNoticias(page: Int){
NoticiasClient.buscarNoticias(currentPage: page, perPage: model.perPage)
.asObservable()
.subscribe(
onNext: { result in
if let pagination = result.pagination {
self.model.setPagination(pagination)
}
self.adicionarNoticiasDataSource(result.data)
},
onError: { error in
}
).disposed(by: disposable)
}
func buscarListaNoticiasDestaque(){
NoticiasClient.buscarNoticiasDestaque()
.asObservable()
.subscribe(
onNext: { result in
let noticiasMap = result.data.map( { NoticiaModel(codable: $0) } )
self.dataSourceNoticiasDestaque.accept(noticiasMap)
},
onError: { error in
}
).disposed(by: disposable)
}
func adicionarNoticiasDataSource(_ novasNoticias: [NoticiaElementCodable]){
var noticias = dataSourceNoticias.value
let novasNoticiasMap = novasNoticias.map( { NoticiaModel(codable: $0) } )
noticias.append(contentsOf: novasNoticiasMap)
let noticiasOrdenadas = noticias.sorted(by: { $0.publishedAt.compare($1.publishedAt) == .orderedDescending })
model.setNoticias(noticiasOrdenadas)
self.dataSourceNoticias.accept(noticiasOrdenadas)
}
// MARK: HomeViewModel Inputs
func proximaPagina() {
if model.checarSeExisteProximaPagina() {
self.buscarListaNoticias(page: model.nextPage)
}
}
func favoritarNoticia(noticia: NoticiaElementCodable) {
var dataArray = PreferencesHelper.instance.getDataArray(key: Constants.App.Keys.noticias_favoritadas)
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(noticia) {
if !dataArray.contains(encoded) {
dataArray.append(encoded)
}else {
dataArray.removeAll(where: { $0 == encoded })
}
self.feedback.accept(.item_destaque_favoritado)
PreferencesHelper.instance.save(key: Constants.App.Keys.noticias_favoritadas, value: dataArray)
}
}
func encerrarSessao() {
UserSessionHelper.instance.clearSession()
PreferencesHelper.instance.clear()
}
}
| 32.869919 | 122 | 0.619589 |
7a57bfefe593e8f0bf412bcee3263d9fb9721a45 | 6,129 | //
// AppDelegate.swift
// SortiererTest
//
// Created by Udemy on 26.02.15.
// Copyright (c) 2015 benchr. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "de.benchr.SortiererTest" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("SortiererTest", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SortiererTest.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| 54.723214 | 290 | 0.717083 |
e8ab842e57c6c0059edfbcdb8853fc37a2cf6def | 11,307 | import Foundation
import PromiseKit
import ServiceWorker
import ServiceWorkerContainer
import WebKit
public class SWWebViewBridge: NSObject, WKURLSchemeHandler, WKScriptMessageHandler {
static let serviceWorkerRequestMethod = "SW_REQUEST"
static let graftedRequestBodyHeader = "X-Grafted-Request-Body"
static let eventStreamPath = "/___events___"
public typealias Command = (EventStream, AnyObject?) throws -> Promise<Any?>?
public static var routes: [String: Command] = [
"/ServiceWorkerContainer/register": ServiceWorkerContainerCommands.register,
"/ServiceWorkerContainer/getregistration": ServiceWorkerContainerCommands.getRegistration,
"/ServiceWorkerContainer/getregistrations": ServiceWorkerContainerCommands.getRegistrations,
"/ServiceWorkerRegistration/unregister": ServiceWorkerRegistrationCommands.unregister,
"/ServiceWorker/postMessage": ServiceWorkerCommands.postMessage,
"/MessagePort/proxyMessage": MessagePortHandler.proxyMessage
]
/// Track the streams we currently have open, so that when one is stopped we know where
/// it came from
var eventStreams = Set<EventStream>()
public func userContentController(_: WKUserContentController, didReceive message: WKScriptMessage) {
firstly { () -> Promise<Any?> in
print("[swift: SWWebViewBridge] useContentController, didReceive message:" + message.name)
guard let body = message.body as? [String: Any] else {
throw ErrorMessage("Could not parse body")
}
guard let eventStreamID = body["streamID"] as? String, let promiseIndex = body["promiseIndex"] as? Int,
let path = body["path"] as? String, let requestBody = body["body"] as AnyObject? else {
throw ErrorMessage("Required parameters not provided")
}
guard let eventStream = eventStreams.first(where: { $0.id == eventStreamID }) else {
throw ErrorMessage("This stream does not exist")
}
let matchingRoute = SWWebViewBridge.routes.first(where: { $0.key == path })
return (try matchingRoute?.value(eventStream, requestBody) ?? Promise(error: ErrorMessage("Route not found")))
.compactMap { response in
eventStream.sendCustomUpdate(identifier: "promisereturn", object: [
"promiseIndex": promiseIndex,
"response": response
])
}.recover { error -> Promise<Any?> in
eventStream.sendCustomUpdate(identifier: "promisereturn", object: [
"promiseIndex": promiseIndex,
"error": "\(error)"
])
return Promise.value(())
}
}.catch { error in
Log.error?("Failed to parse API request: \(error)")
}
}
@available(iOS 11.0, *)
public func webView(_ webview: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
// WKURLSchemeTask can fail even when using didFailWithError if the task
// has already been closed. We handle that in SWURLSchemeTask but first
// we need to create one. So one first catch:
let modifiedTask: SWURLSchemeTask
do {
modifiedTask = try SWURLSchemeTask(underlyingTask: urlSchemeTask)
} catch {
urlSchemeTask.didFailWithError(error)
return
}
// And now that we've got the task set up, we can run async promises without
// worrying about if the task will fail.
firstly { () -> Promise<Void> in
guard let swWebView = webview as? SWWebView else {
throw ErrorMessage("SWWebViewBridge must be used with an SWWebView")
}
guard let requestURL = modifiedTask.request.url else {
throw ErrorMessage("Task must have a request URL")
}
if requestURL.path == SWWebViewBridge.eventStreamPath {
try self.startEventStreamTask(modifiedTask, webview: swWebView)
// Since the event stream stays alive indefinitely, we just early return
// a void promise
return Promise.value(())
}
// if modifiedTask.request.httpMethod == SWWebViewBridge.serviceWorkerRequestMethod {
// return try self.startServiceWorkerTask(modifiedTask, webview: swWebView)
// }
let request = FetchRequest(url: requestURL)
return firstly { () -> Promise<FetchResponseProtocol?> in
guard let referrer = modifiedTask.referrer else {
return Promise.value(nil)
}
guard let container = swWebView.containerDelegate?.container(swWebView, getContainerFor: referrer) else {
return Promise.value(nil)
}
guard let controller = container.controller else {
return Promise.value(nil)
}
let fetchEvent = FetchEvent(request: request)
return controller.dispatchEvent(fetchEvent)
.then {
try fetchEvent.resolve(in: controller)
}
}
.then { maybeResponse -> Promise<FetchResponseProtocol> in
if let responseExists = maybeResponse {
return Promise.value(responseExists)
} else {
return FetchSession.default.fetch(request)
}
}
.then { response -> Promise<Void> in
let outputStream = try SWURLSchemeTaskOutputStream(task: modifiedTask, response: response)
guard let streamPipe = response.streamPipe else {
throw ErrorMessage("Could not get response stream")
}
try streamPipe.add(stream: outputStream)
return streamPipe.pipe()
}
}
.catch { error in
do {
// try to send the full error, if that fails, just use the native error handling
try modifiedTask.didReceiveHeaders(statusCode: 500)
let errorJSON = try JSONSerialization.data(withJSONObject: ["error": "\(error)"], options: [])
try modifiedTask.didReceive(errorJSON)
try modifiedTask.didFinish()
} catch {
modifiedTask.didFailWithError(error)
}
}
}
// func startServiceWorkerTask(_ task: SWURLSchemeTask, webview: SWWebView) throws -> Promise<Void> {
//
// guard let requestURL = task.request.url else {
// throw ErrorMessage("Cannot start a task with no URL")
// }
//
// guard let referrer = task.referrer else {
// throw ErrorMessage("All non-event stream SW API tasks must send a referer header")
// }
//
// guard let container = webview.containerDelegate?.container(webview, getContainerFor: referrer) else {
// throw ErrorMessage("ServiceWorkerContainer should already exist before any tasks are run")
// }
//
// guard let eventStream = self.eventStreams.first(where: { $0.container == container }) else {
// throw ErrorMessage("Commands must have an event stream attached")
// }
//
// guard let matchingRoute = SWWebViewBridge.routes.first(where: { $0.key == requestURL.path })?.value else {
// // We don't recognise this URL, so we just return a 404.
// try task.didReceiveHeaders(statusCode: 404)
// try task.didFinish()
// return Promise(value: ())
// }
//
// var jsonBody: AnyObject?
// if let body = task.request.httpBody {
// jsonBody = try JSONSerialization.jsonObject(with: body, options: []) as AnyObject
// }
//
// return firstly { () -> Promise<Any?> in
// guard let promise = try matchingRoute(eventStream, jsonBody) else {
// // The task didn't return an async promise, so we can just
// // return immediately
// return Promise(value: nil)
// }
// // Otherwise, wait for the return
// return promise
// }
//
// .then { response in
// guard var encodedResponse = "null".data(using: .utf8) else {
// throw ErrorMessage("Could not create default null response")
// }
// if let responseExists = response {
// encodedResponse = try JSONSerialization.data(withJSONObject: responseExists, options: [])
// }
// try task.didReceiveHeaders(statusCode: 200, headers: [
// "Content-Type": "application/json"
// ])
// try task.didReceive(encodedResponse)
// try task.didFinish()
// return Promise(value: ())
// }
// }
func startEventStreamTask(_ task: SWURLSchemeTask, webview: SWWebView) throws {
guard let containerDelegate = webview.containerDelegate else {
throw ErrorMessage("SWWebView has no containerDelegate set, cannot start service worker functionality")
}
guard let requestURL = task.request.url else {
throw ErrorMessage("Cannot start event stream with no URL")
}
// We send in the path of the current page as a query string param. Let's extract it.
guard let path = URLComponents(url: requestURL, resolvingAgainstBaseURL: true)?
.queryItems?.first(where: { $0.name == "path" })?.value else {
throw ErrorMessage("Could not parse incoming URL")
}
guard let fullPageURL = URL(string: path, relativeTo: requestURL) else {
throw ErrorMessage("Could not parse path-relative URL")
}
let container = try containerDelegate.container(webview, createContainerFor: fullPageURL.absoluteURL)
let newStream = try EventStream(for: task, withContainer: container)
self.eventStreams.insert(newStream)
}
@available(iOS 11.0, *)
public func webView(_ webview: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
guard let existingTask = SWURLSchemeTask.getExistingTask(for: urlSchemeTask) else {
Log.error?("Stopping a task that isn't currently running - this should never happen")
return
}
existingTask.close()
if let stream = self.eventStreams.first(where: { $0.task.hash == existingTask.hash }) {
stream.shutdown()
self.eventStreams.remove(stream)
guard let swWebView = webview as? SWWebView else {
Log.error?("Tried to use SWWebViewBridge with a non-SWWebView class")
return
}
swWebView.containerDelegate?.container(swWebView, freeContainer: stream.container)
}
}
}
| 42.829545 | 122 | 0.586451 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.