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 |
---|---|---|---|---|---|
austinzheng/swift-compiler-crashes | crashes-duplicates/12653-no-stacktrace.swift | 11 | 228 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for {
func i{
let a {
class A {
{
}
init( )
{
class
case ,
| mit |
brave/browser-ios | Storage/Cursor.swift | 28 | 2957 | /* 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
/**
* Status results for a Cursor
*/
public enum CursorStatus {
case success
case failure
case closed
}
public protocol TypedCursor: Sequence {
associatedtype T
var count: Int { get }
var status: CursorStatus { get }
var statusMessage: String { get }
subscript(index: Int) -> T? { get }
func asArray() -> [T]
}
/**
* Provides a generic method of returning some data and status information about a request.
*/
open class Cursor<T>: TypedCursor {
open var count: Int {
get { return 0 }
}
// Extra status information
open var status: CursorStatus
public var statusMessage: String
init(err: NSError) {
self.status = .failure
self.statusMessage = err.description
}
public init(status: CursorStatus = .success, msg: String = "") {
self.statusMessage = msg
self.status = status
}
// Collection iteration and access functions
open subscript(index: Int) -> T? {
get { return nil }
}
open func asArray() -> [T] {
var acc = [T]()
acc.reserveCapacity(self.count)
for row in self {
// Shouldn't ever be nil -- that's to allow the generator or subscript to be
// out of range.
if let row = row {
acc.append(row)
}
}
return acc
}
open func makeIterator() -> AnyIterator<T?> {
var nextIndex = 0
return AnyIterator() {
if nextIndex >= self.count || self.status != CursorStatus.success {
return nil
}
defer { nextIndex += 1 }
return self[nextIndex]
}
}
open func close() {
status = .closed
statusMessage = "Closed"
}
deinit {
if status != CursorStatus.closed {
close()
}
}
}
/*
* A cursor implementation that wraps an array.
*/
open class ArrayCursor<T> : Cursor<T> {
fileprivate var data: [T]
open override var count: Int {
if status != .success {
return 0
}
return data.count
}
public init(data: [T], status: CursorStatus, statusMessage: String) {
self.data = data
super.init(status: status, msg: statusMessage)
}
public convenience init(data: [T]) {
self.init(data: data, status: CursorStatus.success, statusMessage: "Success")
}
open override subscript(index: Int) -> T? {
get {
if index >= data.count || index < 0 || status != .success {
return nil
}
return data[index]
}
}
override open func close() {
data = [T]()
super.close()
}
}
| mpl-2.0 |
manavgabhawala/swift | test/SourceKit/NameTranslation/basic.swift | 5 | 4483 | import Foo
var derivedObj = FooClassDerived()
func foo1(_ a : FooClassDerived) {
_ = a.fooProperty1
_ = a.fooInstanceFunc0()
fooFunc3(1,1,1,nil)
}
func foo2 (_ a : FooClassDerived) {
a.fooBaseInstanceFuncOverridden()
a.fooInstanceFunc0()
a.fooInstanceFunc1(2)
a.fooInstanceFunc2(2, withB: 2)
_ = a.fooProperty1
_ = FooClassBase(float: 2.3)
_ = FooClassBase()
}
// REQUIRES: objc_interop
// RUN: %sourcekitd-test -req=translate -objc-name FooClassDerived2 -pos=5:30 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK1 %s
// RUN: %sourcekitd-test -req=translate -objc-selector FooClassDerived2 -pos=3:23 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK11 %s
// RUN: %sourcekitd-test -req=translate -objc-name fooProperty2 -pos=6:16 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK2 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc1 -pos=7:16 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK3 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooFunc3:d:d:d: -pos=8:4 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK-NONE %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooBaseInstanceFuncOverridden1 -pos=12:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK4 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc01 -pos=13:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK5 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc11: -pos=14:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK6 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc2:withBB: -pos=15:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK7 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc21:withBB: -pos=15:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK8 %s
// RUN: %sourcekitd-test -req=translate -objc-name fooProperty11 -pos=16:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK9 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc21:withBB:withC: -pos=15:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK-NONE %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc21: -pos=15:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK-NONE %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc21: -pos=17:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK10 %s
// RUN: %sourcekitd-test -req=translate -objc-selector initWithfloat2: -pos=17:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK12 %s
// RUN: %sourcekitd-test -req=translate -objc-selector initWithfloat2:D: -pos=17:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK-NONE %s
// RUN: %sourcekitd-test -req=translate -objc-selector init: -pos=17:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK13 %s
// RUN: %sourcekitd-test -req=translate -objc-selector iit: -pos=17:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK13 %s
// RUN: %sourcekitd-test -req=translate -objc-selector init: -pos=18:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK-NONE %s
// RUN: %sourcekitd-test -req=translate -objc-selector NAME -pos=18:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK14 %s
// CHECK1: FooClassDerived2
// CHECK-NONE: <empty name translation info>
// CHECK2: fooProperty2
// CHECK3: fooInstanceFunc1
// CHECK4: fooBaseInstanceFuncOverridden1
// CHECK5: fooInstanceFunc01
// CHECK6: fooInstanceFunc11(_:)
// CHECK7: fooInstanceFunc2(_:withBB:)
// CHECK8: fooInstanceFunc21(_:withBB:)
// CHECK9: fooProperty11
// CHECK10: init(nstanceFunc21:)
// CHECK11: init(lassDerived2:)
// CHECK12: init(float2:)
// CHECK13: init(_:)
// CHECK14: init
| apache-2.0 |
material-components/material-components-ios | components/Buttons/examples/supplemental/ButtonsTypicalUseSupplemental.swift | 2 | 2057 | // Copyright 2016-present the Material Components for iOS authors. 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.
import UIKit
import MaterialComponents.MaterialButtons
class ButtonsTypicalUseSupplemental: NSObject {
static let floatingButtonPlusDimension = CGFloat(24)
static func plusShapePath() -> UIBezierPath {
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 19, y: 13))
bezierPath.addLine(to: CGPoint(x: 13, y: 13))
bezierPath.addLine(to: CGPoint(x: 13, y: 19))
bezierPath.addLine(to: CGPoint(x: 11, y: 19))
bezierPath.addLine(to: CGPoint(x: 11, y: 13))
bezierPath.addLine(to: CGPoint(x: 5, y: 13))
bezierPath.addLine(to: CGPoint(x: 5, y: 11))
bezierPath.addLine(to: CGPoint(x: 11, y: 11))
bezierPath.addLine(to: CGPoint(x: 11, y: 5))
bezierPath.addLine(to: CGPoint(x: 13, y: 5))
bezierPath.addLine(to: CGPoint(x: 13, y: 11))
bezierPath.addLine(to: CGPoint(x: 19, y: 11))
bezierPath.addLine(to: CGPoint(x: 19, y: 13))
bezierPath.close()
return bezierPath
}
static func createPlusShapeLayer(_ floatingButton: MDCFloatingButton) -> CAShapeLayer {
let plusShape = CAShapeLayer()
plusShape.path = ButtonsTypicalUseSupplemental.plusShapePath().cgPath
plusShape.fillColor = UIColor.white.cgColor
plusShape.position =
CGPoint(
x: (floatingButton.frame.size.width - floatingButtonPlusDimension) / 2,
y: (floatingButton.frame.size.height - floatingButtonPlusDimension) / 2)
return plusShape
}
}
| apache-2.0 |
tuffz/pi-weather-app | Carthage/Checkouts/realm-cocoa/RealmSwift/Tests/ObjectCreationTests.swift | 1 | 53645 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Realm.Private
import RealmSwift
import Foundation
#if swift(>=3.0)
class ObjectCreationTests: TestCase {
// MARK: Init tests
func testInitWithDefaults() {
// test all properties are defaults
let object = SwiftObject()
XCTAssertNil(object.realm)
// test defaults values
verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false,
boolObjectListValues: [])
// test realm properties are nil for standalone
XCTAssertNil(object.realm)
XCTAssertNil(object.objectCol!.realm)
XCTAssertNil(object.arrayCol.realm)
}
func testInitWithOptionalWithoutDefaults() {
let object = SwiftOptionalObject()
for prop in object.objectSchema.properties {
let value = object[prop.name]
if let value = value as? RLMOptionalBase {
XCTAssertNil(value.underlyingValue)
} else {
XCTAssertNil(value)
}
}
}
func testInitWithOptionalDefaults() {
let object = SwiftOptionalDefaultValuesObject()
verifySwiftOptionalObjectWithDictionaryLiteral(object, dictionary:
SwiftOptionalDefaultValuesObject.defaultValues(), boolObjectValue: true)
}
func testInitWithDictionary() {
// dictionary with all values specified
let baselineValues: [String: Any] =
["boolCol": true,
"intCol": 1,
"floatCol": 1.1 as Float,
"doubleCol": 11.1,
"stringCol": "b",
"binaryCol": "b".data(using: String.Encoding.utf8)!,
"dateCol": Date(timeIntervalSince1970: 2),
"objectCol": SwiftBoolObject(value: [true]),
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()]
]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[props[propNum].name] = validValue
let object = SwiftObject(value: values)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[props[propNum].name] = invalidValue
assertThrows(SwiftObject(value: values), "Invalid property value")
}
}
}
func testInitWithDefaultsAndDictionary() {
// test with dictionary with mix of default and one specified value
let object = SwiftObject(value: ["intCol": 200])
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(object, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
}
func testInitWithArray() {
// array with all values specified
let baselineValues: [Any] = [true, 1, 1.1 as Float, 11.1, "b", "b".data(using: String.Encoding.utf8)!,
Date(timeIntervalSince1970: 2), ["boolCol": true], [[true], [false]]]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[propNum] = validValue
let object = SwiftObject(value: values)
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[propNum] = invalidValue
assertThrows(SwiftObject(value: values), "Invalid property value")
}
}
}
func testInitWithKVCObject() {
// test with kvc object
let objectWithInt = SwiftObject(value: ["intCol": 200])
let objectWithKVCObject = SwiftObject(value: objectWithInt)
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
}
func testGenericInit() {
func createObject<T: Object>() -> T {
return T()
}
let obj1: SwiftBoolObject = createObject()
let obj2 = SwiftBoolObject()
XCTAssertEqual(obj1.boolCol, obj2.boolCol,
"object created via generic initializer should equal object created by calling initializer directly")
}
// MARK: Creation tests
func testCreateWithDefaults() {
let realm = try! Realm()
assertThrows(realm.create(SwiftObject.self), "Must be in write transaction")
var object: SwiftObject!
let objects = realm.objects(SwiftObject.self)
XCTAssertEqual(0, objects.count)
try! realm.write {
// test create with all defaults
object = realm.create(SwiftObject.self)
return
}
verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false,
boolObjectListValues: [])
// test realm properties are populated correctly
XCTAssertEqual(object.realm!, realm)
XCTAssertEqual(object.objectCol!.realm!, realm)
XCTAssertEqual(object.arrayCol.realm!, realm)
}
func testCreateWithOptionalWithoutDefaults() {
let realm = try! Realm()
try! realm.write {
let object = realm.create(SwiftOptionalObject.self)
for prop in object.objectSchema.properties {
XCTAssertNil(object[prop.name])
}
}
}
func testCreateWithOptionalDefaults() {
let realm = try! Realm()
try! realm.write {
let object = realm.create(SwiftOptionalDefaultValuesObject.self)
self.verifySwiftOptionalObjectWithDictionaryLiteral(object,
dictionary: SwiftOptionalDefaultValuesObject.defaultValues(), boolObjectValue: true)
}
}
func testCreateWithOptionalIgnoredProperties() {
let realm = try! Realm()
try! realm.write {
let object = realm.create(SwiftOptionalIgnoredPropertiesObject.self)
let properties = object.objectSchema.properties
XCTAssertEqual(properties.count, 1)
XCTAssertEqual(properties[0].name, "id")
}
}
func testCreateWithDictionary() {
// dictionary with all values specified
let baselineValues: [String: Any] = [
"boolCol": true,
"intCol": 1,
"floatCol": 1.1 as Float,
"doubleCol": 11.1,
"stringCol": "b",
"binaryCol": "b".data(using: String.Encoding.utf8)!,
"dateCol": Date(timeIntervalSince1970: 2),
"objectCol": SwiftBoolObject(value: [true]),
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()]
]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[props[propNum].name] = validValue
try! Realm().beginWrite()
let object = try! Realm().create(SwiftObject.self, value: values)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
try! Realm().commitWrite()
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[props[propNum].name] = invalidValue
try! Realm().beginWrite()
assertThrows(try! Realm().create(SwiftObject.self, value: values), "Invalid property value")
try! Realm().cancelWrite()
}
}
}
func testCreateWithDefaultsAndDictionary() {
// test with dictionary with mix of default and one specified value
let realm = try! Realm()
realm.beginWrite()
let objectWithInt = realm.create(SwiftObject.self, value: ["intCol": 200])
try! realm.commitWrite()
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(objectWithInt, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
}
func testCreateWithArray() {
// array with all values specified
let baselineValues: [Any] = [true, 1, 1.1 as Float, 11.1, "b", "b".data(using: String.Encoding.utf8)!,
Date(timeIntervalSince1970: 2), ["boolCol": true], [[true], [false]]]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[propNum] = validValue
try! Realm().beginWrite()
let object = try! Realm().create(SwiftObject.self, value: values)
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true,
boolObjectListValues: [true, false])
try! Realm().commitWrite()
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid array literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[propNum] = invalidValue
try! Realm().beginWrite()
assertThrows(try! Realm().create(SwiftObject.self, value: values),
"Invalid property value '\(invalidValue)' for property number \(propNum)")
try! Realm().cancelWrite()
}
}
}
func testCreateWithKVCObject() {
// test with kvc object
try! Realm().beginWrite()
let objectWithInt = try! Realm().create(SwiftObject.self, value: ["intCol": 200])
let objectWithKVCObject = try! Realm().create(SwiftObject.self, value: objectWithInt)
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
try! Realm().commitWrite()
verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
XCTAssertEqual(try! Realm().objects(SwiftObject.self).count, 2, "Object should have been copied")
}
func testCreateWithNestedObjects() {
let standalone = SwiftPrimaryStringObject(value: ["p0", 11])
try! Realm().beginWrite()
let objectWithNestedObjects = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p1", ["p1", 11],
[standalone]])
try! Realm().commitWrite()
let stringObjects = try! Realm().objects(SwiftPrimaryStringObject.self)
XCTAssertEqual(stringObjects.count, 2)
let persistedObject = stringObjects.first!
// standalone object should be copied into the realm, not added directly
XCTAssertNotEqual(standalone, persistedObject)
XCTAssertEqual(objectWithNestedObjects.object!, persistedObject)
XCTAssertEqual(objectWithNestedObjects.objects.first!, stringObjects.last!)
let standalone1 = SwiftPrimaryStringObject(value: ["p3", 11])
try! Realm().beginWrite()
assertThrows(try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p3", ["p3", 11], [standalone1]]),
"Should throw with duplicate primary key")
try! Realm().commitWrite()
}
func testUpdateWithNestedObjects() {
let standalone = SwiftPrimaryStringObject(value: ["primary", 11])
try! Realm().beginWrite()
let object = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["otherPrimary", ["primary", 12],
[["primary", 12]]], update: true)
try! Realm().commitWrite()
let stringObjects = try! Realm().objects(SwiftPrimaryStringObject.self)
XCTAssertEqual(stringObjects.count, 1)
let persistedObject = object.object!
XCTAssertEqual(persistedObject.intCol, 12)
XCTAssertNil(standalone.realm) // the standalone object should be copied, rather than added, to the realm
XCTAssertEqual(object.object!, persistedObject)
XCTAssertEqual(object.objects.first!, persistedObject)
}
func testCreateWithObjectsFromAnotherRealm() {
let values: [String: Any] = [
"boolCol": true,
"intCol": 1,
"floatCol": 1.1 as Float,
"doubleCol": 11.1,
"stringCol": "b",
"binaryCol": "b".data(using: String.Encoding.utf8)!,
"dateCol": Date(timeIntervalSince1970: 2),
"objectCol": SwiftBoolObject(value: [true]),
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()],
]
realmWithTestPath().beginWrite()
let otherRealmObject = realmWithTestPath().create(SwiftObject.self, value: values)
try! realmWithTestPath().commitWrite()
try! Realm().beginWrite()
let object = try! Realm().create(SwiftObject.self, value: otherRealmObject)
try! Realm().commitWrite()
XCTAssertNotEqual(otherRealmObject, object)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
func testCreateWithDeeplyNestedObjectsFromAnotherRealm() {
let values: [String: Any] = [
"boolCol": true,
"intCol": 1,
"floatCol": 1.1 as Float,
"doubleCol": 11.1,
"stringCol": "b",
"binaryCol": "b".data(using: String.Encoding.utf8)!,
"dateCol": Date(timeIntervalSince1970: 2),
"objectCol": SwiftBoolObject(value: [true]),
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()],
]
let realmA = realmWithTestPath()
let realmB = try! Realm()
var realmAObject: SwiftListOfSwiftObject!
try! realmA.write {
let array = [SwiftObject(value: values), SwiftObject(value: values)]
realmAObject = realmA.create(SwiftListOfSwiftObject.self, value: ["array": array])
}
var realmBObject: SwiftListOfSwiftObject!
try! realmB.write {
realmBObject = realmB.create(SwiftListOfSwiftObject.self, value: realmAObject)
}
XCTAssertNotEqual(realmAObject, realmBObject)
XCTAssertEqual(realmBObject.array.count, 2)
for swiftObject in realmBObject.array {
verifySwiftObjectWithDictionaryLiteral(swiftObject, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
func testUpdateWithObjectsFromAnotherRealm() {
realmWithTestPath().beginWrite()
let otherRealmObject = realmWithTestPath().create(SwiftLinkToPrimaryStringObject.self,
value: ["primary", NSNull(), [["2", 2], ["4", 4]]])
try! realmWithTestPath().commitWrite()
try! Realm().beginWrite()
try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["primary", ["10", 10], [["11", 11]]])
let object = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: otherRealmObject, update: true)
try! Realm().commitWrite()
XCTAssertNotEqual(otherRealmObject, object) // the object from the other realm should be copied into this realm
XCTAssertEqual(try! Realm().objects(SwiftLinkToPrimaryStringObject.self).count, 1)
XCTAssertEqual(try! Realm().objects(SwiftPrimaryStringObject.self).count, 4)
}
func testCreateWithNSNullLinks() {
let values: [String: Any] = [
"boolCol": true,
"intCol": 1,
"floatCol": 1.1,
"doubleCol": 11.1,
"stringCol": "b",
"binaryCol": "b".data(using: String.Encoding.utf8)!,
"dateCol": Date(timeIntervalSince1970: 2),
"objectCol": NSNull(),
"arrayCol": NSNull(),
]
realmWithTestPath().beginWrite()
let object = realmWithTestPath().create(SwiftObject.self, value: values)
try! realmWithTestPath().commitWrite()
XCTAssert(object.objectCol == nil) // XCTAssertNil caused a NULL deref inside _swift_getClass
XCTAssertEqual(object.arrayCol.count, 0)
}
// test null object
// test null list
// MARK: Add tests
func testAddWithExisingNestedObjects() {
try! Realm().beginWrite()
let existingObject = try! Realm().create(SwiftBoolObject.self)
try! Realm().commitWrite()
try! Realm().beginWrite()
let object = SwiftObject(value: ["objectCol" : existingObject])
try! Realm().add(object)
try! Realm().commitWrite()
XCTAssertNotNil(object.realm)
XCTAssertEqual(object.objectCol, existingObject)
}
func testAddAndUpdateWithExisingNestedObjects() {
try! Realm().beginWrite()
let existingObject = try! Realm().create(SwiftPrimaryStringObject.self, value: ["primary", 1])
try! Realm().commitWrite()
try! Realm().beginWrite()
let object = SwiftLinkToPrimaryStringObject(value: ["primary", ["primary", 2], []])
try! Realm().add(object, update: true)
try! Realm().commitWrite()
XCTAssertNotNil(object.realm)
XCTAssertEqual(object.object!, existingObject) // the existing object should be updated
XCTAssertEqual(existingObject.intCol, 2)
}
// MARK: Private utilities
private func verifySwiftObjectWithArrayLiteral(_ object: SwiftObject, array: [Any], boolObjectValue: Bool,
boolObjectListValues: [Bool]) {
XCTAssertEqual(object.boolCol, (array[0] as! Bool))
XCTAssertEqual(object.intCol, (array[1] as! Int))
XCTAssertEqual(object.floatCol, (array[2] as! Float))
XCTAssertEqual(object.doubleCol, (array[3] as! Double))
XCTAssertEqual(object.stringCol, (array[4] as! String))
XCTAssertEqual(object.binaryCol, (array[5] as! Data))
XCTAssertEqual(object.dateCol, (array[6] as! Date))
XCTAssertEqual(object.objectCol!.boolCol, boolObjectValue)
XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count)
for i in 0..<boolObjectListValues.count {
XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i])
}
}
private func verifySwiftObjectWithDictionaryLiteral(_ object: SwiftObject, dictionary: [String: Any],
boolObjectValue: Bool, boolObjectListValues: [Bool]) {
XCTAssertEqual(object.boolCol, (dictionary["boolCol"] as! Bool))
XCTAssertEqual(object.intCol, (dictionary["intCol"] as! Int))
XCTAssertEqual(object.floatCol, (dictionary["floatCol"] as! Float))
XCTAssertEqual(object.doubleCol, (dictionary["doubleCol"] as! Double))
XCTAssertEqual(object.stringCol, (dictionary["stringCol"] as! String))
XCTAssertEqual(object.binaryCol, (dictionary["binaryCol"] as! Data))
XCTAssertEqual(object.dateCol, (dictionary["dateCol"] as! Date))
XCTAssertEqual(object.objectCol!.boolCol, boolObjectValue)
XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count)
for i in 0..<boolObjectListValues.count {
XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i])
}
}
private func verifySwiftOptionalObjectWithDictionaryLiteral(_ object: SwiftOptionalDefaultValuesObject,
dictionary: [String: Any],
boolObjectValue: Bool?) {
XCTAssertEqual(object.optBoolCol.value, (dictionary["optBoolCol"] as! Bool?))
XCTAssertEqual(object.optIntCol.value, (dictionary["optIntCol"] as! Int?))
XCTAssertEqual(object.optInt8Col.value,
((dictionary["optInt8Col"] as! NSNumber?)?.int8Value).map({Int8($0)}))
XCTAssertEqual(object.optInt16Col.value,
((dictionary["optInt16Col"] as! NSNumber?)?.int16Value).map({Int16($0)}))
XCTAssertEqual(object.optInt32Col.value,
((dictionary["optInt32Col"] as! NSNumber?)?.int32Value).map({Int32($0)}))
XCTAssertEqual(object.optInt64Col.value, (dictionary["optInt64Col"] as! NSNumber?)?.int64Value)
XCTAssertEqual(object.optFloatCol.value, (dictionary["optFloatCol"] as! Float?))
XCTAssertEqual(object.optDoubleCol.value, (dictionary["optDoubleCol"] as! Double?))
XCTAssertEqual(object.optStringCol, (dictionary["optStringCol"] as! String?))
XCTAssertEqual(object.optNSStringCol, (dictionary["optNSStringCol"] as! NSString))
XCTAssertEqual(object.optBinaryCol, (dictionary["optBinaryCol"] as! Data?))
XCTAssertEqual(object.optDateCol, (dictionary["optDateCol"] as! Date?))
XCTAssertEqual(object.optObjectCol?.boolCol, boolObjectValue)
}
private func defaultSwiftObjectValuesWithReplacements(_ replace: [String: Any]) -> [String: Any] {
var valueDict = SwiftObject.defaultValues()
for (key, value) in replace {
valueDict[key] = value
}
return valueDict
}
// return an array of valid values that can be used to initialize each type
// swiftlint:disable:next cyclomatic_complexity
private func validValuesForSwiftObjectType(_ type: PropertyType) -> [Any] {
try! Realm().beginWrite()
let persistedObject = try! Realm().create(SwiftBoolObject.self, value: [true])
try! Realm().commitWrite()
switch type {
case .bool: return [true, NSNumber(value: 0 as Int), NSNumber(value: 1 as Int)]
case .int: return [NSNumber(value: 1 as Int)]
case .float: return [NSNumber(value: 1 as Int), NSNumber(value: 1.1 as Float), NSNumber(value: 11.1 as Double)]
case .double: return [NSNumber(value: 1 as Int), NSNumber(value: 1.1 as Float), NSNumber(value: 11.1 as Double)]
case .string: return ["b"]
case .data: return ["b".data(using: String.Encoding.utf8, allowLossyConversion: false)!]
case .date: return [Date(timeIntervalSince1970: 2)]
case .object: return [[true], ["boolCol": true], SwiftBoolObject(value: [true]), persistedObject]
case .array: return [
[[true], [false]],
[["boolCol": true], ["boolCol": false]],
[SwiftBoolObject(value: [true]), SwiftBoolObject(value: [false])],
[persistedObject, [false]]
]
case .any: XCTFail("not supported")
case .linkingObjects: XCTFail("not supported")
}
return []
}
// swiftlint:disable:next cyclomatic_complexity
private func invalidValuesForSwiftObjectType(_ type: PropertyType) -> [Any] {
try! Realm().beginWrite()
let persistedObject = try! Realm().create(SwiftIntObject.self)
try! Realm().commitWrite()
switch type {
case .bool: return ["invalid", NSNumber(value: 2 as Int), NSNumber(value: 1.1 as Float), NSNumber(value: 11.1 as Double)]
case .int: return ["invalid", NSNumber(value: 1.1 as Float), NSNumber(value: 11.1 as Double)]
case .float: return ["invalid", true, false]
case .double: return ["invalid", true, false]
case .string: return [0x197A71D, true, false]
case .data: return ["invalid"]
case .date: return ["invalid"]
case .object: return ["invalid", ["a"], ["boolCol": "a"], SwiftIntObject()]
case .array: return ["invalid", [["a"]], [["boolCol" : "a"]], [[SwiftIntObject()]], [[persistedObject]]]
case .any: XCTFail("not supported")
case .linkingObjects: XCTFail("not supported")
}
return []
}
}
#else
class ObjectCreationTests: TestCase {
// MARK: Init tests
func testInitWithDefaults() {
// test all properties are defaults
let object = SwiftObject()
XCTAssertNil(object.realm)
// test defaults values
verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false,
boolObjectListValues: [])
// ensure realm properties are nil for unmanaged object
XCTAssertNil(object.realm)
XCTAssertNil(object.objectCol!.realm)
XCTAssertNil(object.arrayCol.realm)
}
func testInitWithOptionalWithoutDefaults() {
let object = SwiftOptionalObject()
for prop in object.objectSchema.properties {
let value = object[prop.name]
if let value = value as? RLMOptionalBase {
XCTAssertNil(value.underlyingValue)
} else {
XCTAssertNil(value)
}
}
}
func testInitWithOptionalDefaults() {
let object = SwiftOptionalDefaultValuesObject()
verifySwiftOptionalObjectWithDictionaryLiteral(object, dictionary:
SwiftOptionalDefaultValuesObject.defaultValues(), boolObjectValue: true)
}
func testInitWithDictionary() {
// dictionary with all values specified
let baselineValues =
["boolCol": true as NSNumber,
"intCol": 1 as NSNumber,
"floatCol": 1.1 as NSNumber,
"doubleCol": 11.1 as NSNumber,
"stringCol": "b" as NSString,
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 2) as NSDate,
"objectCol": SwiftBoolObject(value: [true]) as AnyObject,
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] as AnyObject
]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[props[propNum].name] = validValue
let object = SwiftObject(value: values)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[props[propNum].name] = invalidValue
assertThrows(SwiftObject(value: values), "Invalid property value")
}
}
}
func testInitWithDefaultsAndDictionary() {
// test with dictionary with mix of default and one specified value
let object = SwiftObject(value: ["intCol": 200])
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(object, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
}
func testInitWithArray() {
// array with all values specified
let baselineValues = [true, 1, 1.1, 11.1, "b", "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
NSDate(timeIntervalSince1970: 2) as NSDate, ["boolCol": true], [[true], [false]]] as [AnyObject]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[propNum] = validValue
let object = SwiftObject(value: values)
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[propNum] = invalidValue
assertThrows(SwiftObject(value: values), "Invalid property value")
}
}
}
func testInitWithKVCObject() {
// test with kvc object
let objectWithInt = SwiftObject(value: ["intCol": 200])
let objectWithKVCObject = SwiftObject(value: objectWithInt)
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
}
func testGenericInit() {
func createObject<T: Object>() -> T {
return T()
}
let obj1: SwiftBoolObject = createObject()
let obj2 = SwiftBoolObject()
XCTAssertEqual(obj1.boolCol, obj2.boolCol,
"object created via generic initializer should equal object created by calling initializer directly")
}
// MARK: Creation tests
func testCreateWithDefaults() {
let realm = try! Realm()
assertThrows(realm.create(SwiftObject), "Must be in write transaction")
var object: SwiftObject!
let objects = realm.objects(SwiftObject.self)
XCTAssertEqual(0, objects.count)
try! realm.write {
// test create with all defaults
object = realm.create(SwiftObject)
return
}
verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false,
boolObjectListValues: [])
// test realm properties are populated correctly
XCTAssertEqual(object.realm!, realm)
XCTAssertEqual(object.objectCol!.realm!, realm)
XCTAssertEqual(object.arrayCol.realm!, realm)
}
func testCreateWithOptionalWithoutDefaults() {
let realm = try! Realm()
try! realm.write {
let object = realm.create(SwiftOptionalObject)
for prop in object.objectSchema.properties {
XCTAssertNil(object[prop.name])
}
}
}
func testCreateWithOptionalDefaults() {
let realm = try! Realm()
try! realm.write {
let object = realm.create(SwiftOptionalDefaultValuesObject)
self.verifySwiftOptionalObjectWithDictionaryLiteral(object,
dictionary: SwiftOptionalDefaultValuesObject.defaultValues(), boolObjectValue: true)
}
}
func testCreateWithOptionalIgnoredProperties() {
let realm = try! Realm()
try! realm.write {
let object = realm.create(SwiftOptionalIgnoredPropertiesObject)
let properties = object.objectSchema.properties
XCTAssertEqual(properties.count, 1)
XCTAssertEqual(properties[0].name, "id")
}
}
func testCreateWithDictionary() {
// dictionary with all values specified
let baselineValues: [String: AnyObject] = [
"boolCol": true,
"intCol": 1,
"floatCol": 1.1,
"doubleCol": 11.1,
"stringCol": "b",
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)!,
"dateCol": NSDate(timeIntervalSince1970: 2),
"objectCol": SwiftBoolObject(value: [true]),
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()]
]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[props[propNum].name] = validValue
try! Realm().beginWrite()
let object = try! Realm().create(SwiftObject.self, value: values)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
try! Realm().commitWrite()
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[props[propNum].name] = invalidValue
try! Realm().beginWrite()
assertThrows(try! Realm().create(SwiftObject.self, value: values), "Invalid property value")
try! Realm().cancelWrite()
}
}
}
func testCreateWithDefaultsAndDictionary() {
// test with dictionary with mix of default and one specified value
let realm = try! Realm()
realm.beginWrite()
let objectWithInt = realm.create(SwiftObject.self, value: ["intCol": 200])
try! realm.commitWrite()
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(objectWithInt, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
}
func testCreateWithArray() {
// array with all values specified
let baselineValues = [true, 1, 1.1, 11.1, "b", "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
NSDate(timeIntervalSince1970: 2) as NSDate, ["boolCol": true], [[true], [false]]] as [AnyObject]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[propNum] = validValue
try! Realm().beginWrite()
let object = try! Realm().create(SwiftObject.self, value: values)
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true,
boolObjectListValues: [true, false])
try! Realm().commitWrite()
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid array literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[propNum] = invalidValue
try! Realm().beginWrite()
assertThrows(try! Realm().create(SwiftObject.self, value: values),
"Invalid property value '\(invalidValue)' for property number \(propNum)")
try! Realm().cancelWrite()
}
}
}
func testCreateWithKVCObject() {
// test with kvc object
try! Realm().beginWrite()
let objectWithInt = try! Realm().create(SwiftObject.self, value: ["intCol": 200])
let objectWithKVCObject = try! Realm().create(SwiftObject.self, value: objectWithInt)
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
try! Realm().commitWrite()
verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
XCTAssertEqual(try! Realm().objects(SwiftObject.self).count, 2, "Object should have been copied")
}
func testCreateWithNestedObjects() {
let unmanaged = SwiftPrimaryStringObject(value: ["p0", 11])
try! Realm().beginWrite()
let objectWithNestedObjects = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p1", ["p1", 11],
[unmanaged]])
try! Realm().commitWrite()
let stringObjects = try! Realm().objects(SwiftPrimaryStringObject.self)
XCTAssertEqual(stringObjects.count, 2)
let managedObject = stringObjects.first!
// unmanaged object should be copied into the Realm, not added directly
XCTAssertNotEqual(unmanaged, managedObject)
XCTAssertEqual(objectWithNestedObjects.object!, managedObject)
XCTAssertEqual(objectWithNestedObjects.objects.first!, stringObjects.last!)
let unmanaged1 = SwiftPrimaryStringObject(value: ["p3", 11])
try! Realm().beginWrite()
assertThrows(try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p3", ["p3", 11], [unmanaged1]]),
"Should throw with duplicate primary key")
try! Realm().commitWrite()
}
func testUpdateWithNestedObjects() {
let unmanaged = SwiftPrimaryStringObject(value: ["primary", 11])
try! Realm().beginWrite()
let object = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["otherPrimary", ["primary", 12],
[["primary", 12]]], update: true)
try! Realm().commitWrite()
let stringObjects = try! Realm().objects(SwiftPrimaryStringObject.self)
XCTAssertEqual(stringObjects.count, 1)
let managedObject = object.object!
XCTAssertEqual(managedObject.intCol, 12)
XCTAssertNil(unmanaged.realm) // the unmanaged object should be copied, rather than added, to the realm
XCTAssertEqual(object.object!, managedObject)
XCTAssertEqual(object.objects.first!, managedObject)
}
func testCreateWithObjectsFromAnotherRealm() {
let values = [
"boolCol": true as NSNumber,
"intCol": 1 as NSNumber,
"floatCol": 1.1 as NSNumber,
"doubleCol": 11.1 as NSNumber,
"stringCol": "b" as NSString,
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 2) as NSDate,
"objectCol": SwiftBoolObject(value: [true]) as AnyObject,
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] as AnyObject,
]
realmWithTestPath().beginWrite()
let otherRealmObject = realmWithTestPath().create(SwiftObject.self, value: values)
try! realmWithTestPath().commitWrite()
try! Realm().beginWrite()
let object = try! Realm().create(SwiftObject.self, value: otherRealmObject)
try! Realm().commitWrite()
XCTAssertNotEqual(otherRealmObject, object)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
func testCreateWithDeeplyNestedObjectsFromAnotherRealm() {
let values = [
"boolCol": true as NSNumber,
"intCol": 1 as NSNumber,
"floatCol": 1.1 as NSNumber,
"doubleCol": 11.1 as NSNumber,
"stringCol": "b" as NSString,
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 2) as NSDate,
"objectCol": SwiftBoolObject(value: [true]) as AnyObject,
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] as AnyObject,
]
let realmA = realmWithTestPath()
let realmB = try! Realm()
var realmAObject: SwiftListOfSwiftObject!
try! realmA.write {
let array = [SwiftObject(value: values), SwiftObject(value: values)]
realmAObject = realmA.create(SwiftListOfSwiftObject.self, value: ["array": array])
}
var realmBObject: SwiftListOfSwiftObject!
try! realmB.write {
realmBObject = realmB.create(SwiftListOfSwiftObject.self, value: realmAObject)
}
XCTAssertNotEqual(realmAObject, realmBObject)
XCTAssertEqual(realmBObject.array.count, 2)
for swiftObject in realmBObject.array {
verifySwiftObjectWithDictionaryLiteral(swiftObject, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
func testUpdateWithObjectsFromAnotherRealm() {
realmWithTestPath().beginWrite()
let otherRealmObject = realmWithTestPath().create(SwiftLinkToPrimaryStringObject.self,
value: ["primary", NSNull(), [["2", 2], ["4", 4]]])
try! realmWithTestPath().commitWrite()
try! Realm().beginWrite()
try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["primary", ["10", 10], [["11", 11]]])
let object = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: otherRealmObject, update: true)
try! Realm().commitWrite()
XCTAssertNotEqual(otherRealmObject, object) // the object from the other realm should be copied into this realm
XCTAssertEqual(try! Realm().objects(SwiftLinkToPrimaryStringObject.self).count, 1)
XCTAssertEqual(try! Realm().objects(SwiftPrimaryStringObject.self).count, 4)
}
func testCreateWithNSNullLinks() {
let values = [
"boolCol": true as NSNumber,
"intCol": 1 as NSNumber,
"floatCol": 1.1 as NSNumber,
"doubleCol": 11.1 as NSNumber,
"stringCol": "b" as NSString,
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 2) as NSDate,
"objectCol": NSNull(),
"arrayCol": NSNull(),
]
realmWithTestPath().beginWrite()
let object = realmWithTestPath().create(SwiftObject.self, value: values)
try! realmWithTestPath().commitWrite()
XCTAssert(object.objectCol == nil) // XCTAssertNil caused a NULL deref inside _swift_getClass
XCTAssertEqual(object.arrayCol.count, 0)
}
// test null object
// test null list
// MARK: Add tests
func testAddWithExisingNestedObjects() {
try! Realm().beginWrite()
let existingObject = try! Realm().create(SwiftBoolObject)
try! Realm().commitWrite()
try! Realm().beginWrite()
let object = SwiftObject(value: ["objectCol" : existingObject])
try! Realm().add(object)
try! Realm().commitWrite()
XCTAssertNotNil(object.realm)
XCTAssertEqual(object.objectCol, existingObject)
}
func testAddAndUpdateWithExisingNestedObjects() {
try! Realm().beginWrite()
let existingObject = try! Realm().create(SwiftPrimaryStringObject.self, value: ["primary", 1])
try! Realm().commitWrite()
try! Realm().beginWrite()
let object = SwiftLinkToPrimaryStringObject(value: ["primary", ["primary", 2], []])
try! Realm().add(object, update: true)
try! Realm().commitWrite()
XCTAssertNotNil(object.realm)
XCTAssertEqual(object.object!, existingObject) // the existing object should be updated
XCTAssertEqual(existingObject.intCol, 2)
}
func testAddWithNumericOptionalPrimaryKeyProperty() {
let realm = try! Realm()
realm.beginWrite()
let object = SwiftPrimaryOptionalIntObject()
object.intCol.value = 1
realm.add(object, update: true)
let nilObject = SwiftPrimaryOptionalIntObject()
nilObject.intCol.value = nil
realm.add(nilObject, update: true)
try! realm.commitWrite()
XCTAssertNotNil(object.realm)
XCTAssertNotNil(nilObject.realm)
}
// MARK: Private utilities
private func verifySwiftObjectWithArrayLiteral(object: SwiftObject, array: [AnyObject], boolObjectValue: Bool,
boolObjectListValues: [Bool]) {
XCTAssertEqual(object.boolCol, (array[0] as! Bool))
XCTAssertEqual(object.intCol, (array[1] as! Int))
XCTAssertEqual(object.floatCol, (array[2] as! Float))
XCTAssertEqual(object.doubleCol, (array[3] as! Double))
XCTAssertEqual(object.stringCol, (array[4] as! String))
XCTAssertEqual(object.binaryCol, (array[5] as! NSData))
XCTAssertEqual(object.dateCol, (array[6] as! NSDate))
XCTAssertEqual(object.objectCol!.boolCol, boolObjectValue)
XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count)
for i in 0..<boolObjectListValues.count {
XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i])
}
}
private func verifySwiftObjectWithDictionaryLiteral(object: SwiftObject, dictionary: [String:AnyObject],
boolObjectValue: Bool, boolObjectListValues: [Bool]) {
XCTAssertEqual(object.boolCol, (dictionary["boolCol"] as! Bool))
XCTAssertEqual(object.intCol, (dictionary["intCol"] as! Int))
XCTAssertEqual(object.floatCol, (dictionary["floatCol"] as! Float))
XCTAssertEqual(object.doubleCol, (dictionary["doubleCol"] as! Double))
XCTAssertEqual(object.stringCol, (dictionary["stringCol"] as! String))
XCTAssertEqual(object.binaryCol, (dictionary["binaryCol"] as! NSData))
XCTAssertEqual(object.dateCol, (dictionary["dateCol"] as! NSDate))
XCTAssertEqual(object.objectCol!.boolCol, boolObjectValue)
XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count)
for i in 0..<boolObjectListValues.count {
XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i])
}
}
private func verifySwiftOptionalObjectWithDictionaryLiteral(object: SwiftOptionalDefaultValuesObject,
dictionary: [String:AnyObject],
boolObjectValue: Bool?) {
XCTAssertEqual(object.optBoolCol.value, (dictionary["optBoolCol"] as! Bool?))
XCTAssertEqual(object.optIntCol.value, (dictionary["optIntCol"] as! Int?))
XCTAssertEqual(object.optInt8Col.value,
((dictionary["optInt8Col"] as! NSNumber?)?.longValue).map({Int8($0)}))
XCTAssertEqual(object.optInt16Col.value,
((dictionary["optInt16Col"] as! NSNumber?)?.longValue).map({Int16($0)}))
XCTAssertEqual(object.optInt32Col.value,
((dictionary["optInt32Col"] as! NSNumber?)?.longValue).map({Int32($0)}))
XCTAssertEqual(object.optInt64Col.value, (dictionary["optInt64Col"] as! NSNumber?)?.longLongValue)
XCTAssertEqual(object.optFloatCol.value, (dictionary["optFloatCol"] as! Float?))
XCTAssertEqual(object.optDoubleCol.value, (dictionary["optDoubleCol"] as! Double?))
XCTAssertEqual(object.optStringCol, (dictionary["optStringCol"] as! String?))
XCTAssertEqual(object.optNSStringCol, (dictionary["optNSStringCol"] as! String?))
XCTAssertEqual(object.optBinaryCol, (dictionary["optBinaryCol"] as! NSData?))
XCTAssertEqual(object.optDateCol, (dictionary["optDateCol"] as! NSDate?))
XCTAssertEqual(object.optObjectCol?.boolCol, boolObjectValue)
}
private func defaultSwiftObjectValuesWithReplacements(replace: [String: AnyObject]) -> [String: AnyObject] {
var valueDict = SwiftObject.defaultValues()
for (key, value) in replace {
valueDict[key] = value
}
return valueDict
}
// return an array of valid values that can be used to initialize each type
// swiftlint:disable:next cyclomatic_complexity
private func validValuesForSwiftObjectType(type: PropertyType) -> [AnyObject] {
try! Realm().beginWrite()
let managedObject = try! Realm().create(SwiftBoolObject.self, value: [true])
try! Realm().commitWrite()
switch type {
case .Bool: return [true, 0 as Int, 1 as Int]
case .Int: return [1 as Int]
case .Float: return [1 as Int, 1.1 as Float, 11.1 as Double]
case .Double: return [1 as Int, 1.1 as Float, 11.1 as Double]
case .String: return ["b"]
case .Data: return ["b".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! as NSData]
case .Date: return [NSDate(timeIntervalSince1970: 2) as AnyObject]
case .Object: return [[true], ["boolCol": true], SwiftBoolObject(value: [true]), managedObject]
case .Array: return [
[[true], [false]],
[["boolCol": true], ["boolCol": false]],
[SwiftBoolObject(value: [true]), SwiftBoolObject(value: [false])],
[managedObject, [false]]
]
case .Any: XCTFail("not supported")
case .LinkingObjects: XCTFail("not supported")
}
return []
}
// swiftlint:disable:next cyclomatic_complexity
private func invalidValuesForSwiftObjectType(type: PropertyType) -> [AnyObject] {
try! Realm().beginWrite()
let managedObject = try! Realm().create(SwiftIntObject)
try! Realm().commitWrite()
switch type {
case .Bool: return ["invalid", 2 as Int, 1.1 as Float, 11.1 as Double]
case .Int: return ["invalid", 1.1 as Float, 11.1 as Double]
case .Float: return ["invalid", true, false]
case .Double: return ["invalid", true, false]
case .String: return [0x197A71D, true, false]
case .Data: return ["invalid"]
case .Date: return ["invalid"]
case .Object: return ["invalid", ["a"], ["boolCol": "a"], SwiftIntObject()]
case .Array: return ["invalid", [["a"]], [["boolCol" : "a"]], [[SwiftIntObject()]], [[managedObject]]]
case .Any: XCTFail("not supported")
case .LinkingObjects: XCTFail("not supported")
}
return []
}
}
#endif
| mit |
VanHack/binners-project-ios | ios-binners-project/UIImage+Extension.swift | 1 | 1263 | //
// UIImage+Extension.swift
// ios-binners-project
//
// Created by Matheus Ruschel on 4/11/16.
// Copyright © 2016 Rodrigo de Souza Reis. All rights reserved.
//
import Foundation
extension UIImage {
func makeImageWithColorAndSize(_ color: UIColor, size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
func imageWithColor(_ color:UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, self.scale)
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0, y: self.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(CGBlendMode.normal)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
context?.clip(to: rect, mask: self.cgImage!)
color.setFill()
context?.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
| mit |
hansemannn/studentenfutter-app | extensions/Mensa/Mensa/ViewController.swift | 1 | 483 | //
// ViewController.swift
// Mensa
//
// Created by Hans Knöchel on 02.07.18.
// Copyright © 2018 Hans Knöchel. 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 |
cnoon/swift-compiler-crashes | fixed/26699-swift-expr-walk.swift | 7 | 220 | // 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 B<T where B:T{var b=nil
class d<b:a func a<e
| mit |
wenluma/swift | test/Generics/protocol_type_aliases.swift | 5 | 4258 | // RUN: %target-typecheck-verify-swift -typecheck %s
// RUN: %target-typecheck-verify-swift -typecheck -debug-generic-signatures %s > %t.dump 2>&1
// RUN: %FileCheck %s < %t.dump
func sameType<T>(_: T.Type, _: T.Type) {}
protocol P {
associatedtype A // expected-note{{'A' declared here}}
typealias X = A
}
protocol Q {
associatedtype B: P
}
// CHECK-LABEL: .requirementOnNestedTypeAlias@
// CHECK-NEXT: Requirements:
// CHECK-NEXT: τ_0_0 : Q [τ_0_0: Explicit @ 22:51]
// CHECK-NEXT: τ_0_0[.Q].B : P [τ_0_0: Explicit @ 22:51 -> Protocol requirement (via Self.B in Q)
// CHECK-NEXT: τ_0_0[.Q].B[.P].A == Int [τ_0_0[.Q].B[.P].X: Explicit @ 22:62]
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Q, τ_0_0.B.A == Int>
func requirementOnNestedTypeAlias<T>(_: T) where T: Q, T.B.X == Int {}
struct S<T> {}
protocol P2 {
associatedtype A
typealias X = S<A>
}
protocol Q2 {
associatedtype B: P2
associatedtype C
}
// CHECK-LABEL: .requirementOnConcreteNestedTypeAlias@
// CHECK-NEXT: Requirements:
// CHECK-NEXT: τ_0_0 : Q2 [τ_0_0: Explicit @ 42:59]
// CHECK-NEXT: τ_0_0[.Q2].B : P2 [τ_0_0: Explicit @ 42:59 -> Protocol requirement (via Self.B in Q2)
// CHECK-NEXT: τ_0_0[.Q2].C == S<T.B.A> [τ_0_0[.Q2].C: Explicit]
// CHECK-NEXT: τ_0_0[.Q2].B[.P2].X == S<T.B.A> [τ_0_0[.Q2].B[.P2].X: Concrete type binding]
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Q2, τ_0_0.C == S<τ_0_0.B.A>>
func requirementOnConcreteNestedTypeAlias<T>(_: T) where T: Q2, T.C == T.B.X {}
// CHECK-LABEL: .concreteRequirementOnConcreteNestedTypeAlias@
// CHECK-NEXT: Requirements:
// CHECK-NEXT: τ_0_0 : Q2 [τ_0_0: Explicit @ 51:67]
// CHECK-NEXT: τ_0_0[.Q2].B : P2 [τ_0_0: Explicit @ 51:67 -> Protocol requirement (via Self.B in Q2)
// CHECK-NEXT: τ_0_0[.Q2].C == τ_0_0[.Q2].B[.P2].A [τ_0_0[.Q2].C: Explicit]
// CHECK-NEXT: τ_0_0[.Q2].B[.P2].X == S<T.B.A> [τ_0_0[.Q2].B[.P2].X: Concrete type binding]
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Q2, τ_0_0.C == τ_0_0.B.A>
func concreteRequirementOnConcreteNestedTypeAlias<T>(_: T) where T: Q2, S<T.C> == T.B.X {}
// Incompatible concrete typealias types are flagged as such
protocol P3 {
typealias T = Int
}
protocol Q3: P3 { // expected-error{{generic signature requires types 'Int'}}
typealias T = Float
}
protocol P3_1 {
typealias T = Float
}
protocol Q3_1: P3, P3_1 {} // expected-error{{generic signature requires types 'Float'}}
// Subprotocols can force associated types in their parents to be concrete, and
// this should be understood for types constrained by the subprotocols.
protocol Q4: P {
typealias A = Int // expected-warning{{typealias overriding associated type 'A' from protocol 'P'}}
}
protocol Q5: P {
typealias X = Int
}
// fully generic functions that manipulate the archetypes in a P
func getP_A<T: P>(_: T.Type) -> T.A.Type { return T.A.self }
func getP_X<T: P>(_: T.Type) -> T.X.Type { return T.X.self }
// ... which we use to check if the compiler is following through the concrete
// same-type constraints implied by the subprotocols.
func checkQ4_A<T: Q4>(x: T.Type) { sameType(getP_A(x), Int.self) }
func checkQ4_X<T: Q4>(x: T.Type) { sameType(getP_X(x), Int.self) }
// FIXME: these do not work, seemingly mainly due to the 'recursive decl validation'
// FIXME in GenericSignatureBuilder.cpp.
/*
func checkQ5_A<T: Q5>(x: T.Type) { sameType(getP_A(x), Int.self) }
func checkQ5_X<T: Q5>(x: T.Type) { sameType(getP_X(x), Int.self) }
*/
// Typealiases happen to allow imposing same type requirements between parent
// protocols
protocol P6_1 {
associatedtype A // expected-note{{'A' declared here}}
}
protocol P6_2 {
associatedtype B
}
protocol Q6: P6_1, P6_2 {
typealias A = B // expected-warning{{typealias overriding associated type}}
}
func getP6_1_A<T: P6_1>(_: T.Type) -> T.A.Type { return T.A.self }
func getP6_2_B<T: P6_2>(_: T.Type) -> T.B.Type { return T.B.self }
func checkQ6<T: Q6>(x: T.Type) {
sameType(getP6_1_A(x), getP6_2_B(x))
}
protocol P7 {
typealias A = Int
}
protocol P7a : P7 {
associatedtype A // expected-warning{{associated type 'A' is redundant with type 'A' declared in inherited protocol 'P7'}}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/23751-swift-sildeserializer-readsilinstruction.swift | 10 | 216 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
}func f : p}}Void{typealias e = j> Void{>:b(){
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/17108-no-stacktrace.swift | 11 | 234 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol P {
let start = {
func d {
( [ {
if true {
class
case ,
| mit |
hadibadjian/GAlileo | planets/Planets/PlanetEntity+CoreDataProperties.swift | 1 | 505 | //
// PlanetEntity+CoreDataProperties.swift
// Planets
//
// Created by HB on 06/06/2016.
// Copyright © 2016 HB. 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 PlanetEntity {
@NSManaged var title: String?
@NSManaged var desc: String?
@NSManaged var icon: String?
@NSManaged var favorite: NSNumber?
}
| mit |
ealeksandrov/SomaFM-miniplayer | Source/Networking/MusicSearchAPI.swift | 1 | 1898 | //
// MusicSearchAPI.swift
//
// Copyright © 2017 Evgeny Aleksandrov. All rights reserved.
import Foundation
public struct MusicSearchAPI {
static var trackSearchURL: URL?
static func searchTrack() {
trackSearchURL = nil
searchItunes()
}
}
private extension MusicSearchAPI {
// MARK: - Networking
struct SearchResultsList: Codable {
let results: [SearchResult]
}
static func searchItunes() {
guard let trackName = RadioPlayer.currentTrack else { return }
var iTunesSearchURL = URLComponents(string: "https://itunes.apple.com/search")!
iTunesSearchURL.queryItems = [URLQueryItem(name: "term", value: trackName),
URLQueryItem(name: "entity", value: "song"),
URLQueryItem(name: "limit", value: "1"),
URLQueryItem(name: "at", value: "1000lHGx")]
guard let finalURL = iTunesSearchURL.url else { fallbackToGoogle(); return }
let session = URLSession(configuration: URLSessionConfiguration.default)
let request = URLRequest(url: finalURL)
session.dataTask(with: request) { data, _, _ in
guard let data = data else { fallbackToGoogle(); return }
if let channelList = try? JSONDecoder().decode(SearchResultsList.self, from: data), let resultURL = channelList.results.first?.trackViewUrl {
trackSearchURL = resultURL
} else {
fallbackToGoogle()
Log.error("iTunesSearch: error")
}
}.resume()
}
static func fallbackToGoogle() {
guard let trackName = RadioPlayer.currentTrack?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return }
trackSearchURL = URL(string: "https://www.google.ru/search?q=" + trackName)
}
}
| mit |
abu0306/CnPhoto | CnPhotoTests/CnPhotoTests.swift | 1 | 957 | //
// CnPhotoTests.swift
// CnPhotoTests
//
// Created by abu on 2017/8/7.
// Copyright © 2017年 abu. All rights reserved.
//
import XCTest
@testable import CnPhoto
class CnPhotoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
avito-tech/Marshroute | Marshroute/Sources/Transitions/TransitionAnimations/ModalEndpointNavigation/Presentation/ModalEndpointNavigationPresentationAnimationContext.swift | 1 | 1593 | import UIKit
/// Описание параметров анимаций прямого модального перехода на конечный UINavigationController,
/// например, на MFMailComposeViewController, UIImagePickerController
public struct ModalEndpointNavigationPresentationAnimationContext {
/// навигационный контроллер, на который нужно осуществить прямой модальный переход
public let targetNavigationController: UINavigationController
/// контроллер, с которого нужно осуществить прямой модальный переход
public let sourceViewController: UIViewController
public init(
targetNavigationController: UINavigationController,
sourceViewController: UIViewController)
{
self.targetNavigationController = targetNavigationController
self.sourceViewController = sourceViewController
}
public init?(
modalEndpointNavigationPresentationAnimationLaunchingContext animationLaunchingContext: ModalEndpointNavigationPresentationAnimationLaunchingContext)
{
guard let targetNavigationController = animationLaunchingContext.targetNavigationController
else { return nil }
guard let sourceViewController = animationLaunchingContext.sourceViewController
else { return nil }
self.targetNavigationController = targetNavigationController
self.sourceViewController = sourceViewController
}
}
| mit |
tardieu/swift | validation-test/compiler_crashers_fixed/25861-swift-printingdiagnosticconsumer-handlediagnostic.swift | 65 | 472 | // 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
init{struct c{
class T{
({
{
{
{((
{{
}[{
({
c"
}}
{
class A{
class
case,
| apache-2.0 |
tardieu/swift | test/PrintAsObjC/swift_name.swift | 5 | 1883 | // Please keep this file in alphabetical order!
// REQUIRES: objc_interop
// RUN: rm -rf %t && mkdir -p %t
// FIXME: BEGIN -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/Foundation.swift
// FIXME: END -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -import-objc-header %S/Inputs/swift_name.h -emit-module -o %t %s
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -import-objc-header %S/Inputs/swift_name.h -parse-as-library %t/swift_name.swiftmodule -typecheck -emit-objc-header-path %t/swift_name.h
// RUN: %FileCheck %s < %t/swift_name.h
// RUN: %check-in-clang %t/swift_name.h
import Foundation
// CHECK-LABEL: @interface Test : NSObject
// CHECK-NEXT: - (NSArray<ABCStringAlias> * _Nonnull)makeArray:(ABCStringAlias _Nonnull)_ SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (void)usePoint:(struct ABCPoint)_;
// CHECK-NEXT: - (void)useAlignment:(enum ABCAlignment)_;
// CHECK-NEXT: - (NSArray<id <ABCProto>> * _Nonnull)useObjects:(ABCClass * _Nonnull)_ SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: @end
class Test : NSObject {
func makeArray(_: ZZStringAlias) -> [ZZStringAlias] { return [] }
func usePoint(_: ZZPoint) {}
func useAlignment(_: ZZAlignment) {}
func useObjects(_: ZZClass) -> [ZZProto] { return [] }
}
| apache-2.0 |
kang77649119/DouYuDemo | DouYuDemo/DouYuDemo/Classes/Main/View/CollectionPrettyCell.swift | 1 | 973 | //
// CollectionPrettyCell.swift
// DouYuDemo
//
// Created by 也许、 on 16/10/9.
// Copyright © 2016年 K. All rights reserved.
//
import UIKit
import SDWebImage
class CollectionPrettyCell: UICollectionViewCell {
@IBOutlet weak var iconImg: UIImageView!
@IBOutlet weak var nickNameBtn: UIButton!
@IBOutlet weak var onLineLabel: UILabel!
var anchor : Anchor? {
didSet {
self.iconImg.sd_setImage(with: URL(string: anchor!.vertical_src), placeholderImage: UIImage(named: "live_cell_default_phone"))
self.nickNameBtn.setTitle(anchor!.nickname, for: .normal)
if anchor!.online >= 10000 {
self.onLineLabel.text = String(format: "%d.%d万", anchor!.online / 10000 , anchor!.online % 10000 / 1000)
} else {
self.onLineLabel.text = "\(anchor!.online)"
}
}
}
}
| mit |
raykle/CustomTransition | CustomModelTransition/CustomModelTransition/PresentedViewController.swift | 1 | 409 | //
// PresentedViewController.swift
// CustomModelTransition
//
// Created by guomin on 16/3/16.
// Copyright © 2016年 iBinaryOrg. All rights reserved.
//
import UIKit
class PresentedViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func dismissAction() {
self.dismissViewControllerAnimated(true, completion: nil)
}
} | mit |
galv/reddift | reddift/Network/Session+links.swift | 1 | 14584 | //
// Session+links.swift
// reddift
//
// Created by sonson on 2015/05/19.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
extension Session {
/**
Submit a new comment or reply to a message, whose parent is the fullname of the thing being replied to.
Its value changes the kind of object created by this request:
- the fullname of a Link: a top-level comment in that Link's thread.
- the fullname of a Comment: a comment reply to that comment.
- the fullname of a Message: a message reply to that message.
Response is JSON whose type is t1 Thing.
- parameter text: The body of comment, should be the raw markdown body of the comment or message.
- parameter parentName: Name of Thing is commented or replied to.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func postComment(text:String, parentName:String, completion:(Result<Comment>) -> Void) -> NSURLSessionDataTask? {
let parameter:[String:String] = ["thing_id":parentName, "api_type":"json", "text":text]
guard let request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/comment", parameter:parameter, method:"POST", token:token) else { return nil }
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
self.updateRateLimitWithURLResponse(response)
let result = resultFromOptionalError(Response(data: data, urlResponse: response), optionalError:error)
.flatMap(response2Data)
.flatMap(data2Json)
.flatMap(json2Comment)
completion(result)
})
task.resume()
return task
}
/**
Delete a Link or Comment.
- parameter thing: Thing object to be deleted.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func deleteCommentOrLink(name:String, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
let parameter:[String:String] = ["id":name]
guard let request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/del", parameter:parameter, method:"POST", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
/**
Vote specified thing.
- parameter direction: The type of voting direction as VoteDirection.
- parameter thing: Thing will be voted.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func setVote(direction:VoteDirection, name:String, completion:(Result<JSON>) -> Void) -> NSURLSessionDataTask? {
let parameter:[String:String] = ["dir":String(direction.rawValue), "id":name]
guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/vote", parameter:parameter, method:"POST", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
/**
Save a specified content.
- parameter save: If you want to save the content, set to "true". On the other, if you want to remove the content from saved content, set to "false".
- parameter name: Name of Thing will be saved/unsaved.
- parameter category: Name of category into which you want to saved the content
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func setSave(save:Bool, name:String, category:String = "", completion:(Result<JSON>) -> Void) -> NSURLSessionDataTask? {
var parameter:[String:String] = ["id":name]
if !category.characters.isEmpty {
parameter["category"] = category
}
var request:NSMutableURLRequest! = nil
if save {
request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/save", parameter:parameter, method:"POST", token:token)
}
else {
request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/unsave", parameter:parameter, method:"POST", token:token)
}
return handleAsJSONRequest(request, completion:completion)
}
/**
Set hide/show a specified content.
- parameter save: If you want to hide the content, set to "true". On the other, if you want to show the content, set to "false".
- parameter name: Name of Thing will be hide/show.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func setHide(hide:Bool, name:String, completion:(Result<JSON>) -> Void) -> NSURLSessionDataTask? {
let parameter:[String:String] = ["id":name]
var request:NSMutableURLRequest! = nil
if hide {
request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/hide", parameter:parameter, method:"POST", token:token)
}
else {
request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/unhide", parameter:parameter, method:"POST", token:token)
}
return handleAsJSONRequest(request, completion:completion)
}
/**
Return a listing of things specified by their fullnames.
Only Links, Comments, and Subreddits are allowed.
- parameter names: Array of contents' fullnames.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func getInfo(names:[String], completion:(Result<Listing>) -> Void) -> NSURLSessionDataTask? {
let commaSeparatedNameString = commaSeparatedStringFromList(names)
guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/info", parameter:["id":commaSeparatedNameString], method:"GET", token:token) else { return nil }
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
self.updateRateLimitWithURLResponse(response)
let result = resultFromOptionalError(Response(data: data, urlResponse: response), optionalError:error)
.flatMap(response2Data)
.flatMap(data2Json)
.flatMap(json2RedditAny)
.flatMap({
(redditAny: RedditAny) -> Result<Listing> in
if let listing = redditAny as? Listing {
return Result(value: listing)
}
return Result(error: ReddiftError.Malformed.error)
})
completion(result)
})
task.resume()
return task
}
/**
Mark or unmark a link NSFW.
- parameter thing: Thing object, to set fullname of a thing.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func setNSFW(mark:Bool, thing:Thing, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
var path = "/api/unmarknsfw"
if mark {
path = "/api/marknsfw"
}
guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:path, parameter:["id":thing.name], method:"POST", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
// MARK: BDT does not cover following methods.
/**
Get a list of categories in which things are currently saved.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func getSavedCategories(completion:(Result<JSON>) -> Void) -> NSURLSessionDataTask? {
guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/saved_categories", method:"GET", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
/**
Report a link, comment or message.
Reporting a thing brings it to the attention of the subreddit's moderators. Reporting a message sends it to a system for admin review.
For links and comments, the thing is implicitly hidden as well.
- parameter thing: Thing object, to set fullname of a thing.
- parameter reason: Reason of a string no longer than 100 characters.
- parameter otherReason: The other reason of a string no longer than 100 characters.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func report(thing:Thing, reason:String, otherReason:String, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
let parameter = [
"api_type" :"json",
"reason" :reason,
"other_reason":otherReason,
"thing_id" :thing.name]
guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/report", parameter:parameter, method:"POST", token:token) else { return nil }
return handleRequest(request, completion:completion)
}
/**
Submit a link to a subreddit.
- parameter subreddit: The subreddit to which is submitted a link.
- parameter title: The title of the submission. up to 300 characters long.
- parameter URL: A valid URL
- parameter captcha: The user's response to the CAPTCHA challenge
- parameter captchaIden: The identifier of the CAPTCHA challenge
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func submitLink(subreddit:Subreddit, title:String, URL:String, captcha:String, captchaIden:String, completion:(Result<JSON>) -> Void) -> NSURLSessionDataTask? {
var parameter:[String:String] = [:]
parameter["api_type"] = "json"
parameter["captcha"] = captcha
parameter["iden"] = captchaIden
parameter["kind"] = "link"
parameter["resubmit"] = "true"
parameter["sendreplies"] = "true"
parameter["sr"] = subreddit.displayName
parameter["title"] = title
parameter["url"] = URL
guard let request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/submit", parameter:parameter, method:"POST", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
/**
Submit a text to a subreddit.
Response JSON is, {"json":{"data":{"id":"35ljt6","name":"t3_35ljt6","url":"https://www.reddit.com/r/sandboxtest/comments/35ljt6/this_is_test/"},"errors":[]}}
- parameter subreddit: The subreddit to which is submitted a link.
- parameter title: The title of the submission. up to 300 characters long.
- parameter text: Raw markdown text
- parameter captcha: The user's response to the CAPTCHA challenge
- parameter captchaIden: The identifier of the CAPTCHA challenge
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func submitText(subreddit:Subreddit, title:String, text:String, captcha:String, captchaIden:String, completion:(Result<JSON>) -> Void) -> NSURLSessionDataTask? {
var parameter:[String:String] = [:]
parameter["api_type"] = "json"
parameter["captcha"] = captcha
parameter["iden"] = captchaIden
parameter["kind"] = "self"
parameter["resubmit"] = "true"
parameter["sendreplies"] = "true"
parameter["sr"] = subreddit.displayName
parameter["text"] = text
parameter["title"] = title
guard let request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/submit", parameter:parameter, method:"POST", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
/**
Retrieve additional comments omitted from a base comment tree. When a comment tree is rendered, the most relevant comments are selected for display first. Remaining comments are stubbed out with "MoreComments" links. This API call is used to retrieve the additional comments represented by those stubs, up to 20 at a time. The two core parameters required are link and children. link is the fullname of the link whose comments are being fetched. children is a comma-delimited list of comment ID36s that need to be fetched. If id is passed, it should be the ID of the MoreComments object this call is replacing. This is needed only for the HTML UI's purposes and is optional otherwise. NOTE: you may only make one request at a time to this API endpoint. Higher concurrency will result in an error being returned.
- parameter children: A comma-delimited list of comment ID36s.
- parameter link: Thing object from which you get more children.
- parameter sort: The type of sorting children.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func getMoreChildren(children:[String], link:Link, sort:CommentSort, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
let commaSeparatedChildren = commaSeparatedStringFromList(children)
let parameter = ["children":commaSeparatedChildren, "link_id":link.name, "sort":sort.type, "api_type":"json"]
guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/morechildren", parameter:parameter, method:"GET", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
} | mit |
logkit/logkit | Sources/FileEndpoints.swift | 1 | 24826 | // FileEndpoints.swift
//
// Copyright (c) 2015 - 2016, Justin Pawela & The LogKit Project
// http://www.logkit.info/
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import Foundation
/// This notification is posted whenever a FileEndpoint-family Endpoint instance is about to rotate to a new log file.
///
/// The notification's `object` is the actual Endpoint instance that is rotating files. The `userInfo` dictionary
/// contains the current and next URLs, at the `LXFileEndpointRotationCurrentURLKey` and
/// `LXFileEndpointRotationNextURLKey` keys, respectively.
///
/// This notification is send _before_ the rotation occurs.
public let LXFileEndpointWillRotateFilesNotification: String = "info.logkit.endpoint.fileEndpoint.willRotateFiles"
/// This notification is posted whenever a FileEndpoint-family Endpoint instance has completed rotating to a new log
/// file.
///
/// The notification's `object` is the actual Endpoint instance that is rotating files. The `userInfo` dictionary
/// contains the current and previous URLs, at the `LXFileEndpointRotationCurrentURLKey` and
/// `LXFileEndpointRotationPreviousURLKey` keys, respectively.
///
/// This notification is send _after_ the rotation occurs, but _before_ any pending Log Entries have been written to
/// the new file.
public let LXFileEndpointDidRotateFilesNotification: String = "info.logkit.endpoint.fileEndpoint.didRotateFiles"
/// The value found at this key is the `NSURL` of the sender's previous log file.
public let LXFileEndpointRotationPreviousURLKey: String = "info.logkit.endpoint.fileEndpoint.previousURL"
/// The value found at this key is the `NSURL` of the sender's current log file.
public let LXFileEndpointRotationCurrentURLKey: String = "info.logkit.endpoint.fileEndpoint.currentURL"
/// The value found at this key is the `NSURL` of the sender's next log file.
public let LXFileEndpointRotationNextURLKey: String = "info.logkit.endpoint.fileEndpoint.nextURL"
/// The default file to use when logging: `log.txt`
private let defaultLogFileURL: NSURL? = LK_DEFAULT_LOG_DIRECTORY?.URLByAppendingPathComponent("log.txt", isDirectory: false)
/// A private UTC-based calendar used in date comparisons.
private let UTCCalendar: NSCalendar = {
//TODO: this is a cheap hack because .currentCalendar() compares dates based on local TZ
let cal = NSCalendar.currentCalendar().copy() as! NSCalendar
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return cal
}()
//MARK: Log File Wrapper
/// A wrapper for a log file.
private class LXLogFile {
private let lockQueue: dispatch_queue_t = dispatch_queue_create("logFile-Lock", DISPATCH_QUEUE_SERIAL)
private let handle: NSFileHandle
private var privateByteCounter: UIntMax?
private var privateModificationTracker: NSTimeInterval?
/// Clean up.
deinit {
dispatch_barrier_sync(self.lockQueue, {
self.handle.synchronizeFile()
self.handle.closeFile()
})
}
/// Open a log file.
private init(URL: NSURL, handle: NSFileHandle, appending: Bool) {
self.handle = handle
if appending {
self.privateByteCounter = UIntMax(self.handle.seekToEndOfFile())
} else {
self.handle.truncateFileAtOffset(0)
self.privateByteCounter = 0
}
let fileAttributes = try? URL.resourceValuesForKeys([NSURLContentModificationDateKey])
self.privateModificationTracker = (
fileAttributes?[NSURLContentModificationDateKey] as? NSDate
)?.timeIntervalSinceReferenceDate
}
/// Initialize a log file. `throws` if the file cannot be accessed.
///
/// - parameter URL: The URL of the log file.
/// - parameter shouldAppend: Indicates whether new data should be appended to existing data in the file, or if
/// the file should be truncated when opened.
/// - throws: `NSError` with domain `NSURLErrorDomain`
convenience init(URL: NSURL, shouldAppend: Bool) throws {
try NSFileManager.defaultManager().ensureFile(at: URL)
guard let handle = try? NSFileHandle(forWritingToURL: URL) else {
assertionFailure("Error opening log file at path: \(URL.absoluteString)")
throw NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, userInfo: [NSURLErrorKey: URL])
}
self.init(URL: URL, handle: handle, appending: shouldAppend)
}
/// The size of this log file in bytes.
var sizeInBytes: UIntMax? {
var size: UIntMax?
dispatch_sync(self.lockQueue, { size = self.privateByteCounter })
return size
}
/// The date when this log file was last modified.
var modificationDate: NSDate? {
var interval: NSTimeInterval?
dispatch_sync(self.lockQueue, { interval = self.privateModificationTracker })
return interval == nil ? nil : NSDate(timeIntervalSinceReferenceDate: interval!)
}
/// Write data to this log file.
func writeData(data: NSData) {
dispatch_async(self.lockQueue, {
self.handle.writeData(data)
self.privateByteCounter = (self.privateByteCounter ?? 0) + UIntMax(data.length)
self.privateModificationTracker = CFAbsoluteTimeGetCurrent()
})
}
/// Set an extended attribute on the log file.
///
/// - note: Extended attributes are not available on watchOS.
func setExtendedAttribute(name name: String, value: String, options: CInt = 0) {
#if !os(watchOS) // watchOS 2 does not support extended attributes
dispatch_async(self.lockQueue, {
fsetxattr(self.handle.fileDescriptor, name, value, value.utf8.count, 0, options)
})
#endif
}
/// Empty this log file. Future writes will start from the the beginning of the file.
func reset() {
dispatch_sync(self.lockQueue, {
self.handle.synchronizeFile()
self.handle.truncateFileAtOffset(0)
self.privateByteCounter = 0
self.privateModificationTracker = CFAbsoluteTimeGetCurrent()
})
}
}
//MARK: Rotating File Endpoint
/// An Endpoint that writes Log Entries to a set of numbered files. Once a file has reached its maximum file size,
/// the Endpoint automatically rotates to the next file in the set.
///
/// The notifications `LXFileEndpointWillRotateFilesNotification` and `LXFileEndpointDidRotateFilesNotification`
/// are sent to the default notification center directly before and after rotating log files.
public class RotatingFileEndpoint: LXEndpoint {
/// The minimum Priority Level a Log Entry must meet to be accepted by this Endpoint.
public var minimumPriorityLevel: LXPriorityLevel
/// The formatter used by this Endpoint to serialize a Log Entry’s `dateTime` property to a string.
public var dateFormatter: LXDateFormatter
/// The formatter used by this Endpoint to serialize each Log Entry to a string.
public var entryFormatter: LXEntryFormatter
/// This Endpoint requires a newline character appended to each serialized Log Entry string.
public let requiresNewlines: Bool = true
/// The URL of the directory in which the set of log files is located.
public let directoryURL: NSURL
/// The base file name of the log files.
private let baseFileName: String
/// The maximum allowed file size in bytes. `nil` indicates no limit.
private let maxFileSizeBytes: UIntMax?
/// The number of files to include in the rotating set.
private let numberOfFiles: UInt
/// The index of the current file from the rotating set.
private lazy var currentIndex: UInt = { [unowned self] in
/* The goal here is to find the index of the file in the set that was last modified (has the largest
`modified` timestamp). If no file returns a `modified` property, it's probably because no files in this
set exist yet, in which case we'll just return index 1. */
let indexDates = Array(1...self.numberOfFiles).map({ (index) -> (index: UInt, modified: NSTimeInterval?) in
let fileAttributes = try? self.URLForIndex(index).resourceValuesForKeys([NSURLContentModificationDateKey])
let modified = fileAttributes?[NSURLContentModificationDateKey] as? NSDate
return (index: index, modified: modified?.timeIntervalSinceReferenceDate)
})
return (indexDates.maxElement({ $0.modified <= $1.modified && $1.modified != nil }))?.index ?? 1
}()
/// The file currently being written to.
private lazy var currentFile: LXLogFile? = { [unowned self] in
guard let file = try? LXLogFile(URL: self.currentURL, shouldAppend: true) else {
assertionFailure("Could not open the log file at URL '\(self.currentURL.absoluteString)'")
return nil
}
file.setExtendedAttribute(name: self.extendedAttributeKey, value: LK_LOGKIT_VERSION)
return file
}()
/// The name of the extended attribute metadata item used to identify one of this Endpoint's files.
private lazy var extendedAttributeKey: String = { [unowned self] in return "info.logkit.endpoint.\(self.dynamicType)" }()
/// Initialize a Rotating File Endpoint.
///
/// If the specified file cannot be opened, or if the index-prepended URL evaluates to `nil`, the initializer may
/// fail.
///
/// - parameter baseURL: The URL used to build the rotating file set’s file URLs. Each file's index
/// number will be prepended to the last path component of this URL. Defaults
/// to `Application Support/{bundleID}/logs/{number}_log.txt`. Must not be `nil`.
/// - parameter numberOfFiles: The number of files to be used in the rotation. Defaults to `5`.
/// - parameter maxFileSizeKiB: The maximum file size of each file in the rotation, specified in kilobytes.
/// Passing `nil` results in no limit, and no automatic rotation. Defaults
/// to `1024`.
/// - parameter minimumPriorityLevel: The minimum Priority Level a Log Entry must meet to be accepted by this
/// Endpoint. Defaults to `.All`.
/// - parameter dateFormatter: The formatter used by this Endpoint to serialize a Log Entry’s `dateTime`
/// property to a string. Defaults to `.standardFormatter()`.
/// - parameter entryFormatter: The formatter used by this Endpoint to serialize each Log Entry to a string.
/// Defaults to `.standardFormatter()`.
public init?(
baseURL: NSURL? = defaultLogFileURL,
numberOfFiles: UInt = 5,
maxFileSizeKiB: UInt? = 1024,
minimumPriorityLevel: LXPriorityLevel = .All,
dateFormatter: LXDateFormatter = LXDateFormatter.standardFormatter(),
entryFormatter: LXEntryFormatter = LXEntryFormatter.standardFormatter()
) {
self.dateFormatter = dateFormatter
self.entryFormatter = entryFormatter
self.maxFileSizeBytes = maxFileSizeKiB == nil ? nil : UIntMax(maxFileSizeKiB!) * 1024
self.numberOfFiles = numberOfFiles
//TODO: check file or directory to predict if file is accessible
guard let dirURL = baseURL?.URLByDeletingLastPathComponent, filename = baseURL?.lastPathComponent else {
assertionFailure("The log file URL '\(baseURL?.absoluteString ?? String())' is invalid")
self.minimumPriorityLevel = .None
self.directoryURL = NSURL(string: "")!
self.baseFileName = ""
return nil
}
self.minimumPriorityLevel = minimumPriorityLevel
self.directoryURL = dirURL
self.baseFileName = filename
}
/// The index of the next file in the rotation.
private var nextIndex: UInt { return self.currentIndex + 1 > self.numberOfFiles ? 1 : self.currentIndex + 1 }
/// The URL of the log file currently in use. Manually modifying this file is _not_ recommended.
public var currentURL: NSURL { return self.URLForIndex(self.currentIndex) }
/// The URL of the next file in the rotation.
private var nextURL: NSURL { return self.URLForIndex(self.nextIndex) }
/// The URL for the file at a given index.
private func URLForIndex(index: UInt) -> NSURL {
return self.directoryURL.URLByAppendingPathComponent(self.fileNameForIndex(index), isDirectory: false)
}
/// The name for the file at a given index.
private func fileNameForIndex(index: UInt) -> String {
let format = "%0\(Int(floor(log10(Double(self.numberOfFiles)) + 1.0)))d"
return "\(String(format: format, index))_\(self.baseFileName)"
}
/// Returns the next log file to be written to, already prepared for use.
private func nextFile() -> LXLogFile? {
guard let nextFile = try? LXLogFile(URL: self.nextURL, shouldAppend: false) else {
assertionFailure("The log file at URL '\(self.nextURL)' could not be opened.")
return nil
}
nextFile.setExtendedAttribute(name: self.extendedAttributeKey, value: LK_LOGKIT_VERSION)
return nextFile
}
/// Writes a serialized Log Entry string to the currently selected file.
public func write(string: String) {
if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
//TODO: might pass test but file fills before write
if self.shouldRotateBeforeWritingDataWithLength(data.length), let nextFile = self.nextFile() {
self.rotateToFile(nextFile)
}
self.currentFile?.writeData(data)
} else {
assertionFailure("Failure to create data from entry string")
}
}
/// Clears the currently selected file and begins writing again at its beginning.
public func resetCurrentFile() {
self.currentFile?.reset()
}
/// Instructs the Endpoint to rotate to the next log file in its sequence.
public func rotate() {
if let nextFile = self.nextFile() {
self.rotateToFile(nextFile)
}
}
/// Sets the current file to the next index and notifies about rotation
private func rotateToFile(nextFile: LXLogFile) {
//TODO: Move these notifications into property observers, if the properties can be made non-lazy.
//TODO: Getting `nextURL` from `nextFile`, instead of calculating it again, might be more robust.
NSNotificationCenter.defaultCenter().postNotificationName(
LXFileEndpointWillRotateFilesNotification,
object: self,
userInfo: [
LXFileEndpointRotationCurrentURLKey: self.currentURL,
LXFileEndpointRotationNextURLKey: self.nextURL
]
)
let previousURL = self.currentURL
self.currentFile = nextFile
self.currentIndex = self.nextIndex
NSNotificationCenter.defaultCenter().postNotificationName(
LXFileEndpointDidRotateFilesNotification,
object: self,
userInfo: [
LXFileEndpointRotationCurrentURLKey: self.currentURL,
LXFileEndpointRotationPreviousURLKey: previousURL
]
)
}
/// This method provides an opportunity to determine whether a new log file should be selected before writing the
/// next Log Entry.
///
/// - parameter length: The length of the data (number of bytes) that will be written next.
///
/// - returns: A boolean indicating whether a new log file should be selected.
private func shouldRotateBeforeWritingDataWithLength(length: Int) -> Bool {
switch (self.maxFileSizeBytes, self.currentFile?.sizeInBytes) {
case (.Some(let maxSize), .Some(let size)) where size + UIntMax(length) > maxSize: // Won't fit
fallthrough
case (.Some, .None): // Can't determine current size
return true
case (.None, .None), (.None, .Some), (.Some, .Some): // No limit or will fit
return false
}
}
/// A utility method that will not return until all previously scheduled writes have completed. Useful for testing.
///
/// - returns: Timestamp of last write (scheduled before barrier).
internal func barrier() -> NSTimeInterval? {
return self.currentFile?.modificationDate?.timeIntervalSinceReferenceDate
}
}
//MARK: File Endpoint
/// An Endpoint that writes Log Entries to a specified file.
public class FileEndpoint: RotatingFileEndpoint {
/// Initialize a File Endpoint.
///
/// If the specified file cannot be opened, or if the URL evaluates to `nil`, the initializer may fail.
///
/// - parameter fileURL: The URL of the log file.
/// Defaults to `Application Support/{bundleID}/logs/log.txt`. Must not be `nil`.
/// - parameter shouldAppend: Indicates whether the Endpoint should continue appending Log Entries to the
/// end of the file, or clear it and start at the beginning. Defaults to `true`.
/// - parameter minimumPriorityLevel: The minimum Priority Level a Log Entry must meet to be accepted by this
/// Endpoint. Defaults to `.All`.
/// - parameter dateFormatter: The formatter used by this Endpoint to serialize a Log Entry’s `dateTime`
/// property to a string. Defaults to `.standardFormatter()`.
/// - parameter entryFormatter: The formatter used by this Endpoint to serialize each Log Entry to a string.
/// Defaults to `.standardFormatter()`.
public init?(
fileURL: NSURL? = defaultLogFileURL,
shouldAppend: Bool = true,
minimumPriorityLevel: LXPriorityLevel = .All,
dateFormatter: LXDateFormatter = LXDateFormatter.standardFormatter(),
entryFormatter: LXEntryFormatter = LXEntryFormatter.standardFormatter()
) {
super.init(
baseURL: fileURL,
numberOfFiles: 1,
maxFileSizeKiB: nil,
minimumPriorityLevel: minimumPriorityLevel,
dateFormatter: dateFormatter,
entryFormatter: entryFormatter
)
if !shouldAppend {
self.resetCurrentFile()
}
}
/// This Endpoint always uses `baseFileName` as its file name.
private override func fileNameForIndex(index: UInt) -> String {
return self.baseFileName
}
/// Does nothing. File Endpoint does not rotate.
public override func rotate() {}
/// This endpoint will never rotate files.
private override func shouldRotateBeforeWritingDataWithLength(length: Int) -> Bool {
return false
}
}
//MARK: Dated File Endpoint
/// An Endpoint that writes Log Enties to a dated file. A datestamp will be prepended to the file's name. The file
/// rotates automatically at midnight UTC.
///
/// The notifications `LXFileEndpointWillRotateFilesNotification` and `LXFileEndpointDidRotateFilesNotification` are
/// sent to the default notification center directly before and after rotating log files.
public class DatedFileEndpoint: RotatingFileEndpoint {
/// The formatter used for datestamp preparation.
private let nameFormatter = LXDateFormatter.dateOnlyFormatter()
/// Initialize a Dated File Endpoint.
///
/// If the specified file cannot be opened, or if the datestamp-prepended URL evaluates to `nil`, the initializer
/// may fail.
///
/// - parameter baseURL: The URL used to build the date files’ URLs. Today's date will be prepended
/// to the last path component of this URL. Must not be `nil`.
/// Defaults to `Application Support/{bundleID}/logs/{datestamp}_log.txt`.
/// - parameter minimumPriorityLevel: The minimum Priority Level a Log Entry must meet to be accepted by this
/// Endpoint. Defaults to `.All`.
/// - parameter dateFormatter: The formatter used by this Endpoint to serialize a Log Entry’s `dateTime`
/// property to a string. Defaults to `.standardFormatter()`.
/// - parameter entryFormatter: The formatter used by this Endpoint to serialize each Log Entry to a string.
/// Defaults to `.standardFormatter()`.
public init?(
baseURL: NSURL? = defaultLogFileURL,
minimumPriorityLevel: LXPriorityLevel = .All,
dateFormatter: LXDateFormatter = LXDateFormatter.standardFormatter(),
entryFormatter: LXEntryFormatter = LXEntryFormatter.standardFormatter()
) {
super.init(
baseURL: baseURL,
numberOfFiles: 1,
maxFileSizeKiB: nil,
minimumPriorityLevel: minimumPriorityLevel,
dateFormatter: dateFormatter,
entryFormatter: entryFormatter
)
}
/// The name for the file with today's date.
private override func fileNameForIndex(index: UInt) -> String {
return "\(self.nameFormatter.stringFromDate(NSDate()))_\(self.baseFileName)"
}
/// Does nothing. Dated File Endpoint only rotates by date.
public override func rotate() {}
/// Returns `true` if the current date no longer matches the log file's date. Disregards the `length` parameter.
private override func shouldRotateBeforeWritingDataWithLength(length: Int) -> Bool {
switch self.currentFile?.modificationDate {
case .Some(let modificationDate) where !UTCCalendar.isDateSameAsToday(modificationDate): // Wrong date
fallthrough
case .None: // Can't determine the date
return true
case .Some: // Correct date
return false
}
}
//TODO: Cap the max number trailing log files.
}
// ======================================================================== //
// MARK: Aliases
// ======================================================================== //
// Classes in LogKit 3.0 will drop the LX prefixes. To facilitate other 3.0
// features, the File Endpoint family classes have been renamed early. The
// aliases below ensure developers are not affected by this early change.
//TODO: Remove unnecessary aliases in LogKit 4.0
/// An Endpoint that writes Log Entries to a set of numbered files. Once a file has reached its maximum file size,
/// the Endpoint automatically rotates to the next file in the set.
///
/// The notifications `LXFileEndpointWillRotateFilesNotification` and `LXFileEndpointDidRotateFilesNotification`
/// are sent to the default notification center directly before and after rotating log files.
/// - note: This is a LogKit 3.0 forward-compatibility typealias to `RotatingFileEndpoint`.
public typealias LXRotatingFileEndpoint = RotatingFileEndpoint
/// An Endpoint that writes Log Entries to a specified file.
/// - note: This is a LogKit 3.0 forward-compatibility typealias to `FileEndpoint`.
public typealias LXFileEndpoint = FileEndpoint
/// An Endpoint that writes Log Enties to a dated file. A datestamp will be prepended to the file's name. The file
/// rotates automatically at midnight UTC.
///
/// The notifications `LXFileEndpointWillRotateFilesNotification` and `LXFileEndpointDidRotateFilesNotification` are
/// sent to the default notification center directly before and after rotating log files.
/// - note: This is a LogKit 3.0 forward-compatibility typealias to `DatedFileEndpoint`.
public typealias LXDatedFileEndpoint = DatedFileEndpoint
| isc |
wireapp/wire-ios-data-model | Source/Utilis/Protos/GenericMessage+Hashing.swift | 1 | 3685 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// 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.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
protocol BigEndianDataConvertible {
var asBigEndianData: Data { get }
}
extension GenericMessage {
func hashOfContent(with timestamp: Date) -> Data? {
guard let content = content else {
return nil
}
switch content {
case .location(let data as BigEndianDataConvertible),
.text(let data as BigEndianDataConvertible),
.edited(let data as BigEndianDataConvertible),
.asset(let data as BigEndianDataConvertible):
return data.hashWithTimestamp(timestamp: timestamp.timeIntervalSince1970)
case .ephemeral(let data):
guard let content = data.content else {
return nil
}
switch content {
case .location(let data as BigEndianDataConvertible),
.text(let data as BigEndianDataConvertible),
.asset(let data as BigEndianDataConvertible):
return data.hashWithTimestamp(timestamp: timestamp.timeIntervalSince1970)
default:
return nil
}
default:
return nil
}
}
}
extension MessageEdit: BigEndianDataConvertible {
var asBigEndianData: Data {
return text.asBigEndianData
}
}
extension WireProtos.Text: BigEndianDataConvertible {
var asBigEndianData: Data {
return content.asBigEndianData
}
}
extension Location: BigEndianDataConvertible {
var asBigEndianData: Data {
var data = latitude.times1000.asBigEndianData
data.append(longitude.times1000.asBigEndianData)
return data
}
}
extension WireProtos.Asset: BigEndianDataConvertible {
var asBigEndianData: Data {
return uploaded.assetID.asBigEndianData
}
}
fileprivate extension Float {
var times1000: Int {
return Int(roundf(self * 1000.0))
}
}
extension String: BigEndianDataConvertible {
var asBigEndianData: Data {
var data = Data([0xFE, 0xFF]) // Byte order marker
data.append(self.data(using: .utf16BigEndian)!)
return data
}
}
extension Int: BigEndianDataConvertible {
public var asBigEndianData: Data {
return withUnsafePointer(to: self.bigEndian) {
Data(bytes: $0, count: MemoryLayout.size(ofValue: self))
}
}
}
extension TimeInterval: BigEndianDataConvertible {
public var asBigEndianData: Data {
let long = Int64(self).bigEndian
return withUnsafePointer(to: long) {
return Data(bytes: $0, count: MemoryLayout.size(ofValue: long))
}
}
}
extension BigEndianDataConvertible {
public func dataWithTimestamp(timestamp: TimeInterval) -> Data {
var data = self.asBigEndianData
data.append(timestamp.asBigEndianData)
return data
}
public func hashWithTimestamp(timestamp: TimeInterval) -> Data {
return dataWithTimestamp(timestamp: timestamp).zmSHA256Digest()
}
}
| gpl-3.0 |
hooman/swift | stdlib/public/Concurrency/AsyncDropFirstSequence.swift | 3 | 4982 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@available(SwiftStdlib 5.5, *)
extension AsyncSequence {
/// Omits a specified number of elements from the base asynchronous sequence,
/// then passes through all remaining elements.
///
/// Use `dropFirst(_:)` when you want to drop the first *n* elements from the
/// base sequence and pass through the remaining elements.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `10`. The `dropFirst(_:)` method causes the modified
/// sequence to ignore the values `0` through `4`, and instead emit `5` through `10`:
///
/// for await number in Counter(howHigh: 10).dropFirst(3) {
/// print("\(number) ", terminator: " ")
/// }
/// // prints "4 5 6 7 8 9 10"
///
/// If the number of elements to drop exceeds the number of elements in the
/// sequence, the result is an empty sequence.
///
/// - Parameter count: The number of elements to drop from the beginning of
/// the sequence. `count` must be greater than or equal to zero.
/// - Returns: An asynchronous sequence that drops the first `count`
/// elements from the base sequence.
@inlinable
public __consuming func dropFirst(
_ count: Int = 1
) -> AsyncDropFirstSequence<Self> {
precondition(count >= 0,
"Can't drop a negative number of elements from an async sequence")
return AsyncDropFirstSequence(self, dropping: count)
}
}
/// An asynchronous sequence which omits a specified number of elements from the
/// base asynchronous sequence, then passes through all remaining elements.
@available(SwiftStdlib 5.5, *)
@frozen
public struct AsyncDropFirstSequence<Base: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let count: Int
@inlinable
init(_ base: Base, dropping count: Int) {
self.base = base
self.count = count
}
}
@available(SwiftStdlib 5.5, *)
extension AsyncDropFirstSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The drop-first sequence produces whatever type of element its base
/// iterator produces.
public typealias Element = Base.Element
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the drop-first sequence.
@frozen
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
var count: Int
@inlinable
init(_ baseIterator: Base.AsyncIterator, count: Int) {
self.baseIterator = baseIterator
self.count = count
}
/// Produces the next element in the drop-first sequence.
///
/// Until reaching the number of elements to drop, this iterator calls
/// `next()` on its base iterator and discards the result. If the base
/// iterator returns `nil`, indicating the end of the sequence, this
/// iterator returns `nil`. After reaching the number of elements to
/// drop, this iterator passes along the result of calling `next()` on
/// the base iterator.
@inlinable
public mutating func next() async rethrows -> Base.Element? {
var remainingToDrop = count
while remainingToDrop > 0 {
guard try await baseIterator.next() != nil else {
count = 0
return nil
}
remainingToDrop -= 1
}
count = 0
return try await baseIterator.next()
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), count: count)
}
}
@available(SwiftStdlib 5.5, *)
extension AsyncDropFirstSequence {
/// Omits a specified number of elements from the base asynchronous sequence,
/// then passes through all remaining elements.
///
/// When you call `dropFirst(_:)` on an asynchronous sequence that is already
/// an `AsyncDropFirstSequence`, the returned sequence simply adds the new
/// drop count to the current drop count.
@inlinable
public __consuming func dropFirst(
_ count: Int = 1
) -> AsyncDropFirstSequence<Base> {
// If this is already a AsyncDropFirstSequence, we can just sum the current
// drop count and additional drop count.
precondition(count >= 0,
"Can't drop a negative number of elements from an async sequence")
return AsyncDropFirstSequence(base, dropping: self.count + count)
}
}
| apache-2.0 |
swilliams/DB5-Swift | Source/ThemeLoader.swift | 1 | 1148 | //
// ThemeLoader.swift
// DB5Demo
//
import UIKit
class ThemeLoader: NSObject {
var defaultTheme: Theme?
var themes: [Theme]
init(themeFilename filename: String) {
let themesFilePath = NSBundle.mainBundle().pathForResource(filename, ofType: "plist")
let themesDictionary = NSDictionary(contentsOfFile: themesFilePath!)!
themes = [Theme]()
for oneKey in themesDictionary.allKeys {
let key = oneKey as! String
let themeDictionary = themesDictionary[key] as! NSDictionary
let theme = Theme(fromDictionary: themeDictionary)
if key.lowercaseString == "default" {
defaultTheme = theme
}
theme.name = key
themes.append(theme)
}
for oneTheme in themes {
if oneTheme != defaultTheme {
oneTheme.parentTheme = defaultTheme
}
}
}
func themeNamed(themeName: String) -> Theme? {
for oneTheme in themes {
if themeName == oneTheme.name {
return oneTheme
}
}
return nil
}
}
| mit |
HackerEcology/BeginnerCourse | tdjackey/GuidedTour.playground/section-48.swift | 3 | 62 | let sortedNumbers = sorted(numbers) { $0 > $1 }
sortedNumbers
| mit |
hstdt/GodEye | Carthage/Checkouts/AssistiveButton/Example/Tests/Tests.swift | 1 | 765 | import UIKit
import XCTest
import AssistiveButton
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.
XCTAssert(true, "Pass")
}
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 |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/foundation_value_types/urlcomponents/main.swift | 2 | 1511 | // main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
import Foundation
func main() {
var urlc = URLComponents(string: "https://www.apple.com:12345/thisurl/isnotreal/itoldyou.php?page=fake")!
print(urlc.scheme) //% self.expect('frame variable -d run -- urlc', substrs=['urlString = "https://www.apple.com:12345/thisurl/isnotreal/itoldyou.php?page=fake"'])
print(urlc.host) //% self.expect('frame variable -d run -- urlc', substrs=['scheme = "https"'])
print(urlc.port) //% self.expect('frame variable -d run -- urlc', substrs=['host = "www.apple.com"'])
print(urlc.path) //% self.expect('frame variable -d run -- urlc', substrs=['port = 0x', 'Int64(12345)'])
print(urlc.query) //% self.expect('frame variable -d run -- urlc', substrs=['path = "/thisurl/isnotreal/itoldyou.php"'])
print("break here last") //% self.expect('frame variable -d run -- urlc', substrs=['query = "page=fake"'])
//% self.expect('expression -d run -- urlc', substrs=['urlString = "https://www.apple.com:12345/thisurl/isnotreal/itoldyou.php?page=fake"', 'scheme = "https"', 'user = nil', 'fragment = nil'])
}
main()
| apache-2.0 |
ziogaschr/SwiftPasscodeLock | PasscodeLockTests/Fakes/FakePasscodeState.swift | 1 | 691 | //
// FakePasscodeState.swift
// PasscodeLock
//
// Created by Yanko Dimitrov on 8/28/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import Foundation
class FakePasscodeState: PasscodeLockStateType {
let title = "A"
let description = "B"
let isCancellableAction = true
var isTouchIDAllowed = true
var acceptPaccodeCalled = false
var acceptedPasscode = [String]()
var numberOfAcceptedPasscodes = 0
init() {}
func acceptPasscode(_ passcode: [String], fromLock lock: PasscodeLockType) {
acceptedPasscode = passcode
acceptPaccodeCalled = true
numberOfAcceptedPasscodes += 1
}
}
| mit |
benlangmuir/swift | test/Generics/concrete_contraction_unrelated_typealias.swift | 6 | 3315 | // RUN: %target-swift-frontend -typecheck -verify %s -debug-generic-signatures -warn-redundant-requirements 2>&1 | %FileCheck %s
// Another GenericSignatureBuilder oddity, reduced from RxSwift.
//
// The requirements 'Proxy.Parent == P' and 'Proxy.Delegate == D' in the
// init() below refer to both the typealias and the associated type,
// despite the class being unrelated to the protocol; it just happens to
// define typealiases with the same name.
//
// In the Requirement Machine, the concrete contraction pre-processing
// pass would eagerly substitute the concrete type into these two
// requirements, producing the useless requirements 'P == P' and 'D == D'.
//
// Make sure concrete contraction keeps these requirements as-is by
// checking the generic signature with and without concrete contraction.
class GenericDelegateProxy<P : AnyObject, D> {
typealias Parent = P
typealias Delegate = D
// Here if we resolve Proxy.Parent and Proxy.Delegate to the typealiases,
// we get vacuous requirements 'P == P' and 'D == D'. By keeping both
// the substituted and original requirement, we ensure that the
// unrelated associated type 'Parent' is constrained instead.
// CHECK-LABEL: .GenericDelegateProxy.init(_:)@
// CHECK-NEXT: <P, D, Proxy where P == Proxy.[DelegateProxyType]Parent, D == Proxy.[DelegateProxyType]Delegate, Proxy : GenericDelegateProxy<P, D>, Proxy : DelegateProxyType>
init<Proxy: DelegateProxyType>(_: Proxy.Type)
where Proxy: GenericDelegateProxy<P, D>,
Proxy.Parent == P, // expected-warning {{redundant same-type constraint 'GenericDelegateProxy<P, D>.Parent' (aka 'P') == 'P'}}
Proxy.Delegate == D {} // expected-warning {{redundant same-type constraint 'GenericDelegateProxy<P, D>.Delegate' (aka 'D') == 'D'}}
}
class SomeClass {}
struct SomeStruct {}
class ConcreteDelegateProxy {
typealias Parent = SomeClass
typealias Delegate = SomeStruct
// An even more esoteric edge case. Note that this one I made up; only
// the first one is relevant for compatibility with RxSwift.
//
// Here unfortunately we produce a different result from the GSB, because
// the hack for keeping both the substituted and original requirement means
// the substituted requirements become 'P == SomeClass' and 'D == SomeStruct'.
//
// The GSB does not constrain P and D in this way and instead produced the
// following minimized signature:
//
// <P, D, Proxy where P == Proxy.[DelegateProxyType]Parent, D == Proxy.[DelegateProxyType]Delegate, Proxy : ConcreteDelegateProxy, Proxy : DelegateProxyType>!
// CHECK-LABEL: .ConcreteDelegateProxy.init(_:_:_:)@
// CHECK-NEXT: <P, D, Proxy where P == SomeClass, D == SomeStruct, Proxy : ConcreteDelegateProxy, Proxy : DelegateProxyType, Proxy.[DelegateProxyType]Delegate == SomeStruct, Proxy.[DelegateProxyType]Parent == SomeClass>
// expected-warning@+2 {{same-type requirement makes generic parameter 'P' non-generic}}
// expected-warning@+1 {{same-type requirement makes generic parameter 'D' non-generic}}
init<P, D, Proxy: DelegateProxyType>(_: P, _: D, _: Proxy.Type)
where Proxy: ConcreteDelegateProxy,
Proxy.Parent == P,
Proxy.Delegate == D {}
}
protocol DelegateProxyType {
associatedtype Parent : AnyObject
associatedtype Delegate
}
| apache-2.0 |
klundberg/swift-corelibs-foundation | TestFoundation/TestNSPropertyList.swift | 1 | 2144 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSPropertyList : XCTestCase {
static var allTests: [(String, (TestNSPropertyList) -> () throws -> Void)] {
return [
("test_BasicConstruction", test_BasicConstruction ),
("test_decode", test_decode ),
]
}
func test_BasicConstruction() {
let dict = NSMutableDictionary(capacity: 0)
// dict["foo"] = "bar"
var data: Data? = nil
do {
data = try PropertyListSerialization.data(fromPropertyList: dict, format: PropertyListSerialization.PropertyListFormat.binary, options: 0)
} catch {
}
XCTAssertNotNil(data)
XCTAssertEqual(data!.count, 42, "empty dictionary should be 42 bytes")
}
func test_decode() {
var decoded: Any?
var fmt = PropertyListSerialization.PropertyListFormat.binary
let path = testBundle().urlForResource("Test", withExtension: "plist")
let data = try! Data(contentsOf: path!)
do {
decoded = try withUnsafeMutablePointer(&fmt) { (format: UnsafeMutablePointer<PropertyListSerialization.PropertyListFormat>) -> Any in
return try PropertyListSerialization.propertyList(from: data, options: [], format: format)
}
} catch {
}
XCTAssertNotNil(decoded)
let dict = decoded as! Dictionary<String, Any>
XCTAssertEqual(dict.count, 3)
let val = dict["Foo"]
XCTAssertNotNil(val)
if let str = val as? String {
XCTAssertEqual(str, "Bar")
} else {
XCTFail("value stored is not a string")
}
}
}
| apache-2.0 |
cristov26/moviesApp | MoviesApp/Core/Services/Caching/Protocols/BaseService.swift | 1 | 2539 | //
// BaseService.swift
//
//
// Created by Cristian Tovar on 11/16/17.
// Copyright © 2017. All rights reserved.
//
import UIKit
import Alamofire
// TODO: Override this protocol in all the Services that need it
enum ServiceResponse {
case failure
case notConnectedToInternet
case success(response: [AnyObject])
}
class BaseService {
let appKey = "4613442500106debd35a2a2dc8241956"
public var kProductsArrayKey: String {
return ""
}
// Different result codes
let successCode = 200
func callEndpoint (endPoint: String, completion:@escaping (ServiceResponse) -> Void) {
AF.request(endPoint).responseJSON { (response) in
switch response.result {
case let .success(jsonValue):
self.success(result: self.parse(response: jsonValue as AnyObject)!, completion: completion)
case .failure(_):
if response.response?.statusCode == NSURLErrorNotConnectedToInternet {
self.notConnectedToInternet(completion: completion)
} else {
self.failure(completion: completion)
}
}
}
}
/**
* Parse method
* Pure virtual, this is intended to be overrided with a custom parsing method
* @param: {String} completion - Initial block with response
*/
func parse (response: AnyObject) -> [AnyObject]? {
return nil
}
/**
* Not connected method
* Override as needed, this provides a default implementation for the 'No Connection' result
* @param: {String} completion - Initial block with response
*/
func notConnectedToInternet (completion:@escaping (ServiceResponse) -> Void) {
completion(.notConnectedToInternet)
}
/**
* Failure method
* Override as needed, this provides a default implementation for the failure result
* @param: {String} completion - Initial block with response
*/
func failure (completion:@escaping (ServiceResponse) -> Void) {
completion(.failure)
}
/**
* Success method
* Override as needed, this provides a default implementation for the success result
* @param: {String} result - Parsing result
* @param: {String} completion - Initial block with response
*/
func success (result: [AnyObject], completion:@escaping (ServiceResponse) -> Void) {
completion(.success(response: result))
}
}
| mit |
soffes/deck | Deck/Card.swift | 1 | 649 | //
// Card.swift
// Deck
//
// Created by Sam Soffes on 11/5/14.
// Copyright (c) 2014 Sam Soffes. All rights reserved.
//
public struct Card: Comparable {
public let suit: Suit
public let rank: Rank
public var shortDescription: String {
return "\(suit.shortDescription)\(rank.shortDescription)"
}
public var description: String {
return "\(rank.description) of \(suit.description)"
}
public init(suit: Suit, rank: Rank) {
self.suit = suit
self.rank = rank
}
}
// MARK: - Comparable
public func ==(x: Card, y: Card) -> Bool {
return x.rank == y.rank
}
public func <(x: Card, y: Card) -> Bool {
return x.rank < y.rank
}
| mit |
docopt/docopt.swift | Sources/Option.swift | 2 | 3103 | //
// Option.swift
// docopt
//
// Created by Pavel S. Mazurin on 2/28/15.
// Copyright (c) 2015 kovpas. All rights reserved.
//
import Foundation
internal class Option: LeafPattern {
internal var short: String?
internal var long: String?
internal var argCount: UInt
override internal var name: String? {
get {
return self.long ?? self.short
}
set {
}
}
override var description: String {
get {
var valueDescription : String = value?.description ?? "nil"
if value is Bool, let val = value as? Bool
{
valueDescription = val ? "true" : "false"
}
return "Option(\(String(describing: short)), \(String(describing: long)), \(argCount), \(valueDescription))"
}
}
convenience init(_ option: Option) {
self.init(option.short, long: option.long, argCount: option.argCount, value: option.value)
}
init(_ short: String? = nil, long: String? = nil, argCount: UInt = 0, value: AnyObject? = false as NSNumber) {
assert(argCount <= 1)
self.short = short
self.long = long
self.argCount = argCount
super.init("", value: value)
if argCount > 0 && value as? Bool == false {
self.value = nil
} else {
self.value = value
}
}
static func parse(_ optionDescription: String) -> Option {
var short: String? = nil
var long: String? = nil
var argCount: UInt = 0
var value: AnyObject? = kCFBooleanFalse
var (options, _, description) = optionDescription.strip().partition(" ")
options = options.replacingOccurrences(of: ",", with: " ", options: [], range: nil)
options = options.replacingOccurrences(of: "=", with: " ", options: [], range: nil)
for s in options.components(separatedBy: " ").filter({!$0.isEmpty}) {
if s.hasPrefix("--") {
long = s
} else if s.hasPrefix("-") {
short = s
} else {
argCount = 1
}
}
if argCount == 1 {
let matched = description.findAll("\\[default: (.*)\\]", flags: .caseInsensitive)
if matched.count > 0
{
value = matched[0] as AnyObject
}
else
{
value = nil
}
}
return Option(short, long: long, argCount: argCount, value: value)
}
override func singleMatch<T: LeafPattern>(_ left: [T]) -> SingleMatchResult {
for i in 0..<left.count {
let pattern = left[i]
if pattern.name == name {
return (i, pattern)
}
}
return (0, nil)
}
}
func ==(lhs: Option, rhs: Option) -> Bool {
let valEqual = lhs as LeafPattern == rhs as LeafPattern
return lhs.short == rhs.short
&& lhs.long == lhs.long
&& lhs.argCount == rhs.argCount
&& valEqual
}
| mit |
isgustavo/AnimatedMoviesMakeMeCry | iOS/Animated Movies Make Me Cry/Pods/Firebase/Samples/authentication/AuthenticationExampleSwift/AppDelegate.swift | 9 | 2751 | //
// Copyright (c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
// [START auth_import]
import Firebase
// [END auth_import]
import GoogleSignIn
import FBSDKCoreKit
import Fabric
import TwitterKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [NSObject: AnyObject]?) -> Bool {
// [START firebase_configure]
// Use Firebase library to configure APIs
FIRApp.configure()
// [END firebase_configure]
FBSDKApplicationDelegate.sharedInstance().application(application,
didFinishLaunchingWithOptions:launchOptions)
let key = NSBundle.mainBundle().objectForInfoDictionaryKey("consumerKey"),
secret = NSBundle.mainBundle().objectForInfoDictionaryKey("consumerSecret")
if let key = key as? String, secret = secret as? String
where key.characters.count > 0 && secret.characters.count > 0 {
Twitter.sharedInstance().startWithConsumerKey(key, consumerSecret: secret)
}
return true
}
@available(iOS 9.0, *)
func application(application: UIApplication, openURL url: NSURL, options: [String : AnyObject])
-> Bool {
return self.application(application,
openURL: url,
sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] as! String?,
annotation: [:])
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
if GIDSignIn.sharedInstance().handleURL(url,
sourceApplication: sourceApplication,
annotation: annotation) {
return true
}
return FBSDKApplicationDelegate.sharedInstance().application(application,
openURL: url,
sourceApplication: sourceApplication,
annotation: annotation)
}
}
| apache-2.0 |
sol/aeson | tests/JSONTestSuite/parsers/test_Freddy_2_1_0/test_Freddy/main.swift | 12 | 771 | //
// main.swift
// test_Freddy
//
// Created by nst on 10/08/16.
// Copyright © 2016 Nicolas Seriot. All rights reserved.
//
import Foundation
func main() {
guard Process.arguments.count == 2 else {
let url = NSURL(fileURLWithPath: Process.arguments[0])
guard let programName = url.lastPathComponent else { exit(1) }
print("Usage: ./\(programName) file.json")
exit(1)
}
let path = Process.arguments[1]
let url = NSURL.fileURLWithPath(path)
guard let data = NSData(contentsOfURL:url) else {
print("*** CANNOT READ DATA AT \(url)")
return
}
var p = JSONParser(utf8Data: data)
do {
try p.parse()
exit(0)
} catch {
exit(1)
}
}
main()
| bsd-3-clause |
stepanhruda/libpq-darwin | Package.swift | 1 | 68 | import PackageDescription
let package = Package(
name: "libpq"
)
| mit |
SwiftGen/templates | Pods/StencilSwiftKit/Sources/SwiftIdentifier.swift | 2 | 3717 | //
// StencilSwiftKit
// Copyright (c) 2017 SwiftGen
// MIT Licence
//
import Foundation
private func mr(_ char: Int) -> CountableClosedRange<Int> {
return char...char
}
// Official list of valid identifier characters
// swiftlint:disable:next line_length
// from: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/doc/uid/TP40014097-CH30-ID410
private let headRanges: [CountableClosedRange<Int>] = [
0x61...0x7a, 0x41...0x5a, mr(0x5f), mr(0xa8), mr(0xaa), mr(0xad), mr(0xaf),
0xb2...0xb5, 0xb7...0xba, 0xbc...0xbe, 0xc0...0xd6, 0xd8...0xf6, 0xf8...0xff,
0x100...0x2ff, 0x370...0x167f, 0x1681...0x180d, 0x180f...0x1dbf,
0x1e00...0x1fff, 0x200b...0x200d, 0x202a...0x202e, mr(0x203F), mr(0x2040),
mr(0x2054), 0x2060...0x206f, 0x2070...0x20cf, 0x2100...0x218f, 0x2460...0x24ff,
0x2776...0x2793, 0x2c00...0x2dff, 0x2e80...0x2fff, 0x3004...0x3007,
0x3021...0x302f, 0x3031...0x303f, 0x3040...0xd7ff, 0xf900...0xfd3d,
0xfd40...0xfdcf, 0xfdf0...0xfe1f, 0xfe30...0xfe44, 0xfe47...0xfffd,
0x10000...0x1fffd, 0x20000...0x2fffd, 0x30000...0x3fffd, 0x40000...0x4fffd,
0x50000...0x5fffd, 0x60000...0x6fffd, 0x70000...0x7fffd, 0x80000...0x8fffd,
0x90000...0x9fffd, 0xa0000...0xafffd, 0xb0000...0xbfffd, 0xc0000...0xcfffd,
0xd0000...0xdfffd, 0xe0000...0xefffd
]
private let tailRanges: [CountableClosedRange<Int>] = [
0x30...0x39, 0x300...0x36F, 0x1dc0...0x1dff, 0x20d0...0x20ff, 0xfe20...0xfe2f
]
private func identifierCharacterSets(exceptions: String) -> (head: NSMutableCharacterSet, tail: NSMutableCharacterSet) {
let addRange: (NSMutableCharacterSet, CountableClosedRange<Int>) -> Void = { (mcs, range) in
mcs.addCharacters(in: NSRange(location: range.lowerBound, length: range.count))
}
let head = NSMutableCharacterSet()
for range in headRanges {
addRange(head, range)
}
head.removeCharacters(in: exceptions)
guard let tail = head.mutableCopy() as? NSMutableCharacterSet else {
fatalError("Internal error: mutableCopy() should have returned a valid NSMutableCharacterSet")
}
for range in tailRanges {
addRange(tail, range)
}
tail.removeCharacters(in: exceptions)
return (head, tail)
}
enum SwiftIdentifier {
static func identifier(from string: String,
forbiddenChars exceptions: String = "",
replaceWithUnderscores underscores: Bool = false) -> String {
let (_, tail) = identifierCharacterSets(exceptions: exceptions)
let parts = string.components(separatedBy: tail.inverted)
let replacement = underscores ? "_" : ""
let mappedParts = parts.map({ (string: String) -> String in
// Can't use capitalizedString here because it will lowercase all letters after the first
// e.g. "SomeNiceIdentifier".capitalizedString will because "Someniceidentifier" which is not what we want
let ns = NSString(string: string)
if ns.length > 0 {
let firstLetter = ns.substring(to: 1)
let rest = ns.substring(from: 1)
return firstLetter.uppercased() + rest
} else {
return ""
}
})
let result = mappedParts.joined(separator: replacement)
return prefixWithUnderscoreIfNeeded(string: result, forbiddenChars: exceptions)
}
static func prefixWithUnderscoreIfNeeded(string: String,
forbiddenChars exceptions: String = "") -> String {
let (head, _) = identifierCharacterSets(exceptions: exceptions)
let chars = string.unicodeScalars
let firstChar = chars[chars.startIndex]
let prefix = !head.longCharacterIsMember(firstChar.value) ? "_" : ""
return prefix + string
}
}
| mit |
nifty-swift/Nifty | Tests/NiftyTests/rand_test.swift | 2 | 2170 |
/***************************************************************************************************
* rand_test.swift
*
* This file tests the rand function.
*
* Author: Philip Erickson
* Creation Date: 22 Jan 2017
*
* 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.
*
* Copyright 2017 Philip Erickson
**************************************************************************************************/
import Dispatch
import XCTest
@testable import Nifty
class rand_test: XCTestCase
{
#if os(Linux)
static var allTests: [XCTestCaseEntry]
{
let tests =
[
testCase([("testBasic", self.testBasic)]),
]
return tests
}
#endif
func testBasic()
{
// reseed global generator
let r1 = rand(10, seed: 1234)
let r2 = rand(10)
let r3 = rand(10, seed: 1234)
print(r1)
print(r2)
print(r3)
XCTAssert(isequal(r1, r3, within: 0.1))
XCTAssert(!isequal(r1, r2, within: 0.1))
// thread safe - ensure each iteration pulls a unique number
let lock = DispatchSemaphore(value: 1)
var nums = Set<Int>()
let itr = 100000
func randBlock(_ i: Int)
{
let r = rand(threadSafe: true)
lock.wait()
nums.insert(Int(r*1000000000000))
lock.signal()
}
let queue = DispatchQueue(label: "randQueue", attributes: .concurrent)
queue.sync
{
DispatchQueue.concurrentPerform(iterations: itr, execute: randBlock)
}
XCTAssert(nums.count == itr)
}
}
| apache-2.0 |
realgreys/RGPageMenu | RGPageMenu/Classes/MenuItemView.swift | 1 | 3830 | //
// MenuItemView.swift
// paging
//
// Created by realgreys on 2016. 5. 10..
// Copyright © 2016 realgreys. All rights reserved.
//
import UIKit
class MenuItemView: UIView {
private var options: RGPageMenuOptions!
var titleLabel: UILabel = {
let label = UILabel(frame: .zero)
label.textAlignment = .Center
label.userInteractionEnabled = true
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private var labelSize: CGSize {
guard let text = titleLabel.text else { return .zero }
return NSString(string: text).boundingRectWithSize(CGSizeMake(CGFloat.max, CGFloat.max),
options: .UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: titleLabel.font],
context: nil).size
}
private var widthConstraint: NSLayoutConstraint!
var selected: Bool = false {
didSet {
backgroundColor = selected ? options.selectedColor : options.backgroundColor
titleLabel.textColor = selected ? options.selectedTextColor : options.textColor
// font가 변경되면 size 계산 다시 해야 한다.
}
}
// MARK: - Lifecycle
init(title: String, options: RGPageMenuOptions) {
super.init(frame: .zero)
self.options = options
backgroundColor = options.backgroundColor
translatesAutoresizingMaskIntoConstraints = false
setupLabel(title)
layoutLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Layout
private func setupLabel(title: String) {
titleLabel.text = title
titleLabel.textColor = options.textColor
titleLabel.font = options.font
addSubview(titleLabel)
}
private func layoutLabel() {
let viewsDictionary = ["label": titleLabel]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[label]|",
options: [],
metrics: nil,
views: viewsDictionary)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[label]|",
options: [],
metrics: nil,
views: viewsDictionary)
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
let labelSize = calcLabelSize()
widthConstraint = NSLayoutConstraint(item: titleLabel, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: labelSize.width)
widthConstraint.active = true
}
private func calcLabelSize() -> CGSize {
let height = floor(labelSize.height) // why floor?
if options.menuAlign == .Fit {
let windowSize = UIApplication.sharedApplication().keyWindow!.bounds.size
let width = windowSize.width / CGFloat(options.menuItemCount)
return CGSizeMake(width, height)
} else {
let width = ceil(labelSize.width)
return CGSizeMake(width + options.menuItemMargin * 2, height)
}
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/02060-swift-constraints-constraintsystem-getfixedtyperecursive.swift | 11 | 479 | // 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
// RUN: not %target-swift-frontend %s -parse
print(1):
class func f<T) -> : NSObject {
struct A<T where B : b> {
static let end = a
| apache-2.0 |
natecook1000/swift | stdlib/public/SDK/Foundation/Data.swift | 2 | 80964 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if DEPLOYMENT_RUNTIME_SWIFT
#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
import CoreFoundation
internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) {
munmap(mem, length)
}
internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) {
free(mem)
}
internal func __NSDataIsCompact(_ data: NSData) -> Bool {
return data._isCompact()
}
#else
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
import _SwiftCoreFoundationOverlayShims
internal func __NSDataIsCompact(_ data: NSData) -> Bool {
if #available(OSX 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) {
return data._isCompact()
} else {
var compact = true
let len = data.length
data.enumerateBytes { (_, byteRange, stop) in
if byteRange.length != len {
compact = false
}
stop.pointee = true
}
return compact
}
}
#endif
@usableFromInline
internal final class _DataStorage {
@usableFromInline
enum Backing {
// A mirror of the Objective-C implementation that is suitable to inline in Swift
case swift
// these two storage points for immutable and mutable data are reserved for references that are returned by "known"
// cases from Foundation in which implement the backing of struct Data, these have signed up for the concept that
// the backing bytes/mutableBytes pointer does not change per call (unless mutated) as well as the length is ok
// to be cached, this means that as long as the backing reference is retained no further objc_msgSends need to be
// dynamically dispatched out to the reference.
case immutable(NSData) // This will most often (perhaps always) be NSConcreteData
case mutable(NSMutableData) // This will often (perhaps always) be NSConcreteMutableData
// These are reserved for foreign sources where neither Swift nor Foundation are fully certain whom they belong
// to from an object inheritance standpoint, this means that all bets are off and the values of bytes, mutableBytes,
// and length cannot be cached. This also means that all methods are expected to dynamically dispatch out to the
// backing reference.
case customReference(NSData) // tracks data references that are only known to be immutable
case customMutableReference(NSMutableData) // tracks data references that are known to be mutable
}
static let maxSize = Int.max >> 1
static let vmOpsThreshold = NSPageSize() * 4
static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? {
if clear {
return calloc(1, size)
} else {
return malloc(size)
}
}
@usableFromInline
static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) {
var dest = dest_
var source = source_
var num = num_
if _DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 {
let pages = NSRoundDownToMultipleOfPageSize(num)
NSCopyMemoryPages(source!, dest, pages)
source = source!.advanced(by: pages)
dest = dest.advanced(by: pages)
num -= pages
}
if num > 0 {
memmove(dest, source!, num)
}
}
static func shouldAllocateCleared(_ size: Int) -> Bool {
return (size > (128 * 1024))
}
@usableFromInline
var _bytes: UnsafeMutableRawPointer?
@usableFromInline
var _length: Int
@usableFromInline
var _capacity: Int
@usableFromInline
var _needToZero: Bool
@usableFromInline
var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?
@usableFromInline
var _backing: Backing = .swift
@usableFromInline
var _offset: Int
@usableFromInline
var bytes: UnsafeRawPointer? {
@inlinable
get {
switch _backing {
case .swift:
return UnsafeRawPointer(_bytes)?.advanced(by: -_offset)
case .immutable:
return UnsafeRawPointer(_bytes)?.advanced(by: -_offset)
case .mutable:
return UnsafeRawPointer(_bytes)?.advanced(by: -_offset)
case .customReference(let d):
return d.bytes.advanced(by: -_offset)
case .customMutableReference(let d):
return d.bytes.advanced(by: -_offset)
}
}
}
@usableFromInline
@discardableResult
func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
switch _backing {
case .swift: fallthrough
case .immutable: fallthrough
case .mutable:
return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, _length)))
case .customReference(let d):
if __NSDataIsCompact(d) {
let len = d.length
guard len > 0 else {
return try apply(UnsafeRawBufferPointer(start: nil, count: 0))
}
return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len)))
} else {
var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment)
defer { buffer.deallocate() }
let sliceRange = NSRange(location: range.lowerBound - _offset, length: range.count)
var enumerated = 0
d.enumerateBytes { (ptr, byteRange, stop) in
if byteRange.upperBound - _offset < range.lowerBound {
// before the range that we are looking for...
} else if byteRange.lowerBound - _offset > range.upperBound {
stop.pointee = true // we are past the range in question so we need to stop
} else {
// the byteRange somehow intersects the range in question that we are looking for...
let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound)
let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound)
let len = upper - lower
memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len)
enumerated += len
if upper == range.upperBound {
stop.pointee = true
}
}
}
return try apply(UnsafeRawBufferPointer(buffer))
}
case .customMutableReference(let d):
if __NSDataIsCompact(d) {
let len = d.length
guard len > 0 else {
return try apply(UnsafeRawBufferPointer(start: nil, count: 0))
}
return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len)))
} else {
var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment)
defer { buffer.deallocate() }
var enumerated = 0
d.enumerateBytes { (ptr, byteRange, stop) in
if byteRange.upperBound - _offset < range.lowerBound {
// before the range that we are looking for...
} else if byteRange.lowerBound - _offset > range.upperBound {
stop.pointee = true // we are past the range in question so we need to stop
} else {
// the byteRange somehow intersects the range in question that we are looking for...
let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound)
let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound)
let len = upper - lower
memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len)
enumerated += len
if upper == range.upperBound {
stop.pointee = true
}
}
}
return try apply(UnsafeRawBufferPointer(buffer))
}
}
}
@usableFromInline
@discardableResult
func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
switch _backing {
case .swift: fallthrough
case .mutable:
return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length)))
case .customMutableReference(let d):
let len = d.length
return try apply(UnsafeMutableRawBufferPointer(start: d.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len)))
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
_backing = .mutable(data)
_bytes = data.mutableBytes
return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length)))
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
_backing = .customMutableReference(data)
let len = data.length
return try apply(UnsafeMutableRawBufferPointer(start: data.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len)))
}
}
var mutableBytes: UnsafeMutableRawPointer? {
@inlinable
get {
switch _backing {
case .swift:
return _bytes?.advanced(by: -_offset)
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .mutable(data)
_bytes = data.mutableBytes
return _bytes?.advanced(by: -_offset)
case .mutable:
return _bytes?.advanced(by: -_offset)
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .customMutableReference(data)
return data.mutableBytes.advanced(by: -_offset)
case .customMutableReference(let d):
return d.mutableBytes.advanced(by: -_offset)
}
}
}
@usableFromInline
var length: Int {
@inlinable
get {
switch _backing {
case .swift:
return _length
case .immutable:
return _length
case .mutable:
return _length
case .customReference(let d):
return d.length
case .customMutableReference(let d):
return d.length
}
}
@inlinable
set {
setLength(newValue)
}
}
func _freeBytes() {
if let bytes = _bytes {
if let dealloc = _deallocator {
dealloc(bytes, length)
} else {
free(bytes)
}
}
}
func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) {
var stopv: Bool = false
var data: NSData
switch _backing {
case .swift: fallthrough
case .immutable: fallthrough
case .mutable:
block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.count, _length)), 0, &stopv)
return
case .customReference(let d):
data = d
break
case .customMutableReference(let d):
data = d
break
}
data.enumerateBytes { (ptr, region, stop) in
// any region that is not in the range should be skipped
guard range.contains(region.lowerBound) || range.contains(region.upperBound) else { return }
var regionAdjustment = 0
if region.lowerBound < range.lowerBound {
regionAdjustment = range.lowerBound - (region.lowerBound - _offset)
}
let bytePtr = ptr.advanced(by: regionAdjustment).assumingMemoryBound(to: UInt8.self)
let effectiveLength = Swift.min((region.location - _offset) + region.length, range.upperBound) - (region.location - _offset)
block(UnsafeBufferPointer(start: bytePtr, count: effectiveLength - regionAdjustment), region.location + regionAdjustment - _offset, &stopv)
if stopv {
stop.pointee = true
}
}
}
@usableFromInline
@inline(never)
func _grow(_ newLength: Int, _ clear: Bool) {
let cap = _capacity
var additionalCapacity = (newLength >> (_DataStorage.vmOpsThreshold <= newLength ? 2 : 1))
if Int.max - additionalCapacity < newLength {
additionalCapacity = 0
}
var newCapacity = Swift.max(cap, newLength + additionalCapacity)
let origLength = _length
var allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity)
var newBytes: UnsafeMutableRawPointer? = nil
if _bytes == nil {
newBytes = _DataStorage.allocate(newCapacity, allocateCleared)
if newBytes == nil {
/* Try again with minimum length */
allocateCleared = clear && _DataStorage.shouldAllocateCleared(newLength)
newBytes = _DataStorage.allocate(newLength, allocateCleared)
}
} else {
let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4)
if allocateCleared && tryCalloc {
newBytes = _DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
_DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
/* Where calloc/memmove/free fails, realloc might succeed */
if newBytes == nil {
allocateCleared = false
if _deallocator != nil {
newBytes = _DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
_DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
_deallocator = nil
}
} else {
newBytes = realloc(_bytes!, newCapacity)
}
}
/* Try again with minimum length */
if newBytes == nil {
newCapacity = newLength
allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity)
if allocateCleared && tryCalloc {
newBytes = _DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
_DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
if newBytes == nil {
allocateCleared = false
newBytes = realloc(_bytes!, newCapacity)
}
}
}
if newBytes == nil {
/* Could not allocate bytes */
// At this point if the allocation cannot occur the process is likely out of memory
// and Bad-Things™ are going to happen anyhow
fatalError("unable to allocate memory for length (\(newLength))")
}
if origLength < newLength && clear && !allocateCleared {
memset(newBytes!.advanced(by: origLength), 0, newLength - origLength)
}
/* _length set by caller */
_bytes = newBytes
_capacity = newCapacity
/* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */
_needToZero = !allocateCleared
}
@inlinable
func setLength(_ length: Int) {
switch _backing {
case .swift:
let origLength = _length
let newLength = length
if _capacity < newLength || _bytes == nil {
_grow(newLength, true)
} else if origLength < newLength && _needToZero {
memset(_bytes! + origLength, 0, newLength - origLength)
} else if newLength < origLength {
_needToZero = true
}
_length = newLength
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .mutable(data)
_length = length
_bytes = data.mutableBytes
case .mutable(let d):
d.length = length
_length = length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.length = length
}
}
@inlinable
func append(_ bytes: UnsafeRawPointer, length: Int) {
precondition(length >= 0, "Length of appending bytes must not be negative")
switch _backing {
case .swift:
let origLength = _length
let newLength = origLength + length
if _capacity < newLength || _bytes == nil {
_grow(newLength, false)
}
_length = newLength
_DataStorage.move(_bytes!.advanced(by: origLength), bytes, length)
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.append(bytes, length: length)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
case .mutable(let d):
d.append(bytes, length: length)
_length = d.length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.append(bytes, length: length)
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.append(bytes, length: length)
}
}
// fast-path for appending directly from another data storage
@inlinable
func append(_ otherData: _DataStorage, startingAt start: Int, endingAt end: Int) {
let otherLength = otherData.length
if otherLength == 0 { return }
if let bytes = otherData.bytes {
append(bytes.advanced(by: start), length: end - start)
}
}
@inlinable
func append(_ otherData: Data) {
otherData.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, _, _) in
append(buffer.baseAddress!, length: buffer.count)
}
}
@inlinable
func increaseLength(by extraLength: Int) {
if extraLength == 0 { return }
switch _backing {
case .swift:
let origLength = _length
let newLength = origLength + extraLength
if _capacity < newLength || _bytes == nil {
_grow(newLength, true)
} else if _needToZero {
memset(_bytes!.advanced(by: origLength), 0, extraLength)
}
_length = newLength
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.increaseLength(by: extraLength)
_backing = .mutable(data)
_length += extraLength
_bytes = data.mutableBytes
case .mutable(let d):
d.increaseLength(by: extraLength)
_length += extraLength
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.increaseLength(by: extraLength)
_backing = .customReference(data)
case .customMutableReference(let d):
d.increaseLength(by: extraLength)
}
}
@usableFromInline
func get(_ index: Int) -> UInt8 {
switch _backing {
case .swift: fallthrough
case .immutable: fallthrough
case .mutable:
return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee
case .customReference(let d):
if __NSDataIsCompact(d) {
return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee
} else {
var byte: UInt8 = 0
d.enumerateBytes { (ptr, range, stop) in
if NSLocationInRange(index, range) {
let offset = index - range.location - _offset
byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee
stop.pointee = true
}
}
return byte
}
case .customMutableReference(let d):
if __NSDataIsCompact(d) {
return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee
} else {
var byte: UInt8 = 0
d.enumerateBytes { (ptr, range, stop) in
if NSLocationInRange(index, range) {
let offset = index - range.location - _offset
byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee
stop.pointee = true
}
}
return byte
}
}
}
@inlinable
func set(_ index: Int, to value: UInt8) {
switch _backing {
case .swift:
fallthrough
case .mutable:
_bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value
default:
var theByte = value
let range = NSRange(location: index, length: 1)
replaceBytes(in: range, with: &theByte, length: 1)
}
}
@inlinable
func replaceBytes(in range: NSRange, with bytes: UnsafeRawPointer?) {
if range.length == 0 { return }
switch _backing {
case .swift:
if _length < range.location + range.length {
let newLength = range.location + range.length
if _capacity < newLength {
_grow(newLength, false)
}
_length = newLength
}
_DataStorage.move(_bytes!.advanced(by: range.location - _offset), bytes!, range.length)
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
case .mutable(let d):
d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!)
_length = d.length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!)
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!)
}
}
@inlinable
func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) {
let range = NSRange(location: range_.location - _offset, length: range_.length)
let currentLength = _length
let resultingLength = currentLength - range.length + replacementLength
switch _backing {
case .swift:
let shift = resultingLength - currentLength
var mutableBytes = _bytes
if resultingLength > currentLength {
setLength(resultingLength)
mutableBytes = _bytes!
}
/* shift the trailing bytes */
let start = range.location
let length = range.length
if shift != 0 {
memmove(mutableBytes! + start + replacementLength, mutableBytes! + start + length, currentLength - start - length)
}
if replacementLength != 0 {
if let replacementBytes = replacementBytes {
memmove(mutableBytes! + start, replacementBytes, replacementLength)
} else {
memset(mutableBytes! + start, 0, replacementLength)
}
}
if resultingLength < currentLength {
setLength(resultingLength)
}
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
case .mutable(let d):
d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
_backing = .mutable(d)
_length = d.length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
}
}
@inlinable
func resetBytes(in range_: NSRange) {
let range = NSRange(location: range_.location - _offset, length: range_.length)
if range.length == 0 { return }
switch _backing {
case .swift:
if _length < range.location + range.length {
let newLength = range.location + range.length
if _capacity < newLength {
_grow(newLength, false)
}
_length = newLength
}
memset(_bytes!.advanced(by: range.location), 0, range.length)
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.resetBytes(in: range)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
case .mutable(let d):
d.resetBytes(in: range)
_length = d.length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.resetBytes(in: range)
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.resetBytes(in: range)
}
}
@usableFromInline
convenience init() {
self.init(capacity: 0)
}
@usableFromInline
init(length: Int) {
precondition(length < _DataStorage.maxSize)
var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length
if _DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
let clear = _DataStorage.shouldAllocateCleared(length)
_bytes = _DataStorage.allocate(capacity, clear)!
_capacity = capacity
_needToZero = !clear
_length = 0
_offset = 0
setLength(length)
}
@usableFromInline
init(capacity capacity_: Int) {
var capacity = capacity_
precondition(capacity < _DataStorage.maxSize)
if _DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = 0
_bytes = _DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
_offset = 0
}
@usableFromInline
init(bytes: UnsafeRawPointer?, length: Int) {
precondition(length < _DataStorage.maxSize)
_offset = 0
if length == 0 {
_capacity = 0
_length = 0
_needToZero = false
_bytes = nil
} else if _DataStorage.vmOpsThreshold <= length {
_capacity = length
_length = length
_needToZero = true
_bytes = _DataStorage.allocate(length, false)!
_DataStorage.move(_bytes!, bytes, length)
} else {
var capacity = length
if _DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = length
_bytes = _DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
_DataStorage.move(_bytes!, bytes, length)
}
}
@usableFromInline
init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) {
precondition(length < _DataStorage.maxSize)
_offset = offset
if length == 0 {
_capacity = 0
_length = 0
_needToZero = false
_bytes = nil
if let dealloc = deallocator,
let bytes_ = bytes {
dealloc(bytes_, length)
}
} else if !copy {
_capacity = length
_length = length
_needToZero = false
_bytes = bytes
_deallocator = deallocator
} else if _DataStorage.vmOpsThreshold <= length {
_capacity = length
_length = length
_needToZero = true
_bytes = _DataStorage.allocate(length, false)!
_DataStorage.move(_bytes!, bytes, length)
if let dealloc = deallocator {
dealloc(bytes!, length)
}
} else {
var capacity = length
if _DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = length
_bytes = _DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
_DataStorage.move(_bytes!, bytes, length)
if let dealloc = deallocator {
dealloc(bytes!, length)
}
}
}
@usableFromInline
init(immutableReference: NSData, offset: Int) {
_offset = offset
_bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes)
_capacity = 0
_needToZero = false
_length = immutableReference.length
_backing = .immutable(immutableReference)
}
@usableFromInline
init(mutableReference: NSMutableData, offset: Int) {
_offset = offset
_bytes = mutableReference.mutableBytes
_capacity = 0
_needToZero = false
_length = mutableReference.length
_backing = .mutable(mutableReference)
}
@usableFromInline
init(customReference: NSData, offset: Int) {
_offset = offset
_bytes = nil
_capacity = 0
_needToZero = false
_length = 0
_backing = .customReference(customReference)
}
@usableFromInline
init(customMutableReference: NSMutableData, offset: Int) {
_offset = offset
_bytes = nil
_capacity = 0
_needToZero = false
_length = 0
_backing = .customMutableReference(customMutableReference)
}
deinit {
switch _backing {
case .swift:
_freeBytes()
default:
break
}
}
@inlinable
func mutableCopy(_ range: Range<Int>) -> _DataStorage {
switch _backing {
case .swift:
return _DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.count, copy: true, deallocator: nil, offset: range.lowerBound)
case .immutable(let d):
if range.lowerBound == 0 && range.upperBound == _length {
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound)
} else {
return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound)
}
case .mutable(let d):
if range.lowerBound == 0 && range.upperBound == _length {
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound)
} else {
return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound)
}
case .customReference(let d):
if range.lowerBound == 0 && range.upperBound == _length {
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound)
} else {
return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound)
}
case .customMutableReference(let d):
if range.lowerBound == 0 && range.upperBound == _length {
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound)
} else {
return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound)
}
}
}
func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T {
if range.isEmpty {
return try work(NSData()) // zero length data can be optimized as a singleton
}
switch _backing {
case .swift:
return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false))
case .immutable(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false))
}
return try work(d)
case .mutable(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false))
}
return try work(d)
case .customReference(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false))
}
return try work(d)
case .customMutableReference(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false))
}
return try work(d)
}
}
func bridgedReference(_ range: Range<Int>) -> NSData {
if range.isEmpty {
return NSData() // zero length data can be optimized as a singleton
}
switch _backing {
case .swift:
return _NSSwiftData(backing: self, range: range)
case .immutable(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return _NSSwiftData(backing: self, range: range)
}
return d
case .mutable(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return _NSSwiftData(backing: self, range: range)
}
return d
case .customReference(let d):
guard range.lowerBound == 0 && range.upperBound == d.length else {
return _NSSwiftData(backing: self, range: range)
}
return d
case .customMutableReference(let d):
guard range.lowerBound == 0 && range.upperBound == d.length else {
return d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC()
}
return d.copy() as! NSData
}
}
@usableFromInline
func subdata(in range: Range<Data.Index>) -> Data {
switch _backing {
case .customReference(let d):
return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count))
case .customMutableReference(let d):
return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count))
default:
return Data(bytes: _bytes!.advanced(by: range.lowerBound - _offset), count: range.count)
}
}
}
internal class _NSSwiftData : NSData {
var _backing: _DataStorage!
var _range: Range<Data.Index>!
convenience init(backing: _DataStorage, range: Range<Data.Index>) {
self.init()
_backing = backing
_range = range
}
override var length: Int {
return _range.count
}
override var bytes: UnsafeRawPointer {
// NSData's byte pointer methods are not annotated for nullability correctly
// (but assume non-null by the wrapping macro guards). This placeholder value
// is to work-around this bug. Any indirection to the underlying bytes of an NSData
// with a length of zero would have been a programmer error anyhow so the actual
// return value here is not needed to be an allocated value. This is specifically
// needed to live like this to be source compatible with Swift3. Beyond that point
// this API may be subject to correction.
guard let bytes = _backing.bytes else {
return UnsafeRawPointer(bitPattern: 0xBAD0)!
}
return bytes.advanced(by: _range.lowerBound)
}
override func copy(with zone: NSZone? = nil) -> Any {
return self
}
override func mutableCopy(with zone: NSZone? = nil) -> Any {
return NSMutableData(bytes: bytes, length: length)
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@objc override
func _isCompact() -> Bool {
return true
}
#endif
#if DEPLOYMENT_RUNTIME_SWIFT
override func _providesConcreteBacking() -> Bool {
return true
}
#else
@objc(_providesConcreteBacking)
func _providesConcreteBacking() -> Bool {
return true
}
#endif
}
public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection {
public typealias ReferenceType = NSData
public typealias ReadingOptions = NSData.ReadingOptions
public typealias WritingOptions = NSData.WritingOptions
public typealias SearchOptions = NSData.SearchOptions
public typealias Base64EncodingOptions = NSData.Base64EncodingOptions
public typealias Base64DecodingOptions = NSData.Base64DecodingOptions
public typealias Index = Int
public typealias Indices = Range<Int>
@usableFromInline internal var _backing : _DataStorage
@usableFromInline internal var _sliceRange: Range<Index>
// A standard or custom deallocator for `Data`.
///
/// When creating a `Data` with the no-copy initializer, you may specify a `Data.Deallocator` to customize the behavior of how the backing store is deallocated.
public enum Deallocator {
/// Use a virtual memory deallocator.
#if !DEPLOYMENT_RUNTIME_SWIFT
case virtualMemory
#endif
/// Use `munmap`.
case unmap
/// Use `free`.
case free
/// Do nothing upon deallocation.
case none
/// A custom deallocator.
case custom((UnsafeMutableRawPointer, Int) -> Void)
fileprivate var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) {
#if DEPLOYMENT_RUNTIME_SWIFT
switch self {
case .unmap:
return { __NSDataInvokeDeallocatorUnmap($0, $1) }
case .free:
return { __NSDataInvokeDeallocatorFree($0, $1) }
case .none:
return { _, _ in }
case .custom(let b):
return { (ptr, len) in
b(ptr, len)
}
}
#else
switch self {
case .virtualMemory:
return { NSDataDeallocatorVM($0, $1) }
case .unmap:
return { NSDataDeallocatorUnmap($0, $1) }
case .free:
return { NSDataDeallocatorFree($0, $1) }
case .none:
return { _, _ in }
case .custom(let b):
return { (ptr, len) in
b(ptr, len)
}
}
#endif
}
}
// MARK: -
// MARK: Init methods
/// Initialize a `Data` with copied memory content.
///
/// - parameter bytes: A pointer to the memory. It will be copied.
/// - parameter count: The number of bytes to copy.
public init(bytes: UnsafeRawPointer, count: Int) {
_backing = _DataStorage(bytes: bytes, length: count)
_sliceRange = 0..<count
}
/// Initialize a `Data` with copied memory content.
///
/// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) {
let count = MemoryLayout<SourceType>.stride * buffer.count
_backing = _DataStorage(bytes: buffer.baseAddress, length: count)
_sliceRange = 0..<count
}
/// Initialize a `Data` with copied memory content.
///
/// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) {
let count = MemoryLayout<SourceType>.stride * buffer.count
_backing = _DataStorage(bytes: buffer.baseAddress, length: count)
_sliceRange = 0..<count
}
/// Initialize a `Data` with a repeating byte pattern
///
/// - parameter repeatedValue: A byte to initialize the pattern
/// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue
public init(repeating repeatedValue: UInt8, count: Int) {
self.init(count: count)
withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> Void in
memset(bytes, Int32(repeatedValue), count)
}
}
/// Initialize a `Data` with the specified size.
///
/// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount.
///
/// This method sets the `count` of the data to 0.
///
/// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page.
///
/// - parameter capacity: The size of the data.
public init(capacity: Int) {
_backing = _DataStorage(capacity: capacity)
_sliceRange = 0..<0
}
/// Initialize a `Data` with the specified count of zeroed bytes.
///
/// - parameter count: The number of bytes the data initially contains.
public init(count: Int) {
_backing = _DataStorage(length: count)
_sliceRange = 0..<count
}
/// Initialize an empty `Data`.
public init() {
_backing = _DataStorage(length: 0)
_sliceRange = 0..<0
}
/// Initialize a `Data` without copying the bytes.
///
/// If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed.
/// - parameter bytes: A pointer to the bytes.
/// - parameter count: The size of the bytes.
/// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`.
public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) {
let whichDeallocator = deallocator._deallocator
_backing = _DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0)
_sliceRange = 0..<count
}
/// Initialize a `Data` with the contents of a `URL`.
///
/// - parameter url: The `URL` to read.
/// - parameter options: Options for the read operation. Default value is `[]`.
/// - throws: An error in the Cocoa domain, if `url` cannot be read.
public init(contentsOf url: URL, options: Data.ReadingOptions = []) throws {
let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue))
_backing = _DataStorage(immutableReference: d, offset: 0)
_sliceRange = 0..<d.length
}
/// Initialize a `Data` from a Base-64 encoded String using the given options.
///
/// Returns nil when the input is not recognized as valid Base-64.
/// - parameter base64String: The string to parse.
/// - parameter options: Encoding options. Default value is `[]`.
public init?(base64Encoded base64String: String, options: Data.Base64DecodingOptions = []) {
if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) {
_backing = _DataStorage(immutableReference: d, offset: 0)
_sliceRange = 0..<d.length
} else {
return nil
}
}
/// Initialize a `Data` from a Base-64, UTF-8 encoded `Data`.
///
/// Returns nil when the input is not recognized as valid Base-64.
///
/// - parameter base64Data: Base-64, UTF-8 encoded input data.
/// - parameter options: Decoding options. Default value is `[]`.
public init?(base64Encoded base64Data: Data, options: Data.Base64DecodingOptions = []) {
if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) {
_backing = _DataStorage(immutableReference: d, offset: 0)
_sliceRange = 0..<d.length
} else {
return nil
}
}
/// Initialize a `Data` by adopting a reference type.
///
/// You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation.
///
/// If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass.
///
/// - parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`.
public init(referencing reference: NSData) {
#if DEPLOYMENT_RUNTIME_SWIFT
let providesConcreteBacking = reference._providesConcreteBacking()
#else
let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false
#endif
if providesConcreteBacking {
_backing = _DataStorage(immutableReference: reference.copy() as! NSData, offset: 0)
_sliceRange = 0..<reference.length
} else {
_backing = _DataStorage(customReference: reference.copy() as! NSData, offset: 0)
_sliceRange = 0..<reference.length
}
}
// slightly faster paths for common sequences
@inlinable
public init<S: Sequence>(_ elements: S) where S.Iterator.Element == UInt8 {
let backing = _DataStorage(capacity: Swift.max(elements.underestimatedCount, 1))
var (iter, endIndex) = elements._copyContents(initializing: UnsafeMutableBufferPointer(start: backing._bytes?.bindMemory(to: UInt8.self, capacity: backing._capacity), count: backing._capacity))
backing._length = endIndex
while var element = iter.next() {
backing.append(&element, length: 1)
}
self.init(backing: backing, range: 0..<backing._length)
}
@available(swift, introduced: 4.2)
@inlinable
public init<S: Sequence>(bytes elements: S) where S.Iterator.Element == UInt8 {
self.init(elements)
}
@available(swift, obsoleted: 4.2)
public init(bytes: Array<UInt8>) {
self.init(bytes)
}
@available(swift, obsoleted: 4.2)
public init(bytes: ArraySlice<UInt8>) {
self.init(bytes)
}
@usableFromInline
internal init(backing: _DataStorage, range: Range<Index>) {
_backing = backing
_sliceRange = range
}
@usableFromInline
internal func _validateIndex(_ index: Int, message: String? = nil) {
precondition(_sliceRange.contains(index), message ?? "Index \(index) is out of bounds of range \(_sliceRange)")
}
@usableFromInline
internal func _validateRange<R: RangeExpression>(_ range: R) where R.Bound == Int {
let lower = R.Bound(_sliceRange.lowerBound)
let upper = R.Bound(_sliceRange.upperBound)
let r = range.relative(to: lower..<upper)
precondition(r.lowerBound >= _sliceRange.lowerBound && r.lowerBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)")
precondition(r.upperBound >= _sliceRange.lowerBound && r.upperBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)")
}
// -----------------------------------
// MARK: - Properties and Functions
/// The number of bytes in the data.
public var count: Int {
get {
return _sliceRange.count
}
set {
precondition(count >= 0, "count must not be negative")
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
_backing.length = newValue
_sliceRange = _sliceRange.lowerBound..<(_sliceRange.lowerBound + newValue)
}
}
/// Access the bytes in the data.
///
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
return try _backing.withUnsafeBytes(in: _sliceRange) {
return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafePointer<ContentType>(bitPattern: 0xBAD0)!)
}
}
/// Mutate the bytes in the data.
///
/// This function assumes that you are mutating the contents.
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
return try _backing.withUnsafeMutableBytes(in: _sliceRange) {
return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafeMutablePointer<ContentType>(bitPattern: 0xBAD0)!)
}
}
// MARK: -
// MARK: Copy Bytes
/// Copy the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
/// - parameter count: The number of bytes to copy.
/// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes.
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) {
precondition(count >= 0, "count of bytes to copy must not be negative")
if count == 0 { return }
_backing.withUnsafeBytes(in: _sliceRange) {
memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(count, $0.count))
}
}
private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: NSRange) {
if range.length == 0 { return }
_backing.withUnsafeBytes(in: range.lowerBound..<range.upperBound) {
memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(range.length, $0.count))
}
}
/// Copy a subset of the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
/// - parameter range: The range in the `Data` to copy.
/// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes.
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) {
_copyBytesHelper(to: pointer, from: NSRange(range))
}
// Copy the contents of the data into a buffer.
///
/// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer.
/// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called.
/// - parameter buffer: A buffer to copy the data into.
/// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied.
/// - returns: Number of bytes copied into the destination buffer.
public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int {
let cnt = count
guard cnt > 0 else { return 0 }
let copyRange : Range<Index>
if let r = range {
guard !r.isEmpty else { return 0 }
copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count))
} else {
copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt)
}
_validateRange(copyRange)
guard !copyRange.isEmpty else { return 0 }
let nsRange = NSRange(location: copyRange.lowerBound, length: copyRange.upperBound - copyRange.lowerBound)
_copyBytesHelper(to: buffer.baseAddress!, from: nsRange)
return copyRange.count
}
// MARK: -
#if !DEPLOYMENT_RUNTIME_SWIFT
private func _shouldUseNonAtomicWriteReimplementation(options: Data.WritingOptions = []) -> Bool {
// Avoid a crash that happens on OS X 10.11.x and iOS 9.x or before when writing a bridged Data non-atomically with Foundation's standard write() implementation.
if !options.contains(.atomic) {
#if os(macOS)
return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max)
#else
return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max)
#endif
} else {
return false
}
}
#endif
/// Write the contents of the `Data` to a location.
///
/// - parameter url: The location to write the data into.
/// - parameter options: Options for writing the data. Default value is `[]`.
/// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`.
public func write(to url: URL, options: Data.WritingOptions = []) throws {
try _backing.withInteriorPointerReference(_sliceRange) {
#if DEPLOYMENT_RUNTIME_SWIFT
try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue))
#else
if _shouldUseNonAtomicWriteReimplementation(options: options) {
var error: NSError? = nil
guard __NSDataWriteToURL($0, url, options, &error) else { throw error! }
} else {
try $0.write(to: url, options: options)
}
#endif
}
}
// MARK: -
/// Find the given `Data` in the content of this `Data`.
///
/// - parameter dataToFind: The data to be searched for.
/// - parameter options: Options for the search. Default value is `[]`.
/// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data.
/// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found.
/// - precondition: `range` must be in the bounds of the Data.
public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? {
let nsRange : NSRange
if let r = range {
_validateRange(r)
nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound)
} else {
nsRange = NSRange(location: 0, length: count)
}
let result = _backing.withInteriorPointerReference(_sliceRange) {
$0.range(of: dataToFind, options: options, in: nsRange)
}
if result.location == NSNotFound {
return nil
}
return (result.location + startIndex)..<((result.location + startIndex) + result.length)
}
/// Enumerate the contents of the data.
///
/// In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontiguously. In those cases, this function invokes the closure for each contiguous region of bytes.
/// - parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`.
public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) {
_backing.enumerateBytes(in: _sliceRange, block)
}
@inlinable
internal mutating func _append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
if buffer.isEmpty { return }
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
_backing.replaceBytes(in: NSRange(location: _sliceRange.upperBound, length: _backing.length - (_sliceRange.upperBound - _backing._offset)), with: buffer.baseAddress, length: buffer.count * MemoryLayout<SourceType>.stride)
_sliceRange = _sliceRange.lowerBound..<(_sliceRange.upperBound + buffer.count * MemoryLayout<SourceType>.stride)
}
public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) {
if count == 0 { return }
_append(UnsafeBufferPointer(start: bytes, count: count))
}
public mutating func append(_ other: Data) {
other.enumerateBytes { (buffer, _, _) in
_append(buffer)
}
}
/// Append a buffer of bytes to the data.
///
/// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`.
public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
_append(buffer)
}
public mutating func append(contentsOf bytes: [UInt8]) {
bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in
_append(buffer)
}
}
@inlinable
public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Iterator.Element == Iterator.Element {
let underestimatedCount = Swift.max(newElements.underestimatedCount, 1)
_withStackOrHeapBuffer(underestimatedCount) { (buffer) in
let capacity = buffer.pointee.capacity
let base = buffer.pointee.memory.bindMemory(to: UInt8.self, capacity: capacity)
var (iter, endIndex) = newElements._copyContents(initializing: UnsafeMutableBufferPointer(start: base, count: capacity))
_append(UnsafeBufferPointer(start: base, count: endIndex))
while var element = iter.next() {
append(&element, count: 1)
}
}
}
// MARK: -
/// Set a region of the data to `0`.
///
/// If `range` exceeds the bounds of the data, then the data is resized to fit.
/// - parameter range: The range in the data to set to `0`.
public mutating func resetBytes(in range: Range<Index>) {
// it is worth noting that the range here may be out of bounds of the Data itself (which triggers a growth)
precondition(range.lowerBound >= 0, "Ranges must not be negative bounds")
precondition(range.upperBound >= 0, "Ranges must not be negative bounds")
let range = NSRange(location: range.lowerBound, length: range.upperBound - range.lowerBound)
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
_backing.resetBytes(in: range)
if _sliceRange.upperBound < range.upperBound {
_sliceRange = _sliceRange.lowerBound..<range.upperBound
}
}
/// Replace a region of bytes in the data with new data.
///
/// This will resize the data if required, to fit the entire contents of `data`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append.
/// - parameter data: The replacement data.
public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) {
let cnt = data.count
data.withUnsafeBytes {
replaceSubrange(subrange, with: $0, count: cnt)
}
}
/// Replace a region of bytes in the data with new bytes from a buffer.
///
/// This will resize the data if required, to fit the entire contents of `buffer`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace.
/// - parameter buffer: The replacement bytes.
public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) {
guard !buffer.isEmpty else { return }
replaceSubrange(subrange, with: buffer.baseAddress!, count: buffer.count * MemoryLayout<SourceType>.stride)
}
/// Replace a region of bytes in the data with new bytes from a collection.
///
/// This will resize the data if required, to fit the entire contents of `newElements`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace.
/// - parameter newElements: The replacement bytes.
public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element {
_validateRange(subrange)
let totalCount: Int = numericCast(newElements.count)
_withStackOrHeapBuffer(totalCount) { conditionalBuffer in
let buffer = UnsafeMutableBufferPointer(start: conditionalBuffer.pointee.memory.assumingMemoryBound(to: UInt8.self), count: totalCount)
var (iterator, index) = newElements._copyContents(initializing: buffer)
while let byte = iterator.next() {
buffer[index] = byte
index = buffer.index(after: index)
}
replaceSubrange(subrange, with: conditionalBuffer.pointee.memory, count: totalCount)
}
}
public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) {
_validateRange(subrange)
let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound)
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
let upper = _sliceRange.upperBound
_backing.replaceBytes(in: nsRange, with: bytes, length: cnt)
let resultingUpper = upper - nsRange.length + cnt
_sliceRange = _sliceRange.lowerBound..<resultingUpper
}
/// Return a new copy of the data in a specified range.
///
/// - parameter range: The range to copy.
public func subdata(in range: Range<Index>) -> Data {
_validateRange(range)
if isEmpty {
return Data()
}
return _backing.subdata(in: range)
}
// MARK: -
//
/// Returns a Base-64 encoded string.
///
/// - parameter options: The options to use for the encoding. Default value is `[]`.
/// - returns: The Base-64 encoded string.
public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String {
return _backing.withInteriorPointerReference(_sliceRange) {
return $0.base64EncodedString(options: options)
}
}
/// Returns a Base-64 encoded `Data`.
///
/// - parameter options: The options to use for the encoding. Default value is `[]`.
/// - returns: The Base-64 encoded data.
public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data {
return _backing.withInteriorPointerReference(_sliceRange) {
return $0.base64EncodedData(options: options)
}
}
// MARK: -
//
/// The hash value for the data.
public var hashValue: Int {
var hashValue = 0
let hashRange: Range<Int> = _sliceRange.lowerBound..<Swift.min(_sliceRange.lowerBound + 80, _sliceRange.upperBound)
_withStackOrHeapBuffer(hashRange.count + 1) { buffer in
if !hashRange.isEmpty {
_backing.withUnsafeBytes(in: hashRange) {
memcpy(buffer.pointee.memory, $0.baseAddress!, hashRange.count)
}
}
hashValue = Int(bitPattern: CFHashBytes(buffer.pointee.memory.assumingMemoryBound(to: UInt8.self), hashRange.count))
}
return hashValue
}
public func advanced(by amount: Int) -> Data {
_validateIndex(startIndex + amount)
let length = count - amount
precondition(length > 0)
return withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data in
return Data(bytes: ptr.advanced(by: amount), count: length)
}
}
// MARK: -
// MARK: -
// MARK: Index and Subscript
/// Sets or returns the byte at the specified index.
public subscript(index: Index) -> UInt8 {
get {
_validateIndex(index)
return _backing.get(index)
}
set {
_validateIndex(index)
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
_backing.set(index, to: newValue)
}
}
public subscript(bounds: Range<Index>) -> Data {
get {
_validateRange(bounds)
return Data(backing: _backing, range: bounds)
}
set {
replaceSubrange(bounds, with: newValue)
}
}
public subscript<R: RangeExpression>(_ rangeExpression: R) -> Data
where R.Bound: FixedWidthInteger {
get {
let lower = R.Bound(_sliceRange.lowerBound)
let upper = R.Bound(_sliceRange.upperBound)
let range = rangeExpression.relative(to: lower..<upper)
let start: Int = numericCast(range.lowerBound)
let end: Int = numericCast(range.upperBound)
let r: Range<Int> = start..<end
_validateRange(r)
return Data(backing: _backing, range: r)
}
set {
let lower = R.Bound(_sliceRange.lowerBound)
let upper = R.Bound(_sliceRange.upperBound)
let range = rangeExpression.relative(to: lower..<upper)
let start: Int = numericCast(range.lowerBound)
let end: Int = numericCast(range.upperBound)
let r: Range<Int> = start..<end
_validateRange(r)
replaceSubrange(r, with: newValue)
}
}
/// The start `Index` in the data.
public var startIndex: Index {
get {
return _sliceRange.lowerBound
}
}
/// The end `Index` into the data.
///
/// This is the "one-past-the-end" position, and will always be equal to the `count`.
public var endIndex: Index {
get {
return _sliceRange.upperBound
}
}
public func index(before i: Index) -> Index {
return i - 1
}
public func index(after i: Index) -> Index {
return i + 1
}
public var indices: Range<Int> {
get {
return startIndex..<endIndex
}
}
public func _copyContents(initializing buffer: UnsafeMutableBufferPointer<UInt8>) -> (Iterator, UnsafeMutableBufferPointer<UInt8>.Index) {
guard !isEmpty else { return (makeIterator(), buffer.startIndex) }
guard let p = buffer.baseAddress else {
preconditionFailure("Attempt to copy contents into nil buffer pointer")
}
let cnt = count
precondition(cnt <= buffer.count, "Insufficient space allocated to copy Data contents")
withUnsafeBytes { p.initialize(from: $0, count: cnt) }
return (Iterator(endOf: self), buffer.index(buffer.startIndex, offsetBy: cnt))
}
/// An iterator over the contents of the data.
///
/// The iterator will increment byte-by-byte.
public func makeIterator() -> Data.Iterator {
return Iterator(self)
}
public struct Iterator : IteratorProtocol {
// Both _data and _endIdx should be 'let' rather than 'var'.
// They are 'var' so that the stored properties can be read
// independently of the other contents of the struct. This prevents
// an exclusivity violation when reading '_endIdx' and '_data'
// while simultaneously mutating '_buffer' with the call to
// withUnsafeMutablePointer(). Once we support accessing struct
// let properties independently we should make these variables
// 'let' again.
private var _data: Data
private var _buffer: (
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)
private var _idx: Data.Index
private var _endIdx: Data.Index
fileprivate init(_ data: Data) {
_data = data
_buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
_idx = data.startIndex
_endIdx = data.endIndex
}
fileprivate init(endOf data: Data) {
self._data = data
_buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
_idx = data.endIndex
_endIdx = data.endIndex
}
public mutating func next() -> UInt8? {
guard _idx < _endIdx else { return nil }
defer { _idx += 1 }
let bufferSize = MemoryLayout.size(ofValue: _buffer)
return withUnsafeMutablePointer(to: &_buffer) { ptr_ in
let ptr = UnsafeMutableRawPointer(ptr_).assumingMemoryBound(to: UInt8.self)
let bufferIdx = (_idx - _data.startIndex) % bufferSize
if bufferIdx == 0 {
// populate the buffer
_data.copyBytes(to: ptr, from: _idx..<(_endIdx - _idx > bufferSize ? _idx + bufferSize : _endIdx))
}
return ptr[bufferIdx]
}
}
}
// MARK: -
//
@available(*, unavailable, renamed: "count")
public var length: Int {
get { fatalError() }
set { fatalError() }
}
@available(*, unavailable, message: "use withUnsafeBytes instead")
public var bytes: UnsafeRawPointer { fatalError() }
@available(*, unavailable, message: "use withUnsafeMutableBytes instead")
public var mutableBytes: UnsafeMutableRawPointer { fatalError() }
/// Returns `true` if the two `Data` arguments are equal.
public static func ==(d1 : Data, d2 : Data) -> Bool {
let backing1 = d1._backing
let backing2 = d2._backing
if backing1 === backing2 {
if d1._sliceRange == d2._sliceRange {
return true
}
}
let length1 = d1.count
if length1 != d2.count {
return false
}
if backing1.bytes == backing2.bytes {
if d1._sliceRange == d2._sliceRange {
return true
}
}
if length1 > 0 {
return d1.withUnsafeBytes { (b1) in
return d2.withUnsafeBytes { (b2) in
return memcmp(b1, b2, length1) == 0
}
}
}
return true
}
}
extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
/// A human-readable description for the data.
public var description: String {
return "\(self.count) bytes"
}
/// A human-readable debug description for the data.
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
let nBytes = self.count
var children: [(label: String?, value: Any)] = []
children.append((label: "count", value: nBytes))
self.withUnsafeBytes { (bytes : UnsafePointer<UInt8>) in
children.append((label: "pointer", value: bytes))
}
// Minimal size data is output as an array
if nBytes < 64 {
children.append((label: "bytes", value: Array(self[startIndex..<Swift.min(nBytes + startIndex, endIndex)])))
}
let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.struct)
return m
}
}
extension Data {
@available(*, unavailable, renamed: "copyBytes(to:count:)")
public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, length: Int) { }
@available(*, unavailable, renamed: "copyBytes(to:from:)")
public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, range: NSRange) { }
}
/// Provides bridging functionality for struct Data to class NSData and vice-versa.
extension Data : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSData {
return _backing.bridgedReference(_sliceRange)
}
public static func _forceBridgeFromObjectiveC(_ input: NSData, result: inout Data?) {
// We must copy the input because it might be mutable; just like storing a value type in ObjC
result = Data(referencing: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSData, result: inout Data?) -> Bool {
// We must copy the input because it might be mutable; just like storing a value type in ObjC
result = Data(referencing: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSData?) -> Data {
guard let src = source else { return Data() }
return Data(referencing: src)
}
}
extension NSData : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self))
}
}
extension Data : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
// It's more efficient to pre-allocate the buffer if we can.
if let count = container.count {
self.init(count: count)
// Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space.
// We don't want to write past the end of what we allocated.
for i in 0 ..< count {
let byte = try container.decode(UInt8.self)
self[i] = byte
}
} else {
self.init()
}
while !container.isAtEnd {
var byte = try container.decode(UInt8.self)
self.append(&byte, count: 1)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
// Since enumerateBytes does not rethrow, we need to catch the error, stow it away, and rethrow if we stopped.
var caughtError: Error? = nil
self.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, byteIndex: Data.Index, stop: inout Bool) in
do {
try container.encode(contentsOf: buffer)
} catch {
caughtError = error
stop = true
}
}
if let error = caughtError {
throw error
}
}
}
| apache-2.0 |
overtake/TelegramSwift | Telegram-Mac/EditImageCanvasColorPicker.swift | 1 | 15701 | //
// EditImageCanvasColorPickerBackground.swift
// Telegram
//
// Created by Mikhail Filimonov on 16/04/2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
class EditImageCanvasColorPickerBackground: Control {
override func draw(_ layer: CALayer, in ctx: CGContext) {
super.draw(layer, in: ctx)
let rect = bounds
let radius: CGFloat = rect.size.width > rect.size.height ? rect.size.height / 2.0 : rect.size.width / 2.0
addRoundedRectToPath(ctx, bounds, radius, radius)
ctx.clip()
let colors = EditImageCanvasColorPickerBackground.colors
var locations = EditImageCanvasColorPickerBackground.locations
let colorSpc = CGColorSpaceCreateDeviceRGB()
let gradient: CGGradient = CGGradient(colorsSpace: colorSpc, colors: colors as CFArray, locations: &locations)!
if rect.size.width > rect.size.height {
ctx.drawLinearGradient(gradient, start: CGPoint(x: 0.0, y: rect.size.height / 2.0), end: CGPoint(x: rect.size.width, y: rect.size.height / 2.0), options: .drawsAfterEndLocation)
} else {
ctx.drawLinearGradient(gradient, start: CGPoint(x: rect.size.width / 2.0, y: 0.0), end: CGPoint(x: rect.size.width / 2.0, y: rect.size.height), options: .drawsAfterEndLocation)
}
ctx.setBlendMode(.clear)
ctx.setFillColor(.clear)
}
private func addRoundedRectToPath(_ context: CGContext, _ rect: CGRect, _ ovalWidth: CGFloat, _ ovalHeight: CGFloat) {
var fw: CGFloat
var fh: CGFloat
if ovalWidth == 0 || ovalHeight == 0 {
context.addRect(rect)
return
}
context.saveGState()
context.translateBy(x: rect.minX, y: rect.minY)
context.scaleBy(x: ovalWidth, y: ovalHeight)
fw = rect.width / ovalWidth
fh = rect.height / ovalHeight
context.move(to: CGPoint(x: fw, y: fh / 2))
context.addArc(tangent1End: CGPoint(x: fw, y: fh), tangent2End: CGPoint(x: fw / 2, y: fh), radius: 1)
context.addArc(tangent1End: CGPoint(x: 0, y: fh), tangent2End: CGPoint(x: 0, y: fh / 2), radius: 1)
context.addArc(tangent1End: CGPoint(x: 0, y: 0), tangent2End: CGPoint(x: fw / 2, y: 0), radius: 1)
context.addArc(tangent1End: CGPoint(x: fw, y: 0), tangent2End: CGPoint(x: fw, y: fh / 2), radius: 1)
context.closePath()
context.restoreGState()
}
func color(for location: CGFloat) -> NSColor {
let locations = EditImageCanvasColorPickerBackground.locations
let colors = EditImageCanvasColorPickerBackground.colors
if location < .ulpOfOne {
return NSColor(cgColor: colors[0])!
} else if location > 1 - .ulpOfOne {
return NSColor(cgColor: colors[colors.count - 1])!
}
var leftIndex: Int = -1
var rightIndex: Int = -1
for (index, value) in locations.enumerated() {
if index > 0 {
if value > location {
leftIndex = index - 1
rightIndex = index
break
}
}
}
let leftLocation = locations[leftIndex]
let leftColor = NSColor(cgColor: colors[leftIndex])!
let rightLocation = locations[rightIndex]
let rightColor = NSColor(cgColor: colors[rightIndex])!
let factor = (location - leftLocation) / (rightLocation - leftLocation)
return self.interpolateColor(color1: leftColor, color2: rightColor, factor: factor)
}
private func interpolateColor(color1: NSColor, color2: NSColor, factor: CGFloat) -> NSColor {
let factor = min(max(factor, 0.0), 1.0)
var r1: CGFloat = 0
var r2: CGFloat = 0
var g1: CGFloat = 0
var g2: CGFloat = 0
var b1: CGFloat = 0
var b2: CGFloat = 0
self.colorComponentsFor(color1, red: &r1, green: &g1, blue: &b1)
self.colorComponentsFor(color2, red: &r2, green: &g2, blue: &b2)
let r = r1 + (r2 - r1) * factor;
let g = g1 + (g2 - g1) * factor;
let b = b1 + (b2 - b1) * factor;
return NSColor(red: r, green: g, blue: b, alpha: 1.0)
}
private func colorComponentsFor(_ color: NSColor, red:inout CGFloat, green:inout CGFloat, blue:inout CGFloat) {
let componentsCount = color.cgColor.numberOfComponents
let components = color.cgColor.components
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 1.0
if componentsCount == 4 {
r = components?[0] ?? 0.0
g = components?[1] ?? 0.0
b = components?[2] ?? 0.0
a = components?[3] ?? 0.0
} else {
b = components?[0] ?? 0.0
g = b
r = g
}
red = r
green = g
blue = b
}
static var colors: [CGColor] {
return [NSColor(0xea2739).cgColor,
NSColor(0xdb3ad2).cgColor,
NSColor(0x3051e3).cgColor,
NSColor(0x49c5ed).cgColor,
NSColor(0x80c864).cgColor,
NSColor(0xfcde65).cgColor,
NSColor(0xfc964d).cgColor,
NSColor(0x000000).cgColor,
NSColor(0xffffff).cgColor
]
}
static var locations: [CGFloat] {
return [ 0.0, //red
0.14, //pink
0.24, //blue
0.39, //cyan
0.49, //green
0.62, //yellow
0.73, //orange
0.85, //black
1.0
]
}
}
private final class PaintColorPickerKnobCircleView : View {
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var strokeIntensity: CGFloat = 0
var strokesLowContrastColors: Bool = false
override var needsLayout: Bool {
didSet {
needsDisplay = true
}
}
var color: NSColor = .black {
didSet {
if strokesLowContrastColors {
var strokeIntensity: CGFloat = 0.0
var hue: CGFloat = 0
var saturation: CGFloat = 0
var brightness: CGFloat = 0
var alpha: CGFloat = 0
color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
if hue < CGFloat.ulpOfOne && saturation < CGFloat.ulpOfOne && brightness > 0.92 {
strokeIntensity = (brightness - 0.92) / 0.08
}
self.strokeIntensity = strokeIntensity
}
needsDisplay = true
}
}
override func draw(_ layer: CALayer, in context: CGContext) {
super.draw(layer, in: context)
let rect = bounds
context.setFillColor(color.cgColor)
context.fillEllipse(in: rect)
if strokeIntensity > .ulpOfOne {
context.setLineWidth(1.0)
context.setStrokeColor(NSColor(white: 0.88, alpha: strokeIntensity).cgColor)
context.strokeEllipse(in: rect.insetBy(dx: 1.0, dy: 1.0))
}
}
}
private let paintColorSmallCircle: CGFloat = 4.0
private let paintColorLargeCircle: CGFloat = 20.0
private let paintColorWeightGestureRange: CGFloat = 200
private let paintVerticalThreshold: CGFloat = 5
private let paintPreviewOffset: CGFloat = -60
private let paintPreviewScale: CGFloat = 2.0
private let paintDefaultBrushWeight: CGFloat = 0.22
private let oaintDefaultColorLocation: CGFloat = 1.0
private final class PaintColorPickerKnob: View {
fileprivate var isZoomed: Bool = false
fileprivate var weight: CGFloat = 0.5
fileprivate func updateWeight(_ weight: CGFloat, animated: Bool) {
self.weight = weight
var diameter = circleDiameter(forBrushWeight: weight, zoomed: self.isZoomed)
if Int(diameter) % 2 != 0 {
diameter -= 1
}
colorView.setFrameSize(NSMakeSize(diameter, diameter))
backgroundView.setFrameSize(NSMakeSize(24 * (isZoomed ? paintPreviewScale : 1), 24 * (isZoomed ? paintPreviewScale : 1)))
backgroundView.center()
if animated {
if isZoomed {
colorView.layer?.animateScaleSpring(from: 0.5, to: 1, duration: 0.3)
backgroundView.layer?.animateScaleSpring(from: 0.5, to: 1, duration: 0.3)
} else {
colorView.layer?.animateScaleSpring(from: 2.0, to: 1, duration: 0.3)
backgroundView.layer?.animateScaleSpring(from: 2.0, to: 1, duration: 0.3)
}
}
needsLayout = true
}
fileprivate var color: NSColor = .random {
didSet {
colorView.color = color
}
}
fileprivate var width: CGFloat {
return circleDiameter(forBrushWeight: weight, zoomed: false) - 2
}
private let backgroundView = PaintColorPickerKnobCircleView(frame: .zero)
private let colorView = PaintColorPickerKnobCircleView(frame: .zero)
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
backgroundView.color = NSColor(0xffffff)
backgroundView.isEventLess = true
colorView.isEventLess = true
colorView.color = NSColor.blue
colorView.strokesLowContrastColors = true
addSubview(backgroundView)
addSubview(colorView)
}
func circleDiameter(forBrushWeight size: CGFloat, zoomed: Bool) -> CGFloat {
var result = CGFloat(paintColorSmallCircle) + CGFloat((paintColorLargeCircle - paintColorSmallCircle)) * size
result = CGFloat(zoomed ? result * paintPreviewScale : floor(result))
return floorToScreenPixels(backingScaleFactor, result)
}
override func layout() {
super.layout()
backgroundView.setFrameSize(NSMakeSize(24 * (isZoomed ? paintPreviewScale : 1), 24 * (isZoomed ? paintPreviewScale : 1)))
backgroundView.center()
colorView.center()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
final class EditImageColorPicker: View {
var arguments: EditImageCanvasArguments? {
didSet {
arguments?.updateColorAndWidth(knobView.color, knobView.width)
}
}
private let knobView = PaintColorPickerKnob(frame: NSMakeRect(0, 0, 24 * paintPreviewScale, 24 * paintPreviewScale))
let backgroundView = EditImageCanvasColorPickerBackground()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(backgroundView)
addSubview(knobView)
knobView.isEventLess = true
knobView.userInteractionEnabled = false
backgroundView.set(handler: { [weak self] _ in
self?.updateLocation(animated: false)
}, for: .MouseDragging)
backgroundView.set(handler: { [weak self] _ in
self?.knobView.isZoomed = true
self?.updateLocation(animated: true)
}, for: .Down)
backgroundView.set(handler: { [weak self] _ in
self?.knobView.isZoomed = false
self?.updateLocation(animated: true)
}, for: .Up)
let colorValue = UserDefaults.standard.value(forKey: "painterColorLocation") as? CGFloat
let weightValue = UserDefaults.standard.value(forKey: "painterBrushWeight") as? CGFloat
let colorLocation: CGFloat
if let colorValue = colorValue {
colorLocation = colorValue
} else {
colorLocation = CGFloat(arc4random()) / CGFloat(UInt32.max)
UserDefaults.standard.setValue(colorLocation, forKey: "painterColorLocation")
}
self.location = colorLocation
knobView.color = backgroundView.color(for: colorLocation)
let weight = weightValue ?? paintDefaultBrushWeight
knobView.updateWeight(weight, animated: false)
}
private var location: CGFloat = 0
private func updateLocation(animated: Bool) {
guard let window = self.window else {
return
}
let location = backgroundView.convert(window.mouseLocationOutsideOfEventStream, from: nil)
let colorLocation = max(0.0, min(1.0, location.x / backgroundView.frame.width))
self.location = colorLocation
knobView.color = backgroundView.color(for: colorLocation)
let threshold = min(max(frame.height - backgroundView.frame.minY, frame.height - self.convert(window.mouseLocationOutsideOfEventStream, from: nil).y), paintColorWeightGestureRange + paintPreviewOffset)
let weight = threshold / (paintColorWeightGestureRange + paintPreviewOffset);
knobView.updateWeight(weight, animated: animated)
arguments?.updateColorAndWidth(knobView.color, knobView.width)
UserDefaults.standard.set(Double(colorLocation), forKey: "painterColorLocation")
UserDefaults.standard.set(Double(weight), forKey: "painterBrushWeight")
if animated {
knobView.layer?.animatePosition(from: NSMakePoint(knobView.frame.minX - knobPosition.x, knobView.frame.minY - knobPosition.y), to: .zero, duration: 0.3, timingFunction: .spring, removeOnCompletion: true, additive: true)
}
needsLayout = true
}
override var isEventLess: Bool {
get {
guard let window = self.window else {
return false
}
let point = self.convert(window.mouseLocationOutsideOfEventStream, from: nil)
if NSPointInRect(point, backgroundView.frame) || NSPointInRect(point, knobView.frame) {
return false
} else {
return true
}
}
set {
super.isEventLess = newValue
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var knobPosition: NSPoint {
guard let window = self.window else {
return .zero
}
let threshold: CGFloat
if knobView.isZoomed {
threshold = min(max(0, frame.height - self.convert(window.mouseLocationOutsideOfEventStream, from: nil).y - (frame.height - backgroundView.frame.minY)), paintColorWeightGestureRange)
} else {
threshold = 0
}
let knobY: CGFloat = max(0, (backgroundView.frame.midY - knobView.frame.height / 2) + (knobView.isZoomed ? paintPreviewOffset : 0) + -threshold)
let knobX: CGFloat = max(0, min(backgroundView.frame.width * location, self.frame.width - knobView.frame.width))
return NSMakePoint(knobX, knobY)
}
override func layout() {
super.layout()
backgroundView.frame = NSMakeRect(24, frame.height - 24, frame.width - 48, 20)
knobView.frame = CGRect(x: knobPosition.x, y: knobPosition.y, width: knobView.frame.size.width, height: knobView.frame.size.height)
}
}
| gpl-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/01071-swift-modulefile-lookupvalue.swift | 11 | 468 | // 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
// RUN: not %target-swift-frontend %s -parse
struct c<e> {
let d: i h
}
struct d<c : e, d: e where d.e == c(c:<b>) {
}
d
| apache-2.0 |
natecook1000/swift | test/Runtime/demangleToMetadataObjC.swift | 2 | 2656 | // RUN: %target-run-simple-swift-swift3
// REQUIRES: executable_test
// REQUIRES: objc_interop
import StdlibUnittest
import Foundation
import CoreFoundation
import CoreLocation
let DemangleToMetadataTests = TestSuite("DemangleToMetadataObjC")
@objc class C : NSObject { }
@objc enum E: Int { case a }
@objc protocol P1 { }
protocol P2 { }
DemangleToMetadataTests.test("@objc classes") {
expectEqual(type(of: C()), _typeByMangledName("4main1CC")!)
}
DemangleToMetadataTests.test("@objc enums") {
expectEqual(type(of: E.a), _typeByMangledName("4main1EO")!)
}
func f1_composition_objc_protocol(_: P1) { }
DemangleToMetadataTests.test("@objc protocols") {
expectEqual(type(of: f1_composition_objc_protocol),
_typeByMangledName("yy4main2P1_pc")!)
}
DemangleToMetadataTests.test("Objective-C classes") {
expectEqual(type(of: NSObject()), _typeByMangledName("So8NSObjectC")!)
}
func f1_composition_NSCoding(_: NSCoding) { }
DemangleToMetadataTests.test("Objective-C protocols") {
expectEqual(type(of: f1_composition_NSCoding), _typeByMangledName("yySo8NSCoding_pc")!)
}
DemangleToMetadataTests.test("Classes that don't exist") {
expectNil(_typeByMangledName("4main4BoomC"))
}
DemangleToMetadataTests.test("CoreFoundation classes") {
expectEqual(CFArray.self, _typeByMangledName("So10CFArrayRefa")!)
}
DemangleToMetadataTests.test("Imported error types") {
expectEqual(URLError.self, _typeByMangledName("10Foundation8URLErrorV")!)
expectEqual(URLError.Code.self,
_typeByMangledName("10Foundation8URLErrorV4CodeV")!)
}
DemangleToMetadataTests.test("Imported swift_wrapper types") {
expectEqual(URLFileResourceType.self,
_typeByMangledName("So21NSURLFileResourceTypea")!)
}
DemangleToMetadataTests.test("Imported enum types") {
expectEqual(NSURLSessionTask.State.self,
_typeByMangledName("So21NSURLSessionTaskStateV")!)
}
class CG4<T: P1, U: P2> { }
extension C : P1 { }
extension C : P2 { }
class D: P2 { }
DemangleToMetadataTests.test("@objc protocol conformances") {
expectEqual(CG4<C, C>.self,
_typeByMangledName("4main3CG4CyAA1CCAA1CCG")!)
expectNil(_typeByMangledName("4main3CG4CyAA1DCAA1DCG"))
}
DemangleToMetadataTests.test("synthesized declarations") {
expectEqual(CLError.self, _typeByMangledName("SC7CLErrorLeV")!)
expectNil(_typeByMangledName("SC7CLErrorV"))
expectEqual(CLError.Code.self, _typeByMangledName("So7CLErrorV")!)
let error = NSError(domain: NSCocoaErrorDomain, code: 0)
let reflectionString = String(reflecting: CLError(_nsError: error))
expectTrue(reflectionString.hasPrefix("__C_Synthesized.related decl 'e' for CLError(_nsError:"))
}
runAllTests()
| apache-2.0 |
remirobert/MyCurrency | MyCurrency/CurrencyModel.swift | 1 | 617 | //
// CurrencyModel.swift
// MyCurrency
//
// Created by Remi Robert on 10/12/2016.
// Copyright © 2016 Remi Robert. All rights reserved.
//
import UIKit
struct CurrencyModel {
var to: Currency
var from: Currency
var rate: Double
init?(json: [String:AnyObject]) {
guard let to = Currency(rawValue: (json["to"] as? String) ?? ""),
let from = Currency(rawValue: (json["from"] as? String) ?? ""),
let rate = json["rate"] as? Double else {
return nil
}
self.to = to
self.from = from
self.rate = rate
}
}
| mit |
arvedviehweger/swift | test/IRGen/objc_pointers.swift | 4 | 1063 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
@objc class Foo : NSObject {
// CHECK: define internal void @_T013objc_pointers3FooC16pointerArgumentsySpySiG_Sv1ySPySiG1zs33AutoreleasingUnsafeMutablePointerVyACSgG1wtFTo(%0*, i8*, i64*, i8*, i64*, %0**)
@objc func pointerArguments(_ x: UnsafeMutablePointer<Int>,
y: UnsafeMutableRawPointer,
z: UnsafePointer<Int>,
w: AutoreleasingUnsafeMutablePointer<Foo?>) {}
// CHECK: define internal void @_T013objc_pointers3FooC24pointerMetatypeArgumentsys33AutoreleasingUnsafeMutablePointerVys9AnyObject_pXpG1x_AFysAG_pXpSgG1ytFTo(%0*, i8*, i8**, i8**)
@objc func pointerMetatypeArguments(x: AutoreleasingUnsafeMutablePointer<AnyClass>,
y: AutoreleasingUnsafeMutablePointer<AnyClass?>) {}
}
| apache-2.0 |
xebia/xtime-ios | xtime-ios/xtime-ios/XTimeProxyApi.swift | 1 | 1703 | //
// XTimeProxyApi.swift
// xtime-ios
//
// Created by Steven Mulder on 8/22/14.
// Copyright (c) 2014 Xebia Nederland B.V. All rights reserved.
//
import Foundation
class XTimeProxyApi : API {
func getWeekOverview(request: GetWeekOverviewRequest, callback: GetWeekOverviewResponse -> Void, error: NSErrorPointer) {
let url = NSURL(string: "http://localhost:9000/week?date=2014-08-11")
var request = NSMutableURLRequest(URL: url)
request.setValue("username=smulder; JSESSIONID=5678C9CB30F010E03353107E93E1268E; _hp2_id.2790962031=4600497982186508.0.0; s_fid=0001184F49D05B24-3B6EB99660721A7C; __utma=179778477.69251742.1379142638.1391176259.1393790031.13; __utmz=179778477.1379142638.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _ga=GA1.2.69251742.1379142638; hsfirstvisit=http%3A%2F%2Ftraining.xebia.com%2Fsummer-specials%2Fsummer-special-automated-acceptance-testing-with-fitnesse-and-appium||1401696949959; __hstc=232286976.12e4110469efdd95968c50621192e0cc.1401696949961.1401696949961.1401696949961.1; hubspotutk=12e4110469efdd95968c50621192e0cc", forHTTPHeaderField: "Cookie")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {(data, response, error) in
println("response")
}
task.resume()
callback( GetWeekOverviewResponse(lastTransferred: 0, monthlyDataApproved: false, projects: [], timesheetRows: [], username: "") )
}
func getWorkTypesForProject(request: GetWorkTypesForProjectRequest, callback: GetWorkTypesForProjectResponse -> Void, error: NSErrorPointer) {
callback( GetWorkTypesForProjectResponse(workTypes: []) )
}
} | apache-2.0 |
alokc83/rayW-SwiftSeries | RW_SwiftSeries-classes-chellenge8.playground/Contents.swift | 1 | 2384 | //: Playground - noun: a place where people can play
import UIKit
// Classes part 8 || challenge 8
class Account{
var firstName:String
var lastName:String
var balance: Double
var rate = 0.0
init(firstName:String, lastName:String, balance:Double){
self.firstName = firstName
self.lastName = lastName
self.balance = balance
}
convenience init(){
self.init(firstName:"", lastName:"", balance:0)
}
func interestOverYears(years:Double) -> Double{
return 0
}
func printBreakDown(){
var balance = NSString(format: "%f", self.balance)
println("\(firstName) \(lastName): \(balance)")
}
}
class CheckingAccount:Account{
override init(firstName:String, lastName:String, balance:Double){
super.init(firstName:firstName, lastName:lastName, balance:balance)
self.rate = 4.3
}
override func interestOverYears(years: Double) -> Double {
return (balance * rate * years) / 100
}
}
var account = Account(firstName: "Alok", lastName: "Cewalll", balance: 1.0)
account.printBreakDown()
var account2 = Account()
var checkingAccont = CheckingAccount(firstName: "Alok", lastName: "Cewall", balance: 200_000)
checkingAccont.interestOverYears(5)
class Animal{
var name:String
init(name:String){
self.name = name
}
func speak() -> (String?){
return nil
}
}
class Dog:Animal{
override init(name: String) {
super.init(name: name)
}
convenience init() {
self.init(name:"")
}
override func speak() -> (String?) {
return "Woof Woof"
}
}
class Cat:Animal{
override init(name: String) {
super.init(name: name)
}
convenience init() {
self.init(name:"")
}
override func speak() -> (String?) {
return "Meow Meow"
}
}
class Fox:Animal{
override init(name: String) {
super.init(name: name)
}
convenience init() {
self.init(name:"")
}
override func speak() -> (String?) {
return "ding ding"
}
}
var spoty = Dog(name: "Spoty")
spoty.speak()
var kitty = Cat(name: "Kitty")
kitty.speak()
var foxy = Fox(name: "foxy")
foxy.speak()
let animals = [Dog(), Cat(), Fox()]
for animal in animals{
animal.speak()
}
| mit |
toohotz/IQKeyboardManager | Demo/Swift_Demo/ViewController/YYTextViewController.swift | 1 | 817 | //
// YYTextViewController.swift
// Demo
//
// Created by IEMacBook01 on 23/05/16.
// Copyright © 2016 Iftekhar. All rights reserved.
//
class YYTextViewController: UIViewController, YYTextViewDelegate {
@IBOutlet var textView : YYTextView!
override internal class func initialize() {
super.initialize()
IQKeyboardManager.sharedManager().registerTextFieldViewClass(YYTextView.self, didBeginEditingNotificationName: YYTextViewTextDidBeginEditingNotification, didEndEditingNotificationName: YYTextViewTextDidEndEditingNotification)
}
override func viewDidLoad() {
super.viewDidLoad()
textView.placeholderText = "This is placeholder text of YYTextView"
}
func textViewDidBeginEditing(tv: YYTextView) {
tv.reloadInputViews()
}
}
| mit |
jmcalister1/iOS-Calculator | ClassCalculator/ViewController.swift | 1 | 1694 | //
// ViewController.swift
// ClassCalculator
//
// Created by Joshua McAlister on 1/24/17.
// Copyright © 2017 Harding University. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var userIsTyping = false
var CPU = CalculatorCPU()
@IBOutlet weak var display: UILabel!
private var myFormatter = NumberFormatter()
var displayValue:Double {
get {
return Double(display.text!) ?? 0.0
}
set {
myFormatter.minimumIntegerDigits = 1
myFormatter.maximumFractionDigits = 10
display.text = myFormatter.string(from: NSNumber(value:newValue)) ?? "0"
}
}
@IBAction func digitPressed(_ sender: UIButton) {
if let digit = sender.currentTitle {
if userIsTyping {
display.text! += digit
} else {
display.text = digit
}
userIsTyping = true
}
}
@IBAction func touchDecimalPoint(_ sender: UIButton) {
if let str = display.text {
if userIsTyping {
if !str.contains(".") {
display.text! += "."
}
} else {
display.text = "0."
}
userIsTyping = true
}
}
@IBAction func doOperation(_ sender: UIButton) {
if userIsTyping {
CPU.setOperand(operand: displayValue)
userIsTyping = false
}
if let mathSymbol = sender.currentTitle {
CPU.performOperation(symbol: mathSymbol)
}
displayValue = CPU.result
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers/25819-std-function-func-swift-type-subst.swift | 9 | 273 | // 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
class B<T{
enum P{class A{
enum S{
case c
let a=c
| apache-2.0 |
TouchInstinct/LeadKit | TIMapUtils/Sources/MapItem/Clusterable.swift | 1 | 1254 | //
// Copyright (c) 2022 Touch Instinct
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public protocol Clusterable {
associatedtype ClusterIdentifier
var clusterIdentifier: ClusterIdentifier { get }
}
| apache-2.0 |
WEIHOME/SliderExample-Swift | TipCalc.swift | 1 | 1208 | //
// TipCalc.swift
// TipCalc
//
// Created by Weihong Chen on 26/03/2015.
// Copyright (c) 2015 Weihong. All rights reserved.
//
import Foundation
class TipCalc {
var tipAmount: Float = 0
var taxAmount: Float = 0
var amountBeforeTax: Float = 0
var amountAfterTax: Float = 0
var amountTotal: Float = 0
var tipPercentage: Float = 0
var taxPercentage: Float = 0
var howManyPeople: Int = 0
var average: Float = 0
init(amountBeforeTax:Float, tipPercentage:Float, taxPercentage:Float, howManyPeople:Int) {
self.amountBeforeTax = amountBeforeTax
self.tipPercentage = tipPercentage
self.taxPercentage = taxPercentage
self.howManyPeople = howManyPeople
}
func calculateTip() {
tipAmount = amountBeforeTax * tipPercentage
}
func calculateTotalIncludedTaxAndTip(){
amountTotal = amountBeforeTax * taxPercentage + tipAmount + amountBeforeTax
}
func averageForPerPerson(){
average = amountTotal / Float(howManyPeople)
}
func calculateAmountAfterTax(){
amountAfterTax = amountBeforeTax * taxPercentage + amountBeforeTax
}
} | mit |
optimizely/objective-c-sdk | Pods/Mixpanel-swift/Mixpanel/BaseNotificationViewController.swift | 2 | 2701 | //
// BaseNotificationViewController.swift
// Mixpanel
//
// Created by Yarden Eitan on 8/11/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import UIKit
protocol NotificationViewControllerDelegate {
@discardableResult
func notificationShouldDismiss(controller: BaseNotificationViewController,
callToActionURL: URL?,
shouldTrack: Bool,
additionalTrackingProperties: Properties?) -> Bool
}
class BaseNotificationViewController: UIViewController {
var notification: InAppNotification!
var delegate: NotificationViewControllerDelegate?
var window: UIWindow?
var panStartPoint: CGPoint!
convenience init(notification: InAppNotification, nameOfClass: String) {
// avoiding `type(of: self)` as it doesn't work with Swift 4.0.3 compiler
// perhaps due to `self` not being fully constructed at this point
let bundle = Bundle(for: BaseNotificationViewController.self)
self.init(nibName: nameOfClass, bundle: bundle)
self.notification = notification
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .all
}
override var shouldAutorotate: Bool {
return true
}
func show(animated: Bool) {}
func hide(animated: Bool, completion: @escaping () -> Void) {}
}
extension UIColor {
/**
The shorthand four-digit hexadecimal representation of color with alpha.
#RGBA defines to the color #AARRGGBB.
- parameter MPHex: hexadecimal value.
*/
public convenience init(MPHex: UInt) {
let divisor = CGFloat(255)
let alpha = CGFloat((MPHex & 0xFF000000) >> 24) / divisor
let red = CGFloat((MPHex & 0x00FF0000) >> 16) / divisor
let green = CGFloat((MPHex & 0x0000FF00) >> 8) / divisor
let blue = CGFloat( MPHex & 0x000000FF ) / divisor
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
/**
Add two colors together
*/
func add(overlay: UIColor) -> UIColor {
var bgR: CGFloat = 0
var bgG: CGFloat = 0
var bgB: CGFloat = 0
var bgA: CGFloat = 0
var fgR: CGFloat = 0
var fgG: CGFloat = 0
var fgB: CGFloat = 0
var fgA: CGFloat = 0
self.getRed(&bgR, green: &bgG, blue: &bgB, alpha: &bgA)
overlay.getRed(&fgR, green: &fgG, blue: &fgB, alpha: &fgA)
let r = fgA * fgR + (1 - fgA) * bgR
let g = fgA * fgG + (1 - fgA) * bgG
let b = fgA * fgB + (1 - fgA) * bgB
return UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
}
| apache-2.0 |
beforeload/calculate-app | Calculate/ViewController.swift | 1 | 2652 | //
// ViewController.swift
// Calculate
//
// Created by daniel on 9/25/14.
// Copyright (c) 2014 beforeload. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var lastNumber: String = ""
var endAllCalc: Bool = false
var endOneCalc: Bool = false
@IBOutlet weak var answerField: UILabel!
@IBOutlet weak var operatorLabel: UILabel!
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.
}
@IBAction func buttonTapped(theButton: UIButton) {
if answerField.text == "0" || endAllCalc || endOneCalc {
endAllCalc = false
endOneCalc = false
answerField.text = theButton.titleLabel?.text
} else {
if let txt = theButton.titleLabel?.text {
answerField.text = answerField.text! + txt
}
}
}
@IBAction func ClearTapped(sender: AnyObject) {
answerField.text = "0"
operatorLabel.text = ""
lastNumber = ""
}
@IBAction func minusTapped(sender: UIButton) {
if operatorLabel.text == "" {
operatorLabel.text = "-"
lastNumber = answerField.text!
answerField.text = "0"
} else {
caculate()
operatorLabel.text = "-"
}
}
@IBAction func plusTapped(sender: UIButton) {
if operatorLabel.text == "" {
operatorLabel.text = "+"
lastNumber = answerField.text!
answerField.text = "0"
} else {
caculate()
operatorLabel.text = "+"
}
}
@IBAction func enterTapped() {
endAllCalc = true
caculate()
}
func caculate() {
var num1 = lastNumber.toInt()
var num2 = answerField.text?.toInt()
var answer = 0
if (num1 == nil || (num2 == nil)) {
showError()
return
}
if operatorLabel.text == "-" {
answer = num1! - num2!
} else if operatorLabel.text == "+" {
answer = num1! + num2!
} else {
showError()
return
}
answerField.text = "\(answer)"
operatorLabel.text = ""
endOneCalc = true
if endAllCalc {
lastNumber = ""
} else {
lastNumber = "\(answer)"
}
}
func showError() {
}
}
| mit |
xusader/firefox-ios | Sync/State.swift | 2 | 13077 | /* 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 Shared
import XCGLogger
// TODO: same comment as for SyncAuthState.swift!
private let log = XCGLogger.defaultInstance()
/*
* This file includes types that manage intra-sync and inter-sync metadata
* for the use of synchronizers and the state machine.
*
* See docs/sync.md for details on what exactly we need to persist.
*/
public struct Fetched<T: Equatable>: Equatable {
let value: T
let timestamp: Timestamp
}
public func ==<T: Equatable>(lhs: Fetched<T>, rhs: Fetched<T>) -> Bool {
return lhs.timestamp == rhs.timestamp &&
lhs.value == rhs.value
}
/*
* Persistence pref names.
* Note that syncKeyBundle isn't persisted by us.
*
* Note also that fetched keys aren't kept in prefs: we keep the timestamp ("PrefKeysTS"),
* and we keep a 'label'. This label is used to find the real fetched keys in the Keychain.
*/
private let PrefVersion = "_v"
private let PrefGlobal = "global"
private let PrefGlobalTS = "globalTS"
private let PrefKeyLabel = "keyLabel"
private let PrefKeysTS = "keysTS"
private let PrefLastFetched = "lastFetched"
private let PrefClientName = "clientName"
private let PrefClientGUID = "clientGUID"
/**
* The scratchpad consists of the following:
*
* 1. Cached records. We cache meta/global and crypto/keys until they change.
* 2. Metadata like timestamps, both for cached records and for server fetches.
* 3. User preferences -- engine enablement.
* 4. Client record state.
*
* Note that the scratchpad itself is immutable, but is a class passed by reference.
* Its mutable fields can be mutated, but you can't accidentally e.g., switch out
* meta/global and get confused.
*
* TODO: the Scratchpad needs to be loaded from persistent storage, and written
* back at certain points in the state machine (after a replayable action is taken).
*/
public class Scratchpad {
public class Builder {
var syncKeyBundle: KeyBundle // For the love of god, if you change this, invalidate keys, too!
private var global: Fetched<MetaGlobal>?
private var keys: Fetched<Keys>?
private var keyLabel: String
var collectionLastFetched: [String: Timestamp]
var engineConfiguration: EngineConfiguration?
var clientGUID: String
var clientName: String
var prefs: Prefs
init(p: Scratchpad) {
self.syncKeyBundle = p.syncKeyBundle
self.prefs = p.prefs
self.global = p.global
self.keys = p.keys
self.keyLabel = p.keyLabel
self.collectionLastFetched = p.collectionLastFetched
self.engineConfiguration = p.engineConfiguration
self.clientGUID = p.clientGUID
self.clientName = p.clientName
}
public func setKeys(keys: Fetched<Keys>?) -> Builder {
self.keys = keys
if let keys = keys {
self.collectionLastFetched["crypto"] = keys.timestamp
}
return self
}
public func setGlobal(global: Fetched<MetaGlobal>?) -> Builder {
self.global = global
if let global = global {
self.collectionLastFetched["meta"] = global.timestamp
}
return self
}
public func clearFetchTimestamps() -> Builder {
self.collectionLastFetched = [:]
return self
}
public func build() -> Scratchpad {
return Scratchpad(
b: self.syncKeyBundle,
m: self.global,
k: self.keys,
keyLabel: self.keyLabel,
fetches: self.collectionLastFetched,
engines: self.engineConfiguration,
clientGUID: self.clientGUID,
clientName: self.clientName,
persistingTo: self.prefs
)
}
}
public func evolve() -> Scratchpad.Builder {
return Scratchpad.Builder(p: self)
}
// This is never persisted.
let syncKeyBundle: KeyBundle
// Cached records.
// This cached meta/global is what we use to add or remove enabled engines. See also
// engineConfiguration, below.
// We also use it to detect when meta/global hasn't changed -- compare timestamps.
//
// Note that a Scratchpad held by a Ready state will have the current server meta/global
// here. That means we don't need to track syncIDs separately (which is how desktop and
// Android are implemented).
// If we don't have a meta/global, and thus we don't know syncIDs, it means we haven't
// synced with this server before, and we'll do a fresh sync.
let global: Fetched<MetaGlobal>?
// We don't store these keys (so-called "collection keys" or "bulk keys") in Prefs.
// Instead, we store a label, which is seeded when you first create a Scratchpad.
// This label is used to retrieve the real keys from your Keychain.
//
// Note that we also don't store the syncKeyBundle here. That's always created from kB,
// provided by the Firefox Account.
//
// Why don't we derive the label from your Sync Key? Firstly, we'd like to be able to
// clean up without having your key. Secondly, we don't want to accidentally load keys
// from the Keychain just because the Sync Key is the same -- e.g., after a node
// reassignment. Randomly generating a label offers all of the benefits with none of the
// problems, with only the cost of persisting that label alongside the rest of the state.
let keys: Fetched<Keys>?
let keyLabel: String
// Collection timestamps.
var collectionLastFetched: [String: Timestamp]
// Enablement states.
let engineConfiguration: EngineConfiguration?
// What's our client name?
let clientName: String
let clientGUID: String
// Where do we persist when told?
let prefs: Prefs
init(b: KeyBundle,
m: Fetched<MetaGlobal>?,
k: Fetched<Keys>?,
keyLabel: String,
fetches: [String: Timestamp],
engines: EngineConfiguration?,
clientGUID: String,
clientName: String,
persistingTo prefs: Prefs
) {
self.syncKeyBundle = b
self.prefs = prefs
self.keys = k
self.keyLabel = keyLabel
self.global = m
self.engineConfiguration = engines
self.collectionLastFetched = fetches
self.clientGUID = clientGUID
self.clientName = clientName
}
// This should never be used in the end; we'll unpickle instead.
// This should be a convenience initializer, but... Swift compiler bug?
init(b: KeyBundle, persistingTo prefs: Prefs) {
self.syncKeyBundle = b
self.prefs = prefs
self.keys = nil
self.keyLabel = Bytes.generateGUID()
self.global = nil
self.engineConfiguration = nil
self.collectionLastFetched = [String: Timestamp]()
self.clientGUID = Bytes.generateGUID()
self.clientName = DeviceInfo.defaultClientName()
}
// For convenience.
func withGlobal(m: Fetched<MetaGlobal>?) -> Scratchpad {
return self.evolve().setGlobal(m).build()
}
func freshStartWithGlobal(global: Fetched<MetaGlobal>) -> Scratchpad {
// TODO: I *think* a new keyLabel is unnecessary.
return self.evolve()
.setGlobal(global)
.setKeys(nil)
.clearFetchTimestamps()
.build()
}
func applyEngineChoices(old: MetaGlobal?) -> (Scratchpad, MetaGlobal?) {
log.info("Applying engine choices from inbound meta/global.")
log.info("Old meta/global syncID: \(old?.syncID)")
log.info("New meta/global syncID: \(self.global?.value.syncID)")
log.info("HACK: ignoring engine choices.")
// TODO: detect when the sets of declined or enabled engines have changed, and update
// our preferences and generate a new meta/global if necessary.
return (self, nil)
}
private class func unpickleV1FromPrefs(prefs: Prefs, syncKeyBundle: KeyBundle) -> Scratchpad {
let b = Scratchpad(b: syncKeyBundle, persistingTo: prefs).evolve()
// Do this first so that the meta/global and crypto/keys unpickling can overwrite the timestamps.
if let lastFetched: [String: AnyObject] = prefs.dictionaryForKey(PrefLastFetched) {
b.collectionLastFetched = optFilter(mapValues(lastFetched, { ($0 as? NSNumber)?.unsignedLongLongValue }))
}
if let mg = prefs.stringForKey(PrefGlobal) {
if let mgTS = prefs.unsignedLongForKey(PrefGlobalTS) {
if let global = MetaGlobal.fromPayload(mg) {
b.setGlobal(Fetched(value: global, timestamp: mgTS))
} else {
log.error("Malformed meta/global in prefs. Ignoring.")
}
} else {
// This should never happen.
log.error("Found global in prefs, but not globalTS!")
}
}
if let keyLabel = prefs.stringForKey(PrefKeyLabel) {
b.keyLabel = keyLabel
if let ckTS = prefs.unsignedLongForKey(PrefKeysTS) {
if let keys = KeychainWrapper.stringForKey("keys." + keyLabel) {
// We serialize as JSON.
let keys = Keys(payload: KeysPayload(keys))
if keys.valid {
log.debug("Read keys from Keychain with label \(keyLabel).")
b.setKeys(Fetched(value: keys, timestamp: ckTS))
} else {
log.error("Invalid keys extracted from Keychain. Discarding.")
}
} else {
log.error("Found keysTS in prefs, but didn't find keys in Keychain!")
}
}
}
b.clientGUID = prefs.stringForKey(PrefClientGUID) ?? {
log.error("No value found in prefs for client GUID! Generating one.")
return Bytes.generateGUID()
}()
b.clientName = prefs.stringForKey(PrefClientName) ?? {
log.error("No value found in prefs for client name! Using default.")
return DeviceInfo.defaultClientName()
}()
// TODO: engineConfiguration
return b.build()
}
public class func restoreFromPrefs(prefs: Prefs, syncKeyBundle: KeyBundle) -> Scratchpad? {
if let ver = prefs.intForKey(PrefVersion) {
switch (ver) {
case 1:
return unpickleV1FromPrefs(prefs, syncKeyBundle: syncKeyBundle)
default:
return nil
}
}
log.debug("No scratchpad found in prefs.")
return nil
}
/**
* Persist our current state to our origin prefs.
* Note that calling this from multiple threads with either mutated or evolved
* scratchpads will cause sadness — individual writes are thread-safe, but the
* overall pseudo-transaction is not atomic.
*/
public func checkpoint() -> Scratchpad {
return pickle(self.prefs)
}
func pickle(prefs: Prefs) -> Scratchpad {
prefs.setInt(1, forKey: PrefVersion)
if let global = global {
prefs.setLong(global.timestamp, forKey: PrefGlobalTS)
prefs.setString(global.value.toPayload().toString(), forKey: PrefGlobal)
} else {
prefs.removeObjectForKey(PrefGlobal)
prefs.removeObjectForKey(PrefGlobalTS)
}
// We store the meat of your keys in the Keychain, using a random identifier that we persist in prefs.
prefs.setString(self.keyLabel, forKey: PrefKeyLabel)
if let keys = self.keys {
let payload = keys.value.asPayload().toString(pretty: false)
let label = "keys." + self.keyLabel
log.debug("Storing keys in Keychain with label \(label).")
prefs.setString(self.keyLabel, forKey: PrefKeyLabel)
prefs.setLong(keys.timestamp, forKey: PrefKeysTS)
// TODO: I could have sworn that we could specify kSecAttrAccessibleAfterFirstUnlock here.
KeychainWrapper.setString(payload, forKey: label)
} else {
log.debug("Removing keys from Keychain.")
KeychainWrapper.removeObjectForKey(self.keyLabel)
}
// TODO: engineConfiguration
prefs.setString(clientName, forKey: PrefClientName)
prefs.setString(clientGUID, forKey: PrefClientGUID)
// Thanks, Swift.
let dict = mapValues(collectionLastFetched, { NSNumber(unsignedLongLong: $0) }) as NSDictionary
prefs.setObject(dict, forKey: PrefLastFetched)
return self
}
}
| mpl-2.0 |
huangboju/Moots | UICollectionViewLayout/MagazineLayout-master/Tests/RowOffsetTrackerTests.swift | 1 | 3957 | // Created by Bryan Keller on 5/23/19.
// Copyright © 2019 Airbnb Inc. All rights reserved.
import XCTest
@testable import MagazineLayout
final class RowOffsetTrackerTests: XCTestCase {
// MARK: Internal
func testOneRow() {
var rowOffsetTracker1 = RowOffsetTracker(numberOfRows: 1)
XCTAssert(rowOffsetTracker1.offsetForRow(at: 0) == 0)
rowOffsetTracker1.addOffset(-50, forRowsStartingAt: 0)
XCTAssert(rowOffsetTracker1.offsetForRow(at: 0) == -50)
rowOffsetTracker1.addOffset(0, forRowsStartingAt: 0)
XCTAssert(rowOffsetTracker1.offsetForRow(at: 0) == -50)
rowOffsetTracker1.addOffset(50, forRowsStartingAt: 0)
XCTAssert(rowOffsetTracker1.offsetForRow(at: 0) == 0)
}
func testTwoRows() {
var rowOffsetTracker2 = RowOffsetTracker(numberOfRows: 2)
XCTAssert(rowOffsetTracker2.offsetForRow(at: 0) == 0)
XCTAssert(rowOffsetTracker2.offsetForRow(at: 1) == 0)
rowOffsetTracker2.addOffset(10, forRowsStartingAt: 0)
XCTAssert(rowOffsetTracker2.offsetForRow(at: 0) == 10)
XCTAssert(rowOffsetTracker2.offsetForRow(at: 1) == 10)
rowOffsetTracker2.addOffset(-5, forRowsStartingAt: 1)
rowOffsetTracker2.addOffset(20, forRowsStartingAt: 0)
XCTAssert(rowOffsetTracker2.offsetForRow(at: 1) == 25)
XCTAssert(rowOffsetTracker2.offsetForRow(at: 0) == 30)
}
func testPowerOfTwoNumberOfRows() {
var rowOffsetTracker64 = RowOffsetTracker(numberOfRows: 64)
XCTAssert(rowOffsetTracker64.offsetForRow(at: 0) == 0)
XCTAssert(rowOffsetTracker64.offsetForRow(at: 63) == 0)
rowOffsetTracker64.addOffset(-50, forRowsStartingAt: 30)
rowOffsetTracker64.addOffset(100, forRowsStartingAt: 25)
rowOffsetTracker64.addOffset(10, forRowsStartingAt: 63)
rowOffsetTracker64.addOffset(10, forRowsStartingAt: 1)
rowOffsetTracker64.addOffset(-5, forRowsStartingAt: 0)
rowOffsetTracker64.addOffset(60, forRowsStartingAt: 23)
rowOffsetTracker64.addOffset(62, forRowsStartingAt: -1)
let expectedOffsets: [CGFloat] = [
-5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0,
5.0, 5.0, 5.0, 5.0, 5.0, 65.0, 65.0, 165.0, 165.0, 165.0, 165.0, 165.0, 115.0, 115.0, 115.0,
115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0,
115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0,
115.0, 115.0, 115.0, 115.0, 187.0
]
for i in 0..<64 {
XCTAssert(rowOffsetTracker64.offsetForRow(at: i) == expectedOffsets[i])
}
}
func testNonPowerOfTwoNumberOfRows() {
var rowOffsetTracker70 = RowOffsetTracker(numberOfRows: 70)
XCTAssert(rowOffsetTracker70.offsetForRow(at: 0) == 0)
XCTAssert(rowOffsetTracker70.offsetForRow(at: 69) == 0)
rowOffsetTracker70.addOffset(-50, forRowsStartingAt: 30)
rowOffsetTracker70.addOffset(100, forRowsStartingAt: 25)
rowOffsetTracker70.addOffset(10, forRowsStartingAt: 63)
rowOffsetTracker70.addOffset(10, forRowsStartingAt: 1)
rowOffsetTracker70.addOffset(-5, forRowsStartingAt: 0)
rowOffsetTracker70.addOffset(60, forRowsStartingAt: 23)
rowOffsetTracker70.addOffset(62, forRowsStartingAt: -1)
rowOffsetTracker70.addOffset(-100, forRowsStartingAt: 65)
rowOffsetTracker70.addOffset(0, forRowsStartingAt: 69)
let expectedOffsets: [CGFloat] = [
-5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0,
5.0, 5.0, 5.0, 5.0, 5.0, 65.0, 65.0, 165.0, 165.0, 165.0, 165.0, 165.0, 115.0, 115.0, 115.0,
115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0,
115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0, 115.0,
115.0, 115.0, 115.0, 115.0, 125.0, 125.0, 25.0, 25.0, 25.0, 25.0, 25.0
]
for i in 0..<70 {
XCTAssert(rowOffsetTracker70.offsetForRow(at: i) == expectedOffsets[i])
}
}
}
| mit |
kesun421/firefox-ios | Client/Frontend/Browser/TabTrayController.swift | 2 | 43665 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
import Storage
import ReadingList
import Shared
struct TabTrayControllerUX {
static let CornerRadius = CGFloat(6.0)
static let BackgroundColor = UIConstants.TabTrayBG
static let CellBackgroundColor = UIConstants.TabTrayBG
static let TextBoxHeight = CGFloat(32.0)
static let FaviconSize = CGFloat(20)
static let Margin = CGFloat(15)
static let ToolbarBarTintColor = UIColor.black
static let ToolbarButtonOffset = CGFloat(10.0)
static let CloseButtonSize = CGFloat(18.0)
static let CloseButtonMargin = CGFloat(6.0)
static let CloseButtonEdgeInset = CGFloat(10)
static let NumberOfColumnsThin = 1
static let NumberOfColumnsWide = 3
static let CompactNumberOfColumnsThin = 2
static let MenuFixedWidth: CGFloat = 320
}
struct LightTabCellUX {
static let TabTitleTextColor = UIColor.black
}
struct DarkTabCellUX {
static let TabTitleTextColor = UIColor.white
}
protocol TabCellDelegate: class {
func tabCellDidClose(_ cell: TabCell)
}
class TabCell: UICollectionViewCell {
enum Style {
case light
case dark
}
static let Identifier = "TabCellIdentifier"
static let BorderWidth: CGFloat = 3
var style: Style = .light {
didSet {
applyStyle(style)
}
}
let backgroundHolder = UIView()
let screenshotView = UIImageViewAligned()
let titleText: UILabel
let favicon: UIImageView = UIImageView()
let closeButton: UIButton
var title: UIVisualEffectView!
var animator: SwipeAnimator!
weak var delegate: TabCellDelegate?
// Changes depending on whether we're full-screen or not.
var margin = CGFloat(0)
override init(frame: CGRect) {
self.backgroundHolder.backgroundColor = UIColor.white
self.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
self.backgroundHolder.clipsToBounds = true
self.backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor
self.screenshotView.contentMode = UIViewContentMode.scaleAspectFill
self.screenshotView.clipsToBounds = true
self.screenshotView.isUserInteractionEnabled = false
self.screenshotView.alignLeft = true
self.screenshotView.alignTop = true
screenshotView.backgroundColor = UIConstants.AppBackgroundColor
self.favicon.backgroundColor = UIColor.clear
self.favicon.layer.cornerRadius = 2.0
self.favicon.layer.masksToBounds = true
self.titleText = UILabel()
self.titleText.textAlignment = NSTextAlignment.left
self.titleText.isUserInteractionEnabled = false
self.titleText.numberOfLines = 1
self.titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold
self.closeButton = UIButton()
self.closeButton.setImage(UIImage.templateImageNamed("nav-stop"), for: UIControlState())
self.closeButton.tintColor = UIColor.lightGray
self.closeButton.imageEdgeInsets = UIEdgeInsets(equalInset: TabTrayControllerUX.CloseButtonEdgeInset)
super.init(frame: frame)
self.animator = SwipeAnimator(animatingView: self)
self.closeButton.addTarget(self, action: #selector(TabCell.close), for: UIControlEvents.touchUpInside)
contentView.addSubview(backgroundHolder)
backgroundHolder.addSubview(self.screenshotView)
// Default style is light
applyStyle(style)
self.accessibilityCustomActions = [
UIAccessibilityCustomAction(name: NSLocalizedString("Close", comment: "Accessibility label for action denoting closing a tab in tab list (tray)"), target: self.animator, selector: #selector(SwipeAnimator.closeWithoutGesture))
]
}
fileprivate func applyStyle(_ style: Style) {
self.title?.removeFromSuperview()
let title: UIVisualEffectView
switch style {
case .light:
title = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
self.titleText.textColor = LightTabCellUX.TabTitleTextColor
case .dark:
title = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
self.titleText.textColor = DarkTabCellUX.TabTitleTextColor
}
titleText.backgroundColor = UIColor.clear
title.contentView.addSubview(self.closeButton)
title.contentView.addSubview(self.titleText)
title.contentView.addSubview(self.favicon)
backgroundHolder.addSubview(title)
self.title = title
}
func setTabSelected(_ isPrivate: Bool) {
// This creates a border around a tabcell. Using the shadow craetes a border _outside_ of the tab frame.
layer.shadowColor = (isPrivate ? UIConstants.PrivateModePurple : UIConstants.SystemBlueColor).cgColor
layer.shadowOpacity = 1
layer.shadowRadius = 0 // A 0 radius creates a solid border instead of a gradient blur
layer.masksToBounds = false
// create a frame that is "BorderWidth" size bigger than the cell
layer.shadowOffset = CGSize(width: -TabCell.BorderWidth, height: -TabCell.BorderWidth)
let shadowPath = CGRect(x: 0, y: 0, width: layer.frame.width + (TabCell.BorderWidth * 2), height: layer.frame.height + (TabCell.BorderWidth * 2))
layer.shadowPath = UIBezierPath(roundedRect: shadowPath, cornerRadius: TabTrayControllerUX.CornerRadius+TabCell.BorderWidth).cgPath
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let w = frame.width
let h = frame.height
backgroundHolder.frame = CGRect(x: margin,
y: margin,
width: w,
height: h)
screenshotView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: backgroundHolder.frame.size)
title.frame = CGRect(x: 0,
y: 0,
width: backgroundHolder.frame.width,
height: TabTrayControllerUX.TextBoxHeight)
favicon.frame = CGRect(x: 6,
y: (TabTrayControllerUX.TextBoxHeight - TabTrayControllerUX.FaviconSize)/2,
width: TabTrayControllerUX.FaviconSize,
height: TabTrayControllerUX.FaviconSize)
let titleTextLeft = favicon.frame.origin.x + favicon.frame.width + 6
titleText.frame = CGRect(x: titleTextLeft,
y: 0,
width: title.frame.width - titleTextLeft - margin - TabTrayControllerUX.CloseButtonSize - TabTrayControllerUX.CloseButtonMargin * 2,
height: title.frame.height)
closeButton.snp.makeConstraints { make in
make.size.equalTo(title.snp.height)
make.trailing.centerY.equalTo(title)
}
let top = (TabTrayControllerUX.TextBoxHeight - titleText.bounds.height) / 2.0
titleText.frame.origin = CGPoint(x: titleText.frame.origin.x, y: max(0, top))
let shadowPath = CGRect(x: 0, y: 0, width: layer.frame.width + (TabCell.BorderWidth * 2), height: layer.frame.height + (TabCell.BorderWidth * 2))
layer.shadowPath = UIBezierPath(roundedRect: shadowPath, cornerRadius: TabTrayControllerUX.CornerRadius+TabCell.BorderWidth).cgPath
}
override func prepareForReuse() {
// Reset any close animations.
backgroundHolder.transform = CGAffineTransform.identity
backgroundHolder.alpha = 1
self.titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold
layer.shadowOffset = CGSize.zero
layer.shadowPath = nil
layer.shadowOpacity = 0
}
override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool {
var right: Bool
switch direction {
case .left:
right = false
case .right:
right = true
default:
return false
}
animator.close(right: right)
return true
}
@objc
func close() {
self.animator.closeWithoutGesture()
}
}
struct PrivateModeStrings {
static let toggleAccessibilityLabel = NSLocalizedString("Private Mode", tableName: "PrivateBrowsing", comment: "Accessibility label for toggling on/off private mode")
static let toggleAccessibilityHint = NSLocalizedString("Turns private mode on or off", tableName: "PrivateBrowsing", comment: "Accessiblity hint for toggling on/off private mode")
static let toggleAccessibilityValueOn = NSLocalizedString("On", tableName: "PrivateBrowsing", comment: "Toggled ON accessibility value")
static let toggleAccessibilityValueOff = NSLocalizedString("Off", tableName: "PrivateBrowsing", comment: "Toggled OFF accessibility value")
}
protocol TabTrayDelegate: class {
func tabTrayDidDismiss(_ tabTray: TabTrayController)
func tabTrayDidAddBookmark(_ tab: Tab)
func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord?
func tabTrayRequestsPresentationOf(_ viewController: UIViewController)
}
class TabTrayController: UIViewController {
let tabManager: TabManager
let profile: Profile
weak var delegate: TabTrayDelegate?
var collectionView: UICollectionView!
var draggedCell: TabCell?
var dragOffset: CGPoint = CGPoint.zero
lazy var toolbar: TrayToolbar = {
let toolbar = TrayToolbar()
toolbar.addTabButton.addTarget(self, action: #selector(TabTrayController.didClickAddTab), for: .touchUpInside)
toolbar.maskButton.addTarget(self, action: #selector(TabTrayController.didTogglePrivateMode), for: .touchUpInside)
toolbar.deleteButton.addTarget(self, action: #selector(TabTrayController.didTapDelete(_:)), for: .touchUpInside)
return toolbar
}()
fileprivate(set) internal var privateMode: Bool = false {
didSet {
tabDataSource.tabs = tabsToDisplay
toolbar.styleToolbar(privateMode)
collectionView?.reloadData()
}
}
fileprivate var tabsToDisplay: [Tab] {
return self.privateMode ? tabManager.privateTabs : tabManager.normalTabs
}
fileprivate lazy var emptyPrivateTabsView: EmptyPrivateTabsView = {
let emptyView = EmptyPrivateTabsView()
emptyView.learnMoreButton.addTarget(self, action: #selector(TabTrayController.didTapLearnMore), for: UIControlEvents.touchUpInside)
return emptyView
}()
fileprivate lazy var tabDataSource: TabManagerDataSource = {
return TabManagerDataSource(tabs: self.tabsToDisplay, cellDelegate: self, tabManager: self.tabManager)
}()
fileprivate lazy var tabLayoutDelegate: TabLayoutDelegate = {
let delegate = TabLayoutDelegate(profile: self.profile, traitCollection: self.traitCollection)
delegate.tabSelectionDelegate = self
return delegate
}()
init(tabManager: TabManager, profile: Profile) {
self.tabManager = tabManager
self.profile = profile
super.init(nibName: nil, bundle: nil)
tabManager.addDelegate(self)
}
convenience init(tabManager: TabManager, profile: Profile, tabTrayDelegate: TabTrayDelegate) {
self.init(tabManager: tabManager, profile: profile)
self.delegate = tabTrayDelegate
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
self.tabManager.removeDelegate(self)
}
func dynamicFontChanged(_ notification: Notification) {
guard notification.name == NotificationDynamicFontChanged else { return }
self.collectionView.reloadData()
}
// MARK: View Controller Callbacks
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.")
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.dataSource = tabDataSource
collectionView.delegate = tabLayoutDelegate
collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: UIConstants.BottomToolbarHeight, right: 0)
collectionView.register(TabCell.self, forCellWithReuseIdentifier: TabCell.Identifier)
collectionView.backgroundColor = TabTrayControllerUX.BackgroundColor
view.addSubview(collectionView)
view.addSubview(toolbar)
makeConstraints()
view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView)
emptyPrivateTabsView.snp.makeConstraints { make in
make.top.left.right.equalTo(self.collectionView)
make.bottom.equalTo(self.toolbar.snp.top)
}
if let tab = tabManager.selectedTab, tab.isPrivate {
privateMode = true
}
// register for previewing delegate to enable peek and pop if force touch feature available
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: view)
}
emptyPrivateTabsView.isHidden = !privateTabsAreEmpty()
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.appWillResignActiveNotification), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.appDidBecomeActiveNotification), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.dynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Update the trait collection we reference in our layout delegate
tabLayoutDelegate.traitCollection = traitCollection
self.collectionView.collectionViewLayout.invalidateLayout()
}
fileprivate func cancelExistingGestures() {
if let visibleCells = self.collectionView.visibleCells as? [TabCell] {
for cell in visibleCells {
cell.animator.cancelExistingGestures()
}
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { _ in
self.collectionView.collectionViewLayout.invalidateLayout()
}, completion: nil)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent //this will need to be fixed
}
fileprivate func makeConstraints() {
collectionView.snp.makeConstraints { make in
make.left.bottom.right.equalTo(view)
make.top.equalTo(self.topLayoutGuide.snp.bottom)
}
toolbar.snp.makeConstraints { make in
make.left.right.bottom.equalTo(view)
make.height.equalTo(UIConstants.BottomToolbarHeight)
}
}
// MARK: Selectors
func didClickDone() {
presentingViewController!.dismiss(animated: true, completion: nil)
}
func didClickSettingsItem() {
assert(Thread.isMainThread, "Opening settings requires being invoked on the main thread")
let settingsTableViewController = AppSettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
settingsTableViewController.settingsDelegate = self
let controller = SettingsNavigationController(rootViewController: settingsTableViewController)
controller.popoverDelegate = self
controller.modalPresentationStyle = UIModalPresentationStyle.formSheet
present(controller, animated: true, completion: nil)
}
func didClickAddTab() {
openNewTab()
LeanplumIntegration.sharedInstance.track(eventName: .openedNewTab, withParameters: ["Source": "Tab Tray" as AnyObject])
}
func didTapLearnMore() {
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
if let langID = Locale.preferredLanguages.first {
let learnMoreRequest = URLRequest(url: "https://support.mozilla.org/1/mobile/\(appVersion)/iOS/\(langID)/private-browsing-ios".asURL!)
openNewTab(learnMoreRequest)
}
}
func didTogglePrivateMode() {
let scaleDownTransform = CGAffineTransform(scaleX: 0.9, y: 0.9)
let fromView: UIView
if !privateTabsAreEmpty(), let snapshot = collectionView.snapshotView(afterScreenUpdates: false) {
snapshot.frame = collectionView.frame
view.insertSubview(snapshot, aboveSubview: collectionView)
fromView = snapshot
} else {
fromView = emptyPrivateTabsView
}
tabManager.willSwitchTabMode()
privateMode = !privateMode
// If we are exiting private mode and we have the close private tabs option selected, make sure
// we clear out all of the private tabs
let exitingPrivateMode = !privateMode && tabManager.shouldClearPrivateTabs()
toolbar.maskButton.setSelected(privateMode, animated: true)
collectionView.layoutSubviews()
let toView: UIView
if !privateTabsAreEmpty(), let newSnapshot = collectionView.snapshotView(afterScreenUpdates: !exitingPrivateMode) {
emptyPrivateTabsView.isHidden = true
//when exiting private mode don't screenshot the collectionview (causes the UI to hang)
newSnapshot.frame = collectionView.frame
view.insertSubview(newSnapshot, aboveSubview: fromView)
collectionView.alpha = 0
toView = newSnapshot
} else {
emptyPrivateTabsView.isHidden = false
toView = emptyPrivateTabsView
}
toView.alpha = 0
toView.transform = scaleDownTransform
UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: { () -> Void in
fromView.transform = scaleDownTransform
fromView.alpha = 0
toView.transform = CGAffineTransform.identity
toView.alpha = 1
}) { finished in
if fromView != self.emptyPrivateTabsView {
fromView.removeFromSuperview()
}
if toView != self.emptyPrivateTabsView {
toView.removeFromSuperview()
}
self.collectionView.alpha = 1
}
}
fileprivate func privateTabsAreEmpty() -> Bool {
return privateMode && tabManager.privateTabs.count == 0
}
func changePrivacyMode(_ isPrivate: Bool) {
if isPrivate != privateMode {
guard let _ = collectionView else {
privateMode = isPrivate
return
}
didTogglePrivateMode()
}
}
fileprivate func openNewTab(_ request: URLRequest? = nil) {
toolbar.isUserInteractionEnabled = false
// We're only doing one update here, but using a batch update lets us delay selecting the tab
// until after its insert animation finishes.
self.collectionView.performBatchUpdates({ _ in
let tab = self.tabManager.addTab(request, isPrivate: self.privateMode)
}, completion: { finished in
// The addTab delegate method will pop to the BVC no need to do anything here.
self.toolbar.isUserInteractionEnabled = true
if finished {
if request == nil && NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage {
if let bvc = self.navigationController?.topViewController as? BrowserViewController {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
bvc.urlBar.tabLocationViewDidTapLocation(bvc.urlBar.locationView)
}
}
}
}
})
}
fileprivate func closeTabsForCurrentTray() {
tabManager.removeTabsWithUndoToast(tabsToDisplay)
self.collectionView.reloadData()
}
}
// MARK: - App Notifications
extension TabTrayController {
func appWillResignActiveNotification() {
if privateMode {
collectionView.alpha = 0
}
}
func appDidBecomeActiveNotification() {
// Re-show any components that might have been hidden because they were being displayed
// as part of a private mode tab
UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: {
self.collectionView.alpha = 1
},
completion: nil)
}
}
extension TabTrayController: TabSelectionDelegate {
func didSelectTabAtIndex(_ index: Int) {
let tab = tabsToDisplay[index]
tabManager.selectTab(tab)
_ = self.navigationController?.popViewController(animated: true)
}
}
extension TabTrayController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) {
dismiss(animated: animated, completion: { self.collectionView.reloadData() })
}
}
extension TabTrayController: TabManagerDelegate {
func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) {
}
func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) {
}
func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) {
}
func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) {
// Get the index of the added tab from it's set (private or normal)
guard let index = tabsToDisplay.index(of: tab) else { return }
if !privateTabsAreEmpty() {
emptyPrivateTabsView.isHidden = true
}
tabDataSource.addTab(tab)
self.collectionView?.performBatchUpdates({ _ in
self.collectionView.insertItems(at: [IndexPath(item: index, section: 0)])
}, completion: { finished in
if finished {
tabManager.selectTab(tab)
// don't pop the tab tray view controller if it is not in the foreground
if self.presentedViewController == nil {
_ = self.navigationController?.popViewController(animated: true)
}
}
})
}
func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) {
// it is possible that we are removing a tab that we are not currently displaying
// through the Close All Tabs feature (which will close tabs that are not in our current privacy mode)
// check this before removing the item from the collection
let removedIndex = tabDataSource.removeTab(tab)
if removedIndex > -1 {
self.collectionView.performBatchUpdates({
self.collectionView.deleteItems(at: [IndexPath(item: removedIndex, section: 0)])
}, completion: { finished in
guard finished && self.privateTabsAreEmpty() else { return }
self.emptyPrivateTabsView.isHidden = false
})
}
}
func tabManagerDidAddTabs(_ tabManager: TabManager) {
}
func tabManagerDidRestoreTabs(_ tabManager: TabManager) {
}
func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) {
guard privateMode else {
return
}
if let toast = toast {
view.addSubview(toast)
toast.snp.makeConstraints { make in
make.left.right.equalTo(view)
make.bottom.equalTo(toolbar.snp.top)
}
toast.showToast()
}
}
}
extension TabTrayController: UIScrollViewAccessibilityDelegate {
func accessibilityScrollStatus(for scrollView: UIScrollView) -> String? {
var visibleCells = collectionView.visibleCells as! [TabCell]
var bounds = collectionView.bounds
bounds = bounds.offsetBy(dx: collectionView.contentInset.left, dy: collectionView.contentInset.top)
bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right
bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom
// visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...)
visibleCells = visibleCells.filter { !$0.frame.intersection(bounds).isEmpty }
let cells = visibleCells.map { self.collectionView.indexPath(for: $0)! }
let indexPaths = cells.sorted { (a: IndexPath, b: IndexPath) -> Bool in
return a.section < b.section || (a.section == b.section && a.row < b.row)
}
if indexPaths.count == 0 {
return NSLocalizedString("No tabs", comment: "Message spoken by VoiceOver to indicate that there are no tabs in the Tabs Tray")
}
let firstTab = indexPaths.first!.row + 1
let lastTab = indexPaths.last!.row + 1
let tabCount = collectionView.numberOfItems(inSection: 0)
if firstTab == lastTab {
let format = NSLocalizedString("Tab %@ of %@", comment: "Message spoken by VoiceOver saying the position of the single currently visible tab in Tabs Tray, along with the total number of tabs. E.g. \"Tab 2 of 5\" says that tab 2 is visible (and is the only visible tab), out of 5 tabs total.")
return String(format: format, NSNumber(value: firstTab as Int), NSNumber(value: tabCount as Int))
} else {
let format = NSLocalizedString("Tabs %@ to %@ of %@", comment: "Message spoken by VoiceOver saying the range of tabs that are currently visible in Tabs Tray, along with the total number of tabs. E.g. \"Tabs 8 to 10 of 15\" says tabs 8, 9 and 10 are visible, out of 15 tabs total.")
return String(format: format, NSNumber(value: firstTab as Int), NSNumber(value: lastTab as Int), NSNumber(value: tabCount as Int))
}
}
}
extension TabTrayController: SwipeAnimatorDelegate {
func swipeAnimator(_ animator: SwipeAnimator, viewWillExitContainerBounds: UIView) {
let tabCell = animator.animatingView as! TabCell
if let indexPath = collectionView.indexPath(for: tabCell) {
let tab = tabsToDisplay[indexPath.item]
tabManager.removeTab(tab)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Closing tab", comment: "Accessibility label (used by assistive technology) notifying the user that the tab is being closed."))
}
}
}
extension TabTrayController: TabCellDelegate {
func tabCellDidClose(_ cell: TabCell) {
let indexPath = collectionView.indexPath(for: cell)!
let tab = tabsToDisplay[indexPath.item]
tabManager.removeTab(tab)
}
}
extension TabTrayController: SettingsDelegate {
func settingsOpenURLInNewTab(_ url: URL) {
let request = URLRequest(url: url)
openNewTab(request)
}
}
extension TabTrayController: PhotonActionSheetProtocol {
func didTapDelete(_ sender: UIButton) {
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: Strings.AppMenuCloseAllTabsTitleString, style: .default, handler: { _ in self.closeTabsForCurrentTray() }))
controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: nil))
controller.popoverPresentationController?.sourceView = sender
controller.popoverPresentationController?.sourceRect = sender.bounds
present(controller, animated: true, completion: nil)
}
}
fileprivate class TabManagerDataSource: NSObject, UICollectionViewDataSource {
unowned var cellDelegate: TabCellDelegate & SwipeAnimatorDelegate
fileprivate var tabs: [Tab]
fileprivate var tabManager: TabManager
init(tabs: [Tab], cellDelegate: TabCellDelegate & SwipeAnimatorDelegate, tabManager: TabManager) {
self.cellDelegate = cellDelegate
self.tabs = tabs
self.tabManager = tabManager
super.init()
}
/**
Removes the given tab from the data source
- parameter tab: Tab to remove
- returns: The index of the removed tab, -1 if tab did not exist
*/
func removeTab(_ tabToRemove: Tab) -> Int {
var index: Int = -1
for (i, tab) in tabs.enumerated() where tabToRemove === tab {
index = i
tabs.remove(at: index)
break
}
return index
}
/**
Adds the given tab to the data source
- parameter tab: Tab to add
*/
func addTab(_ tab: Tab) {
tabs.append(tab)
}
@objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let tabCell = collectionView.dequeueReusableCell(withReuseIdentifier: TabCell.Identifier, for: indexPath) as! TabCell
tabCell.animator.delegate = cellDelegate
tabCell.delegate = cellDelegate
let tab = tabs[indexPath.item]
tabCell.style = tab.isPrivate ? .dark : .light
tabCell.titleText.text = tab.displayTitle
tabCell.closeButton.tintColor = tab.isPrivate ? UIColor.white : UIColor.gray
if !tab.displayTitle.isEmpty {
tabCell.accessibilityLabel = tab.displayTitle
} else {
tabCell.accessibilityLabel = tab.url?.aboutComponent ?? "" // If there is no title we are most likely on a home panel.
}
tabCell.isAccessibilityElement = true
tabCell.accessibilityHint = NSLocalizedString("Swipe right or left with three fingers to close the tab.", comment: "Accessibility hint for tab tray's displayed tab.")
if let favIcon = tab.displayFavicon {
tabCell.favicon.sd_setImage(with: URL(string: favIcon.url)!)
} else {
let defaultFavicon = UIImage(named: "defaultFavicon")
if tab.isPrivate {
tabCell.favicon.image = defaultFavicon
tabCell.favicon.tintColor = UIColor.white
} else {
tabCell.favicon.image = defaultFavicon
}
}
if tab == tabManager.selectedTab {
tabCell.setTabSelected(tab.isPrivate)
}
tabCell.screenshotView.image = tab.screenshot
return tabCell
}
@objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabs.count
}
@objc fileprivate func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let fromIndex = sourceIndexPath.item
let toIndex = destinationIndexPath.item
tabs.insert(tabs.remove(at: fromIndex), at: toIndex < fromIndex ? toIndex : toIndex - 1)
tabManager.moveTab(isPrivate: tabs[fromIndex].isPrivate, fromIndex: fromIndex, toIndex: toIndex)
}
}
@objc protocol TabSelectionDelegate: class {
func didSelectTabAtIndex(_ index: Int)
}
fileprivate class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout {
weak var tabSelectionDelegate: TabSelectionDelegate?
fileprivate var traitCollection: UITraitCollection
fileprivate var profile: Profile
fileprivate var numberOfColumns: Int {
// iPhone 4-6+ portrait
if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
return TabTrayControllerUX.CompactNumberOfColumnsThin
} else {
return TabTrayControllerUX.NumberOfColumnsWide
}
}
init(profile: Profile, traitCollection: UITraitCollection) {
self.profile = profile
self.traitCollection = traitCollection
super.init()
}
fileprivate func cellHeightForCurrentDevice() -> CGFloat {
let shortHeight = TabTrayControllerUX.TextBoxHeight * 6
if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.compact {
return shortHeight
} else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.compact {
return shortHeight
} else {
return TabTrayControllerUX.TextBoxHeight * 8
}
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellWidth = floor((collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns))
return CGSize(width: cellWidth, height: self.cellHeightForCurrentDevice())
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(equalInset: TabTrayControllerUX.Margin)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row)
}
}
struct EmptyPrivateTabsViewUX {
static let TitleColor = UIColor.white
static let TitleFont = UIFont.systemFont(ofSize: 22, weight: UIFontWeightMedium)
static let DescriptionColor = UIColor.white
static let DescriptionFont = UIFont.systemFont(ofSize: 17)
static let LearnMoreFont = UIFont.systemFont(ofSize: 15, weight: UIFontWeightMedium)
static let TextMargin: CGFloat = 18
static let LearnMoreMargin: CGFloat = 30
static let MaxDescriptionWidth: CGFloat = 250
static let MinBottomMargin: CGFloat = 10
}
// View we display when there are no private tabs created
fileprivate class EmptyPrivateTabsView: UIView {
fileprivate lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.TitleColor
label.font = EmptyPrivateTabsViewUX.TitleFont
label.textAlignment = NSTextAlignment.center
return label
}()
fileprivate var descriptionLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.DescriptionColor
label.font = EmptyPrivateTabsViewUX.DescriptionFont
label.textAlignment = NSTextAlignment.center
label.numberOfLines = 0
label.preferredMaxLayoutWidth = EmptyPrivateTabsViewUX.MaxDescriptionWidth
return label
}()
fileprivate var learnMoreButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle(
NSLocalizedString("Learn More", tableName: "PrivateBrowsing", comment: "Text button displayed when there are no tabs open while in private mode"),
for: UIControlState())
button.setTitleColor(UIConstants.PrivateModeTextHighlightColor, for: UIControlState())
button.titleLabel?.font = EmptyPrivateTabsViewUX.LearnMoreFont
return button
}()
fileprivate var iconImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "largePrivateMask"))
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.text = NSLocalizedString("Private Browsing",
tableName: "PrivateBrowsing", comment: "Title displayed for when there are no open tabs while in private mode")
descriptionLabel.text = NSLocalizedString("Firefox won’t remember any of your history or cookies, but new bookmarks will be saved.",
tableName: "PrivateBrowsing", comment: "Description text displayed when there are no open tabs while in private mode")
addSubview(titleLabel)
addSubview(descriptionLabel)
addSubview(iconImageView)
addSubview(learnMoreButton)
titleLabel.snp.makeConstraints { make in
make.center.equalTo(self)
}
iconImageView.snp.makeConstraints { make in
make.bottom.equalTo(titleLabel.snp.top).offset(-EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
descriptionLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
learnMoreButton.snp.makeConstraints { (make) -> Void in
make.top.equalTo(descriptionLabel.snp.bottom).offset(EmptyPrivateTabsViewUX.LearnMoreMargin).priority(10)
make.bottom.lessThanOrEqualTo(self).offset(-EmptyPrivateTabsViewUX.MinBottomMargin).priority(1000)
make.centerX.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TabTrayController: TabPeekDelegate {
func tabPeekDidAddBookmark(_ tab: Tab) {
delegate?.tabTrayDidAddBookmark(tab)
}
func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord? {
return delegate?.tabTrayDidAddToReadingList(tab)
}
func tabPeekDidCloseTab(_ tab: Tab) {
if let index = self.tabDataSource.tabs.index(of: tab),
let cell = self.collectionView?.cellForItem(at: IndexPath(item: index, section: 0)) as? TabCell {
cell.close()
}
}
func tabPeekRequestsPresentationOf(_ viewController: UIViewController) {
delegate?.tabTrayRequestsPresentationOf(viewController)
}
}
extension TabTrayController: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let collectionView = collectionView else { return nil }
let convertedLocation = self.view.convert(location, to: collectionView)
guard let indexPath = collectionView.indexPathForItem(at: convertedLocation),
let cell = collectionView.cellForItem(at: indexPath) else { return nil }
let tab = tabDataSource.tabs[indexPath.row]
let tabVC = TabPeekViewController(tab: tab, delegate: self)
if let browserProfile = profile as? BrowserProfile {
tabVC.setState(withProfile: browserProfile, clientPickerDelegate: self)
}
previewingContext.sourceRect = self.view.convert(cell.frame, from: collectionView)
return tabVC
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
guard let tpvc = viewControllerToCommit as? TabPeekViewController else { return }
tabManager.selectTab(tpvc.tab)
navigationController?.popViewController(animated: true)
delegate?.tabTrayDidDismiss(self)
}
}
extension TabTrayController: ClientPickerViewControllerDelegate {
func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) {
if let item = clientPickerViewController.shareItem {
self.profile.sendItems([item], toClients: clients)
}
clientPickerViewController.dismiss(animated: true, completion: nil)
}
func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) {
clientPickerViewController.dismiss(animated: true, completion: nil)
}
}
extension TabTrayController: UIAdaptivePresentationControllerDelegate, UIPopoverPresentationControllerDelegate {
// Returning None here makes sure that the Popover is actually presented as a Popover and
// not as a full-screen modal, which is the default on compact device classes.
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return UIModalPresentationStyle.none
}
}
// MARK: - Toolbar
class TrayToolbar: UIView {
fileprivate let toolbarButtonSize = CGSize(width: 44, height: 44)
lazy var addTabButton: UIButton = {
let button = UIButton()
button.setImage(UIImage.templateImageNamed("nav-add"), for: .normal)
button.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.")
button.accessibilityIdentifier = "TabTrayController.addTabButton"
return button
}()
lazy var deleteButton: UIButton = {
let button = UIButton()
button.setImage(UIImage.templateImageNamed("action_delete"), for: .normal)
button.accessibilityLabel = Strings.TabTrayDeleteMenuButtonAccessibilityLabel
button.accessibilityIdentifier = "TabTrayController.removeTabsButton"
return button
}()
lazy var maskButton: PrivateModeButton = PrivateModeButton()
fileprivate let sideOffset: CGFloat = 32
fileprivate override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
addSubview(addTabButton)
var buttonToCenter: UIButton?
addSubview(deleteButton)
buttonToCenter = deleteButton
maskButton.accessibilityIdentifier = "TabTrayController.maskButton"
buttonToCenter?.snp.makeConstraints { make in
make.centerX.equalTo(self)
make.top.equalTo(self)
make.size.equalTo(toolbarButtonSize)
}
addTabButton.snp.makeConstraints { make in
make.top.equalTo(self)
make.right.equalTo(self).offset(-sideOffset)
make.size.equalTo(toolbarButtonSize)
}
addSubview(maskButton)
maskButton.snp.makeConstraints { make in
make.top.equalTo(self)
make.left.equalTo(self).offset(sideOffset)
make.size.equalTo(toolbarButtonSize)
}
styleToolbar(false)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func styleToolbar(_ isPrivate: Bool) {
addTabButton.tintColor = isPrivate ? UIColor(rgb: 0xf9f9fa) : UIColor(rgb: 0x272727)
deleteButton.tintColor = isPrivate ? UIColor(rgb: 0xf9f9fa) : UIColor(rgb: 0x272727)
backgroundColor = isPrivate ? UIConstants.PrivateModeToolbarTintColor : UIColor(rgb: 0xf9f9fa)
maskButton.styleForMode(privateMode: isPrivate)
}
}
| mpl-2.0 |
fsproru/ScoutReport | ScoutReportTests/FakePresenter.swift | 1 | 683 | import UIKit
@testable import ScoutReport
class FakePresenter: PresenterType {
var underlyingViewController: UIViewController?
var presentedViewController: UIViewController?
var animated: Bool?
var completion: (() -> Void)?
func present(underlyingViewController underlyingViewController: UIViewController, viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?) {
self.underlyingViewController = underlyingViewController
self.presentedViewController = viewControllerToPresent
self.animated = animated
self.completion = completion
}
} | mit |
VladislavJevremovic/Exchange-Rates-NBS | Exchange Rates NBS/Logic/Constants.swift | 1 | 1711 | //
// Constants.swift
// Exchange Rates NBS
//
// Created by Vladislav Jevremovic on 12/6/14.
// Copyright (c) 2014 Vladislav Jevremovic. All rights reserved.
//
import Foundation
import UIKit
struct Constants {
struct CustomColor {
static let Manatee = UIColor(red: 142.0 / 255.0, green: 142.0 / 255.0, blue: 147.0 / 255.0, alpha: 1.0)
static let RadicalRed = UIColor(red: 255.0 / 255.0, green: 45.0 / 255.0, blue: 85.0 / 255.0, alpha: 1.0)
static let RedOrange = UIColor(red: 255.0 / 255.0, green: 59.0 / 255.0, blue: 48.0 / 255.0, alpha: 1.0)
static let Pizazz = UIColor(red: 255.0 / 255.0, green: 149.0 / 255.0, blue: 0.0 / 255.0, alpha: 1.0)
static let Supernova = UIColor(red: 255.0 / 255.0, green: 204.0 / 255.0, blue: 0.0 / 255.0, alpha: 1.0)
static let Emerald = UIColor(red: 76.0 / 255.0, green: 217.0 / 255.0, blue: 100.0 / 255.0, alpha: 1.0)
static let Malibu = UIColor(red: 90.0 / 255.0, green: 200.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0)
static let CuriousBlue = UIColor(red: 52.0 / 255.0, green: 170.0 / 255.0, blue: 220.0 / 255.0, alpha: 1.0)
static let AzureRadiance = UIColor(red: 0.0 / 255.0, green: 122.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0)
static let Indigo = UIColor(red: 88.0 / 255.0, green: 86.0 / 255.0, blue: 214.0 / 255.0, alpha: 1.0)
static let TableBackgroundColor = UIColor(red: 176.0 / 255.0, green: 214.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0)
static let TableCellColor = UIColor(red: 120.0 / 255.0, green: 185.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0)
static let TableFooterColor = UIColor(red: 0.43, green: 0.45, blue: 0.45, alpha: 1.0)
}
}
| mit |
catloafsoft/AudioKit | AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Band Pass Filter.xcplaygroundpage/Contents.swift | 1 | 1326 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Band Pass Filter
//: ### Band-pass filters allow audio above a specified frequency range and bandwidth to pass through to an output. The center frequency is the starting point from where the frequency limit is set. Adjusting the bandwidth sets how far out above and below the center frequency the frequency band should be. Anything above that band should pass through.
import XCPlayground
import AudioKit
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("mixloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
var bandPassFilter = AKBandPassFilter(player)
//: Set the parameters of the Band-Pass Filter here
bandPassFilter.centerFrequency = 5000 // Hz
bandPassFilter.bandwidth = 600 // Cents
AudioKit.output = bandPassFilter
AudioKit.start()
player.play()
//: Toggle processing on every loop
AKPlaygroundLoop(every: 3.428) { () -> () in
if bandPassFilter.isBypassed {
bandPassFilter.start()
} else {
bandPassFilter.bypass()
}
bandPassFilter.isBypassed ? "Bypassed" : "Processing" // Open Quicklook for this
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit |
blockchain/My-Wallet-V3-iOS | Modules/WalletPayload/Sources/WalletPayloadKit/Services/Sync/WalletSyncError.swift | 1 | 996 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Errors
import Foundation
import Localization
import ToolKit
public enum WalletSyncError: LocalizedError, Equatable {
case unknown
case encodingError(WalletEncodingError)
case verificationFailure(EncryptAndVerifyError)
case networkFailure(NetworkError)
case syncPubKeysFailure(SyncPubKeysAddressesProviderError)
public var errorDescription: String? {
switch self {
case .unknown:
return LocalizationConstants.WalletPayloadKit.Error.unknown
case .encodingError(let walletEncodingError):
return walletEncodingError.errorDescription
case .verificationFailure(let encryptAndVerifyError):
return encryptAndVerifyError.errorDescription
case .networkFailure(let networkError):
return networkError.description
case .syncPubKeysFailure(let error):
return error.localizedDescription
}
}
}
| lgpl-3.0 |
tzef/BmoViewPager | Example/BmoViewPager/CustomView/SegmentedView.swift | 1 | 1670 | //
// SegmentedView.swift
// BmoViewPager
//
// Created by LEE ZHE YU on 2017/6/4.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import UIKit
@IBDesignable
class SegmentedView: UIView {
@IBInspectable var strokeColor: UIColor = UIColor.black {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable var lineWidth: CGFloat = 1.0 {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable var segmentedCount: Int = 0 {
didSet {
self.setNeedsDisplay()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
self.layer.borderWidth = 1.0
self.layer.cornerRadius = 5.0
self.layer.masksToBounds = true
self.layer.borderColor = strokeColor.cgColor
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else {
return
}
let marginX = rect.width / CGFloat(segmentedCount)
strokeColor.setStroke()
context.setLineWidth(lineWidth)
for i in 0...segmentedCount {
context.move(to: CGPoint(x: rect.minX + marginX * CGFloat(i + 1), y: rect.minY))
context.addLine(to: CGPoint(x: rect.minX + marginX * CGFloat(i + 1), y: rect.maxY))
}
context.strokePath()
}
}
| mit |
Schwenger/SwiftUtil | Sources/SwiftUtil/Extensions/Optional.swift | 1 | 1925 | //
// Optional.swift
// SwiftUtil
//
// Created by Maximilian Schwenger on 24.07.17.
//
infix operator +?: AdditionPrecedence
infix operator -?: AdditionPrecedence
infix operator *?: MultiplicationPrecedence
infix operator /?: MultiplicationPrecedence
infix operator ==?: ComparisonPrecedence
public extension Optional {
func getOrElse(_ gen: () -> Wrapped) -> Wrapped {
switch self {
case .some(let content): return content
case .none: return gen()
}
}
public var empty: Bool { get {
switch self {
case .none: return true
case .some: return false
}}
}
}
public extension Optional where Wrapped: Numeric {
// All those functions also work for an unwrapped Numeric as left operand due to implicit conversion of Optionals.
static func +?(_ left: Optional<Wrapped>, right: Optional<Wrapped>) -> Optional<Wrapped> {
if left.empty || right.empty { return nil }
else { return left! + right! }
}
static func -?(_ left: Optional<Wrapped>, right: Optional<Wrapped>) -> Optional<Wrapped> {
if left.empty || right.empty { return nil }
else { return left! - right! }
}
static func *?(_ left: Optional<Wrapped>, right: Optional<Wrapped>) -> Optional<Wrapped> {
if left.empty || right.empty { return nil }
else { return left! * right! }
}
}
// Allows extending datastructures with associated optional type.
// Thanks to https://stackoverflow.com/questions/33138712/function-arrayoptionalt-optionalarrayt
public protocol OptionalType {
associatedtype Wrapped
var optional: Wrapped? { get }
}
extension Optional: OptionalType {
public var optional: Wrapped? { return self }
}
public func ==?<T: Equatable> (lhs: T?, rhs: T?) -> Bool {
if let lhs = lhs, let rhs = rhs {
return lhs == rhs
} else {
return lhs == nil && rhs == nil
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/01373-swift-valuedecl-getinterfacetype.swift | 11 | 699 | // 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
// RUN: not %target-swift-frontend %s -parse
import Foundation
extension NSData {
var d = c
let c(n: d {
override init(a(self)] == a")
func i> : a: k.C) -> {
public class A<H : Sequence where T>() {
}
}
protocol A {
}
protocol a {
typealias A : A, T : d where T : (c: e = Swift.f = B
func f<f = .Element>(2, ((x(")() -> T: AnyObject> Any in
func b, le
| apache-2.0 |
calkinssean/TIY-Assignments | Day 18/MoviesApp2/DetailViewController.swift | 1 | 1198 | //
// DetailViewController.swift
// MoviesApp2
//
// Created by Sean Calkins on 2/24/16.
// Copyright © 2016 Sean Calkins. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var movieTitleLabel: UILabel!
@IBOutlet weak var movieImageView: UIImageView!
@IBOutlet weak var movieOverviewLabel: UILabel!
var detailMovie = Movie()
override func viewDidLoad() {
super.viewDidLoad()
self.movieTitleLabel.text = detailMovie.title
self.movieOverviewLabel.text = detailMovie.overview
self.loadImageFromURL("https://image.tmdb.org/t/p/w185\(detailMovie.poster_path)")
}
func loadImageFromURL(urlString: String) {
if urlString.isEmpty == false {
dispatch_async(dispatch_get_main_queue(), {
if let url = NSURL(string: urlString) {
if let data = NSData(contentsOfURL: url) {
self.movieImageView.image = UIImage(data: data)
}
}
})
} else {
debugPrint("Invalid \(urlString)")
}
}
}
| cc0-1.0 |
Bashta/ImageDownloader | ImageDownloader/View/ImageTableViewCustoCells/ImageTableViewCell.swift | 1 | 3440 | //
// ImageTableViewCell.swift
// ImageDownloader
//
// Created by Alb on 4/4/16.
// Copyright © 2016 10gic. All rights reserved.
//
import UIKit
import Kingfisher
protocol ImageDownloaderCellDelegate: class {
func cellFinishedDownloadingImage(image: UIImage, cellIndex: Int)
}
final class ImageTableViewCell: UITableViewCell {
static let nib = UINib(nibName: "ImageTableViewCell", bundle: nil)
static let reuseId = "imageTableViewCell"
@IBOutlet private weak var progressView: UIProgressView?
@IBOutlet private weak var imageThumbnailImageView: UIImageView?
@IBOutlet private weak var imageNameLabel: UILabel?
@IBOutlet private weak var progressPercentageLabel: UILabel?
@IBOutlet private weak var downloadButton: UIButton?
private var imageFetcher: RetrieveImageTask?
weak var cellImageDownloaderCellDelegate: ImageDownloaderCellDelegate?
var datasourceCachedImage: UIImage? {
didSet {
imageThumbnailImageView?.image = datasourceCachedImage ?? UIImage(named: "image_placeholder")
setupCell()
}
}
var cellInfo:(imageUrl: NSURL, imageName: String, cellIndex: Int)? {
didSet {
setupCell()
}
}
}
extension ImageTableViewCell {
//MARK:- Action Buttons
@IBAction func downloadButtonPressed(sender: UIButton) {
switch sender.titleLabel!.text! {
case "Download":
downloadButton?.setTitle(downloadButton?.titleLabel?.text == "Download" ? "Stop" : "Download", forState: .Normal)
imageFetcher = imageThumbnailImageView?.kf_setImageWithURL(cellInfo!.imageUrl, placeholderImage: nil, optionsInfo: [.ForceRefresh],progressBlock: { receivedSize, totalSize in
dispatch_async(dispatch_get_main_queue(), {
self.progressPercentageLabel?.text = "\((Float(receivedSize) / Float(totalSize) * 100))%"
self.progressView?.progress = (Float(receivedSize) / Float(totalSize))
})
}, completionHandler: { image, error, cacheType, imageURL in
self.downloadButton?.setTitle("Done", forState: .Normal)
self.progressView?.progress
guard let image = image, index = self.cellInfo?.cellIndex else {
return
}
self.cellImageDownloaderCellDelegate?.cellFinishedDownloadingImage(image, cellIndex: index)
})
case "Cancel":
imageFetcher?.cancel()
default:
return
}
}
override func prepareForReuse() {
super.prepareForReuse()
dispatch_async(dispatch_get_main_queue(), {
})
progressView?.progress = datasourceCachedImage == nil ? 0 : 100
progressPercentageLabel?.text = datasourceCachedImage == nil ? "0%" : "100%"
imageNameLabel?.text = cellInfo?.imageName
downloadButton?.titleLabel?.text = datasourceCachedImage == nil ? "Download" : "Done"
imageFetcher?.cancel()
}
}
private extension ImageTableViewCell {
func setupCell() {
progressView?.progress = datasourceCachedImage == nil ? 0 : 100
progressPercentageLabel?.text = datasourceCachedImage == nil ? "0%" : "100%"
imageNameLabel?.text = cellInfo?.imageName
downloadButton?.titleLabel?.text = datasourceCachedImage == nil ? "Download" : "Done"
}
} | mit |
yarshure/Surf | Surf/TitleView.swift | 1 | 1641 | //
// TitleView.swift
// Surf
//
// Created by yarshure on 16/5/25.
// Copyright © 2016年 yarshure. All rights reserved.
//
import UIKit
class TitleView: UIView {
var titleLabel:UILabel
var subLabel:UILabel
override init(frame: CGRect) {
var y0:CGFloat = 10.0
var y1:CGFloat = 32.0
let os = ProcessInfo().operatingSystemVersion
switch (os.majorVersion, os.minorVersion, os.patchVersion) {
case (8, 0, _):
print("iOS >= 8.0.0, < 8.1.0")
case (8, _, _):
print("iOS >= 8.1.0, < 9.0")
case (11, _, _):
y0 = y0 - 6
y1 = y1 - 6
default:
// this code will have already crashed on iOS 7, so >= iOS 10.0
print("iOS >= 9.0.0")
}
titleLabel = UILabel.init(frame: CGRect(x:0,y: y0,width: frame.size.width,height: 20))
titleLabel.font = UIFont.boldSystemFont(ofSize: 16)
//titleLabel?.sizeToFit()
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor.white
subLabel = UILabel.init(frame: CGRect(x:0, y:y1, width:frame.size.width, height:15))
subLabel.font = UIFont.systemFont(ofSize: 12)
//titleLabel?.sizeToFit()
subLabel.textAlignment = .center
subLabel.textColor = UIColor.lightGray
//subLabel.backgroundColor = UIColor.cyanColor()
super.init(frame: frame)
self.addSubview(titleLabel)
self.addSubview(subLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| bsd-3-clause |
MillmanY/MMLocalization | Example/Tests/Tests.swift | 1 | 764 | import UIKit
import XCTest
import MMLocalization
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.
XCTAssert(true, "Pass")
}
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 |
megavolt605/CNLUIKitTools | CNLUIKitTools/CNLDatePickerView.swift | 1 | 5283 | //
// CNLDatePickerView.swift
// CNLUIKitTools
//
// Created by Igor Smirnov on 25/11/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import UIKit
import CNLFoundationTools
public typealias CNLDatePickerValueChanged = (_ datePicker: CNLDatePicker, _ date: Date) -> Void
open class CNLDatePicker: UIPickerView {
fileprivate let maxRowCount = 500
fileprivate let dayCount = 31
fileprivate let monthCount = 12
fileprivate let yearCount = 110
fileprivate let calendar = Calendar.current
open var year: Int = 2000
open var month: Int = 1
open var day: Int = 1
open var valueChanged: CNLDatePickerValueChanged?
open var date: Date {
var dc = DateComponents()
dc.calendar = calendar
dc.year = year
dc.month = month
dc.day = day
while !dc.isValidDate(in: calendar) {
day -= 1
}
dc.day = day
let date = dc.date!.addingTimeInterval(TimeInterval(calendar.timeZone.secondsFromGMT()))
return date
}
open func setDate(_ date: Date, animated: Bool) {
let dc = (calendar as Calendar).dateComponents([.day, .month, .year], from: date)
year = dc.year!
month = dc.month!
day = dc.day!
var s = (maxRowCount / 2 / dayCount) * dayCount
selectRow(s + day - 1, inComponent: 0, animated: animated)
s = (maxRowCount / 2 / monthCount) * monthCount
selectRow(s + month - 1, inComponent: 1, animated: animated)
s = (maxRowCount / 2 / yearCount) * yearCount
selectRow(s + year - 1900, inComponent: 2, animated: animated)
valueChanged?(self, date)
}
func initialization() {
dataSource = self
delegate = self
setDate(date, animated: false)
//calendar.timeZone = NSTimeZone.localTimeZone()
}
override public init(frame: CGRect) {
super.init(frame: frame)
initialization()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialization()
}
convenience init() {
self.init(frame: CGRect.zero)
}
}
extension CNLDatePicker: UIPickerViewDataSource {
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return maxRowCount
}
}
extension CNLDatePicker: UIPickerViewDelegate {
public func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
switch component {
case 0: return 60
case 1: return 150
case 2: return 70
default: return 30
}
}
public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 40.0
}
public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let s = pickerView.rowSize(forComponent: component)
let v = UIView(frame: CGRect(x: 0.0, y: 0.0, width: s.width, height: s.height))
let l = UILabel(frame: v.bounds)
l.backgroundColor = UIColor(white: 0.3, alpha: 1.0)
l.isOpaque = false
l.textColor = UIColor.white
l.font = UIFont.systemFont(ofSize: 24.0)
l.textAlignment = .center
switch component {
case 0: // day
var b = l.frame
b.size.width -= 5.0
l.text = "\(row % dayCount + 1)"
case 1: // month
let df = DateFormatter()
df.dateFormat = "MMMM"
var dc = DateComponents()
dc.year = 2000
dc.month = row % monthCount + 1
dc.day = 1
dc.calendar = calendar
l.text = "\(df.string(from: dc.date!))"
case 2: // year
l.text = "\(1900 + row % yearCount)"
default: break
}
v.addSubview(l)
return l
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch component {
case 0:
let s = (maxRowCount / 2 / dayCount) * dayCount
day = row - s + 1
while day <= 0 { day += dayCount }
while day > dayCount { day -= dayCount }
selectRow(s + day - 1, inComponent: component, animated: false)
case 1:
let s = (maxRowCount / 2 / monthCount) * monthCount
month = row - s + 1
while month <= 0 { month += monthCount }
while month > monthCount { month -= monthCount }
selectRow(s + month - 1, inComponent: component, animated: false)
case 2:
let s = (maxRowCount / 2 / yearCount) * yearCount
year = row - s
while year <= 0 { year += yearCount }
while year > yearCount { year -= yearCount }
selectRow(s + year, inComponent: component, animated: false)
year += 1900
default: break
}
setDate(date, animated: true)
}
}
| mit |
hyperoslo/Postman | Pod/Demo/ViewController.swift | 1 | 893 | import UIKit
class ViewController: UIViewController, PostmanDelegate {
var postman: Postman?
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.view.backgroundColor = UIColor.whiteColor()
let button = UIBarButtonItem(
title: "Send mail",
style: .Done,
target: self,
action: "sendMailAction")
navigationItem.leftBarButtonItem = button
}
func sendMailAction() {
postman = Postman()
postman!.sendMailTo(
"olivia@louise.com",
subject: "Hi",
body: "Livy Darling, \n\nI am grateful — grate-fuller than ever before — that you were born, & that your love is mine & our two lives woven & melded together! \n\n- SLC",
attachment: nil,
usingController: self)
postman!.delegate = self
}
func postmanDidFinish(postman: Postman!) {
println("postmanDidFinish!")
}
}
| mit |
Coderian/SwiftedKML | SwiftedKML/Elements/LinkName.swift | 1 | 1093 | //
// LinkName.swift
// SwiftedKML
//
// Created by 佐々木 均 on 2016/02/02.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// KML LinkName
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <element name="linkName" type="string"/>
public class LinkName:SPXMLElement,HasXMLElementValue,HasXMLElementSimpleValue {
public static var elementName: String = "linkName"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as NetworkLinkControl: v.value.linkName = self
default: break
}
}
}
}
public var value: String = ""
public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{
self.value = contents
self.parent = parent
return parent
}
}
| mit |
caiodias/CleanerSkeeker | CleanerSeeker/CleanerSeeker/LoginViewController.swift | 1 | 2511 | //
// LoginScreenUI.swift
// CleanerSeeker
//
// Created by Orest Hazda on 29/03/17.
// Copyright © 2017 Caio Dias. All rights reserved.
//
import UIKit
class LoginViewController: BasicVC {
private enum ShowTabController: String {
case Worker = "workerTabController"
case JobPoster = "jobPosterTabController"
}
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var userName: UITextField!
@IBOutlet weak var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
super.baseScrollView = self.scrollView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
if let currentUser = CSUser.current() {
//User is logged in so redirect him based on type and update location
self.redirectLoggedInUser(currentUser)
}
}
@IBAction func login(_ sender: UIButton) {
self.handleTap()
Utilities.showLoading()
Facade.shared.loginUser(login: userName.text!, password: password.text!, onSuccess: onLoginSuccess, onFail: onLoginFail)
}
// MARK: Redirect user to right tab controller
private func displayTabController(tabController: ShowTabController) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
print("Not possible to get the appDelegate")
return
}
let initialViewController = self.storyboard!.instantiateViewController(withIdentifier: tabController.rawValue)
// Replace root controller
appDelegate.window?.rootViewController = initialViewController
appDelegate.window?.makeKeyAndVisible()
}
// MARK: login callbacks
private func onLoginSuccess(object: Any) {
print(object)
Utilities.dismissLoading()
guard let user = object as? CSUser else {
print("Not possible convert login object to user")
return
}
self.redirectLoggedInUser(user)
}
private func redirectLoggedInUser(_ user: CSUser) {
if user.userType == CSUserType.Worker.rawValue {
Facade.shared.updateCurrentUserLoccation()
displayTabController(tabController: ShowTabController.Worker)
} else {
displayTabController(tabController: ShowTabController.JobPoster)
}
}
private func onLoginFail(error: Error) {
Utilities.dismissLoading()
Utilities.displayAlert(error)
}
}
| mit |
Navdy/protobuf-swift | plugin/ProtocolBuffers/ProtocolBuffersTests/pbTests/ProtobufUnittest.UnittestLiteImportsNonlite.proto.swift | 1 | 13925 | // Generated by the Protocol Buffers 3.0 compiler. DO NOT EDIT!
// Source file "unittest_lite_imports_nonlite.proto"
// Syntax "Proto2"
import Foundation
import ProtocolBuffers
public extension ProtobufUnittest{}
public extension ProtobufUnittest {
public struct UnittestLiteImportsNonliteRoot {
public static let `default` = UnittestLiteImportsNonliteRoot()
public var extensionRegistry:ExtensionRegistry
init() {
extensionRegistry = ExtensionRegistry()
registerAllExtensions(registry: extensionRegistry)
ProtobufUnittest.UnittestRoot.default.registerAllExtensions(registry: extensionRegistry)
}
public func registerAllExtensions(registry: ExtensionRegistry) {
}
}
final public class TestLiteImportsNonlite : GeneratedMessage {
public static func == (lhs: ProtobufUnittest.TestLiteImportsNonlite, rhs: ProtobufUnittest.TestLiteImportsNonlite) -> Bool {
if (lhs === rhs) {
return true
}
var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)
fieldCheck = fieldCheck && (lhs.hasMessage == rhs.hasMessage) && (!lhs.hasMessage || lhs.message == rhs.message)
fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields))
return fieldCheck
}
public fileprivate(set) var message:ProtobufUnittest.TestAllTypes!
public fileprivate(set) var hasMessage:Bool = false
required public init() {
super.init()
}
override public func isInitialized() -> Bool {
return true
}
override public func writeTo(codedOutputStream: CodedOutputStream) throws {
if hasMessage {
try codedOutputStream.writeMessage(fieldNumber: 1, value:message)
}
try unknownFields.writeTo(codedOutputStream: codedOutputStream)
}
override public func serializedSize() -> Int32 {
var serialize_size:Int32 = memoizedSerializedSize
if serialize_size != -1 {
return serialize_size
}
serialize_size = 0
if hasMessage {
if let varSizemessage = message?.computeMessageSize(fieldNumber: 1) {
serialize_size += varSizemessage
}
}
serialize_size += unknownFields.serializedSize()
memoizedSerializedSize = serialize_size
return serialize_size
}
public class func getBuilder() -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
return ProtobufUnittest.TestLiteImportsNonlite.classBuilder() as! ProtobufUnittest.TestLiteImportsNonlite.Builder
}
public func getBuilder() -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
return classBuilder() as! ProtobufUnittest.TestLiteImportsNonlite.Builder
}
override public class func classBuilder() -> ProtocolBuffersMessageBuilder {
return ProtobufUnittest.TestLiteImportsNonlite.Builder()
}
override public func classBuilder() -> ProtocolBuffersMessageBuilder {
return ProtobufUnittest.TestLiteImportsNonlite.Builder()
}
public func toBuilder() throws -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
return try ProtobufUnittest.TestLiteImportsNonlite.builderWithPrototype(prototype:self)
}
public class func builderWithPrototype(prototype:ProtobufUnittest.TestLiteImportsNonlite) throws -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
return try ProtobufUnittest.TestLiteImportsNonlite.Builder().mergeFrom(other:prototype)
}
override public func encode() throws -> Dictionary<String,Any> {
guard isInitialized() else {
throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message")
}
var jsonMap:Dictionary<String,Any> = Dictionary<String,Any>()
if hasMessage {
jsonMap["message"] = try message.encode()
}
return jsonMap
}
override class public func decode(jsonMap:Dictionary<String,Any>) throws -> ProtobufUnittest.TestLiteImportsNonlite {
return try ProtobufUnittest.TestLiteImportsNonlite.Builder.decodeToBuilder(jsonMap:jsonMap).build()
}
override class public func fromJSON(data:Data) throws -> ProtobufUnittest.TestLiteImportsNonlite {
return try ProtobufUnittest.TestLiteImportsNonlite.Builder.fromJSONToBuilder(data:data).build()
}
override public func getDescription(indent:String) throws -> String {
var output = ""
if hasMessage {
output += "\(indent) message {\n"
if let outDescMessage = message {
output += try outDescMessage.getDescription(indent: "\(indent) ")
}
output += "\(indent) }\n"
}
output += unknownFields.getDescription(indent: indent)
return output
}
override public var hashValue:Int {
get {
var hashCode:Int = 7
if hasMessage {
if let hashValuemessage = message?.hashValue {
hashCode = (hashCode &* 31) &+ hashValuemessage
}
}
hashCode = (hashCode &* 31) &+ unknownFields.hashValue
return hashCode
}
}
//Meta information declaration start
override public class func className() -> String {
return "ProtobufUnittest.TestLiteImportsNonlite"
}
override public func className() -> String {
return "ProtobufUnittest.TestLiteImportsNonlite"
}
//Meta information declaration end
final public class Builder : GeneratedMessageBuilder {
fileprivate var builderResult:ProtobufUnittest.TestLiteImportsNonlite = ProtobufUnittest.TestLiteImportsNonlite()
public func getMessage() -> ProtobufUnittest.TestLiteImportsNonlite {
return builderResult
}
required override public init () {
super.init()
}
public var hasMessage:Bool {
get {
return builderResult.hasMessage
}
}
public var message:ProtobufUnittest.TestAllTypes! {
get {
if messageBuilder_ != nil {
builderResult.message = messageBuilder_.getMessage()
}
return builderResult.message
}
set (value) {
builderResult.hasMessage = true
builderResult.message = value
}
}
fileprivate var messageBuilder_:ProtobufUnittest.TestAllTypes.Builder! {
didSet {
builderResult.hasMessage = true
}
}
public func getMessageBuilder() -> ProtobufUnittest.TestAllTypes.Builder {
if messageBuilder_ == nil {
messageBuilder_ = ProtobufUnittest.TestAllTypes.Builder()
builderResult.message = messageBuilder_.getMessage()
if message != nil {
try! messageBuilder_.mergeFrom(other: message)
}
}
return messageBuilder_
}
@discardableResult
public func setMessage(_ value:ProtobufUnittest.TestAllTypes!) -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
self.message = value
return self
}
@discardableResult
public func mergeMessage(value:ProtobufUnittest.TestAllTypes) throws -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
if builderResult.hasMessage {
builderResult.message = try ProtobufUnittest.TestAllTypes.builderWithPrototype(prototype:builderResult.message).mergeFrom(other: value).buildPartial()
} else {
builderResult.message = value
}
builderResult.hasMessage = true
return self
}
@discardableResult
public func clearMessage() -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
messageBuilder_ = nil
builderResult.hasMessage = false
builderResult.message = nil
return self
}
override public var internalGetResult:GeneratedMessage {
get {
return builderResult
}
}
@discardableResult
override public func clear() -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
builderResult = ProtobufUnittest.TestLiteImportsNonlite()
return self
}
override public func clone() throws -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
return try ProtobufUnittest.TestLiteImportsNonlite.builderWithPrototype(prototype:builderResult)
}
override public func build() throws -> ProtobufUnittest.TestLiteImportsNonlite {
try checkInitialized()
return buildPartial()
}
public func buildPartial() -> ProtobufUnittest.TestLiteImportsNonlite {
let returnMe:ProtobufUnittest.TestLiteImportsNonlite = builderResult
return returnMe
}
@discardableResult
public func mergeFrom(other:ProtobufUnittest.TestLiteImportsNonlite) throws -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
if other == ProtobufUnittest.TestLiteImportsNonlite() {
return self
}
if (other.hasMessage) {
try mergeMessage(value: other.message)
}
try merge(unknownField: other.unknownFields)
return self
}
@discardableResult
override public func mergeFrom(codedInputStream: CodedInputStream) throws -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry())
}
@discardableResult
override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields)
while (true) {
let protobufTag = try codedInputStream.readTag()
switch protobufTag {
case 0:
self.unknownFields = try unknownFieldsBuilder.build()
return self
case 10:
let subBuilder:ProtobufUnittest.TestAllTypes.Builder = ProtobufUnittest.TestAllTypes.Builder()
if hasMessage {
try subBuilder.mergeFrom(other: message)
}
try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry)
message = subBuilder.buildPartial()
default:
if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) {
unknownFields = try unknownFieldsBuilder.build()
return self
}
}
}
}
class override public func decodeToBuilder(jsonMap:Dictionary<String,Any>) throws -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
let resultDecodedBuilder = ProtobufUnittest.TestLiteImportsNonlite.Builder()
if let jsonValueMessage = jsonMap["message"] as? Dictionary<String,Any> {
resultDecodedBuilder.message = try ProtobufUnittest.TestAllTypes.Builder.decodeToBuilder(jsonMap:jsonValueMessage).build()
}
return resultDecodedBuilder
}
override class public func fromJSONToBuilder(data:Data) throws -> ProtobufUnittest.TestLiteImportsNonlite.Builder {
let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0))
guard let jsDataCast = jsonData as? Dictionary<String,Any> else {
throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data")
}
return try ProtobufUnittest.TestLiteImportsNonlite.Builder.decodeToBuilder(jsonMap:jsDataCast)
}
}
}
}
extension ProtobufUnittest.TestLiteImportsNonlite: GeneratedMessageProtocol {
public class func parseArrayDelimitedFrom(inputStream: InputStream) throws -> Array<ProtobufUnittest.TestLiteImportsNonlite> {
var mergedArray = Array<ProtobufUnittest.TestLiteImportsNonlite>()
while let value = try parseDelimitedFrom(inputStream: inputStream) {
mergedArray.append(value)
}
return mergedArray
}
public class func parseDelimitedFrom(inputStream: InputStream) throws -> ProtobufUnittest.TestLiteImportsNonlite? {
return try ProtobufUnittest.TestLiteImportsNonlite.Builder().mergeDelimitedFrom(inputStream: inputStream)?.build()
}
public class func parseFrom(data: Data) throws -> ProtobufUnittest.TestLiteImportsNonlite {
return try ProtobufUnittest.TestLiteImportsNonlite.Builder().mergeFrom(data: data, extensionRegistry:ProtobufUnittest.UnittestLiteImportsNonliteRoot.default.extensionRegistry).build()
}
public class func parseFrom(data: Data, extensionRegistry:ExtensionRegistry) throws -> ProtobufUnittest.TestLiteImportsNonlite {
return try ProtobufUnittest.TestLiteImportsNonlite.Builder().mergeFrom(data: data, extensionRegistry:extensionRegistry).build()
}
public class func parseFrom(inputStream: InputStream) throws -> ProtobufUnittest.TestLiteImportsNonlite {
return try ProtobufUnittest.TestLiteImportsNonlite.Builder().mergeFrom(inputStream: inputStream).build()
}
public class func parseFrom(inputStream: InputStream, extensionRegistry:ExtensionRegistry) throws -> ProtobufUnittest.TestLiteImportsNonlite {
return try ProtobufUnittest.TestLiteImportsNonlite.Builder().mergeFrom(inputStream: inputStream, extensionRegistry:extensionRegistry).build()
}
public class func parseFrom(codedInputStream: CodedInputStream) throws -> ProtobufUnittest.TestLiteImportsNonlite {
return try ProtobufUnittest.TestLiteImportsNonlite.Builder().mergeFrom(codedInputStream: codedInputStream).build()
}
public class func parseFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> ProtobufUnittest.TestLiteImportsNonlite {
return try ProtobufUnittest.TestLiteImportsNonlite.Builder().mergeFrom(codedInputStream: codedInputStream, extensionRegistry:extensionRegistry).build()
}
}
// @@protoc_insertion_point(global_scope)
| apache-2.0 |
KanChen2015/DRCCamera | DRCCamera/DRCCameraSwiftTests/DRCCameraSwiftTests.swift | 1 | 996 | //
// DRCCameraSwiftTests.swift
// DRCCameraSwiftTests
//
// Created by Kan Chen on 9/28/15.
// Copyright © 2015 Kan Chen. All rights reserved.
//
import XCTest
@testable import DRCCameraSwift
class DRCCameraSwiftTests: 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 |
beforeload/love-finder-app | LoveFinderTests/LoveFinderTests.swift | 1 | 903 | //
// LoveFinderTests.swift
// LoveFinderTests
//
// Created by daniel on 9/28/14.
// Copyright (c) 2014 beforeload. All rights reserved.
//
import UIKit
import XCTest
class LoveFinderTests: 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 |
crspybits/SMSyncServer | iOS/iOSTests/Pods/SMSyncServer/SMSyncServer/Classes/Public/SMSyncServerUser.swift | 1 | 14600 | //
// SMSyncServerUser.swift
// SMSyncServer
//
// Created by Christopher Prince on 1/18/16.
// Copyright © 2016 Spastic Muffin, LLC. All rights reserved.
//
// Provides user sign-in & authentication for the SyncServer.
import Foundation
import SMCoreLib
// "class" so its delegate var can be weak.
internal protocol SMServerAPIUserDelegate : class {
var userCredentialParams:[String:AnyObject]? {get}
func refreshUserCredentials()
}
public struct SMLinkedAccount {
// This is the userId assigned by the sync server, not by the specific account system.
public var internalUserId:SMInternalUserId
public var userName:String?
public var capabilityMask:SMSharingUserCapabilityMask
}
public enum SMUserType : Equatable {
case OwningUser
// The owningUserId selects the specific shared/linked account being shared. It should only be nil when you are first creating the account, or redeeming a new sharing invitation.
case SharingUser(owningUserId:SMInternalUserId?)
public func toString() -> String {
switch self {
case .OwningUser:
return SMServerConstants.userTypeOwning
case .SharingUser:
return SMServerConstants.userTypeSharing
}
}
}
public func ==(lhs:SMUserType, rhs:SMUserType) -> Bool {
switch lhs {
case .OwningUser:
switch rhs {
case .OwningUser:
return true
case .SharingUser(_):
return false
}
case .SharingUser(_):
switch rhs {
case .OwningUser:
return false
case .SharingUser(_):
return true
}
}
}
// This enum is the interface from the client app to the SMSyncServer framework providing client credential information to the server.
public enum SMUserCredentials {
// In the following,
// userType *must* be OwningUser.
// When using as a parameter to call createNewUser, authCode must not be nil.
case Google(userType:SMUserType, idToken:String!, authCode:String?, userName:String?)
// userType *must* be SharingUser
case Facebook(userType:SMUserType, accessToken:String!, userId:String!, userName:String?)
internal func toServerParameterDictionary() -> [String:AnyObject] {
var userCredentials = [String:AnyObject]()
switch self {
case .Google(userType: let userType, idToken: let idToken, authCode: let authCode, userName: let userName):
Assert.If(userType != .OwningUser, thenPrintThisString: "Yikes: Google accounts with userTypeSharing not yet implemented!")
Log.msg("Sending IdToken: \(idToken)")
userCredentials[SMServerConstants.userType] = userType.toString()
userCredentials[SMServerConstants.accountType] = SMServerConstants.accountTypeGoogle
userCredentials[SMServerConstants.googleUserIdToken] = idToken
userCredentials[SMServerConstants.googleUserAuthCode] = authCode
userCredentials[SMServerConstants.accountUserName] = userName
case .Facebook(userType: let userType, accessToken: let accessToken, userId: let userId, userName: let userName):
switch userType {
case .OwningUser:
Assert.badMojo(alwaysPrintThisString: "Yikes: Not allowed!")
case .SharingUser(owningUserId: let owningUserId):
Log.msg("owningUserId: \(owningUserId)")
userCredentials[SMServerConstants.linkedOwningUserId] = owningUserId
}
userCredentials[SMServerConstants.userType] = userType.toString()
userCredentials[SMServerConstants.accountType] = SMServerConstants.accountTypeFacebook
userCredentials[SMServerConstants.facebookUserId] = userId
userCredentials[SMServerConstants.facebookUserAccessToken] = accessToken
userCredentials[SMServerConstants.accountUserName] = userName
}
return userCredentials
}
}
// This class is *not* intended to be subclassed for particular sign-in systems.
public class SMSyncServerUser {
private var _internalUserId:String?
// A distinct UUID for this user mobile device.
// I'm going to persist this in the keychain not so much because it needs to be secure, but rather because it will survive app deletions/reinstallations.
private static let MobileDeviceUUID = SMPersistItemString(name: "SMSyncServerUser.MobileDeviceUUID", initialStringValue: "", persistType: .KeyChain)
private var _signInCallback = NSObject()
// var signInCompletion:((error:NSError?)->(Void))?
internal weak var delegate: SMLazyWeakRef<SMUserSignInAccount>!
public static var session = SMSyncServerUser()
private init() {
self._signInCallback.resetTargets()
}
// You *must* set this (e.g., shortly after app launch). Currently, this must be a single name, with no subfolders, relative to the root. Don't put any "/" character in the name.
// 1/18/16; I just moved this here, from SMCloudStorageCredentials because it seems like the cloudFolderPath should be at a different level of abstraction, or at least seems independent of the details of cloud storage user creds.
// 1/18/16; I've now made this public because the folder used in cloud storage is fundamentally a client app decision-- i.e., it is a decision made by the user of SMSyncServer, e.g., Petunia.
// TODO: Eventually it would seem like a good idea to give the user a way to change the cloud folder path. BUT: It's a big change. i.e., the user shouldn't change this lightly because it will mean all of their data has to be moved or re-synced. (Plus, the SMSyncServer currently has no means to do such a move or re-sync-- it would have to be handled at a layer above the SMSyncServer).
public var cloudFolderPath:String?
internal func appLaunchSetup(withUserSignInLazyDelegate userSignInLazyDelegate:SMLazyWeakRef<SMUserSignInAccount>!) {
if 0 == SMSyncServerUser.MobileDeviceUUID.stringValue.characters.count {
SMSyncServerUser.MobileDeviceUUID.stringValue = UUID.make()
}
self.delegate = userSignInLazyDelegate
SMServerAPI.session.userDelegate = self
}
// Add target/selector to this to get a callback when the user sign-in process completes.
// An NSError? parameter is passed to each target/selector you give, which will be nil if there was no error in the sign-in process, and non-nil if there was an error in signing in.
public var signInProcessCompleted:TargetsAndSelectors {
get {
return self._signInCallback
}
}
// Is the user signed in? (So we don't have to expose the delegate publicly.)
public var signedIn:Bool {
get {
if let result = self.delegate.lazyRef?.syncServerUserIsSignedIn {
return result
}
else {
return false
}
}
}
// A string giving the identifier used internally on the SMSyncServer server to refer to a users cloud storage account. Has no meaning with respect to any specific cloud storage system (e.g., Google Drive).
// Returns non-nil value iff signedIn is true.
public var internalUserId:String? {
get {
if self.signedIn {
Assert.If(self._internalUserId == nil, thenPrintThisString: "Yikes: Nil internal user id")
return self._internalUserId
}
else {
return nil
}
}
}
public func signOut() {
self.delegate.lazyRef?.syncServerUserIsSignedIn
}
// This method doesn't keep a reference to userCreds; it just allows the caller to create a new user on the server.
public func createNewUser(callbacksAfterSigninSuccess callbacksAfterSignin:Bool=true, userCreds:SMUserCredentials, completion:((error: NSError?)->())?) {
switch (userCreds) {
case .Google(userType: _, idToken: _, authCode: let authCode, userName: _):
Assert.If(nil == authCode, thenPrintThisString: "The authCode must be non-nil when calling createNewUser for a Google user")
case .Facebook:
break
}
SMServerAPI.session.createNewUser(self.serverParameters(userCreds)) { internalUserId, cnuResult in
self._internalUserId = internalUserId
let returnError = self.processSignInResult(forExistingUser: false, apiResult: cnuResult)
self.finish(callbacksAfterSignin:callbacksAfterSignin, withError: returnError, completion: completion)
}
}
// This method doesn't keep a reference to userCreds; it just allows the caller to check for an existing user on the server.
public func checkForExistingUser(userCreds:SMUserCredentials, completion:((error: NSError?)->())?) {
SMServerAPI.session.checkForExistingUser(
self.serverParameters(userCreds)) { internalUserId, cfeuResult in
self._internalUserId = internalUserId
let returnError = self.processSignInResult(forExistingUser: true, apiResult: cfeuResult)
self.finish(withError: returnError, completion: completion)
}
}
// Optionally can have a currently signed in user. i.e., if you give userCreds, they will be used. Otherwise, the currently signed in user creds are used.
public func redeemSharingInvitation(invitationCode invitationCode:String, userCreds:SMUserCredentials?=nil, completion:((linkedOwningUserId:SMInternalUserId?, error: NSError?)->())?) {
var userCredParams:[String:AnyObject]
if userCreds == nil {
userCredParams = self.userCredentialParams!
}
else {
userCredParams = self.serverParameters(userCreds!)
}
SMServerAPI.session.redeemSharingInvitation(
userCredParams, invitationCode: invitationCode, completion: { (linkedOwningUserId, internalUserId, apiResult) in
Log.msg("SMServerAPI linkedOwningUserId: \(linkedOwningUserId)")
let returnError = self.processSignInResult(forExistingUser: true, apiResult: apiResult)
self.finish(withError: returnError) { error in
completion?(linkedOwningUserId:linkedOwningUserId, error: error)
}
})
}
private func finish(callbacksAfterSignin callbacksAfterSignin:Bool=true, withError error:NSError?, completion:((error: NSError?)->())?) {
// The ordering of these two lines of code is important. callSignInCompletion needs to be second because it tests for the sign-in state generated by the completion.
completion?(error: error)
if callbacksAfterSignin {
self.callSignInCompletion(withError: error)
}
}
public func getLinkedAccountsForSharingUser(userCreds:SMUserCredentials?=nil, completion:((linkedAccounts:[SMLinkedAccount]?, error:NSError?)->(Void))?) {
var userCredParams:[String:AnyObject]
if userCreds == nil {
userCredParams = self.userCredentialParams!
}
else {
userCredParams = self.serverParameters(userCreds!)
}
SMServerAPI.session.getLinkedAccountsForSharingUser(userCredParams) { (linkedAccounts, apiResult) -> (Void) in
completion?(linkedAccounts:linkedAccounts, error:apiResult.error)
}
}
private func callSignInCompletion(withError error:NSError?) {
if error == nil {
self._signInCallback.forEachTargetInCallbacksDo() { (obj:AnyObject?, sel:Selector, dict:NSMutableDictionary!) in
if let nsObject = obj as? NSObject {
nsObject.performSelector(sel, withObject: error)
}
else {
Assert.badMojo(alwaysPrintThisString: "Objects should be NSObject's")
}
}
}
else {
Log.error("Could not sign in: \(error)")
}
}
// Parameters in a REST API call to be provided to the server for a user's credentials & other info (e.g., deviceId, cloudFolderPath).
private func serverParameters(userCreds:SMUserCredentials) -> [String:AnyObject] {
Assert.If(0 == SMSyncServerUser.MobileDeviceUUID.stringValue.characters.count, thenPrintThisString: "Whoops: No device UUID!")
var userCredentials = userCreds.toServerParameterDictionary()
userCredentials[SMServerConstants.mobileDeviceUUIDKey] = SMSyncServerUser.MobileDeviceUUID.stringValue
userCredentials[SMServerConstants.cloudFolderPath] = self.cloudFolderPath!
var serverParameters = [String:AnyObject]()
serverParameters[SMServerConstants.userCredentialsDataKey] = userCredentials
return serverParameters
}
private func processSignInResult(forExistingUser existingUser:Bool, apiResult:SMServerAPIResult) -> NSError? {
// Not all non-nil "errors" actually indicate an error in our context. Check the return code first.
var returnError = apiResult.error
if apiResult.returnCode != nil {
switch (apiResult.returnCode!) {
case SMServerConstants.rcOK:
returnError = nil
case SMServerConstants.rcUserOnSystem:
returnError = nil
case SMServerConstants.rcUserNotOnSystem:
if existingUser {
returnError = Error.Create("That user doesn't exist yet-- you need to create the user first!")
}
default:
returnError = Error.Create("An error occurred when trying to sign in (return code: \(apiResult.returnCode))")
}
}
return returnError
}
}
extension SMSyncServerUser : SMServerAPIUserDelegate {
var userCredentialParams:[String:AnyObject]? {
get {
Assert.If(!self.signedIn, thenPrintThisString: "Yikes: There is no signed in user!")
if let creds = self.delegate.lazyRef?.syncServerSignedInUser {
return self.serverParameters(creds)
}
else {
return nil
}
}
}
func refreshUserCredentials() {
self.delegate.lazyRef?.syncServerRefreshUserCredentials()
}
}
| gpl-3.0 |
nathawes/swift | test/SILOptimizer/global_init_opt.swift | 22 | 840 | // RUN: %target-swift-frontend -parse-as-library -O -module-name=test %s -emit-sil | %FileCheck %s
var gg: Int = {
print("gg init")
return 27
}()
// CHECK-LABEL: sil @$s4test3cseSiyF
// CHECK: builtin "once"
// CHECK-NOT: builtin "once"
// CHECK: [[G:%[0-9]+]] = load
// CHECK-NOT: builtin "once"
// CHECK: builtin "sadd_{{.*}}"([[G]] : $Builtin.Int{{[0-9]+}}, [[G]] : $Builtin.Int{{[0-9]+}}, %{{[0-9]+}} : $Builtin.Int1)
// CHECK-NOT: builtin "once"
// CHECK: } // end sil function '$s4test3cseSiyF'
public func cse() -> Int {
return gg + gg
}
// CHECK-LABEL: sil @$s4test4licmSiyF
// CHECK: bb0:
// CHECK: builtin "once"
// CHECK: bb1{{.*}}:
// CHECK-NOT: builtin "once"
// CHECK: } // end sil function '$s4test4licmSiyF'
public func licm() -> Int {
var s = 0
for _ in 0..<100 {
s += gg
}
return s
}
| apache-2.0 |
roambotics/swift | test/Interop/SwiftToCxx/properties/getter-in-cxx.swift | 2 | 8589 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -typecheck -module-name Properties -clang-header-expose-decls=all-public -emit-clang-header-path %t/properties.h
// RUN: %FileCheck %s < %t/properties.h
// RUN: %check-interop-cxx-header-in-clang(%t/properties.h)
public struct FirstSmallStruct {
public let x: UInt32
}
// CHECK: class FirstSmallStruct final {
// CHECK: public:
// CHECK: inline FirstSmallStruct(FirstSmallStruct &&)
// CHECK-NEXT: inline uint32_t getX() const;
// CHECK-NEXT: private:
public struct LargeStruct {
public let x1, x2, x3, x4, x5, x6: Int
public var anotherLargeStruct: LargeStruct {
return LargeStruct(x1: 11, x2: 42, x3: -0xFFF, x4: 0xbad, x5: 5, x6: 0)
}
public var firstSmallStruct: FirstSmallStruct {
return FirstSmallStruct(x: 65)
}
static public var staticX: Int {
return -402
}
static public var staticSmallStruct: FirstSmallStruct {
return FirstSmallStruct(x: 789)
}
}
// CHECK: class LargeStruct final {
// CHECK: public:
// CHECK: inline LargeStruct(LargeStruct &&)
// CHECK-NEXT: inline swift::Int getX1() const;
// CHECK-NEXT: inline swift::Int getX2() const;
// CHECK-NEXT: inline swift::Int getX3() const;
// CHECK-NEXT: inline swift::Int getX4() const;
// CHECK-NEXT: inline swift::Int getX5() const;
// CHECK-NEXT: inline swift::Int getX6() const;
// CHECK-NEXT: inline LargeStruct getAnotherLargeStruct() const;
// CHECK-NEXT: inline FirstSmallStruct getFirstSmallStruct() const;
// CHECK-NEXT: static inline swift::Int getStaticX();
// CHECK-NEXT: static inline FirstSmallStruct getStaticSmallStruct();
// CHECK-NEXT: private:
public final class PropertiesInClass {
public let storedInt: Int32
init(_ x: Int32) {
storedInt = x
}
public var computedInt: Int {
return Int(storedInt) - 1
}
public var smallStruct: FirstSmallStruct {
return FirstSmallStruct(x: UInt32(-storedInt));
}
}
// CHECK: class PropertiesInClass final : public swift::_impl::RefCountedClass {
// CHECK: using RefCountedClass::operator=;
// CHECK-NEXT: inline int32_t getStoredInt();
// CHECK-NEXT: inline swift::Int getComputedInt();
// CHECK-NEXT: inline FirstSmallStruct getSmallStruct();
public func createPropsInClass(_ x: Int32) -> PropertiesInClass {
return PropertiesInClass(x)
}
public struct SmallStructWithGetters {
public let storedInt: UInt32
public var computedInt: Int {
return Int(storedInt) + 2
}
public var largeStruct: LargeStruct {
return LargeStruct(x1: computedInt * 2, x2: 1, x3: 2, x4: 3, x5: 4, x6: 5)
}
public var smallStruct: SmallStructWithGetters {
return SmallStructWithGetters(storedInt: 0xFAE);
}
}
// CHECK: class SmallStructWithGetters final {
// CHECK: public:
// CHECK: inline SmallStructWithGetters(SmallStructWithGetters &&)
// CHECK-NEXT: inline uint32_t getStoredInt() const;
// CHECK-NEXT: inline swift::Int getComputedInt() const;
// CHECK-NEXT: inline LargeStruct getLargeStruct() const;
// CHECK-NEXT: inline SmallStructWithGetters getSmallStruct() const;
// CHECK-NEXT: private:
public func createSmallStructWithGetter() -> SmallStructWithGetters {
return SmallStructWithGetters(storedInt: 21)
}
private class RefCountedClass {
let x: Int
init(x: Int) {
self.x = x
print("create RefCountedClass \(x)")
}
deinit {
print("destroy RefCountedClass \(x)")
}
}
public struct StructWithRefCountStoredProp {
private let storedRef: RefCountedClass
internal init(x: Int) {
storedRef = RefCountedClass(x: x)
}
public var another: StructWithRefCountStoredProp {
return StructWithRefCountStoredProp(x: 1)
}
}
public func createStructWithRefCountStoredProp() -> StructWithRefCountStoredProp {
return StructWithRefCountStoredProp(x: 0)
}
// CHECK: inline uint32_t FirstSmallStruct::getX() const {
// CHECK-NEXT: return _impl::$s10Properties16FirstSmallStructV1xs6UInt32Vvg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: }
// CHECK: inline swift::Int LargeStruct::getX1() const {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x1Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int LargeStruct::getX2() const {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x2Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int LargeStruct::getX3() const {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x3Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int LargeStruct::getX4() const {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x4Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int LargeStruct::getX5() const {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x5Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int LargeStruct::getX6() const {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x6Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline LargeStruct LargeStruct::getAnotherLargeStruct() const {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s10Properties11LargeStructV07anotherbC0ACvg(result, _getOpaquePointer());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline FirstSmallStruct LargeStruct::getFirstSmallStruct() const {
// CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Properties_uint32_t_0_4(result, _impl::$s10Properties11LargeStructV010firstSmallC0AA05FirsteC0Vvg(_getOpaquePointer()));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int LargeStruct::getStaticX() {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV7staticXSivgZ();
// CHECK-NEXT: }
// CHECK-NEXT: inline FirstSmallStruct LargeStruct::getStaticSmallStruct() {
// CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Properties_uint32_t_0_4(result, _impl::$s10Properties11LargeStructV011staticSmallC0AA05FirsteC0VvgZ());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline int32_t PropertiesInClass::getStoredInt() {
// CHECK-NEXT: return _impl::$s10Properties0A7InClassC9storedInts5Int32Vvg(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int PropertiesInClass::getComputedInt() {
// CHECK-NEXT: return _impl::$s10Properties0A7InClassC11computedIntSivg(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }
// CHECK-NEXT: inline FirstSmallStruct PropertiesInClass::getSmallStruct() {
// CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Properties_uint32_t_0_4(result, _impl::$s10Properties0A7InClassC11smallStructAA010FirstSmallE0Vvg(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this)));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline uint32_t SmallStructWithGetters::getStoredInt() const {
// CHECK-NEXT: return _impl::$s10Properties22SmallStructWithGettersV9storedInts6UInt32Vvg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int SmallStructWithGetters::getComputedInt() const {
// CHECK-NEXT: return _impl::$s10Properties22SmallStructWithGettersV11computedIntSivg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: }
// CHECK-NEXT: inline LargeStruct SmallStructWithGetters::getLargeStruct() const {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s10Properties22SmallStructWithGettersV05largeC0AA05LargeC0Vvg(result, _impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline SmallStructWithGetters SmallStructWithGetters::getSmallStruct() const {
// CHECK-NEXT: return _impl::_impl_SmallStructWithGetters::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Properties_uint32_t_0_4(result, _impl::$s10Properties22SmallStructWithGettersV05smallC0ACvg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer())));
// CHECK-NEXT: });
// CHECK-NEXT: }
| apache-2.0 |
dokun1/Lumina | Sources/Lumina/Camera/Extensions/FocusHandlerExtension.swift | 1 | 1852 | //
// FocusHandlerExtension.swift
// Lumina
//
// Created by David Okun on 11/20/17.
// Copyright © 2017 David Okun. All rights reserved.
//
import Foundation
import AVFoundation
extension LuminaCamera {
func handleFocus(at focusPoint: CGPoint) {
self.sessionQueue.async {
guard let input = self.videoInput else {
return
}
do {
if input.device.isFocusModeSupported(.autoFocus) && input.device.isFocusPointOfInterestSupported {
try input.device.lockForConfiguration()
input.device.focusMode = .autoFocus
input.device.focusPointOfInterest = CGPoint(x: focusPoint.x, y: focusPoint.y)
if input.device.isExposureModeSupported(.autoExpose) && input.device.isExposurePointOfInterestSupported {
input.device.exposureMode = .autoExpose
input.device.exposurePointOfInterest = CGPoint(x: focusPoint.x, y: focusPoint.y)
}
input.device.unlockForConfiguration()
} else {
self.delegate?.finishedFocus(camera: self)
}
} catch {
self.delegate?.finishedFocus(camera: self)
}
}
}
func resetCameraToContinuousExposureAndFocus() {
do {
guard let input = self.videoInput else {
LuminaLogger.error(message: "Trying to focus, but cannot detect device input!")
return
}
if input.device.isFocusModeSupported(.continuousAutoFocus) {
try input.device.lockForConfiguration()
input.device.focusMode = .continuousAutoFocus
if input.device.isExposureModeSupported(.continuousAutoExposure) {
input.device.exposureMode = .continuousAutoExposure
}
input.device.unlockForConfiguration()
}
} catch {
LuminaLogger.error(message: "could not reset to continuous auto focus and exposure!!")
}
}
}
| mit |
IngmarStein/swift | validation-test/IDE/crashers/016-swift-mangle-mangler-mangleidentifier.swift | 3 | 128 | // RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
var d{let:{func a#^A^#
| apache-2.0 |
crazypoo/PTools | Pods/FluentDarkModeKit/Sources/FluentDarkModeKit/Extensions/UITextField+DarkModeKit.swift | 1 | 1643 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
extension UITextField {
override open func dmTraitCollectionDidChange(_ previousTraitCollection: DMTraitCollection?) {
super.dmTraitCollectionDidChange(previousTraitCollection)
if #available(iOS 13.0, *) {
return
}
else {
dm_updateDynamicColors()
if let dynamicTextColor = textColor?.copy() as? DynamicColor {
textColor = dynamicTextColor
}
keyboardAppearance = {
if DMTraitCollection.override.userInterfaceStyle == .dark {
return .dark
}
else {
return .default
}
}()
}
}
}
extension UITextField {
/// `UITextField` will not call `super.willMove(toWindow:)` in its implementation, so we need to swizzle it separately.
static let swizzleTextFieldWillMoveToWindowOnce: Void = {
let selector = #selector(willMove(toWindow:))
guard let method = class_getInstanceMethod(UITextField.self, selector) else {
assertionFailure(DarkModeManager.messageForSwizzlingFailed(class: UITextField.self, selector: selector))
return
}
let imp = method_getImplementation(method)
class_replaceMethod(UITextField.self, selector, imp_implementationWithBlock({ (self: UITextField, window: UIWindow?) -> Void in
let oldIMP = unsafeBitCast(imp, to: (@convention(c) (UITextField, Selector, UIWindow?) -> Void).self)
oldIMP(self, selector, window)
self.dmTraitCollectionDidChange(nil)
} as @convention(block) (UITextField, UIWindow?) -> Void), method_getTypeEncoding(method))
}()
}
| mit |
Fluffcorn/ios-sticker-packs-app | MessagesExtension/WAStickers code files/Limits.swift | 1 | 674 | //
// Copyright (c) WhatsApp Inc. and its affiliates.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
//
import UIKit
struct Limits {
static let MaxStickerFileSize: Int = 100 * 1024
static let MaxTrayImageFileSize: Int = 50 * 1024
static let TrayImageDimensions: CGSize = CGSize(width: 96, height: 96)
static let ImageDimensions: CGSize = CGSize(width: 512, height: 512)
static let MinStickersPerPack: Int = 3
static let MaxStickersPerPack: Int = 30
static let MaxCharLimit128: Int = 128
static let MaxEmojisCount: Int = 3
}
| mit |
JamesBirchall/udemyiossamples | Pokedex/Pokedex/Constants.swift | 1 | 237 | //
// Constants.swift
// Pokedex
//
// Created by James Birchall on 29/07/2017.
// Copyright © 2017 James Birchall. All rights reserved.
//
import Foundation
let URL_BASE = "http://pokeapi.co"
let URL_POKEMON = "/api/v1/pokemon/"
| apache-2.0 |
caronae/caronae-ios | Caronae/AppDelegate+Notifications.swift | 1 | 6189 | import AudioToolbox
extension AppDelegate {
func handleNotification(_ userInfo: [AnyHashable: Any]) -> Bool {
guard let notificationType = userInfo["msgType"] as? String else {
handleUnknownNotification(userInfo)
return false
}
switch notificationType {
case "chat":
handleChatNotification(userInfo)
case "joinRequest":
handleJoinRequestNotification(userInfo)
case "accepted":
handleJoinRequestAccepted(userInfo)
case "canceled", "cancelled", "finished", "refused":
handleFinishedNotification(userInfo)
case "quitter":
handleQuitterNotification(userInfo)
default:
handleUnknownNotification(userInfo)
return false
}
return true
}
private func handleJoinRequestNotification(_ userInfo: [AnyHashable: Any]) {
guard let (id, senderID, rideID, message) = rideNotificationInfo(userInfo) else {
NSLog("Received ride join request notification but could not parse the notification data")
return
}
let notification = Notification()
notification.id = id
notification.senderID = senderID
notification.rideID = rideID
notification.kind = .rideJoinRequest
NotificationService.instance.createNotification(notification)
showMessageIfActive(message)
}
private func handleJoinRequestAccepted(_ userInfo: [AnyHashable: Any]) {
guard let (id, senderID, rideID, message) = rideNotificationInfo(userInfo) else {
NSLog("Received ride join request accepted notification but could not parse the notification data")
return
}
let notification = Notification()
notification.id = id
notification.senderID = senderID
notification.rideID = rideID
notification.kind = .rideJoinRequestAccepted
NotificationService.instance.createNotification(notification)
updateMyRidesIfActive()
showMessageIfActive(message)
}
private func handleFinishedNotification(_ userInfo: [AnyHashable: Any]) {
guard let (_, _, rideID, message) = rideNotificationInfo(userInfo) else {
NSLog("Received ride finished notification but could not parse the notification data")
return
}
NotificationService.instance.clearNotifications(forRideID: rideID)
updateMyRidesIfActive()
showMessageIfActive(message)
}
private func handleQuitterNotification(_ userInfo: [AnyHashable: Any]) {
guard let (_, _, _, message) = rideNotificationInfo(userInfo) else {
NSLog("Received quitter notification but could not parse the notification data")
return
}
updateMyRidesIfActive()
showMessageIfActive(message)
}
private func handleChatNotification(_ userInfo: [AnyHashable: Any]) {
guard let (id, senderID, rideID, message) = rideNotificationInfo(userInfo),
senderID != UserService.instance.user?.id else {
return
}
ChatService.instance.updateMessagesForRide(withID: rideID) { error in
guard error == nil else {
NSLog("Error updating messages for ride %ld. (%@)", rideID, error!.localizedDescription)
return
}
NSLog("Updated messages for ride %ld", rideID)
}
// Display notification if the chat window is not already open
let notification = Notification()
notification.kind = .chat
notification.id = id
notification.senderID = senderID
notification.rideID = rideID
if UIApplication.shared.applicationState != .active {
NotificationService.instance.createNotification(notification)
return
}
if let topViewController = UIApplication.shared.topViewController(),
let chatViewController = topViewController as? ChatViewController,
chatViewController.ride.id == rideID {
return
}
NotificationService.instance.createNotification(notification)
showMessageIfActive(message)
}
private func handleUnknownNotification(_ userInfo: [AnyHashable: Any]) {
if let message = userInfo["message"] as? String {
showMessageIfActive(message)
} else {
NSLog("Received unknown notification type: (%@)", userInfo)
}
}
func playNotificationSound() {
AudioServicesPlayAlertSoundWithCompletion(beepSound, nil)
}
func showMessageIfActive(_ message: String) {
if UIApplication.shared.applicationState == .active {
playNotificationSound()
CaronaeMessagesNotification.instance.showSuccess(withText: message)
}
}
func updateMyRidesIfActive() {
if UIApplication.shared.applicationState == .active {
RideService.instance.updateMyRides(success: {
NSLog("My rides updated")
}, error: { error in
NSLog("Error updating my rides (\(error.localizedDescription))")
})
}
}
@objc func updateApplicationBadgeNumber() {
guard let notifications = try? NotificationService.instance.getNotifications() else { return }
UIApplication.shared.applicationIconBadgeNumber = notifications.count
}
private func rideNotificationInfo(_ userInfo: [AnyHashable: Any]) -> (String, Int, Int, String)? {
guard let id = userInfo["id"] as? String,
let senderIDString = userInfo["senderId"] as? String,
let senderID = Int(senderIDString),
let rideIDString = userInfo["rideId"] as? String,
let rideID = Int(rideIDString),
let message = userInfo["message"] as? String else {
return nil
}
return (id, senderID, rideID, message)
}
}
| gpl-3.0 |
jeannustre/HomeComics | HomeComics/HCFormats.swift | 1 | 416 | //
// HCFormats.swift
// HomeComics
//
// Created by Jean Sarda on 11/05/2017.
// Copyright © 2017 Jean Sarda. All rights reserved.
//
import UIKit
import Haneke
final class HCFormats {
private init() { }
static let shared = HCFormats()
let reader = Format<UIImage>(name: "ReaderCache", diskCapacity: UInt64(UserDefaults.standard.integer(forKey: "diskCache")) * 1024 * 1024)
}
| gpl-3.0 |
firebase/FirebaseUI-iOS | samples/swift/FirebaseUI-demo-swift/Samples/Auth/FUICustomAuthPickerViewController.swift | 1 | 799 | //
// Copyright (c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import FirebaseAuthUI
class FUICustomAuthPickerViewController: FUIAuthPickerViewController {
@IBAction func onClose(_ sender: AnyObject) {
self.cancelAuthorization()
}
}
| apache-2.0 |
pascaljette/PokeBattleDemo | PokeBattleDemo/Pods/GearKit/Pod/GearKit/GKTable/TableConfiguration/TableSection/GKTableSectionBase.swift | 2 | 1654 | // The MIT License (MIT)
//
// Copyright (c) 2015 pascaljette
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
/// Represents a section in the table view.
public class GKTableSectionBase {
//
// MARK: Stored properties
//
/// Array of cells that comprise the section. Empty array to have an empty section.
public var cells: [GKTableCellBase] = []
//
// MARK: Initializers
//
/// Initializer
///
/// - parameter cells: The cells contained in the section.
public init(cells: [GKTableCellBase]) {
self.cells = cells
}
}
| mit |
jeden/kocomojo-kit | KocomojoApp/KocomojoApp/extensions/String+Localization.swift | 2 | 263 | //
// String+Localization.swift
// KocomojoApp
//
// Created by Antonio Bello on 1/27/15.
// Copyright (c) 2015 Elapsus. All rights reserved.
//
import Foundation
extension String {
var localized: String { return NSLocalizedString(self, comment: "") }
} | mit |
fhisa/CocoaStudy | 20150905/LayoutSampleWithoutCode/LayoutSampleWithoutCode/ViewController.swift | 1 | 527 | //
// ViewController.swift
// LayoutSampleWithoutCode
//
// Created by fhisa on 2015/09/03.
// Copyright (c) 2015年 Hisakuni Fujimoto. 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 |
podverse/podverse-ios | Podverse/UITabbarController+PlayerView.swift | 1 | 5800 | //
// UITabbarController+PlayerView.swift
// Podverse
//
// Created by Creon Creonopoulos on 7/16/17.
// Copyright © 2017 Podverse LLC. All rights reserved.
//
import UIKit
protocol PlayerViewProtocol {
func setupPlayerBar()
func hidePlayerView()
func showPlayerView()
func goToNowPlaying(isDataAvailable:Bool)
var playerView:NowPlayingBar {get}
}
private var pvAssociationKey: UInt8 = 0
extension UITabBarController:PlayerViewProtocol {
var playerView:NowPlayingBar {
get {
return objc_getAssociatedObject(self, &pvAssociationKey) as! NowPlayingBar
}
set(newValue) {
objc_setAssociatedObject(self, &pvAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
override open func viewDidLoad() {
super.viewDidLoad()
self.playerView = NowPlayingBar()
setupPlayerBar()
}
func setupPlayerBar() {
var extraIphoneXSpace:CGFloat = 0.0
if (UIScreen.main.nativeBounds.height == 2436.0) {
extraIphoneXSpace = 33.0
}
self.playerView.frame = CGRect(x: self.tabBar.frame.minX,
y: self.tabBar.frame.minY - NowPlayingBar.playerHeight - extraIphoneXSpace,
width: self.tabBar.frame.width,
height: NowPlayingBar.playerHeight)
self.playerView.isHidden = true
self.view.addSubview(self.playerView)
self.playerView.delegate = self
}
func hidePlayerView() {
self.playerView.isHidden = true
PVViewController.delegate?.adjustTableView()
}
func showPlayerView() {
self.playerView.isHidden = false
PVViewController.delegate?.adjustTableView()
}
func goToNowPlaying(isDataAvailable:Bool = true) {
if let currentNavVC = self.selectedViewController?.childViewControllers.first?.navigationController {
var optionalMediaPlayerVC: MediaPlayerViewController?
for controller in currentNavVC.viewControllers {
if controller.isKind(of: MediaPlayerViewController.self) {
optionalMediaPlayerVC = controller as? MediaPlayerViewController
break
}
}
if let mediaPlayerVC = optionalMediaPlayerVC {
currentNavVC.popToViewController(mediaPlayerVC, animated: false)
} else if let mediaPlayerVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MediaPlayerVC") as? MediaPlayerViewController {
PVMediaPlayer.shared.isDataAvailable = isDataAvailable
if !isDataAvailable {
PVMediaPlayer.shared.shouldAutoplayOnce = true
}
currentNavVC.pushViewController(mediaPlayerVC, animated: true)
}
}
}
func goToClips(_ clipFilter:ClipFilter? = nil, _ clipSorting:ClipSorting? = nil) {
if let currentNavVC = self.selectedViewController?.childViewControllers.first?.navigationController {
var optionalClipsTVC: ClipsTableViewController?
for controller in currentNavVC.viewControllers {
if controller.isKind(of: ClipsTableViewController.self) {
optionalClipsTVC = controller as? ClipsTableViewController
break
}
}
if let clipFilter = clipFilter {
UserDefaults.standard.set(clipFilter.rawValue, forKey: kClipsTableFilterType)
} else {
UserDefaults.standard.set(ClipFilter.allPodcasts.rawValue, forKey: kClipsTableFilterType)
}
if let clipSorting = clipSorting {
UserDefaults.standard.set(clipSorting.rawValue, forKey: kClipsTableSortingType)
} else {
UserDefaults.standard.set(ClipSorting.topWeek.rawValue, forKey: kClipsTableFilterType)
}
if let clipsTVC = optionalClipsTVC {
clipsTVC.shouldOverrideQuery = true
currentNavVC.popToViewController(clipsTVC, animated: false)
} else if let clipsTVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ClipsTVC") as? ClipsTableViewController {
currentNavVC.pushViewController(clipsTVC, animated: false)
}
}
}
func goToPlaylistDetail(id:String) {
if let currentNavVC = self.selectedViewController?.childViewControllers.first?.navigationController {
if let playlistDetailVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PlaylistDetailVC") as? PlaylistDetailTableViewController {
playlistDetailVC.playlistId = id
playlistDetailVC.isDataAvailable = false
currentNavVC.pushViewController(playlistDetailVC, animated: true)
}
}
}
func gotoSearchPodcastView(id:String) {
if let currentNavVC = self.selectedViewController?.childViewControllers.first?.navigationController {
if let searchPodcastVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SearchPodcastVC") as? SearchPodcastViewController {
searchPodcastVC.podcastId = id
currentNavVC.pushViewController(searchPodcastVC, animated: true)
}
}
}
}
extension UITabBarController:NowPlayingBarDelegate {
func didTapView() {
goToNowPlaying()
}
}
| agpl-3.0 |
dduan/swift | validation-test/compiler_crashers_fixed/26040-swift-parser-parsetoken.swift | 11 | 430 | // 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
// RUN: not %target-swift-frontend %s -parse
{{{}
}class A{
protocol P{class
case,
| apache-2.0 |
omaralbeik/SwifterSwift | Sources/Extensions/UIKit/UITableViewExtensions.swift | 1 | 7663 | //
// UITableViewExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/22/16.
// Copyright © 2016 SwifterSwift
//
#if canImport(UIKit) && !os(watchOS)
import UIKit
// MARK: - Properties
public extension UITableView {
/// SwifterSwift: Index path of last row in tableView.
public var indexPathForLastRow: IndexPath? {
return indexPathForLastRow(inSection: lastSection)
}
/// SwifterSwift: Index of last section in tableView.
public var lastSection: Int {
return numberOfSections > 0 ? numberOfSections - 1 : 0
}
}
// MARK: - Methods
public extension UITableView {
/// SwifterSwift: Number of all rows in all sections of tableView.
///
/// - Returns: The count of all rows in the tableView.
public func numberOfRows() -> Int {
var section = 0
var rowCount = 0
while section < numberOfSections {
rowCount += numberOfRows(inSection: section)
section += 1
}
return rowCount
}
/// SwifterSwift: IndexPath for last row in section.
///
/// - Parameter section: section to get last row in.
/// - Returns: optional last indexPath for last row in section (if applicable).
public func indexPathForLastRow(inSection section: Int) -> IndexPath? {
guard section >= 0 else { return nil }
guard numberOfRows(inSection: section) > 0 else {
return IndexPath(row: 0, section: section)
}
return IndexPath(row: numberOfRows(inSection: section) - 1, section: section)
}
/// Reload data with a completion handler.
///
/// - Parameter completion: completion handler to run after reloadData finishes.
public func reloadData(_ completion: @escaping () -> Void) {
UIView.animate(withDuration: 0, animations: {
self.reloadData()
}, completion: { _ in
completion()
})
}
/// SwifterSwift: Remove TableFooterView.
public func removeTableFooterView() {
tableFooterView = nil
}
/// SwifterSwift: Remove TableHeaderView.
public func removeTableHeaderView() {
tableHeaderView = nil
}
/// SwifterSwift: Scroll to bottom of TableView.
///
/// - Parameter animated: set true to animate scroll (default is true).
public func scrollToBottom(animated: Bool = true) {
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height)
setContentOffset(bottomOffset, animated: animated)
}
/// SwifterSwift: Scroll to top of TableView.
///
/// - Parameter animated: set true to animate scroll (default is true).
public func scrollToTop(animated: Bool = true) {
setContentOffset(CGPoint.zero, animated: animated)
}
/// SwifterSwift: Dequeue reusable UITableViewCell using class name
///
/// - Parameter name: UITableViewCell type
/// - Returns: UITableViewCell object with associated class name.
public func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type) -> T {
guard let cell = dequeueReusableCell(withIdentifier: String(describing: name)) as? T else {
fatalError("Couldn't find UITableViewCell for \(String(describing: name))")
}
return cell
}
/// SwifterSwift: Dequeue reusable UITableViewCell using class name for indexPath
///
/// - Parameters:
/// - name: UITableViewCell type.
/// - indexPath: location of cell in tableView.
/// - Returns: UITableViewCell object with associated class name.
public func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type, for indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withIdentifier: String(describing: name), for: indexPath) as? T else {
fatalError("Couldn't find UITableViewCell for \(String(describing: name))")
}
return cell
}
/// SwifterSwift: Dequeue reusable UITableViewHeaderFooterView using class name
///
/// - Parameter name: UITableViewHeaderFooterView type
/// - Returns: UITableViewHeaderFooterView object with associated class name.
public func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(withClass name: T.Type) -> T {
guard let headerFooterView = dequeueReusableHeaderFooterView(withIdentifier: String(describing: name)) as? T else {
fatalError("Couldn't find UITableViewHeaderFooterView for \(String(describing: name))")
}
return headerFooterView
}
/// SwifterSwift: Register UITableViewHeaderFooterView using class name
///
/// - Parameters:
/// - nib: Nib file used to create the header or footer view.
/// - name: UITableViewHeaderFooterView type.
public func register<T: UITableViewHeaderFooterView>(nib: UINib?, withHeaderFooterViewClass name: T.Type) {
register(nib, forHeaderFooterViewReuseIdentifier: String(describing: name))
}
/// SwifterSwift: Register UITableViewHeaderFooterView using class name
///
/// - Parameter name: UITableViewHeaderFooterView type
public func register<T: UITableViewHeaderFooterView>(headerFooterViewClassWith name: T.Type) {
register(T.self, forHeaderFooterViewReuseIdentifier: String(describing: name))
}
/// SwifterSwift: Register UITableViewCell using class name
///
/// - Parameter name: UITableViewCell type
public func register<T: UITableViewCell>(cellWithClass name: T.Type) {
register(T.self, forCellReuseIdentifier: String(describing: name))
}
/// SwifterSwift: Register UITableViewCell using class name
///
/// - Parameters:
/// - nib: Nib file used to create the tableView cell.
/// - name: UITableViewCell type.
public func register<T: UITableViewCell>(nib: UINib?, withCellClass name: T.Type) {
register(nib, forCellReuseIdentifier: String(describing: name))
}
/// SwifterSwift: Register UITableViewCell with .xib file using only its corresponding class.
/// Assumes that the .xib filename and cell class has the same name.
///
/// - Parameters:
/// - name: UITableViewCell type.
/// - bundleClass: Class in which the Bundle instance will be based on.
public func register<T: UITableViewCell>(nibWithCellClass name: T.Type, at bundleClass: AnyClass? = nil) {
let identifier = String(describing: name)
var bundle: Bundle?
if let bundleName = bundleClass {
bundle = Bundle(for: bundleName)
}
register(UINib(nibName: identifier, bundle: bundle), forCellReuseIdentifier: identifier)
}
/// SwifterSwift: Check whether IndexPath is valid within the tableView
///
/// - Parameter indexPath: An IndexPath to check
/// - Returns: Boolean value for valid or invalid IndexPath
public func isValidIndexPath(_ indexPath: IndexPath) -> Bool {
return indexPath.section < numberOfSections && indexPath.row < numberOfRows(inSection: indexPath.section)
}
/// SwifterSwift: Safely scroll to possibly invalid IndexPath
///
/// - Parameters:
/// - indexPath: Target IndexPath to scroll to
/// - scrollPosition: Scroll position
/// - animated: Whether to animate or not
public func safeScrollToRow(at indexPath: IndexPath, at scrollPosition: UITableView.ScrollPosition, animated: Bool) {
guard indexPath.section < numberOfSections else { return }
guard indexPath.row < numberOfRows(inSection: indexPath.section) else { return }
scrollToRow(at: indexPath, at: scrollPosition, animated: animated)
}
}
#endif
| mit |
akrio714/Wbm | Wbm/Campaign/List/Model/CampaignListItemModel.swift | 1 | 1118 | //
// CampaignListItemModel.swift
// Wbm
//
// Created by akrio on 2017/7/14.
// Copyright © 2017年 akrio. All rights reserved.
//
import Foundation
import SwiftDate
import Moya_SwiftyJSONMapper
import SwiftyJSON
import RxDataSources
struct CampaignListItemModel:ALSwiftyJSONAble {
/// 唯一标示
let id:String
/// publisher名字
let publishers:[String]
/// 价格
let price:Float
/// 持续时间
let durations:Int
/// 创建时间
let createTime:DateInRegion
/// 图片地址
let imageUrl:String
init?(jsonData: JSON) {
self.publishers = jsonData["publishers"].arrayValue.map{ $0.stringValue }
self.price = jsonData["price"].floatValue
self.durations = jsonData["durations"].intValue
self.createTime = jsonData["createTime"].dateFormatValue(.iso8601Auto)
self.id = jsonData["id"].stringValue
self.imageUrl = jsonData["image"].stringValue
}
init() {
publishers = [""]
price = 0
durations = 0
createTime = DateInRegion()
id = ""
imageUrl = ""
}
}
| apache-2.0 |
hayashi311/iosdcjp2016app | iOSApp/iOSDCJP2016/Entities/Sponsor.swift | 1 | 702 | //
// Sponsor.swift
// iOSDCJP2016
//
// Created by hayashi311 on 7/10/16.
// Copyright © 2016 hayashi311. All rights reserved.
//
import Foundation
import Unbox
struct Sponsor: Unboxable {
let name: String
let description: String?
let image: String?
let url: String?
init(unboxer: Unboxer) {
name = unboxer.unbox("name")
description = unboxer.unbox("description")
image = unboxer.unbox("image")
url = unboxer.unbox("url")
}
}
struct SponsorTier: Unboxable {
let name: String
let sponsors: [Sponsor]
init(unboxer: Unboxer) {
name = unboxer.unbox("name")
sponsors = unboxer.unbox("sponsors")
}
}
| mit |
eburns1148/CareKit | testing/OCKTest/OCKTest/AppDelegate.swift | 1 | 3881 | /*
Copyright (c) 2016, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
#if swift(>=3.0)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
#else
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
#endif
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-3-clause |
Muxing1991/Standford_Developing_iOS8_With_Swift | AxesDrawer.swift | 1 | 8479 | //
// AxesDrawer.swift
// Calculator
//
// Created by CS193p Instructor.
// Copyright (c) 2015 Stanford University. All rights reserved.
//
import UIKit
class AxesDrawer
{
private struct Constants {
static let HashmarkSize: CGFloat = 6
}
var color = UIColor.blueColor()
var minimumPointsPerHashmark: CGFloat = 40
var contentScaleFactor: CGFloat = 1 // set this from UIView's contentScaleFactor to position axes with maximum accuracy
convenience init(color: UIColor, contentScaleFactor: CGFloat) {
self.init()
self.color = color
self.contentScaleFactor = contentScaleFactor
}
convenience init(color: UIColor) {
self.init()
self.color = color
}
convenience init(contentScaleFactor: CGFloat) {
self.init()
self.contentScaleFactor = contentScaleFactor
}
// this method is the heart of the AxesDrawer
// it draws in the current graphic context's coordinate system
// therefore origin and bounds must be in the current graphics context's coordinate system
// pointsPerUnit is essentially the "scale" of the axes
// e.g. if you wanted there to be 100 points along an axis between -1 and 1,
// you'd set pointsPerUnit to 50
func drawAxesInRect(bounds: CGRect, origin: CGPoint, pointsPerUnit: CGFloat)
{
CGContextSaveGState(UIGraphicsGetCurrentContext())
color.set()
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: bounds.minX, y: align(origin.y)))
path.addLineToPoint(CGPoint(x: bounds.maxX, y: align(origin.y)))
path.moveToPoint(CGPoint(x: align(origin.x), y: bounds.minY))
path.addLineToPoint(CGPoint(x: align(origin.x), y: bounds.maxY))
path.stroke()
drawHashmarksInRect(bounds, origin: origin, pointsPerUnit: abs(pointsPerUnit))
CGContextRestoreGState(UIGraphicsGetCurrentContext())
}
// the rest of this class is private
private func drawHashmarksInRect(bounds: CGRect, origin: CGPoint, pointsPerUnit: CGFloat)
{
if ((origin.x >= bounds.minX) && (origin.x <= bounds.maxX)) || ((origin.y >= bounds.minY) && (origin.y <= bounds.maxY))
{
// figure out how many units each hashmark must represent
// to respect both pointsPerUnit and minimumPointsPerHashmark
var unitsPerHashmark = minimumPointsPerHashmark / pointsPerUnit
if unitsPerHashmark < 1 {
unitsPerHashmark = pow(10, ceil(log10(unitsPerHashmark)))
} else {
unitsPerHashmark = floor(unitsPerHashmark)
}
let pointsPerHashmark = pointsPerUnit * unitsPerHashmark
// figure out which is the closest set of hashmarks (radiating out from the origin) that are in bounds
var startingHashmarkRadius: CGFloat = 1
if !CGRectContainsPoint(bounds, origin) {
if origin.x > bounds.maxX {
startingHashmarkRadius = (origin.x - bounds.maxX) / pointsPerHashmark + 1
} else if origin.x < bounds.minX {
startingHashmarkRadius = (bounds.minX - origin.x) / pointsPerHashmark + 1
} else if origin.y > bounds.maxY {
startingHashmarkRadius = (origin.y - bounds.maxY) / pointsPerHashmark + 1
} else {
startingHashmarkRadius = (bounds.minY - origin.y) / pointsPerHashmark + 1
}
startingHashmarkRadius = floor(startingHashmarkRadius)
}
// now create a bounding box inside whose edges those four hashmarks lie
let bboxSize = pointsPerHashmark * startingHashmarkRadius * 2
var bbox = CGRect(center: origin, size: CGSize(width: bboxSize, height: bboxSize))
// formatter for the hashmark labels
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = Int(-log10(Double(unitsPerHashmark)))
formatter.minimumIntegerDigits = 1
// radiate the bbox out until the hashmarks are further out than the bounds
while !CGRectContainsRect(bbox, bounds)
{
let label = formatter.stringFromNumber((origin.x-bbox.minX)/pointsPerUnit)!
if let leftHashmarkPoint = alignedPoint(bbox.minX, y: origin.y, insideBounds:bounds) {
drawHashmarkAtLocation(leftHashmarkPoint, .Top("-\(label)"))
}
if let rightHashmarkPoint = alignedPoint(bbox.maxX, y: origin.y, insideBounds:bounds) {
drawHashmarkAtLocation(rightHashmarkPoint, .Top(label))
}
if let topHashmarkPoint = alignedPoint(origin.x, y: bbox.minY, insideBounds:bounds) {
drawHashmarkAtLocation(topHashmarkPoint, .Left(label))
}
if let bottomHashmarkPoint = alignedPoint(origin.x, y: bbox.maxY, insideBounds:bounds) {
drawHashmarkAtLocation(bottomHashmarkPoint, .Left("-\(label)"))
}
bbox.insetInPlace(dx: -pointsPerHashmark, dy: -pointsPerHashmark)
}
}
}
private func drawHashmarkAtLocation(location: CGPoint, _ text: AnchoredText)
{
var dx: CGFloat = 0, dy: CGFloat = 0
switch text {
case .Left: dx = Constants.HashmarkSize / 2
case .Right: dx = Constants.HashmarkSize / 2
case .Top: dy = Constants.HashmarkSize / 2
case .Bottom: dy = Constants.HashmarkSize / 2
}
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: location.x-dx, y: location.y-dy))
path.addLineToPoint(CGPoint(x: location.x+dx, y: location.y+dy))
path.stroke()
text.drawAnchoredToPoint(location, color: color)
}
private enum AnchoredText
{
case Left(String)
case Right(String)
case Top(String)
case Bottom(String)
static let VerticalOffset: CGFloat = 3
static let HorizontalOffset: CGFloat = 6
func drawAnchoredToPoint(location: CGPoint, color: UIColor) {
let attributes = [
NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleFootnote),
NSForegroundColorAttributeName : color
]
var textRect = CGRect(center: location, size: text.sizeWithAttributes(attributes))
switch self {
case Top: textRect.origin.y += textRect.size.height / 2 + AnchoredText.VerticalOffset
case Left: textRect.origin.x += textRect.size.width / 2 + AnchoredText.HorizontalOffset
case Bottom: textRect.origin.y -= textRect.size.height / 2 + AnchoredText.VerticalOffset
case Right: textRect.origin.x -= textRect.size.width / 2 + AnchoredText.HorizontalOffset
}
text.drawInRect(textRect, withAttributes: attributes)
}
var text: String {
switch self {
case Left(let text): return text
case Right(let text): return text
case Top(let text): return text
case Bottom(let text): return text
}
}
}
// we want the axes and hashmarks to be exactly on pixel boundaries so they look sharp
// setting contentScaleFactor properly will enable us to put things on the closest pixel boundary
// if contentScaleFactor is left to its default (1), then things will be on the nearest "point" boundary instead
// the lines will still be sharp in that case, but might be a pixel (or more theoretically) off of where they should be
private func alignedPoint(x: CGFloat, y: CGFloat, insideBounds: CGRect? = nil) -> CGPoint?
{
let point = CGPoint(x: align(x), y: align(y))
if let permissibleBounds = insideBounds {
if (!CGRectContainsPoint(permissibleBounds, point)) {
return nil
}
}
return point
}
private func align(coordinate: CGFloat) -> CGFloat {
return round(coordinate * contentScaleFactor) / contentScaleFactor
}
}
extension CGRect
{
init(center: CGPoint, size: CGSize) {
self.init(x: center.x-size.width/2, y: center.y-size.height/2, width: size.width, height: size.height)
}
}
| mit |
JGiola/swift-package-manager | Sources/Workspace/InitPackage.swift | 1 | 13315 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import PackageModel
/// Create an initial template package.
public final class InitPackage {
/// The tool version to be used for new packages.
public static let newPackageToolsVersion = ToolsVersion(version: "5.0.0")
/// Represents a package type for the purposes of initialization.
public enum PackageType: String, CustomStringConvertible {
case empty = "empty"
case library = "library"
case executable = "executable"
case systemModule = "system-module"
public var description: String {
return rawValue
}
}
/// A block that will be called to report progress during package creation
public var progressReporter: ((String) -> Void)?
/// Where to create the new package
let destinationPath: AbsolutePath
/// The type of package to create.
let packageType: PackageType
/// The name of the package to create.
let pkgname: String
/// The name of the target to create.
var moduleName: String
/// The name of the type to create (within the package).
var typeName: String {
return moduleName
}
/// Create an instance that can create a package with given arguments.
public init(name: String, destinationPath: AbsolutePath, packageType: PackageType) throws {
self.packageType = packageType
self.destinationPath = destinationPath
self.pkgname = name
self.moduleName = name.spm_mangledToC99ExtendedIdentifier()
}
/// Actually creates the new package at the destinationPath
public func writePackageStructure() throws {
progressReporter?("Creating \(packageType) package: \(pkgname)")
// FIXME: We should form everything we want to write, then validate that
// none of it exists, and then act.
try writeManifestFile()
try writeREADMEFile()
try writeGitIgnore()
try writeSources()
try writeModuleMap()
try writeTests()
}
private func writePackageFile(_ path: AbsolutePath, body: (OutputByteStream) -> Void) throws {
progressReporter?("Creating \(path.relative(to: destinationPath).asString)")
try localFileSystem.writeFileContents(path, body: body)
}
private func writeManifestFile() throws {
let manifest = destinationPath.appending(component: Manifest.filename)
guard exists(manifest) == false else {
throw InitError.manifestAlreadyExists
}
try writePackageFile(manifest) { stream in
stream <<< """
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
"""
var pkgParams = [String]()
pkgParams.append("""
name: "\(pkgname)"
""")
if packageType == .library {
pkgParams.append("""
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "\(pkgname)",
targets: ["\(pkgname)"]),
]
""")
}
pkgParams.append("""
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
]
""")
if packageType == .library || packageType == .executable {
pkgParams.append("""
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "\(pkgname)",
dependencies: []),
.testTarget(
name: "\(pkgname)Tests",
dependencies: ["\(pkgname)"]),
]
""")
}
stream <<< pkgParams.joined(separator: ",\n") <<< "\n)\n"
}
// Create a tools version with current version but with patch set to zero.
// We do this to avoid adding unnecessary constraints to patch versions, if
// the package really needs it, they should add it manually.
let version = InitPackage.newPackageToolsVersion.zeroedPatch
// Write the current tools version.
try writeToolsVersion(
at: manifest.parentDirectory, version: version, fs: localFileSystem)
}
private func writeREADMEFile() throws {
let readme = destinationPath.appending(component: "README.md")
guard exists(readme) == false else {
return
}
try writePackageFile(readme) { stream in
stream <<< """
# \(pkgname)
A description of this package.
"""
}
}
private func writeGitIgnore() throws {
let gitignore = destinationPath.appending(component: ".gitignore")
guard exists(gitignore) == false else {
return
}
try writePackageFile(gitignore) { stream in
stream <<< """
.DS_Store
/.build
/Packages
/*.xcodeproj
"""
}
}
private func writeSources() throws {
if packageType == .systemModule {
return
}
let sources = destinationPath.appending(component: "Sources")
guard exists(sources) == false else {
return
}
progressReporter?("Creating \(sources.relative(to: destinationPath).asString)/")
try makeDirectories(sources)
if packageType == .empty {
return
}
let moduleDir = sources.appending(component: "\(pkgname)")
try makeDirectories(moduleDir)
let sourceFileName = (packageType == .executable) ? "main.swift" : "\(typeName).swift"
let sourceFile = moduleDir.appending(RelativePath(sourceFileName))
try writePackageFile(sourceFile) { stream in
switch packageType {
case .library:
stream <<< """
struct \(typeName) {
var text = "Hello, World!"
}
"""
case .executable:
stream <<< """
print("Hello, world!")
"""
case .systemModule, .empty:
fatalError("invalid")
}
}
}
private func writeModuleMap() throws {
if packageType != .systemModule {
return
}
let modulemap = destinationPath.appending(component: "module.modulemap")
guard exists(modulemap) == false else {
return
}
try writePackageFile(modulemap) { stream in
stream <<< """
module \(moduleName) [system] {
header "/usr/include/\(moduleName).h"
link "\(moduleName)"
export *
}
"""
}
}
private func writeTests() throws {
if packageType == .systemModule {
return
}
let tests = destinationPath.appending(component: "Tests")
guard exists(tests) == false else {
return
}
progressReporter?("Creating \(tests.relative(to: destinationPath).asString)/")
try makeDirectories(tests)
switch packageType {
case .systemModule, .empty: break
case .library, .executable:
try writeLinuxMain(testsPath: tests)
try writeTestFileStubs(testsPath: tests)
}
}
private func writeLinuxMain(testsPath: AbsolutePath) throws {
try writePackageFile(testsPath.appending(component: "LinuxMain.swift")) { stream in
stream <<< """
import XCTest
import \(moduleName)Tests
var tests = [XCTestCaseEntry]()
tests += \(moduleName)Tests.allTests()
XCTMain(tests)
"""
}
}
private func writeLibraryTestsFile(_ path: AbsolutePath) throws {
try writePackageFile(path) { stream in
stream <<< """
import XCTest
@testable import \(moduleName)
final class \(moduleName)Tests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
XCTAssertEqual(\(typeName)().text, "Hello, World!")
}
static var allTests = [
("testExample", testExample),
]
}
"""
}
}
private func writeExecutableTestsFile(_ path: AbsolutePath) throws {
try writePackageFile(path) { stream in
stream <<< """
import XCTest
import class Foundation.Bundle
final class \(moduleName)Tests: XCTestCase {
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
// Some of the APIs that we use below are available in macOS 10.13 and above.
guard #available(macOS 10.13, *) else {
return
}
let fooBinary = productsDirectory.appendingPathComponent("\(pkgname)")
let process = Process()
process.executableURL = fooBinary
let pipe = Pipe()
process.standardOutput = pipe
try process.run()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
XCTAssertEqual(output, "Hello, world!\\n")
}
/// Returns path to the built products directory.
var productsDirectory: URL {
#if os(macOS)
for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") {
return bundle.bundleURL.deletingLastPathComponent()
}
fatalError("couldn't find the products directory")
#else
return Bundle.main.bundleURL
#endif
}
static var allTests = [
("testExample", testExample),
]
}
"""
}
}
private func writeTestFileStubs(testsPath: AbsolutePath) throws {
let testModule = testsPath.appending(RelativePath(pkgname + Target.testModuleNameSuffix))
progressReporter?("Creating \(testModule.relative(to: destinationPath).asString)/")
try makeDirectories(testModule)
let testClassFile = testModule.appending(RelativePath("\(moduleName)Tests.swift"))
switch packageType {
case .systemModule, .empty: break
case .library:
try writeLibraryTestsFile(testClassFile)
case .executable:
try writeExecutableTestsFile(testClassFile)
}
try writePackageFile(testModule.appending(component: "XCTestManifests.swift")) { stream in
stream <<< """
import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(\(moduleName)Tests.allTests),
]
}
#endif
"""
}
}
}
// Private helpers
private enum InitError: Swift.Error {
case manifestAlreadyExists
}
extension InitError: CustomStringConvertible {
var description: String {
switch self {
case .manifestAlreadyExists:
return "a manifest file already exists in this directory"
}
}
}
| apache-2.0 |
mownier/photostream | Photostream/Modules/Photo Capture/Presenter/PhotoCapturePresenterInterface.swift | 1 | 516 | //
// PhotoCapturePresenterInterface.swift
// Photostream
//
// Created by Mounir Ybanez on 10/11/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import GPUImage
protocol PhotoCapturePresenterInterface: class {
var view: PhotoCaptureViewInterface! { set get }
var wireframe: PhotoCaptureWireframeInterface! { set get }
var moduleDelegate: PhotoCaptureModuleDelegate? { set get }
var camera: GPUImageStillCamera? { set get }
var filter: GPUImageFilter? { set get }
}
| mit |
Donny8028/Swift-Animation | TabBarSwitch/TabBarSwitch/ReadLaterViewController.swift | 1 | 1343 | //
// ReadLaterViewController.swift
// TabBarSwitch
//
// Created by 賢瑭 何 on 2016/5/29.
// Copyright © 2016年 Donny. All rights reserved.
//
import UIKit
class ReadLaterViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
imageView.transform = CGAffineTransformMakeScale(0.1, 0.1)
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: .CurveEaseOut, animations: {
self.imageView.transform = CGAffineTransformIdentity
}, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.