repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
orospakr/suppressor | suppressorTests/suppressorTests.swift | 1 | 916 | //
// suppressorTests.swift
// suppressorTests
//
// Created by Andrew Clunis on 2014-11-01.
// Copyright (c) 2014 Andrew Clunis. All rights reserved.
//
import Cocoa
import XCTest
class suppressorTests: 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.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
LacieJiang/Custom-2048 | Custom-2048/Custom-2048/AppDelegate.swift | 1 | 2102 | //
// AppDelegate.swift
// Custom-2048
//
// Created by liyinjiang on 6/17/14.
// Copyright (c) 2014 liyinjiang. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> 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:.
}
}
| bsd-2-clause |
zenangst/Faker | Source/Data/Parser.swift | 1 | 2753 | import SwiftyJSON
public class Parser {
public var locale: String {
didSet {
if locale != oldValue {
loadData()
}
}
}
var data: JSON = []
var provider: Provider
public init(locale: String = Config.defaultLocale) {
self.provider = Provider()
self.locale = locale
loadData()
}
// MARK: - Parsing
public func fetch(key: String) -> String {
var parsed: String = ""
var parts = split(key) {$0 == "."}
if parts.count > 0 {
var keyData = data[locale]["faker"]
let subject = parts[0]
for part in parts {
keyData = keyData[part]
}
if let value = keyData.string {
parsed = value
} else if let array = keyData.arrayObject {
let count = UInt32(array.count)
if let item = array[Int(arc4random_uniform(count))] as? String {
parsed = item
}
}
if parsed.rangeOfString("#{") != nil {
parsed = parse(parsed, forSubject: subject)
}
}
return parsed
}
func parse(template: String, forSubject subject: String) -> String {
var text = ""
let string = template as NSString
let regex = NSRegularExpression(pattern: "(\\(?)#\\{([A-Za-z]+\\.)?([^\\}]+)\\}([^#]+)?",
options: nil,
error: nil)!
let matches = regex.matchesInString(string as String,
options: nil,
range: NSMakeRange(0, string.length)) as! [NSTextCheckingResult]
if matches.count > 0 {
for match in matches {
if match.numberOfRanges < 4 {
continue
}
let prefixRange = match.rangeAtIndex(1)
let subjectRange = match.rangeAtIndex(2)
let methodRange = match.rangeAtIndex(3)
let otherRange = match.rangeAtIndex(4)
if prefixRange.length > 0 {
text += string.substringWithRange(prefixRange)
}
var subjectWithDot = subject + "."
if subjectRange.length > 0 {
subjectWithDot = string.substringWithRange(subjectRange)
}
if methodRange.length > 0 {
let key = subjectWithDot.lowercaseString + string.substringWithRange(methodRange)
text += fetch(key)
}
if otherRange.length > 0 {
text += string.substringWithRange(otherRange)
}
}
} else {
text = template
}
return text
}
// MARK: - Data loading
func loadData() {
if let localeData = provider.dataForLocale(locale) {
data = JSON(data: localeData,
options: NSJSONReadingOptions.AllowFragments,
error: nil)
} else if locale != Config.defaultLocale {
locale = Config.defaultLocale
} else {
fatalError("JSON file for '\(locale)' locale was not found.")
}
}
}
| mit |
xilosada/TravisViewerIOS | TVView/BuildTableViewModeling.swift | 1 | 306 | //
// BuildTableViewModeling.swift
// TravisViewerIOS
//
// Created by X.I. Losada on 09/02/16.
// Copyright © 2016 XiLosada. All rights reserved.
//
import TVModel
import RxSwift
public protocol BuildTableViewModeling {
func getBuilds(repoId: Int) -> Observable<[BuildTableViewCellModeling]>
}
| mit |
mrlegowatch/JSON-to-Swift-Converter | JSON to Swift Converter/ViewController.swift | 1 | 7441 | //
// ViewController.swift
// JSON to Swift Converter
//
// Created by Brian Arnold on 2/20/17.
// Copyright © 2018 Brian Arnold. All rights reserved.
//
import Cocoa
extension NSButton {
var isChecked: Bool {
return self.state == .on
}
}
extension String {
/// Returns an attributed string with the specified color.
func attributed(with color: NSColor) -> NSAttributedString {
let attributes: [NSAttributedStringKey: Any] = [.foregroundColor: color]
return NSMutableAttributedString(string: self, attributes: attributes)
}
/// Returns an attributed string with the Swift "keyword" color.
var attributedKeywordColor: NSAttributedString {
return self.attributed(with: NSColor(calibratedRed: 0.72, green: 0.2, blue: 0.66, alpha: 1.0))
}
/// Returns an attributed string with the Swift "type" color.
var attributedTypeColor: NSAttributedString {
return self.attributed(with: NSColor(calibratedRed: 0.44, green: 0.26, blue: 0.66, alpha: 1.0))
}
/// Returns an attributed string with the Swift "string literal" color.
var attributedStringColor: NSAttributedString {
return self.attributed(with: NSColor(calibratedRed: 0.84, green: 0.19, blue: 0.14, alpha: 1.0))
}
/// Returns an attributed string with the Swift "int literal" color.
var attributedIntColor: NSAttributedString {
return self.attributed(with: NSColor(calibratedRed: 0.16, green: 0.20, blue: 0.83, alpha: 1.0))
}
/// Returns self as an attributed string, for contatenation with other attributed strings.
var attributed: NSAttributedString {
return NSAttributedString(string: self)
}
}
class ViewController: NSViewController {
@IBOutlet weak var declarationLet: NSButton!
@IBOutlet weak var declarationVar: NSButton!
@IBOutlet weak var typeExplicit: NSButton!
@IBOutlet weak var typeOptional: NSButton!
@IBOutlet weak var typeRequired: NSButton!
@IBOutlet weak var addDefaultValue: NSButton!
@IBOutlet weak var supportCodable: NSButton!
@IBOutlet weak var version: NSTextField! {
didSet {
version.stringValue = "Version \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String)"
}
}
@IBOutlet weak var output: NSTextField!
var appSettings = AppSettings()
override func viewDidLoad() {
super.viewDidLoad()
updateControls()
updateOutput()
}
/// Update the controls to match the user defaults settings
func updateControls() {
let isDeclarationLet = appSettings.declaration == .useLet
declarationLet.state = isDeclarationLet ? .on : .off
declarationVar.state = isDeclarationLet ? .off : .on
let typeUnwrapping = appSettings.typeUnwrapping
typeExplicit.state = typeUnwrapping == .explicit ? .on : .off
typeOptional.state = typeUnwrapping == .optional ? .on : .off
typeRequired.state = typeUnwrapping == .required ? .on : .off
addDefaultValue.state = appSettings.addDefaultValue ? .on : .off
supportCodable.state = appSettings.supportCodable ? .on : .off
}
/// Update the output text view to reflect the current settings
func updateOutput() {
let declaration = appSettings.declaration == .useLet ? "let" : "var"
let typeUnwrapping = appSettings.typeUnwrapping == .optional ? "?" : appSettings.typeUnwrapping == .required ? "!" : ""
let outputData = [["user name", "String", "\"\""], ["age", "Int", "0"]]
let outputString = NSMutableAttributedString(string: "")
outputString.beginEditing()
let lineIndent = LineIndent(useTabs: false, indentationWidth: 4, level: 1)
// Add the coding keys (required for example because swiftName doesn't match JSON name)
outputString.append("private enum".attributedKeywordColor)
outputString.append(" CodingKeys: ".attributed)
outputString.append("String".attributedKeywordColor)
outputString.append(", ".attributed)
outputString.append("CodingKey".attributedKeywordColor)
outputString.append(" {\n".attributed)
for item in outputData {
outputString.append("\(lineIndent)".attributed)
outputString.append("case ".attributedKeywordColor)
outputString.append(" \(item[0].swiftName)".attributed)
if item[0] != item[0].swiftName {
outputString.append(" = ".attributed)
outputString.append("\"\(item[0])\"".attributedStringColor)
}
outputString.append("\n".attributed)
}
outputString.append("}\n\n".attributed)
// Add the declarations
for item in outputData {
outputString.append("\(declaration)".attributedKeywordColor)
outputString.append(" \(item[0].swiftName): ".attributed)
outputString.append(": \(item[1])".attributedTypeColor)
outputString.append("\(typeUnwrapping)".attributed)
if appSettings.addDefaultValue {
outputString.append(" = ".attributed)
let value = item[2] == "0" ? "\(item[2])".attributedIntColor : "\(item[2])".attributedStringColor
outputString.append(value)
}
outputString.append("\n".attributed)
}
outputString.append("\n".attributed)
if appSettings.supportCodable {
// Add the init method.
do {//if appSettings.addInit {
outputString.append("init".attributedKeywordColor)
outputString.append("(from decoder: ".attributed)
outputString.append("Decoder".attributedKeywordColor)
outputString.append(") ".attributed)
outputString.append("throws".attributedKeywordColor)
outputString.append(" { ... }\n".attributed)
}
// Add the dictionary variable.
do {//if appSettings.addDictionary {
outputString.append("func encode".attributedKeywordColor)
outputString.append("(to encoder: ".attributed)
outputString.append("Encoder".attributedKeywordColor)
outputString.append(") ".attributed)
outputString.append("throws".attributedKeywordColor)
outputString.append(" { ... }".attributed)
}
}
outputString.endEditing()
output.attributedStringValue = outputString
}
@IBAction func changeDeclaration(_ sender: NSButton) {
let selectedTag = sender.selectedTag()
appSettings.declaration = AppSettings.Declaration(rawValue: selectedTag)!
updateOutput()
}
@IBAction func changeTypeUnwrapping(_ sender: NSButton) {
let selectedTag = sender.selectedTag()
appSettings.typeUnwrapping = AppSettings.TypeUnwrapping(rawValue: selectedTag)!
updateOutput()
}
@IBAction func changeDefaultValue(_ sender: NSButton) {
appSettings.addDefaultValue = sender.isChecked
updateOutput()
}
@IBAction func changeSupportCodable(_ sender: NSButton) {
appSettings.supportCodable = sender.isChecked
updateOutput()
}
}
| mit |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/01957-swift-typechecker-resolvetypeincontext.swift | 1 | 277 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func i<S {
func f {
for c {
}
{
}
}
enum a {
{
}
protocol e : b
{
}
}
protocol b : BooleanType
{
}
struct c
| mit |
flowsprenger/RxLifx-Swift | RxLifxApi/RxLifxApi/Light.swift | 1 | 10987 | /*
Copyright 2017 Florian Sprenger
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 LifxDomain
import RxSwift
public protocol LightSource {
var tick: Observable<Int> { get }
var source: UInt32 { get }
var ioScheduler: SchedulerType { get }
var mainScheduler: SchedulerType { get }
func extensionOf<E>() -> E? where E: LightServiceExtension
var messages: Observable<SourcedMessage> { get }
func sendMessage(light: Light?, data: Data) -> Bool
}
public protocol LightsChangeDispatcher {
func notifyChange(light: Light, property: LightPropertyName, oldValue: Any?, newValue: Any?)
func lightAdded(light: Light)
}
public enum LightPropertyName {
case color
case zones
case power
case label
case hostFirmware
case wifiFirmware
case version
case group
case location
case infraredBrightness
case reachable
}
public class Light: Equatable {
private var disposeBag: CompositeDisposable = CompositeDisposable()
public let lightSource: LightSource
public let lightChangeDispatcher: LightsChangeDispatcher
public let target: UInt64
public let id: String
public var addr: sockaddr?
public var sequence: UInt8 = 0
public static let refreshMutablePropertiesTickModulo = 20
public static let productsSupportingMultiZone = [0, 31, 32, 38]
public static let productsSupportingInfrared = [0, 29, 30, 45, 46]
public static let productsSupportingTile = [55]
public lazy var color: LightProperty<HSBK> = {
LightProperty<HSBK>(light: self, name: .color)
}()
public lazy var zones: LightProperty<MultiZones> = {
LightProperty<MultiZones>(light: self, name: .zones)
}()
public lazy var power: LightProperty<UInt16> = {
LightProperty<UInt16>(light: self, name: .power)
}()
public lazy var label: LightProperty<String> = {
LightProperty<String>(light: self, name: .label)
}()
public lazy var hostFirmware: LightProperty<FirmwareVersion> = {
LightProperty<FirmwareVersion>(light: self, name: .hostFirmware)
}()
public lazy var wifiFirmware: LightProperty<FirmwareVersion> = {
LightProperty<FirmwareVersion>(light: self, name: .wifiFirmware)
}()
public lazy var version: LightProperty<LightVersion> = {
LightProperty<LightVersion>(light: self, name: .version)
}()
public lazy var group: LightProperty<LightGroup> = {
LightProperty<LightGroup>(light: self, name: .group, defaultValue: LightGroup.defaultGroup)
}()
public lazy var location: LightProperty<LightLocation> = {
LightProperty<LightLocation>(light: self, name: .location, defaultValue: LightLocation.defaultLocation)
}()
public lazy var infraredBrightness: LightProperty<UInt16> = {
LightProperty<UInt16>(light: self, name: .infraredBrightness)
}()
public lazy var reachable: LightProperty<Bool> = {
LightProperty<Bool>(light: self, name: .reachable, defaultValue: false)
}()
public var lastSeenAt: Date = Date.distantPast
public var powerState: Bool {
get {
return power.value ?? 0 == 0 ? false : true
}
}
public var supportsMultiZone: Bool {
get {
return Light.productsSupportingMultiZone.contains(Int(version.value?.product ?? 0))
}
}
public var supportsInfrared: Bool {
get {
return Light.productsSupportingInfrared.contains(Int(version.value?.product ?? 0))
}
}
public var supportsTile: Bool {
get {
return Light.productsSupportingTile.contains(Int(version.value?.product ?? 0))
}
}
public init(id: UInt64, lightSource: LightSource, lightChangeDispatcher: LightsChangeDispatcher) {
self.lightSource = lightSource
self.lightChangeDispatcher = lightChangeDispatcher
self.target = id
self.id = id.toLightId()
}
public func dispose() {
disposeBag.dispose()
}
public func getNextSequence() -> UInt8 {
sequence = sequence &+ 1
return sequence
}
public func updateReachability() {
reachable.updateFromClient(value: lastSeenAt.timeIntervalSinceNow > -11)
}
public func attach(observable: GroupedObservable<UInt64, SourcedMessage>) -> Light {
dispose()
disposeBag = CompositeDisposable()
_ = disposeBag.insert(observable.subscribe(onNext: {
(message: SourcedMessage) in
self.addr = message.sourceAddress
self.lastSeenAt = Date()
self.updateReachability()
LightMessageHandler.handleMessage(light: self, message: message.message)
}))
_ = disposeBag.insert(lightSource.tick.subscribe(onNext: {
c in
self.pollState()
self.updateReachability()
if (c % Light.refreshMutablePropertiesTickModulo == 0) {
self.pollMutableProperties()
}
return
}))
pollProperties()
pollState()
return self
}
private func pollState() {
LightGetCommand.create(light: self).fireAndForget()
if (supportsMultiZone) {
MultiZoneGetColorZonesCommand.create(light: self, startIndex: UInt8.min, endIndex: UInt8.max).fireAndForget()
}
if (supportsInfrared) {
LightGetInfraredCommand.create(light: self).fireAndForget()
}
}
private func pollProperties() {
DeviceGetHostFirmwareCommand.create(light: self).fireAndForget()
DeviceGetWifiFirmwareCommand.create(light: self).fireAndForget()
DeviceGetVersionCommand.create(light: self).fireAndForget()
pollMutableProperties()
}
private func pollMutableProperties() {
DeviceGetGroupCommand.create(light: self).fireAndForget()
DeviceGetLocationCommand.create(light: self).fireAndForget()
}
public static func ==(lhs: Light, rhs: Light) -> Bool {
return lhs.target == rhs.target
}
}
public class LightProperty<T: Equatable> {
private var _value: T? = nil
public var value: T? {
get {
return _value
}
}
private let light: Light
private let name: LightPropertyName
private var updatedFromClientAt: Date = Date.distantPast
private let localValueValidityWindow: TimeInterval = -2
init(light: Light, name: LightPropertyName, defaultValue: T? = nil) {
self.light = light
self.name = name
self._value = defaultValue
}
public func updateFromClient(value: T?) {
if (_value != value) {
let oldValue = _value
_value = value
updatedFromClientAt = Date()
light.lightChangeDispatcher.notifyChange(light: light, property: name, oldValue: oldValue, newValue: value)
}
}
public func updateFromDevice(value: T?) {
if (_value != value && !hasRecentlyUpdatedFromClient()) {
let oldValue = _value
_value = value
light.lightChangeDispatcher.notifyChange(light: light, property: name, oldValue: oldValue, newValue: value)
}
}
public func hasRecentlyUpdatedFromClient() -> Bool {
return updatedFromClientAt.timeIntervalSinceNow > localValueValidityWindow
}
}
public class FirmwareVersion: Equatable {
public let build: UInt64
public let version: UInt32
init(build: UInt64, version: UInt32) {
self.build = build
self.version = version
}
public static func ==(lhs: FirmwareVersion, rhs: FirmwareVersion) -> Bool {
return lhs.build == rhs.build && lhs.version == rhs.version
}
}
public class LightVersion: Equatable {
public let vendor: UInt32
public let product: UInt32
public let version: UInt32
init(vendor: UInt32, product: UInt32, version: UInt32) {
self.vendor = vendor
self.product = product
self.version = version
}
public static func ==(lhs: LightVersion, rhs: LightVersion) -> Bool {
return lhs.vendor == rhs.vendor && lhs.product == rhs.product && lhs.version == rhs.version
}
}
public class LightLocation: Equatable {
static let defaultLocation = LightLocation(id: Array(repeating: 48, count: 8), label: "", updatedAt: Date(timeIntervalSince1970: 0))
public let id: [UInt8]
public let label: String
public let updatedAt: Date
public lazy var identifier: String = String(describing: id.map({ UnicodeScalar($0) }))
init(id: [UInt8], label: String, updatedAt: Date) {
self.id = id
self.label = label
self.updatedAt = updatedAt
}
public static func ==(lhs: LightLocation, rhs: LightLocation) -> Bool {
return lhs.id == rhs.id && lhs.label == rhs.label && lhs.updatedAt == rhs.updatedAt
}
}
public class LightGroup: Equatable {
static let defaultGroup = LightGroup(id: Array(repeating: 48, count: 8), label: "", updatedAt: Date(timeIntervalSince1970: 0))
public let id: [UInt8]
public let label: String
public let updatedAt: Date
public lazy var identifier: String = String(describing: id.map({ UnicodeScalar($0) }))
init(id: [UInt8], label: String, updatedAt: Date) {
self.id = id
self.label = label
self.updatedAt = updatedAt
}
public static func ==(lhs: LightGroup, rhs: LightGroup) -> Bool {
return lhs.id == rhs.id && lhs.label == rhs.label && lhs.updatedAt == rhs.updatedAt
}
}
public class MultiZones: Equatable {
public var colors: [HSBK] = []
public static func ==(lhs: MultiZones, rhs: MultiZones) -> Bool {
return false
}
func dimTo(_ count: Int) {
while (colors.count < count) {
colors.append(HSBK(hue: 0, saturation: 0, brightness: 0, kelvin: 0))
}
while (colors.count > count) {
colors.removeLast()
}
}
} | mit |
gkye/TheMovieDatabaseSwiftWrapper | Sources/TMDBSwift/Client/Client_Trending.swift | 1 | 374 | import Foundation
extension Client {
static func trending(baseURL: String, completion: @escaping (ClientReturn) -> Void) {
let url = "https://api.themoviedb.org/3/trending/" + baseURL
networkRequest(url: url, parameters: [:]) { apiReturn in
if apiReturn.error == nil {
completion(apiReturn)
}
}
}
}
| mit |
JohnEstropia/CoreStore | Sources/AttributeProtocol.swift | 1 | 1940 | //
// AttributeProtocol.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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 CoreData
// MARK: - AttributeProtocol
internal protocol AttributeProtocol: AnyObject, PropertyProtocol {
typealias EntityDescriptionValues = (
attributeType: NSAttributeType,
isOptional: Bool,
isTransient: Bool,
allowsExternalBinaryDataStorage: Bool,
versionHashModifier: String?,
renamingIdentifier: String?,
affectedByKeyPaths: Set<String>,
defaultValue: Any?
)
var entityDescriptionValues: () -> EntityDescriptionValues { get }
var rawObject: CoreStoreManagedObject? { get set }
var getter: CoreStoreManagedObject.CustomGetter? { get }
var setter: CoreStoreManagedObject.CustomSetter? { get }
var valueForSnapshot: Any? { get }
}
| mit |
vojto/NiceKit | NiceKit/EditableTableRowView.swift | 1 | 1239 | //
// CustomTableRowView.swift
// FocusPlan
//
// Created by Vojtech Rinik on 5/11/17.
// Copyright © 2017 Median. All rights reserved.
//
import Foundation
import AppKit
open class EditableTableRowView: NSTableRowView {
open var isEditing = false
}
open class CustomTableRowView: EditableTableRowView {
static var selectionColor = NSColor(hexString: "ECEEFA")!
override open var isSelected: Bool {
didSet {
needsDisplay = true
}
}
override open var isEditing: Bool {
didSet {
needsDisplay = true
}
}
override open func drawBackground(in dirtyRect: NSRect) {
let rect = bounds.insetBy(dx: 4, dy: 4)
let path = NSBezierPath(roundedRect: rect, cornerRadius: 3)
let blue = CustomTableRowView.selectionColor
if isEditing {
NSColor.white.set()
bounds.fill()
blue.setStroke()
path.stroke()
} else if isSelected {
NSColor.white.set()
bounds.fill()
blue.setFill()
path.fill()
} else {
NSColor.white.set()
bounds.fill()
}
}
}
| mit |
saraford/AttemptOne | AttemptOne/ViewController.swift | 1 | 10986 | //
// ViewController.swift
// AttemptOne
//
// Created by Sara Ford on 8/29/15.
// Copyright (c) 2015 Sara Ford. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
var gameScenes = [GameScene]()
var gameEngine:GameEngine!
// var validCommands:ValidCommands!
var allCommands = [Command]()
var currentScene:Int = 0
@IBOutlet weak var responseText: UITextView!
@IBOutlet weak var userInput: UITextField!
@IBOutlet weak var gameText: UITextView!
@IBOutlet var sceneView: UIView!
@IBOutlet weak var sceneTextView: UITextView!
@IBOutlet weak var responseTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// needed for the keyboard
self.userInput.delegate = self
// show keyboard
userInput.becomeFirstResponder()
gameText.scrollRangeToVisible(NSRange(location:0, length:0))
gameEngine = GameEngine(viewController: self)
createGameScenes()
updateInitScene()
// validCommands = ValidCommands()
// println("commands: \(validCommands.verbs)")
}
func updateInitScene() {
currentScene = 0
gameText.text = gameScenes[currentScene].sceneText
responseText.text = gameScenes[currentScene].hintText
gameText.textColor = UIColor.whiteColor()
sceneView.backgroundColor = UIColor.blackColor()
sceneTextView.backgroundColor = UIColor.blackColor()
responseTextView.backgroundColor = UIColor.blackColor()
}
func updateScene(newScene: Int, lastCommand: String) {
currentScene = newScene
var currentGameScene = gameScenes[currentScene]
gameText.text = lastCommand + "\n\n" + currentGameScene.sceneText
// update new scene with hint text, if any
responseText.text = currentGameScene.hintText
}
func updateDeathScene(deathText: String) {
gameText.text = deathText.uppercaseString
responseText.text = gameScenes[0].hintText
sceneView.backgroundColor = UIColor.redColor()
sceneTextView.backgroundColor = UIColor.redColor()
responseTextView.backgroundColor = UIColor.redColor()
responseText.text = "hint \"try again\""
}
func updateResponse(error: String) {
responseText.text = error
}
func createGameScenes() {
var commandFeelAround = Command(verb: "feel", object: "around")
allCommands.append(commandFeelAround)
var commandWalkForwards = Command(verb:"walk", object:"forwards")
allCommands.append(commandWalkForwards)
var commandWalkBackwards = Command(verb:"walk", object:"backwards")
allCommands.append(commandWalkBackwards)
var commandHelp = Command(verb:"help", object:"")
allCommands.append(commandHelp)
var commandTakeShoes = Command(verb:"take", object:"shoes")
allCommands.append(commandTakeShoes)
var commandOpenDoor = Command(verb: "open", object: "door")
allCommands.append(commandOpenDoor)
var commandDoNothing = Command(verb: "do", object: "nothing")
allCommands.append(commandDoNothing)
var commandWalkLeft = Command(verb: "walk", object: "left")
allCommands.append(commandWalkLeft)
var commandWalkRight = Command(verb: "walk", object: "right")
allCommands.append(commandWalkRight)
var commandSayHello = Command(verb: "say", object: "hello")
allCommands.append(commandSayHello)
var commandTryAgain = Command(verb: "try", object: "again")
allCommands.append(commandTryAgain)
var state0 = GameScene()
state0.sceneText = "You open your eyes, but the world remains dark."
state0.hintText = "hint: \"feel around\""
state0.addValidCommand(commandFeelAround, text: "You feel around", goToScene: 1)
state0.addNothingCommand(commandDoNothing)
gameScenes.append(state0)
var state1 = GameScene()
state1.sceneText = "You are in a small room. The room rocks gently back and forth. There's a loud rumbling noise in the distance."
state1.hintText = ""
state1.addValidCommand(commandFeelAround, text: "You feel around", goToScene: 2)
state1.addValidCommand(commandOpenDoor, text: "You open the door and walk through", goToScene: 3)
state1.addUnableToCommand(commandWalkForwards, error: "You walk directly into something")
gameScenes.append(state1)
var state2 = GameScene()
state2.sceneText = "You find a closed door blocking your path. The room rocks gently back and forth."
state2.hintText = ""
state2.addValidCommand(commandOpenDoor, text: "You open the door", goToScene: 3)
state2.addUnableToCommand(commandWalkForwards, error: "You walk directly into something")
gameScenes.append(state2)
var state3 = GameScene()
state3.sceneText = "You see the bow of a boat. The roar and darkness of an approaching storm frightens you."
state3.addValidCommand(commandWalkForwards, text: "You walk forwards", goToScene: 4)
state3.hintText = ""
gameScenes.append(state3)
var state4 = GameScene()
state4.sceneText = "You jump off the boat. You are on a pier. The shore is on right. The pier continues on left"
state4.hintText = "hint: \"walk left or walk right\""
state4.addValidCommand(commandWalkRight, text: "You walk right", goToScene: 5)
state4.addDeathCommand(commandWalkLeft, deathText: "A water spout appears. The wind is too fearce to run away. You fall into the bay and drown.")
gameScenes.append(state4)
var state5 = GameScene()
state5.sceneText = "You arrive at the entrance of the Yacht Club. It starts to downpour. A waterspout appears heading right for you."
state5.hintText = ""
state5.addValidCommand(commandOpenDoor, text: "You open the door", goToScene: 6)
state5.addDeathCommand(commandFeelAround, deathText: "You took too long getting inside. A wooden board from the pier hits you in the head.")
gameScenes.append(state5)
var state6 = GameScene()
state6.sceneText = "You take shelter with others inside."
state6.hintText = "hint \"Say hello\""
state6.addValidCommand(commandSayHello, text: "You say hello", goToScene: 7)
gameScenes.append(state6)
var state7 = GameScene()
state7.sceneText = "No one remembers how they got here. The sky becomes pitch black. A dragon appears over the small bay, looking for you."
state7.addValidCommand(commandWalkForwards, text: "You leave the yacht club", goToScene: 8)
gameScenes.append(state7)
var state8 = GameScene()
state8.sceneText = "You get out just in time. You are in a parking lot."
state8.hintText = "Congrats you won becuase this is as far as I've gotten."
gameScenes.append(state8)
}
// for handling the return key when it is clicked from the keyboard
// requires UITextFieldDelegate and setting the delegate!!
func textFieldShouldReturn(textField: UITextField) -> Bool {
processInput()
// textField.resignFirstResponder()
return true;
}
// if the user taps outside the keyboard to add the item
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if (userInput.text == "") {
// just ignore in case user accidentally tapped outside the textbox without any info
return
}
// self.view.endEditing(true)
}
func processInput() {
var input = userInput.text.lowercaseString
println(input)
var command:Command!
// check if input is valid input from user before even continuing
if (validateInput(input)) {
// got a valid command
var command = createCommand(input)
// update the scene
gameEngine.executeCommand(gameScenes[currentScene], command: command)
}
userInput.text = ""
}
func createCommand(input: String) -> Command {
var words = findWords(input)
// add an 's' to forward and backward objects
if (words.count > 1) {
if (words[1] == "forward") {
words[1] = "forwards"
}
else if (words[1] == "backward") {
words[1] = "backward"
}
}
if (words.count == 1) {
return Command(verb: words[0], object: "")
} else {
return Command(verb: words[0], object: words[1])
}
}
func validateInput(input: String) -> Bool {
if (input.isEmpty || input == "") {
displayError("Are you giving me the slience treatment?")
return false
}
// remove any trailing whitespace
var trimmedInput = input.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if (trimmedInput.isEmpty || trimmedInput == "") {
displayError("Are you giving me the slience treatment?")
return false
}
var words = findWords(trimmedInput)
if (words.count > 2) {
displayError("I only respond to 1 or 2 word commands")
return false
}
// verify first word is in list of known words
for cmd in allCommands {
if (cmd.verb == words[0]) {
return true
}
}
displayError("Sorry, I don't know what \(words[0]) means ")
return false
}
func displayError(error:String) {
updateResponse("Um... \(error)")
}
func findWords(s: String) -> [String] {
var words = s.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
var legitWords = [String]()
for word in words {
if (word != "") {
legitWords.append(word)
}
}
return legitWords
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
infobip/mobile-messaging-sdk-ios | Example/Tests/MobileMessagingTests/UtilsTests.swift | 1 | 740 | //
// UtilsTests.swift
// MobileMessagingExample
//
// Created by Andrey Kadochnikov on 12.03.2021.
//
import XCTest
@testable import MobileMessaging
class UtilsTests: XCTestCase {
func testChecksAnyValuesForNil() {
let megaOptionalString: String?????? = nil
let nilString: String? = nil
let string: String = "some string"
let dict: [String: Any] = ["nilString": nilString as Any]
XCTAssertTrue(checkIfAnyIsNil(megaOptionalString as Any))
XCTAssertTrue(checkIfAnyIsNil(dict["nilString"] as Any))
XCTAssertTrue(checkIfAnyIsNil(dict["absentKey"] as Any))
XCTAssertTrue(checkIfAnyIsNil(nilString as Any))
XCTAssertFalse(checkIfAnyIsNil(string as Any))
}
}
| apache-2.0 |
andrewferrier/imbk | imbk/AppDelegate.swift | 1 | 3247 | //
// AppDelegate.swift
// imbk
//
// Created by Andrew Ferrier on 10/05/2016.
// Copyright © 2016 Andrew Ferrier. All rights reserved.
//
import UIKit
import HockeySDK
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
NSLog("About to authenticate with HockeyApp services")
BITHockeyManager.sharedHockeyManager().configureWithIdentifier("a15ddd8537b64652afe2e1aca26887c9")
BITHockeyManager.sharedHockeyManager().startManager()
BITHockeyManager.sharedHockeyManager().authenticator.authenticateInstallation()
NSLog("About to ask for permission for notifications.")
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Sound, UIUserNotificationType.Alert,
UIUserNotificationType.Badge], categories: nil))
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.
let notification = UILocalNotification()
notification.timeZone = NSTimeZone.defaultTimeZone()
let dateTime = NSDate(timeIntervalSinceNow: 60 * 60 * 24 * 3) // 3 days
notification.fireDate = dateTime
notification.alertBody = "Time to backup your photos with imbk!"
notification.applicationIconBadgeNumber = 1
UIApplication.sharedApplication().scheduleLocalNotification(notification)
NSLog("Local notification scheduled.")
}
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:.
}
}
| mit |
pine613/SwiftyPopover | Example/Tests/Tests.swift | 1 | 1180 | // https://github.com/Quick/Quick
import Quick
import Nimble
import SwiftyPopover
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit |
iluuu1994/2048 | 2048/Classes/GameOverScene.swift | 1 | 2291 | //
// GameOverScene.swift
// 2048
//
// Created by Ilija Tovilo on 31/07/14.
// Copyright (c) 2014 Ilija Tovilo. All rights reserved.
//
import Foundation
@objc(TFGameOverScene)
class GameOverScene: CCScene {
// MARK: Instanc Variables
private let _score: Int
lazy private var _backgroundNode: CCNodeColor = {
CCNodeColor(color: CCColor(red: 0.98, green: 0.97, blue: 0.94))
}()
lazy var _gameOverLabel: CCLabelTTF = {
let l = CCLabelTTF(string: "Game Over!", fontName: "ClearSans-Bold", fontSize: 40)
l.position = CGPoint(x: 0.5, y: 0.55)
l.positionType = CCPositionType(
xUnit: .Normalized,
yUnit: .Normalized,
corner: .BottomLeft
)
l.fontColor = CCColor(red: 0.47, green: 0.43, blue: 0.4)
return l
}()
lazy var _scoreLabel: CCLabelTTF = {
let l = CCLabelTTF(string: "Score: \(self._score)", fontName: "ClearSans-Bold", fontSize: 28)
l.position = CGPoint(x: 0.5, y: 0.45)
l.positionType = CCPositionType(
xUnit: .Normalized,
yUnit: .Normalized,
corner: .BottomLeft
)
l.fontColor = CCColor(red: 0.67, green: 0.63, blue: 0.6)
return l
}()
lazy var _tryAgainButton: CCButton = {
let l = Button(title: "TRY AGAIN", fontName: "ClearSans-Bold", fontSize: 28)
l.position = CGPoint(x: 0.5, y: 0.3)
l.positionType = CCPositionType(
xUnit: .Normalized,
yUnit: .Normalized,
corner: .BottomLeft
)
l.setTarget(self, selector: "restartGame")
return l
}()
// MARK: Init
class func scene(#score: Int) -> GameOverScene {
return GameOverScene(score: score)
}
init(score: Int) {
_score = score
super.init()
initSubnodes()
}
func initSubnodes() {
addChild(_backgroundNode)
addChild(_gameOverLabel)
addChild(_scoreLabel)
addChild(_tryAgainButton)
}
// MARK: Target Actions
func restartGame() {
CCDirector.sharedDirector().replaceScene(GameScene.scene())
}
}
| bsd-3-clause |
tokyovigilante/CesiumKit | CesiumKit/Core/Matrix4.swift | 1 | 56037 | //
// Matrix4.swift
// CesiumKit
//
// Created by Ryan Walklin on 13/07/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import Foundation
import simd
/**
* A 4x4 matrix, indexable as a column-major order array.
* Constructor parameters are in row-major order for code readability.
* @alias Matrix4
* @constructor
*
* @param {Number} [column0Row0=0.0] The value for column 0, row 0.
* @param {Number} [column1Row0=0.0] The value for column 1, row 0.
* @param {Number} [column2Row0=0.0] The value for column 2, row 0.
* @param {Number} [column3Row0=0.0] The value for column 3, row 0.
* @param {Number} [column0Row1=0.0] The value for column 0, row 1.
* @param {Number} [column1Row1=0.0] The value for column 1, row 1.
* @param {Number} [column2Row1=0.0] The value for column 2, row 1.
* @param {Number} [column3Row1=0.0] The value for column 3, row 1.
* @param {Number} [column0Row2=0.0] The value for column 0, row 2.
* @param {Number} [column1Row2=0.0] The value for column 1, row 2.
* @param {Number} [column2Row2=0.0] The value for column 2, row 2.
* @param {Number} [column3Row2=0.0] The value for column 3, row 2.
* @param {Number} [column0Row3=0.0] The value for column 0, row 3.
* @param {Number} [column1Row3=0.0] The value for column 1, row 3.
* @param {Number} [column2Row3=0.0] The value for column 2, row 3.
* @param {Number} [column3Row3=0.0] The value for column 3, row 3.
*
* @see Matrix4.fromColumnMajorArray
* @see Matrix4.fromRowMajorArray
* @see Matrix4.fromRotationTranslation
* @see Matrix4.fromTranslationQuaternionRotationScale
* @see Matrix4.fromTranslation
* @see Matrix4.fromScale
* @see Matrix4.fromUniformScale
* @see Matrix4.fromCamera
* @see Matrix4.computePerspectiveFieldOfView
* @see Matrix4.computeOrthographicOffCenter
* @see Matrix4.computePerspectiveOffCenter
* @see Matrix4.computeInfinitePerspectiveOffCenter
* @see Matrix4.computeViewportTransformation
* @see Matrix2
* @see Matrix3
* @see Packable
*/
public struct Matrix4 {
fileprivate (set) internal var simdType: double4x4
var floatRepresentation: float4x4 {
return float4x4([
simd_float(simdType[0]),
simd_float(simdType[1]),
simd_float(simdType[2]),
simd_float(simdType[3])
])
}
public init(
_ column0Row0: Double, _ column1Row0: Double, _ column2Row0: Double, _ column3Row0: Double,
_ column0Row1: Double, _ column1Row1: Double, _ column2Row1: Double, _ column3Row1: Double,
_ column0Row2: Double, _ column1Row2: Double, _ column2Row2: Double, _ column3Row2: Double,
_ column0Row3: Double, _ column1Row3: Double, _ column2Row3: Double, _ column3Row3: Double)
{
simdType = double4x4(rows: [
double4(column0Row0, column1Row0, column2Row0, column3Row0),
double4(column0Row1, column1Row1, column2Row1, column3Row1),
double4(column0Row2, column1Row2, column2Row2, column3Row2),
double4(column0Row3, column1Row3, column2Row3, column3Row3)
])
}
public init(grid: [Double]) {
assert(grid.count >= Matrix4.packedLength(), "invalid grid length")
self.init(
grid[0], grid[1], grid[2], grid[3],
grid[4], grid[5], grid[6], grid[7],
grid[8], grid[9], grid[10], grid[11],
grid[12], grid[13], grid[14], grid[15]
)
}
public init (simd: double4x4) {
simdType = simd
}
public init (_ scalar: Double = 0.0) {
simdType = double4x4(scalar)
}
public init (diagonal: double4) {
simdType = double4x4(diagonal: diagonal)
}
/*
/**
* Creates a Matrix4 from 16 consecutive elements in an array.
* @function
*
* @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
* @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
* @param {Matrix4} [result] The object onto which to store the result.
* @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
*
* @example
* // Create the Matrix4:
* // [1.0, 2.0, 3.0, 4.0]
* // [1.0, 2.0, 3.0, 4.0]
* // [1.0, 2.0, 3.0, 4.0]
* // [1.0, 2.0, 3.0, 4.0]
*
* var v = [1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
* var m = Cesium.Matrix4.fromArray(v);
*
* // Create same Matrix4 with using an offset into an array
* var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
* var m2 = Cesium.Matrix4.fromArray(v2, 2);
*/
Matrix4.fromArray = Matrix4.unpack;
/**
* Computes a Matrix4 instance from a column-major order array.
*
* @param {Number[]} values The column-major order array.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
Matrix4.fromColumnMajorArray = function(values, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(values)) {
throw new DeveloperError('values is required');
}
//>>includeEnd('debug');
assert(grid.count == 16, "Invalid source array")
self.init(rows: [
double4(grid[0], grid[1], grid[2], grid[3]),
double4(grid[4], grid[5], grid[6], grid[7]),
double4(grid[8], grid[9], grid[10], grid[11]),
double4(grid[12], grid[13], grid[14], grid[15])
])
}};
*/
/**
* Computes a Matrix4 instance from a row-major order array.
* The resulting matrix will be in column-major order.
*
* @param {Number[]} values The row-major order array.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
init(rowMajorArray grid: [Double]) {
self.init(grid: grid)
}
/**
* Computes a Matrix4 instance from a Matrix3 representing the rotation
* and a Cartesian3 representing the translation.
*
* @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
* @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
init (rotation: Matrix3, translation: Cartesian3 = Cartesian3.zero) {
self.init(
rotation[0,0], rotation[1,0], rotation[2,0], translation.x,
rotation[0,1], rotation[1,1], rotation[2,1], translation.y,
rotation[0,2], rotation[1,2], rotation[2,2], translation.z,
0.0, 0.0, 0.0, 1.0
)
}
/*
var scratchTrsRotation = new Matrix3();
/**
* Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
* representation with the rotation represented as a quaternion.
*
* @param {Cartesian3} translation The translation transformation.
* @param {Quaternion} rotation The rotation transformation.
* @param {Cartesian3} scale The non-uniform scale transformation.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @example
* result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
* new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
* Cesium.Quaternion.IDENTITY, // rotation
* new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
* result);
*/
Matrix4.fromTranslationQuaternionRotationScale = function(translation, rotation, scale, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(translation)) {
throw new DeveloperError('translation is required.');
}
if (!defined(rotation)) {
throw new DeveloperError('rotation is required.');
}
if (!defined(scale)) {
throw new DeveloperError('scale is required.');
}
//>>includeEnd('debug');
if (!defined(result)) {
result = new Matrix4();
}
var scaleX = scale.x;
var scaleY = scale.y;
var scaleZ = scale.z;
var x2 = rotation.x * rotation.x;
var xy = rotation.x * rotation.y;
var xz = rotation.x * rotation.z;
var xw = rotation.x * rotation.w;
var y2 = rotation.y * rotation.y;
var yz = rotation.y * rotation.z;
var yw = rotation.y * rotation.w;
var z2 = rotation.z * rotation.z;
var zw = rotation.z * rotation.w;
var w2 = rotation.w * rotation.w;
var m00 = x2 - y2 - z2 + w2;
var m01 = 2.0 * (xy - zw);
var m02 = 2.0 * (xz + yw);
var m10 = 2.0 * (xy + zw);
var m11 = -x2 + y2 - z2 + w2;
var m12 = 2.0 * (yz - xw);
var m20 = 2.0 * (xz - yw);
var m21 = 2.0 * (yz + xw);
var m22 = -x2 - y2 + z2 + w2;
result[0] = m00 * scaleX;
result[1] = m10 * scaleX;
result[2] = m20 * scaleX;
result[3] = 0.0;
result[4] = m01 * scaleY;
result[5] = m11 * scaleY;
result[6] = m21 * scaleY;
result[7] = 0.0;
result[8] = m02 * scaleZ;
result[9] = m12 * scaleZ;
result[10] = m22 * scaleZ;
result[11] = 0.0;
result[12] = translation.x;
result[13] = translation.y;
result[14] = translation.z;
result[15] = 1.0;
return result;
};
*/
/**
* Creates a Matrix4 instance from a Cartesian3 representing the translation.
*
* @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @see Matrix4.multiplyByTranslation
*/
init (translation: Cartesian3) {
self.init(rotation: Matrix3.identity, translation: translation)
}
/**
* Computes a Matrix4 instance representing a non-uniform scale.
*
* @param {Cartesian3} scale The x, y, and z scale factors.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @example
* // Creates
* // [7.0, 0.0, 0.0, 0.0]
* // [0.0, 8.0, 0.0, 0.0]
* // [0.0, 0.0, 9.0, 0.0]
* // [0.0, 0.0, 0.0, 1.0]
* var m = Cesium.Matrix4.fromScale(new Cartesian3(7.0, 8.0, 9.0));
*/
init (scale: Cartesian3) {
let diagonal = double4([scale.simdType.x, scale.simdType.y, scale.simdType.z, 1.0])
self.simdType = double4x4(diagonal: diagonal)
/*Matrix4(
scale.x, 0.0, 0.0, 0.0,
0.0, scale.y, 0.0, 0.0,
0.0, 0.0, scale.z, 0.0,
0.0, 0.0, 0.0, 1.0);*/
}
/*
/**
* Computes a Matrix4 instance representing a uniform scale.
*
* @param {Number} scale The uniform scale factor.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @example
* // Creates
* // [2.0, 0.0, 0.0, 0.0]
* // [0.0, 2.0, 0.0, 0.0]
* // [0.0, 0.0, 2.0, 0.0]
* // [0.0, 0.0, 0.0, 1.0]
* var m = Cesium.Matrix4.fromScale(2.0);
*/
Matrix4.fromUniformScale = function(scale, result) {
//>>includeStart('debug', pragmas.debug);
if (typeof scale !== 'number') {
throw new DeveloperError('scale is required.');
}
//>>includeEnd('debug');
if (!defined(result)) {
return new Matrix4(scale, 0.0, 0.0, 0.0,
0.0, scale, 0.0, 0.0,
0.0, 0.0, scale, 0.0,
0.0, 0.0, 0.0, 1.0);
}
result[0] = scale;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = scale;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = scale;
result[11] = 0.0;
result[12] = 0.0;
result[13] = 0.0;
result[14] = 0.0;
result[15] = 1.0;
return result;
};
var fromCameraF = new Cartesian3();
var fromCameraS = new Cartesian3();
var fromCameraU = new Cartesian3();
/**
* Computes a Matrix4 instance from a Camera.
*
* @param {Camera} camera The camera to use.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
Matrix4.fromCamera = function(camera, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(camera)) {
throw new DeveloperError('camera is required.');
}
//>>includeEnd('debug');
var eye = camera.eye;
var target = camera.target;
var up = camera.up;
//>>includeStart('debug', pragmas.debug);
if (!defined(eye)) {
throw new DeveloperError('camera.eye is required.');
}
if (!defined(target)) {
throw new DeveloperError('camera.target is required.');
}
if (!defined(up)) {
throw new DeveloperError('camera.up is required.');
}
//>>includeEnd('debug');
Cartesian3.normalize(Cartesian3.subtract(target, eye, fromCameraF), fromCameraF);
Cartesian3.normalize(Cartesian3.cross(fromCameraF, up, fromCameraS), fromCameraS);
Cartesian3.normalize(Cartesian3.cross(fromCameraS, fromCameraF, fromCameraU), fromCameraU);
var sX = fromCameraS.x;
var sY = fromCameraS.y;
var sZ = fromCameraS.z;
var fX = fromCameraF.x;
var fY = fromCameraF.y;
var fZ = fromCameraF.z;
var uX = fromCameraU.x;
var uY = fromCameraU.y;
var uZ = fromCameraU.z;
var eyeX = eye.x;
var eyeY = eye.y;
var eyeZ = eye.z;
var t0 = sX * -eyeX + sY * -eyeY+ sZ * -eyeZ;
var t1 = uX * -eyeX + uY * -eyeY+ uZ * -eyeZ;
var t2 = fX * eyeX + fY * eyeY + fZ * eyeZ;
//The code below this comment is an optimized
//version of the commented lines.
//Rather that create two matrices and then multiply,
//we just bake in the multiplcation as part of creation.
//var rotation = new Matrix4(
// sX, sY, sZ, 0.0,
// uX, uY, uZ, 0.0,
// -fX, -fY, -fZ, 0.0,
// 0.0, 0.0, 0.0, 1.0);
//var translation = new Matrix4(
// 1.0, 0.0, 0.0, -eye.x,
// 0.0, 1.0, 0.0, -eye.y,
// 0.0, 0.0, 1.0, -eye.z,
// 0.0, 0.0, 0.0, 1.0);
//return rotation.multiply(translation);
if (!defined(result)) {
return new Matrix4(
sX, sY, sZ, t0,
uX, uY, uZ, t1,
-fX, -fY, -fZ, t2,
0.0, 0.0, 0.0, 1.0);
}
result[0] = sX;
result[1] = uX;
result[2] = -fX;
result[3] = 0.0;
result[4] = sY;
result[5] = uY;
result[6] = -fY;
result[7] = 0.0;
result[8] = sZ;
result[9] = uZ;
result[10] = -fZ;
result[11] = 0.0;
result[12] = t0;
result[13] = t1;
result[14] = t2;
result[15] = 1.0;
return result;
};
*/
public subscript (column: Int) -> Cartesian4 {
return Cartesian4(simd: simdType[column])
}
/// Access to individual elements.
public subscript (column: Int, row: Int) -> Double {
return simdType[column][row]
}
/*
/**
* Computes a Matrix4 instance representing a perspective transformation matrix.
*
* @param {Number} fovY The field of view along the Y axis in radians.
* @param {Number} aspectRatio The aspect ratio.
* @param {Number} near The distance to the near plane in meters.
* @param {Number} far The distance to the far plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns The modified result parameter.
*
* @exception {DeveloperError} fovY must be in [0, PI).
* @exception {DeveloperError} aspectRatio must be greater than zero.
* @exception {DeveloperError} near must be greater than zero.
* @exception {DeveloperError} far must be greater than zero.
*/
Matrix4.computePerspectiveFieldOfView = function(fovY, aspectRatio, near, far, result) {
//>>includeStart('debug', pragmas.debug);
if (fovY <= 0.0 || fovY > Math.PI) {
throw new DeveloperError('fovY must be in [0, PI).');
}
if (aspectRatio <= 0.0) {
throw new DeveloperError('aspectRatio must be greater than zero.');
}
if (near <= 0.0) {
throw new DeveloperError('near must be greater than zero.');
}
if (far <= 0.0) {
throw new DeveloperError('far must be greater than zero.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
var bottom = Math.tan(fovY * 0.5);
var column1Row1 = 1.0 / bottom;
var column0Row0 = column1Row1 / aspectRatio;
var column2Row2 = (far + near) / (near - far);
var column3Row2 = (2.0 * far * near) / (near - far);
result[0] = column0Row0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = column1Row1;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = column2Row2;
result[11] = -1.0;
result[12] = 0.0;
result[13] = 0.0;
result[14] = column3Row2;
result[15] = 0.0;
return result;
};
*/
/**
* Computes a Matrix4 instance representing an orthographic transformation matrix.
*
* @param {Number} left The number of meters to the left of the camera that will be in view.
* @param {Number} right The number of meters to the right of the camera that will be in view.
* @param {Number} bottom The number of meters below of the camera that will be in view.
* @param {Number} top The number of meters above of the camera that will be in view.
* @param {Number} near The distance to the near plane in meters.
* @param {Number} far The distance to the far plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns The modified result parameter.
*/
static func computeOrthographicOffCenter (left: Double, right: Double, bottom: Double, top: Double, near: Double = 0.0, far: Double = 1.0) -> Matrix4 {
// Converted to Metal NDC coordinates - z: [0-1]
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb205348(v=vs.85).aspx
let a = 2.0 / (right - left)
let b = 2.0 / (top - bottom)
let c = 1.0 / (far - near)
let tx = (right + left) / (left - right)
let ty = (top + bottom) / (bottom - top)
let tz = near / (far - near)
return Matrix4(
a, 0.0, 0.0, tx,
0.0, b, 0.0, ty,
0.0, 0.0, c, tz,
0.0, 0.0, 0.0, 1.0)
}
/**
* Computes a Matrix4 instance representing an off center perspective transformation.
*
* @param {Number} left The number of meters to the left of the camera that will be in view.
* @param {Number} right The number of meters to the right of the camera that will be in view.
* @param {Number} bottom The number of meters below of the camera that will be in view.
* @param {Number} top The number of meters above of the camera that will be in view.
* @param {Number} near The distance to the near plane in meters.
* @param {Number} far The distance to the far plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns The modified result parameter.
*/
static func computePerspectiveOffCenter (left: Double, right: Double, bottom: Double, top: Double, near: Double, far: Double) -> Matrix4 {
// Converted to Metal NDC coordinates - z: [0-1]
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb205354(v=vs.85).aspx
let column0Row0 = 2.0 * near / (right - left) // w
let column1Row1 = 2.0 * near / (top - bottom) // h
let column2Row0 = (left + right) / (right - left)
let column2Row1 = (top + bottom) / (top - bottom)
let column2Row2 = far / (near - far) // Q
let column3Row2 = near * far / (near - far)
return Matrix4(
column0Row0, 0.0, column2Row0, 0.0,
0.0, column1Row1, column2Row1, 0.0,
0.0, 0.0, column2Row2, column3Row2,
0.0, 0.0, -1.0, 0.0)
}
/**
* Computes a Matrix4 instance representing an infinite off center perspective transformation.
*
* @param {Number} left The number of meters to the left of the camera that will be in view.
* @param {Number} right The number of meters to the right of the camera that will be in view.
* @param {Number} bottom The number of meters below of the camera that will be in view.
* @param {Number} top The number of meters above of the camera that will be in view.
* @param {Number} near The distance to the near plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns The modified result parameter.
*/
static func computeInfinitePerspectiveOffCenter (left: Double, right: Double, bottom: Double, top: Double, near: Double) -> Matrix4 {
//assertionFailure("not updated for metal NDC")
let column0Row0 = 2.0 * near / (right - left)
let column1Row1 = 2.0 * near / (top - bottom)
let column2Row0 = (right + left) / (right - left)
let column2Row1 = (top + bottom) / (top - bottom)
let column2Row2 = -1.0
let column2Row3 = -1.0
let column3Row2 = -2.0 * near
return Matrix4(
column0Row0, 0.0, column2Row0, 0.0,
0.0, column1Row1, column2Row1, 0.0,
0.0, 0.0, column2Row2, column3Row2,
0.0, 0.0, column2Row3, 0.0)
}
/**
* Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
*
* @param {Object}[viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
* @param {Number}[nearDepthRange=0.0] The near plane distance in window coordinates.
* @param {Number}[farDepthRange=1.0] The far plane distance in window coordinates.
* @param {Matrix4} result The object in which the result will be stored.
* @returns The modified result parameter.
*
* @example
* // Example 1. Create viewport transformation using an explicit viewport and depth range.
* var m = Cesium.Matrix4.computeViewportTransformation({
* x : 0.0,
* y : 0.0,
* width : 1024.0,
* height : 768.0
* }, 0.0, 1.0);
*
* @example
* // Example 2. Create viewport transformation using the context's viewport.
* var m = Cesium.Matrix4.computeViewportTransformation(context.getViewport());
*/
internal static func computeViewportTransformation (_ viewport: Cartesian4, nearDepthRange: Double = 0.0, farDepthRange: Double = 1.0) -> Matrix4 {
let x = viewport.x
let y = viewport.y
let width = viewport.width
let height = viewport.height
let halfWidth = width * 0.5
let halfHeight = height * 0.5
let halfDepth = (farDepthRange - nearDepthRange) * 0.5
let column0Row0 = halfWidth
let column1Row1 = halfHeight
let column2Row2 = halfDepth
let column3Row0 = x + halfWidth
let column3Row1 = y + halfHeight
let column3Row2 = nearDepthRange + halfDepth
let column3Row3 = 1.0
return Matrix4(
column0Row0, 0.0, 0.0, column3Row0,
0.0, column1Row1, 0.0, column3Row1,
0.0, 0.0, column2Row2, column3Row2,
0.0, 0.0, 0.0, column3Row3
)
}
/*
/**
* Computes the array index of the element at the provided row and column.
*
* @param {Number} row The zero-based index of the row.
* @param {Number} column The zero-based index of the column.
* @returns {Number} The index of the element at the provided row and column.
*
* @exception {DeveloperError} row must be 0, 1, 2, or 3.
* @exception {DeveloperError} column must be 0, 1, 2, or 3.
*
* @example
* var myMatrix = new Cesium.Matrix4();
* var column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
* var column1Row0 = myMatrix[column1Row0Index]
* myMatrix[column1Row0Index] = 10.0;
*/
Matrix4.getElementIndex = function(column, row) {
//>>includeStart('debug', pragmas.debug);
if (typeof row !== 'number' || row < 0 || row > 3) {
throw new DeveloperError('row must be 0, 1, 2, or 3.');
}
if (typeof column !== 'number' || column < 0 || column > 3) {
throw new DeveloperError('column must be 0, 1, 2, or 3.');
}
//>>includeEnd('debug');
return column * 4 + row;
};
*/
/**
* Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to retrieve.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //returns a Cartesian4 instance with values from the specified column
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* //Example 1: Creates an instance of Cartesian
* var a = Cesium.Matrix4.getColumn(m, 2);
*
* @example
* //Example 2: Sets values for Cartesian instance
* var a = new Cesium.Cartesian4();
* Cesium.Matrix4.getColumn(m, 2, a);
*
* // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
*/
func getColumn (_ index: Int) -> Cartesian4 {
assert(index >= 0 && index <= 3, "index must be 0, 1, 2, or 3.")
return Cartesian4(simd: simdType[index])
}
/**
* Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to set.
* @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
* @returns {Matrix4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //creates a new Matrix4 instance with new column values from the Cartesian4 instance
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* var a = Cesium.Matrix4.setColumn(m, 2, new Cartesian4(99.0, 98.0, 97.0, 96.0));
*
* // m remains the same
* // a = [10.0, 11.0, 99.0, 13.0]
* // [14.0, 15.0, 98.0, 17.0]
* // [18.0, 19.0, 97.0, 21.0]
* // [22.0, 23.0, 96.0, 25.0]
*/
func setColumn (_ index: Int, cartesian: Cartesian4) -> Matrix4 {
assert(index >= 0 && index <= 3, "index must be 0, 1, 2, or 3.")
var result = simdType
result[index] = double4(cartesian.x, cartesian.y, cartesian.z, cartesian.w)
return Matrix4(simd: result)
}
/**
* Computes a new matrix that replaces the translation in the rightmost column of the provided
* matrix with the provided translation. This assumes the matrix is an affine transformation
*
* @param {Matrix4} matrix The matrix to use.
* @param {Cartesian3} translation The translation that replaces the translation of the provided matrix.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
func setTranslation (_ translation: Cartesian3) -> Matrix4 {
var result = simdType
result[3] = double4(translation.x, translation.y, translation.z, simdType[3].w)
return Matrix4(simd: result)
}
/**
* Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to retrieve.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //returns a Cartesian4 instance with values from the specified column
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* //Example 1: Returns an instance of Cartesian
* var a = Cesium.Matrix4.getRow(m, 2);
*
* @example
* //Example 2: Sets values for a Cartesian instance
* var a = new Cesium.Cartesian4();
* Cesium.Matrix4.getRow(m, 2, a);
*
* // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
*/
func row (_ index: Int) -> Cartesian4 {
assert(index >= 0 && index <= 3, "index must be 0, 1, 2, or 3.")
return Cartesian4(
x: self[0, index],
y: self[1, index],
z: self[2, index],
w: self[3, index]
)
}
/**
* Computes the product of two matrices.
*
* @param {MatrixType} self The first matrix.
* @param {MatrixType} other The second matrix.
* @returns {MatrixType} The modified result parameter.
*/
func multiply(_ other: Matrix4) -> Matrix4 {
return Matrix4(simd: simdType * other.simdType)
}
func negate() -> Matrix4 {
return Matrix4(simd: -simdType)
}
func transpose () -> Matrix4 {
return Matrix4(simd: simdType.transpose)
}
/**
* Compares this matrix to the provided matrix componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {MatrixType} [right] The right hand side matrix.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
func equals(_ other: Matrix4) -> Bool {
return simd_equal(simdType, other.simdType)
}
/**
* Compares the provided matrices componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {MatrixType} [left] The first matrix.
* @param {MatrixType} [right] The second matrix.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
func equalsEpsilon(_ other: Matrix4, epsilon: Double) -> Bool {
return simd_almost_equal_elements(self.simdType, other.simdType, epsilon)
}
/*
/**
* Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to set.
* @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //create a new Matrix4 instance with new row values from the Cartesian4 instance
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* var a = Cesium.Matrix4.setRow(m, 2, new Cartesian4(99.0, 98.0, 97.0, 96.0));
*
* // m remains the same
* // a = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [99.0, 98.0, 97.0, 96.0]
* // [22.0, 23.0, 24.0, 25.0]
*/
Matrix4.setRow = function(matrix, index, cartesian, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (typeof index !== 'number' || index < 0 || index > 3) {
throw new DeveloperError('index must be 0, 1, 2, or 3.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result = Matrix4.clone(matrix, result);
result[index] = cartesian.x;
result[index + 4] = cartesian.y;
result[index + 8] = cartesian.z;
result[index + 12] = cartesian.w;
return result;
};
var scratchColumn = new Cartesian3();
/**
* Extracts the non-uniform scale assuming the matrix is an affine transformation.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter
*/
Matrix4.getScale = function(matrix, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn));
result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn));
return result;
};
var scratchScale = new Cartesian3();
/**
* Computes the maximum scale assuming the matrix is an affine transformation.
* The maximum scale is the maximum length of the column vectors in the upper-left
* 3x3 matrix.
*
* @param {Matrix4} matrix The matrix.
* @returns {Number} The maximum scale.
*/
Matrix4.getMaximumScale = function(matrix) {
Matrix4.getScale(matrix, scratchScale);
return Cartesian3.maximumComponent(scratchScale);
};
*/
/**
* Computes the product of two matrices assuming the matrices are
* affine transformation matrices, where the upper left 3x3 elements
* are a rotation matrix, and the upper three elements in the fourth
* column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
* The matrix is not verified to be in the proper form.
* This method is faster than computing the product for general 4x4
* matrices using {@link Matrix4.multiply}.
*
* @param {Matrix4} left The first matrix.
* @param {Matrix4} right The second matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* var m1 = new Cesium.Matrix4(1.0, 6.0, 7.0, 0.0, 2.0, 5.0, 8.0, 0.0, 3.0, 4.0, 9.0, 0.0, 0.0, 0.0, 0.0, 1.0];
* var m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
* var m3 = Cesium.Matrix4.multiplyTransformation(m1, m2);
*/
/*func multiplyTransformation (other: Matrix4) -> Matrix4 {
let this0 = _grid[0]
let this1 = _grid[1]
let this2 = _grid[2]
let this4 = _grid[4]
let this5 = _grid[5]
let this6 = _grid[6]
let this8 = _grid[8]
let this9 = _grid[9]
let this10 = _grid[10]
let this12 = _grid[12]
let this13 = _grid[13]
let this14 = _grid[14]
let other0 = other[0]
let other1 = other[1]
let other2 = other[2]
let other4 = other[4]
let other5 = other[5]
let other6 = other[6]
let other8 = other[8]
let other9 = other[9]
let other10 = other[10]
let other12 = other[12]
let other13 = other[13]
let other14 = other[14]
let column0Row0 = this0 * other0 + this4 * other1 + this8 * other2
let column0Row1 = this1 * other0 + this5 * other1 + this9 * other2
let column0Row2 = this2 * other0 + this6 * other1 + this10 * other2
let column1Row0 = this0 * other4 + this4 * other5 + this8 * other6
let column1Row1 = this1 * other4 + this5 * other5 + this9 * other6
let column1Row2 = this2 * other4 + this6 * other5 + this10 * other6
let column2Row0 = this0 * other8 + this4 * other9 + this8 * other10
let column2Row1 = this1 * other8 + this5 * other9 + this9 * other10
let column2Row2 = this2 * other8 + this6 * other9 + this10 * other10
let column3Row0 = this0 * other12 + this4 * other13 + this8 * other14 + this12
let column3Row1 = this1 * other12 + this5 * other13 + this9 * other14 + this13
let column3Row2 = this2 * other12 + this6 * other13 + this10 * other14 + this14
return Matrix4(
column0Row0, column1Row0, column2Row0, column3Row0,
column0Row1, column1Row1, column2Row1, column3Row1,
column0Row2, column1Row2, column2Row2, column3Row2,
0.0, 0.0, 0.0, 1.0
)
}*/
/*
/**
* Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
* by a 3x3 rotation matrix. This is an optimization
* for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations.
*
* @param {Matrix4} matrix The matrix on the left-hand side.
* @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
* Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
*/
Matrix4.multiplyByMatrix3 = function(matrix, rotation, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(rotation)) {
throw new DeveloperError('rotation is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
var left0 = matrix[0];
var left1 = matrix[1];
var left2 = matrix[2];
var left4 = matrix[4];
var left5 = matrix[5];
var left6 = matrix[6];
var left8 = matrix[8];
var left9 = matrix[9];
var left10 = matrix[10];
var right0 = rotation[0];
var right1 = rotation[1];
var right2 = rotation[2];
var right4 = rotation[3];
var right5 = rotation[4];
var right6 = rotation[5];
var right8 = rotation[6];
var right9 = rotation[7];
var right10 = rotation[8];
var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = 0.0;
result[4] = column1Row0;
result[5] = column1Row1;
result[6] = column1Row2;
result[7] = 0.0;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = 0.0;
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
};
/**
* Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
* by an implicit non-uniform scale matrix. This is an optimization
* for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
* <code>m</code> must be an affine matrix.
* This function performs fewer allocations and arithmetic operations.
*
* @param {Matrix4} matrix The matrix on the left-hand side.
* @param {Cartesian3} translation The translation on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
* Cesium.Matrix4.multiplyByTranslation(m, position, m);
*/
Matrix4.multiplyByTranslation = function(matrix, translation, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(translation)) {
throw new DeveloperError('translation is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
var x = translation.x;
var y = translation.y;
var z = translation.z;
var tx = (x * matrix[0]) + (y * matrix[4]) + (z * matrix[8]) + matrix[12];
var ty = (x * matrix[1]) + (y * matrix[5]) + (z * matrix[9]) + matrix[13];
var tz = (x * matrix[2]) + (y * matrix[6]) + (z * matrix[10]) + matrix[14];
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
result[9] = matrix[9];
result[10] = matrix[10];
result[11] = matrix[11];
result[12] = tx;
result[13] = ty;
result[14] = tz;
result[15] = matrix[15];
return result;
};
var uniformScaleScratch = new Cartesian3();
/**
* Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
* by an implicit uniform scale matrix. This is an optimization
* for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code> with less allocations and arithmetic operations.
*
* @param {Matrix4} matrix The matrix on the left-hand side.
* @param {Number} scale The uniform scale on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @see Matrix4.fromUniformScale
* @see Matrix4.multiplyByScale
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
* Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
*/
Matrix4.multiplyByUniformScale = function(matrix, scale, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (typeof scale !== 'number') {
throw new DeveloperError('scale is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
uniformScaleScratch.x = scale;
uniformScaleScratch.y = scale;
uniformScaleScratch.z = scale;
return Matrix4.multiplyByScale(matrix, uniformScaleScratch, result);
};
/**
* Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
* by an implicit non-uniform scale matrix. This is an optimization
* for <code>Matrix4.multiply(m, Matrix4.fromScale(scale), m);</code> with less allocations and arithmetic operations.
*
* @param {Matrix4} matrix The matrix on the left-hand side.
* @param {Cartesian3} scale The non-uniform scale on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @see Matrix4.fromScale
* @see Matrix4.multiplyByUniformScale
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
* Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
*/
Matrix4.multiplyByScale = function(matrix, scale, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(scale)) {
throw new DeveloperError('scale is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
var scaleX = scale.x;
var scaleY = scale.y;
var scaleZ = scale.z;
// Faster than Cartesian3.equals
if ((scaleX === 1.0) && (scaleY === 1.0) && (scaleZ === 1.0)) {
return Matrix4.clone(matrix, result);
}
result[0] = scaleX * matrix[0];
result[1] = scaleX * matrix[1];
result[2] = scaleX * matrix[2];
result[3] = 0.0;
result[4] = scaleY * matrix[4];
result[5] = scaleY * matrix[5];
result[6] = scaleY * matrix[6];
result[7] = 0.0;
result[8] = scaleZ * matrix[8];
result[9] = scaleZ * matrix[9];
result[10] = scaleZ * matrix[10];
result[11] = 0.0;
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = 1.0;
return result;
};
*/
/**
* Computes the product of a matrix and a column vector.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian4} cartesian The vector.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
func multiplyByVector(_ cartesian: Cartesian4) -> Cartesian4 {
return Cartesian4(simd: self.simdType * cartesian.simdType)
}
/**
* Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
* with a {@link Cartesian4} with a <code>w</code> component of zero.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian3} cartesian The point.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @example
* var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
* Cesium.Matrix4.multiplyByPointAsVector(matrix, p, result);
* // A shortcut for
* // Cartesian3 p = ...
* // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
*/
func multiplyByPointAsVector (_ cartesian: Cartesian3) -> Cartesian3 {
let vector = simdType * double4(cartesian.x, cartesian.y, cartesian.z, 0.0)
return Cartesian3(x: vector.x, y: vector.y, z: vector.z)
}
/**
* Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
* with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian3} cartesian The point.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @example
* var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
* Cesium.Matrix4.multiplyByPoint(matrix, p, result);
*/
func multiplyByPoint (_ cartesian: Cartesian3) -> Cartesian3 {
let vector = simdType * double4(cartesian.x, cartesian.y, cartesian.z, 1.0)
return Cartesian3(x: vector.x, y: vector.y, z: vector.z)
}
/*
/**
* Computes the product of a matrix and a scalar.
*
* @param {Matrix4} matrix The matrix.
* @param {Number} scalar The number to multiply by.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* //create a Matrix4 instance which is a scaled version of the supplied Matrix4
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* var a = Cesium.Matrix4.multiplyBy(scalar: m, -2);
*
* // m remains the same
* // a = [-20.0, -22.0, -24.0, -26.0]
* // [-28.0, -30.0, -32.0, -34.0]
* // [-36.0, -38.0, -40.0, -42.0]
* // [-44.0, -46.0, -48.0, -50.0]
*/
Matrix4.multiplyByScalar = function(matrix, scalar, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (typeof scalar !== 'number') {
throw new DeveloperError('scalar must be a number');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result[0] = matrix[0] * scalar;
result[1] = matrix[1] * scalar;
result[2] = matrix[2] * scalar;
result[3] = matrix[3] * scalar;
result[4] = matrix[4] * scalar;
result[5] = matrix[5] * scalar;
result[6] = matrix[6] * scalar;
result[7] = matrix[7] * scalar;
result[8] = matrix[8] * scalar;
result[9] = matrix[9] * scalar;
result[10] = matrix[10] * scalar;
result[11] = matrix[11] * scalar;
result[12] = matrix[12] * scalar;
result[13] = matrix[13] * scalar;
result[14] = matrix[14] * scalar;
result[15] = matrix[15] * scalar;
return result;
};
/**
* Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
*
* @param {Matrix4} matrix The matrix with signed elements.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.abs = function(matrix, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result[0] = Math.abs(matrix[0]);
result[1] = Math.abs(matrix[1]);
result[2] = Math.abs(matrix[2]);
result[3] = Math.abs(matrix[3]);
result[4] = Math.abs(matrix[4]);
result[5] = Math.abs(matrix[5]);
result[6] = Math.abs(matrix[6]);
result[7] = Math.abs(matrix[7]);
result[8] = Math.abs(matrix[8]);
result[9] = Math.abs(matrix[9]);
result[10] = Math.abs(matrix[10]);
result[11] = Math.abs(matrix[11]);
result[12] = Math.abs(matrix[12]);
result[13] = Math.abs(matrix[13]);
result[14] = Math.abs(matrix[14]);
result[15] = Math.abs(matrix[15]);
return result;
};
*/
/**
* Gets the translation portion of the provided matrix, assuming the matrix is a affine transformation matrix.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
var translation: Cartesian3 {
let column3 = simdType[3]
return Cartesian3(x: column3.x, y: column3.y, z: column3.z)
}
/**
* Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is a affine transformation matrix.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @example
* // returns a Matrix3 instance from a Matrix4 instance
*
* // m = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* var b = new Cesium.Matrix3();
* Cesium.Matrix4.getRotation(m,b);
*
* // b = [10.0, 14.0, 18.0]
* // [11.0, 15.0, 19.0]
* // [12.0, 16.0, 20.0]
*/
var rotation: Matrix3 {
let column0 = simdType[0]
let column1 = simdType[1]
let column2 = simdType[2]
return Matrix3(
column0.x, column1.x, column2.x,
column0.y, column1.y, column2.y,
column0.z, column1.z, column2.z)
}
var inverse: Matrix4 {
// Special case for a zero scale matrix that can occur, for example,
// when a model's node has a [0, 0, 0] scale.
if rotation.equalsEpsilon(Matrix3.zero, epsilon: Math.Epsilon7) && self[3] == Cartesian4.unitW {
return Matrix4(simd: double4x4([
double4(),
double4(),
double4(),
double4(self[3,0], self[3,1], self[3,2], 1.0)])
)
/*result[0] = 0.0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = 0.0;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = 0.0;
result[11] = 0.0;
result[12] = -matrix[12];
result[13] = -matrix[13];
result[14] = -matrix[14];
result[15] = 1.0;
return result;*/
}
return Matrix4(simd: simdType.inverse)
}
/**
* An immutable Matrix4 instance initialized to the identity matrix.
*
* @type {Matrix4}
* @constant
*/
public static let identity = Matrix4(1.0)
public static let zero = Matrix4()
/**
* @private
*/
func equalsArray (_ array: [Float], offset: Int) -> Bool {
let other = Matrix4.unpack(array, startingIndex: offset)
return self == other
}
}
extension Matrix4: Packable {
var length: Int {
return Matrix4.packedLength()
}
static func packedLength () -> Int {
return 16
}
init(array: [Double], startingIndex: Int = 0) {
self.init()
assert(checkPackedArrayLength(array, startingIndex: startingIndex), "Invalid packed array length")
_ = array.withUnsafeBufferPointer { (pointer: UnsafeBufferPointer<Double>) in
memcpy(&self, pointer.baseAddress, Matrix4.packedLength() * MemoryLayout<Double>.stride)
}
}
}
extension Matrix4: Equatable {}
/**
* Compares the provided matrices componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Matrix4} [left] The first matrix.
* @param {Matrix4} [right] The second matrix.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*
* @example
* //compares two Matrix4 instances
*
* // a = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* // b = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* if(Cesium.Matrix4.equals(a,b)) {
* console.log("Both matrices are equal");
* } else {
* console.log("They are not equal");
* }
*
* //Prints "Both matrices are equal" on the console
*/
public func == (left: Matrix4, right: Matrix4) -> Bool {
return left.equals(right)
}
| apache-2.0 |
v-andr/LakestoneCore | Source/PersistentPropertyList.swift | 1 | 12465 | //
// PersistentPropertyList.swift
// LakestoneCore
//
// Created by Taras Vozniuk on 6/13/16.
// Copyright © 2016 GeoThings. All rights reserved.
//
// --------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#if COOPER
import android.content
import android.preference
#else
import Foundation
#endif
public class PersistentPropertyList {
#if COOPER
fileprivate let sharedPreference: SharedPreferences
fileprivate let sharedPreferenceEditor: SharedPreferences.Editor
public init(applicationContext: Context, preferenceFileKey: String? = nil){
if let passedPreferenceKey = preferenceFileKey {
self.sharedPreference = applicationContext.getSharedPreferences(preferenceFileKey, Context.MODE_PRIVATE)
} else {
self.sharedPreference = PreferenceManager.getDefaultSharedPreferences(applicationContext)
}
self.sharedPreferenceEditor = self.sharedPreference.edit()
}
#else
fileprivate let userDefaults: UserDefaults
public init(){
self.userDefaults = UserDefaults.standard
}
#endif
public func set(_ value: Bool, forKey key: String){
#if COOPER
self.sharedPreferenceEditor.putBoolean(key, value)
#else
self.userDefaults.set(value, forKey: key)
#endif
}
public func set(_ value: Int, forKey key: String){
#if COOPER
self.sharedPreferenceEditor.putLong(key, value)
#else
self.userDefaults.set(value, forKey: key)
#endif
}
public func set(_ value: Float, forKey key: String){
#if COOPER
self.sharedPreferenceEditor.putFloat(key, value)
#else
self.userDefaults.set(value, forKey: key)
#endif
}
public func set(_ value: Double, forKey key: String){
#if COOPER
//android sharedPreference for some reason doesn't have double support, store as string then instead
self.sharedPreferenceEditor.putString(key, value.toString())
#else
self.userDefaults.set(value, forKey: key)
#endif
}
public func set(_ value: String, forKey key: String){
#if COOPER
self.sharedPreferenceEditor.putString(key, value)
#else
self.userDefaults.set(value, forKey: key)
#endif
}
public func set(_ value: Set<String>, forKey key: String){
#if COOPER
var javaSet = java.util.HashSet<String>(value)
self.sharedPreferenceEditor.putStringSet(key, javaSet)
#else
self.userDefaults.set([String](value), forKey: key)
#endif
}
public func bool(forKey key: String) -> Bool? {
#if COOPER
return (self.sharedPreference.contains(key)) ? self.sharedPreference.getBoolean(key, false) : nil
#else
return (self.userDefaults.object(forKey: key) != nil) ? self.userDefaults.bool(forKey: key) : nil
#endif
}
public func integer(forKey key: String) -> Int? {
#if COOPER
return (self.sharedPreference.contains(key)) ? self.sharedPreference.getLong(key, 0) : nil
#else
return (self.userDefaults.object(forKey: key) != nil) ? self.userDefaults.integer(forKey: key) : nil
#endif
}
public func float(forKey key: String) -> Float? {
#if COOPER
return (self.sharedPreference.contains(key)) ? self.sharedPreference.getFloat(key, 0.0) : nil
#else
return (self.userDefaults.object(forKey: key) != nil) ? self.userDefaults.float(forKey: key) : nil
#endif
}
public func double(forKey key: String) -> Double? {
#if COOPER
//android sharedPreference for some reason doesn't have double support, it is stored as string instead
return (self.sharedPreference.contains(key)) ? Double.parseDouble(self.sharedPreference.getString(key, "0.0")) : nil
#else
return (self.userDefaults.object(forKey: key) != nil) ? self.userDefaults.double(forKey: key) : nil
#endif
}
public func string(forKey key: String) -> String? {
#if COOPER
return (self.sharedPreference.contains(key)) ? self.sharedPreference.getString(key, "") : nil
#else
return self.userDefaults.string(forKey: key)
#endif
}
public func stringSet(forKey key: String) -> Set<String>? {
#if COOPER
if (self.sharedPreference.contains(key)){
let javaStringSet = java.util.HashSet<String>(self.sharedPreference.getStringSet(key, java.util.HashSet<String>()))
let returnSet = Set<String>()
for entity in javaStringSet {
returnSet.insert(entity)
}
return returnSet
} else {
return nil
}
#else
guard let stringArray = self.userDefaults.stringArray(forKey: key) else {
return nil
}
return Set<String>(stringArray)
#endif
}
public func removeObject(forKey key: String){
#if COOPER
self.sharedPreferenceEditor.remove(key)
#else
self.userDefaults.removeObject(forKey: key)
#endif
}
public func synchronize(){
#if COOPER
self.sharedPreferenceEditor.apply()
#else
_ = self.userDefaults.synchronize()
#endif
}
public func contains(key: String) -> Bool {
#if COOPER
return self.sharedPreference.contains(key)
#else
return self.userDefaults.object(forKey: key) != nil
#endif
}
#if COOPER
public var allKeys: Set<String> {
let javaStringSet = self.sharedPreference.getAll().keySet()
let returnSet = Set<String>()
for entity in javaStringSet {
returnSet.insert(entity)
}
return returnSet
}
#elseif !os(Linux)
public var allKeys: Set<String> {
return Set<String>(self.userDefaults.dictionaryRepresentation().keys)
}
#endif
}
// Array, Dictionary, Date, String, URL, UUID
extension PersistentPropertyList {
/// -remark: Overloading with '_ value:' will result in dex failure in Silver
public func set(array: [Any], forKey key: String) {
#if COOPER
guard let jsonString = try? JSONSerialization.string(withJSONObject: array) else {
return
}
self.set(jsonString, forKey: key)
#else
self.userDefaults.set(array, forKey: key)
#endif
}
public func set(set: Set<AnyHashable>, forKey key: String){
self.set(array: [AnyHashable](set), forKey: key)
}
public func set(_ value: [String: Any], forKey key: String) {
#if COOPER
guard let jsonString = try? JSONSerialization.string(withJSONObject: value) else {
return
}
self.set(jsonString, forKey: key)
#else
self.userDefaults.set(value, forKey: key)
#endif
}
public func set(_ value: Date, forKey key: String) {
#if COOPER
let timeInterval = value.timeIntervalSince1970
self.set(timeInterval, forKey: key)
#else
self.userDefaults.set(value, forKey: key)
#endif
}
public func set(_ value: URL, forKey key: String) {
#if COOPER
let absoluteString = value.absoluteString
self.set(absoluteString, forKey: key)
#else
self.userDefaults.set(value, forKey: key)
#endif
}
public func set(_ uuid: UUID, forKey key: String){
self.set(uuid.uuidString, forKey: key)
}
public func array(forKey key: String) -> [Any]? {
#if COOPER
guard let jsonString = self.string(forKey: key),
let jsonData = Data.with(utf8EncodedString: jsonString)
else {
return nil
}
guard let jsonObject = try? JSONSerialization.jsonObject(with: jsonData)
else {
return nil
}
return jsonObject as? [Any]
#else
return self.userDefaults.array(forKey: key)
#endif
}
public func set(forKey key: String) -> Set<AnyHashable>? {
guard let array = self.array(forKey: key) as? [AnyHashable] else {
return nil
}
return Set<AnyHashable>(array)
}
public func dictionary(forKey key: String) -> [String: Any]? {
#if COOPER
guard let jsonString = self.string(forKey: key),
let jsonData = Data.with(utf8EncodedString: jsonString)
else {
return nil
}
guard let jsonObject = try? JSONSerialization.jsonObject(with: jsonData)
else {
return nil
}
return jsonObject as? [String: Any]
#else
return self.userDefaults.dictionary(forKey: key)
#endif
}
public func date(forKey key: String) -> Date? {
#if COOPER
guard let timeInterval = self.double(forKey: key) else {
return nil
}
return Date(timeIntervalSince1970: timeInterval)
#else
return self.userDefaults.object(forKey: key) as? Date
#endif
}
public func url(forKey key: String) -> URL? {
#if COOPER
guard let absoluteString = self.string(forKey: key) else {
return nil
}
return URL(string: absoluteString)
#else
return self.userDefaults.url(forKey: key)
#endif
}
public func uuid(forKey key: String) -> UUID? {
guard let uuidString = self.string(forKey: key) else {
return nil
}
return UUID(uuidString: uuidString)
}
}
// CustomSerializable support
extension PersistentPropertyList {
public func setCustomSerializable(_ customSerializable: CustomSerializable, forKey key: String) throws {
let serializedDict = try CustomSerialization.dictionary(from: customSerializable)
#if COOPER
let jsonString = try JSONSerialization.string(withJSONObject: serializedDict)
self.set(jsonString, forKey: key)
#else
self.userDefaults.set(serializedDict, forKey: key)
#endif
}
public func set(customSerializableArray: [CustomSerializable], forKey key: String) throws {
let serializedArray = try CustomSerialization.array(from: customSerializableArray)
#if COOPER
let jsonString = try JSONSerialization.string(withJSONObject: serializedArray)
self.set(jsonString, forKey: key)
#else
self.userDefaults.set(serializedArray, forKey: key)
#endif
}
#if COOPER
// if using generics with Class<T> in Silver, the return type of T? will be interpretted as? '? extends CustomSerializable'
// while in Swift you can have strong typing with
// public func customSerializable<T: CustomSerializable>(forKey key: String, ofDesiredType: T.Type, withTotalCustomTypes: [CustomSerializableType]) -> T?
// using the CustomSerializable return type for the sake of matching declarations for now
private func _performCustomSerializationToUnderlyingParsedJSONEntity(forKey key: String, withCustomTypes: [CustomSerializableType]) -> Any? {
guard let jsonString = self.string(forKey: key),
let jsonData = Data.with(utf8EncodedString: jsonString),
let jsonObject = try? JSONSerialization.jsonObject(with: jsonData),
let targetEntity = try? CustomSerialization.applyCustomSerialization(ofCustomTypes: withCustomTypes, to: jsonObject)
else {
return nil
}
return targetEntity
}
public func customSerializable(forKey key: String, withCustomTypes: [CustomSerializableType]) -> CustomSerializable? {
return _performCustomSerializationToUnderlyingParsedJSONEntity(forKey: key, withCustomTypes: withCustomTypes) as? CustomSerializable
}
public func customSerializableArray(forKey key: String, withCustomTypes: [CustomSerializableType]) -> [CustomSerializable]? {
return _performCustomSerializationToUnderlyingParsedJSONEntity(forKey: key, withCustomTypes: withCustomTypes) as? [CustomSerializable]
}
#else
public func customSerializable(forKey key: String, withCustomTypes: [CustomSerializableType]) -> CustomSerializable? {
guard let storedDictionary = self.userDefaults.dictionary(forKey: key),
let customSerializable = try? CustomSerialization.applyCustomSerialization(ofCustomTypes: withCustomTypes, to: storedDictionary)
else {
return nil
}
return customSerializable as? CustomSerializable
}
public func customSerializableArray(forKey key: String, withCustomTypes: [CustomSerializableType]) -> [CustomSerializable]? {
guard let storedDictionary = self.userDefaults.array(forKey: key),
let customSerializableArray = try? CustomSerialization.applyCustomSerialization(ofCustomTypes: withCustomTypes, to: storedDictionary)
else {
return nil
}
return customSerializableArray as? [CustomSerializable]
}
#endif
}
| apache-2.0 |
theodinspire/FingerBlade | FingerBlade/SampleCountTableViewCell.swift | 1 | 928 | //
// SampleCountTableViewCell.swift
// FingerBlade
//
// Created by Eric T Cormack on 3/8/17.
// Copyright © 2017 the Odin Spire. All rights reserved.
//
import UIKit
class SampleCountTableViewCell: UITableViewCell {
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var countStepper: UIStepper!
var delegate: SelectionViewController?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
/// Performs the stepper value changed action
///
/// - Parameter sender: Stepper object
@IBAction func stepped(_ sender: UIStepper) {
let count = Int(sender.value)
countLabel.text = String(count)
delegate?.samplesPerCut = count
}
}
| gpl-3.0 |
cristiannomartins/Tree-Sets | Tree Sets/PopulateDB.swift | 1 | 28037 | //
// PopulateDB.swift
// Tree Sets
//
// Created by Cristianno Vieira on 29/12/16.
// Copyright © 2016 Cristianno Vieira. All rights reserved.
//
import Foundation
import CoreData
import UIKit
class PopulateDB {
// MARK: -- Local variables declarations
static let encoding: String.Encoding = String.Encoding.utf8
// managedObjectContext: interface to access the data model
//static let CDWrapper = CoreDataWrapper()
static let CDWrapper = (UIApplication.shared.delegate as! AppDelegate).CDWrapper
// static let managedObjectContext: NSManagedObjectContext =
// (UIApplication.shared.delegate
// //as! AppDelegate).persistentContainer.viewContext
// as! AppDelegate).managedObjectContext
//static fileprivate var basePokemon: [String:Pokemon] = [:]
static fileprivate var basePkms = [Pokemon]() // references of pkms that were added to the data source
static fileprivate var types = [Type]() // references of types that were added to the data source
static fileprivate var stats = [Stats]() // references of stats that were added to the data source
static fileprivate var abilities = [Ability]() // references of abilities that were added to the data source
static fileprivate var items = [Item]() // references of items that were added to the data source
static fileprivate var moves = [Move]() // references of moves that were added to the data source
static fileprivate var tclasses = [TrainerClass]() // references of Trainer Classes that were added to the data source
static fileprivate var dexes = [(id: Int, dex: Dex)]() // references of Dexes that were added to the data source
static fileprivate var pkmSets = [PokemonSet]() // references of PkmSets that were added to the data source
static var processingQueue = DispatchQueue(label: "com.Tree_Sets.heavyProcessing", attributes: [])
// MARK: -- Auxiliary enums
//Lookup | ID | Ndex | Species | Forme | Type1 | Type2 | Ability1 | Ability2 | AbilityH | HP | Attack | Defense | SpAttack | SpDefense | Speed | Total | Weight | Height | Dex1 | Dex2 | Class | %Male | %Female | Pre-Evolution | Egg Group 1 | Egg Group 2 | Type Concat | Ability Concat
enum PkmTSV: Int {
case species = 0
case id = 1
case nid
//case species
case primaryType = 5
case secondaryType
case ability1
case ability2
case abilityH
case baseHP
case baseAtk
case baseDef
case baseSpa
case baseSpd
case baseSpe
}
enum DexCSV: Int {
// first line of a dex
//case id = 0
//case trainers
// other dex lines (max of 5 repetitions)
case species = 0
case set1
case set2
case set3
case set4
}
// just a shortcut to organize the stats ids
enum StatID: Int16 {
case HP = 0
case Atk
case Def
case Spa
case Spd
case Spe
}
enum ItemCSV: Int {
// Name;Mega Stone;ID;Effect
case name = 0
case ID = 2
}
enum PkmImagesCSV: Int {
// Lookup;ID;subid;Ndex
case species = 0
case ID
}
// Pokemon | Nature | Item | [Moves 1 - 4] | [EV Placement HP-Spe]
enum PkmSetCSV: Int {
case species = 0
case isMega
case nature
case heldItem
case move1
case move2
case move3
case move4
case hpEV
case atkEV
case defEV
case spaEV
case spdEV
case speEV
}
// Name | dex | Category | possible sex | sex | Start | End
enum TrainerCSV: Int {
case name = 0
case dexID
case category
case sex = 4
case start
case end
}
// Trainer Category | Possible Sex | Characteristic
enum TrainerClassCSV: Int {
case name = 0
case possibleSex
case characteristic
}
// MARK: -- Auxiliary getOrCreate functions
static fileprivate func createPokemonSet() -> PokemonSet {
return NSEntityDescription.insertNewObject(forEntityName: "PokemonSet", into: CDWrapper.managedObjectContext) as! PokemonSet
}
static fileprivate func createImage() -> Image {
return NSEntityDescription.insertNewObject(forEntityName: "Image", into: CDWrapper.managedObjectContext) as! Image
}
static fileprivate func getOrCreateMove(_ name: String) -> Move {
let result = moves.filter() { $0.name == name }
if result.count > 1 {
// there is more than one pokemon with the same species: something went wrong!
abort()
}
if result.count == 1 {
return result.first!
}
// TODO: Implement the rest of the moves fields
let newMove = NSEntityDescription.insertNewObject(forEntityName: "Move", into: CDWrapper.managedObjectContext) as! Move
newMove.name = name
moves.append(newMove)
return newMove
}
static var PkmnID = [String:Int]()
static fileprivate func getID(forPkmn name: String) -> Int {
if PkmnID.count > 0 {
return PkmnID[name]!
}
if let contentsOfURL = Bundle.main.url(forResource: "pkmn_images-Table 1-1", withExtension: "csv") {
do {
let content = try String(contentsOf: contentsOfURL, encoding: encoding)
var lines:[String] = content.components(separatedBy: "\r\n") as [String]
lines.remove(at: 0) // gets rid of the header line
for line in lines {
let values = line.components(separatedBy: ";")
PkmnID[values[PkmImagesCSV.species.rawValue]] = Int(values[PkmImagesCSV.ID.rawValue])
}
} catch {
print(error)
}
}
return getID(forPkmn: name)
}
static var ItemID = [String:Int]()
static fileprivate func getID(forItem name: String) -> Int {
if ItemID.count > 0 {
return ItemID[name]!
}
if let contentsOfURL = Bundle.main.url(forResource: "items_images-Table 1-1", withExtension: "csv") {
do {
let content = try String(contentsOf: contentsOfURL, encoding: encoding)
var lines:[String] = content.components(separatedBy: "\r\n") as [String]
lines.remove(at: 0) // gets rid of the header line
for line in lines {
let values = line.components(separatedBy: ";")
ItemID[values[ItemCSV.name.rawValue]] = Int(values[ItemCSV.ID.rawValue])
}
} catch {
print(error)
}
}
return getID(forItem: name)
}
static fileprivate func getOrCreateItem(_ name: String) -> Item {
let result = items.filter() { $0.name == name }
if result.count > 1 {
// there is more than one pokemon with the same species: something went wrong!
abort()
}
if result.count == 1 {
return result.first!
}
// TODO: Implement the image from the items
let newItem = NSEntityDescription.insertNewObject(forEntityName: "Item", into: CDWrapper.managedObjectContext) as! Item
newItem.name = name
let itemID = getID(forItem: name)
let itemImage = createImage()
itemImage.x = NSNumber.init(value: itemID / Image.ImageColumns)
itemImage.y = NSNumber.init(value: itemID % Image.ImageColumns)
newItem.image = itemImage
items.append(newItem)
return newItem
}
static fileprivate func getOrCreateAbility(_ name: String) -> Ability {
let result = abilities.filter() { $0.name == name }
if result.count > 1 {
// there is more than one pokemon with the same species: something went wrong!
abort()
}
if result.count == 1 {
return result.first!
}
let newAbility = NSEntityDescription.insertNewObject(forEntityName: "Ability", into: CDWrapper.managedObjectContext) as! Ability
newAbility.name = name
abilities.append(newAbility)
return newAbility
}
static fileprivate func getOrCreateType(_ name: String) -> Type {
let result = types.filter() { $0.name == name }
if result.count > 1 {
// there is more than one pokemon with the same species: something went wrong!
abort()
}
if result.count == 1 {
return result.first!
}
let newType = NSEntityDescription.insertNewObject(forEntityName: "Type", into: CDWrapper.managedObjectContext) as! Type
newType.name = name
types.append(newType)
return newType
}
static fileprivate func getOrCreateStat(id: Int16, value: Int16) -> Stats {
let result = stats.filter() { $0.id == id && $0.value == value }
if result.count > 1 {
// there is more than one pokemon with the same species: something went wrong!
abort()
}
if result.count == 1 {
return result.first!
}
let newStat = NSEntityDescription.insertNewObject(forEntityName: "Stat", into: CDWrapper.managedObjectContext) as! Stats
newStat.id = id
newStat.value = value
stats.append(newStat)
return newStat
}
static fileprivate func getOrCreatePokemon(ofSpecies species: String) -> Pokemon {
let result = basePkms.filter() { $0.species == species }
if result.count > 1 {
print("there is more than one pokemon with the same species: something went wrong!\n")
abort()
}
if result.count == 1 {
// found the mon
return result.first!
}
// need to create a new mon
let tuples = pkmBaseData.filter() { $0.key == species }
if tuples.count != 1 {
print("there is more/less than one pokemon with the same species: something went wrong!\n")
abort()
}
let monData = tuples.first!
let newMon = NSEntityDescription.insertNewObject(forEntityName: "Pokemon", into: CDWrapper.managedObjectContext) as! Pokemon
newMon.species = monData.key
// TODO: What should I do on these cases?
if monData.value.count > 1 {
print("More than one found for species \(monData.key):\n")
for value in monData.value {
print("\t\(value)\n")
}
}
let values = monData.value.first!.components(separatedBy: "\t")
newMon.id = Int32(values[PkmTSV.id.rawValue])!
newMon.firstAbility = getOrCreateAbility(values[PkmTSV.ability1.rawValue])
newMon.secondAbility = getOrCreateAbility(values[PkmTSV.ability2.rawValue])
newMon.hiddenAbility = getOrCreateAbility(values[PkmTSV.abilityH.rawValue])
newMon.type1 = getOrCreateType(values[PkmTSV.primaryType.rawValue])
newMon.type2 = getOrCreateType(values[PkmTSV.secondaryType.rawValue])
var baseStats = [Stats]()
baseStats.append(getOrCreateStat(id: StatID.HP.rawValue, value: Int16(values[PkmTSV.baseHP.rawValue])!))
baseStats.append(getOrCreateStat(id: StatID.Atk.rawValue, value: Int16(values[PkmTSV.baseAtk.rawValue])!))
baseStats.append(getOrCreateStat(id: StatID.Def.rawValue, value: Int16(values[PkmTSV.baseDef.rawValue])!))
baseStats.append(getOrCreateStat(id: StatID.Spa.rawValue, value: Int16(values[PkmTSV.baseSpa.rawValue])!))
baseStats.append(getOrCreateStat(id: StatID.Spd.rawValue, value: Int16(values[PkmTSV.baseSpd.rawValue])!))
baseStats.append(getOrCreateStat(id: StatID.Spe.rawValue, value: Int16(values[PkmTSV.baseSpe.rawValue])!))
//print("1\n")
newMon.baseStats = NSSet(array: baseStats)
//print("2\n")
basePkms.append(newMon)
return newMon
}
// MARK: -- Other functions
/**
* Returns a dictionary that contains an array representing the different forms
* a given pokemon can have. A string containing the pokemon species is the key.
*/
static fileprivate func getPokemonBasicData() -> [String:[String]] {
var pokemons = [String:[String]]()
if let contentsOfURL = Bundle.main.url(forResource: "Battle Tree Lookup - Pokedex", withExtension: "tsv") {
do {
let content = try String(contentsOf: contentsOfURL, encoding: encoding)
var lines:[String] = content.components(separatedBy: "\r\n") as [String]
lines.remove(at: 0) // gets rid of the header line
for line in lines {
let values = line.components(separatedBy: "\t")
if pokemons[values[PkmTSV.species.rawValue]] == nil {
pokemons[values[PkmTSV.species.rawValue]] = []
}
pokemons[values[PkmTSV.species.rawValue]]!.append(line)
}
} catch {
print(error)
}
}
return pokemons
}
static fileprivate func getRecalcStats(stats precalcStats: [Stats], forItem item: Item) -> NSSet {
// TODO: Implement this function to recalculate the stats based on the item
var newStats = [Stats]()
for stat in precalcStats {
switch PokemonSet.PkmnStats(rawValue: stat.id)! {
case .hp:
newStats.append(stat)
case .atk:
if item.name == "Choice Band" {
newStats.append(getOrCreateStat(id: PokemonSet.PkmnStats.atk.rawValue, value: Int16(Double(stat.value)*1.5)))
} else {
newStats.append(stat)
}
case .def:
newStats.append(stat)
case .spa:
if item.name == "Choice Specs" {
newStats.append(getOrCreateStat(id: PokemonSet.PkmnStats.spa.rawValue, value: Int16(Double(stat.value)*1.5)))
} else {
newStats.append(stat)
}
case .spd:
newStats.append(stat)
case .spe:
if item.name == "Choice Scarf" {
newStats.append(getOrCreateStat(id: PokemonSet.PkmnStats.spe.rawValue, value: Int16(Double(stat.value)*1.5)))
} else {
newStats.append(stat)
}
}
}
return NSSet(array: newStats)
}
static fileprivate func createImage(forPokemon id: Int) -> Image {
let img = NSEntityDescription.insertNewObject(forEntityName: "Image", into: CDWrapper.managedObjectContext) as! Image
img.x = NSNumber(value: id / Image.PkmColumns)
img.y = NSNumber(value: id % Image.PkmColumns)
return img
}
static fileprivate let pkmBaseData = getPokemonBasicData() // raw data of all pkm species
//static fileprivate var altForms = [[String]]() // species of alternate forms
static fileprivate func parsePkms() {
if let contentsOfURL = Bundle.main.url(forResource: "Pokemon-Table 1", withExtension: "csv") {
do {
let content = try String(contentsOf: contentsOfURL, encoding: encoding)
var lines:[String] = content.components(separatedBy: "\r\n") as [String]
lines.remove(at: 0) // gets rid of the header line
var index = 0
while index < lines.count {
var species = ""
var bckspecies = ""
var basePkm: Pokemon!
for i in 0...3 {
var values = lines[index + i].components(separatedBy: ";")
if i == 0 {
species = values[0]
}
bckspecies = species
// creates a new line with the same species but a different form
if values[PkmSetCSV.isMega.rawValue] == "Mega" { // Megas
species = "\(species) (Mega \(species))"
}
basePkm = getOrCreatePokemon(ofSpecies: species)
// empty line of alternative sets
if values[PkmSetCSV.heldItem.rawValue] == "" {
//species = bckspecies
continue
}
let newPkmSet = createPokemonSet()
newPkmSet.species = basePkm
newPkmSet.setID = (i + 1) as NSNumber?
newPkmSet.nature = values[PkmSetCSV.nature.rawValue]
newPkmSet.holding = getOrCreateItem(values[PkmSetCSV.heldItem.rawValue])
var evs = [Stats]()
var divisor = 0
for c in PkmSetCSV.hpEV.rawValue...PkmSetCSV.speEV.rawValue {
if values[c] != "" {
divisor += 1
}
}
let investment = divisor == 2 ? 252 : 164
evs.append(getOrCreateStat(id: StatID.HP.rawValue,
value: Int16(values[PkmSetCSV.hpEV.rawValue] == "" ? 0 : investment) ))
evs.append(getOrCreateStat(id: StatID.Atk.rawValue,
value: Int16(values[PkmSetCSV.atkEV.rawValue] == "" ? 0 : investment) ))
evs.append(getOrCreateStat(id: StatID.Def.rawValue,
value: Int16(values[PkmSetCSV.defEV.rawValue] == "" ? 0 : investment) ))
evs.append(getOrCreateStat(id: StatID.Spa.rawValue,
value: Int16(values[PkmSetCSV.spaEV.rawValue] == "" ? 0 : investment) ))
evs.append(getOrCreateStat(id: StatID.Spd.rawValue,
value: Int16(values[PkmSetCSV.spdEV.rawValue] == "" ? 0 : investment) ))
evs.append(getOrCreateStat(id: StatID.Spe.rawValue,
value: Int16(values[PkmSetCSV.speEV.rawValue] == "" ? 0 : investment) ))
newPkmSet.evs = NSSet(array: evs)
var precalcStats = [Stats]()
precalcStats.append(getOrCreateStat(id: StatID.HP.rawValue, value: Int16(newPkmSet.getStatValue(PokemonSet.PkmnStats.hp))))
precalcStats.append(getOrCreateStat(id: StatID.Atk.rawValue, value: Int16(newPkmSet.getStatValue(PokemonSet.PkmnStats.atk))))
precalcStats.append(getOrCreateStat(id: StatID.Def.rawValue, value: Int16(newPkmSet.getStatValue(PokemonSet.PkmnStats.def))))
precalcStats.append(getOrCreateStat(id: StatID.Spa.rawValue, value: Int16(newPkmSet.getStatValue(PokemonSet.PkmnStats.spa))))
precalcStats.append(getOrCreateStat(id: StatID.Spd.rawValue, value: Int16(newPkmSet.getStatValue(PokemonSet.PkmnStats.spd))))
precalcStats.append(getOrCreateStat(id: StatID.Spe.rawValue, value: Int16(newPkmSet.getStatValue(PokemonSet.PkmnStats.spe))))
newPkmSet.preCalcStatsNoItem = NSSet(array: precalcStats)
newPkmSet.preCalcStats = getRecalcStats(stats: precalcStats, forItem: newPkmSet.holding!)
var moveSet = [Move]()
moveSet.append(getOrCreateMove(values[PkmSetCSV.move1.rawValue]))
moveSet.append(getOrCreateMove(values[PkmSetCSV.move2.rawValue]))
moveSet.append(getOrCreateMove(values[PkmSetCSV.move3.rawValue]))
moveSet.append(getOrCreateMove(values[PkmSetCSV.move4.rawValue]))
newPkmSet.moveSet = NSSet(array: moveSet)
newPkmSet.image = createImage(forPokemon: getID(forPkmn:newPkmSet.species!.species!))
//try? newPkmSet.managedObjectContext?.save()
pkmSets.append(newPkmSet)
//print("\(species), set \(i): OK")
species = bckspecies
}
index += 4
}
//CDWrapper.saveContext()
} catch {
print(error)
}
}
}
static fileprivate func getTrainerClassPossibleSex(_ name: String) -> String {
if let contentsOfURL = Bundle.main.url(forResource: "Trainer Category-Table 1", withExtension: "csv") {
do {
let content = try String(contentsOf: contentsOfURL, encoding: encoding)
var lines:[String] = content.components(separatedBy: "\r\n") as [String]
lines.remove(at: 0) // gets rid of the header line
for line in lines {
let values = line.components(separatedBy: ";")
if values[TrainerClassCSV.name.rawValue] == name {
return values[TrainerClassCSV.possibleSex.rawValue]
}
}
} catch {
print(error)
}
}
//print("Could not find trainer class named \(name) on Trainer Category Table.")
//abort()
return "?" // undiscovered trainer class
}
static fileprivate func getPkmSet(pkmNamed species: String, id setID: Int) -> PokemonSet {
if let result = findPkmSet(pkmNamed: species, id: setID) { // regular form
return result
} else if let result = findPkmSet(pkmNamed: "\(species) (Mega \(species))", id: setID) { // mega
return result
} else {
abort()
}
}
static fileprivate func findPkmSet(pkmNamed species: String, id setID: Int) -> PokemonSet? {
let result = pkmSets.filter() { $0.species?.species == species }
if result.count == 0 {
// there is no pokemon from that species on the db
abort()
}
for res in result {
if Int(res.setID!) == setID {
return res
}
}
//
// // Could not find a pkmSet with the same id as requested
// abort()
return nil
}
static fileprivate func parseDexes() {
if let contentsOfURL = Bundle.main.url(forResource: "Dex-Table 1", withExtension: "csv") {
do {
let content = try String(contentsOf: contentsOfURL, encoding: encoding)
let lines:[String] = content.components(separatedBy: "\r\n") as [String]
var curr = 0
while (curr < lines.count) {
// first line of a dex (only the id matters)
let id = Int(lines[curr].components(separatedBy: ";")[0])!
curr += 1
var values = lines[curr].components(separatedBy: ";")
let newDex = NSEntityDescription.insertNewObject(forEntityName: "Dex", into: CDWrapper.managedObjectContext) as! Dex
var pkmSets = [PokemonSet]()
while values[0] != "" {
for setID in 1...4 {
if values[setID] == "\(setID)" {
pkmSets.append(getPkmSet(pkmNamed: values[DexCSV.species.rawValue], id: setID))
}
}
values.removeFirst(5)
if values.count == 0 { // this line has ended
curr += 1
// there are no more lines available
if curr == lines.count {
values.append("")
continue
}
values = lines[curr].components(separatedBy: ";")
} else if values[0] == "" { // or this line was an incomplete one
curr += 1
}
}
newDex.contains = NSSet(array:pkmSets)
dexes.append((id: id, dex: newDex))
curr += 1
}
} catch {
print(error)
}
}
}
static fileprivate func getDex(_ id: Int) -> Dex {
if dexes.count == 0 {
parseDexes()
}
let result = dexes.filter() { $0.id == id }
if result.count > 1 {
// there is more than one dex with the same id: something went wrong!
abort()
}
if result.count == 1 {
return result.first!.dex
}
print("Could not find dex with id \(id).")
abort()
}
static fileprivate func getOrCreateTrainerClass(_ name: String) -> TrainerClass {
let result = tclasses.filter() { $0.name == name }
if result.count > 1 {
// there is more than one pokemon with the same species: something went wrong!
abort()
}
if result.count == 1 {
return result.first!
}
// TODO: Implement the image of Trainer Class
let newTClass = NSEntityDescription.insertNewObject(forEntityName: "TrainerClass", into: CDWrapper.managedObjectContext) as! TrainerClass
newTClass.name = name
newTClass.possibleSex = getTrainerClassPossibleSex(name)
tclasses.append(newTClass)
return newTClass
}
static fileprivate func parseTrainers() /*-> [Trainer]*/ {
//var trainers = [Trainer]()
if let contentsOfURL = Bundle.main.url(forResource: "Trainer-Table 1", withExtension: "csv") {
do {
let content = try String(contentsOf: contentsOfURL, encoding: encoding)
var lines:[String] = content.components(separatedBy: "\r\n") as [String]
lines.remove(at: 0) // gets rid of the header line
for line in lines {
let values = line.components(separatedBy: ";")
// TODO: Implement the quotes spoken by the trainers
let newTrainer = NSEntityDescription.insertNewObject(forEntityName: "Trainer", into: CDWrapper.managedObjectContext) as! Trainer
newTrainer.name = values[TrainerCSV.name.rawValue]
newTrainer.sex = values[TrainerCSV.sex.rawValue]
newTrainer.start = values[TrainerCSV.start.rawValue] == "" ? nil : values[TrainerCSV.start.rawValue]
newTrainer.end = values[TrainerCSV.end.rawValue] == "" ? nil : values[TrainerCSV.end.rawValue]
newTrainer.trainerClass = getOrCreateTrainerClass(values[TrainerCSV.category.rawValue])
newTrainer.availableMons = getDex(Int(values[TrainerCSV.dexID.rawValue])!)
//try? newTrainer.managedObjectContext?.save()
//trainers.append(newTrainer)
}
//CDWrapper.saveContext()
} catch {
print(error)
}
}
//return trainers
}
/**
* Remove all content inside the database (for debugging purposes)
*/
static fileprivate func removeData () {
// Remove the existing mons-sets and trainers
let fetchMonSets = NSFetchRequest<PokemonSet>(entityName: "PokemonSet")
let fetchTrainers = NSFetchRequest<Trainer>(entityName: "Trainer")
do {
let pkms = try CDWrapper.managedObjectContext.fetch(fetchMonSets)
for pkm in pkms {
CDWrapper.managedObjectContext.delete(pkm)
}
let trainers = try CDWrapper.managedObjectContext.fetch(fetchTrainers)
for trainer in trainers {
CDWrapper.managedObjectContext.delete(trainer)
}
} catch {
print("Failed to retrieve record: \(error)")
}
// Remove the existing items, moves and pkm
let fetchItems = NSFetchRequest<Item>(entityName: "Item")
let fetchMoves = NSFetchRequest<Move>(entityName: "Move")
let fetchMons = NSFetchRequest<Pokemon>(entityName: "Pokemon")
do {
let items = try CDWrapper.managedObjectContext.fetch(fetchItems)
for item in items {
CDWrapper.managedObjectContext.delete(item)
}
let moves = try CDWrapper.managedObjectContext.fetch(fetchMoves)
for move in moves {
CDWrapper.managedObjectContext.delete(move)
}
let pkms = try CDWrapper.managedObjectContext.fetch(fetchMons)
for pkm in pkms {
CDWrapper.managedObjectContext.delete(pkm)
}
} catch {
print("Failed to retrieve record: \(error)")
}
// Remove the existing dexes, abilities, types and trainer categories
let fetchTrainerCat = NSFetchRequest<TrainerClass>(entityName: "TrainerClass")
let fetchDex = NSFetchRequest<Dex>(entityName: "Dex")
let fetchAbility = NSFetchRequest<Ability>(entityName: "Ability")
let fetchType = NSFetchRequest<Type>(entityName: "Type")
do {
let cats = try CDWrapper.managedObjectContext.fetch(fetchTrainerCat)
for cat in cats {
CDWrapper.managedObjectContext.delete(cat)
}
let dexes = try CDWrapper.managedObjectContext.fetch(fetchDex)
for dex in dexes {
CDWrapper.managedObjectContext.delete(dex)
}
let abilities = try CDWrapper.managedObjectContext.fetch(fetchAbility)
for ability in abilities {
CDWrapper.managedObjectContext.delete(ability)
}
let types = try CDWrapper.managedObjectContext.fetch(fetchType)
for type in types {
CDWrapper.managedObjectContext.delete(type)
}
} catch {
print("Failed to retrieve record: \(error)")
}
}
static func preload() {
removeData()
parsePkms()
//parseAlternateForms()
parseTrainers()
//CDWrapper.saveContext()
}
}
| mit |
DerrickQin2853/SinaWeibo-Swift | SinaWeibo/SinaWeibo/Classes/View/EmoticonKeyboard/View/DQEmoticonToolBar.swift | 1 | 2614 | //
// DQEmoticonToolBar.swift
// SinaWeibo
//
// Created by admin on 2016/10/8.
// Copyright © 2016年 Derrick_Qin. All rights reserved.
//
import UIKit
enum EmoticonType: Int {
case RECENT = 0
case DEFAULT
case EMOJI
case LXH
}
class DQEmoticonToolBar: UIStackView {
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
axis = .horizontal
distribution = .fillEqually
tag = 999
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
addButton(title: "最近", backgroundImageName: "compose_emotion_table_left", type: .RECENT)
addButton(title: "默认", backgroundImageName: "compose_emotion_table_mid", type: .DEFAULT)
addButton(title: "Emoji", backgroundImageName: "compose_emotion_table_mid", type: .EMOJI)
addButton(title: "浪小花", backgroundImageName: "compose_emotion_table_right", type: .LXH)
}
private func addButton(title: String, backgroundImageName: String, type: EmoticonType) {
let button = UIButton()
button.tag = type.rawValue
button.setBackgroundImage(UIImage(named: backgroundImageName + "_normal"), for: .normal)
button.setBackgroundImage(UIImage(named: backgroundImageName + "_selected"), for: .selected)
button.setTitle(title, for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.setTitleColor(UIColor.darkGray, for: .selected)
button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
button.addTarget(self, action: #selector(buttonClick(btn:)), for: .touchUpInside)
self.addArrangedSubview(button)
if type == .RECENT {
button.isSelected = true
lastSelectedButton = button
}
}
func setButtonSelected(indexPath: IndexPath) {
let btn = self.viewWithTag(indexPath.section) as! UIButton
if btn.isSelected {
return
}
lastSelectedButton?.isSelected = false
lastSelectedButton = btn
btn.isSelected = true
}
@objc private func buttonClick(btn: UIButton) {
if btn.isSelected {
return
}
lastSelectedButton?.isSelected = false
lastSelectedButton = btn
btn.isSelected = true
emoticonTypeSelectClosure?(EmoticonType.init(rawValue: btn.tag)!)
}
var lastSelectedButton: UIButton?
var emoticonTypeSelectClosure: ((EmoticonType) -> ())?
}
| mit |
ios-ximen/DYZB | 斗鱼直播/Pods/Kingfisher/Sources/UIButton+Kingfisher.swift | 68 | 19447 | //
// UIButton+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/13.
//
// Copyright (c) 2017 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
// MARK: - Set Images
/**
* Set image to use in button from web for a specified state.
*/
extension Kingfisher where Base: UIButton {
/**
Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and
completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
If `resource` is `nil`, the `placeholder` image will be set and
`completionHandler` will be called with both `error` and `image` being `nil`.
*/
@discardableResult
public func setImage(with resource: Resource?,
for state: UIControlState,
placeholder: UIImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
guard let resource = resource else {
base.setImage(placeholder, for: state)
setWebURL(nil, for: state)
completionHandler?(nil, nil, .none, nil)
return .empty
}
let options = KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo)
if !options.keepCurrentImageWhileLoading {
base.setImage(placeholder, for: state)
}
setWebURL(resource.downloadURL, for: state)
let task = KingfisherManager.shared.retrieveImage(
with: resource,
options: options,
progressBlock: { receivedSize, totalSize in
guard resource.downloadURL == self.webURL(for: state) else {
return
}
if let progressBlock = progressBlock {
progressBlock(receivedSize, totalSize)
}
},
completionHandler: {[weak base] image, error, cacheType, imageURL in
DispatchQueue.main.safeAsync {
guard let strongBase = base, imageURL == self.webURL(for: state) else {
completionHandler?(image, error, cacheType, imageURL)
return
}
self.setImageTask(nil)
if image != nil {
strongBase.setImage(image, for: state)
}
completionHandler?(image, error, cacheType, imageURL)
}
})
setImageTask(task)
return task
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func cancelImageDownloadTask() {
imageTask?.cancel()
}
/**
Set the background image to use for a specified state with a resource,
a placeholder image, options progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
If `resource` is `nil`, the `placeholder` image will be set and
`completionHandler` will be called with both `error` and `image` being `nil`.
*/
@discardableResult
public func setBackgroundImage(with resource: Resource?,
for state: UIControlState,
placeholder: UIImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
guard let resource = resource else {
base.setBackgroundImage(placeholder, for: state)
setBackgroundWebURL(nil, for: state)
completionHandler?(nil, nil, .none, nil)
return .empty
}
let options = KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo)
if !options.keepCurrentImageWhileLoading {
base.setBackgroundImage(placeholder, for: state)
}
setBackgroundWebURL(resource.downloadURL, for: state)
let task = KingfisherManager.shared.retrieveImage(
with: resource,
options: options,
progressBlock: { receivedSize, totalSize in
guard resource.downloadURL == self.backgroundWebURL(for: state) else {
return
}
if let progressBlock = progressBlock {
progressBlock(receivedSize, totalSize)
}
},
completionHandler: { [weak base] image, error, cacheType, imageURL in
DispatchQueue.main.safeAsync {
guard let strongBase = base, imageURL == self.backgroundWebURL(for: state) else {
completionHandler?(image, error, cacheType, imageURL)
return
}
self.setBackgroundImageTask(nil)
if image != nil {
strongBase.setBackgroundImage(image, for: state)
}
completionHandler?(image, error, cacheType, imageURL)
}
})
setBackgroundImageTask(task)
return task
}
/**
Cancel the background image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func cancelBackgroundImageDownloadTask() {
backgroundImageTask?.cancel()
}
}
// MARK: - Associated Object
private var lastURLKey: Void?
private var imageTaskKey: Void?
extension Kingfisher where Base: UIButton {
/**
Get the image URL binded to this button for a specified state.
- parameter state: The state that uses the specified image.
- returns: Current URL for image.
*/
public func webURL(for state: UIControlState) -> URL? {
return webURLs[NSNumber(value:state.rawValue)] as? URL
}
fileprivate func setWebURL(_ url: URL?, for state: UIControlState) {
webURLs[NSNumber(value:state.rawValue)] = url
}
fileprivate var webURLs: NSMutableDictionary {
var dictionary = objc_getAssociatedObject(base, &lastURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
setWebURLs(dictionary!)
}
return dictionary!
}
fileprivate func setWebURLs(_ URLs: NSMutableDictionary) {
objc_setAssociatedObject(base, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
fileprivate var imageTask: RetrieveImageTask? {
return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask
}
fileprivate func setImageTask(_ task: RetrieveImageTask?) {
objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private var lastBackgroundURLKey: Void?
private var backgroundImageTaskKey: Void?
extension Kingfisher where Base: UIButton {
/**
Get the background image URL binded to this button for a specified state.
- parameter state: The state that uses the specified background image.
- returns: Current URL for background image.
*/
public func backgroundWebURL(for state: UIControlState) -> URL? {
return backgroundWebURLs[NSNumber(value:state.rawValue)] as? URL
}
fileprivate func setBackgroundWebURL(_ url: URL?, for state: UIControlState) {
backgroundWebURLs[NSNumber(value:state.rawValue)] = url
}
fileprivate var backgroundWebURLs: NSMutableDictionary {
var dictionary = objc_getAssociatedObject(base, &lastBackgroundURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
setBackgroundWebURLs(dictionary!)
}
return dictionary!
}
fileprivate func setBackgroundWebURLs(_ URLs: NSMutableDictionary) {
objc_setAssociatedObject(base, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
fileprivate var backgroundImageTask: RetrieveImageTask? {
return objc_getAssociatedObject(base, &backgroundImageTaskKey) as? RetrieveImageTask
}
fileprivate func setBackgroundImageTask(_ task: RetrieveImageTask?) {
objc_setAssociatedObject(base, &backgroundImageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Deprecated. Only for back compatibility.
/**
* Set image to use from web for a specified state. Deprecated. Use `kf` namespacing instead.
*/
extension UIButton {
/**
Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and
completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
@discardableResult
@available(*, deprecated,
message: "Extensions directly on UIButton are deprecated. Use `button.kf.setImage` instead.",
renamed: "kf.setImage")
public func kf_setImage(with resource: Resource?,
for state: UIControlState,
placeholder: UIImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
return kf.setImage(with: resource, for: state, placeholder: placeholder, options: options,
progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
@available(*, deprecated,
message: "Extensions directly on UIButton are deprecated. Use `button.kf.cancelImageDownloadTask` instead.",
renamed: "kf.cancelImageDownloadTask")
public func kf_cancelImageDownloadTask() { kf.cancelImageDownloadTask() }
/**
Set the background image to use for a specified state with a resource,
a placeholder image, options progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
@discardableResult
@available(*, deprecated,
message: "Extensions directly on UIButton are deprecated. Use `button.kf.setBackgroundImage` instead.",
renamed: "kf.setBackgroundImage")
public func kf_setBackgroundImage(with resource: Resource?,
for state: UIControlState,
placeholder: UIImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
return kf.setBackgroundImage(with: resource, for: state, placeholder: placeholder, options: options,
progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Cancel the background image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
@available(*, deprecated,
message: "Extensions directly on UIButton are deprecated. Use `button.kf.cancelBackgroundImageDownloadTask` instead.",
renamed: "kf.cancelBackgroundImageDownloadTask")
public func kf_cancelBackgroundImageDownloadTask() { kf.cancelBackgroundImageDownloadTask() }
/**
Get the image URL binded to this button for a specified state.
- parameter state: The state that uses the specified image.
- returns: Current URL for image.
*/
@available(*, deprecated,
message: "Extensions directly on UIButton are deprecated. Use `button.kf.webURL` instead.",
renamed: "kf.webURL")
public func kf_webURL(for state: UIControlState) -> URL? { return kf.webURL(for: state) }
@available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setWebURL")
fileprivate func kf_setWebURL(_ url: URL, for state: UIControlState) { kf.setWebURL(url, for: state) }
@available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.webURLs")
fileprivate var kf_webURLs: NSMutableDictionary { return kf.webURLs }
@available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setWebURLs")
fileprivate func kf_setWebURLs(_ URLs: NSMutableDictionary) { kf.setWebURLs(URLs) }
@available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.imageTask")
fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask }
@available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setImageTask")
fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) }
/**
Get the background image URL binded to this button for a specified state.
- parameter state: The state that uses the specified background image.
- returns: Current URL for background image.
*/
@available(*, deprecated,
message: "Extensions directly on UIButton are deprecated. Use `button.kf.backgroundWebURL` instead.",
renamed: "kf.backgroundWebURL")
public func kf_backgroundWebURL(for state: UIControlState) -> URL? { return kf.backgroundWebURL(for: state) }
@available(*, deprecated,
message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundWebURL")
fileprivate func kf_setBackgroundWebURL(_ url: URL, for state: UIControlState) {
kf.setBackgroundWebURL(url, for: state)
}
@available(*, deprecated,
message: "Extensions directly on UIButton are deprecated.",renamed: "kf.backgroundWebURLs")
fileprivate var kf_backgroundWebURLs: NSMutableDictionary { return kf.backgroundWebURLs }
@available(*, deprecated,
message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundWebURLs")
fileprivate func kf_setBackgroundWebURLs(_ URLs: NSMutableDictionary) { kf.setBackgroundWebURLs(URLs) }
@available(*, deprecated,
message: "Extensions directly on UIButton are deprecated.",renamed: "kf.backgroundImageTask")
fileprivate var kf_backgroundImageTask: RetrieveImageTask? { return kf.backgroundImageTask }
@available(*, deprecated,
message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundImageTask")
fileprivate func kf_setBackgroundImageTask(_ task: RetrieveImageTask?) { return kf.setBackgroundImageTask(task) }
}
| mit |
emilstahl/swift | validation-test/compiler_crashers/26939-swift-patternbindingdecl-setpattern.swift | 9 | 329 | // RUN: not --crash %target-swift-frontend %s -parse
// 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 P{{S:{enum S<T where A<T>:P{class a{let a=[{let a{struct b{var d{var _=c{class d{{}class d{let:{let c
| apache-2.0 |
emilstahl/swift | test/SourceKit/CodeFormat/indent-closure.swift | 10 | 1478 | func foo() {
bar() {
var abc = 1
let a: String = {
let b = "asdf"
return b
}()
}
}
class C {
private static let durationTimeFormatter: NSDateComponentsFormatter = {
return timeFormatter
}()
}
func foo1(a: Int, handler : ()->()) {}
func foo2(handler : () ->()) {}
func foo3() {
foo1(1)
{
}
}
// RUN: %sourcekitd-test -req=format -line=3 -length=1 %s >%t.response
// RUN: %sourcekitd-test -req=format -line=4 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=5 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=6 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=7 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=8 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=14 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=22 -length=1 %s >>%t.response
// RUN: FileCheck --strict-whitespace %s <%t.response
// CHECK: key.sourcetext: " var abc = 1"
// CHECK: key.sourcetext: " let a: String = {"
// CHECK: key.sourcetext: " let b = "asdf""
// CHECK: key.sourcetext: " return b"
// CHECK: key.sourcetext: " }()"
// CHECK: key.sourcetext: " }"
// " private static let durationTimeFormatter: NSDateComponentsFormatter = {"
// CHECK: key.sourcetext: " }()"
// " foo1(1)"
// CHECK: key.sourcetext: " {"
| apache-2.0 |
jbennett/Issues | IssuesKit/TrackingService.swift | 1 | 763 | //
// TrackingService.swift
// Issues
//
// Created by Jonathan Bennett on 2015-12-25.
// Copyright © 2015 Jonathan Bennett. All rights reserved.
//
import Foundation
public enum TrackingService: String {
case Github
case Sifter
public func title() -> String {
switch self {
case .Sifter: return "Sifter"
case .Github: return "Github"
// default: return self.rawValue
}
}
public func logoName() -> String {
switch self {
case .Sifter: return "Sifter Logo"
case .Github: return "Github Logo"
}
}
public func logoImage() -> UIImage {
let bundle = NSBundle(forClass: ServiceTypeTableViewCell.self)
return UIImage(named: self.logoName(), inBundle: bundle, compatibleWithTraitCollection: nil)!
}
}
| mit |
SmartCodeLab/SwiftDevTools | SwiftDevTools/Classes/DeviceTools.swift | 1 | 807 | //
// DeviceTools.swift
// Pods
//
// Created by FengJerry on 17/7/3.
//
//
import Foundation
/*
* 获取设备token
*/
public func getDeviceToken() -> String {
return (UIDevice.current.identifierForVendor?.uuidString)!
}
/*
* 获取设备名称
*/
public func getDeviceName() -> String {
return UIDevice.current.name
}
/*
* 获取系统名称
*/
public func getSystemName() -> String {
return UIDevice.current.systemName
}
/*
* 获取系统版本
*/
public func getSystemVersion() -> String {
return UIDevice.current.systemVersion
}
/*
* 获取设备型号
*/
public func getSystemModel() -> String {
return UIDevice.current.model
}
/*
* 获取设备区域化型号
*/
public func getLocalizedSystemModel() -> String {
return UIDevice.current.localizedModel
}
| mit |
JamieScanlon/AugmentKit | AugmentKit/Renderer/Passes/DrawCall.swift | 1 | 17939 | //
// DrawCall.swift
// AugmentKit
//
// MIT License
//
// Copyright (c) 2018 JamieScanlon
//
// 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 AugmentKitShader
// MARK: - DrawCall
/// Represents a draw call which is a single mesh geometry that is rendered with a Vertex / Fragment Shader. A single draw call can have many submeshes. Each submesh calls `drawIndexPrimitives`
struct DrawCall {
var uuid: UUID
var renderPipelineState: MTLRenderPipelineState {
guard qualityRenderPipelineStates.count > 0 else {
fatalError("Attempting to fetch the `renderPipelineState` property before the render pipelines states have not been initialized")
}
return qualityRenderPipelineStates[0]
}
var qualityRenderPipelineStates = [MTLRenderPipelineState]()
var depthStencilState: MTLDepthStencilState?
var cullMode: MTLCullMode = .back
var depthBias: RenderPass.DepthBias?
var drawData: DrawData?
var usesSkeleton: Bool {
if let myDrawData = drawData {
return myDrawData.skeleton != nil
} else {
return false
}
}
var vertexFunction: MTLFunction? {
guard qualityVertexFunctions.count > 0 else {
return nil
}
return qualityVertexFunctions[0]
}
var qualityVertexFunctions = [MTLFunction]()
var fragmentFunction: MTLFunction? {
guard qualityFragmentFunctions.count > 0 else {
return nil
}
return qualityFragmentFunctions[0]
}
var qualityFragmentFunctions = [MTLFunction]()
/// Create a new `DralCall`
/// - Parameters:
/// - renderPipelineState: A render pipeline state used for the command encoder
/// - depthStencilState: The depth stencil state used for the command encoder
/// - cullMode: The `cullMode` property that will be used for the render encoder
/// - depthBias: The optional `depthBias` property that will be used for the render encoder
/// - drawData: The draw call data
/// - uuid: An unique identifier for this draw call
init(renderPipelineState: MTLRenderPipelineState, depthStencilState: MTLDepthStencilState? = nil, cullMode: MTLCullMode = .back, depthBias: RenderPass.DepthBias? = nil, drawData: DrawData? = nil, uuid: UUID = UUID()) {
self.uuid = uuid
self.qualityRenderPipelineStates.append(renderPipelineState)
self.depthStencilState = depthStencilState
self.cullMode = cullMode
self.depthBias = depthBias
self.drawData = drawData
}
/// Create a new `DralCall`
/// - Parameters:
/// - qualityRenderPipelineStates: An array of render pipeline states for each quality level. The index of the render pipeline state will be it's quality level. the number of `qualityRenderPipelineStates` determines the number of distinct Levels of Detail. The descriptor at 0 should be the **highest** quality state with the quality level reducing as the index gets higher.
/// - depthStencilState: The depth stencil state used for the command encoder
/// - cullMode: The `cullMode` property that will be used for the render encoder
/// - depthBias: The optional `depthBias` property that will be used for the render encoder
/// - drawData: The draw call data
/// - uuid: An unique identifier for this draw call
init(qualityRenderPipelineStates: [MTLRenderPipelineState], depthStencilState: MTLDepthStencilState? = nil, cullMode: MTLCullMode = .back, depthBias: RenderPass.DepthBias? = nil, drawData: DrawData? = nil, uuid: UUID = UUID()) {
self.uuid = uuid
self.qualityRenderPipelineStates = qualityRenderPipelineStates
self.qualityRenderPipelineStates.append(renderPipelineState)
self.depthStencilState = depthStencilState
self.cullMode = cullMode
self.depthBias = depthBias
self.drawData = drawData
}
/// Create a new `DralCall`
/// - Parameters:
/// - device: The metal device used to create the render pipeline state
/// - renderPipelineDescriptor: The render pass descriptor used to create the render pipeline state
/// - depthStencilDescriptor: The depth stencil descriptor used to make the depth stencil state
/// - cullMode: The `cullMode` property that will be used for the render encoder
/// - depthBias: The optional `depthBias` property that will be used for the render encoder
/// - drawData: The draw call data
init(withDevice device: MTLDevice, renderPipelineDescriptor: MTLRenderPipelineDescriptor, depthStencilDescriptor: MTLDepthStencilDescriptor? = nil, cullMode: MTLCullMode = .back, depthBias: RenderPass.DepthBias? = nil, drawData: DrawData? = nil) {
let myPipelineState: MTLRenderPipelineState = {
do {
return try device.makeRenderPipelineState(descriptor: renderPipelineDescriptor)
} catch let error {
print("failed to create render pipeline state for the device. ERROR: \(error)")
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error))))
NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]])
fatalError()
}
}()
let myDepthStencilState: MTLDepthStencilState? = {
if let depthStencilDescriptor = depthStencilDescriptor {
return device.makeDepthStencilState(descriptor: depthStencilDescriptor)
} else {
return nil
}
}()
self.init(renderPipelineState: myPipelineState, depthStencilState: myDepthStencilState, cullMode: cullMode, depthBias: depthBias, drawData: drawData)
}
/// Create a new `DralCall`
/// - Parameters:
/// - device: The metal device used to create the render pipeline state
/// - qualityRenderPipelineDescriptors: An array of render pipeline descriptors used to create render pipeline states for each quality level. The index of the render pipeline descriptor will be it's quality level. the number of `qualityRenderPipelineDescriptors` determines the number of distinct Levels of Detail. The descriptor at 0 should be the **highest** quality descriptor with the quality level reducing as the index gets higher.
/// - depthStencilDescriptor: The depth stencil descriptor used to make the depth stencil state
/// - cullMode: The `cullMode` property that will be used for the render encoder
/// - depthBias: The optional `depthBias` property that will be used for the render encoder
/// - drawData: The draw call data
init(withDevice device: MTLDevice, qualityRenderPipelineDescriptors: [MTLRenderPipelineDescriptor], depthStencilDescriptor: MTLDepthStencilDescriptor? = nil, cullMode: MTLCullMode = .back, depthBias: RenderPass.DepthBias? = nil, drawData: DrawData? = nil) {
let myPipelineStates: [MTLRenderPipelineState] = qualityRenderPipelineDescriptors.map {
do {
return try device.makeRenderPipelineState(descriptor: $0)
} catch let error {
print("failed to create render pipeline state for the device. ERROR: \(error)")
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error))))
NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]])
fatalError()
}
}
let myDepthStencilState: MTLDepthStencilState? = {
if let depthStencilDescriptor = depthStencilDescriptor {
return device.makeDepthStencilState(descriptor: depthStencilDescriptor)
} else {
return nil
}
}()
self.init(qualityRenderPipelineStates: myPipelineStates, depthStencilState: myDepthStencilState, cullMode: cullMode, depthBias: depthBias, drawData: drawData)
}
/// All shader function and pipeline states are created during initialization so it is reccommended that these objects be created on an asynchonous thread
/// - Parameters:
/// - metalLibrary: The metal library for the compiled render functions
/// - renderPass: The `RenderPass` associated with this draw call
/// - vertexFunctionName: The name of the vertex function that will be created.
/// - fragmentFunctionName: The name of the fragment function that will be created.
/// - vertexDescriptor: The vertex decriptor that will be used for the render pipeline state
/// - depthComareFunction: The depth compare function that will be used for the depth stencil state
/// - depthWriteEnabled: The `depthWriteEnabled` flag that will be used for the depth stencil state
/// - cullMode: The `cullMode` property that will be used for the render encoder
/// - depthBias: The optional `depthBias` property that will be used for the render encoder
/// - drawData: The draw call data
/// - uuid: An unique identifier for this draw call
/// - numQualityLevels: When using Level Of Detail optimizations in the renderer, this parameter indecates the number of distinct levels and also determines how many pipeline states are set up. This value must be greater than 0
init(metalLibrary: MTLLibrary, renderPass: RenderPass, vertexFunctionName: String, fragmentFunctionName: String, vertexDescriptor: MTLVertexDescriptor? = nil, depthComareFunction: MTLCompareFunction = .less, depthWriteEnabled: Bool = true, cullMode: MTLCullMode = .back, depthBias: RenderPass.DepthBias? = nil, drawData: DrawData? = nil, uuid: UUID = UUID(), numQualityLevels: Int = 1) {
guard numQualityLevels > 0 else {
fatalError("Invalid number of quality levels provided. Must be at least 1")
}
var myPipelineStates = [MTLRenderPipelineState]()
var myVertexFunctions = [MTLFunction]()
var myFragmentFunctions = [MTLFunction]()
for level in 0..<numQualityLevels {
let funcConstants = RenderUtilities.getFuncConstants(forDrawData: drawData, qualityLevel: QualityLevel(rawValue: UInt32(level)))
let fragFunc: MTLFunction = {
do {
return try metalLibrary.makeFunction(name: fragmentFunctionName, constantValues: funcConstants)
} catch let error {
print("Failed to create fragment function for pipeline state descriptor, error \(error)")
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error))))
NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]])
fatalError()
}
}()
let vertFunc: MTLFunction = {
do {
// Specify which shader to use based on if the model has skinned skeleton suppot
return try metalLibrary.makeFunction(name: vertexFunctionName, constantValues: funcConstants)
} catch let error {
print("Failed to create vertex function for pipeline state descriptor, error \(error)")
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error))))
NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]])
fatalError()
}
}()
guard let renderPipelineStateDescriptor = renderPass.renderPipelineDescriptor(withVertexDescriptor: vertexDescriptor, vertexFunction: vertFunc, fragmentFunction: fragFunc) else {
print("failed to create render pipeline state descriptorfor the device.")
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: nil))))
NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]])
fatalError()
}
let renderPipelineState: MTLRenderPipelineState = {
do {
return try renderPass.device.makeRenderPipelineState(descriptor: renderPipelineStateDescriptor)
} catch let error {
print("failed to create render pipeline state for the device. ERROR: \(error)")
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error))))
NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]])
fatalError()
}
}()
myVertexFunctions.append(vertFunc)
myFragmentFunctions.append(fragFunc)
myPipelineStates.append(renderPipelineState)
}
let depthStencilDescriptor = renderPass.depthStencilDescriptor(withDepthComareFunction: depthComareFunction, isDepthWriteEnabled: depthWriteEnabled)
let myDepthStencilState: MTLDepthStencilState? = renderPass.device.makeDepthStencilState(descriptor: depthStencilDescriptor)
self.uuid = uuid
self.qualityVertexFunctions = myVertexFunctions
self.qualityFragmentFunctions = myFragmentFunctions
self.qualityRenderPipelineStates = myPipelineStates
self.depthStencilState = myDepthStencilState
self.cullMode = cullMode
self.depthBias = depthBias
self.drawData = drawData
}
/// Prepares the Render Command Encoder with the draw call state.
/// You must call `prepareCommandEncoder(withCommandBuffer:)` before calling this method
/// - Parameters:
/// - renderPass: The `RenderPass` associated with this draw call
/// - qualityLevel: Indicates at which texture quality the pass will be rendered. a `qualityLevel` of 0 indicates **highest** quality. The higher the number the lower the quality. The level must be less than the number of `qualityRenderPasses` or `numQualityLevels` passed in durring initialization
func prepareDrawCall(withRenderPass renderPass: RenderPass, qualityLevel: Int = 0) {
guard let renderCommandEncoder = renderPass.renderCommandEncoder else {
return
}
renderCommandEncoder.setRenderPipelineState(renderPipelineState(for: qualityLevel))
renderCommandEncoder.setDepthStencilState(depthStencilState)
renderCommandEncoder.setCullMode(cullMode)
if let depthBias = depthBias {
renderCommandEncoder.setDepthBias(depthBias.bias, slopeScale: depthBias.slopeScale, clamp: depthBias.clamp)
}
}
/// Returns the `MTLRenderPipelineState` for the given quality level
/// - Parameter qualityLevel: Indicates at which texture quality the pass will be rendered. a `qualityLevel` of 0 indicates **highest** quality. The higher the number the lower the quality. The level must be less than the number of `qualityRenderPasses` or `numQualityLevels` passed in durring initialization
func renderPipelineState(for qualityLevel: Int = 0 ) -> MTLRenderPipelineState {
guard qualityLevel < qualityRenderPipelineStates.count else {
fatalError("The qualityLevel must be less than the number of `qualityRenderPasses` or `numQualityLevels` passed in durring initialization")
}
return qualityRenderPipelineStates[qualityLevel]
}
func markTexturesAsVolitile() {
drawData?.markTexturesAsVolitile()
}
func markTexturesAsNonVolitile() {
drawData?.markTexturesAsNonVolitile()
}
}
extension DrawCall: CustomDebugStringConvertible, CustomStringConvertible {
/// :nodoc:
var description: String {
return debugDescription
}
/// :nodoc:
var debugDescription: String {
let myDescription = "<DrawCall: > uuid: \(uuid), renderPipelineState:\(String(describing: renderPipelineState.debugDescription)), depthStencilState:\(depthStencilState?.debugDescription ?? "None"), cullMode: \(cullMode), usesSkeleton: \(usesSkeleton), vertexFunction: \(vertexFunction?.debugDescription ?? "None"), fragmentFunction: \(fragmentFunction?.debugDescription ?? "None")"
return myDescription
}
}
| mit |
mrdepth/Neocom | Legacy/Neocom/Neocom/FittingMenu.swift | 2 | 549 | //
// FittingMenu.swift
// Neocom
//
// Created by Artem Shimanski on 11/23/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import Futures
enum FittingMenu: Assembly {
typealias View = FittingMenuViewController
case `default`
func instantiate(_ input: View.Input) -> Future<View> {
switch self {
case .default:
let controller = UIStoryboard.fitting.instantiateViewController(withIdentifier: "FittingMenuViewController") as! View
controller.input = input
return .init(controller)
}
}
}
| lgpl-2.1 |
ganchau/Happiness | Happiness/HappinessTests/HappinessTests.swift | 1 | 974 | //
// HappinessTests.swift
// HappinessTests
//
// Created by Gan Chau on 11/5/15.
// Copyright © 2015 GC App. All rights reserved.
//
import XCTest
@testable import Happiness
class HappinessTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit |
alessioborraccino/reviews | reviewsTests/ViewModel/AddReviewViewModelTests.swift | 1 | 1565 | //
// AddReviewViewModelTests.swift
// reviews
//
// Created by Alessio Borraccino on 16/05/16.
// Copyright © 2016 Alessio Borraccino. All rights reserved.
//
import XCTest
@testable import reviews
class AddReviewViewModelTests: XCTestCase {
private let reviewAPI = ReviewAPIMock()
private lazy var addReviewViewModel : AddReviewViewModelType = AddReviewViewModel(reviewAPI: self.reviewAPI)
func didTryToSaveNotValidReview() {
setInvalidValues()
let expectation = expectationWithDescription("invalid values")
addReviewViewModel.didTryToSaveNotValidReview.observeNext {
expectation.fulfill()
}
addReviewViewModel.addReview()
waitForExpectationsWithTimeout(0.001, handler: nil)
}
func testSaveReview() {
setValidValues()
let expectation = expectationWithDescription("valid values")
addReviewViewModel.didSaveReview.observeNext { review in
if let _ = review {
expectation.fulfill()
} else {
XCTFail("No Review saved")
}
}
addReviewViewModel.addReview()
waitForExpectationsWithTimeout(0.001, handler: nil)
}
private func setValidValues() {
addReviewViewModel.author = "Author"
addReviewViewModel.message = "Message"
addReviewViewModel.title = "Title"
}
private func setInvalidValues() {
addReviewViewModel.author = "Author"
addReviewViewModel.message = ""
addReviewViewModel.title = ""
}
}
| mit |
philphilphil/isaacitems-ios | TrackerItems+CoreDataProperties.swift | 1 | 490 | //
// TrackerItems+CoreDataProperties.swift
// Isaac Items
//
// Created by Philipp Baum on 07/11/15.
// Copyright © 2015 Thinkcoding. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension TrackerItems {
@NSManaged var active: Bool
@NSManaged var trackerrun: Tracker?
@NSManaged var item: Item?
}
| mit |
ollieatkinson/Expectation | Expectation/Source/Matchers/Expectation+HavePrefix.swift | 1 | 521 | //
// Expectation+HavePrefix.swift
// Expectation
//
// Created by Oliver Atkinson on 08/12/2015.
// Copyright © 2015 Oliver. All rights reserved.
//
public extension Expectation where T: ExpressibleByStringLiteral {
public func havePrefix(_ other: T, _ description: String = "") {
if let expect = expect {
assertTrue("\(expect)".hasPrefix("\(other)"), self.description(#function, other, description))
} else {
fail(self.description(#function, other, description))
}
}
}
| mit |
Bartlebys/Bartleby | BartlebysUI/BartlebysUI/IdentificationStates.swift | 1 | 1298 | //
// IdentificationStates.swift
// BartlebyKit
//
// Created by Benoit Pereira da silva on 06/03/2017.
//
//
import Foundation
import BartlebyKit
// You should start by the IdentityWindowController to understand the variety of possible workflows.
// Bartleby supports a lot variations from distributed execution, to confined deployments.
public enum IdentificationStates:StateMessage{
// Initial state
case undefined
// PrepareUserCreationViewController
case prepareUserCreation
case userCreationHasBeenPrepared
// SetupCollaborativeServerViewController
case selectTheServer
case serverHasBeenSelected
case createTheUser
case userHasBeenCreated
// RevealPasswordViewController
case revealPassword
// UpdatePasswordViewController -> IdentityWindowController
case updatePassword
// ConfirmUpdatePasswordActivationCode -> IdentityWindowController
case passwordHasBeenUpdated
// ValidatePasswordViewController
case validatePassword
case passwordsAreMatching
// ConfirmActivationViewController
case confirmAccount
case accountHasBeenConfirmed
// RecoverSugarViewController
case recoverSugar
case sugarHasBeenRecovered // just after DocumentStates.collectionsDataHasBeenDecrypted
}
| apache-2.0 |
cailingyun2010/swift-keyboard | 01-表情键盘/ViewController.swift | 1 | 1125 | //
// ViewController.swift
// 01-表情键盘
//
// Created by nimingM on 16/4/6.
// Copyright © 2016年 蔡凌云. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// 添加自控制器
addChildViewController(emoticonVC)
// 将表情键盘设置车呼出键盘
textView.inputView = emoticonVC.view
}
// weak 相当于OC中的 __weak , 特点对象释放之后会将变量设置为nil
// unowned 相当于OC中的 unsafe_unretained, 特点对象释放之后不会将变量设置为nil
private lazy var emoticonVC: EmoticonViewController = EmoticonViewController { [unowned self] (emoticon) -> () in
// 1.判断当前点击的是否是emoji表情
if emoticon.emojiStr != nil{
self.textView.replaceRange(self.textView.selectedTextRange!, withText: emoticon.emojiStr!)
}
}
deinit {
print("控制器被销毁了")
}
}
| mit |
khizkhiz/swift | validation-test/compiler_crashers_fixed/28041-swift-typechecker-lookupunqualified.swift | 1 | 399 | // Test is no longer valid as there is no longer `map` as a free function in Swift 3
// XFAIL: *
// DUPLICATE-OF: 26813-generic-enum-tuple-optional-payload.swift
// RUN: not --crash %target-swift-frontend %s -parse
// 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{{map($0
| apache-2.0 |
tkremenek/swift | validation-test/Sema/type_checker_perf/fast/rdar42672946.swift | 28 | 175 | // RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
func f(tail: UInt64, byteCount: UInt64) {
if tail & ~(1 << ((byteCount & 7) << 3) - 1) == 0 { }
}
| apache-2.0 |
sammeadley/responder-chain | ResponderChain/ViewController.swift | 1 | 3795 | //
// ViewController.swift
// ResponderChain
//
// Created by Sam Meadley on 03/01/2016.
// Copyright © 2016 Sam Meadley. All rights reserved.
//
import UIKit
// Gross global variable to suppress print output until touch event received. There is almost certainly a better way. Maybe 100 better ways.
var touchReceived = false
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
// Nil-targeted actions are passed up the responder chain until they are handled.
// The didSelectButton:sender implementation below shows a useful example, detecting the
// collection view cell in which a button touch event occurred.
@IBAction func didSelectButton(sender: UIButton) {
let point = sender.convertPoint(CGPointZero, toView:self.collectionView)
let indexPath = self.collectionView.indexPathForItemAtPoint(point)
print("Event handled! I'm \(self.dynamicType) and I will handle the \(sender.dynamicType) touch event for item \(indexPath!.row) \n\n... Now where was I? Oh yeah...", terminator:"\n\n")
}
override func nextResponder() -> UIResponder? {
let nextResponder = super.nextResponder()
printNextResponder(nextResponder)
return nextResponder
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCellWithReuseIdentifier(CollectionViewCell.defaultReuseIdentifier(), forIndexPath: indexPath)
}
}
class View: UIView {
override func nextResponder() -> UIResponder? {
let nextResponder = super.nextResponder()
printNextResponder(nextResponder)
return nextResponder
}
}
class CollectionView: UICollectionView {
override func nextResponder() -> UIResponder? {
let nextResponder = super.nextResponder()
printNextResponder(nextResponder)
return nextResponder
}
}
class CollectionViewCell: UICollectionViewCell {
class func defaultReuseIdentifier() -> String {
return "CollectionViewCell"
}
override func nextResponder() -> UIResponder? {
let nextResponder = super.nextResponder()
printNextResponder(nextResponder)
return nextResponder
}
}
class Button: UIButton {
override func nextResponder() -> UIResponder? {
let nextResponder = super.nextResponder()
printNextResponder(nextResponder)
return nextResponder
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
touchReceived = true
printEvent(event)
super.touchesBegan(touches, withEvent: event)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
printEvent(event)
super.touchesEnded(touches, withEvent: event)
}
func printEvent(event: UIEvent?) {
if let phase = event?.allTouches()?.first?.phase {
print("\nHi, Button here. \"\(phase)\" received and understood. I'll let the Responder Chain know...")
}
}
}
extension UIResponder {
func printNextResponder(nextResponder: UIResponder?) {
guard let responder = nextResponder else {
return
}
if (touchReceived) {
print("-> \(self.dynamicType): Hey \(responder.dynamicType), something coming your way!")
}
}
}
| mit |
functionaldude/XLPagerTabStrip | Example/Example/ReloadExampleViewController.swift | 1 | 3204 | // ReloadExampleViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import XLPagerTabStrip
class ReloadExampleViewController: UIViewController {
@IBOutlet lazy var titleLabel: UILabel! = {
let label = UILabel()
return label
}()
lazy var bigLabel: UILabel = {
let bigLabel = UILabel()
bigLabel.backgroundColor = .clear
bigLabel.textColor = .white
bigLabel.font = UIFont.boldSystemFont(ofSize: 20)
bigLabel.adjustsFontSizeToFitWidth = true
return bigLabel
}()
override func viewDidLoad() {
super.viewDidLoad()
if navigationController != nil {
navigationItem.titleView = bigLabel
bigLabel.sizeToFit()
}
if let pagerViewController = childViewControllers.first as? PagerTabStripViewController {
updateTitle(of: pagerViewController)
}
}
@IBAction func reloadTapped(_ sender: UIBarButtonItem) {
for childViewController in childViewControllers {
guard let child = childViewController as? PagerTabStripViewController else {
continue
}
child.reloadPagerTabStripView()
updateTitle(of: child)
break
}
}
@IBAction func closeTapped(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
func updateTitle(of pagerTabStripViewController: PagerTabStripViewController) {
func stringFromBool(_ bool: Bool) -> String {
return bool ? "YES" : "NO"
}
titleLabel.text = "Progressive = \(stringFromBool(pagerTabStripViewController.pagerBehaviour.isProgressiveIndicator)) ElasticLimit = \(stringFromBool(pagerTabStripViewController.pagerBehaviour.isElasticIndicatorLimit))"
(navigationItem.titleView as? UILabel)?.text = titleLabel.text
navigationItem.titleView?.sizeToFit()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
| mit |
guumeyer/MarveListHeroes | MarvelHeroes/Extensions/UIViewController+ NVActivityIndicatorView.swift | 1 | 685 | //
// UIViewController+ NVActivityIndicatorView.swift
// MarvelHeros
//
// Created by gustavo r meyer on 8/13/17.
// Copyright © 2017 gustavo r meyer. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
extension UIViewController:NVActivityIndicatorViewable{
func showActivityIndicatory() {
NVActivityIndicatorView.DEFAULT_TYPE = .pacman
NVActivityIndicatorView.DEFAULT_COLOR = UIColor.red
let activityData = ActivityData()
NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData)
}
func hideActivityIndicatory() {
NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
}
}
| apache-2.0 |
radex/swift-compiler-crashes | crashes-duplicates/09994-swift-valuedecl-overwritetype.swift | 11 | 277 | // 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 {
struct d {
struct c<d : a
struct d<T where g = b
" " {
typealias e = n
}
class func a
func a
func a
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/08875-swift-archetypebuilder-resolvearchetype.swift | 11 | 223 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A{deinit{{}struct c<H{{}{}struct B<T where H.e=c | mit |
radex/swift-compiler-crashes | crashes-duplicates/20137-no-stacktrace.swift | 11 | 229 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class c {
func a {
for in {
for {
protocol A {
class
case ,
| mit |
acort3255/Emby.ApiClient.Swift | Emby.ApiClient/model/connect/ConnectPassword.swift | 2 | 873 | //
// ConnectPassword.swift
// Emby.ApiClient
//
// Created by Vedran Ozir on 07/10/15.
// Copyright © 2015 Vedran Ozir. All rights reserved.
//
import Foundation
//package mediabrowser.model.connect;
extension String {
func replace(what: String, with: String) -> String {
//return self.stringByReplacingOccurrencesOfString(what, withString: with)
return self.replacingOccurrences(of: what, with: with)
}
}
public final class ConnectPassword
{
public static func PerformPreHashFilter( password: String) -> String
{
return password.replace(what: "&", with: "&").replace(what: "/", with: "\").replace(what: "!", with: "!").replace(what: "$", with: "$").replace(what: "\"", with: """).replace(what: "<", with: "<").replace(what: ">", with: ">").replace(what: "'", with: "'");
}
}
| mit |
ruddfawcett/VerticalTextView | Source/VerticalTextView.swift | 1 | 2870 | // VerticalTextView.swift
// Copyright (c) 2015 Brendan Conron
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class VerticalTextView: UITextView {
enum VerticalAlignment: Int {
case Top = 0, Middle, Bottom
}
var verticalAlignment: VerticalAlignment = .Middle
//override contentSize property and observe using didSet
override var contentSize: CGSize {
didSet {
let height = self.bounds.size.height
let contentHeight: CGFloat = contentSize.height
var topCorrect: CGFloat = 0.0
switch (self.verticalAlignment) {
case .Top:
self.contentOffset = CGPointZero //set content offset to top
case .Middle:
topCorrect = (height - contentHeight * self.zoomScale) / 2.0
topCorrect = topCorrect < 0 ? 0 : topCorrect
self.contentOffset = CGPoint(x: 0, y: -topCorrect)
case .Bottom:
topCorrect = self.bounds.size.height - contentHeight
topCorrect = topCorrect < 0 ? 0 : topCorrect
self.contentOffset = CGPoint(x: 0, y: -topCorrect)
}
if contentHeight >= height { // if the contentSize is greater than the height
topCorrect = contentHeight - height // set the contentOffset to be the
topCorrect = topCorrect < 0 ? 0 : topCorrect // contentHeight - height of textView
self.contentOffset = CGPoint(x: 0, y: topCorrect)
}
}
}
// MARK: - UIView
override func layoutSubviews() {
super.layoutSubviews()
let size = self.contentSize // forces didSet to be called
self.contentSize = size
}
} | mit |
openhab/openhab.ios | openHAB/UIAlertView+Block.swift | 1 | 1884 | // Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import ObjectiveC
import UIKit
private var kNSCBAlertWrapper = 0
class NSCBAlertWrapper: NSObject {
var completionBlock: ((_ alertView: UIAlertView?, _ buttonIndex: Int) -> Void)?
// MARK: - UIAlertViewDelegate
// Called when a button is clicked. The view will be automatically dismissed after this call returns
func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
if completionBlock != nil {
completionBlock?(alertView, buttonIndex)
}
}
// Called when we cancel a view (eg. the user clicks the Home button). This is not called when the user clicks the cancel button.
// If not defined in the delegate, we simulate a click in the cancel button
func alertViewCancel(_ alertView: UIAlertView) {
// Just simulate a cancel button click
if completionBlock != nil {
completionBlock?(alertView, alertView.cancelButtonIndex)
}
}
}
extension UIAlertView {
@objc
func show(withCompletion completion: @escaping (_ alertView: UIAlertView?, _ buttonIndex: Int) -> Void) {
let alertWrapper = NSCBAlertWrapper()
alertWrapper.completionBlock = completion
delegate = alertWrapper as AnyObject
// Set the wrapper as an associated object
objc_setAssociatedObject(self, &kNSCBAlertWrapper, alertWrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// Show the alert as normal
show()
}
// MARK: - Class Public
}
| epl-1.0 |
GabrielGhe/SwiftProjects | App3/App3Tests/App3Tests.swift | 1 | 873 | //
// App3Tests.swift
// App3Tests
//
// Created by Gabriel on 2014-06-19.
// Copyright (c) 2014 Gabriel. All rights reserved.
//
import XCTest
class App3Tests: 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.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
soxjke/Redux-ReactiveSwift | Example/Simple-Weather-App/Simple-Weather-App/Store/AppStore.swift | 1 | 5542 | //
// AppStore.swift
// Simple-Weather-App
//
// Created by Petro Korienev on 10/30/17.
// Copyright © 2017 Sigma Software. All rights reserved.
//
import Foundation
import Redux_ReactiveSwift
extension AppState: Defaultable {
static var defaultValue: AppState = AppState(location: AppLocation(locationState: .notYetRequested,
locationRequestState: .none),
weather: AppWeather(geopositionRequestState: .none,
weatherRequestState: .none))
}
final class AppStore: Store<AppState, AppEvent> {
static let shared: AppStore = AppStore()
init() {
super.init(state: AppState.defaultValue, reducers: [appstore_reducer])
}
required init(state: AppState, reducers: [AppStore.Reducer]) {
super.init(state: state, reducers: reducers)
}
}
internal func appstore_reducer(state: AppState, event: AppEvent) -> AppState {
return AppState(location: locationReducer(state.location, event),
weather: weatherReducer(state.weather, event))
}
// MARK: Location reducers
fileprivate func locationReducer(_ state: AppLocation, _ event: AppEvent) -> AppLocation {
switch event {
case .locationPermissionResult(let success): return location(permissionResult: success, previous: state)
case .locationRequest: return locationRequest(previous: state)
case .locationResult(let latitude, let longitude, let timestamp, let error):
return locationResult(latitude: latitude, longitude: longitude, timestamp: timestamp, error: error, previous: state)
default: return state
}
}
fileprivate func location(permissionResult: Bool, previous: AppLocation) -> AppLocation {
return AppLocation(locationState: permissionResult ? .available : .notAvailable,
locationRequestState: previous.locationRequestState)
}
fileprivate func locationRequest(previous: AppLocation) -> AppLocation {
guard case .available = previous.locationState else { return previous }
if case .success(_, _, let timestamp) = previous.locationRequestState {
if (Date().timeIntervalSince1970 - timestamp < 10) { // Don't do update if location succeeded within last 10 seconds
return previous
}
}
return AppLocation(locationState: previous.locationState, locationRequestState: .updating) // Perform location update
}
fileprivate func locationResult(latitude: Double?, longitude: Double?, timestamp: TimeInterval?, error: Swift.Error?, previous: AppLocation) -> AppLocation {
guard let error = error else {
if let latitude = latitude, let longitude = longitude, let timestamp = timestamp {
return AppLocation(locationState: previous.locationState, locationRequestState: .success(latitude: latitude, longitude: longitude, timestamp: timestamp))
}
return AppLocation(locationState: previous.locationState, locationRequestState: .error(error: AppError.inconsistentLocationEvent))
}
return AppLocation(locationState: previous.locationState, locationRequestState: .error(error: error))
}
// MARK: Weather reducers
fileprivate func weatherReducer(_ state: AppWeather, _ event: AppEvent) -> AppWeather {
switch event {
case .geopositionRequest: return geopositionRequest(previous: state)
case .geopositionResult(let geoposition, let error): return geopositionResult(geoposition: geoposition, error: error, previous: state)
case .weatherRequest: return weatherRequest(previous: state)
case .weatherResult(let current, let forecast, let error): return weatherResult(current: current, forecast: forecast, error: error, previous: state)
default: return state
}
}
fileprivate func geopositionRequest(previous: AppWeather) -> AppWeather {
return AppWeather(geopositionRequestState: .updating, weatherRequestState: previous.weatherRequestState)
}
fileprivate func geopositionResult(geoposition: Geoposition?, error: Swift.Error?, previous: AppWeather) -> AppWeather {
guard let error = error else {
if let geoposition = geoposition {
return AppWeather(geopositionRequestState: .success(geoposition: geoposition), weatherRequestState: previous.weatherRequestState)
}
return AppWeather(geopositionRequestState: .error(error: AppError.inconsistentGeopositionEvent), weatherRequestState: previous.weatherRequestState)
}
return AppWeather(geopositionRequestState: .error(error: error), weatherRequestState: previous.weatherRequestState)
}
fileprivate func weatherRequest(previous: AppWeather) -> AppWeather {
return AppWeather(geopositionRequestState: previous.geopositionRequestState, weatherRequestState: .updating)
}
fileprivate func weatherResult(current: CurrentWeather?, forecast: [Weather]?, error: Swift.Error?, previous: AppWeather) -> AppWeather {
guard let error = error else {
if let current = current, let forecast = forecast {
return AppWeather(geopositionRequestState: previous.geopositionRequestState,
weatherRequestState: .success(currentWeather: current, forecast: forecast))
}
return AppWeather(geopositionRequestState: .error(error: AppError.inconsistentWeatherEvent), weatherRequestState: previous.weatherRequestState)
}
return AppWeather(geopositionRequestState: previous.geopositionRequestState, weatherRequestState: .error(error: error))
}
| mit |
hkellaway/Gloss | Sources/GlossTests/Test Models/TestKeyPathModelCustomDelimiter.swift | 1 | 1219 | //
// TestKeyPathModelCustomDelimiter.swift
// GlossExample
//
// Created by Maciej Kołek on 10/18/16.
// Copyright © 2016 Harlan Kellaway. All rights reserved.
//
import Foundation
import Gloss
struct TestKeyPathModelCustomDelimiter: Glossy {
let id: Int?
let url: URL?
init?(json: JSON) {
self.id = Decoder.decode(key: "nested*id", keyPathDelimiter: "*")(json)
self.url = Decoder.decode(urlForKey: "nested*url", keyPathDelimiter: "*")(json)
}
func toJSON() -> JSON? {
return jsonify([
"nested*id" ~~> self.id,
"nested*url" ~~> self.url
], keyPathDelimiter: "*")
}
}
// MARK - Codable Migration
extension TestKeyPathModelCustomDelimiter: Decodable {
init(from decoder: Swift.Decoder) throws {
throw GlossError.decodableMigrationUnimplemented(context: "TestKeyPathModelCustomDelimiter")
}
}
extension TestKeyPathModelCustomDelimiter: Encodable {
func encode(to encoder: Swift.Encoder) throws {
// Remove GlossError to see Codable error in console
throw GlossError.encodableMigrationUnimplemented(context: "TestKeyPathModelCustomDelimiter")
}
}
| mit |
kenjitayama/MustacheMultitypeRender | Example/Tests/Tests.swift | 1 | 2813 | import UIKit
import XCTest
import MustacheMultitypeRender
class Tests: 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.
let filters: [String: TemplateStringRender.Filter] = [
"flyingTo": { (args: [String]) in
return "\(args[0]) 🛫🛬 \(args[1])"
}
]
let implicitFilter = { (renderSource: String) in
return "[\(renderSource)]"
}
// start/end with non-placeholder
// 1 valid replacemnt, 1 missing replacement
var template = TemplateStringRender(
templateString: "start {{apple}} {{candy}} {{flyingTo(city1,city2)}} end",
filters: filters,
implicitFilter: implicitFilter)
var renderResult = template.render([
"apple": "cherry",
"city1": "Tokyo",
"city2": "New York"
])
XCTAssertEqual(renderResult, "[start ][cherry][ ][candy][ ]Tokyo 🛫🛬 New York[ end]")
// start/end with placeholder,
// 1 valid replacemnt, 1 missing replacement
// 1 missing filter argument (2 needed)
template = TemplateStringRender(
templateString: "{{apple}} {{candy}} {{flyingTo(city1,city2)}}, {{flyingTo(city1,city3)}}",
filters: filters,
implicitFilter: implicitFilter)
renderResult = template.render([
"apple": "cherry",
"city1": "Tokyo",
])
XCTAssertEqual(renderResult, "[cherry][ ][candy][ ]Tokyo 🛫🛬 city2[, ]Tokyo 🛫🛬 city3")
// start with placeholder,
// 1 valid replacemnt, 1 missing replacement
// 2 missing filter argument (2 needed)
template = TemplateStringRender(
templateString: "[start ][cherry][ ][mentos][ ][distance(city1,city2)][, ]city1 🛫🛬 city3",
filters: filters,
implicitFilter: implicitFilter)
renderResult = template.render([
"apple": "cherry",
"candy": "mentos"
])
XCTAssertEqual(renderResult, "[[start ][cherry][ ][mentos][ ][distance(city1,city2)][, ]city1 🛫🛬 city3]")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
DeliciousRaspberryPi/MockFive | MockFiveTests/MockFiveTests.swift | 1 | 11771 | import Quick
import Nimble
@testable import MockFive
protocol MyMockableProtocol {
func myComplexMethod(description: String?, price: Int, accessories: Any...) -> (Int, String)
func myOptionalMethod(arg: Int) -> String?
func mySimpleMethod()
}
protocol MockFiveTests: MyMockableProtocol, Mock {}
struct TestMock: MockFiveTests {
let mockFiveLock = lock()
func mySimpleMethod() { stub(identifier: "mySimpleMethod") }
func myOptionalMethod(arg: Int) -> String? { return stub(identifier: "myOptionalMethod", arguments: arg) }
func myComplexMethod(description: String?, price: Int, accessories: Any...) -> (Int, String) { return stub(identifier: "myComplexMethod", arguments: description, price, accessories) { _ in (7, "Fashion") } }
}
class MockFiveSpecs: QuickSpec {
override func spec() {
var mock: MockFiveTests = TestMock()
beforeEach { mock.resetMock() }
describe("logging method calls") {
context("when it's a simple call") {
beforeEach {
mock.mySimpleMethod()
}
it("should have the correct output") {
expect(mock.invocations.count).to(equal(1))
expect(mock.invocations.first).to(equal("mySimpleMethod()"))
}
}
context("When it's a complex call") {
context("with the correct number of arguments") {
beforeEach {
mock.myComplexMethod(nil, price: 42, accessories: "shoes", "shirts", "timepieces")
}
it("should have the correct output") {
expect(mock.invocations.count).to(equal(1))
expect(mock.invocations.first).to(equal("myComplexMethod(_: nil, price: 42, accessories: [\"shoes\", \"shirts\", \"timepieces\"]) -> (Int, String)"))
}
}
context("with too few arguments") {
struct TooFewTestMock: MockFiveTests {
let mockFiveLock = lock()
func mySimpleMethod() {}
func myOptionalMethod(arg: Int) -> String? { return .None }
func myComplexMethod(description: String?, price: Int, accessories: Any...) -> (Int, String) { return stub(identifier: "myComplexMethod", arguments: description) { _ in (7, "Fashion") } }
}
beforeEach {
mock = TooFewTestMock()
mock.myComplexMethod("A fun argument", price: 7, accessories: "Necklace")
}
it("should have the correct output") {
expect(mock.invocations.count).to(equal(1))
expect(mock.invocations.first).to(equal("myComplexMethod(_: A fun argument, price: , accessories: ) -> (Int, String) [Expected 3, got 1]"))
}
}
context("with too many arguments") {
struct TooManyTestMock: MockFiveTests {
let mockFiveLock = lock()
func mySimpleMethod() {}
func myOptionalMethod(arg: Int) -> String? { return .None }
func myComplexMethod(description: String?, price: Int, accessories: Any...) -> (Int, String) { return stub(identifier: "myComplexMethod", arguments: description, price, accessories, "fruit", 9) { _ in (7, "Fashion") } }
}
beforeEach {
mock = TooManyTestMock()
mock.myComplexMethod("A fun argument", price: 7, accessories: "Necklace")
}
it("should have the correct output") {
expect(mock.invocations.count).to(equal(1))
expect(mock.invocations.first).to(equal("myComplexMethod(_: A fun argument, price: 7, accessories: [\"Necklace\"]) -> (Int, String) [Expected 3, got 5: fruit, 9]"))
}
}
}
}
describe("stubbing method implementations") {
let testMock = TestMock()
var fatalErrorString: String? = .None
let fatalErrorDispatch = { (behavior: () -> ()) in dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), behavior) }
beforeEach { FatalErrorUtil.replaceFatalError({ (message, _, _) -> () in fatalErrorString = message }) }
afterEach { FatalErrorUtil.restoreFatalError() }
context("when the type does not conform to nilLiteralConvertible") {
context("when I have registered a closure of the correct type") {
var arguments: [Any?]? = .None
beforeEach {
testMock.registerStub("myComplexMethod") { args -> (Int, String) in
arguments = args
return (21, "string")
}
testMock.myComplexMethod("", price: 1)
}
it("should pass the arguments to the closure") {
if let description = arguments?[0] as? String {
expect(description).to(equal(""))
} else { fail() }
if let price = arguments?[1] as? Int {
expect(price).to(equal(1))
} else { fail() }
}
it("should return the registered closure's value") {
expect(testMock.myComplexMethod("", price: 1).0).to(equal(21))
expect(testMock.myComplexMethod("", price: 1).1).to(equal("string"))
}
describe("resetting the mock") {
beforeEach {
testMock.unregisterStub("myComplexMethod")
}
it("should return the default block's value") {
expect(testMock.myComplexMethod("", price: 1).0).to(equal(7))
expect(testMock.myComplexMethod("", price: 1).1).to(equal("Fashion"))
}
}
}
context("when I have registered a closure of the incorrect type") {
beforeEach {
testMock.registerStub("myComplexMethod") { _ in return 7 }
fatalErrorDispatch({ testMock.myComplexMethod("", price: 1) })
}
it("should throw a fatal error") {
expect(fatalErrorString).toEventually(equal("MockFive: Incompatible block of type 'Array<Optional<protocol<>>> -> Int' registered for function 'myComplexMethod' requiring block type '([Any?]) -> (Int, String)'"))
}
}
}
context("when the type conforms to nil literal convertible") {
context("when I have not registered a closure") {
it("should return a default of nil") {
expect(testMock.myOptionalMethod(7)).to(beNil())
}
}
context("when I have registered a closure of the correct type") {
var arguments: [Any?]? = .None
beforeEach {
testMock.registerStub("myOptionalMethod") { args -> String? in
arguments = args
return "string"
}
testMock.myOptionalMethod(7)
}
it("should pass the arguments to the closure") {
if let arg = arguments?[0] as? Int {
expect(arg).to(equal(7))
} else { fail() }
}
it("should return the closure value") {
expect(testMock.myOptionalMethod(7)).to(equal("string"))
}
describe("resetting the mock") {
beforeEach {
testMock.unregisterStub("myOptionalMethod")
}
it("should return nil") {
expect(testMock.myOptionalMethod(7)).to(beNil())
}
}
}
context("when I have registered a closure of the incorrect type") {
beforeEach {
testMock.registerStub("myOptionalMethod") { _ in 21 }
}
it("should throw a fatal error") {
expect(fatalErrorString).toEventually(equal("MockFive: Incompatible block of type 'Array<Optional<protocol<>>> -> Int' registered for function 'myComplexMethod' requiring block type '([Any?]) -> (Int, String)'"))
}
}
}
}
describe("mock object identity") {
let mock1 = TestMock()
let mock2 = TestMock()
beforeEach {
mock1.mySimpleMethod()
mock1.myComplexMethod("", price: 9)
}
it("should log the calls on the first mock") {
expect(mock1.invocations.count).to(equal(2))
}
it("should not log the calls on the second mock") {
expect(mock2.invocations.count).to(equal(0))
}
}
describe("resetting the mock log") {
context("when I am resetting the mock log for one instance") {
let mock1 = TestMock()
let mock2 = TestMock()
beforeEach {
mock1.mySimpleMethod()
mock2.myComplexMethod("", price: 9)
mock1.resetMock()
}
it("should empty the invocations on the mock") {
expect(mock1.invocations.count).to(equal(0))
}
it("should not empty the invocations on other mocks") {
expect(mock2.invocations.count).toNot(equal(0))
}
}
context("when I am resetting the global mock log") {
let mock1 = TestMock()
let mock2 = TestMock()
beforeEach {
mock1.mySimpleMethod()
mock2.myComplexMethod("", price: 9)
resetMockFive()
}
it("should empty the invocations of the mock") {
expect(mock1.invocations.count).to(equal(0))
}
it("should empty the invocations of the mock") {
expect(mock2.invocations.count).to(equal(0))
}
}
}
}
}
| apache-2.0 |
jschmid/couchbase-chat | ios-app/couchbase-chat/Controllers/LoginViewController.swift | 1 | 1676 | //
// LoginViewController.swift
// couchbase-chat
//
// Created by Jonas Schmid on 13/07/15.
// Copyright © 2015 schmid. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
}
override func viewDidAppear(animated: Bool) {
let prefs = NSUserDefaults.standardUserDefaults()
if let username = prefs.stringForKey("username"),
let password = prefs.stringForKey("password") {
startLogin(username, password: password)
}
}
@IBAction func signinClick(sender: UIButton) {
if let username = usernameTextField.text,
let password = passwordTextField.text {
startLogin(username, password: password)
}
}
private func startLogin(username: String, password: String) {
let syncHelper = SyncHelper(username: username, password: password)
let app = UIApplication.sharedApplication().delegate as! AppDelegate
app.syncHelper = syncHelper
syncHelper.start()
let prefs = NSUserDefaults.standardUserDefaults()
prefs.setObject(username, forKey: "username")
prefs.setObject(password, forKey: "password")
// Async call because this method may be called from viewDidLoad and the performSegue will not work
dispatch_async(dispatch_get_main_queue()) {
let ctrl = self.storyboard?.instantiateViewControllerWithIdentifier("splitViewController")
app.window!.rootViewController = ctrl
}
}
}
| mit |
corichmond/turbo-adventure | project4/Project4/AppDelegate.swift | 20 | 2048 | //
// AppDelegate.swift
// Project4
//
// Created by Hudzilla on 19/11/2014.
// Copyright (c) 2014 Hudzilla. 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:.
}
}
| unlicense |
kickstarter/ios-oss | KsApi/models/lenses/GraphCategoriesEnvelopeLenses.swift | 1 | 267 | import Prelude
extension RootCategoriesEnvelope {
public enum lens {
public static let categories = Lens<RootCategoriesEnvelope, [Category]>(
view: { $0.rootCategories },
set: { part, _ in RootCategoriesEnvelope(rootCategories: part) }
)
}
}
| apache-2.0 |
Foild/SugarRecord | example/SugarRecordExample/Shared/Models/CoreDataModel.swift | 12 | 289 | //
// CoreDataModel.swift
// SugarRecordExample
//
// Created by Robert Dougan on 10/12/14.
// Copyright (c) 2014 Robert Dougan. All rights reserved.
//
import Foundation
import CoreData
@objc(CoreDataModel)
class CoreDataModel: NSManagedObject {
@NSManaged var text: String
}
| mit |
majia144119/MarKingForGitHub | marking/marking/ViewController.swift | 1 | 494 | //
// ViewController.swift
// marking
//
// Created by mac on 15/10/13.
// Copyright © 2015年 majia. 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.
}
}
| mit |
antonio081014/LeeCode-CodeBase | Swift/distribute-candies.swift | 2 | 370 | /**
* https://leetcode.com/problems/distribute-candies/
*
*
*/
// Date: Mon Mar 1 11:31:09 PST 2021
class Solution {
func distributeCandies(_ candyType: [Int]) -> Int {
var count: [Int : Int] = [:]
for candy in candyType {
count[candy, default: 0] += 1
}
return min(count.keys.count, candyType.count / 2)
}
}
| mit |
ZhaoBingDong/EasySwifty | EasySwifty/Classes/Easy+UIView.swift | 1 | 6230 | //
// Easy+UIView.swift
// EaseSwifty
//
// Created by 董招兵 on 2017/8/6.
// Copyright © 2017年 大兵布莱恩特. All rights reserved.
//
import Foundation
import UIKit
//public func kScaleWidth(_ value : CGFloat) -> CGFloat {
// return UIScreen.main.autoScaleW(value)
//}
//
public func kScaleWidth(_ value : CGFloat) -> CGFloat {
return 0.0
}
// MARK: - UIView
public extension UIView {
class func viewType() -> Self {
return self.init()
}
// Top
var top : CGFloat {
set (_newTop){
var rect = self.frame;
rect.origin.y = _newTop;
self.frame = rect;
}
get { return self.frame.minY }
}
// Left
var left : CGFloat {
set(_newLeft) {
var rect = self.frame;
rect.origin.x = _newLeft;
self.frame = rect;
}
get { return self.frame.minX }
}
// Bottom
var bottom : CGFloat {
set (_newBottom) {
var frame = self.frame
frame.origin.y = _newBottom - frame.size.height;
self.frame = frame;
}
get { return self.frame.maxY }
}
// Right
var right : CGFloat {
set (_newRight){
var rect = self.frame;
rect.origin.x = _newRight - rect.width;
self.frame = rect;
}
get { return self.frame.maxX }
}
// Width
var width : CGFloat {
set(_newWidth) {
var rect = self.frame;
rect.size.width = _newWidth;
self.frame = rect;
}
get { return self.frame.width }
}
// Height
var height : CGFloat {
set (_newHeight){
var rect = self.frame;
rect.size.height = _newHeight;
self.frame = rect;
}
get { return self.frame.height }
}
// Size
var size : CGSize {
set(_newSize) {
var frame = self.frame;
frame.size = _newSize;
self.frame = frame;
}
get { return self.frame.size }
}
// Origin
var origin : CGPoint {
set (_newOrgin) {
var frame = self.frame;
frame.origin = _newOrgin;
self.frame = frame;
}
get { return self.frame.origin }
}
// CenterX
var center_x : CGFloat {
set (_newCenterX) {
self.center = CGPoint(x: _newCenterX, y: self.center_x)
}
get { return self.center.x }
}
// CenterY
var center_y : CGFloat {
set (_newCenterY) {
self.center = CGPoint(x: self.center_x, y: _newCenterY)
}
get { return self.center.y }
}
/**
移除所有子视图
*/
func removeAllSubviews() {
while self.subviews.count > 0 {
let view = self.subviews.last
view?.removeFromSuperview()
}
}
/**
给一个 view 添加手势事件
*/
func addTarget(_ target : AnyObject?, action : Selector?) {
if (target == nil || action == nil) { return }
self.isUserInteractionEnabled = true;
self.addGestureRecognizer(UITapGestureRecognizer(target: target, action: action!))
}
@discardableResult
class func viewFromNib<T: UIView>() -> T {
let className = T.reuseIdentifier.components(separatedBy: ".").last ?? ""
let nib = Bundle.main.loadNibNamed(className, owner: nil, options: nil)?.last
guard nib != nil else {
fatalError("Could not find Nib with name: \(className)")
}
return nib as! T
}
}
// MARK: - UIButton
@objc public extension UIButton {
/**
给按钮设置不同状态下的颜色
*/
func setBackgroundColor(backgroundColor color: UIColor? ,forState state: UIControl.State) {
guard color != nil else { return }
self.setBackgroundImage(UIImage.imageWithColor(color!), for: state)
}
/// 获取 button 所在tableview cell 的 indexPath
/// button 点击方法应该
// button.addTarget(self, action: #selector(buttonClick(btn:event:)), for: .touchUpInside)
// @objc func buttonClick(btn:UIButton,event:Any) {
//
// if let indexPath = btn.indexPath(at: UITableView(), forEvent: event) {
// print(indexPath)
// }
// }
@discardableResult
func indexPathAtTableView(_ tableView : UITableView, forEvent event : Any) -> IndexPath? {
// 获取 button 所在 cell 的indexPath
let set = (event as! UIEvent).allTouches
for (_ ,anyObj) in (set?.enumerated())! {
let point = anyObj.location(in: tableView)
let indexPath = tableView.indexPathForRow(at: point)
if indexPath != nil {
return indexPath!;
}
}
return nil
}
/// 当点击某个 CollectionCell 上 button 时 获取某个 cell.indexPath
// button.addTarget(self, action: #selector(buttonClick(btn:event:)), for: .touchUpInside)
// @objc func buttonClick(btn:UIButton,event:Any) {
//
// if let indexPath = btn.indexPath(at: UICollectionView(), forEvent: event) {
// print(indexPath)
// }
// }
@discardableResult
func indexPathAtCollectionView(_ collectionView : UICollectionView, forEvent event : NSObject) -> IndexPath? {
// 获取 button 所在 cell 的indexPath
let set = (event as! UIEvent).allTouches
for (_ ,anyObj) in (set?.enumerated())! {
let point = anyObj.location(in: collectionView)
let indexPath = collectionView.indexPathForItem(at: point)
if indexPath != nil {
return indexPath!;
}
}
return nil
}
}
extension UIView : ViewNameReusable {
public class var reuseIdentifier:String {
return String(describing: self)
}
public class var xib : UINib? {
return UINib(nibName: self.reuseIdentifier, bundle: nil)
}
}
public protocol ViewNameReusable : class {
static var reuseIdentifier : String { get }
}
| apache-2.0 |
szpnygo/firefox-ios | Client/Frontend/Reader/ReadabilityBrowserHelper.swift | 20 | 2103 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
protocol ReadabilityBrowserHelperDelegate {
func readabilityBrowserHelper(readabilityBrowserHelper: ReadabilityBrowserHelper, didFinishWithReadabilityResult result: ReadabilityResult)
}
class ReadabilityBrowserHelper: BrowserHelper {
var delegate: ReadabilityBrowserHelperDelegate?
class func name() -> String {
return "ReadabilityBrowserHelper"
}
init?(browser: Browser) {
if let readabilityPath = NSBundle.mainBundle().pathForResource("Readability", ofType: "js"),
let readabilitySource = NSMutableString(contentsOfFile: readabilityPath, encoding: NSUTF8StringEncoding, error: nil),
let readabilityBrowserHelperPath = NSBundle.mainBundle().pathForResource("ReadabilityBrowserHelper", ofType: "js"),
let readabilityBrowserHelperSource = NSMutableString(contentsOfFile: readabilityBrowserHelperPath, encoding: NSUTF8StringEncoding, error: nil) {
readabilityBrowserHelperSource.replaceOccurrencesOfString("%READABILITYJS%", withString: readabilitySource as String, options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, readabilityBrowserHelperSource.length))
var userScript = WKUserScript(source: readabilityBrowserHelperSource as String, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
browser.webView!.configuration.userContentController.addUserScript(userScript)
}
}
func scriptMessageHandlerName() -> String? {
return "readabilityMessageHandler"
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let readabilityResult = ReadabilityResult(object: message.body) {
delegate?.readabilityBrowserHelper(self, didFinishWithReadabilityResult: readabilityResult)
}
}
} | mpl-2.0 |
davejlong/ResponseDetective | ResponseDetective/Source Files/PlainTextInterceptor.swift | 1 | 2463 | //
// PlainTextInterceptor.swift
//
// Copyright (c) 2015 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
/// Intercepts plain text requests and responses.
public final class PlainTextInterceptor {
/// The output stream used by the interceptor.
public private(set) var outputStream: OutputStreamType
// The acceptable content types.
private let acceptableContentTypes = [
"text/plain"
]
// MARK: Initialization
/// Initializes the interceptor with an output stream.
///
/// - parameter outputStream: The output stream to be used.
public init(outputStream: OutputStreamType) {
self.outputStream = outputStream
}
/// Initializes the interceptor with a Println output stream.
public convenience init() {
self.init(outputStream: PrintlnOutputStream())
}
// MARK: Prettifying
/// Prettifies the plain text data.
///
/// - parameter data: The plain text data to prettify.
///
/// - returns: A prettified plain text string.
private func prettifyPlainTextData(data: NSData) -> String? {
return Optional(data).flatMap {
NSString(data: $0, encoding: NSUTF8StringEncoding) as String?
}
}
}
// MARK: -
extension PlainTextInterceptor: RequestInterceptorType {
// MARK: RequestInterceptorType implementation
public func canInterceptRequest(request: RequestRepresentation) -> Bool {
return request.contentType.map {
self.acceptableContentTypes.contains($0)
} ?? false
}
public func interceptRequest(request: RequestRepresentation) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
if let plainTextString = request.bodyData.flatMap({
self.prettifyPlainTextData($0)
}) {
dispatch_async(dispatch_get_main_queue()) {
self.outputStream.write(plainTextString)
}
}
}
}
}
// MARK: -
extension PlainTextInterceptor: ResponseInterceptorType {
// MARK: ResponseInterceptorType implementation
public func canInterceptResponse(response: ResponseRepresentation) -> Bool {
return response.contentType.map {
self.acceptableContentTypes.contains($0)
} ?? false
}
public func interceptResponse(response: ResponseRepresentation) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
if let plainTextString = response.bodyData.flatMap({
self.prettifyPlainTextData($0)
}) {
dispatch_async(dispatch_get_main_queue()) {
self.outputStream.write(plainTextString)
}
}
}
}
}
| mit |
flodev/DbMigration | DbMigration/ViewController.swift | 1 | 544 | //
// ViewController.swift
// DbMigration
//
// Created by Florian Biewald on 19/08/14.
// Copyright (c) 2014 Florian Biewald. 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.
}
}
| mit |
watr/PTPPT | PTP/PTPDataSet.swift | 1 | 6522 |
import Foundation
public protocol PTPDataSet {
init?(data: Data)
}
public struct GetDeviceInfoDataSet: PTPDataSet, CustomStringConvertible {
public typealias StandardVersion = UInt16
public let standardVersion: StandardVersion
public typealias VendorExtensionID = UInt32
public let vendorExtensionID: VendorExtensionID
public typealias VendorExtensionVersion = UInt16
public let vendorExtensionVersion: VendorExtensionVersion
public typealias VendorExtensionDesc = String
public let vendorExtensionDesc: VendorExtensionDesc
public typealias FunctionalMode = UInt16
public let functionalMode: FunctionalMode
public typealias OperationsSupported = [UInt16]
public let operationsSupported: OperationsSupported
public typealias EventsSupported = [UInt16]
public let eventsSupported: EventsSupported
public typealias DevicePropertiesSupported = [UInt16]
public let devicePropertiesSupported: DevicePropertiesSupported
public typealias CaptureFormats = [UInt16]
public let captureFormats: CaptureFormats
public typealias ImageFormats = [UInt16]
public let imageFormats: ImageFormats
public typealias Manufacturer = String
public let manufacturer: Manufacturer
public typealias Model = String
public let model: Model
public typealias DeviceVersion = String
public let deviceVersion: DeviceVersion
public typealias SerialNumber = String
public let serialNumber: SerialNumber
public init?(data: Data) {
var offset: Int = 0
var capacity: Int = 0
capacity = MemoryLayout<StandardVersion>.size
self.standardVersion = data.subdata(in: offset..<(offset + capacity)).withUnsafeBytes({$0.pointee})
offset += capacity
capacity = MemoryLayout<VendorExtensionID>.size
self.vendorExtensionID = data.subdata(in: offset..<(offset + capacity)).withUnsafeBytes({$0.pointee})
offset += capacity
capacity = MemoryLayout<VendorExtensionVersion>.size
self.vendorExtensionVersion = data.subdata(in: offset..<(offset + capacity)).withUnsafeBytes({$0.pointee})
offset += capacity
capacity = data.ptpStringCapacity(from: offset)
self.vendorExtensionDesc = data.subdata(in: offset..<(offset + capacity)).ptpString()
offset += capacity
capacity = MemoryLayout<FunctionalMode>.size
self.functionalMode = data.subdata(in: offset..<(offset + capacity)).withUnsafeBytes({$0.pointee})
offset += capacity
capacity = data.ptpArrayCapacity(from: offset, each: MemoryLayout<UInt16>.size)
self.operationsSupported = data.subdata(in: offset..<(offset + capacity)).ptpArray()
offset += capacity
capacity = data.ptpArrayCapacity(from: offset, each: MemoryLayout<UInt16>.size)
self.eventsSupported = data.subdata(in: offset..<(offset + capacity)).ptpArray()
offset += capacity
capacity = data.ptpArrayCapacity(from: offset, each: MemoryLayout<UInt16>.size)
self.devicePropertiesSupported = data.subdata(in: offset..<(offset + capacity)).ptpArray()
offset += capacity
capacity = data.ptpArrayCapacity(from: offset, each: MemoryLayout<UInt16>.size)
self.captureFormats = data.subdata(in: offset..<(offset + capacity)).ptpArray()
offset += capacity
capacity = data.ptpArrayCapacity(from: offset, each: MemoryLayout<UInt16>.size)
self.imageFormats = data.subdata(in: offset..<(offset + capacity)).ptpArray()
offset += capacity
capacity = data.ptpStringCapacity(from: offset)
self.manufacturer = data.subdata(in: offset..<(offset + capacity)).ptpString()
offset += capacity
capacity = data.ptpStringCapacity(from: offset)
self.model = data.subdata(in: offset..<(offset + capacity)).ptpString()
offset += capacity
capacity = data.ptpStringCapacity(from: offset)
self.deviceVersion = data.subdata(in: offset..<(offset + capacity)).ptpString()
offset += capacity
capacity = data.ptpStringCapacity(from: offset)
self.serialNumber = data.subdata(in: offset..<(offset + capacity)).ptpString()
offset += capacity
}
public var description: String {
let descriptions: [String] = [
"data set \"get deice info\"",
" standard version: \(self.standardVersion)",
" vendor extension id: \(self.vendorExtensionID)",
" vendor extension version: \(self.vendorExtensionVersion)",
" vendor extension desc: \(self.vendorExtensionDesc)",
" functional mode: \(self.functionalMode)",
" operations supported: \(self.operationsSupported.map({String(format: "0x%x", $0)}).joined(separator: ", "))",
" events supported: \(self.eventsSupported.map({String(format: "0x%x", $0)}).joined(separator: ", "))",
"device properties supported: \(self.devicePropertiesSupported.map({String(format: "0x%x", $0)}).joined(separator: ", "))",
" capture formats: \(self.captureFormats.map({String(format: "0x%x", $0)}).joined(separator: ", "))",
" image formats: \(self.imageFormats.map({String(format: "0x%x", $0)}).joined(separator: ", "))",
" manufacturer: \(self.manufacturer)",
" model: \(self.model)",
" device version: \(self.deviceVersion)",
" serial number: \(self.serialNumber)",
]
return descriptions.joined(separator: "\n")
}
}
public struct GetStorageIDsDataSet: PTPDataSet, CustomStringConvertible {
public let storageIDs: [UInt32]
public init?(data: Data) {
var offset: Int = 0
var capacity: Int = 0
capacity = data.ptpArrayCapacity(from: offset, each: MemoryLayout<UInt32>.size)
self.storageIDs = data.ptpArray()
offset += capacity
}
public var description: String {
let descriptions: [String] = [
"data set \"get storage IDs\"",
"storage IDs: \(self.storageIDs.map({String(format: "0x%x", $0)}).joined(separator: ", "))",
]
return descriptions.joined(separator: "\n")
}
}
| mit |
pyze/iOS-Samples | PyzeWatchOSInApp/PyzeWatchOSInApp WatchKit Extension/NotificationController.swift | 1 | 2916 | import WatchKit
import Foundation
import UserNotifications
import Pyze
class NotificationController: WKUserNotificationInterfaceController {
override init() {
// Initialize variables here.
super.init()
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
// MARK: - WatchOS2
override func didReceiveRemoteNotification(_ remoteNotification: [AnyHashable : Any], withCompletion completionHandler: @escaping (WKUserNotificationInterfaceType) -> Void) {
if let aps = remoteNotification["aps"] as? NSDictionary {
if let alert = aps["alert"] as? NSDictionary {
if let title = alert["title"] as? NSString {
if let body = alert["body"] as? NSString {
let alert:WKAlertAction = WKAlertAction(title: "OK", style: .default, handler: {
print("Alert action 'OK' performed")
})
let actions = [alert]
self.presentAlert(withTitle: title as String, message: body as String, preferredStyle: .alert, actions: actions)
Pyze.processReceivedRemoteNotification(remoteNotification)
}
}
}
}
}
// MARK: - WatchOS3
@available(watchOSApplicationExtension 3.0, *)
override func didReceive(_ notification: UNNotification, withCompletion completionHandler: @escaping (WKUserNotificationInterfaceType) -> Swift.Void) {
let userInfo = notification.request.content.userInfo
if let aps = userInfo["aps"] as? NSDictionary {
if let alert = aps["alert"] as? NSDictionary {
if let title = alert["title"] as? NSString {
if let body = alert["body"] as? NSString {
let alert:WKAlertAction = WKAlertAction(title: "OK", style: .default, handler: {
print("Alert action 'OK' performed")
})
let actions = [alert]
self.presentAlert(withTitle: title as String, message: body as String, preferredStyle: .alert, actions: actions)
Pyze.processReceivedRemoteNotification(userInfo)
}
}
}
}
completionHandler(.custom)
}
}
| mit |
think-dev/UIRefreshableScrollView | UIRefreshableScrollView/Refreshable.swift | 1 | 1320 |
import UIKit
public protocol Refreshable {
var customRefreshView: UIRefreshControlContentView? { get set }
var pullToRefreshControl: UIRefreshControl? { get set }
var refreshDelegate: UIRefreshableScrollViewDelegate? { get set }
func insertRefreshControl(using customView: UIView?)
func update(using offset: CGFloat)
}
extension Refreshable where Self: UIScrollView {
public func insertRefreshControl(using customView: UIView? = nil) {
guard let refreshControlInstance = pullToRefreshControl else {
fatalError("refreshControl cannot be nil")
}
refreshControlInstance.addTarget(self, action: #selector(manageRefreshing), for: .valueChanged)
addSubview(refreshControlInstance)
guard let refreshView = customView else {
return
}
insert(customRefreshView: refreshView)
}
private func insert(customRefreshView view: UIView) {
guard let refreshControlInstance = pullToRefreshControl else {
fatalError("refreshControl cannot be nil")
}
refreshControlInstance.addSubview(view)
}
public func update(using offset: CGFloat) {
}
}
extension UIScrollView {
open func manageRefreshing() {
}
}
| mit |
gitkong/FLTableViewComponent | FLTableComponent/FLBaseHandlerProtocol.swift | 2 | 2547 | //
// FLBaseHandlerProtocol.swift
// FLComponentDemo
//
// Created by 孔凡列 on 2017/7/29.
// Copyright © 2017年 gitKong. All rights reserved.
//
import UIKit
// MARK : modifily components
protocol FLTableViewHandlerProtocol {
func component(by identifier: String) -> FLTableBaseComponent?
func component(at index : NSInteger) -> FLTableBaseComponent?
func exchange(_ component : FLTableBaseComponent, by exchangeComponent : FLTableBaseComponent)
func replace(_ component : FLTableBaseComponent, by replacementComponent : FLTableBaseComponent)
func addAfterIdentifier(_ component : FLTableBaseComponent, after identifier : String)
func addAfterComponent(_ component : FLTableBaseComponent, after afterComponent : FLTableBaseComponent)
func addAfterSection(_ component : FLTableBaseComponent, after index : NSInteger)
func add(_ component : FLTableBaseComponent)
func removeComponent(by identifier : String, removeType : FLComponentRemoveType)
func removeComponent(_ component : FLTableBaseComponent?)
func removeComponent(at index : NSInteger)
func reloadComponents()
func reloadComponents(_ components : [FLTableBaseComponent])
func reloadComponent(_ component : FLTableBaseComponent)
func reloadComponent(at index : NSInteger)
}
protocol FLCollectionViewHandlerProtocol {
func component(by identifier: String) -> FLCollectionBaseComponent?
func component(at index : NSInteger) -> FLCollectionBaseComponent?
func exchange(_ component : FLCollectionBaseComponent, by exchangeComponent : FLCollectionBaseComponent)
func replace(_ component : FLCollectionBaseComponent, by replacementComponent : FLCollectionBaseComponent)
func addAfterIdentifier(_ component : FLCollectionBaseComponent, after identifier : String)
func addAfterComponent(_ component : FLCollectionBaseComponent, after afterComponent : FLCollectionBaseComponent)
func addAfterSection(_ component : FLCollectionBaseComponent, after index : NSInteger)
func add(_ component : FLCollectionBaseComponent)
func removeComponent(by identifier : String, removeType : FLComponentRemoveType)
func removeComponent(_ component : FLCollectionBaseComponent?)
func removeComponent(at index : NSInteger)
func reloadComponents()
func reloadComponents(_ components : [FLCollectionBaseComponent])
func reloadComponent(_ component : FLCollectionBaseComponent)
func reloadComponent(at index : NSInteger)
}
| mit |
SusanDoggie/Doggie | Sources/DoggieGraphics/ApplePlatform/Performance/CIContextPool.swift | 1 | 4143 | //
// CIContextPool.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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.
//
#if canImport(CoreImage) && canImport(Metal)
private struct CIContextOptions: Hashable {
var colorSpace: ColorSpace<RGBColorModel>?
var outputPremultiplied: Bool
var workingFormat: CIFormat
}
public class CIContextPool {
public static let `default`: CIContextPool = CIContextPool()
public let commandQueue: MTLCommandQueue?
private let lck = NSLock()
private var table: [CIContextOptions: CIContext] = [:]
public init() {
self.commandQueue = MTLCreateSystemDefaultDevice()?.makeCommandQueue()
}
public init(device: MTLDevice) {
self.commandQueue = device.makeCommandQueue()
}
public init(commandQueue: MTLCommandQueue) {
self.commandQueue = commandQueue
}
}
extension CIContextPool {
private func make_context(options: CIContextOptions) -> CIContext? {
let _options: [CIContextOption: Any]
if let colorSpace = options.colorSpace {
guard let cgColorSpace = colorSpace.cgColorSpace else { return nil }
_options = [
.workingColorSpace: cgColorSpace,
.outputColorSpace: cgColorSpace,
.outputPremultiplied: options.outputPremultiplied,
.workingFormat: options.workingFormat,
]
} else {
_options = [
.workingColorSpace: CGColorSpaceCreateDeviceRGB(),
.outputColorSpace: CGColorSpaceCreateDeviceRGB(),
.outputPremultiplied: options.outputPremultiplied,
.workingFormat: options.workingFormat,
]
}
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *), let commandQueue = commandQueue {
return CIContext(mtlCommandQueue: commandQueue, options: _options)
} else if let device = commandQueue?.device {
return CIContext(mtlDevice: device, options: _options)
} else {
return CIContext(options: _options)
}
}
public func makeContext(colorSpace: ColorSpace<RGBColorModel>? = nil, outputPremultiplied: Bool = true, workingFormat: CIFormat = .BGRA8) -> CIContext? {
lck.lock()
defer { lck.unlock() }
let options = CIContextOptions(
colorSpace: colorSpace,
outputPremultiplied: outputPremultiplied,
workingFormat: workingFormat
)
if table[options] == nil {
table[options] = make_context(options: options)
}
return table[options]
}
public func clearCaches() {
lck.lock()
defer { lck.unlock() }
for context in table.values {
context.clearCaches()
}
}
}
#endif
| mit |
duycao2506/SASCoffeeIOS | Pods/ExSwift/ExSwift/Range.swift | 1 | 1866 | //
// Range.swift
// ExSwift
//
// Created by pNre on 04/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import Foundation
public extension Range {
/**
For each element in the range invokes function.
:param: function Function to call
*/
func times (function: () -> ()) {
each { (current: T) -> () in
function()
}
}
/**
For each element in the range invokes function passing the element as argument.
:param: function Function to invoke
*/
func times (function: (T) -> ()) {
each (function)
}
/**
For each element in the range invokes function passing the element as argument.
:param: function Function to invoke
*/
func each (function: (T) -> ()) {
for i in self {
function(i)
}
}
/**
Range of Int with random bounds between from and to (inclusive).
:param: from Lower bound
:param: to Upper bound
:returns: Random range
*/
static func random (from: Int, to: Int) -> Range<Int> {
let lowerBound = Int.random(min: from, max: to)
let upperBound = Int.random(min: lowerBound, max: to)
return lowerBound...upperBound
}
}
/**
* Operator == to compare 2 ranges first, second by start & end indexes. If first.startIndex is equal to
* second.startIndex and first.endIndex is equal to second.endIndex the ranges are considered equal.
*/
public func == <U: ForwardIndexType> (first: Range<U>, second: Range<U>) -> Bool {
return first.startIndex == second.startIndex &&
first.endIndex == second.endIndex
}
/**
* DP2 style open range operator
*/
public func .. <U : Comparable> (first: U, second: U) -> HalfOpenInterval<U> {
return first..<second
}
| gpl-3.0 |
mindbody/Conduit | Tests/ConduitTests/Networking/Serialization/SOAPEnvelopeFactoryTests.swift | 1 | 2228 | //
// SOAPEnvelopeFactoryTests.swift
// ConduitTests
//
// Created by John Hammerlund on 7/10/17.
// Copyright © 2017 MINDBODY. All rights reserved.
//
import XCTest
@testable import Conduit
class SOAPEnvelopeFactoryTests: XCTestCase {
func testProducesSOAPBodyElements() {
let sut = SOAPEnvelopeFactory()
let bodyNode = XMLNode(name: "N")
let soapBodyNode = sut.makeSOAPBody(root: bodyNode)
XCTAssertEqual(soapBodyNode.name, "soap:Body")
XCTAssertEqual(soapBodyNode.children.count, 1)
XCTAssertEqual(soapBodyNode.children.first?.name, "N")
}
func testProducesSOAPEnvelopeElements() {
let sut = SOAPEnvelopeFactory()
let envelope = sut.makeSOAPEnvelope()
XCTAssertEqual(envelope.name, "soap:Envelope")
XCTAssertEqual(envelope.attributes["xmlns:xsi"], "http://www.w3.org/2001/XMLSchema-instance")
XCTAssertEqual(envelope.attributes["xmlns:xsd"], "http://www.w3.org/2001/XMLSchema")
XCTAssertEqual(envelope.attributes["xmlns:soap"], "http://schemas.xmlsoap.org/soap/envelope/")
XCTAssertEqual(envelope.attributes["soap:encodingStyle"], "")
}
func testProducesFormattedSOAPXML() {
let sut = SOAPEnvelopeFactory()
let bodyNode = XMLNode(name: "N")
let soapXML = sut.makeXML(soapBody: bodyNode)
XCTAssertEqual(soapXML.root?.name, "soap:Envelope")
XCTAssertEqual(soapXML.root?.children.count, 1)
XCTAssertEqual(soapXML.root?["soap:Body"]?.children.count, 1)
XCTAssertNotNil(soapXML.root?["soap:Body"]?["N"])
}
func testRespectsCustomPrefixAndRootNamespaceSchema() {
var sut = SOAPEnvelopeFactory()
sut.rootNamespaceSchema = "http://clients.mindbodyonline.com/api/0_5"
sut.soapEnvelopeNamespace = "soapenv"
let bodyNode = XMLNode(name: "N")
let soapXML = sut.makeXML(soapBody: bodyNode)
XCTAssertEqual(soapXML.root?.name, "soapenv:Envelope")
XCTAssertEqual(soapXML.root?.attributes["xmlns"], "http://clients.mindbodyonline.com/api/0_5")
XCTAssertEqual(soapXML.root?.children.count, 1)
XCTAssertEqual(soapXML.root?["soapenv:Body"]?.children.count, 1)
}
}
| apache-2.0 |
mohamede1945/quran-ios | Quran/AudioDownloadsNavigationController.swift | 1 | 1453 | //
// AudioDownloadsNavigationController.swift
// Quran
//
// Created by Mohamed Afifi on 4/17/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UIKit
class AudioDownloadsNavigationController: BaseNavigationController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
tabBarItem = UITabBarItem(title: NSLocalizedString("audio_manager", tableName: "Android", comment: ""),
image: #imageLiteral(resourceName: "download-25"),
selectedImage: #imageLiteral(resourceName: "download_filled-25"))
}
required init?(coder aDecoder: NSCoder) {
unimplemented()
}
}
| gpl-3.0 |
omondigeno/ActionablePushMessages | PushedActionableMessages/DodoDistrib.swift | 1 | 78403 | //
// Dodo
//
// A message bar for iOS.
//
// https://github.com/marketplacer/Dodo
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// DodoAnimation.swift
//
// ----------------------------
import UIKit
/// A closure that is called for animation of the bar when it is being shown or hidden.
public typealias DodoAnimation = (UIView, duration: NSTimeInterval?,
locationTop: Bool, completed: DodoAnimationCompleted)->()
/// A closure that is called by the animator when animation has finished.
public typealias DodoAnimationCompleted = ()->()
// ----------------------------
//
// DodoAnimations.swift
//
// ----------------------------
import UIKit
/// Collection of animation effects use for showing and hiding the notification bar.
public enum DodoAnimations: String {
/// Animation that fades the bar in/out.
case Fade = "Fade"
/// Used for showing notification without animation.
case NoAnimation = "No animation"
/// Animation that rotates the bar around X axis in perspective with spring effect.
case Rotate = "Rotate"
/// Animation that swipes the bar to/from the left with fade effect.
case SlideLeft = "Slide left"
/// Animation that swipes the bar to/from the right with fade effect.
case SlideRight = "Slide right"
/// Animation that slides the bar in/out vertically.
case SlideVertically = "Slide vertically"
/**
Get animation function that can be used for showing notification bar.
- returns: Animation function.
*/
public var show: DodoAnimation {
switch self {
case .Fade:
return DodoAnimationsShow.fade
case .NoAnimation:
return DodoAnimations.noAnimation
case .Rotate:
return DodoAnimationsShow.rotate
case .SlideLeft:
return DodoAnimationsShow.slideLeft
case .SlideRight:
return DodoAnimationsShow.slideRight
case .SlideVertically:
return DodoAnimationsShow.slideVertically
}
}
/**
Get animation function that can be used for hiding notification bar.
- returns: Animation function.
*/
public var hide: DodoAnimation {
switch self {
case .Fade:
return DodoAnimationsHide.fade
case .NoAnimation:
return DodoAnimations.noAnimation
case .Rotate:
return DodoAnimationsHide.rotate
case .SlideLeft:
return DodoAnimationsHide.slideLeft
case .SlideRight:
return DodoAnimationsHide.slideRight
case .SlideVertically:
return DodoAnimationsHide.slideVertically
}
}
/**
A empty animator which is used when no animation is supplied.
It simply calls the completion closure.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func noAnimation(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
completed()
}
/// Helper function for fading the view in and out.
static func fade(duration: NSTimeInterval?, showView: Bool, view: UIView,
completed: DodoAnimationCompleted) {
let actualDuration = duration ?? 0.5
let startAlpha: CGFloat = showView ? 0 : 1
let endAlpha: CGFloat = showView ? 1 : 0
view.alpha = startAlpha
UIView.animateWithDuration(actualDuration,
animations: {
view.alpha = endAlpha
},
completion: { finished in
completed()
}
)
}
/// Helper function for sliding the view vertically
static func slideVertically(duration: NSTimeInterval?, showView: Bool, view: UIView,
locationTop: Bool, completed: DodoAnimationCompleted) {
let actualDuration = duration ?? 0.5
view.layoutIfNeeded()
var distance: CGFloat = 0
if locationTop {
distance = view.frame.height + view.frame.origin.y
} else {
distance = UIScreen.mainScreen().bounds.height - view.frame.origin.y
}
let transform = CGAffineTransformMakeTranslation(0, locationTop ? -distance : distance)
let start: CGAffineTransform = showView ? transform : CGAffineTransformIdentity
let end: CGAffineTransform = showView ? CGAffineTransformIdentity : transform
view.transform = start
UIView.animateWithDuration(actualDuration,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 1,
options: [],
animations: {
view.transform = end
},
completion: { finished in
completed()
}
)
}
static weak var timer: MoaTimer?
/// Animation that rotates the bar around X axis in perspective with spring effect.
static func rotate(duration: NSTimeInterval?, showView: Bool, view: UIView, completed: DodoAnimationCompleted) {
let actualDuration = duration ?? 2.0
let start: Double = showView ? Double(M_PI / 2) : 0
let end: Double = showView ? 0 : Double(M_PI / 2)
let damping = showView ? 0.85 : 3
let myCALayer = view.layer
var transform = CATransform3DIdentity
transform.m34 = -1.0/200.0
myCALayer.transform = CATransform3DRotate(transform, CGFloat(end), 1, 0, 0)
myCALayer.zPosition = 300
SpringAnimationCALayer.animate(myCALayer,
keypath: "transform.rotation.x",
duration: actualDuration,
usingSpringWithDamping: damping,
initialSpringVelocity: 1,
fromValue: start,
toValue: end,
onFinished: showView ? completed : nil)
// Hide the bar prematurely for better looks
timer?.cancel()
if !showView {
timer = MoaTimer.runAfter(0.3) { timer in
completed()
}
}
}
/// Animation that swipes the bar to the right with fade-out effect.
static func slide(duration: NSTimeInterval?, right: Bool, showView: Bool,
view: UIView, completed: DodoAnimationCompleted) {
let actualDuration = duration ?? 0.4
let distance = UIScreen.mainScreen().bounds.width
let transform = CGAffineTransformMakeTranslation(right ? distance : -distance, 0)
let start: CGAffineTransform = showView ? transform : CGAffineTransformIdentity
let end: CGAffineTransform = showView ? CGAffineTransformIdentity : transform
let alphaStart: CGFloat = showView ? 0.2 : 1
let alphaEnd: CGFloat = showView ? 1 : 0.2
view.transform = start
view.alpha = alphaStart
UIView.animateWithDuration(actualDuration,
delay: 0,
options: UIViewAnimationOptions.CurveEaseOut,
animations: {
view.transform = end
view.alpha = alphaEnd
},
completion: { finished in
completed()
}
)
}
}
// ----------------------------
//
// DodoAnimationsHide.swift
//
// ----------------------------
import UIKit
/// Collection of animation effects use for hiding the notification bar.
struct DodoAnimationsHide {
/**
Animation that rotates the bar around X axis in perspective with spring effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func rotate(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.rotate(duration, showView: false, view: view, completed: completed)
}
/**
Animation that swipes the bar from to the left with fade-in effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideLeft(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slide(duration, right: false, showView: false, view: view, completed: completed)
}
/**
Animation that swipes the bar to the right with fade-out effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideRight(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slide(duration, right: true, showView: false, view: view, completed: completed)
}
/**
Animation that fades the bar out.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func fade(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.fade(duration, showView: false, view: view, completed: completed)
}
/**
Animation that slides the bar vertically out of view.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideVertically(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slideVertically(duration, showView: false, view: view,
locationTop: locationTop, completed: completed)
}
}
// ----------------------------
//
// DodoAnimationsShow.swift
//
// ----------------------------
import UIKit
/// Collection of animation effects use for showing the notification bar.
struct DodoAnimationsShow {
/**
Animation that rotates the bar around X axis in perspective with spring effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func rotate(view: UIView, duration: NSTimeInterval?,
locationTop: Bool, completed: DodoAnimationCompleted) {
DodoAnimations.rotate(duration, showView: true, view: view, completed: completed)
}
/**
Animation that swipes the bar from the left with fade-in effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideLeft(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slide(duration, right: false, showView: true, view: view, completed: completed)
}
/**
Animation that swipes the bar from the right with fade-in effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideRight(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slide(duration, right: true, showView: true, view: view, completed: completed)
}
/**
Animation that fades the bar in.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func fade(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.fade(duration, showView: true, view: view, completed: completed)
}
/**
Animation that slides the bar in/out vertically.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideVertically(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slideVertically(duration, showView: true, view: view,
locationTop: locationTop,completed: completed)
}
}
// ----------------------------
//
// DodoButtonOnTap.swift
//
// ----------------------------
/// A closure that is called when a bar button is tapped
public typealias DodoButtonOnTap = ()->()
// ----------------------------
//
// DodoButtonView.swift
//
// ----------------------------
import UIKit
class DodoButtonView: UIImageView {
private let style: DodoButtonStyle
weak var delegate: DodoButtonViewDelegate?
var onTap: OnTap?
init(style: DodoButtonStyle) {
self.style = style
super.init(frame: CGRect())
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Create button views for given button styles.
static func createMany(styles: [DodoButtonStyle]) -> [DodoButtonView] {
if !haveButtons(styles) { return [] }
return styles.map { style in
let view = DodoButtonView(style: style)
view.setup()
return view
}
}
static func haveButtons(styles: [DodoButtonStyle]) -> Bool {
let hasImages = styles.filter({ $0.image != nil }).count > 0
let hasIcons = styles.filter({ $0.icon != nil }).count > 0
return hasImages || hasIcons
}
func doLayout(onLeftSide onLeftSide: Bool) {
precondition(delegate != nil, "Button view delegate can not be nil")
translatesAutoresizingMaskIntoConstraints = false
// Set button's size
TegAutolayoutConstraints.width(self, value: style.size.width)
TegAutolayoutConstraints.height(self, value: style.size.height)
if let superview = superview {
let alignAttribute = onLeftSide ? NSLayoutAttribute.Left : NSLayoutAttribute.Right
let marginHorizontal = onLeftSide ? style.horizontalMarginToBar : -style.horizontalMarginToBar
// Align the button to the left/right of the view
TegAutolayoutConstraints.alignSameAttributes(self, toItem: superview,
constraintContainer: superview,
attribute: alignAttribute, margin: marginHorizontal)
// Center the button verticaly
TegAutolayoutConstraints.centerY(self, viewTwo: superview, constraintContainer: superview)
}
}
func setup() {
if let image = DodoButtonView.image(style) { applyStyle(image) }
setupTap()
}
/// Increase the hitsize of the image view if it's less than 44px for easier tapping.
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
let oprimizedBounds = DodoTouchTarget.optimize(bounds)
return oprimizedBounds.contains(point)
}
/// Returns the image supplied by user or create one from the icon
class func image(style: DodoButtonStyle) -> UIImage? {
if style.image != nil {
return style.image
}
if let icon = style.icon {
let bundle = NSBundle(forClass: self)
let imageName = icon.rawValue
return UIImage(named: imageName, inBundle: bundle, compatibleWithTraitCollection: nil)
}
return nil
}
private func applyStyle(imageIn: UIImage) {
var imageToShow = imageIn
if let tintColorToShow = style.tintColor {
// Replace image colors with the specified tint color
imageToShow = imageToShow.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
tintColor = tintColorToShow
}
layer.minificationFilter = kCAFilterTrilinear // make the image crisp
image = imageToShow
contentMode = UIViewContentMode.ScaleAspectFit
// Make button accessible
if let accessibilityLabelToShow = style.accessibilityLabel {
isAccessibilityElement = true
accessibilityLabel = accessibilityLabelToShow
accessibilityTraits = UIAccessibilityTraitButton
}
}
private func setupTap() {
onTap = OnTap(view: self, gesture: UITapGestureRecognizer()) { [weak self] in
self?.didTap()
}
}
private func didTap() {
self.delegate?.buttonDelegateDidTap(self.style)
style.onTap?()
}
}
// ----------------------------
//
// DodoButtonViewDelegate.swift
//
// ----------------------------
protocol DodoButtonViewDelegate: class {
func buttonDelegateDidTap(buttonStyle: DodoButtonStyle)
}
// ----------------------------
//
// Dodo.swift
//
// ----------------------------
import UIKit
/**
Main class that coordinates the process of showing and hiding of the message bar.
Instance of this class is created automatically in the `dodo` property of any UIView instance.
It is not expected to be instantiated manually anywhere except unit tests.
For example:
let view = UIView()
view.dodo.info("Horses are blue?")
*/
final class Dodo: DodoInterface, DodoButtonViewDelegate {
private weak var superview: UIView!
private var hideTimer: MoaTimer?
// Gesture handler that hides the bar when it is tapped
var onTap: OnTap?
/// Specify optional layout guide for positioning the bar view.
var topLayoutGuide: UILayoutSupport?
/// Specify optional layout guide for positioning the bar view.
var bottomLayoutGuide: UILayoutSupport?
/// Defines styles for the bar.
var style = DodoStyle(parentStyle: DodoPresets.defaultPreset.style)
init(superview: UIView) {
self.superview = superview
DodoKeyboardListener.startListening()
}
/// Changes the style preset for the bar widget.
var preset: DodoPresets = DodoPresets.defaultPreset {
didSet {
if preset != oldValue {
style.parent = preset.style
}
}
}
/**
Shows the message bar with *.Success* preset. It can be used to indicate successful completion of an operation.
- parameter message: The text message to be shown.
*/
func success(message: String) {
preset = .Success
show(message)
}
/**
Shows the message bar with *.Info* preset. It can be used for showing information messages that have neutral emotional value.
- parameter message: The text message to be shown.
*/
func info(message: String) {
preset = .Info
show(message)
}
/**
Shows the message bar with *.Warning* preset. It can be used for for showing warning messages.
- parameter message: The text message to be shown.
*/
func warning(message: String) {
preset = .Warning
show(message)
}
/**
Shows the message bar with *.Warning* preset. It can be used for showing critical error messages
- parameter message: The text message to be shown.
*/
func error(message: String) {
preset = .Error
show(message)
}
/**
Shows the message bar. Set `preset` property to change the appearance of the message bar, or use the shortcut methods: `success`, `info`, `warning` and `error`.
- parameter message: The text message to be shown.
*/
func show(message: String) {
removeExistingBars()
setupHideTimer()
let bar = DodoToolbar(witStyle: style)
setupHideOnTap(bar)
bar.layoutGuide = style.bar.locationTop ? topLayoutGuide : bottomLayoutGuide
bar.buttonViewDelegate = self
bar.show(inSuperview: superview, withMessage: message)
}
/// Hide the message bar if it's currently open.
func hide() {
hideTimer?.cancel()
toolbar?.hide(onAnimationCompleted: {})
}
func listenForKeyboard() {
}
private var toolbar: DodoToolbar? {
get {
return superview.subviews.filter { $0 is DodoToolbar }.map { $0 as! DodoToolbar }.first
}
}
private func removeExistingBars() {
for view in superview.subviews {
if let existingToolbar = view as? DodoToolbar {
existingToolbar.removeFromSuperview()
}
}
}
// MARK: - Hiding after delay
private func setupHideTimer() {
hideTimer?.cancel()
if style.bar.hideAfterDelaySeconds > 0 {
hideTimer = MoaTimer.runAfter(style.bar.hideAfterDelaySeconds) { [weak self] timer in
dispatch_async(dispatch_get_main_queue()) {
self?.hide()
}
}
}
}
// MARK: - Reacting to tap
private func setupHideOnTap(toolbar: UIView) {
onTap = OnTap(view: toolbar, gesture: UITapGestureRecognizer()) { [weak self] in
self?.didTapTheBar()
}
}
/// The bar has been tapped
private func didTapTheBar() {
style.bar.onTap?()
if style.bar.hideOnTap {
hide()
}
}
// MARK: - DodoButtonViewDelegate
func buttonDelegateDidTap(buttonStyle: DodoButtonStyle) {
if buttonStyle.hideOnTap {
hide()
}
}
}
// ----------------------------
//
// DodoBarOnTap.swift
//
// ----------------------------
/// A closure that is called when a bar is tapped
public typealias DodoBarOnTap = ()->()
// ----------------------------
//
// DodoInterface.swift
//
// ----------------------------
import UIKit
/**
Coordinates the process of showing and hiding of the message bar.
The instance is created automatically in the `dodo` property of any UIView instance.
It is not expected to be instantiated manually anywhere except unit tests.
For example:
let view = UIView()
view.dodo.info("Horses are blue?")
*/
public protocol DodoInterface: class {
/// Specify optional layout guide for positioning the bar view.
var topLayoutGuide: UILayoutSupport? { get set }
/// Specify optional layout guide for positioning the bar view.
var bottomLayoutGuide: UILayoutSupport? { get set }
/// Defines styles for the bar.
var style: DodoStyle { get set }
/// Changes the style preset for the bar widget.
var preset: DodoPresets { get set }
/**
Shows the message bar with *.Success* preset. It can be used to indicate successful completion of an operation.
- parameter message: The text message to be shown.
*/
func success(message: String)
/**
Shows the message bar with *.Info* preset. It can be used for showing information messages that have neutral emotional value.
- parameter message: The text message to be shown.
*/
func info(message: String)
/**
Shows the message bar with *.Warning* preset. It can be used for for showing warning messages.
- parameter message: The text message to be shown.
*/
func warning(message: String)
/**
Shows the message bar with *.Warning* preset. It can be used for showing critical error messages
- parameter message: The text message to be shown.
*/
func error(message: String)
/**
Shows the message bar. Set `preset` property to change the appearance of the message bar, or use the shortcut methods: `success`, `info`, `warning` and `error`.
- parameter message: The text message to be shown.
*/
func show(message: String)
/// Hide the message bar if it's currently open.
func hide()
}
// ----------------------------
//
// DodoKeyboardListener.swift
//
// ----------------------------
/**
Start listening for keyboard events. Used for moving the message bar from under the keyboard when the bar is shown at the bottom of the screen.
*/
struct DodoKeyboardListener {
static let underKeyboardLayoutConstraint = UnderKeyboardLayoutConstraint()
static func startListening() {
// Just access the static property to make it initialize itself lazily if it hasn't been already.
underKeyboardLayoutConstraint.isAccessibilityElement = false
}
}
// ----------------------------
//
// DodoToolbar.swift
//
// ----------------------------
import UIKit
class DodoToolbar: UIView {
var layoutGuide: UILayoutSupport?
var style: DodoStyle
weak var buttonViewDelegate: DodoButtonViewDelegate?
private var didCallHide = false
convenience init(witStyle style: DodoStyle) {
self.init(frame: CGRect())
self.style = style
}
override init(frame: CGRect) {
style = DodoStyle()
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func show(inSuperview parentView: UIView, withMessage message: String) {
if superview != nil { return } // already being shown
parentView.addSubview(self)
applyStyle()
layoutBarInSuperview()
let buttons = createButtons()
createLabel(message, withButtons: buttons)
style.bar.animationShow(self, duration: style.bar.animationShowDuration,
locationTop: style.bar.locationTop, completed: {})
}
func hide(onAnimationCompleted onAnimationCompleted: ()->()) {
// Respond only to the first hide() call
if didCallHide { return }
didCallHide = true
style.bar.animationHide(self, duration: style.bar.animationHideDuration,
locationTop: style.bar.locationTop, completed: { [weak self] in
self?.removeFromSuperview()
onAnimationCompleted()
})
}
// MARK: - Label
private func createLabel(message: String, withButtons buttons: [UIView]) {
let label = UILabel()
label.font = style.label.font
label.text = message
label.textColor = style.label.color
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = style.label.numberOfLines
if style.bar.debugMode {
label.backgroundColor = UIColor.redColor()
}
if let shadowColor = style.label.shadowColor {
label.shadowColor = shadowColor
label.shadowOffset = style.label.shadowOffset
}
addSubview(label)
layoutLabel(label, withButtons: buttons)
}
private func layoutLabel(label: UILabel, withButtons buttons: [UIView]) {
label.translatesAutoresizingMaskIntoConstraints = false
// Stretch the label vertically
TegAutolayoutConstraints.fillParent(label, parentView: self,
margin: style.label.horizontalMargin, vertically: true)
if buttons.count == 0 {
if let superview = superview {
// If there are no buttons - stretch the label to the entire width of the view
TegAutolayoutConstraints.fillParent(label, parentView: superview,
margin: style.label.horizontalMargin, vertically: false)
}
} else {
layoutLabelWithButtons(label, withButtons: buttons)
}
}
private func layoutLabelWithButtons(label: UILabel, withButtons buttons: [UIView]) {
if buttons.count != 2 { return }
let views = [buttons[0], label, buttons[1]]
if let superview = superview {
TegAutolayoutConstraints.viewsNextToEachOther(views,
constraintContainer: superview, margin: style.label.horizontalMargin, vertically: false)
}
}
// MARK: - Buttons
private func createButtons() -> [DodoButtonView] {
precondition(buttonViewDelegate != nil, "Button view delegate can not be nil")
let buttonStyles = [style.leftButton, style.rightButton]
let buttonViews = DodoButtonView.createMany(buttonStyles)
for (index, button) in buttonViews.enumerate() {
addSubview(button)
button.delegate = buttonViewDelegate
button.doLayout(onLeftSide: index == 0)
if style.bar.debugMode {
button.backgroundColor = UIColor.yellowColor()
}
}
return buttonViews
}
// MARK: - Style the bar
private func applyStyle() {
backgroundColor = style.bar.backgroundColor
layer.cornerRadius = style.bar.cornerRadius
layer.masksToBounds = true
if let borderColor = style.bar.borderColor where style.bar.borderWidth > 0 {
layer.borderColor = borderColor.CGColor
layer.borderWidth = style.bar.borderWidth
}
}
private func layoutBarInSuperview() {
translatesAutoresizingMaskIntoConstraints = false
if let superview = superview {
// Stretch the toobar horizontally to the width if its superview
TegAutolayoutConstraints.fillParent(self, parentView: superview,
margin: style.bar.marginToSuperview.width, vertically: false)
let vMargin = style.bar.marginToSuperview.height
let verticalMargin = style.bar.locationTop ? -vMargin : vMargin
var verticalConstraints = [NSLayoutConstraint]()
if let layoutGuide = layoutGuide {
// Align the top/bottom edge of the toolbar with the top/bottom layout guide
// (a tab bar, for example)
verticalConstraints = TegAutolayoutConstraints.alignVerticallyToLayoutGuide(self,
onTop: style.bar.locationTop,
layoutGuide: layoutGuide,
constraintContainer: superview,
margin: verticalMargin)
} else {
// Align the top/bottom of the toolbar with the top/bottom of its superview
verticalConstraints = TegAutolayoutConstraints.alignSameAttributes(superview, toItem: self,
constraintContainer: superview,
attribute: style.bar.locationTop ? NSLayoutAttribute.Top : NSLayoutAttribute.Bottom,
margin: verticalMargin)
}
setupKeyboardEvader(verticalConstraints)
}
}
// Moves the message bar from under the keyboard
private func setupKeyboardEvader(verticalConstraints: [NSLayoutConstraint]) {
if let bottomConstraint = verticalConstraints.first,
superview = superview
where !style.bar.locationTop {
DodoKeyboardListener.underKeyboardLayoutConstraint.setup(bottomConstraint,
view: superview, bottomLayoutGuide: layoutGuide)
}
}
}
// ----------------------------
//
// DodoTouchTarget.swift
//
// ----------------------------
import UIKit
/**
Helper function to make sure bounds are big enought to be used as touch target.
The function is used in pointInside(point: CGPoint, withEvent event: UIEvent?) of UIImageView.
*/
struct DodoTouchTarget {
static func optimize(bounds: CGRect) -> CGRect {
let recommendedHitSize: CGFloat = 44
var hitWidthIncrease:CGFloat = recommendedHitSize - bounds.width
var hitHeightIncrease:CGFloat = recommendedHitSize - bounds.height
if hitWidthIncrease < 0 { hitWidthIncrease = 0 }
if hitHeightIncrease < 0 { hitHeightIncrease = 0 }
let extendedBounds: CGRect = CGRectInset(bounds,
-hitWidthIncrease / 2,
-hitHeightIncrease / 2)
return extendedBounds
}
}
// ----------------------------
//
// DodoIcons.swift
//
// ----------------------------
/**
Collection of icons included with Dodo library.
*/
public enum DodoIcons: String {
/// Icon for closing the bar.
case Close = "Close"
/// Icon for reloading.
case Reload = "Reload"
}
// ----------------------------
//
// DodoMock.swift
//
// ----------------------------
import UIKit
/**
This class is for testing the code that uses Dodo. It helps verifying the messages that were shown in the message bar without actually showing them.
Here is how to use it in your unit test.
1. Create an instance of DodoMock.
2. Set it to the `view.dodo` property of the view.
3. Run the code that you are testing.
4. Finally, verify which messages were shown in the message bar.
Example:
// Supply mock to the view
let dodoMock = DodoMock()
view.dodo = dodoMock
// Run the code from the app
runSomeAppCode()
// Verify the message is visible
XCTAssert(dodoMock.results.visible)
// Check total number of messages shown
XCTAssertEqual(1, dodoMock.results.total)
// Verify the text of the success message
XCTAssertEqual("To be prepared is half the victory.", dodoMock.results.success[0])
*/
public class DodoMock: DodoInterface {
/// This property is used in unit tests to verify which messages were displayed in the message bar.
public var results = DodoMockResults()
public var topLayoutGuide: UILayoutSupport?
public var bottomLayoutGuide: UILayoutSupport?
public var style = DodoStyle(parentStyle: DodoPresets.defaultPreset.style)
public init() { }
public var preset: DodoPresets = DodoPresets.defaultPreset {
didSet {
if preset != oldValue {
style.parent = preset.style
}
}
}
public func success(message: String) {
preset = .Success
show(message)
}
public func info(message: String) {
preset = .Info
show(message)
}
public func warning(message: String) {
preset = .Warning
show(message)
}
public func error(message: String) {
preset = .Error
show(message)
}
public func show(message: String) {
let mockMessage = DodoMockMessage(preset: preset, message: message)
results.messages.append(mockMessage)
results.visible = true
}
public func hide() {
results.visible = false
}
}
// ----------------------------
//
// DodoMockMessage.swift
//
// ----------------------------
/**
Contains information about the message that was displayed in message bar. Used in unit tests.
*/
struct DodoMockMessage {
let preset: DodoPresets
let message: String
}
// ----------------------------
//
// DodoMockResults.swift
//
// ----------------------------
/**
Used in unit tests to verify the messages that were shown in the message bar.
*/
public struct DodoMockResults {
/// An array of success messages displayed in the message bar.
public var success: [String] {
return messages.filter({ $0.preset == DodoPresets.Success }).map({ $0.message })
}
/// An array of information messages displayed in the message bar.
public var info: [String] {
return messages.filter({ $0.preset == DodoPresets.Info }).map({ $0.message })
}
/// An array of warning messages displayed in the message bar.
public var warning: [String] {
return messages.filter({ $0.preset == DodoPresets.Warning }).map({ $0.message })
}
/// An array of error messages displayed in the message bar.
public var errors: [String] {
return messages.filter({ $0.preset == DodoPresets.Error }).map({ $0.message })
}
/// Total number of messages shown.
public var total: Int {
return messages.count
}
/// Indicates whether the message is visible
public var visible = false
var messages = [DodoMockMessage]()
}
// ----------------------------
//
// DodoBarDefaultStyles.swift
//
// ----------------------------
import UIKit
/**
Default styles for the bar view.
Default styles are used when individual element styles are not set.
*/
public struct DodoBarDefaultStyles {
/// Revert the property values to their defaults
public static func resetToDefaults() {
animationHide = _animationHide
animationHideDuration = _animationHideDuration
animationShow = _animationShow
animationShowDuration = _animationShowDuration
backgroundColor = _backgroundColor
borderColor = _borderColor
borderWidth = _borderWidth
cornerRadius = _cornerRadius
debugMode = _debugMode
hideAfterDelaySeconds = _hideAfterDelaySeconds
hideOnTap = _hideOnTap
locationTop = _locationTop
marginToSuperview = _marginToSuperview
onTap = _onTap
}
// ---------------------------
private static let _animationHide: DodoAnimation = DodoAnimationsHide.rotate
/// Specify a function for animating the bar when it is hidden.
public static var animationHide: DodoAnimation = _animationHide
// ---------------------------
private static let _animationHideDuration: NSTimeInterval? = nil
/// Duration of hide animation. When nil it uses default duration for selected animation function.
public static var animationHideDuration: NSTimeInterval? = _animationHideDuration
// ---------------------------
private static let _animationShow: DodoAnimation = DodoAnimationsShow.rotate
/// Specify a function for animating the bar when it is shown.
public static var animationShow: DodoAnimation = _animationShow
// ---------------------------
private static let _animationShowDuration: NSTimeInterval? = nil
/// Duration of show animation. When nil it uses default duration for selected animation function.
public static var animationShowDuration: NSTimeInterval? = _animationShowDuration
// ---------------------------
private static let _backgroundColor: UIColor? = nil
/// Background color of the bar.
public static var backgroundColor = _backgroundColor
// ---------------------------
private static let _borderColor: UIColor? = nil
/// Color of the bar's border.
public static var borderColor = _borderColor
// ---------------------------
private static let _borderWidth: CGFloat = 1 / UIScreen.mainScreen().scale
/// Border width of the bar.
public static var borderWidth = _borderWidth
// ---------------------------
private static let _cornerRadius: CGFloat = 20
/// Corner radius of the bar view.
public static var cornerRadius = _cornerRadius
// ---------------------------
private static let _debugMode = false
/// When true it highlights the view background for spotting layout issues.
public static var debugMode = _debugMode
// ---------------------------
private static let _hideAfterDelaySeconds: NSTimeInterval = 0
/**
Hides the bar automatically after the specified number of seconds.
The bar is kept on screen indefinitely if the value is zero.
*/
public static var hideAfterDelaySeconds = _hideAfterDelaySeconds
// ---------------------------
private static let _hideOnTap = false
/// When true the bar is hidden when user taps on it.
public static var hideOnTap = _hideOnTap
// ---------------------------
private static let _locationTop = true
/// Position of the bar. When true the bar is shown on top of the screen.
public static var locationTop = _locationTop
// ---------------------------
private static let _marginToSuperview = CGSize(width: 5, height: 5)
/// Margin between the bar edge and its superview.
public static var marginToSuperview = _marginToSuperview
// ---------------------------
private static let _onTap: DodoBarOnTap? = nil
/// Supply a function that will be called when user taps the bar.
public static var onTap = _onTap
// ---------------------------
}
// ----------------------------
//
// DodoBarStyle.swift
//
// ----------------------------
import UIKit
/// Defines styles related to the bar view in general.
public class DodoBarStyle {
/// The parent style is used to get the property value if the object is missing one.
var parent: DodoBarStyle?
init(parentStyle: DodoBarStyle? = nil) {
self.parent = parentStyle
}
/// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties.
public func clear() {
_animationHide = nil
_animationHideDuration = nil
_animationShow = nil
_animationShowDuration = nil
_backgroundColor = nil
_borderColor = nil
_borderWidth = nil
_cornerRadius = nil
_debugMode = nil
_hideAfterDelaySeconds = nil
_hideOnTap = nil
_locationTop = nil
_marginToSuperview = nil
_onTap = nil
}
// -----------------------------
private var _animationHide: DodoAnimation?
/// Specify a function for animating the bar when it is hidden.
public var animationHide: DodoAnimation {
get {
return (_animationHide ?? parent?.animationHide) ?? DodoBarDefaultStyles.animationHide
}
set {
_animationHide = newValue
}
}
// ---------------------------
private var _animationHideDuration: NSTimeInterval?
/// Duration of hide animation. When nil it uses default duration for selected animation function.
public var animationHideDuration: NSTimeInterval? {
get {
return (_animationHideDuration ?? parent?.animationHideDuration) ??
DodoBarDefaultStyles.animationHideDuration
}
set {
_animationHideDuration = newValue
}
}
// ---------------------------
private var _animationShow: DodoAnimation?
/// Specify a function for animating the bar when it is shown.
public var animationShow: DodoAnimation {
get {
return (_animationShow ?? parent?.animationShow) ?? DodoBarDefaultStyles.animationShow
}
set {
_animationShow = newValue
}
}
// ---------------------------
private var _animationShowDuration: NSTimeInterval?
/// Duration of show animation. When nil it uses default duration for selected animation function.
public var animationShowDuration: NSTimeInterval? {
get {
return (_animationShowDuration ?? parent?.animationShowDuration) ??
DodoBarDefaultStyles.animationShowDuration
}
set {
_animationShowDuration = newValue
}
}
// ---------------------------
private var _backgroundColor: UIColor?
/// Background color of the bar.
public var backgroundColor: UIColor? {
get {
return _backgroundColor ?? parent?.backgroundColor ?? DodoBarDefaultStyles.backgroundColor
}
set {
_backgroundColor = newValue
}
}
// -----------------------------
private var _borderColor: UIColor?
/// Color of the bar's border.
public var borderColor: UIColor? {
get {
return _borderColor ?? parent?.borderColor ?? DodoBarDefaultStyles.borderColor
}
set {
_borderColor = newValue
}
}
// -----------------------------
private var _borderWidth: CGFloat?
/// Border width of the bar.
public var borderWidth: CGFloat {
get {
return _borderWidth ?? parent?.borderWidth ?? DodoBarDefaultStyles.borderWidth
}
set {
_borderWidth = newValue
}
}
// -----------------------------
private var _cornerRadius: CGFloat?
/// Corner radius of the bar view.
public var cornerRadius: CGFloat {
get {
return _cornerRadius ?? parent?.cornerRadius ?? DodoBarDefaultStyles.cornerRadius
}
set {
_cornerRadius = newValue
}
}
// -----------------------------
private var _debugMode: Bool?
/// When true it highlights the view background for spotting layout issues.
public var debugMode: Bool {
get {
return _debugMode ?? parent?.debugMode ?? DodoBarDefaultStyles.debugMode
}
set {
_debugMode = newValue
}
}
// ---------------------------
private var _hideAfterDelaySeconds: NSTimeInterval?
/**
Hides the bar automatically after the specified number of seconds.
If nil the bar is kept on screen.
*/
public var hideAfterDelaySeconds: NSTimeInterval {
get {
return _hideAfterDelaySeconds ?? parent?.hideAfterDelaySeconds ??
DodoBarDefaultStyles.hideAfterDelaySeconds
}
set {
_hideAfterDelaySeconds = newValue
}
}
// -----------------------------
private var _hideOnTap: Bool?
/// When true the bar is hidden when user taps on it.
public var hideOnTap: Bool {
get {
return _hideOnTap ?? parent?.hideOnTap ??
DodoBarDefaultStyles.hideOnTap
}
set {
_hideOnTap = newValue
}
}
// -----------------------------
private var _locationTop: Bool?
/// Position of the bar. When true the bar is shown on top of the screen.
public var locationTop: Bool {
get {
return _locationTop ?? parent?.locationTop ?? DodoBarDefaultStyles.locationTop
}
set {
_locationTop = newValue
}
}
// -----------------------------
private var _marginToSuperview: CGSize?
/// Margin between the bar edge and its superview.
public var marginToSuperview: CGSize {
get {
return _marginToSuperview ?? parent?.marginToSuperview ??
DodoBarDefaultStyles.marginToSuperview
}
set {
_marginToSuperview = newValue
}
}
// ---------------------------
private var _onTap: DodoBarOnTap?
/// Supply a function that will be called when user taps the bar.
public var onTap: DodoBarOnTap? {
get {
return _onTap ?? parent?.onTap ?? DodoBarDefaultStyles.onTap
}
set {
_onTap = newValue
}
}
// -----------------------------
}
// ----------------------------
//
// DodoButtonDefaultStyles.swift
//
// ----------------------------
import UIKit
/**
Default styles for the bar button.
Default styles are used when individual element styles are not set.
*/
public struct DodoButtonDefaultStyles {
/// Revert the property values to their defaults
public static func resetToDefaults() {
accessibilityLabel = _accessibilityLabel
hideOnTap = _hideOnTap
horizontalMarginToBar = _horizontalMarginToBar
icon = _icon
image = _image
onTap = _onTap
size = _size
tintColor = _tintColor
}
// ---------------------------
private static let _accessibilityLabel: String? = nil
/**
This text is spoken by the device when it is in accessibility mode. It is recommended to always set the accessibility label for your button. The text can be a short localized description of the button function, for example: "Close the message", "Reload" etc.
*/
public static var accessibilityLabel = _accessibilityLabel
// ---------------------------
private static let _hideOnTap = false
/// When true it hides the bar when the button is tapped.
public static var hideOnTap = _hideOnTap
// ---------------------------
private static let _horizontalMarginToBar: CGFloat = 10
/// Margin between the bar edge and the button
public static var horizontalMarginToBar = _horizontalMarginToBar
// ---------------------------
private static let _icon: DodoIcons? = nil
/// When set it shows one of the default Dodo icons. Use `image` property to supply a custom image. The color of the image can be changed with `tintColor` property.
public static var icon = _icon
// ---------------------------
private static let _image: UIImage? = nil
/// Custom image for the button. One can also use the `icon` property to show one of the default Dodo icons. The color of the image can be changed with `tintColor` property.
public static var image = _image
// ---------------------------
private static let _onTap: DodoButtonOnTap? = nil
/// Supply a function that will be called when user taps the button.
public static var onTap = _onTap
// ---------------------------
private static let _size = CGSize(width: 25, height: 25)
/// Size of the button.
public static var size = _size
// ---------------------------
private static let _tintColor: UIColor? = nil
/// Replaces the color of the image or icon. The original colors are used when nil.
public static var tintColor = _tintColor
// ---------------------------
}
// ----------------------------
//
// DodoButtonStyle.swift
//
// ----------------------------
import UIKit
/// Defines styles for the bar button.
public class DodoButtonStyle {
/// The parent style is used to get the property value if the object is missing one.
var parent: DodoButtonStyle?
init(parentStyle: DodoButtonStyle? = nil) {
self.parent = parentStyle
}
/// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties.
public func clear() {
_accessibilityLabel = nil
_hideOnTap = nil
_horizontalMarginToBar = nil
_icon = nil
_image = nil
_onTap = nil
_size = nil
_tintColor = nil
}
// -----------------------------
private var _accessibilityLabel: String?
/**
This text is spoken by the device when it is in accessibility mode. It is recommended to always set the accessibility label for your button. The text can be a short localized description of the button function, for example: "Close the message", "Reload" etc.
*/
public var accessibilityLabel: String? {
get {
return _accessibilityLabel ?? parent?.accessibilityLabel ?? DodoButtonDefaultStyles.accessibilityLabel
}
set {
_accessibilityLabel = newValue
}
}
// -----------------------------
private var _hideOnTap: Bool?
/// When true it hides the bar when the button is tapped.
public var hideOnTap: Bool {
get {
return _hideOnTap ?? parent?.hideOnTap ?? DodoButtonDefaultStyles.hideOnTap
}
set {
_hideOnTap = newValue
}
}
// -----------------------------
private var _horizontalMarginToBar: CGFloat?
/// Horizontal margin between the bar edge and the button.
public var horizontalMarginToBar: CGFloat {
get {
return _horizontalMarginToBar ?? parent?.horizontalMarginToBar ??
DodoButtonDefaultStyles.horizontalMarginToBar
}
set {
_horizontalMarginToBar = newValue
}
}
// -----------------------------
private var _icon: DodoIcons?
/// When set it shows one of the default Dodo icons. Use `image` property to supply a custom image. The color of the image can be changed with `tintColor` property.
public var icon: DodoIcons? {
get {
return _icon ?? parent?.icon ?? DodoButtonDefaultStyles.icon
}
set {
_icon = newValue
}
}
// -----------------------------
private var _image: UIImage?
/// Custom image for the button. One can also use the `icon` property to show one of the default Dodo icons. The color of the image can be changed with `tintColor` property.
public var image: UIImage? {
get {
return _image ?? parent?.image ?? DodoButtonDefaultStyles.image
}
set {
_image = newValue
}
}
// ---------------------------
private var _onTap: DodoButtonOnTap?
/// Supply a function that will be called when user taps the button.
public var onTap: DodoButtonOnTap? {
get {
return _onTap ?? parent?.onTap ?? DodoButtonDefaultStyles.onTap
}
set {
_onTap = newValue
}
}
// -----------------------------
private var _size: CGSize?
/// Size of the button.
public var size: CGSize {
get {
return _size ?? parent?.size ?? DodoButtonDefaultStyles.size
}
set {
_size = newValue
}
}
// -----------------------------
private var _tintColor: UIColor?
/// Replaces the color of the image or icon. The original colors are used when nil.
public var tintColor: UIColor? {
get {
return _tintColor ?? parent?.tintColor ?? DodoButtonDefaultStyles.tintColor
}
set {
_tintColor = newValue
}
}
// -----------------------------
}
// ----------------------------
//
// DodoLabelDefaultStyles.swift
//
// ----------------------------
import UIKit
/**
Default styles for the text label.
Default styles are used when individual element styles are not set.
*/
public struct DodoLabelDefaultStyles {
/// Revert the property values to their defaults
public static func resetToDefaults() {
color = _color
font = _font
horizontalMargin = _horizontalMargin
numberOfLines = _numberOfLines
shadowColor = _shadowColor
shadowOffset = _shadowOffset
}
// ---------------------------
private static let _color = UIColor.whiteColor()
/// Color of the label text.
public static var color = _color
// ---------------------------
private static let _font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
/// Font of the label text.
public static var font = _font
// ---------------------------
private static let _horizontalMargin: CGFloat = 10
/// Margin between the bar/button edge and the label.
public static var horizontalMargin = _horizontalMargin
// ---------------------------
private static let _numberOfLines: Int = 3
/// The maximum number of lines in the label.
public static var numberOfLines = _numberOfLines
// ---------------------------
private static let _shadowColor: UIColor? = nil
/// Color of text shadow.
public static var shadowColor = _shadowColor
// ---------------------------
private static let _shadowOffset = CGSize(width: 0, height: 1)
/// Text shadow offset.
public static var shadowOffset = _shadowOffset
// ---------------------------
}
// ----------------------------
//
// DodoLabelStyle.swift
//
// ----------------------------
import UIKit
/// Defines styles related to the text label.
public class DodoLabelStyle {
/// The parent style is used to get the property value if the object is missing one.
var parent: DodoLabelStyle?
init(parentStyle: DodoLabelStyle? = nil) {
self.parent = parentStyle
}
/// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties.
public func clear() {
_color = nil
_font = nil
_horizontalMargin = nil
_numberOfLines = nil
_shadowColor = nil
_shadowOffset = nil
}
// -----------------------------
private var _color: UIColor?
/// Color of the label text.
public var color: UIColor {
get {
return _color ?? parent?.color ?? DodoLabelDefaultStyles.color
}
set {
_color = newValue
}
}
// -----------------------------
private var _font: UIFont?
/// Color of the label text.
public var font: UIFont {
get {
return _font ?? parent?.font ?? DodoLabelDefaultStyles.font
}
set {
_font = newValue
}
}
// -----------------------------
private var _horizontalMargin: CGFloat?
/// Margin between the bar/button edge and the label.
public var horizontalMargin: CGFloat {
get {
return _horizontalMargin ?? parent?.horizontalMargin ??
DodoLabelDefaultStyles.horizontalMargin
}
set {
_horizontalMargin = newValue
}
}
// -----------------------------
private var _numberOfLines: Int?
/// The maximum number of lines in the label.
public var numberOfLines: Int {
get {
return _numberOfLines ?? parent?.numberOfLines ??
DodoLabelDefaultStyles.numberOfLines
}
set {
_numberOfLines = newValue
}
}
// -----------------------------
private var _shadowColor: UIColor?
/// Color of text shadow.
public var shadowColor: UIColor? {
get {
return _shadowColor ?? parent?.shadowColor ?? DodoLabelDefaultStyles.shadowColor
}
set {
_shadowColor = newValue
}
}
// -----------------------------
private var _shadowOffset: CGSize?
/// Text shadow offset.
public var shadowOffset: CGSize {
get {
return _shadowOffset ?? parent?.shadowOffset ?? DodoLabelDefaultStyles.shadowOffset
}
set {
_shadowOffset = newValue
}
}
// -----------------------------
}
// ----------------------------
//
// DodoPresets.swift
//
// ----------------------------
/**
Defines the style presets for the bar.
*/
public enum DodoPresets {
/// A styling preset used for indicating successful completion of an operation. Usually styled with green color.
case Success
/// A styling preset for showing information messages, neutral in color.
case Info
/// A styling preset for showing warning messages. Can be styled with yellow/orange colors.
case Warning
/// A styling preset for showing critical error messages. Usually styled with red color.
case Error
/// The preset is used by default for the bar if it's not set by the user.
static let defaultPreset = DodoPresets.Success
/// The preset cache.
private static var styles = [DodoPresets: DodoStyle]()
/// Returns the style for the preset
public var style: DodoStyle {
var style = DodoPresets.styles[self]
if style == nil {
style = DodoPresets.makeStyle(forPreset: self)
DodoPresets.styles[self] = style
}
precondition(style != nil, "Failed to create style")
return style ?? DodoStyle()
}
/// Reset alls preset styles to their initial states.
public static func resetAll() {
styles = [:]
}
/// Reset the preset style to its initial state.
public func reset() {
DodoPresets.styles.removeValueForKey(self)
}
private static func makeStyle(forPreset preset: DodoPresets) -> DodoStyle{
let style = DodoStyle()
switch preset {
case .Success:
style.bar.backgroundColor = DodoColor.fromHexString("#00CC03C9")
case .Info:
style.bar.backgroundColor = DodoColor.fromHexString("#0057FF96")
case .Warning:
style.bar.backgroundColor = DodoColor.fromHexString("#CEC411DD")
case .Error:
style.bar.backgroundColor = DodoColor.fromHexString("#FF0B0BCC")
}
return style
}
}
// ----------------------------
//
// DodoStyle.swift
//
// ----------------------------
import UIKit
/// Combines various styles for the toolbar element.
public class DodoStyle {
/// The parent style is used to get the property value if the object is missing one.
var parent: DodoStyle? {
didSet {
changeParent()
}
}
init(parentStyle: DodoStyle? = nil) {
self.parent = parentStyle
}
private func changeParent() {
bar.parent = parent?.bar
label.parent = parent?.label
leftButton.parent = parent?.leftButton
rightButton.parent = parent?.rightButton
}
/**
Reverts all the default styles to their initial values. Usually used in setUp() function in the unit tests.
*/
public static func resetDefaultStyles() {
DodoBarDefaultStyles.resetToDefaults()
DodoLabelDefaultStyles.resetToDefaults()
DodoButtonDefaultStyles.resetToDefaults()
}
/// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties.
public func clear() {
bar.clear()
label.clear()
leftButton.clear()
rightButton.clear()
}
/**
Styles for the bar view.
*/
public lazy var bar: DodoBarStyle = self.initBarStyle()
private func initBarStyle() -> DodoBarStyle {
return DodoBarStyle(parentStyle: parent?.bar)
}
/**
Styles for the text label.
*/
public lazy var label: DodoLabelStyle = self.initLabelStyle()
private func initLabelStyle() -> DodoLabelStyle {
return DodoLabelStyle(parentStyle: parent?.label)
}
/**
Styles for the left button.
*/
public lazy var leftButton: DodoButtonStyle = self.initLeftButtonStyle()
private func initLeftButtonStyle() -> DodoButtonStyle {
return DodoButtonStyle(parentStyle: parent?.leftButton)
}
/**
Styles for the right button.
*/
public lazy var rightButton: DodoButtonStyle = self.initRightButtonStyle()
private func initRightButtonStyle() -> DodoButtonStyle {
return DodoButtonStyle(parentStyle: parent?.rightButton)
}
}
// ----------------------------
//
// UIView+SwiftAlertBar.swift
//
// ----------------------------
import UIKit
private var sabAssociationKey: UInt8 = 0
/**
UIView extension for showing a notification widget.
let view = UIView()
view.dodo.show("Hello World!")
*/
public extension UIView {
/**
Message bar extension.
Call `dodo.show`, `dodo.success`, dodo.error` functions to show a notification widget in the view.
let view = UIView()
view.dodo.show("Hello World!")
*/
public var dodo: DodoInterface {
get {
if let value = objc_getAssociatedObject(self, &sabAssociationKey) as? DodoInterface {
return value
} else {
let dodo = Dodo(superview: self)
objc_setAssociatedObject(self, &sabAssociationKey, dodo,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
return dodo
}
}
set {
objc_setAssociatedObject(self, &sabAssociationKey, newValue,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
}
// ----------------------------
//
// DodoColor.swift
//
// ----------------------------
import UIKit
/**
Creates a UIColor object from a string.
Examples:
DodoColor.fromHexString('#340f9a')
// With alpha channel
DodoColor.fromHexString('#f1a2b3a6')
*/
public class DodoColor {
/**
Creates a UIColor object from a string.
- parameter rgba: a RGB/RGBA string representation of color. It can include optional alpha value. Example: "#cca213" or "#cca21312" (with alpha value).
- returns: UIColor object.
*/
public class func fromHexString(rgba: String) -> UIColor {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if !rgba.hasPrefix("#") {
print("Warning: DodoColor.fromHexString, # character missing")
return UIColor()
}
let index = rgba.startIndex.advancedBy(1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if !scanner.scanHexLongLong(&hexValue) {
print("Warning: DodoColor.fromHexString, error scanning hex value")
return UIColor()
}
if hex.characters.count == 6 {
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
} else if hex.characters.count == 8 {
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
} else {
print("Warning: DodoColor.fromHexString, invalid rgb string, length should be 7 or 9")
return UIColor()
}
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
}
// ----------------------------
//
// MoaTimer.swift
//
// ----------------------------
import UIKit
/**
Creates a timer that executes code after delay.
Usage
var timer: MoaTimer.runAfter?
...
func myFunc() {
timer = MoaTimer.runAfter(0.010) { timer in
... code to run
}
}
Canceling the timer
Timer is Canceling automatically when it is deallocated. You can also cancel it manually:
let timer = MoaTimer.runAfter(0.010) { timer in ... }
timer.cancel()
*/
final class MoaTimer: NSObject {
private let repeats: Bool
private var timer: NSTimer?
private var callback: ((MoaTimer)->())?
private init(interval: NSTimeInterval, repeats: Bool = false, callback: (MoaTimer)->()) {
self.repeats = repeats
super.init()
self.callback = callback
timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self,
selector: "timerFired:", userInfo: nil, repeats: repeats)
}
/// Timer is cancelled automatically when it is deallocated.
deinit {
cancel()
}
/**
Cancels the timer and prevents it from firing in the future.
Note that timer is cancelled automatically whe it is deallocated.
*/
func cancel() {
timer?.invalidate()
timer = nil
}
/**
Runs the closure after specified time interval.
- parameter interval: Time interval in milliseconds.
:repeats: repeats When true, the code is run repeatedly.
- returns: callback A closure to be run by the timer.
*/
class func runAfter(interval: NSTimeInterval, repeats: Bool = false,
callback: (MoaTimer)->()) -> MoaTimer {
return MoaTimer(interval: interval, repeats: repeats, callback: callback)
}
func timerFired(timer: NSTimer) {
self.callback?(self)
if !repeats { cancel() }
}
}
// ----------------------------
//
// OnTap.swift
//
// ----------------------------
import UIKit
/**
Calling tap with closure.
*/
class OnTap: NSObject {
var closure: ()->()
init(view: UIView, gesture: UIGestureRecognizer, closure:()->()) {
self.closure = closure
super.init()
view.addGestureRecognizer(gesture)
view.userInteractionEnabled = true
gesture.addTarget(self, action: "didTap:")
}
func didTap(gesture: UIGestureRecognizer) {
closure()
}
}
// ----------------------------
//
// SpringAnimationCALayer.swift
//
// ----------------------------
import UIKit
/**
Animating CALayer with spring effect in iOS with Swift
https://github.com/evgenyneu/SpringAnimationCALayer
*/
class SpringAnimationCALayer {
// Animates layer with spring effect.
class func animate(layer: CALayer,
keypath: String,
duration: CFTimeInterval,
usingSpringWithDamping: Double,
initialSpringVelocity: Double,
fromValue: Double,
toValue: Double,
onFinished: (()->())?) {
CATransaction.begin()
CATransaction.setCompletionBlock(onFinished)
let animation = create(keypath, duration: duration,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
fromValue: fromValue, toValue: toValue)
layer.addAnimation(animation, forKey: keypath + " spring animation")
CATransaction.commit()
}
// Creates CAKeyframeAnimation object
class func create(keypath: String,
duration: CFTimeInterval,
usingSpringWithDamping: Double,
initialSpringVelocity: Double,
fromValue: Double,
toValue: Double) -> CAKeyframeAnimation {
let dampingMultiplier = Double(10)
let velocityMultiplier = Double(10)
let values = animationValues(fromValue, toValue: toValue,
usingSpringWithDamping: dampingMultiplier * usingSpringWithDamping,
initialSpringVelocity: velocityMultiplier * initialSpringVelocity)
let animation = CAKeyframeAnimation(keyPath: keypath)
animation.values = values
animation.duration = duration
return animation
}
class func animationValues(fromValue: Double, toValue: Double,
usingSpringWithDamping: Double, initialSpringVelocity: Double) -> [Double]{
let numOfPoints = 1000
var values = [Double](count: numOfPoints, repeatedValue: 0.0)
let distanceBetweenValues = toValue - fromValue
for point in (0..<numOfPoints) {
let x = Double(point) / Double(numOfPoints)
let valueNormalized = animationValuesNormalized(x,
usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity)
let value = toValue - distanceBetweenValues * valueNormalized
values[point] = value
}
return values
}
private class func animationValuesNormalized(x: Double, usingSpringWithDamping: Double,
initialSpringVelocity: Double) -> Double {
return pow(M_E, -usingSpringWithDamping * x) * cos(initialSpringVelocity * x)
}
}
// ----------------------------
//
// TegAutolayoutConstraints.swift
//
// ----------------------------
//
// TegAlign.swift
//
// Collection of shortcuts to create autolayout constraints.
//
import UIKit
class TegAutolayoutConstraints {
class func centerX(viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView) -> [NSLayoutConstraint] {
return center(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, vertically: false)
}
class func centerY(viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView) -> [NSLayoutConstraint] {
return center(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, vertically: true)
}
private class func center(viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView, vertically: Bool = false) -> [NSLayoutConstraint] {
let attribute = vertically ? NSLayoutAttribute.CenterY : NSLayoutAttribute.CenterX
let constraint = NSLayoutConstraint(
item: viewOne,
attribute: attribute,
relatedBy: NSLayoutRelation.Equal,
toItem: viewTwo,
attribute: attribute,
multiplier: 1,
constant: 0)
constraintContainer.addConstraint(constraint)
return [constraint]
}
class func alignSameAttributes(item: AnyObject, toItem: AnyObject,
constraintContainer: UIView, attribute: NSLayoutAttribute, margin: CGFloat = 0) -> [NSLayoutConstraint] {
let constraint = NSLayoutConstraint(
item: item,
attribute: attribute,
relatedBy: NSLayoutRelation.Equal,
toItem: toItem,
attribute: attribute,
multiplier: 1,
constant: margin)
constraintContainer.addConstraint(constraint)
return [constraint]
}
class func alignVerticallyToLayoutGuide(item: AnyObject, onTop: Bool,
layoutGuide: UILayoutSupport, constraintContainer: UIView,
margin: CGFloat = 0) -> [NSLayoutConstraint] {
let constraint = NSLayoutConstraint(
item: layoutGuide,
attribute: onTop ? NSLayoutAttribute.Bottom : NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: item,
attribute: onTop ? NSLayoutAttribute.Top : NSLayoutAttribute.Bottom,
multiplier: 1,
constant: margin)
constraintContainer.addConstraint(constraint)
return [constraint]
}
class func aspectRatio(view: UIView, ratio: CGFloat) {
let constraint = NSLayoutConstraint(
item: view,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.Height,
multiplier: ratio,
constant: 0)
view.addConstraint(constraint)
}
class func fillParent(view: UIView, parentView: UIView, margin: CGFloat = 0, vertically: Bool = false) {
var marginFormat = ""
if margin != 0 {
marginFormat = "-\(margin)-"
}
var format = "|\(marginFormat)[view]\(marginFormat)|"
if vertically {
format = "V:" + format
}
let constraints = NSLayoutConstraint.constraintsWithVisualFormat(format,
options: [], metrics: nil,
views: ["view": view])
parentView.addConstraints(constraints)
}
class func viewsNextToEachOther(views: [UIView],
constraintContainer: UIView, margin: CGFloat = 0,
vertically: Bool = false) -> [NSLayoutConstraint] {
if views.count < 2 { return [] }
var constraints = [NSLayoutConstraint]()
for (index, view) in views.enumerate() {
if index >= views.count - 1 { break }
let viewTwo = views[index + 1]
constraints += twoViewsNextToEachOther(view, viewTwo: viewTwo,
constraintContainer: constraintContainer, margin: margin, vertically: vertically)
}
return constraints
}
class func twoViewsNextToEachOther(viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView, margin: CGFloat = 0,
vertically: Bool = false) -> [NSLayoutConstraint] {
var marginFormat = ""
if margin != 0 {
marginFormat = "-\(margin)-"
}
var format = "[viewOne]\(marginFormat)[viewTwo]"
if vertically {
format = "V:" + format
}
let constraints = NSLayoutConstraint.constraintsWithVisualFormat(format,
options: [], metrics: nil,
views: [ "viewOne": viewOne, "viewTwo": viewTwo ])
constraintContainer.addConstraints(constraints)
return constraints
}
class func equalWidth(viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView) -> [NSLayoutConstraint] {
let constraints = NSLayoutConstraint.constraintsWithVisualFormat("[viewOne(==viewTwo)]",
options: [], metrics: nil,
views: ["viewOne": viewOne, "viewTwo": viewTwo])
constraintContainer.addConstraints(constraints)
return constraints
}
class func height(view: UIView, value: CGFloat) -> [NSLayoutConstraint] {
return widthOrHeight(view, value: value, isWidth: false)
}
class func width(view: UIView, value: CGFloat) -> [NSLayoutConstraint] {
return widthOrHeight(view, value: value, isWidth: true)
}
private class func widthOrHeight(view: UIView, value: CGFloat,
isWidth: Bool) -> [NSLayoutConstraint] {
let attribute = isWidth ? NSLayoutAttribute.Width : NSLayoutAttribute.Height
let constraint = NSLayoutConstraint(
item: view,
attribute: attribute,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: value)
view.addConstraint(constraint)
return [constraint]
}
}
// ----------------------------
//
// UnderKeyboardDistrib.swift
//
// ----------------------------
//
// An iOS libary for moving content from under the keyboard.
//
// https://github.com/marketplacer/UnderKeyboard
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// UnderKeyboardLayoutConstraint.swift
//
// ----------------------------
import UIKit
/**
Adjusts the length (constant value) of the bottom layout constraint when keyboard shows and hides.
*/
@objc public class UnderKeyboardLayoutConstraint: NSObject {
private weak var bottomLayoutConstraint: NSLayoutConstraint?
private weak var bottomLayoutGuide: UILayoutSupport?
private var keyboardObserver = UnderKeyboardObserver()
private var initialConstraintConstant: CGFloat = 0
private var minMargin: CGFloat = 10
private var viewToAnimate: UIView?
public override init() {
super.init()
keyboardObserver.willAnimateKeyboard = keyboardWillAnimate
keyboardObserver.animateKeyboard = animateKeyboard
keyboardObserver.start()
}
deinit {
stop()
}
/// Stop listening for keyboard notifications.
public func stop() {
keyboardObserver.stop()
}
/**
Supply a bottom Auto Layout constraint. Its constant value will be adjusted by the height of the keyboard when it appears and hides.
- parameter bottomLayoutConstraint: Supply a bottom layout constraint. Its constant value will be adjusted when keyboard is shown and hidden.
- parameter view: Supply a view that will be used to animate the constraint. It is usually the superview containing the view with the constraint.
- parameter minMargin: Specify the minimum margin between the keyboard and the bottom of the view the constraint is attached to. Default: 10.
- parameter bottomLayoutGuide: Supply an optional bottom layout guide (like a tab bar) that will be taken into account during height calculations.
*/
public func setup(bottomLayoutConstraint: NSLayoutConstraint,
view: UIView, minMargin: CGFloat = 10,
bottomLayoutGuide: UILayoutSupport? = nil) {
initialConstraintConstant = bottomLayoutConstraint.constant
self.bottomLayoutConstraint = bottomLayoutConstraint
self.minMargin = minMargin
self.bottomLayoutGuide = bottomLayoutGuide
self.viewToAnimate = view
// Keyboard is already open when setup is called
if let currentKeyboardHeight = keyboardObserver.currentKeyboardHeight
where currentKeyboardHeight > 0 {
keyboardWillAnimate(currentKeyboardHeight)
}
}
func keyboardWillAnimate(height: CGFloat) {
guard let bottomLayoutConstraint = bottomLayoutConstraint else { return }
let layoutGuideHeight = bottomLayoutGuide?.length ?? 0
let correctedHeight = height - layoutGuideHeight
if height > 0 {
let newConstantValue = correctedHeight + minMargin
if newConstantValue > initialConstraintConstant {
// Keyboard height is bigger than the initial constraint length.
// Increase constraint length.
bottomLayoutConstraint.constant = newConstantValue
} else {
// Keyboard height is NOT bigger than the initial constraint length.
// Show the initial constraint length.
bottomLayoutConstraint.constant = initialConstraintConstant
}
} else {
bottomLayoutConstraint.constant = initialConstraintConstant
}
}
func animateKeyboard(height: CGFloat) {
viewToAnimate?.layoutIfNeeded()
}
}
// ----------------------------
//
// UnderKeyboardObserver.swift
//
// ----------------------------
import UIKit
/**
Detects appearance of software keyboard and calls the supplied closures that can be used for changing the layout and moving view from under the keyboard.
*/
public final class UnderKeyboardObserver: NSObject {
public typealias AnimationCallback = (height: CGFloat) -> ()
let notificationCenter: NSNotificationCenter
/// Function that will be called before the keyboard is shown and before animation is started.
public var willAnimateKeyboard: AnimationCallback?
/// Function that will be called inside the animation block. This can be used to call `layoutIfNeeded` on the view.
public var animateKeyboard: AnimationCallback?
/// Current height of the keyboard. Has value `nil` if unknown.
public var currentKeyboardHeight: CGFloat?
public override init() {
notificationCenter = NSNotificationCenter.defaultCenter()
super.init()
}
deinit {
stop()
}
/// Start listening for keyboard notifications.
public func start() {
stop()
notificationCenter.addObserver(self, selector: Selector("keyboardNotification:"), name:UIKeyboardWillShowNotification, object: nil);
notificationCenter.addObserver(self, selector: Selector("keyboardNotification:"), name:UIKeyboardWillHideNotification, object: nil);
}
/// Stop listening for keyboard notifications.
public func stop() {
notificationCenter.removeObserver(self)
}
// MARK: - Notification
func keyboardNotification(notification: NSNotification) {
let isShowing = notification.name == UIKeyboardWillShowNotification
if let userInfo = notification.userInfo,
let height = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue().height,
let duration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
let correctedHeight = isShowing ? height : 0
willAnimateKeyboard?(height: correctedHeight)
UIView.animateWithDuration(duration,
delay: NSTimeInterval(0),
options: UIViewAnimationOptions(rawValue: animationCurveRawNSN.unsignedLongValue),
animations: { [weak self] in
self?.animateKeyboard?(height: correctedHeight)
},
completion: nil
)
currentKeyboardHeight = correctedHeight
}
}
}
| apache-2.0 |
justindarc/firefox-ios | Account/FxAState.swift | 2 | 13469 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import FxA
import Shared
import SwiftyJSON
// The version of the state schema we persist.
let StateSchemaVersion = 2
// We want an enum because the set of states is closed. However, each state has state-specific
// behaviour, and the state's behaviour accumulates, so each state is a class. Switch on the
// label to get exhaustive cases.
public enum FxAStateLabel: String {
case engagedBeforeVerified = "engagedBeforeVerified"
case engagedAfterVerified = "engagedAfterVerified"
case cohabitingBeforeKeyPair = "cohabitingBeforeKeyPair"
case cohabitingAfterKeyPair = "cohabitingAfterKeyPair"
case married = "married"
case separated = "separated"
case doghouse = "doghouse"
// See http://stackoverflow.com/a/24137319
static let allValues: [FxAStateLabel] = [
engagedBeforeVerified,
engagedAfterVerified,
cohabitingBeforeKeyPair,
cohabitingAfterKeyPair,
married,
separated,
doghouse,
]
}
public enum FxAActionNeeded {
case none
case needsVerification
case needsPassword
case needsUpgrade
}
func state(fromJSON json: JSON) -> FxAState? {
if json.error != nil {
return nil
}
if let version = json["version"].int {
if version == 1 {
return stateV1(fromJSON: json)
} else if version == 2 {
return stateV2(fromJSON: json)
}
}
return nil
}
func stateV1(fromJSON json: JSON) -> FxAState? {
var json = json
json["version"] = 2
if let kB = json["kB"].string?.hexDecodedData {
let kSync = FxAClient10.deriveKSync(kB)
let kXCS = FxAClient10.computeClientState(kB)
json["kSync"] = JSON(kSync.hexEncodedString as NSString)
json["kXCS"] = JSON(kXCS as NSString)
json["kA"] = JSON.null
json["kB"] = JSON.null
}
return stateV2(fromJSON: json)
}
// Identical to V1 except `(kA, kB)` have been replaced with `(kSync, kXCS)` throughout.
func stateV2(fromJSON json: JSON) -> FxAState? {
if let labelString = json["label"].string {
if let label = FxAStateLabel(rawValue: labelString) {
switch label {
case .engagedBeforeVerified:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let keyFetchToken = json["keyFetchToken"].string?.hexDecodedData,
let unwrapkB = json["unwrapkB"].string?.hexDecodedData,
let knownUnverifiedAt = json["knownUnverifiedAt"].int64,
let lastNotifiedUserAt = json["lastNotifiedUserAt"].int64 {
return EngagedBeforeVerifiedState(
knownUnverifiedAt: UInt64(knownUnverifiedAt), lastNotifiedUserAt: UInt64(lastNotifiedUserAt),
sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
case .engagedAfterVerified:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let keyFetchToken = json["keyFetchToken"].string?.hexDecodedData,
let unwrapkB = json["unwrapkB"].string?.hexDecodedData {
return EngagedAfterVerifiedState(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
case .cohabitingBeforeKeyPair:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let kSync = json["kSync"].string?.hexDecodedData,
let kXCS = json["kXCS"].string {
return CohabitingBeforeKeyPairState(sessionToken: sessionToken, kSync: kSync, kXCS: kXCS)
}
case .cohabitingAfterKeyPair:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let kSync = json["kSync"].string?.hexDecodedData,
let kXCS = json["kXCS"].string,
let keyPairJSON = json["keyPair"].dictionaryObject,
let keyPair = RSAKeyPair(jsonRepresentation: keyPairJSON),
let keyPairExpiresAt = json["keyPairExpiresAt"].int64 {
return CohabitingAfterKeyPairState(sessionToken: sessionToken, kSync: kSync, kXCS: kXCS,
keyPair: keyPair, keyPairExpiresAt: UInt64(keyPairExpiresAt))
}
case .married:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let kSync = json["kSync"].string?.hexDecodedData,
let kXCS = json["kXCS"].string,
let keyPairJSON = json["keyPair"].dictionaryObject,
let keyPair = RSAKeyPair(jsonRepresentation: keyPairJSON),
let keyPairExpiresAt = json["keyPairExpiresAt"].int64,
let certificate = json["certificate"].string,
let certificateExpiresAt = json["certificateExpiresAt"].int64 {
return MarriedState(sessionToken: sessionToken, kSync: kSync, kXCS: kXCS,
keyPair: keyPair, keyPairExpiresAt: UInt64(keyPairExpiresAt),
certificate: certificate, certificateExpiresAt: UInt64(certificateExpiresAt))
}
case .separated:
return SeparatedState()
case .doghouse:
return DoghouseState()
}
}
}
return nil
}
// Not an externally facing state!
open class FxAState: JSONLiteralConvertible {
open var label: FxAStateLabel { return FxAStateLabel.separated } // This is bogus, but we have to do something!
open var actionNeeded: FxAActionNeeded {
// Kind of nice to have this in one place.
switch label {
case .engagedBeforeVerified: return .needsVerification
case .engagedAfterVerified: return .none
case .cohabitingBeforeKeyPair: return .none
case .cohabitingAfterKeyPair: return .none
case .married: return .none
case .separated: return .needsPassword
case .doghouse: return .needsUpgrade
}
}
open func asJSON() -> JSON {
return JSON([
"version": StateSchemaVersion,
"label": self.label.rawValue,
])
}
}
open class SeparatedState: FxAState {
override open var label: FxAStateLabel { return FxAStateLabel.separated }
override public init() {
super.init()
}
}
// Not an externally facing state!
open class TokenState: FxAState {
let sessionToken: Data
init(sessionToken: Data) {
self.sessionToken = sessionToken
super.init()
}
open override func asJSON() -> JSON {
var d: [String: JSON] = super.asJSON().dictionary!
d["sessionToken"] = JSON(sessionToken.hexEncodedString as NSString)
return JSON(d)
}
}
// Not an externally facing state!
open class ReadyForKeys: TokenState {
let keyFetchToken: Data
let unwrapkB: Data
init(sessionToken: Data, keyFetchToken: Data, unwrapkB: Data) {
self.keyFetchToken = keyFetchToken
self.unwrapkB = unwrapkB
super.init(sessionToken: sessionToken)
}
open override func asJSON() -> JSON {
var d: [String: JSON] = super.asJSON().dictionary!
d["keyFetchToken"] = JSON(keyFetchToken.hexEncodedString as NSString)
d["unwrapkB"] = JSON(unwrapkB.hexEncodedString as NSString)
return JSON(d)
}
}
open class EngagedBeforeVerifiedState: ReadyForKeys {
override open var label: FxAStateLabel { return FxAStateLabel.engagedBeforeVerified }
// Timestamp, in milliseconds after the epoch, when we first knew the account was unverified.
// Use this to avoid nagging the user to verify her account immediately after connecting.
let knownUnverifiedAt: Timestamp
let lastNotifiedUserAt: Timestamp
public init(knownUnverifiedAt: Timestamp, lastNotifiedUserAt: Timestamp, sessionToken: Data, keyFetchToken: Data, unwrapkB: Data) {
self.knownUnverifiedAt = knownUnverifiedAt
self.lastNotifiedUserAt = lastNotifiedUserAt
super.init(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["knownUnverifiedAt"] = JSON(NSNumber(value: knownUnverifiedAt))
d["lastNotifiedUserAt"] = JSON(NSNumber(value: lastNotifiedUserAt))
return JSON(d)
}
func withUnwrapKey(_ unwrapkB: Data) -> EngagedBeforeVerifiedState {
return EngagedBeforeVerifiedState(
knownUnverifiedAt: knownUnverifiedAt, lastNotifiedUserAt: lastNotifiedUserAt,
sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
}
open class EngagedAfterVerifiedState: ReadyForKeys {
override open var label: FxAStateLabel { return FxAStateLabel.engagedAfterVerified }
override public init(sessionToken: Data, keyFetchToken: Data, unwrapkB: Data) {
super.init(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
func withUnwrapKey(_ unwrapkB: Data) -> EngagedAfterVerifiedState {
return EngagedAfterVerifiedState(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
}
// Not an externally facing state!
open class TokenAndKeys: TokenState {
public let kSync: Data
public let kXCS: String
init(sessionToken: Data, kSync: Data, kXCS: String) {
self.kSync = kSync
self.kXCS = kXCS
super.init(sessionToken: sessionToken)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["kSync"] = JSON(kSync.hexEncodedString as NSString)
d["kXCS"] = JSON(kXCS as NSString)
return JSON(d)
}
}
open class CohabitingBeforeKeyPairState: TokenAndKeys {
override open var label: FxAStateLabel { return FxAStateLabel.cohabitingBeforeKeyPair }
}
// Not an externally facing state!
open class TokenKeysAndKeyPair: TokenAndKeys {
let keyPair: KeyPair
// Timestamp, in milliseconds after the epoch, when keyPair expires. After this time, generate a new keyPair.
let keyPairExpiresAt: Timestamp
init(sessionToken: Data, kSync: Data, kXCS: String, keyPair: KeyPair, keyPairExpiresAt: Timestamp) {
self.keyPair = keyPair
self.keyPairExpiresAt = keyPairExpiresAt
super.init(sessionToken: sessionToken, kSync: kSync, kXCS: kXCS)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["keyPair"] = JSON(keyPair.jsonRepresentation() as Any)
d["keyPairExpiresAt"] = JSON(NSNumber(value: keyPairExpiresAt))
return JSON(d)
}
func isKeyPairExpired(_ now: Timestamp) -> Bool {
return keyPairExpiresAt < now
}
}
open class CohabitingAfterKeyPairState: TokenKeysAndKeyPair {
override open var label: FxAStateLabel { return FxAStateLabel.cohabitingAfterKeyPair }
}
open class MarriedState: TokenKeysAndKeyPair {
override open var label: FxAStateLabel { return FxAStateLabel.married }
let certificate: String
let certificateExpiresAt: Timestamp
init(sessionToken: Data, kSync: Data, kXCS: String, keyPair: KeyPair, keyPairExpiresAt: Timestamp, certificate: String, certificateExpiresAt: Timestamp) {
self.certificate = certificate
self.certificateExpiresAt = certificateExpiresAt
super.init(sessionToken: sessionToken, kSync: kSync, kXCS: kXCS, keyPair: keyPair, keyPairExpiresAt: keyPairExpiresAt)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["certificate"] = JSON(certificate as NSString)
d["certificateExpiresAt"] = JSON(NSNumber(value: certificateExpiresAt))
return JSON(d)
}
func isCertificateExpired(_ now: Timestamp) -> Bool {
return certificateExpiresAt < now
}
func withoutKeyPair() -> CohabitingBeforeKeyPairState {
let newState = CohabitingBeforeKeyPairState(sessionToken: sessionToken,
kSync: kSync, kXCS: kXCS)
return newState
}
func withoutCertificate() -> CohabitingAfterKeyPairState {
let newState = CohabitingAfterKeyPairState(sessionToken: sessionToken,
kSync: kSync, kXCS: kXCS,
keyPair: keyPair, keyPairExpiresAt: keyPairExpiresAt)
return newState
}
open func generateAssertionForAudience(_ audience: String, now: Timestamp) -> String {
let assertion = JSONWebTokenUtils.createAssertionWithPrivateKeyToSign(with: keyPair.privateKey,
certificate: certificate,
audience: audience,
issuer: "127.0.0.1",
issuedAt: now,
duration: OneHourInMilliseconds)
return assertion!
}
}
open class DoghouseState: FxAState {
override open var label: FxAStateLabel { return FxAStateLabel.doghouse }
override public init() {
super.init()
}
}
| mpl-2.0 |
tomasharkema/R.swift | Sources/RswiftCore/ResourceTypes/Storyboard.swift | 1 | 9853 | //
// Storyboard.swift
// R.swift
//
// Created by Mathijs Kadijk on 09-12-15.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
private let ElementNameToTypeMapping = [
"viewController": Type._UIViewController,
"tableViewCell": Type(module: "UIKit", name: "UITableViewCell"),
"tabBarController": Type(module: "UIKit", name: "UITabBarController"),
"glkViewController": Type(module: "GLKit", name: "GLKViewController"),
"pageViewController": Type(module: "UIKit", name: "UIPageViewController"),
"tableViewController": Type(module: "UIKit", name: "UITableViewController"),
"splitViewController": Type(module: "UIKit", name: "UISplitViewController"),
"navigationController": Type(module: "UIKit", name: "UINavigationController"),
"avPlayerViewController": Type(module: "AVKit", name: "AVPlayerViewController"),
"collectionViewController": Type(module: "UIKit", name: "UICollectionViewController"),
]
struct Storyboard: WhiteListedExtensionsResourceType, ReusableContainer {
static let supportedExtensions: Set<String> = ["storyboard"]
let name: String
private let initialViewControllerIdentifier: String?
let viewControllers: [ViewController]
let viewControllerPlaceholders: [ViewControllerPlaceholder]
let usedAccessibilityIdentifiers: [String]
let usedImageIdentifiers: [String]
let usedColorResources: [String]
let reusables: [Reusable]
var initialViewController: ViewController? {
return viewControllers
.filter { $0.id == self.initialViewControllerIdentifier }
.first
}
init(url: URL) throws {
try Storyboard.throwIfUnsupportedExtension(url.pathExtension)
guard let filename = url.filename else {
throw ResourceParsingError.parsingFailed("Couldn't extract filename from URL: \(url)")
}
name = filename
guard let parser = XMLParser(contentsOf: url) else {
throw ResourceParsingError.parsingFailed("Couldn't load file at: '\(url)'")
}
let parserDelegate = StoryboardParserDelegate()
parser.delegate = parserDelegate
guard parser.parse() else {
throw ResourceParsingError.parsingFailed("Invalid XML in file at: '\(url)'")
}
initialViewControllerIdentifier = parserDelegate.initialViewControllerIdentifier
viewControllers = parserDelegate.viewControllers
viewControllerPlaceholders = parserDelegate.viewControllerPlaceholders
usedAccessibilityIdentifiers = parserDelegate.usedAccessibilityIdentifiers
usedImageIdentifiers = parserDelegate.usedImageIdentifiers
usedColorResources = parserDelegate.usedColorReferences
reusables = parserDelegate.reusables
}
struct ViewController {
let id: String
let storyboardIdentifier: String?
let type: Type
private(set) var segues: [Segue]
fileprivate mutating func add(_ segue: Segue) {
segues.append(segue)
}
}
struct ViewControllerPlaceholder {
enum ResolvedResult {
case customBundle
case resolved(ViewController?)
}
let id: String
let storyboardName: String?
let referencedIdentifier: String?
let bundleIdentifier: String?
func resolveWithStoryboards(_ storyboards: [Storyboard]) -> ResolvedResult {
if nil != bundleIdentifier {
// Can't resolve storyboard in other bundles
return .customBundle
}
guard let storyboardName = storyboardName else {
// Storyboard reference without a storyboard defined?!
return .resolved(nil)
}
let storyboard = storyboards
.filter { $0.name == storyboardName }
guard let referencedIdentifier = referencedIdentifier else {
return .resolved(storyboard.first?.initialViewController)
}
return .resolved(storyboard
.flatMap {
$0.viewControllers.filter { $0.storyboardIdentifier == referencedIdentifier }
}
.first)
}
}
struct Segue {
let identifier: String
let type: Type
let destination: String
let kind: String
}
}
private class StoryboardParserDelegate: NSObject, XMLParserDelegate {
var initialViewControllerIdentifier: String?
var viewControllers: [Storyboard.ViewController] = []
var viewControllerPlaceholders: [Storyboard.ViewControllerPlaceholder] = []
var usedImageIdentifiers: [String] = []
var usedColorReferences: [String] = []
var usedAccessibilityIdentifiers: [String] = []
var reusables: [Reusable] = []
// State
var currentViewController: Storyboard.ViewController?
@objc func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
switch elementName {
case "document":
if let initialViewController = attributeDict["initialViewController"] {
initialViewControllerIdentifier = initialViewController
}
case "segue":
let customModuleProvider = attributeDict["customModuleProvider"]
let customModule = (customModuleProvider == "target") ? nil : attributeDict["customModule"]
let customClass = attributeDict["customClass"]
let customType = customClass
.map { SwiftIdentifier(name: $0, lowercaseStartingCharacters: false) }
.map { Type(module: Module(name: customModule), name: $0, optional: false) }
if let customType = customType , attributeDict["kind"] != "custom" , attributeDict["kind"] != "unwind" {
warn("Set the segue of class \(customType) with identifier '\(attributeDict["identifier"] ?? "-no identifier-")' to type custom, using segue subclasses with other types can cause crashes on iOS 8 and lower.")
}
if let segueIdentifier = attributeDict["identifier"],
let destination = attributeDict["destination"],
let kind = attributeDict["kind"]
{
let type = customType ?? Type._UIStoryboardSegue
let segue = Storyboard.Segue(identifier: segueIdentifier, type: type, destination: destination, kind: kind)
currentViewController?.add(segue)
}
case "image":
if let imageIdentifier = attributeDict["name"] {
usedImageIdentifiers.append(imageIdentifier)
}
case "color":
if let colorName = attributeDict["name"] {
usedColorReferences.append(colorName)
}
case "accessibility":
if let accessibilityIdentifier = attributeDict["identifier"] {
usedAccessibilityIdentifiers.append(accessibilityIdentifier)
}
case "userDefinedRuntimeAttribute":
if let accessibilityIdentifier = attributeDict["value"], "accessibilityIdentifier" == attributeDict["keyPath"] && "string" == attributeDict["type"] {
usedAccessibilityIdentifiers.append(accessibilityIdentifier)
}
case "viewControllerPlaceholder":
if let id = attributeDict["id"] , attributeDict["sceneMemberID"] == "viewController" {
let placeholder = Storyboard.ViewControllerPlaceholder(
id: id,
storyboardName: attributeDict["storyboardName"],
referencedIdentifier: attributeDict["referencedIdentifier"],
bundleIdentifier: attributeDict["bundleIdentifier"]
)
viewControllerPlaceholders.append(placeholder)
}
default:
if let viewController = viewControllerFromAttributes(attributeDict, elementName: elementName) {
currentViewController = viewController
}
if let reusable = reusableFromAttributes(attributeDict, elementName: elementName) {
reusables.append(reusable)
}
}
}
@objc func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
// We keep the current view controller open to collect segues until the closing scene:
// <scene>
// <viewController>
// ...
// <segue />
// </viewController>
// <segue />
// </scene>
if elementName == "scene" {
if let currentViewController = currentViewController {
viewControllers.append(currentViewController)
self.currentViewController = nil
}
}
}
func viewControllerFromAttributes(_ attributeDict: [String : String], elementName: String) -> Storyboard.ViewController? {
guard let id = attributeDict["id"] , attributeDict["sceneMemberID"] == "viewController" else {
return nil
}
let storyboardIdentifier = attributeDict["storyboardIdentifier"]
let customModuleProvider = attributeDict["customModuleProvider"]
let customModule = (customModuleProvider == "target") ? nil : attributeDict["customModule"]
let customClass = attributeDict["customClass"]
let customType = customClass
.map { SwiftIdentifier(name: $0, lowercaseStartingCharacters: false) }
.map { Type(module: Module(name: customModule), name: $0, optional: false) }
let type = customType ?? ElementNameToTypeMapping[elementName] ?? Type._UIViewController
return Storyboard.ViewController(id: id, storyboardIdentifier: storyboardIdentifier, type: type, segues: [])
}
func reusableFromAttributes(_ attributeDict: [String : String], elementName: String) -> Reusable? {
guard let reuseIdentifier = attributeDict["reuseIdentifier"] , reuseIdentifier != "" else {
return nil
}
let customModuleProvider = attributeDict["customModuleProvider"]
let customModule = (customModuleProvider == "target") ? nil : attributeDict["customModule"]
let customClass = attributeDict["customClass"]
let customType = customClass
.map { SwiftIdentifier(name: $0, lowercaseStartingCharacters: false) }
.map { Type(module: Module(name: customModule), name: $0, optional: false) }
let type = customType ?? ElementNameToTypeMapping[elementName] ?? Type._UIView
return Reusable(identifier: reuseIdentifier, type: type)
}
}
| mit |
samburnstone/SwiftStudyGroup | Swift Language Guide Playgrounds/SwiftQuickstart.playground/Sources/SupportCode.swift | 1 | 203 | //
// This file (and all other Swift source files in the Sources directory of this playground) will be precompiled into a framework which is automatically made available to SwftQuickstart.playground.
//
| mit |
Zewo/Data | Package.swift | 1 | 1424 | // Package.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import PackageDescription
let package = Package(
name: "Data",
dependencies: [
.Package(url: "https://github.com/Zewo/POSIX.git", majorVersion: 0, minor: 4),
.Package(url: "https://github.com/open-swift/C7.git", majorVersion: 0, minor: 4),
]
)
| mit |
ps2/rileylink_ios | MinimedKitTests/Messages/FindDeviceMessageBodyTests.swift | 1 | 932 | //
// FindDeviceMessageBodyTests.swift
// RileyLink
//
// Created by Pete Schwamb on 3/7/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import XCTest
@testable import MinimedKit
class FindDeviceMessageBodyTests: XCTestCase {
func testValidFindDeviceMessage() {
let message = PumpMessage(rxData: Data(hexadecimalString: "a235053509cf99999900")!)
if let message = message {
XCTAssertTrue(message.messageBody is FindDeviceMessageBody)
} else {
XCTFail("\(String(describing: message)) is nil")
}
}
func testMidnightSensor() {
let message = PumpMessage(rxData: Data(hexadecimalString: "a235053509cf99999900")!)!
let body = message.messageBody as! FindDeviceMessageBody
XCTAssertEqual(body.sequence, 79)
XCTAssertEqual(body.deviceAddress.hexadecimalString, "999999")
}
}
| mit |
rymcol/Linux-Server-Side-Swift-Benchmarking | KituraPress/Sources/IndexHandler.swift | 1 | 1701 | #if os(Linux)
import Glibc
#else
import Darwin
#endif
struct IndexHandler {
func generateContent() -> String {
var post = "No matching post was found"
var finalContent = "<section id=\"content\"><div class=\"container\"><div class=\"row\"><div class=\"banner center-block\"><div><img src=\"/img/banner@2x.png\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-1.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-2.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-3.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-4.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-5.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div></div></div><div class=\"row\"><div class=\"col-xs-12\"><h1>"
let randomContent = ContentGenerator().generate()
if let firstPost = randomContent["Test Post 1"] {
post = firstPost as! String
}
let imageNumber = Int(arc4random_uniform(25) + 1)
finalContent += "Test Post 1"
finalContent += "</h1><img src=\""
finalContent += "/img/random/random-\(imageNumber).jpg\" alt=\"Random Image \(imageNumber)\" class=\"alignleft feature-image img-responsive\" />"
finalContent += "<div class=\"content\">\(post)</div>"
finalContent += "</div></div</div></section>"
return finalContent
}
}
| apache-2.0 |
utahiosmac/jobs | Sources/JobContext.swift | 2 | 653 | //
// JobContext.swift
// Jobs
//
import Foundation
public struct JobContext: Observable {
private let state: JobState
internal init(state: JobState) {
self.state = state
}
public var isCancelled: Bool { return state.isCancelled }
public func add(observer: Observer) {
state.add(observer: observer)
}
public func cancel(error: NSError? = nil) {
state.cancel(error: error)
}
public func finish(errors: [NSError] = []) {
state.finish(errors: errors)
}
public func produce(job: JobType) -> Ticket {
return state.produce(job: job)
}
}
| mit |
davidcairns/IntroToXcodeGA | DCDrawingStore.swift | 1 | 1187 | //
// DCDrawingStore.swift
// Drawr
//
// Created by David Cairns on 5/17/15.
// Copyright (c) 2015 David Cairns. All rights reserved.
//
import UIKit
public class DCDrawingStore {
static let sharedInstance = DCDrawingStore()
var images: [UIImage]
private let kCachedImagesKey = "kCachedImagesKey"
init() {
images = []
if let storedImageDataArray = (NSUserDefaults.standardUserDefaults().arrayForKey(kCachedImagesKey) as? [NSData]) {
for storedImageData in storedImageDataArray {
if let decodedImage = UIImage(data: storedImageData) {
images.append(decodedImage)
}
}
}
}
func saveAllImagesToUserDefaults() {
var imageDataArray: [NSData] = []
for image in images {
let imageData = UIImagePNGRepresentation(image)!
imageDataArray.append(imageData)
}
NSUserDefaults.standardUserDefaults().setObject(imageDataArray, forKey: kCachedImagesKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
func saveImage(image: UIImage) {
// Save to our app's settings.
images.append(image)
saveAllImagesToUserDefaults()
// Also save this image to the photos album.
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
| mit |
tutsplus/iOSFromScratch-AutoLayoutBasics | Auto Layout/ViewController.swift | 1 | 510 | //
// ViewController.swift
// Auto Layout
//
// Created by Bart Jacobs on 16/12/15.
// Copyright © 2015 Envato Tuts+. 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.
}
}
| bsd-2-clause |
grahamgilbert/munki-dnd | MSC DND/AppDelegate.swift | 1 | 1732 | //
// AppDelegate.swift
// MSC DND
//
// Created by Graham Gilbert on 05/07/2015.
// Copyright (c) 2015 Graham Gilbert. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-2)
let popover = NSPopover()
var eventMonitor: EventMonitor?
func applicationDidFinishLaunching(notification: NSNotification) {
if let button = statusItem.button {
button.image = NSImage(named: "hibernate")
button.action = Selector("togglePopover:")
}
popover.contentViewController = DNDViewController(nibName: "DNDViewController", bundle: nil)
eventMonitor = EventMonitor(mask: .LeftMouseDownMask | .RightMouseDownMask) { [unowned self] event in
if self.popover.shown {
self.closePopover(event)
}
}
eventMonitor?.start()
showPopover(nil)
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func showPopover(sender: AnyObject?) {
if let button = statusItem.button {
popover.showRelativeToRect(button.bounds, ofView: button, preferredEdge: NSMinYEdge)
eventMonitor?.start()
}
}
func closePopover(sender: AnyObject?) {
popover.performClose(sender)
eventMonitor?.stop()
}
func togglePopover(sender: AnyObject?) {
if popover.shown {
closePopover(sender)
} else {
showPopover(sender)
}
}
}
| apache-2.0 |
CaueAlvesSilva/DropDownAlert | DropDownAlert/DropDownAlert/ExampleViewController/ExampleViewController.swift | 1 | 3893 | //
// ExampleViewController.swift
// DropDownAlert
//
// Created by Cauê Silva on 06/06/17.
// Copyright © 2017 Caue Alves. All rights reserved.
//
import Foundation
import UIKit
// MARK: Enum for button pressed
enum ButtonPressed: Int {
case success
case custom
case fail
}
class ExampleViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet var showDropDownAlertButtons: [UIButton]!
// MARK: VC life cycle
override func viewDidLoad() {
super.viewDidLoad()
setupButtons()
setupTextField()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
showDropDownAlert(message: "Hello message", success: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
DropDownAlertPresenter.dismiss()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
// MARK: Components setup
private func setupButtons() {
let buttonAttributes: [(title: String, color: UIColor)] = [("Success", UIColor.successDropDownAlertColor()),
("Custom", UIColor(red: 239/255, green: 91/255, blue: 48/255, alpha: 1.0)),
("Fail", UIColor.failDropDownAlertColor())]
for (index, button) in showDropDownAlertButtons.enumerated() {
button.layer.cornerRadius = 4
button.setTitle(buttonAttributes[index].title, for: .normal)
button.setTitle(buttonAttributes[index].title, for: .highlighted)
button.setTitleColor(.white, for: .normal)
button.setTitleColor(.white, for: .highlighted)
button.backgroundColor = buttonAttributes[index].color
button.tag = index
}
}
private func setupTextField() {
messageTextField.placeholder = "Enter a custom message for alert"
messageTextField.clearButtonMode = .whileEditing
}
// MARK: Action
@IBAction func showDropDownAlertButtonPressed(_ sender: UIButton) {
guard let buttonPressed = ButtonPressed(rawValue: sender.tag), let inputedMessage = messageTextField.text else {
return
}
let message = inputedMessage.isEmpty ? "Input a message\nnext time" : inputedMessage
switch buttonPressed {
case .success:
DropDownAlertPresenter.show(with: DefaultDropDownAlertLayout(message: message, success: true))
case .custom:
DropDownAlertPresenter.show(with: ExampleCustomAlertLayout(message: message))
case .fail:
DropDownAlertPresenter.show(with: DefaultDropDownAlertLayout(message: message, success: false))
}
}
}
// MARK: Custom alert layout example
struct ExampleCustomAlertLayout: DropDownAlertLayout {
private var message = ""
init(message: String) {
self.message = message
}
var layoutDTO: DropDownAlertViewDTO {
return DropDownAlertViewDTO(image: UIImage(named: "customDropDownAlertIcon") ?? UIImage(),
message: message,
messageColor: .white,
backgroundColor: UIColor(red: 239/255, green: 91/255, blue: 48/255, alpha: 1.0),
visibleTime: 5)
}
}
// MARK: Show DropDownAlet using an extension
extension UIViewController {
func showDropDownAlert(message: String, success: Bool) {
DropDownAlertPresenter.show(with: DefaultDropDownAlertLayout(message: message, success: success))
}
}
| mit |
SwiftGen/SwiftGen | Sources/SwiftGenCLI/Config/Config+Example.swift | 1 | 4023 | //
// SwiftGen
// Copyright © 2022 SwiftGen
// MIT Licence
//
extension Config {
public static func example(versionForDocLink: String, commentAllLines: Bool = true) -> String {
var content = exampleYAMLContent(version: versionForDocLink)
if commentAllLines {
// Comment all lines, except empty lines.
// - If a line is already a comment (starts with "#"), prefix with additional "#" to make it "## Blah"
// - Otherwise, if the line is just supposed to be actual YAML content, prefix it with "# "
content = content
.split(separator: "\n", omittingEmptySubsequences: false)
.map { $0.isEmpty ? "" : $0.hasPrefix("#") ? "#\($0)" : "# \($0)" }
.joined(separator: "\n")
}
return content
}
// swiftlint:disable line_length function_body_length
private static func exampleYAMLContent(version: String) -> String {
"""
# Note: all of the config entries below are just examples with placeholders. Be sure to edit and adjust to your needs when uncommenting.
# In case your config entries all use a common input/output parent directory, you can specify those here.
# Every input/output paths in the rest of the config will then be expressed relative to these.
# Those two top-level keys are optional and default to "." (the directory of the config file).
input_dir: MyLib/Sources/
output_dir: MyLib/Generated/
# Generate constants for your localized strings.
# Be sure that SwiftGen only parses ONE locale (typically Base.lproj, or en.lproj, or whichever your development region is); otherwise it will generate the same keys multiple times.
# SwiftGen will parse all `.strings` files found in that folder.
strings:
inputs:
- Resources/Base.lproj
outputs:
- templateName: structured-swift5
output: Strings+Generated.swift
# Generate constants for your Assets Catalogs, including constants for images, colors, ARKit resources, etc.
# This example also shows how to provide additional parameters to your template to customize the output.
# - Especially the `forceProvidesNamespaces: true` param forces to create sub-namespace for each folder/group used in your Asset Catalogs, even the ones without "Provides Namespace". Without this param, SwiftGen only generates sub-namespaces for folders/groups which have the "Provides Namespace" box checked in the Inspector pane.
# - To know which params are supported for a template, use `swiftgen template doc xcassets swift5` to open the template documentation on GitHub.
xcassets:
inputs:
- Main.xcassets
- ProFeatures.xcassets
outputs:
- templateName: swift5
params:
forceProvidesNamespaces: true
output: XCAssets+Generated.swift
# Generate constants for your storyboards and XIBs.
# This one generates 2 output files, one containing the storyboard scenes, and another for the segues.
# (You can remove the segues entry if you don't use segues in your IB files).
# For `inputs` we can use "." here (aka "current directory", at least relative to `input_dir` = "MyLib/Sources"),
# and SwiftGen will recursively find all `*.storyboard` and `*.xib` files in there.
ib:
inputs:
- .
outputs:
- templateName: scenes-swift5
output: IB-Scenes+Generated.swift
- templateName: segues-swift5
output: IB-Segues+Generated.swift
# There are other parsers available for you to use depending on your needs, for example:
# - `fonts` (if you have custom ttf/ttc font files)
# - `coredata` (for CoreData models)
# - `json`, `yaml` and `plist` (to parse custom JSON/YAML/Plist files and generate code from their content)
# …
#
# For more info, use `swiftgen config doc` to open the full documentation on GitHub.
# \(gitHubDocURL(version: version))
"""
}
// swiftlint:enable line_length function_body_length
}
| mit |
mfitzpatrick79/BidHub-iOS | AuctionApp/CategoryVC/CategoryViewController.swift | 1 | 3608 | //
// CategoryViewController.swift
// AuctionApp
//
// Created by Michael Fitzpatrick on 5/28/17.
// Copyright © 2017 fitz.guru. All rights reserved.
//
import Foundation
import UIKit
protocol CategoryViewControllerDelegate {
func categoryViewControllerDidFilter(_ viewController: CategoryViewController, onCategory: String)
func categoryViewControllerDidCancel(_ viewController: CategoryViewController)
}
class CategoryViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet var darkView: UIView!
@IBOutlet var categoryPicker: UIPickerView!
@IBOutlet var toolbar: UIToolbar!
@IBOutlet var cancelButton: UIBarButtonItem!
@IBOutlet var doneButton: UIBarButtonItem!
var delegate: CategoryViewControllerDelegate?
var categoryNames = ["Art - All", "Art - Paintings", "Art - Photography", "Art - Prints, Drawings, & Other", "Experiences - All", "Experiences - Fashion", "Experiences - Sports", "Experiences - Travel"]
var categoryValues = ["art", "painting", "photo", "pdo", "other", "fashion", "sport", "travel"]
/// UIPickerViewDataSource Methods
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return categoryNames.count;
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return categoryNames[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
return
}
override func viewDidLoad() {
super.viewDidLoad()
categoryPicker.delegate = self
categoryPicker.dataSource = self
animateIn()
}
@IBAction func didTapBackground(_ sender: AnyObject) {
animateOut()
}
@IBAction func didPressCancel(_ sender: AnyObject) {
animateOut()
}
@IBAction func didPressDone(_ sender: AnyObject) {
let category = categoryValues[categoryPicker.selectedRow(inComponent: 0)] as String
if self.delegate != nil {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.darkView.alpha = 0
}, completion: { (finished: Bool) -> Void in
self.delegate!.categoryViewControllerDidFilter(self, onCategory: category)
})
}
}
func didSelectCategory(_ category: String) {
if self.delegate != nil {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.darkView.alpha = 0
}, completion: { (finished: Bool) -> Void in
self.delegate!.categoryViewControllerDidFilter(self, onCategory: category)
})
}
}
func animateIn(){
UIView.animate(
withDuration: 0.5,
delay: 0.0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.0,
options: UIViewAnimationOptions.curveLinear,
animations: {
self.darkView.alpha = 1.0
},
completion: { (fininshed: Bool) -> () in })
}
func animateOut(){
if delegate != nil {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.darkView.alpha = 0
}, completion: { (finished: Bool) -> Void in
self.delegate!.categoryViewControllerDidCancel(self)
})
}
}
}
| apache-2.0 |
roambotics/swift | validation-test/compiler_crashers_fixed/01476-swift-lexer-getlocforendoftoken.swift | 65 | 690 | // 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
// RUN: not %target-swift-frontend %s -typecheck
func g<T where B {
print(T>] = D>] = {
func a(A.e: b["
protocol d {
default:Any) -> T>(()
typealias e : X.b: AnyObject)(e())
}
extension NSSet {
}
class A : T) {
class A<T, AnyObject, U) -> {
func a(range: A {
enum S<Y> {
}
}
}
return b: T.endIndex - range.E == b> {
}
}
class A : b
class b:
| apache-2.0 |
TrustWallet/trust-wallet-ios | Trust/Transfer/Types/DAppRequster.swift | 1 | 140 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
struct DAppRequester {
let title: String?
let url: URL?
}
| gpl-3.0 |
jdkelley/Udacity-OnTheMap-ExampleApps | TheMovieManager-v2/TheMovieManager/BorderedButton.swift | 2 | 2649 | //
// BorderedButton.swift
// MyFavoriteMovies
//
// Created by Jarrod Parkes on 1/23/15.
// Copyright (c) 2015 Udacity. All rights reserved.
//
import UIKit
// MARK: - BorderedButton: Button
class BorderedButton: UIButton {
// MARK: Properties
// constants for styling and configuration
let darkerBlue = UIColor(red: 0.0, green: 0.298, blue: 0.686, alpha:1.0)
let lighterBlue = UIColor(red: 0.0, green:0.502, blue:0.839, alpha: 1.0)
let titleLabelFontSize: CGFloat = 17.0
let borderedButtonHeight: CGFloat = 44.0
let borderedButtonCornerRadius: CGFloat = 4.0
let phoneBorderedButtonExtraPadding: CGFloat = 14.0
var backingColor: UIColor? = nil
var highlightedBackingColor: UIColor? = nil
// MARK: Initialization
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
themeBorderedButton()
}
override init(frame: CGRect) {
super.init(frame: frame)
themeBorderedButton()
}
private func themeBorderedButton() {
layer.masksToBounds = true
layer.cornerRadius = borderedButtonCornerRadius
highlightedBackingColor = darkerBlue
backingColor = lighterBlue
backgroundColor = lighterBlue
setTitleColor(UIColor.whiteColor(), forState: .Normal)
titleLabel?.font = UIFont.systemFontOfSize(titleLabelFontSize)
}
// MARK: Setters
private func setBackingColor(newBackingColor: UIColor) {
if let _ = backingColor {
backingColor = newBackingColor
backgroundColor = newBackingColor
}
}
private func setHighlightedBackingColor(newHighlightedBackingColor: UIColor) {
highlightedBackingColor = newHighlightedBackingColor
backingColor = highlightedBackingColor
}
// MARK: Tracking
override func beginTrackingWithTouch(touch: UITouch, withEvent: UIEvent?) -> Bool {
backgroundColor = highlightedBackingColor
return true
}
override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) {
backgroundColor = backingColor
}
override func cancelTrackingWithEvent(event: UIEvent?) {
backgroundColor = backingColor
}
// MARK: Layout
override func sizeThatFits(size: CGSize) -> CGSize {
let extraButtonPadding : CGFloat = phoneBorderedButtonExtraPadding
var sizeThatFits = CGSizeZero
sizeThatFits.width = super.sizeThatFits(size).width + extraButtonPadding
sizeThatFits.height = borderedButtonHeight
return sizeThatFits
}
} | mit |
toohotz/Alamofire | Tests/TLSEvaluationTests.swift | 69 | 16725 | // TLSEvaluationTests.swift
//
// Copyright (c) 2014–2015 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 Alamofire
import Foundation
import XCTest
private struct TestCertificates {
static let RootCA = TestCertificates.certificateWithFileName("root-ca-disig")
static let IntermediateCA = TestCertificates.certificateWithFileName("intermediate-ca-disig")
static let Leaf = TestCertificates.certificateWithFileName("testssl-expire.disig.sk")
static func certificateWithFileName(fileName: String) -> SecCertificate {
class Bundle {}
let filePath = NSBundle(forClass: Bundle.self).pathForResource(fileName, ofType: "cer")!
let data = NSData(contentsOfFile: filePath)!
let certificate = SecCertificateCreateWithData(nil, data).takeRetainedValue()
return certificate
}
}
// MARK: -
private struct TestPublicKeys {
static let RootCA = TestPublicKeys.publicKeyForCertificate(TestCertificates.RootCA)
static let IntermediateCA = TestPublicKeys.publicKeyForCertificate(TestCertificates.IntermediateCA)
static let Leaf = TestPublicKeys.publicKeyForCertificate(TestCertificates.Leaf)
static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey {
let policy = SecPolicyCreateBasicX509().takeRetainedValue()
var unmanagedTrust: Unmanaged<SecTrust>?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &unmanagedTrust)
let trust = unmanagedTrust!.takeRetainedValue()
let publicKey = SecTrustCopyPublicKey(trust).takeRetainedValue()
return publicKey
}
}
// MARK: -
class TLSEvaluationExpiredLeafCertificateTestCase: BaseTestCase {
let URL = "https://testssl-expire.disig.sk/"
let host = "testssl-expire.disig.sk"
var configuration: NSURLSessionConfiguration!
// MARK: Setup and Teardown
override func setUp() {
super.setUp()
configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
}
// MARK: Default Behavior Tests
func testThatExpiredCertificateRequestFailsWithNoServerTrustPolicy() {
// Given
let expectation = expectationWithDescription("\(URL)")
let manager = Manager(configuration: configuration)
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorServerCertificateUntrusted, "error should be NSURLErrorServerCertificateUntrusted")
}
// MARK: Server Trust Policy - Perform Default Tests
func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() {
// Given
let policies = [host: ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
// MARK: Server Trust Policy - Certificate Pinning Tests
func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() {
// Given
let certificates = [TestCertificates.Leaf]
let policies: [String: ServerTrustPolicy] = [
host: .PinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() {
// Given
let certificates = [TestCertificates.Leaf, TestCertificates.IntermediateCA, TestCertificates.RootCA]
let policies: [String: ServerTrustPolicy] = [
host: .PinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() {
// Given
let certificates = [TestCertificates.Leaf]
let policies: [String: ServerTrustPolicy] = [
host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() {
// Given
let certificates = [TestCertificates.IntermediateCA]
let policies: [String: ServerTrustPolicy] = [
host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() {
// Given
let certificates = [TestCertificates.RootCA]
let policies: [String: ServerTrustPolicy] = [
host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
// MARK: Server Trust Policy - Public Key Pinning Tests
func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.Leaf]
let policies: [String: ServerTrustPolicy] = [
host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: true, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.Leaf]
let policies: [String: ServerTrustPolicy] = [
host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.IntermediateCA]
let policies: [String: ServerTrustPolicy] = [
host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.RootCA]
let policies: [String: ServerTrustPolicy] = [
host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
// MARK: Server Trust Policy - Disabling Evaluation Tests
func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() {
// Given
let policies = [host: ServerTrustPolicy.DisableEvaluation]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
// MARK: Server Trust Policy - Custom Evaluation Tests
func testThatExpiredCertificateRequestSucceedsWhenCustomEvaluationReturnsTrue() {
// Given
let policies = [
host: ServerTrustPolicy.CustomEvaluation { _, _ in
// Implement a custom evaluation routine here...
return true
}
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestFailsWhenCustomEvaluationReturnsFalse() {
// Given
let policies = [
host: ServerTrustPolicy.CustomEvaluation { _, _ in
// Implement a custom evaluation routine here...
return false
}
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
}
| mit |
SergeyVorontsov/SimpleNewsApp | SimpleNewsApp/DataProvider/NewsCache.swift | 1 | 6168 | //
// NewsCache.swift
// Simple News
//
// Created by Sergey Vorontsov
// Copyright (c) 2015 Sergey. All rights reserved.
//
import Foundation
private let NewsListKey = "NewsListKey"
private let NewsTextKey = "NewsTextKey"
private let LikesKey = "LikesKey"
private let PendingLikesKey = "PendingLikesKey"
/**
* Storage news using NSUserDefaults
*/
class NewsCache : NewsInternalStorage {
//MARK: News
/**
Save the news list
*/
func saveNewsList(newsList:[News]) {
let defaults = NSUserDefaults.standardUserDefaults()
let objectsData = NSKeyedArchiver.archivedDataWithRootObject(newsList)
defaults.setObject(objectsData, forKey: NewsListKey)
defaults.synchronize()
}
/**
Restoring the news list
*/
func restoreNewsList() -> [News]?{
let defaults = NSUserDefaults.standardUserDefaults()
if let objectsData = defaults.dataForKey(NewsListKey) {
let news = NSKeyedUnarchiver.unarchiveObjectWithData(objectsData) as? [News]
return news
}
//failed to recover news
return nil
}
/**
Save text news
*/
func saveNewsText(newsId:String, text:String){
let defaults = NSUserDefaults.standardUserDefaults()
//getting saved dict
var textNewsDict:[String:String] = [:]
if let objectsData:NSData = defaults.dataForKey(NewsTextKey) {
textNewsDict = (NSKeyedUnarchiver.unarchiveObjectWithData(objectsData) as? [String:String]) ?? [String:String]()
}
textNewsDict[newsId] = text
//save
let objectsData = NSKeyedArchiver.archivedDataWithRootObject(textNewsDict)
defaults.setObject(objectsData, forKey: NewsTextKey)
defaults.synchronize()
}
/**
Restore text news
*/
func restoreNewsText(newsId:String) -> String? {
let defaults = NSUserDefaults.standardUserDefaults()
if let objectsData:NSData = defaults.dataForKey(NewsTextKey) {
let textNewsDict = NSKeyedUnarchiver.unarchiveObjectWithData(objectsData) as! [String:String]
return textNewsDict[newsId]
}
//не удалось восстановить текст новости
return nil
}
//MARK: Likes
/**
Set like/unlike for news
*/
func saveMyLike(newsId:String, like:Bool) {
var likes = self.restoreLikesDict()
if like {
likes[newsId] = true
} else {
likes.removeValueForKey(newsId)
}
self.saveLikesDict(likes)
}
/**
Returns True if the news we liked
*/
func isLikedNews(newsId:String) -> Bool {
let likes = self.restoreLikesDict()
//if there is an element, then liked
if let likedFlag = likes[newsId]{
return true
}
return false
}
//MARK: PendingLikes
/**
Save pending like
:returns: true if pending like stored
*/
func savePendingLike(newsId:String, like:Bool) -> Bool {
var pendingLikesDict = self.restorePendingLikes()
var storedLikeValue = pendingLikesDict[newsId]
if storedLikeValue == nil {
//add this like as pending
pendingLikesDict[newsId] = like
} else {
//remove pending like
if storedLikeValue != like {
pendingLikesDict.removeValueForKey(newsId)
}else{
println("Warning! Unbalanced PendingLike add/remove")
}
}
return self.savePendingLikesDict(pendingLikesDict)
}
/**
Delete penfing like
:returns: true if like deleted
*/
func deletePendingLike(newsId:String) -> Bool {
var likesDict = self.restorePendingLikes()
if likesDict[newsId] != nil {
likesDict.removeValueForKey(newsId)
return self.savePendingLikesDict(likesDict)
}
return false
}
/**
Restore pending likes dictionary
key - news id, value - is liked (Bool)
:returns: pending likes dictionary
*/
func restorePendingLikes() -> [String:Bool]{
let defaults = NSUserDefaults.standardUserDefaults()
if let objectsData:NSData = defaults.dataForKey(PendingLikesKey),
let likesDict = NSKeyedUnarchiver.unarchiveObjectWithData(objectsData) as? [String:Bool] {
return likesDict
}else{
return [String:Bool]()
}
}
}
//MARK: Private
private extension NewsCache {
/**
Save likes
:param: likes [String:Bool] (news id : liked)
*/
private func saveLikesDict(likes:[String:Bool]) -> Void {
let defaults = NSUserDefaults.standardUserDefaults()
let objectsData = NSKeyedArchiver.archivedDataWithRootObject(likes)
defaults.setObject(objectsData, forKey: LikesKey)
defaults.synchronize()
}
/**
Restore likes
:returns: [String:Bool] (news id : liked)
*/
private func restoreLikesDict() -> [String:Bool] {
let defaults = NSUserDefaults.standardUserDefaults()
if let objectsData:NSData = defaults.dataForKey(LikesKey) {
let likesDict = NSKeyedUnarchiver.unarchiveObjectWithData(objectsData) as? [String:Bool]
return likesDict!
}
return [String:Bool]()
}
/**
Save pending likes dictionary
:param: pendingLikes pending likes dictionary. key - news id, value - is liked (Bool)
:returns: true if saved
*/
private func savePendingLikesDict(pendingLikes:[String:Bool]) -> Bool {
let defaults = NSUserDefaults.standardUserDefaults()
//save
let objectsData = NSKeyedArchiver.archivedDataWithRootObject(pendingLikes)
defaults.setObject(objectsData, forKey: PendingLikesKey)
return defaults.synchronize()
}
}
| mit |
easyui/SwiftMan | SwiftMan/Extension/Foundation/NSObject/NSObject+Man.swift | 1 | 392 | //
// NSObject+Man.swift
// SwiftMan
//
// Created by yangjun on 16/5/4.
// Copyright © 2016年 yangjun. All rights reserved.
//
import Foundation
extension NSObject {
/// 类名
public var m_className: String {
return type(of: self).m_className
}
/// 类名
public static var m_className: String {
return String(describing: self)
}
}
| mit |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/QuestMediaContent.swift | 1 | 934 | //
// QuestMediaContent.swift
// AwesomeCore
//
// Created by Leonardo Vinicius Kaminski Ferreira on 15/05/19.
//
import Foundation
public struct QuestMediaContent: Codable {
public let contentAsset: QuestAsset?
public let coverAsset: QuestAsset?
public let position: Int?
public let title: String?
public let type: String?
}
// MARK: - Equatable
extension QuestMediaContent: Equatable {
public static func ==(lhs: QuestMediaContent, rhs: QuestMediaContent) -> Bool {
if lhs.contentAsset != rhs.contentAsset {
return false
}
if lhs.coverAsset != rhs.coverAsset {
return false
}
if lhs.position != rhs.position {
return false
}
if lhs.title != rhs.title {
return false
}
if lhs.type != rhs.type {
return false
}
return true
}
}
| mit |
huonw/swift | test/Serialization/noinline.swift | 4 | 1446 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_noinline.swift
// RUN: llvm-bcanalyzer %t/def_noinline.swiftmodule | %FileCheck %s
// RUN: %target-swift-frontend -emit-sib -I %t %s -o %t/noinline.sib
// RUN: %target-sil-opt -performance-linker %t/noinline.sib -I %t | %FileCheck %s -check-prefix=SIL
// CHECK-NOT: UnknownCode
import def_noinline
// SIL-LABEL: sil public_external [serialized] [noinline] [canonical] @$S12def_noinline18NoInlineInitStructV1xACSb_tcfC : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct {
// SIL-LABEL: sil public_external [serialized] [noinline] [canonical] @$S12def_noinline12testNoinline1xS2b_tF : $@convention(thin) (Bool) -> Bool {
// SIL-LABEL: sil @main
// SIL: [[RAW:%.+]] = global_addr @$S8noinline3rawSbvp : $*Bool
// SIL: [[FUNC:%.+]] = function_ref @$S12def_noinline12testNoinline1xS2b_tF : $@convention(thin) (Bool) -> Bool
// SIL: [[RESULT:%.+]] = apply [[FUNC]]({{%.+}}) : $@convention(thin) (Bool) -> Bool
// SIL: store [[RESULT]] to [[RAW]] : $*Bool
var raw = testNoinline(x: false)
// SIL: [[FUNC2:%.+]] = function_ref @$S12def_noinline18NoInlineInitStructV1xACSb_tcfC : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct
// SIL: apply [[FUNC2]]({{%.+}}, {{%.+}}) : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct
var a = NoInlineInitStruct(x: false)
| apache-2.0 |
huonw/swift | test/expr/edge-contraction/paren-expr.swift | 66 | 116 | // RUN: %target-typecheck-verify-swift
let x = [1,2,3]
func fun() -> Float {
return 1 + (x.count == 1 ? 0 : 21)
}
| apache-2.0 |
tgu/HAP | Sources/HAP/Endpoints/pairSetup().swift | 1 | 4573 | import Cryptor
import func Evergreen.getLogger
import Foundation
import SRP
fileprivate let logger = getLogger("hap.pairSetup")
fileprivate typealias Session = PairSetupController.Session
fileprivate let SESSION_KEY = "hap.pair-setup.session"
fileprivate enum Error: Swift.Error {
case noSession
}
// swiftlint:disable:next cyclomatic_complexity
func pairSetup(device: Device) -> Application {
let group = Group.N3072
let algorithm = Digest.Algorithm.sha512
let username = "Pair-Setup"
let (salt, verificationKey) = createSaltedVerificationKey(username: username,
password: device.setupCode,
group: group,
algorithm: algorithm)
let controller = PairSetupController(device: device)
func createSession() -> Session {
return Session(server: SRP.Server(username: username,
salt: salt,
verificationKey: verificationKey,
group: group,
algorithm: algorithm))
}
func getSession(_ connection: Server.Connection) throws -> Session {
guard let session = connection.context[SESSION_KEY] as? Session else {
throw Error.noSession
}
return session
}
return { connection, request in
var body = Data()
guard
(try? request.readAllData(into: &body)) != nil,
let data: PairTagTLV8 = try? decode(body),
let sequence = data[.state]?.first.flatMap({ PairSetupStep(rawValue: $0) })
else {
return .badRequest
}
let response: PairTagTLV8?
do {
switch sequence {
// M1: iOS Device -> Accessory -- `SRP Start Request'
case .startRequest:
let session = createSession()
response = try controller.startRequest(data, session)
connection.context[SESSION_KEY] = session
// M3: iOS Device -> Accessory -- `SRP Verify Request'
case .verifyRequest:
let session = try getSession(connection)
response = try controller.verifyRequest(data, session)
// M5: iOS Device -> Accessory -- `Exchange Request'
case .keyExchangeRequest:
let session = try getSession(connection)
response = try controller.keyExchangeRequest(data, session)
// Unknown state - return error and abort
default:
throw PairSetupController.Error.invalidParameters
}
} catch {
logger.warning(error)
connection.context[SESSION_KEY] = nil
try? device.changePairingState(.notPaired)
switch error {
case PairSetupController.Error.invalidParameters:
response = [
(.state, Data(bytes: [PairSetupStep.waiting.rawValue])),
(.error, Data(bytes: [PairError.unknown.rawValue]))
]
case PairSetupController.Error.alreadyPaired:
response = [
(.state, Data(bytes: [PairSetupStep.startResponse.rawValue])),
(.error, Data(bytes: [PairError.unavailable.rawValue]))
]
case PairSetupController.Error.alreadyPairing:
response = [
(.state, Data(bytes: [PairSetupStep.startResponse.rawValue])),
(.error, Data(bytes: [PairError.busy.rawValue]))
]
case PairSetupController.Error.invalidSetupState:
response = [
(.state, Data(bytes: [PairSetupStep.verifyResponse.rawValue])),
(.error, Data(bytes: [PairError.unknown.rawValue]))
]
case PairSetupController.Error.authenticationFailed:
response = [
(.state, Data(bytes: [PairSetupStep.verifyResponse.rawValue])),
(.error, Data(bytes: [PairError.authenticationFailed.rawValue]))
]
default:
response = nil
}
}
if let response = response {
return Response(status: .ok, data: encode(response), mimeType: "application/pairing+tlv8")
} else {
return .badRequest
}
}
}
| mit |
kysonyangs/ysbilibili | Pods/SwiftDate/Sources/SwiftDate/Date+Components.swift | 5 | 18652 | //
// SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones.
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// This is the default region set. It will be set automatically at each startup as the local device's region
internal var DateDefaultRegion: Region = Region.Local()
// MARK: - Date Extension to work with date components
public extension Date {
/// Define a default region to use when you work with components and function of SwiftDate
/// and `Date` objects. Default region is set automatically at runtime to `Region.Local()` which defines
/// a region identified by the device's current `TimeZone` (not updating), `Calendar` (not updating)
/// and `Locale` (not updating).
///
/// - parameter region: region to set. If nil is passed default region is set to Region.Local()
public static func setDefaultRegion(_ region: Region?) {
DateDefaultRegion = region ?? Region.Local()
}
/// Return the default region set.
///
/// - returns: region set; if not changed is set to `Region.Local()`
public static var defaultRegion: Region {
return DateDefaultRegion
}
/// Create a DateInRegion instance from given date expressing it in default region (locale+timezone+calendar)
///
/// - returns: a new DateInRegion object
internal func inDateDefaultRegion() -> DateInRegion {
return self.inRegion(region: DateDefaultRegion)
}
/// The number of era units for the receiver expressed in the context of `defaultRegion`.
public var era: Int {
return self.inDateDefaultRegion().era
}
/// The number of year units for the receiver expressed in the context of `defaultRegion`.
public var year: Int {
return self.inDateDefaultRegion().year
}
/// The number of month units for the receiver expressed in the context of `defaultRegion`.
public var month: Int {
return self.inDateDefaultRegion().month
}
/// The number of day units for the receiver expressed in the context of `defaultRegion`.
public var day: Int {
return self.inDateDefaultRegion().day
}
/// The number of hour units for the receiver expressed in the context of `defaultRegion`.
public var hour: Int {
return self.inDateDefaultRegion().hour
}
/// Nearest rounded hour from the date expressed in the context of `defaultRegion`.
public var nearestHour: Int {
return self.inDateDefaultRegion().nearestHour
}
/// The number of minute units for the receiver expressed in the context of `defaultRegion`.
public var minute: Int {
return self.inDateDefaultRegion().minute
}
/// The number of second units for the receiver expressed in the context of `defaultRegion`.
public var second: Int {
return self.inDateDefaultRegion().second
}
/// The number of nanosecond units for the receiver expressed in the context of `defaultRegion`.
public var nanosecond: Int {
return self.inDateDefaultRegion().nanosecond
}
/// The number of week-numbering units for the receiver expressed in the context of `defaultRegion`.
public var yearForWeekOfYear: Int {
return self.inDateDefaultRegion().yearForWeekOfYear
}
/// The week date of the year for the receiver expressed in the context of `defaultRegion`.
public var weekOfYear: Int {
return self.inDateDefaultRegion().weekOfYear
}
/// The number of weekday units for the receiver expressed in the context of `defaultRegion`.
public var weekday: Int {
return self.inDateDefaultRegion().weekday
}
/// The ordinal number of weekday units for the receiver expressed in the context of `defaultRegion`.
public var weekdayOrdinal: Int {
return self.inDateDefaultRegion().weekdayOrdinal
}
/// Week day name of the date expressed in the context of `defaultRegion`.
public var weekdayName: String {
return self.inDateDefaultRegion().weekdayName
}
/// Weekday short name
/// - note: This value is interpreted in the context of the calendar and timezone with which it is used
public var weekdayShortName: String {
return self.inDateDefaultRegion().weekdayShortName
}
/// Number of days into current's date month expressed in the context of `defaultRegion`.
public var monthDays: Int {
return self.inDateDefaultRegion().monthDays
}
/// he week number in the month expressed in the context of `defaultRegion`.
public var weekOfMonth: Int {
return self.inDateDefaultRegion().weekOfMonth
}
/// Month name of the date expressed in the context of `defaultRegion`.
public var monthName: String {
return self.inDateDefaultRegion().monthName
}
/// Short month name of the date expressed in the context of `defaultRegion`.
public var shortMonthName: String {
return self.inDateDefaultRegion().shortMonthName
}
/// Boolean value that indicates whether the month is a leap month.
/// Calculation is made in the context of `defaultRegion`.
public var leapMonth: Bool {
return self.inDateDefaultRegion().leapMonth
}
/// Boolean value that indicates whether the year is a leap year.
/// Calculation is made in the context of `defaultRegion`.
public var leapYear: Bool {
return self.inDateDefaultRegion().leapYear
}
/// Julian day is the continuous count of days since the beginning of the Julian Period used primarily by astronomers.
/// Calculation is made in the context of `defaultRegion`.
public var julianDay: Double {
return self.inDateDefaultRegion().julianDay
}
/// The Modified Julian Date (MJD) was introduced by the Smithsonian Astrophysical Observatory
/// in 1957 to record the orbit of Sputnik via an IBM 704 (36-bit machine) and using only 18 bits until August 7, 2576.
/// Calculation is made in the context of `defaultRegion`.
public var modifiedJulianDay: Double {
return self.inDateDefaultRegion().modifiedJulianDay
}
/// Return the next weekday after today.
/// For example using now.next(.friday) it will return the first Friday after self represented date.
///
/// - Parameter day: weekday you want to get
/// - Returns: the next weekday after sender date
public func next(day: WeekDay) -> Date? {
return self.inDateDefaultRegion().next(day: day)?.absoluteDate
}
/// Get the first day of the week according to the current calendar set
public var startWeek: Date {
return self.startOf(component: .weekOfYear)
}
/// Get the last day of the week according to the current calendar set
public var endWeek: Date {
return self.endOf(component: .weekOfYear)
}
/// Returns two `DateInRegion` objects indicating the start and the end of the current weekend.
/// Calculation is made in the context of `defaultRegion`.
public var thisWeekend: (startDate: DateInRegion, endDate: DateInRegion)? {
return self.inDateDefaultRegion().thisWeekend
}
/// Returns two `DateInRegion` objects indicating the start and the end
/// of the next weekend after the date.
/// Calculation is made in the context of `defaultRegion`.
public var nextWeekend: (startDate: DateInRegion, endDate: DateInRegion)? {
return self.inDateDefaultRegion().nextWeekend
}
/// Returns two `DateInRegion` objects indicating the start and the end of
/// the previous weekend before the date.
/// Calculation is made in the context of `defaultRegion`.
public var previousWeekend: (startDate: DateInRegion, endDate: DateInRegion)? {
return self.inDateDefaultRegion().previousWeekend
}
/// Returns whether the given date is in today as boolean.
/// Calculation is made in the context of `defaultRegion`.
public var isToday: Bool {
return self.inDateDefaultRegion().isToday
}
/// Returns whether the given date is in yesterday.
/// Calculation is made in the context of `defaultRegion`.
public var isYesterday: Bool {
return self.inDateDefaultRegion().isYesterday
}
/// Returns whether the given date is in tomorrow.
/// Calculation is made in the context of `defaultRegion`.
public var isTomorrow: Bool {
return self.inDateDefaultRegion().isTomorrow
}
/// Returns whether the given date is in the weekend.
/// Calculation is made in the context of `defaultRegion`.
public var isInWeekend: Bool {
return self.inDateDefaultRegion().isInWeekend
}
/// Return true if given date represent a passed date
/// Calculation is made in the context of `defaultRegion`.
public var isInPast: Bool {
return self.inDateDefaultRegion().isInPast
}
/// Return true if given date represent a future date
/// Calculation is made in the context of `defaultRegion`.
public var isInFuture: Bool {
return self.inDateDefaultRegion().isInFuture
}
/// Returns whether the given date is in the morning.
/// Calculation is made in the context of `defaultRegion`.
public var isMorning: Bool {
return self.inDateDefaultRegion().isMorning
}
/// Returns whether the given date is in the afternoon.
/// Calculation is made in the context of `defaultRegion`.
public var isAfternoon: Bool {
return self.inDateDefaultRegion().isAfternoon
}
/// Returns whether the given date is in the evening.
/// Calculation is made in the context of `defaultRegion`.
public var isEvening: Bool {
return self.inDateDefaultRegion().isEvening
}
/// Returns whether the given date is in the night.
/// Calculation is made in the context of `defaultRegion`.
public var isNight: Bool {
return self.inDateDefaultRegion().isNight
}
/// Returns whether the given date is on the same day as the receiver in the time zone and calendar of the receiver.
/// Calculation is made in the context of `defaultRegion`.
///
/// - parameter date: a date to compare against
///
/// - returns: a boolean indicating whether the receiver is on the same day as the given date in
/// the time zone and calendar of the receiver.
public func isInSameDayOf(date: Date) -> Bool {
return self.inDateDefaultRegion().isInSameDayOf(date: date.inDateDefaultRegion())
}
/// Return the instance representing the first moment date of the given date expressed in the context of
/// Calculation is made in the context of `defaultRegion`.
public var startOfDay: Date {
return self.inDateDefaultRegion().startOfDay.absoluteDate
}
/// Return the instance representing the last moment date of the given date expressed in the context of
/// Calculation is made in the context of `defaultRegion`.
public var endOfDay: Date {
return self.inDateDefaultRegion().endOfDay.absoluteDate
}
/// Return a new instance of the date plus one month
/// Calculation is made in the context of `defaultRegion`.
@available(*, deprecated: 4.1.7, message: "Use nextMonth() function instead")
public var nextMonth: Date {
return self.inDateDefaultRegion().nextMonth.absoluteDate
}
/// Return a new instance of the date minus one month
/// Calculation is made in the context of `defaultRegion`.
@available(*, deprecated: 4.1.7, message: "Use prevMonth() function instead")
public var prevMonth: Date {
return self.inDateDefaultRegion().prevMonth.absoluteDate
}
/// Return the date by adding one month to the current date
/// Calculation is made in the context of `defaultRegion`.
///
/// - Parameter time: when `.auto` evaluated date is calculated by adding one month to the current date.
/// If you pass `.start` result date is the first day of the next month (at 00:00:00).
/// If you pass `.end` result date is the last day of the next month (at 23:59:59).
/// - Returns: the new date at the next month
public func nextMonth(at time: TimeReference) -> Date {
return self.inDefaultRegion().nextMonth(at: time).absoluteDate
}
/// Return the date by subtracting one month from the current date
/// Calculation is made in the context of `defaultRegion`.
///
/// - Parameter time: when `.auto` evaluated date is calculated by subtracting one month to the current date.
/// If you pass `.start` result date is the first day of the previous month (at 00:00:00).
/// If you pass `.end` result date is the last day of the previous month (at 23:59:59).
/// - Returns: the new date at the next month
public func prevMonth(at time: TimeReference) -> Date {
return self.inDefaultRegion().prevMonth(at: time).absoluteDate
}
/// Return the date by subtracting one week from the current date
/// Calculation is made in the context of `defaultRegion`.
///
/// - Parameter time: when `.auto` evaluated date is calculated by adding one week to the current date.
/// If you pass `.start` result date is the first day of the previous week (at 00:00:00).
/// If you pass `.end` result date is the last day of the previous week (at 23:59:59).
/// - Returns: the new date at the previous week
public func prevWeek(at time: TimeReference) -> Date {
return self.inDefaultRegion().prevWeek(at: time).absoluteDate
}
/// Return the date by adding one week from the current date
/// Calculation is made in the context of `defaultRegion`.
///
/// - Parameter time: when `.auto` evaluated date is calculated by adding one week to the current date.
/// If you pass `.start` result date is the first day of the next week (at 00:00:00).
/// If you pass `.end` result date is the last day of the next week (at 23:59:59).
/// - Returns: the new date at the next week
public func nextWeek(at time: TimeReference) -> Date {
return self.inDefaultRegion().nextWeek(at: time).absoluteDate
}
/// Takes a date unit and returns a date at the start of that unit.
/// Calculation is made in the context of `defaultRegion`.
///
/// - parameter component: target component
///
/// - returns: the `Date` representing that start of that unit
public func startOf(component: Calendar.Component) -> Date {
return self.inDateDefaultRegion().startOf(component: component).absoluteDate
}
/// Takes a date unit and returns a date at the end of that unit.
/// Calculation is made in the context of `defaultRegion`.
///
/// - parameter component: target component
///
/// - returns: the `Date` representing that end of that unit
public func endOf(component: Calendar.Component) -> Date {
return self.inDateDefaultRegion().endOf(component: component).absoluteDate
}
/// Create a new instance calculated with the given time from self
///
/// - parameter hour: the hour value
/// - parameter minute: the minute value
/// - parameter second: the second value
///
/// - returns: a new `Date` object calculated at given time
public func atTime(hour: Int, minute: Int, second: Int) -> Date? {
return self.inDateDefaultRegion().atTime(hour: hour, minute: minute, second: second)?.absoluteDate
}
/// Create a new instance calculated by setting a specific component of a given date to a given value, while trying to keep lower
/// components the same.
///
/// - parameter unit: The unit to set with the given value
/// - parameter value: The value to set for the given calendar unit.
///
/// - returns: a new `Date` object calculated at given unit value
public func at(unit: Calendar.Component, value: Int) -> Date? {
return self.inDateDefaultRegion().at(unit: unit, value: value)?.absoluteDate
}
/// Create a new instance calculated by setting a list of components of a given date to given values (components
/// are evaluated serially - in order), while trying to keep lower components the same.
///
/// - parameter dict: a dictionary with `Calendar.Component` and it's value
///
/// - throws: throw a `FailedToCalculate` exception.
///
/// - returns: a new `Date` object calculated at given units values
@available(*, deprecated: 4.1.0, message: "This method has know issues. Use at(values:keep:) instead")
public func at(unitsWithValues dict: [Calendar.Component : Int]) throws -> Date {
return try self.inDateDefaultRegion().at(unitsWithValues: dict).absoluteDate
}
/// Create a new instance of the date by keeping passed calendar components and alter
///
/// - Parameters:
/// - values: values to alter in new instance
/// - keep: values to keep from self instance
/// - Returns: a new instance of `DateInRegion` with passed altered values
public func at(values: [Calendar.Component : Int], keep: Set<Calendar.Component>) -> Date? {
return self.inDateDefaultRegion().at(values: values, keep: keep)?.absoluteDate
}
/// Returns a `Date` object representing a date that is the earliest (old) from a given range
/// of dates.
/// The dates are compared in absolute time, i.e. time zones, locales and calendars have no
/// effect on the comparison.
///
/// - parameter list: a list of `Date` to evaluate
///
/// - returns: a `DateInRegion` object representing a date that is the earliest from a given
/// range of dates.
public static func oldestDate(_ list: [Date]) -> Date {
var currentMinimum = Date.distantFuture
list.forEach { cDate in
if currentMinimum > cDate {
currentMinimum = cDate
}
}
return currentMinimum
}
/// Returns a Date object representing a date that is the latest from a given range of
/// dates. The dates are compared in absolute time, i.e. time zones, locales and calendars have
/// no effect on the comparison.
///
/// - parameter list: a list of `Date` to evaluate
///
/// - returns: a `DateInRegion` object representing a date that is the latest from a given
/// range of dates.
public static func recentDate(_ list: [Date]) -> Date {
var currentMaximum = Date.distantPast
list.forEach { cDate in
if currentMaximum < cDate {
currentMaximum = cDate
}
}
return currentMaximum
}
}
| mit |
Jnosh/swift | test/Driver/driver-compile.swift | 3 | 5075 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s -sdk %S/../Inputs/clang-importer-sdk -Xfrontend -foo -Xfrontend -bar -Xllvm -baz -Xcc -garply -F /path/to/frameworks -Fsystem /path/to/systemframeworks -F /path/to/more/frameworks -I /path/to/headers -I path/to/more/headers -module-cache-path /tmp/modules -incremental 2>&1 > %t.complex.txt
// RUN: %FileCheck %s < %t.complex.txt
// RUN: %FileCheck -check-prefix COMPLEX %s < %t.complex.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-silgen -target x86_64-apple-macosx10.9 %s 2>&1 > %t.silgen.txt
// RUN: %FileCheck %s < %t.silgen.txt
// RUN: %FileCheck -check-prefix SILGEN %s < %t.silgen.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-sil -target x86_64-apple-macosx10.9 %s 2>&1 > %t.sil.txt
// RUN: %FileCheck %s < %t.sil.txt
// RUN: %FileCheck -check-prefix SIL %s < %t.sil.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-ir -target x86_64-apple-macosx10.9 %s 2>&1 > %t.ir.txt
// RUN: %FileCheck %s < %t.ir.txt
// RUN: %FileCheck -check-prefix IR %s < %t.ir.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-bc -target x86_64-apple-macosx10.9 %s 2>&1 > %t.bc.txt
// RUN: %FileCheck %s < %t.bc.txt
// RUN: %FileCheck -check-prefix BC %s < %t.bc.txt
// RUN: %swiftc_driver -driver-print-jobs -S -target x86_64-apple-macosx10.9 %s 2>&1 > %t.s.txt
// RUN: %FileCheck %s < %t.s.txt
// RUN: %FileCheck -check-prefix ASM %s < %t.s.txt
// RUN: %swiftc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s 2>&1 > %t.c.txt
// RUN: %FileCheck %s < %t.c.txt
// RUN: %FileCheck -check-prefix OBJ %s < %t.c.txt
// RUN: not %swiftc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s %s 2>&1 | %FileCheck -check-prefix DUPLICATE-NAME %s
// RUN: cp %s %t
// RUN: not %swiftc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s %t/driver-compile.swift 2>&1 | %FileCheck -check-prefix DUPLICATE-NAME %s
// RUN: %swiftc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s %S/../Inputs/empty.swift -module-name main -driver-use-filelists 2>&1 | %FileCheck -check-prefix=FILELIST %s
// RUN: rm -rf %t && mkdir -p %t/DISTINCTIVE-PATH/usr/bin/
// RUN: %hardlink-or-copy(from: %swift_driver_plain, to: %t/DISTINCTIVE-PATH/usr/bin/swiftc)
// RUN: ln -s "swiftc" %t/DISTINCTIVE-PATH/usr/bin/swift-update
// RUN: %t/DISTINCTIVE-PATH/usr/bin/swiftc -driver-print-jobs -c -update-code -target x86_64-apple-macosx10.9 %s 2>&1 > %t.upd.txt
// RUN: %FileCheck -check-prefix UPDATE-CODE %s < %t.upd.txt
// Clean up the test executable because hard links are expensive.
// RUN: rm -rf %t/DISTINCTIVE-PATH/usr/bin/swiftc
// RUN: %swiftc_driver -driver-print-jobs -whole-module-optimization -incremental %s 2>&1 > %t.wmo-inc.txt
// RUN: %FileCheck %s < %t.wmo-inc.txt
// RUN: %FileCheck -check-prefix NO-REFERENCE-DEPENDENCIES %s < %t.wmo-inc.txt
// RUN: %swiftc_driver -driver-print-jobs -embed-bitcode -incremental %s 2>&1 > %t.embed-inc.txt
// RUN: %FileCheck %s < %t.embed-inc.txt
// RUN: %FileCheck -check-prefix NO-REFERENCE-DEPENDENCIES %s < %t.embed-inc.txt
// REQUIRES: CODEGENERATOR=X86
// CHECK: bin/swift
// CHECK: Driver/driver-compile.swift
// CHECK: -o
// COMPLEX: bin/swift
// COMPLEX: -c
// COMPLEX: Driver/driver-compile.swift
// COMPLEX-DAG: -sdk {{.*}}/Inputs/clang-importer-sdk
// COMPLEX-DAG: -foo -bar
// COMPLEX-DAG: -Xllvm -baz
// COMPLEX-DAG: -Xcc -garply
// COMPLEX-DAG: -F /path/to/frameworks -Fsystem /path/to/systemframeworks -F /path/to/more/frameworks
// COMPLEX-DAG: -I /path/to/headers -I path/to/more/headers
// COMPLEX-DAG: -module-cache-path /tmp/modules
// COMPLEX-DAG: -emit-reference-dependencies-path {{(.*/)?driver-compile[^ /]+}}.swiftdeps
// COMPLEX: -o {{.+}}.o
// SILGEN: bin/swift
// SILGEN: -emit-silgen
// SILGEN: -o -
// SIL: bin/swift
// SIL: -emit-sil{{ }}
// SIL: -o -
// IR: bin/swift
// IR: -emit-ir
// IR: -o -
// BC: bin/swift
// BC: -emit-bc
// BC: -o {{[^-]}}
// ASM: bin/swift
// ASM: -S{{ }}
// ASM: -o -
// OBJ: bin/swift
// OBJ: -c{{ }}
// OBJ: -o {{[^-]}}
// DUPLICATE-NAME: error: filename "driver-compile.swift" used twice: '{{.*}}test/Driver/driver-compile.swift' and '{{.*}}driver-compile.swift'
// DUPLICATE-NAME: note: filenames are used to distinguish private declarations with the same name
// FILELIST: bin/swift
// FILELIST: -filelist [[SOURCES:(["][^"]+|[^ ]+)sources([^"]+["]|[^ ]+)]]
// FILELIST: -primary-file {{.*/(driver-compile.swift|empty.swift)}}
// FILELIST: -output-filelist {{[^-]}}
// FILELIST-NEXT: bin/swift
// FILELIST: -filelist [[SOURCES]]
// FILELIST: -primary-file {{.*/(driver-compile.swift|empty.swift)}}
// FILELIST: -output-filelist {{[^-]}}
// UPDATE-CODE: DISTINCTIVE-PATH/usr/bin/swift
// UPDATE-CODE: -frontend -c
// UPDATE-CODE: -emit-remap-file-path {{.+}}.remap
// NO-REFERENCE-DEPENDENCIES: bin/swift
// NO-REFERENCE-DEPENDENCIES-NOT: -emit-reference-dependencies
| apache-2.0 |
fellipecaetano/Democracy-iOS | Pods/RandomKit/Sources/RandomKit/Extensions/Swift/UnicodeScalar+RandomKit.swift | 1 | 4506 | //
// UnicodeScalar+RandomKit.swift
// RandomKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Nikolai Vazquez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
extension UnicodeScalar: Random, RandomInRange, RandomInClosedRange {
/// A unicode scalar range from `" "` through `"~"`.
public static let randomRange: ClosedRange<UnicodeScalar> = " "..."~"
/// Generates a random value of `Self`.
///
/// The random value is in `UnicodeScalar.randomRange`.
public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> UnicodeScalar {
return random(in: UnicodeScalar.randomRange, using: &randomGenerator)
}
/// Returns a random value of `Self` inside of the closed range.
public static func uncheckedRandom<R: RandomGenerator>(in range: Range<UnicodeScalar>, using randomGenerator: inout R) -> UnicodeScalar {
let lower = range.lowerBound.value
let upper = range.upperBound.value
if lower._isLowerRange && !upper._isLowerRange {
let diff: UInt32 = 0xE000 - 0xD7FF - 1
let newRange = Range(uncheckedBounds: (lower, upper - diff))
let random = UInt32.uncheckedRandom(in: newRange, using: &randomGenerator)
if random._isLowerRange {
return _unsafeBitCast(random)
} else {
return _unsafeBitCast(random &+ diff)
}
} else {
let newRange = Range(uncheckedBounds: (lower, upper))
let random = UInt32.uncheckedRandom(in: newRange, using: &randomGenerator)
return _unsafeBitCast(random)
}
}
/// Returns a random value of `Self` inside of the closed range.
public static func random<R: RandomGenerator>(in closedRange: ClosedRange<UnicodeScalar>,
using randomGenerator: inout R) -> UnicodeScalar {
let lower = closedRange.lowerBound.value
let upper = closedRange.upperBound.value
if lower._isLowerRange && !upper._isLowerRange {
let diff: UInt32 = 0xE000 - 0xD7FF - 1
let newRange = ClosedRange(uncheckedBounds: (lower, upper - diff))
let random = UInt32.random(in: newRange, using: &randomGenerator)
if random._isLowerRange {
return _unsafeBitCast(random)
} else {
return _unsafeBitCast(random &+ diff)
}
} else {
let newRange = ClosedRange(uncheckedBounds: (lower, upper))
let random = UInt32.random(in: newRange, using: &randomGenerator)
return _unsafeBitCast(random)
}
}
/// Returns an optional random value of `Self` inside of the range.
public static func random<R: RandomGenerator>(in range: Range<UInt8>,
using randomGenerator: inout R) -> UnicodeScalar? {
return UInt8.random(in: range, using: &randomGenerator).map(UnicodeScalar.init)
}
/// Returns a random value of `Self` inside of the closed range.
public static func random<R: RandomGenerator>(in closedRange: ClosedRange<UInt8>,
using randomGenerator: inout R) -> UnicodeScalar {
return UnicodeScalar(UInt8.random(in: closedRange, using: &randomGenerator))
}
}
private extension UInt32 {
var _isLowerRange: Bool {
return self <= 0xD7FF
}
}
| mit |
cszwdy/Genome | Genome.playground/Sources/Logging.swift | 2 | 248 |
public var loggers: [ErrorType -> Void] = [defaultLogger]
private func defaultLogger(error: ErrorType) {
print(error)
}
internal func logError(error: ErrorType) -> ErrorType {
loggers.forEach {
$0(error)
}
return error
}
| mit |
karwa/swift-corelibs-foundation | Foundation/NSConcreteValue.swift | 3 | 6283 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
internal class NSConcreteValue : NSValue {
struct TypeInfo : Equatable {
let size : Int
let name : String
init?(objCType spec: String) {
var size: Int = 0
var align: Int = 0
var count : Int = 0
var type = _NSSimpleObjCType(spec)
guard type != nil else {
print("NSConcreteValue.TypeInfo: unsupported type encoding spec '\(spec)'")
return nil
}
if type == .StructBegin {
fatalError("NSConcreteValue.TypeInfo: cannot encode structs")
} else if type == .ArrayBegin {
let scanner = NSScanner(string: spec)
scanner.scanLocation = 1
guard scanner.scanInteger(&count) && count > 0 else {
print("NSConcreteValue.TypeInfo: array count is missing or zero")
return nil
}
guard let elementType = _NSSimpleObjCType(scanner.scanUpToString(String(_NSSimpleObjCType.ArrayEnd))) else {
print("NSConcreteValue.TypeInfo: array type is missing")
return nil
}
guard _NSGetSizeAndAlignment(elementType, &size, &align) else {
print("NSConcreteValue.TypeInfo: unsupported type encoding spec '\(spec)'")
return nil
}
type = elementType
}
guard _NSGetSizeAndAlignment(type!, &size, &align) else {
print("NSConcreteValue.TypeInfo: unsupported type encoding spec '\(spec)'")
return nil
}
self.size = count != 0 ? size * count : size
self.name = spec
}
}
private static var _cachedTypeInfo = Dictionary<String, TypeInfo>()
private static var _cachedTypeInfoLock = NSLock()
private var _typeInfo : TypeInfo
private var _storage : UnsafeMutablePointer<UInt8>
required init(bytes value: UnsafePointer<Void>, objCType type: UnsafePointer<Int8>) {
let spec = String(cString: type)
var typeInfo : TypeInfo? = nil
NSConcreteValue._cachedTypeInfoLock.synchronized {
typeInfo = NSConcreteValue._cachedTypeInfo[spec]
if typeInfo == nil {
typeInfo = TypeInfo(objCType: spec)
NSConcreteValue._cachedTypeInfo[spec] = typeInfo
}
}
guard typeInfo != nil else {
fatalError("NSConcreteValue.init: failed to initialize from type encoding spec '\(spec)'")
}
self._typeInfo = typeInfo!
self._storage = UnsafeMutablePointer<UInt8>(allocatingCapacity: self._typeInfo.size)
self._storage.initializeFrom(unsafeBitCast(value, to: UnsafeMutablePointer<UInt8>.self), count: self._typeInfo.size)
}
deinit {
self._storage.deinitialize(count: self._size)
self._storage.deallocateCapacity(self._size)
}
override func getValue(_ value: UnsafeMutablePointer<Void>) {
UnsafeMutablePointer<UInt8>(value).moveInitializeFrom(unsafeBitCast(self._storage, to: UnsafeMutablePointer<UInt8>.self), count: self._size)
}
override var objCType : UnsafePointer<Int8> {
return NSString(self._typeInfo.name).utf8String! // XXX leaky
}
override var classForCoder: AnyClass {
return NSValue.self
}
override var description : String {
return NSData.init(bytes: self.value, length: self._size).description
}
convenience required init?(coder aDecoder: NSCoder) {
if !aDecoder.allowsKeyedCoding {
NSUnimplemented()
} else {
guard let type = aDecoder.decodeObject() as? NSString else {
return nil
}
let typep = type._swiftObject
// FIXME: This will result in reading garbage memory.
self.init(bytes: [], objCType: typep)
aDecoder.decodeValueOfObjCType(typep, at: self.value)
}
}
override func encodeWithCoder(_ aCoder: NSCoder) {
if !aCoder.allowsKeyedCoding {
NSUnimplemented()
} else {
aCoder.encodeObject(String(cString: self.objCType).bridge())
aCoder.encodeValueOfObjCType(self.objCType, at: self.value)
}
}
private var _size : Int {
return self._typeInfo.size
}
private var value : UnsafeMutablePointer<Void> {
return unsafeBitCast(self._storage, to: UnsafeMutablePointer<Void>.self)
}
private func _isEqualToValue(_ other: NSConcreteValue) -> Bool {
if self === other {
return true
}
if self._size != other._size {
return false
}
let bytes1 = self.value
let bytes2 = other.value
if bytes1 == bytes2 {
return true
}
return memcmp(bytes1, bytes2, self._size) == 0
}
override func isEqual(_ object: AnyObject?) -> Bool {
if let other = object as? NSConcreteValue {
return self._typeInfo == other._typeInfo &&
self._isEqualToValue(other)
} else {
return false
}
}
override var hash: Int {
return self._typeInfo.name.hashValue &+
Int(bitPattern: CFHashBytes(unsafeBitCast(self.value, to: UnsafeMutablePointer<UInt8>.self), self._size))
}
}
internal func ==(x : NSConcreteValue.TypeInfo, y : NSConcreteValue.TypeInfo) -> Bool {
return x.name == y.name && x.size == y.size
}
| apache-2.0 |
rporzuc/FindFriends | FindFriends/ManagedObjectSubclasses/Messages+CoreDataProperties.swift | 1 | 710 | //
// Messages+CoreDataProperties.swift
// FindFriends
//
// Created by MacOSXRAFAL on 09/11/17.
// Copyright © 2017 MacOSXRAFAL. All rights reserved.
//
import Foundation
import CoreData
extension Messages {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Messages> {
return NSFetchRequest<Messages>(entityName: "Messages");
}
@NSManaged public var contentsMessage: String?
@NSManaged public var datetimeMessage: NSDate?
@NSManaged public var idConversation: Int32
@NSManaged public var numberMessage: Int32
@NSManaged public var recipientMessage: Int32
@NSManaged public var senderMessage: Int32
@NSManaged public var wasReadMessage: Bool
}
| gpl-3.0 |
sufan/dubstepocto | Shared/Models/TVImageModel.swift | 1 | 163 | //
// TVImageModel.swift
// Potpourri
//
// Created by sufan on 8/19/20.
//
struct TVImageModel: Decodable {
let medium: String
let original: String
}
| mit |
knorrium/MemeMe | MemeMe/SentMemesTableViewController.swift | 1 | 2255 | //
// SentMemesTableViewController.swift
// MemeMe
//
// Created by Felipe Kuhn on 10/16/15.
// Copyright © 2015 Knorrium. All rights reserved.
//
import UIKit
class SentMemesTableViewController: UIViewController, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
override func viewDidLoad() {
tableView.registerClass(SentMemesTableViewCell.self, forCellReuseIdentifier: "SentMemesTableViewCell")
}
override func viewWillAppear(animated: Bool) {
tableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return appDelegate.memes.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SentMemesTableViewCell")!
let meme = appDelegate.memes[indexPath.row]
cell.textLabel?.text = meme.topText + " " + meme.bottomText
cell.imageView?.image = meme.memedImage
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let detailController = storyboard!.instantiateViewControllerWithIdentifier("SentMemesDetailViewController") as! SentMemesDetailViewController
detailController.memedImage = appDelegate.memes[indexPath.row].memedImage
detailController.savedIndex = indexPath.row
navigationController!.pushViewController(detailController, animated: true)
}
//Delete - https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson9.html
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
appDelegate.memes.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
} | mit |
SSamanta/SSNetworking | DemoClient/DemoClient/ViewController.swift | 1 | 644 | //
// ViewController.swift
// DemoClient
//
// Created by Susim Samanta on 20/05/15.
// Copyright (c) 2015 Susim Samanta. All rights reserved.
//
import UIKit
import SSHTTPClient
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let client = SSHTTPClient(url: "http://itunes.apple.com/us/rss/topfreeapplications/limit=100/json", method: "GET", httpBody: "", headerFieldsAndValues: [:])
client.getJsonData { (obj, error) -> Void in
print(obj)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
Subsets and Splits