repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
SocialbitGmbH/SwiftAddressBook
Example/SwiftAddressBookTests/SwiftAddressBookTests.swift
1
2063
// // SwiftAddressBookTests.swift // SwiftAddressBookTests // // Created by Albert Bori on 2/23/15. // Copyright (c) 2015 socialbit. All rights reserved. // import UIKit import XCTest import SwiftAddressBook import AddressBook //**** Run the example project first, to accept address book access **** class SwiftAddressBookTests: XCTestCase { let accessError = "Address book access was not granted. Run the main application and grant access to the address book." let accessErrorNil = "Failed to get address book access denial error" 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() } //TODO: test authorization status, save, revert func testGetAllPeople() { if (swiftAddressBook == nil) { XCTAssertNotNil(swiftAddressBook, self.accessErrorNil) return } let people : Array<SwiftAddressBookPerson>? = swiftAddressBook?.allPeople XCTAssert((people?.count)! > 0, "Unable to get people from address book") } //TODO: tests badly: actually only checks that array is not empty, instead of if linked contacts contained func testGetAllPeopleExcludingLinkedContacts() { if (swiftAddressBook == nil) { XCTAssertNotNil(swiftAddressBook, self.accessErrorNil) return } let people : Array<SwiftAddressBookPerson>? = swiftAddressBook?.allPeopleExcludingLinkedContacts XCTAssert((people?.count)! > 0, "Unable to get main contacts from address book") } //MARK: - Helper funtions func getDateTimestamp() -> String { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ" return formatter.string(from: Date()) } func getDate(_ year: Int,_ month: Int,_ day: Int) -> Date { var components = DateComponents() components.year = year components.month = month components.day = day return Calendar.current.date(from: components)! } }
apache-2.0
764f927b8a315028862cdb29505a5f57
27.652778
120
0.735337
3.914611
false
true
false
false
notbenoit/tvOS-Twitch
Code/Common/Helpers/UIView+MotionEffect.swift
1
1936
// Copyright (c) 2015 Benoit Layer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit extension UIView { func applyMotionEffectForX(_ x: Float, y: Float) { let x = abs(x) let y = abs(y) let effectX = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis) effectX.minimumRelativeValue = NSNumber(value: -x as Float) effectX.maximumRelativeValue = NSNumber(value: x as Float) let effectY = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis) effectY.minimumRelativeValue = NSNumber(value: -y as Float) effectY.maximumRelativeValue = NSNumber(value: y as Float) let effectGroup = UIMotionEffectGroup() effectGroup.motionEffects = [effectX, effectY] self.addMotionEffect(effectGroup) } func removeMotionEffects() { guard let effect = self.motionEffects.first else { return } self.removeMotionEffect(effect) } }
bsd-3-clause
796b357934a58d639cc6dd63c019e71c
43
96
0.761364
4.181425
false
false
false
false
mspasov/KeychainAccess
Lib/KeychainAccessTests/KeychainAccessTests.swift
1
47677
// // KeychainAccessTests.swift // KeychainAccessTests // // Created by kishikawa katsumi on 2014/12/24. // Copyright (c) 2014 kishikawa katsumi. All rights reserved. // import Foundation import XCTest import KeychainAccess class KeychainAccessTests: XCTestCase { override func setUp() { super.setUp() do { try Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared").removeAll() } catch {} do { try Keychain(service: "Twitter").removeAll() } catch {} do { try Keychain(server: NSURL(string: "https://example.com")!, protocolType: .HTTPS).removeAll() } catch {} do { try Keychain().removeAll() } catch {} } override func tearDown() { super.tearDown() } // MARK: func testGenericPassword() { do { // Add Keychain items let keychain = Keychain(service: "Twitter") do { try keychain.set("kishikawa_katsumi", key: "username") } catch {} do { try keychain.set("password_1234", key: "password") } catch {} let username = try! keychain.get("username") XCTAssertEqual(username!, "kishikawa_katsumi") let password = try! keychain.get("password") XCTAssertEqual(password!, "password_1234") } do { // Update Keychain items let keychain = Keychain(service: "Twitter") do { try keychain.set("katsumi_kishikawa", key: "username") } catch {} do { try keychain.set("1234_password", key: "password") } catch {} let username = try! keychain.get("username") XCTAssertEqual(username!, "katsumi_kishikawa") let password = try! keychain.get("password") XCTAssertEqual(password!, "1234_password") } do { // Remove Keychain items let keychain = Keychain(service: "Twitter") do { try keychain.remove("username") } catch {} do { try keychain.remove("password") } catch {} XCTAssertNil(try! keychain.get("username")) XCTAssertNil(try! keychain.get("password")) } } func testGenericPasswordSubscripting() { do { // Add Keychain items let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") keychain["username"] = "kishikawa_katsumi" keychain["password"] = "password_1234" let username = keychain["username"] XCTAssertEqual(username!, "kishikawa_katsumi") let password = keychain["password"] XCTAssertEqual(password!, "password_1234") } do { // Update Keychain items let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") keychain["username"] = "katsumi_kishikawa" keychain["password"] = "1234_password" let username = keychain["username"] XCTAssertEqual(username!, "katsumi_kishikawa") let password = keychain["password"] XCTAssertEqual(password!, "1234_password") } do { // Remove Keychain items let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") keychain["username"] = nil keychain["password"] = nil XCTAssertNil(keychain["username"]) XCTAssertNil(keychain["password"]) } } // MARK: func testInternetPassword() { do { // Add Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) do { try keychain.set("kishikawa_katsumi", key: "username") } catch {} do { try keychain.set("password_1234", key: "password") } catch {} let username = try! keychain.get("username") XCTAssertEqual(username!, "kishikawa_katsumi") let password = try! keychain.get("password") XCTAssertEqual(password!, "password_1234") } do { // Update Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) do { try keychain.set("katsumi_kishikawa", key: "username") } catch {} do { try keychain.set("1234_password", key: "password") } catch {} let username = try! keychain.get("username") XCTAssertEqual(username!, "katsumi_kishikawa") let password = try! keychain.get("password") XCTAssertEqual(password!, "1234_password") } do { // Remove Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) do { try keychain.remove("username") } catch {} do { try keychain.remove("password") } catch {} XCTAssertNil(try! keychain.get("username")) XCTAssertNil(try! keychain.get("password")) } } func testInternetPasswordSubscripting() { do { // Add Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain["username"] = "kishikawa_katsumi" keychain["password"] = "password_1234" let username = keychain["username"] XCTAssertEqual(username!, "kishikawa_katsumi") let password = keychain["password"] XCTAssertEqual(password!, "password_1234") } do { // Update Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain["username"] = "katsumi_kishikawa" keychain["password"] = "1234_password" let username = keychain["username"] XCTAssertEqual(username!, "katsumi_kishikawa") let password = keychain["password"] XCTAssertEqual(password!, "1234_password") } do { // Remove Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain["username"] = nil keychain["password"] = nil XCTAssertNil(keychain["username"]) XCTAssertNil(keychain["password"]) } } // MARK: func testDefaultInitializer() { let keychain = Keychain() XCTAssertEqual(keychain.service, "") XCTAssertNil(keychain.accessGroup) } func testInitializerWithService() { let keychain = Keychain(service: "com.example.github-token") XCTAssertEqual(keychain.service, "com.example.github-token") XCTAssertNil(keychain.accessGroup) } func testInitializerWithAccessGroup() { let keychain = Keychain(accessGroup: "12ABCD3E4F.shared") XCTAssertEqual(keychain.service, "") XCTAssertEqual(keychain.accessGroup!, "12ABCD3E4F.shared") } func testInitializerWithServiceAndAccessGroup() { let keychain = Keychain(service: "com.example.github-token", accessGroup: "12ABCD3E4F.shared") XCTAssertEqual(keychain.service, "com.example.github-token") XCTAssertEqual(keychain.accessGroup!, "12ABCD3E4F.shared") } func testInitializerWithServer() { let server = "https://kishikawakatsumi.com" let URL = NSURL(string: server)! do { let keychain = Keychain(server: server, protocolType: .HTTPS) XCTAssertEqual(keychain.server, URL) XCTAssertEqual(keychain.protocolType, ProtocolType.HTTPS) XCTAssertEqual(keychain.authenticationType, AuthenticationType.Default) } do { let keychain = Keychain(server: URL, protocolType: .HTTPS) XCTAssertEqual(keychain.server, URL) XCTAssertEqual(keychain.protocolType, ProtocolType.HTTPS) XCTAssertEqual(keychain.authenticationType, AuthenticationType.Default) } } func testInitializerWithServerAndAuthenticationType() { let server = "https://kishikawakatsumi.com" let URL = NSURL(string: server)! do { let keychain = Keychain(server: server, protocolType: .HTTPS, authenticationType: .HTMLForm) XCTAssertEqual(keychain.server, URL) XCTAssertEqual(keychain.protocolType, ProtocolType.HTTPS) XCTAssertEqual(keychain.authenticationType, AuthenticationType.HTMLForm) } do { let keychain = Keychain(server: URL, protocolType: .HTTPS, authenticationType: .HTMLForm) XCTAssertEqual(keychain.server, URL) XCTAssertEqual(keychain.protocolType, ProtocolType.HTTPS) XCTAssertEqual(keychain.authenticationType, AuthenticationType.HTMLForm) } } // MARK: func testContains() { let keychain = Keychain(service: "Twitter") XCTAssertFalse(try! keychain.contains("username"), "not stored username") XCTAssertFalse(try! keychain.contains("password"), "not stored password") do { try keychain.set("kishikawakatsumi", key: "username") } catch {} XCTAssertTrue(try! keychain.contains("username"), "stored username") XCTAssertFalse(try! keychain.contains("password"), "not stored password") do { try keychain.set("password1234", key: "password") } catch {} XCTAssertTrue(try! keychain.contains("username"), "stored username") XCTAssertTrue(try! keychain.contains("password"), "stored password") } // MARK: func testSetString() { let keychain = Keychain(service: "Twitter") XCTAssertNil(try! keychain.get("username"), "not stored username") XCTAssertNil(try! keychain.get("password"), "not stored password") do { try keychain.set("kishikawakatsumi", key: "username") } catch {} XCTAssertEqual(try! keychain.get("username")!, "kishikawakatsumi", "stored username") XCTAssertNil(try! keychain.get("password"), "not stored password") do { try keychain.set("password1234", key: "password") } catch {} XCTAssertEqual(try! keychain.get("username")!, "kishikawakatsumi", "stored username") XCTAssertEqual(try! keychain.get("password")!, "password1234", "stored password") } func testSetData() { let JSONObject = ["username": "kishikawakatsumi", "password": "password1234"] let JSONData = try! NSJSONSerialization.dataWithJSONObject(JSONObject, options: []) let keychain = Keychain(service: "Twitter") XCTAssertNil(try! keychain.getData("JSONData"), "not stored JSON data") do { try keychain.set(JSONData, key: "JSONData") } catch {} XCTAssertEqual(try! keychain.getData("JSONData")!, JSONData, "stored JSON data") } func testStringConversionError() { let keychain = Keychain(service: "Twitter") let length = 256 let data = NSMutableData(length: length)! SecRandomCopyBytes(kSecRandomDefault, length, UnsafeMutablePointer<UInt8>(data.mutableBytes)) do { try keychain.set(data, key: "RandomData") let _ = try keychain.getString("RandomData") } catch let error as NSError { XCTAssertEqual(error.domain, KeychainAccessErrorDomain) XCTAssertEqual(error.code, Int(Status.ConversionError.rawValue)) } } func testRemoveString() { let keychain = Keychain(service: "Twitter") XCTAssertNil(try! keychain.get("username"), "not stored username") XCTAssertNil(try! keychain.get("password"), "not stored password") do { try keychain.set("kishikawakatsumi", key: "username") } catch {} XCTAssertEqual(try! keychain.get("username")!, "kishikawakatsumi", "stored username") do { try keychain.set("password1234", key: "password") } catch {} XCTAssertEqual(try! keychain.get("password")!, "password1234", "stored password") do { try keychain.remove("username") } catch {} XCTAssertNil(try! keychain.get("username"), "removed username") XCTAssertEqual(try! keychain.get("password")!, "password1234", "left password") do { try keychain.remove("password") } catch {} XCTAssertNil(try! keychain.get("username"), "removed username") XCTAssertNil(try! keychain.get("password"), "removed password") } func testRemoveData() { let JSONObject = ["username": "kishikawakatsumi", "password": "password1234"] let JSONData = try! NSJSONSerialization.dataWithJSONObject(JSONObject, options: []) let keychain = Keychain(service: "Twitter") XCTAssertNil(try! keychain.getData("JSONData"), "not stored JSON data") do { try keychain.set(JSONData, key: "JSONData") } catch {} XCTAssertEqual(try! keychain.getData("JSONData")!, JSONData, "stored JSON data") do { try keychain.remove("JSONData") } catch {} XCTAssertNil(try! keychain.getData("JSONData"), "removed JSON data") } // MARK: func testSubscripting() { let keychain = Keychain(service: "Twitter") XCTAssertNil(keychain["username"], "not stored username") XCTAssertNil(keychain["password"], "not stored password") XCTAssertNil(keychain[string: "username"], "not stored username") XCTAssertNil(keychain[string: "password"], "not stored password") keychain["username"] = "kishikawakatsumi" XCTAssertEqual(keychain["username"]!, "kishikawakatsumi", "stored username") XCTAssertEqual(keychain[string: "username"]!, "kishikawakatsumi", "stored username") keychain["password"] = "password1234" XCTAssertEqual(keychain["password"]!, "password1234", "stored password") XCTAssertEqual(keychain[string: "password"]!, "password1234", "stored password") keychain[string: "username"] = nil XCTAssertNil(keychain["username"], "removed username") XCTAssertEqual(keychain["password"]!, "password1234", "left password") XCTAssertNil(keychain[string: "username"], "removed username") XCTAssertEqual(keychain[string: "password"]!, "password1234", "left password") keychain[string: "password"] = nil XCTAssertNil(keychain["username"], "removed username") XCTAssertNil(keychain["password"], "removed password") XCTAssertNil(keychain[string: "username"], "removed username") XCTAssertNil(keychain[string: "password"], "removed password") let JSONObject = ["username": "kishikawakatsumi", "password": "password1234"] let JSONData = try! NSJSONSerialization.dataWithJSONObject(JSONObject, options: []) XCTAssertNil(keychain[data:"JSONData"], "not stored JSON data") keychain[data: "JSONData"] = JSONData XCTAssertEqual(keychain[data: "JSONData"]!, JSONData, "stored JSON data") keychain[data: "JSONData"] = nil XCTAssertNil(keychain[data:"JSONData"], "removed JSON data") } // MARK: #if os(iOS) func testErrorHandling() { do { let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") try keychain.removeAll() XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { let keychain = Keychain(service: "Twitter") try keychain.removeAll() XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) try keychain.removeAll() XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { let keychain = Keychain() try keychain.removeAll() XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { // Add Keychain items let keychain = Keychain(service: "Twitter") do { try keychain.set("kishikawa_katsumi", key: "username") XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { try keychain.set("password_1234", key: "password") XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { let username = try keychain.get("username") XCTAssertEqual(username, "kishikawa_katsumi") } catch { XCTFail("error occurred") } do { let password = try keychain.get("password") XCTAssertEqual(password, "password_1234") } catch { XCTFail("error occurred") } } do { // Update Keychain items let keychain = Keychain(service: "Twitter") do { try keychain.set("katsumi_kishikawa", key: "username") XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { try keychain.set("1234_password", key: "password") XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { let username = try keychain.get("username") XCTAssertEqual(username, "katsumi_kishikawa") } catch { XCTFail("error occurred") } do { let password = try keychain.get("password") XCTAssertEqual(password, "1234_password") } catch { XCTFail("error occurred") } } do { // Remove Keychain items let keychain = Keychain(service: "Twitter") do { try keychain.remove("username") XCTAssertNil(try! keychain.get("username")) } catch { XCTFail("error occurred") } do { try keychain.remove("password") XCTAssertNil(try! keychain.get("username")) } catch { XCTFail("error occurred") } } } #endif // MARK: func testSetStringWithCustomService() { let username_1 = "kishikawakatsumi" let password_1 = "password1234" let username_2 = "kishikawa_katsumi" let password_2 = "password_1234" let username_3 = "k_katsumi" let password_3 = "12341234" let service_1 = "" let service_2 = "com.kishikawakatsumi.KeychainAccess" let service_3 = "example.com" do { try Keychain().removeAll() } catch {} do { try Keychain(service: service_1).removeAll() } catch {} do { try Keychain(service: service_2).removeAll() } catch {} do { try Keychain(service: service_3).removeAll() } catch {} XCTAssertNil(try! Keychain().get("username"), "not stored username") XCTAssertNil(try! Keychain().get("password"), "not stored password") XCTAssertNil(try! Keychain(service: service_1).get("username"), "not stored username") XCTAssertNil(try! Keychain(service: service_1).get("password"), "not stored password") XCTAssertNil(try! Keychain(service: service_2).get("username"), "not stored username") XCTAssertNil(try! Keychain(service: service_2).get("password"), "not stored password") XCTAssertNil(try! Keychain(service: service_3).get("username"), "not stored username") XCTAssertNil(try! Keychain(service: service_3).get("password"), "not stored password") do { try Keychain().set(username_1, key: "username") } catch {} XCTAssertEqual(try! Keychain().get("username")!, username_1, "stored username") XCTAssertEqual(try! Keychain(service: service_1).get("username")!, username_1, "stored username") XCTAssertNil(try! Keychain(service: service_2).get("username"), "not stored username") XCTAssertNil(try! Keychain(service: service_3).get("username"), "not stored username") do { try Keychain(service: service_1).set(username_1, key: "username") } catch {} XCTAssertEqual(try! Keychain().get("username")!, username_1, "stored username") XCTAssertEqual(try! Keychain(service: service_1).get("username")!, username_1, "stored username") XCTAssertNil(try! Keychain(service: service_2).get("username"), "not stored username") XCTAssertNil(try! Keychain(service: service_3).get("username"), "not stored username") do { try Keychain(service: service_2).set(username_2, key: "username") } catch {} XCTAssertEqual(try! Keychain().get("username")!, username_1, "stored username") XCTAssertEqual(try! Keychain(service: service_1).get("username")!, username_1, "stored username") XCTAssertEqual(try! Keychain(service: service_2).get("username")!, username_2, "stored username") XCTAssertNil(try! Keychain(service: service_3).get("username"), "not stored username") do { try Keychain(service: service_3).set(username_3, key: "username") } catch {} XCTAssertEqual(try! Keychain().get("username")!, username_1, "stored username") XCTAssertEqual(try! Keychain(service: service_1).get("username")!, username_1, "stored username") XCTAssertEqual(try! Keychain(service: service_2).get("username")!, username_2, "stored username") XCTAssertEqual(try! Keychain(service: service_3).get("username")!, username_3, "stored username") do { try Keychain().set(password_1, key: "password") } catch {} XCTAssertEqual(try! Keychain().get("password")!, password_1, "stored password") XCTAssertEqual(try! Keychain(service: service_1).get("password")!, password_1, "stored password") XCTAssertNil(try! Keychain(service: service_2).get("password"), "not stored password") XCTAssertNil(try! Keychain(service: service_3).get("password"), "not stored password") do { try Keychain(service: service_1).set(password_1, key: "password") } catch {} XCTAssertEqual(try! Keychain().get("password")!, password_1, "stored password") XCTAssertEqual(try! Keychain(service: service_1).get("password")!, password_1, "stored password") XCTAssertNil(try! Keychain(service: service_2).get("password"), "not stored password") XCTAssertNil(try! Keychain(service: service_3).get("password"), "not stored password") do { try Keychain(service: service_2).set(password_2, key: "password") } catch {} XCTAssertEqual(try! Keychain().get("password")!, password_1, "stored password") XCTAssertEqual(try! Keychain(service: service_1).get("password")!, password_1, "stored password") XCTAssertEqual(try! Keychain(service: service_2).get("password")!, password_2, "stored password") XCTAssertNil(try! Keychain(service: service_3).get("password"), "not stored password") do { try Keychain(service: service_3).set(password_3, key: "password") } catch {} XCTAssertEqual(try! Keychain().get("password")!, password_1, "stored password") XCTAssertEqual(try! Keychain(service: service_1).get("password")!, password_1, "stored password") XCTAssertEqual(try! Keychain(service: service_2).get("password")!, password_2, "stored password") XCTAssertEqual(try! Keychain(service: service_3).get("password")!, password_3, "stored password") do { try Keychain().remove("username") } catch {} XCTAssertNil(try! Keychain().get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_1).get("username"), "removed username") XCTAssertEqual(try! Keychain(service: service_2).get("username")!, username_2, "left username") XCTAssertEqual(try! Keychain(service: service_3).get("username")!, username_3, "left username") do { try Keychain(service: service_1).remove("username") } catch {} XCTAssertNil(try! Keychain().get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_1).get("username"), "removed username") XCTAssertEqual(try! Keychain(service: service_2).get("username")!, username_2, "left username") XCTAssertEqual(try! Keychain(service: service_3).get("username")!, username_3, "left username") do { try Keychain(service: service_2).remove("username") } catch {} XCTAssertNil(try! Keychain().get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_1).get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_2).get("username"), "removed username") XCTAssertEqual(try! Keychain(service: service_3).get("username")!, username_3, "left username") do { try Keychain(service: service_3).remove("username") } catch {} XCTAssertNil(try! Keychain().get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_1).get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_2).get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_3).get("username"), "removed username") do { try Keychain().remove("password") } catch {} XCTAssertNil(try! Keychain().get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_1).get("password"), "removed password") XCTAssertEqual(try! Keychain(service: service_2).get("password")!, password_2, "left password") XCTAssertEqual(try! Keychain(service: service_3).get("password")!, password_3, "left password") do { try Keychain(service: service_1).remove("password") } catch {} XCTAssertNil(try! Keychain().get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_1).get("password"), "removed password") XCTAssertEqual(try! Keychain(service: service_2).get("password")!, password_2, "left password") XCTAssertEqual(try! Keychain(service: service_3).get("password")!, password_3, "left password") do { try Keychain(service: service_2).remove("password") } catch {} XCTAssertNil(try! Keychain().get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_1).get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_2).get("password"), "removed password") XCTAssertEqual(try! Keychain(service: service_3).get("password")!, password_3, "left password") do { try Keychain(service: service_3).remove("password") } catch {} XCTAssertNil(try! Keychain().get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_2).get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_2).get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_2).get("password"), "removed password") } // MARK: func testProperties() { guard #available(OSX 10.10, *) else { return } let keychain = Keychain() XCTAssertEqual(keychain.synchronizable, false) XCTAssertEqual(keychain.synchronizable(true).synchronizable, true) XCTAssertEqual(keychain.synchronizable(false).synchronizable, false) XCTAssertEqual(keychain.accessibility(.AfterFirstUnlock).accessibility, Accessibility.AfterFirstUnlock) XCTAssertEqual(keychain.accessibility(.WhenPasscodeSetThisDeviceOnly, authenticationPolicy: .UserPresence).accessibility, Accessibility.WhenPasscodeSetThisDeviceOnly) XCTAssertEqual(keychain.accessibility(.WhenPasscodeSetThisDeviceOnly, authenticationPolicy: .UserPresence).authenticationPolicy, AuthenticationPolicy.UserPresence) XCTAssertNil(keychain.label) XCTAssertEqual(keychain.label("Label").label, "Label") XCTAssertNil(keychain.comment) XCTAssertEqual(keychain.comment("Comment").comment, "Comment") XCTAssertEqual(keychain.authenticationPrompt("Prompt").authenticationPrompt, "Prompt") } // MARK: #if os(iOS) func testAllKeys() { do { let keychain = Keychain() keychain["key1"] = "value1" keychain["key2"] = "value2" keychain["key3"] = "value3" let allKeys = keychain.allKeys() XCTAssertEqual(allKeys.count, 3) XCTAssertEqual(allKeys.sort(), ["key1", "key2", "key3"]) let allItems = keychain.allItems() XCTAssertEqual(allItems.count, 3) let sortedItems = allItems.sort { (item1, item2) -> Bool in let value1 = item1["value"] as! String let value2 = item2["value"] as! String return value1.compare(value2) == NSComparisonResult.OrderedAscending || value1.compare(value2) == NSComparisonResult.OrderedSame } XCTAssertEqual(sortedItems[0]["accessGroup"] as? String, "") XCTAssertEqual(sortedItems[0]["synchronizable"] as? String, "false") XCTAssertEqual(sortedItems[0]["service"] as? String, "") XCTAssertEqual(sortedItems[0]["value"] as? String, "value1") XCTAssertEqual(sortedItems[0]["key"] as? String, "key1") XCTAssertEqual(sortedItems[0]["class"] as? String, "GenericPassword") XCTAssertEqual(sortedItems[0]["accessibility"] as? String, "AfterFirstUnlock") XCTAssertEqual(sortedItems[1]["accessGroup"] as? String, "") XCTAssertEqual(sortedItems[1]["synchronizable"] as? String, "false") XCTAssertEqual(sortedItems[1]["service"] as? String, "") XCTAssertEqual(sortedItems[1]["value"] as? String, "value2") XCTAssertEqual(sortedItems[1]["key"] as? String, "key2") XCTAssertEqual(sortedItems[1]["class"] as? String, "GenericPassword") XCTAssertEqual(sortedItems[1]["accessibility"] as? String, "AfterFirstUnlock") XCTAssertEqual(sortedItems[2]["accessGroup"] as? String, "") XCTAssertEqual(sortedItems[2]["synchronizable"] as? String, "false") XCTAssertEqual(sortedItems[2]["service"] as? String, "") XCTAssertEqual(sortedItems[2]["value"] as? String, "value3") XCTAssertEqual(sortedItems[2]["key"] as? String, "key3") XCTAssertEqual(sortedItems[2]["class"] as? String, "GenericPassword") XCTAssertEqual(sortedItems[2]["accessibility"] as? String, "AfterFirstUnlock") } do { let keychain = Keychain(service: "service1") try! keychain .synchronizable(true) .accessibility(.WhenUnlockedThisDeviceOnly) .set("service1_value1", key: "service1_key1") try! keychain .synchronizable(false) .accessibility(.AfterFirstUnlockThisDeviceOnly) .set("service1_value2", key: "service1_key2") let allKeys = keychain.allKeys() XCTAssertEqual(allKeys.count, 2) XCTAssertEqual(allKeys.sort(), ["service1_key1", "service1_key2"]) let allItems = keychain.allItems() XCTAssertEqual(allItems.count, 2) let sortedItems = allItems.sort { (item1, item2) -> Bool in let value1 = item1["value"] as! String let value2 = item2["value"] as! String return value1.compare(value2) == NSComparisonResult.OrderedAscending || value1.compare(value2) == NSComparisonResult.OrderedSame } XCTAssertEqual(sortedItems[0]["accessGroup"] as? String, "") XCTAssertEqual(sortedItems[0]["synchronizable"] as? String, "true") XCTAssertEqual(sortedItems[0]["service"] as? String, "service1") XCTAssertEqual(sortedItems[0]["value"] as? String, "service1_value1") XCTAssertEqual(sortedItems[0]["key"] as? String, "service1_key1") XCTAssertEqual(sortedItems[0]["class"] as? String, "GenericPassword") XCTAssertEqual(sortedItems[0]["accessibility"] as? String, "WhenUnlockedThisDeviceOnly") XCTAssertEqual(sortedItems[1]["accessGroup"] as? String, "") XCTAssertEqual(sortedItems[1]["synchronizable"] as? String, "false") XCTAssertEqual(sortedItems[1]["service"] as? String, "service1") XCTAssertEqual(sortedItems[1]["value"] as? String, "service1_value2") XCTAssertEqual(sortedItems[1]["key"] as? String, "service1_key2") XCTAssertEqual(sortedItems[1]["class"] as? String, "GenericPassword") XCTAssertEqual(sortedItems[1]["accessibility"] as? String, "AfterFirstUnlockThisDeviceOnly") } do { let keychain = Keychain(server: "https://google.com", protocolType: .HTTPS) try! keychain .synchronizable(false) .accessibility(.AlwaysThisDeviceOnly) .set("google.com_value1", key: "google.com_key1") try! keychain .synchronizable(true) .accessibility(.Always) .set("google.com_value2", key: "google.com_key2") let allKeys = keychain.allKeys() XCTAssertEqual(allKeys.count, 2) XCTAssertEqual(allKeys.sort(), ["google.com_key1", "google.com_key2"]) let allItems = keychain.allItems() XCTAssertEqual(allItems.count, 2) let sortedItems = allItems.sort { (item1, item2) -> Bool in let value1 = item1["value"] as! String let value2 = item2["value"] as! String return value1.compare(value2) == NSComparisonResult.OrderedAscending || value1.compare(value2) == NSComparisonResult.OrderedSame } XCTAssertEqual(sortedItems[0]["synchronizable"] as? String, "false") XCTAssertEqual(sortedItems[0]["value"] as? String, "google.com_value1") XCTAssertEqual(sortedItems[0]["key"] as? String, "google.com_key1") XCTAssertEqual(sortedItems[0]["server"] as? String, "google.com") XCTAssertEqual(sortedItems[0]["class"] as? String, "InternetPassword") XCTAssertEqual(sortedItems[0]["authenticationType"] as? String, "Default") XCTAssertEqual(sortedItems[0]["protocol"] as? String, "HTTPS") XCTAssertEqual(sortedItems[0]["accessibility"] as? String, "AlwaysThisDeviceOnly") XCTAssertEqual(sortedItems[1]["synchronizable"] as? String, "true") XCTAssertEqual(sortedItems[1]["value"] as? String, "google.com_value2") XCTAssertEqual(sortedItems[1]["key"] as? String, "google.com_key2") XCTAssertEqual(sortedItems[1]["server"] as? String, "google.com") XCTAssertEqual(sortedItems[1]["class"] as? String, "InternetPassword") XCTAssertEqual(sortedItems[1]["authenticationType"] as? String, "Default") XCTAssertEqual(sortedItems[1]["protocol"] as? String, "HTTPS") XCTAssertEqual(sortedItems[1]["accessibility"] as? String, "Always") } do { let allKeys = Keychain.allKeys(.GenericPassword) XCTAssertEqual(allKeys.count, 5) let sortedKeys = allKeys.sort { (key1, key2) -> Bool in return key1.1.compare(key2.1) == NSComparisonResult.OrderedAscending || key1.1.compare(key2.1) == NSComparisonResult.OrderedSame } XCTAssertEqual(sortedKeys[0].0, "") XCTAssertEqual(sortedKeys[0].1, "key1") XCTAssertEqual(sortedKeys[1].0, "") XCTAssertEqual(sortedKeys[1].1, "key2") XCTAssertEqual(sortedKeys[2].0, "") XCTAssertEqual(sortedKeys[2].1, "key3") XCTAssertEqual(sortedKeys[3].0, "service1") XCTAssertEqual(sortedKeys[3].1, "service1_key1") XCTAssertEqual(sortedKeys[4].0, "service1") XCTAssertEqual(sortedKeys[4].1, "service1_key2") } do { let allKeys = Keychain.allKeys(.InternetPassword) XCTAssertEqual(allKeys.count, 2) let sortedKeys = allKeys.sort { (key1, key2) -> Bool in return key1.1.compare(key2.1) == NSComparisonResult.OrderedAscending || key1.1.compare(key2.1) == NSComparisonResult.OrderedSame } XCTAssertEqual(sortedKeys[0].0, "google.com") XCTAssertEqual(sortedKeys[0].1, "google.com_key1") XCTAssertEqual(sortedKeys[1].0, "google.com") XCTAssertEqual(sortedKeys[1].1, "google.com_key2") } } func testDescription() { do { let keychain = Keychain() XCTAssertEqual(keychain.description, "[]") XCTAssertEqual(keychain.debugDescription, "[]") } } #endif // MARK: func testAuthenticationPolicy() { guard #available(iOS 9.0, OSX 10.11, *) else { return } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.UserPresence] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } #if os(iOS) do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.UserPresence, .ApplicationPassword] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.UserPresence, .ApplicationPassword, .PrivateKeyUsage] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.ApplicationPassword] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.ApplicationPassword, .PrivateKeyUsage] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.PrivateKeyUsage] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDAny] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDAny, .DevicePasscode] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDAny, .ApplicationPassword] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDAny, .ApplicationPassword, .PrivateKeyUsage] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDCurrentSet] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDCurrentSet, .DevicePasscode] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDCurrentSet, .ApplicationPassword] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDCurrentSet, .ApplicationPassword, .PrivateKeyUsage] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDAny, .Or, .DevicePasscode] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDAny, .And, .DevicePasscode] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } #endif #if os(OSX) do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.UserPresence] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.DevicePasscode] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } #endif } }
mit
0abc88de438c766c0f9f36f495cf6d69
43.683224
174
0.613357
5.21288
false
false
false
false
kickstarter/ios-oss
KsApi/models/Param.swift
1
1530
import Foundation /// Represents a way to paramterize a model by either an `id` integer or `slug` string. public enum Param { case id(Int) case slug(String) /// Returns the `id` of the param if it is of type `.id`. public var id: Int? { if case let .id(id) = self { return id } return nil } /// Returns the `slug` of the param if it is of type `.slug`. public var slug: String? { if case let .slug(slug) = self { return slug } return nil } /// Returns a value suitable for interpolating into a URL. public var urlComponent: String { switch self { case let .id(id): return String(id) case let .slug(slug): return slug } } public var escapedUrlComponent: String { switch self { case let .id(id): return String(id) case let .slug(slug): return encodeForRFC3986(slug) ?? "" } } } extension Param: Equatable {} public func == (lhs: Param, rhs: Param) -> Bool { switch (lhs, rhs) { case let (.id(lhs), .id(rhs)): return lhs == rhs case let (.slug(lhs), .slug(rhs)): return lhs == rhs case let (.id(lhs), .slug(rhs)): return String(lhs) == rhs case let (.slug(lhs), .id(rhs)): return lhs == String(rhs) } } private let allowableRFC3986: CharacterSet = { var set = CharacterSet.alphanumerics set.insert(charactersIn: "-._~/?") return set }() private func encodeForRFC3986(_ str: String) -> String? { return str.addingPercentEncoding(withAllowedCharacters: allowableRFC3986) }
apache-2.0
05e2689b03c6de5f25f565783a07ad28
22.181818
87
0.622222
3.6
false
false
false
false
mentalfaculty/impeller
Playgrounds/Brocolli.playground/Contents.swift
1
2134
//: Playground - noun: a place where people can play import Cocoa typealias UniqueIdentifier = String protocol Storable { associatedtype StoreKeys var metadata: StorageMetadata { get set } } struct StorageProperty<KeyType, ValueType> { var value: ValueType let key: KeyType init(_ key: KeyType, value: ValueType) { self.value = value self.key = key } } struct StorageMetadata { var version: UInt64 = 0 var timestamp = Date.timeIntervalSinceReferenceDate var uniqueIdentifier = UUID().uuidString } struct Person : Storable { var metadata = StorageMetadata() enum Key : String { case name case age } typealias StoreKeys = Key typealias Property<T> = StorageProperty<StoreKeys, T> let name = Property(.name, value: "Tom") let age = Property(.age, value: 64) } class Store { func saveValue<T:Storable>(value:T, resolvingConflictWith handler:((T, T) -> T)? ) { let storeValue:T = fetchValue(identifiedBy: value.metadata.uniqueIdentifier) var resolvedValue:T! if value.metadata.version == storeValue.metadata.version { // Store unchanged, so just save the new value directly resolvedValue = value } else { // Conflict. There have been saves since we fetched this value. let values = [storeValue, value] let sortedValues = values.sorted { $0.metadata.timestamp < $1.metadata.timestamp } if let handler = handler { resolvedValue = handler(sortedValues[0], sortedValues[1]) } else { resolvedValue = sortedValues[1] // Take most recent } } // Update metadata resolvedValue.metadata.timestamp = Date.timeIntervalSinceReferenceDate resolvedValue.metadata.version = storeValue.metadata.version + 1 // TODO: Save resolved value to disk } func fetchValue<T:Storable>(identifiedBy uniqueIdentifier:UniqueIdentifier) -> T { return Person() as! T } }
mit
f0ce011e72da83af0450d86dde105978
27.078947
94
0.621368
4.69011
false
false
false
false
chenyunguiMilook/VisualDebugger
Sources/VisualDebugger/proto/AxisSegment.swift
1
1217
// // AxisSegment.swift // VisualDebugger // // Created by chenyungui on 2018/3/19. // import Foundation import CoreGraphics #if os(iOS) || os(tvOS) import UIKit #else import Cocoa #endif struct AxisSegment { var start: CGPoint var end: CGPoint func getLabels(axis: CoordinateSystem.Axis, segmentValue: CGFloat, numSegments: Int, numFormater: NumberFormatter) -> [AxisLabel] { switch axis { case .x: return (0 ... numSegments).map { let value = start.x + CGFloat($0) * segmentValue let string = numFormater.formatNumber(value) let label = CATextLayer(axisLabel: string) let position = CGPoint(x: value, y: start.y) return AxisLabel(label: label, position: position) } case .y: return (0 ... numSegments).map { let value = start.y + CGFloat($0) * segmentValue let string = numFormater.formatNumber(value) let label = CATextLayer(axisLabel: string) let position = CGPoint(x: start.x, y: value) return AxisLabel(label: label, position: position) } } } }
mit
721f04424cce9ca7a32f799714c83105
29.425
135
0.576828
4.315603
false
false
false
false
TelerikAcademy/Mobile-Applications-with-iOS
demos/SuperheroesApp/SuperheroesApp/SuperheroesApp/ViewControllers/SuperheroesViewController.swift
1
3480
// // SuperheroesViewController.swift // SuperheroesApp // // Created by Doncho Minkov on 3/31/17. // Copyright © 2017 Doncho Minkov. All rights reserved. // import UIKit private let reuseIdentifier = "Superhero cell" class SuperheroesViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, SuperheroesDataDelegate { var superheroes: [Superhero] = [] var data: SuperheroesData? var loadingView: SuperheroesLoadingView? override func viewWillAppear(_ animated: Bool) { } override func viewDidLoad() { super.viewDidLoad() loadingView = SuperheroesLoadingView(frame: view.frame) view.addSubview(loadingView!) loadingView?.startLoading() data = SuperheroesData() data?.delegate = self data?.getAll() self.collectionView!.register(UINib(nibName: "SuperheroCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = collectionView.frame.width / 3.2 let height = (collectionView.frame.width > collectionView.frame.height) ? collectionView.frame.height : collectionView.frame.height / 3; return CGSize(width: width, height: height) } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return superheroes.count } var loadingCounter = 0 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SuperheroCollectionViewCell cell.textLabel.text = superheroes[indexPath.row].name let http = HttpRequester() weak var weakCell = cell loadingCounter += 1 checkShowLoading() cell.imageView.image = #imageLiteral(resourceName: "default-superhero") http.getData(fromUrl: superheroes[indexPath.row].imgUrl) { (imageData) in let image = UIImage(data: imageData) self.loadingCounter -= 1 self.checkHideLoading() DispatchQueue.main.async { weakCell?.imageView.image = image } } return cell } func checkShowLoading() { if (loadingView?.isLoading)! { return } loadingView?.startLoading() } func checkHideLoading() { if loadingCounter > 0 { return } if !(loadingView?.isLoading)! { return } loadingView?.stopLoading() } func didReceivedAll(superheroes: [Superhero]) { self.superheroes = superheroes DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(5)) { self.collectionView?.reloadData() self.loadingView?.stopLoading() } } }
mit
53c39721f4935b92ba00333fee8b1cd0
29.787611
160
0.626904
5.461538
false
false
false
false
pkx0128/UIKit
MUIStepper/MUIStepper/ViewController.swift
1
1664
// // ViewController.swift // MUIStepper // // Created by pankx on 2017/9/24. // Copyright © 2017年 pankx. All rights reserved. // import UIKit class ViewController: UIViewController { var myLabel: UILabel! var myStepper: UIStepper! override func viewDidLoad() { super.viewDidLoad() //创建myLabel myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 40)) //设置位置 myLabel.center = CGPoint(x: view.bounds.width * 0.5, y: view.bounds.height * 0.4) //设置初始值 myLabel.text = "0" //设置内容居中 myLabel.textAlignment = .center //设置字体颜色 myLabel.textColor = UIColor.red view.addSubview(myLabel) //创建myStepper myStepper = UIStepper() //设置位置 myStepper.center = view.center //设置按住自动增/减值 myStepper.autorepeat = true //设置最小值 myStepper.minimumValue = 0 //设置最大值 myStepper.maximumValue = 100 //设置改变的步长 myStepper.stepValue = 2 //设置是否加减到最大最小值后从头开始 myStepper.wraps = true //添加事件 myStepper.addTarget(self, action: #selector(addValue), for: .valueChanged) view.addSubview(myStepper) } //事件相关方法 func addValue() { myLabel.text = "\(myStepper.value)" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
3dbab6518bee2c86f8f70c75885b5d1a
23.540984
90
0.586506
4.013405
false
false
false
false
codingforentrepreneurs/30-Days-of-Swift
Simple_Final/Simple/CustomCollectionViewCell.swift
2
1228
// // CustomCollectionViewCell.swift // Simple // // Created by Justin Mitchel on 12/17/14. // Copyright (c) 2014 Coding for Entrepreneurs. All rights reserved. // import UIKit class CustomCollectionViewCell: UICollectionViewCell { var textView:UITextView! var imageView:UIImageView! required init(coder aDecoder:NSCoder) { super.init(coder: aDecoder) } override init(frame:CGRect) { super.init(frame:frame) imageView = UIImageView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height)) imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true contentView.addSubview(imageView) let tvFrame = CGRectMake(0, frame.size.height * 1/2, frame.size.width, frame.size.height * 1/3) textView = UITextView(frame: tvFrame) textView.font = UIFont.systemFontOfSize(20.0) textView.backgroundColor = UIColor(white: 1.0, alpha: 0.3) textView.textAlignment = .Center textView.scrollEnabled = false textView.userInteractionEnabled = false textView.editable = false contentView.addSubview(textView) } }
apache-2.0
421e792d1cc078aa43b9240b30376281
29.7
103
0.659609
4.514706
false
false
false
false
duycao2506/SASCoffeeIOS
Pods/DrawerController/DrawerController/DrawerBarButtonItem.swift
2
2723
// Copyright (c) 2017 evolved.io (http://evolved.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Foundation open class DrawerBarButtonItem: UIBarButtonItem { var menuButton: AnimatedMenuButton // MARK: - Initializers public override init() { self.menuButton = AnimatedMenuButton(frame: CGRect(x: 0, y: 0, width: 26, height: 26)) super.init() self.customView = self.menuButton } public convenience init(target: AnyObject?, action: Selector) { self.init(target: target, action: action, menuIconColor: UIColor.gray) } public convenience init(target: AnyObject?, action: Selector, menuIconColor: UIColor) { self.init(target: target, action: action, menuIconColor: menuIconColor, animatable: true) } public convenience init(target: AnyObject?, action: Selector, menuIconColor: UIColor, animatable: Bool) { let menuButton = AnimatedMenuButton(frame: CGRect(x: 0, y: 0, width: 26, height: 26), strokeColor: menuIconColor) menuButton.animatable = animatable menuButton.addTarget(target, action: action, for: UIControlEvents.touchUpInside) self.init(customView: menuButton) self.menuButton = menuButton } public required init?(coder aDecoder: NSCoder) { self.menuButton = AnimatedMenuButton(frame: CGRect(x: 0, y: 0, width: 26, height: 26)) super.init(coder: aDecoder) self.customView = self.menuButton } // MARK: - Animations open func animate(withFractionVisible fractionVisible: CGFloat, drawerSide: DrawerSide) { if let btn = self.customView as? AnimatedMenuButton { btn.animate(withFractionVisible: fractionVisible, drawerSide: drawerSide) } } }
gpl-3.0
7f63d51bddee6b21d9cf6a1a2efdae23
40.257576
117
0.737789
4.41329
false
false
false
false
randymarsh77/amethyst
players/iOS/Sources/AppViewModel.swift
1
3865
import AVFoundation import Foundation import Async import Bonjour import Cancellation import Crystal import Fetch import Scope import Sockets import Streams import Time import Using import WKInterop public class AppModel { public init(_ interop: WKInterop) { _interop = interop _state = State() _state.statusMessage = "Idle" _visualizer = VisualizerViewModel(interop) _player = V2AudioStreamPlayer() _ = _interop.registerEventHandler(route: "js.togglePlayPause") { self.togglePlayPause() } _ = _interop.registerEventHandler(route: "js.ready") { self.publishState() } _ = _interop.registerRequestHandler(route: "cover") { return GetCover() } let session = AVAudioSession.sharedInstance() try! session.setCategory(AVAudioSessionCategoryPlayback) try! session.setActive(true) tryConnect() } private func tryConnect() { let qSettings = QuerySettings( serviceType: .Unregistered(identifier: "_crystal-content"), serviceProtocol: .TCP, domain: .AnyDomain ) self.setStatusMessage("Searching for services...") DispatchQueue.global(qos: .default).async { let service = await (Bonjour.FindAll(qSettings)).first if (service != nil) { self.setStatusMessage("Found service, attempting to resolve host...") await (Bonjour.Resolve(service!)) let endpoint = service!.getEndpointAddress()! self.setStatusMessage("Resolved host to \(endpoint.host) on port \(endpoint.port)") let client = TCPClient(endpoint: endpoint) using ((try! client.tryConnect())!) { (socket: Socket) in using (socket.createAudioStream()) { (audio: ReadableStream<AudioData>) in self.setIsPlaying(true) socket.pong() _ = audio .pipe(to: self._player.stream) // .convert(to: kAudioFormatLinearPCM) // .pipe(to: self._visualizer.stream) await (Cancellation(self._playTokenSource!.token)) }} } else { self.setStatusMessage("No services found :(") } } } private func togglePlayPause() { DispatchQueue.main.async { NSLog("Toggling play state") if (self._state.isPlaying) { self.setIsPlaying(false) } else { self.tryConnect() } } } private func setStatusMessage(_ message: String) { DispatchQueue.main.async { NSLog("Setting status: %@", message) self._state.statusMessage = message self.publishState() } } private func setIsPlaying(_ playing: Bool) { if (self._state.isPlaying == playing) { return } _playTokenSource?.cancel() _playTokenSource = CancellationTokenSource() self._state.isPlaying = playing DispatchQueue.main.async { self.publishState() } } private func publishState() { _interop.publish(route: "swift.set.state", content: _state) } private var _interop: WKInterop private var _state: State private var _visualizer: VisualizerViewModel private var _player: V2AudioStreamPlayer private var _playTokenSource: CancellationTokenSource? } func GetCover() -> Task<String> { return async { (task: Task<String>) in let qSettings = QuerySettings( serviceType: .Unregistered(identifier: "_crystal-meta"), serviceProtocol: .TCP, domain: .AnyDomain ) var result = "" DispatchQueue.global(qos: .default).async { let service = await (Bonjour.FindAll(qSettings)).first if (service != nil) { await (Bonjour.Resolve(service!)) let endpoint = service!.getEndpointAddress()! let url = "http://\(endpoint.host):\(endpoint.port)/art" let data = await (Fetch(URL(string: url)!)) if (data != nil) { result = "data:image/png;base64,\(data!.base64EncodedString())" } } Async.Wake(task) } Async.Suspend() return result } } fileprivate func Cancellation(_ token: CancellationToken) -> Task<Void> { let task = async { Async.Suspend() } _ = try! token.register { Async.Wake(task) } return task }
mit
1cd3cf4af2f765f4476abf5b112f96c2
21.869822
87
0.687451
3.469479
false
false
false
false
superman-coder/pakr
pakr/pakr/Model/Parking/VehicleDetail.swift
1
1314
// // VehicleDetail.swift // pakr // // Created by Huynh Quang Thao on 4/11/16. // Copyright © 2016 Pakr. All rights reserved. // import Foundation class VehicleDetail: NSObject, ParseNestedObjectProtocol { let PKVehicleType = "vehicle_type" let PKVehiclePriceMin = "vehicle_price_min" let PKVehiclePriceMax = "vehicle_price_max" let PKVehicleNote = "vehicle_note" let vehicleType: VehicleType! let minPrice: String! let maxPrice: String! let note: String! init(vehicleType: VehicleType!, minPrice: String!, maxPrice: String!, note: String!) { self.vehicleType = vehicleType self.minPrice = minPrice self.maxPrice = maxPrice self.note = note } required init(dict: NSDictionary) { vehicleType = VehicleType(rawValue: dict[PKVehicleType] as! Int) minPrice = dict[PKVehiclePriceMin] as! String maxPrice = dict[PKVehiclePriceMax] as! String note = dict[PKVehicleNote] as! String } func toDictionary() -> NSDictionary { var dict: [String:AnyObject] = [:] dict[PKVehicleType] = vehicleType.rawValue dict[PKVehiclePriceMin] = minPrice dict[PKVehiclePriceMax] = maxPrice dict[PKVehicleNote] = note return dict } }
apache-2.0
8d92852f3ed8fcd9c18e7137228b4885
27.565217
90
0.646611
3.919403
false
false
false
false
hanwanjie853710069/Easy-living
易持家/Class/Vendor/IQKeyboardManagerSwift/IQKeyboardReturnKeyHandler.swift
6
17329
// // IQKeyboardReturnKeyHandler.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit /** Manages the return key to work like next/done in a view hierarchy. */ public class IQKeyboardReturnKeyHandler: NSObject , UITextFieldDelegate, UITextViewDelegate { ///--------------- /// MARK: Settings ///--------------- /** Delegate of textField/textView. */ public var delegate: protocol<UITextFieldDelegate, UITextViewDelegate>? /** Set the last textfield return key type. Default is UIReturnKeyDefault. */ public var lastTextFieldReturnKeyType : UIReturnKeyType = UIReturnKeyType.Default { didSet { for infoDict in textFieldInfoCache { if let view = infoDict.objectForKey(kIQTextField) as? UIView { updateReturnKeyTypeOnTextField(view) } } } } ///-------------------------------------- /// MARK: Initialization/Deinitialization ///-------------------------------------- public override init() { super.init() } /** Add all the textFields available in UIViewController's view. */ public init(controller : UIViewController) { super.init() addResponderFromView(controller.view) } deinit { for infoDict in textFieldInfoCache { let view : AnyObject = infoDict.objectForKey(kIQTextField)! if let textField = view as? UITextField { let returnKeyTypeValue = infoDict[kIQTextFieldReturnKeyType] as! NSNumber textField.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.integerValue)! textField.delegate = infoDict[kIQTextFieldDelegate] as! UITextFieldDelegate? } else if let textView = view as? UITextView { textView.returnKeyType = UIReturnKeyType(rawValue: (infoDict[kIQTextFieldReturnKeyType] as! NSNumber).integerValue)! let returnKeyTypeValue = infoDict[kIQTextFieldReturnKeyType] as! NSNumber textView.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.integerValue)! textView.delegate = infoDict[kIQTextFieldDelegate] as! UITextViewDelegate? } } textFieldInfoCache.removeAllObjects() } ///------------------------ /// MARK: Private variables ///------------------------ private var textFieldInfoCache = NSMutableSet() private let kIQTextField = "kIQTextField" private let kIQTextFieldDelegate = "kIQTextFieldDelegate" private let kIQTextFieldReturnKeyType = "kIQTextFieldReturnKeyType" ///------------------------ /// MARK: Private Functions ///------------------------ private func textFieldCachedInfo(textField : UIView) -> [String : AnyObject]? { for infoDict in textFieldInfoCache { if infoDict.objectForKey(kIQTextField) as! NSObject == textField { return infoDict as? [String : AnyObject] } } return nil } private func updateReturnKeyTypeOnTextField(view : UIView) { var superConsideredView : UIView? //If find any consider responderView in it's upper hierarchy then will get deepResponderView. (Bug ID: #347) for disabledClassString in IQKeyboardManager.sharedManager().toolbarPreviousNextAllowedClasses { if let disabledClass = NSClassFromString(disabledClassString) { superConsideredView = view.superviewOfClassType(disabledClass) if superConsideredView != nil { break } } } var textFields : [UIView]? //If there is a tableView in view's hierarchy, then fetching all it's subview that responds. if let unwrappedTableView = superConsideredView { // (Enhancement ID: #22) textFields = unwrappedTableView.deepResponderViews() } else { //Otherwise fetching all the siblings textFields = view.responderSiblings() //Sorting textFields according to behaviour switch IQKeyboardManager.sharedManager().toolbarManageBehaviour { //If needs to sort it by tag case .ByTag: textFields = textFields?.sortedArrayByTag() //If needs to sort it by Position case .ByPosition: textFields = textFields?.sortedArrayByPosition() default: break } } if let lastView = textFields?.last { if let textField = view as? UITextField { //If it's the last textField in responder view, else next textField.returnKeyType = (view == lastView) ? lastTextFieldReturnKeyType : UIReturnKeyType.Next } else if let textView = view as? UITextView { //If it's the last textField in responder view, else next textView.returnKeyType = (view == lastView) ? lastTextFieldReturnKeyType : UIReturnKeyType.Next } } } ///---------------------------------------------- /// MARK: Registering/Unregistering textFieldView ///---------------------------------------------- /** Should pass UITextField/UITextView intance. Assign textFieldView delegate to self, change it's returnKeyType. @param textFieldView UITextField/UITextView object to register. */ public func addTextFieldView(view : UIView) { var dictInfo : [String : AnyObject] = [String : AnyObject]() dictInfo[kIQTextField] = view if let textField = view as? UITextField { dictInfo[kIQTextFieldReturnKeyType] = textField.returnKeyType.rawValue if let textFieldDelegate = textField.delegate { dictInfo[kIQTextFieldDelegate] = textFieldDelegate } textField.delegate = self } else if let textView = view as? UITextView { dictInfo[kIQTextFieldReturnKeyType] = textView.returnKeyType.rawValue if let textViewDelegate = textView.delegate { dictInfo[kIQTextFieldDelegate] = textViewDelegate } textView.delegate = self } textFieldInfoCache.addObject(dictInfo) } /** Should pass UITextField/UITextView intance. Restore it's textFieldView delegate and it's returnKeyType. @param textFieldView UITextField/UITextView object to unregister. */ public func removeTextFieldView(view : UIView) { if let dict : [String : AnyObject] = textFieldCachedInfo(view) { if let textField = view as? UITextField { let returnKeyTypeValue = dict[kIQTextFieldReturnKeyType] as! NSNumber textField.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.integerValue)! textField.delegate = dict[kIQTextFieldDelegate] as! UITextFieldDelegate? } else if let textView = view as? UITextView { let returnKeyTypeValue = dict[kIQTextFieldReturnKeyType] as! NSNumber textView.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.integerValue)! textView.delegate = dict[kIQTextFieldDelegate] as! UITextViewDelegate? } textFieldInfoCache.removeObject(dict) } } /** Add all the UITextField/UITextView responderView's. @param UIView object to register all it's responder subviews. */ public func addResponderFromView(view : UIView) { let textFields = view.deepResponderViews() for textField in textFields { addTextFieldView(textField) } } /** Remove all the UITextField/UITextView responderView's. @param UIView object to unregister all it's responder subviews. */ public func removeResponderFromView(view : UIView) { let textFields = view.deepResponderViews() for textField in textFields { removeTextFieldView(textField) } } private func goToNextResponderOrResign(view : UIView) { var superConsideredView : UIView? //If find any consider responderView in it's upper hierarchy then will get deepResponderView. (Bug ID: #347) for disabledClassString in IQKeyboardManager.sharedManager().toolbarPreviousNextAllowedClasses { if let disabledClass = NSClassFromString(disabledClassString) { superConsideredView = view.superviewOfClassType(disabledClass) if superConsideredView != nil { break } } } var textFields : [UIView]? //If there is a tableView in view's hierarchy, then fetching all it's subview that responds. if let unwrappedTableView = superConsideredView { // (Enhancement ID: #22) textFields = unwrappedTableView.deepResponderViews() } else { //Otherwise fetching all the siblings textFields = view.responderSiblings() //Sorting textFields according to behaviour switch IQKeyboardManager.sharedManager().toolbarManageBehaviour { //If needs to sort it by tag case .ByTag: textFields = textFields?.sortedArrayByTag() //If needs to sort it by Position case .ByPosition: textFields = textFields?.sortedArrayByPosition() default: break } } if let unwrappedTextFields = textFields { //Getting index of current textField. if let index = unwrappedTextFields.indexOf(view) { //If it is not last textField. then it's next object becomeFirstResponder. if index < (unwrappedTextFields.count - 1) { let nextTextField = unwrappedTextFields[index+1] nextTextField.becomeFirstResponder() } else { view.resignFirstResponder() } } } } ///---------------------------------------------- /// MARK: UITextField/UITextView delegates ///---------------------------------------------- public func textFieldShouldBeginEditing(textField: UITextField) -> Bool { if delegate?.respondsToSelector(#selector(UITextFieldDelegate.textFieldShouldBeginEditing(_:))) != nil { return (delegate?.textFieldShouldBeginEditing?(textField) == true) } else { return true } } public func textFieldShouldEndEditing(textField: UITextField) -> Bool { if delegate?.respondsToSelector(#selector(UITextFieldDelegate.textFieldShouldEndEditing(_:))) != nil { return (delegate?.textFieldShouldEndEditing?(textField) == true) } else { return true } } public func textFieldDidBeginEditing(textField: UITextField) { updateReturnKeyTypeOnTextField(textField) delegate?.textFieldShouldBeginEditing?(textField) } public func textFieldDidEndEditing(textField: UITextField) { delegate?.textFieldDidEndEditing?(textField) } public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if delegate?.respondsToSelector(#selector(UITextFieldDelegate.textField(_:shouldChangeCharactersInRange:replacementString:))) != nil { return (delegate?.textField?(textField, shouldChangeCharactersInRange: range, replacementString: string) == true) } else { return true } } public func textFieldShouldClear(textField: UITextField) -> Bool { if delegate?.respondsToSelector(#selector(UITextFieldDelegate.textFieldShouldClear(_:))) != nil { return (delegate?.textFieldShouldClear?(textField) == true) } else { return true } } public func textFieldShouldReturn(textField: UITextField) -> Bool { var shouldReturn = true if delegate?.respondsToSelector(#selector(UITextFieldDelegate.textFieldShouldReturn(_:))) != nil { shouldReturn = (delegate?.textFieldShouldReturn?(textField) == true) } if shouldReturn == true { goToNextResponderOrResign(textField) } return shouldReturn } public func textViewShouldBeginEditing(textView: UITextView) -> Bool { if delegate?.respondsToSelector(#selector(UITextViewDelegate.textViewShouldBeginEditing(_:))) != nil { return (delegate?.textViewShouldBeginEditing?(textView) == true) } else { return true } } public func textViewShouldEndEditing(textView: UITextView) -> Bool { if delegate?.respondsToSelector(#selector(UITextViewDelegate.textViewShouldEndEditing(_:))) != nil { return (delegate?.textViewShouldEndEditing?(textView) == true) } else { return true } } public func textViewDidBeginEditing(textView: UITextView) { updateReturnKeyTypeOnTextField(textView) delegate?.textViewDidBeginEditing?(textView) } public func textViewDidEndEditing(textView: UITextView) { delegate?.textViewDidEndEditing?(textView) } public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { var shouldReturn = true if delegate?.respondsToSelector(#selector(UITextViewDelegate.textView(_:shouldChangeTextInRange:replacementText:))) != nil { shouldReturn = ((delegate?.textView?(textView, shouldChangeTextInRange: range, replacementText: text)) == true) } if shouldReturn == true && text == "\n" { goToNextResponderOrResign(textView) } return shouldReturn } public func textViewDidChange(textView: UITextView) { delegate?.textViewDidChange?(textView) } public func textViewDidChangeSelection(textView: UITextView) { delegate?.textViewDidChangeSelection?(textView) } public func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { if delegate?.respondsToSelector(#selector(UITextViewDelegate.textView(_:shouldInteractWithURL:inRange:))) != nil { return ((delegate?.textView?(textView, shouldInteractWithURL: URL, inRange: characterRange)) == true) } else { return true } } public func textView(textView: UITextView, shouldInteractWithTextAttachment textAttachment: NSTextAttachment, inRange characterRange: NSRange) -> Bool { if delegate?.respondsToSelector(#selector(UITextViewDelegate.textView(_:shouldInteractWithTextAttachment:inRange:))) != nil { return ((delegate?.textView?(textView, shouldInteractWithTextAttachment: textAttachment, inRange: characterRange)) == true) } else { return true } } }
apache-2.0
646f98d38af9571f64c9184d84fcfbc9
36.027778
156
0.596341
6.461223
false
false
false
false
arciem/Lores
LoresPlay/LoresPlay/Programs/Example Programs/006-BallProgram.swift
1
1870
import Lores import WolfCore typealias Point = Lores.Point class BallProgram : Program { var balls = [Ball]() override func setup() { framesPerSecond = 30 for _ in 1...20 { let dx = Random.randomBoolean() ? 1 : -1 let dy = Random.randomBoolean() ? 1 : -1 let ball = BallProgram.Ball(location: canvas.randomPoint(), direction: Offset(dx: dx, dy: dy), color: Color.randomColor()) balls.append(ball) } } override func update() { for ball in balls { ball.update(canvas) } } override func draw() { for ball in balls { ball.draw(canvas) } } class Ball { var location: Point var direction: Offset let color: Color init(location: Point, direction: Offset, color: Color) { self.location = location self.direction = direction self.color = color } func update(canvas: Canvas) { var newDX = direction.dx var newDY = direction.dy if location.y + newDY > canvas.maxY { newDY = -1 } if location.y + newDY < canvas.minY { newDY = 1 } if location.x + newDX > canvas.maxX { newDX = -1 } if location.x + newDX < canvas.minX { newDX = 1 } let newX = location.x + newDX let newY = location.y + newDY location = Point(x: newX, y: newY) direction = Offset(dx: newDX, dy: newDY) } func draw(canvas: Canvas) { canvas[location] = color } } }
apache-2.0
d1af6ccf5d58ffa8d6f4d0bba9a36d16
23.933333
134
0.45508
4.605911
false
false
false
false
andrebocchini/SwiftChatty
Pods/Freddy/Sources/JSONDecodable.swift
1
7804
// // JSONDecodable.swift // Freddy // // Created by Matthew D. Mathias on 3/24/15. // Copyright © 2015 Big Nerd Ranch. Licensed under MIT. // /// A protocol to provide functionality for creating a model object with a `JSON` /// value. public protocol JSONDecodable { /// Creates an instance of the model with a `JSON` instance. /// - parameter json: An instance of a `JSON` value from which to /// construct an instance of the implementing type. /// - throws: Any `JSON.Error` for errors derived from inspecting the /// `JSON` value, or any other error involved in decoding. init(json: JSON) throws } extension Double: JSONDecodable { /// An initializer to create an instance of `Double` from a `JSON` value. /// - parameter json: An instance of `JSON`. /// - throws: The initializer will throw an instance of `JSON.Error` if /// an instance of `Double` cannot be created from the `JSON` value that was /// passed to this initializer. public init(json: JSON) throws { if case let .double(double) = json { self = double } else if case let .int(int) = json { self = Double(int) } else if case let .string(string) = json, let s = Double(string) { self = s } else { throw JSON.Error.valueNotConvertible(value: json, to: Double.self) } } } extension Int: JSONDecodable { /// An initializer to create an instance of `Int` from a `JSON` value. /// - parameter json: An instance of `JSON`. /// - throws: The initializer will throw an instance of `JSON.Error` if /// an instance of `Int` cannot be created from the `JSON` value that was /// passed to this initializer. public init(json: JSON) throws { if case let .double(double) = json, double <= Double(Int.max) { self = Int(double) } else if case let .int(int) = json { self = int } else if case let .string(string) = json, let int = Int(string) { self = int } else if case let .string(string) = json, let double = Double(string), let decimalSeparator = string.characters.index(of: "."), let int = Int(String(string.characters.prefix(upTo: decimalSeparator))), double == Double(int) { self = int } else { throw JSON.Error.valueNotConvertible(value: json, to: Int.self) } } } extension String: JSONDecodable { /// An initializer to create an instance of `String` from a `JSON` value. /// - parameter json: An instance of `JSON`. /// - throws: The initializer will throw an instance of `JSON.Error` if /// an instance of `String` cannot be created from the `JSON` value that was /// passed to this initializer. public init(json: JSON) throws { switch json { case let .string(string): self = string case let .int(int): self = String(int) case let .bool(bool): self = String(bool) case let .double(double): self = String(double) default: throw JSON.Error.valueNotConvertible(value: json, to: String.self) } } } extension Bool: JSONDecodable { /// An initializer to create an instance of `Bool` from a `JSON` value. /// - parameter json: An instance of `JSON`. /// - throws: The initializer will throw an instance of `JSON.Error` if /// an instance of `Bool` cannot be created from the `JSON` value that was /// passed to this initializer. public init(json: JSON) throws { guard case let .bool(bool) = json else { throw JSON.Error.valueNotConvertible(value: json, to: Bool.self) } self = bool } } extension RawRepresentable where RawValue: JSONDecodable { /// An initializer to create an instance of `RawRepresentable` from a `JSON` value. /// - parameter json: An instance of `JSON`. /// - throws: The initializer will throw an instance of `JSON.Error` if /// an instance of `RawRepresentable` cannot be created from the `JSON` value that was /// passed to this initializer. public init(json: JSON) throws { let raw = try json.decode(type: RawValue.self) guard let value = Self(rawValue: raw) else { throw JSON.Error.valueNotConvertible(value: json, to: Self.self) } self = value } } internal extension JSON { /// Retrieves a `[JSON]` from the JSON. /// - parameter: A `JSON` to be used to create the returned `Array`. /// - returns: An `Array` of `JSON` elements /// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`. /// - seealso: `JSON.decode(_:type:)` static func getArray(from json: JSON) throws -> [JSON] { // Ideally should be expressed as a conditional protocol implementation on Swift.Array. guard case let .array(array) = json else { throw Error.valueNotConvertible(value: json, to: Swift.Array<JSON>.self) } return array } /// Retrieves a `[String: JSON]` from the JSON. /// - parameter: A `JSON` to be used to create the returned `Dictionary`. /// - returns: An `Dictionary` of `String` mapping to `JSON` elements /// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`. /// - seealso: `JSON.decode(_:type:)` static func getDictionary(from json: JSON) throws -> [String: JSON] { // Ideally should be expressed as a conditional protocol implementation on Swift.Dictionary. guard case let .dictionary(dictionary) = json else { throw Error.valueNotConvertible(value: json, to: Swift.Dictionary<String, JSON>.self) } return dictionary } /// Attempts to decode many values from a descendant JSON array at a path /// into JSON. /// - parameter json: A `JSON` to be used to create the returned `Array` of some type conforming to `JSONDecodable`. /// - returns: An `Array` of `Decoded` elements. /// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`, as /// well as any error that arises from decoding the contained values. /// - seealso: `JSON.decode(_:type:)` static func decodedArray<Decoded: JSONDecodable>(from json: JSON) throws -> [Decoded] { // Ideally should be expressed as a conditional protocol implementation on Swift.Dictionary. // This implementation also doesn't do the `type = Type.self` trick. return try getArray(from: json).map(Decoded.init) } /// Attempts to decode many values from a descendant JSON object at a path /// into JSON. /// - parameter json: A `JSON` to be used to create the returned `Dictionary` of some type conforming to `JSONDecodable`. /// - returns: A `Dictionary` of string keys and `Decoded` values. /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)` or /// any error that arises from decoding the contained values. /// - seealso: `JSON.decode(_:type:)` static func decodedDictionary<Decoded: JSONDecodable>(from json: JSON) throws -> [Swift.String: Decoded] { guard case let .dictionary(dictionary) = json else { throw Error.valueNotConvertible(value: json, to: Swift.Dictionary<String, Decoded>.self) } var decodedDictionary = Swift.Dictionary<String, Decoded>(minimumCapacity: dictionary.count) for (key, value) in dictionary { decodedDictionary[key] = try Decoded(json: value) } return decodedDictionary } }
mit
b21bd432f4608f7a1ecc96f6a22e7c9c
40.951613
125
0.614507
4.270936
false
false
false
false
makma/cloud-sdk-swift
KenticoCloud/Classes/DeliveryService/Models/ElementTypes/RichTextBlocks/Block.swift
1
564
// // Block.swift // Pods // // Created by Martin Makarsky on 05/09/2017. // // import Kanna /// Protocol for RichText's blocks. public protocol Block { } extension Block { func isKenticoCloudApplicationType(tag: String) -> Bool { let typeXpath = "//@type" if let tagDoc = try? HTML(html: tag, encoding: .utf8) { let type = tagDoc.xpath(typeXpath).first?.content if type == "application/kenticocloud" { return true } } return false } }
mit
41668f1856c33111dc488becfc97cefa
16.625
63
0.54078
3.785235
false
false
false
false
mihyaeru21/RxTwift
Pod/Classes/Api.swift
1
1527
// // Api.swift // Pods // // Created by Mihyaeru on 2/28/16. // // import Foundation import RxSwift public class Api { private let client: Client public lazy var get: GetApi = GetApi(client: self.client) public lazy var post: PostApi = PostApi(client: self.client) public init( consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String, random: RandomProtocol = Random(), timestamp: TimestampProtocol = Timestamp() ) { let oauth = OAuth( consumerKey: consumerKey, consumerSecret: consumerSecret, accessToken: accessToken, accessTokenSecret: accessTokenSecret, random: random, timestamp: timestamp ) self.client = Client(oauth: oauth) } } public class GetApi { internal let client: Client private init(client: Client) { self.client = client } public lazy var statuses: GetStatusesApi = GetStatusesApi(client: self.client) public lazy var lists: GetListsApi = GetListsApi(client: self.client) } public class PostApi { internal let client: Client private init(client: Client) { self.client = client } public lazy var statuses: PostStatusesApi = PostStatusesApi(client: self.client) public lazy var lists: PostListsApi = PostListsApi(client: self.client) }
mit
0212c6f5d9856d89b2b5d83d0faedb34
26.267857
84
0.602489
4.464912
false
false
false
false
segmentio/analytics-swift
Examples/destination_plugins/AdjustDestination.swift
1
6827
// // AdjustDestination.swift // DestinationsExample // // Created by Brandon Sneed on 5/27/21. // // NOTE: You can see this plugin in use in the DestinationsExample application. // // This plugin is NOT SUPPORTED by Segment. It is here merely as an example, // and for your convenience should you find it useful. // // Adjust SPM package can be found here: https://github.com/adjust/ios_sdk // MIT License // // Copyright (c) 2021 Segment // // 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 Segment import Adjust @objc class AdjustDestination: NSObject, DestinationPlugin, RemoteNotifications { let timeline = Timeline() let type = PluginType.destination let key = "Adjust" weak var analytics: Analytics? = nil private var settings: AdjustSettings? = nil public func update(settings: Settings, type: UpdateType) { // we've already set up this singleton SDK, can't do it again, so skip. guard type == .initial else { return } guard let settings: AdjustSettings = settings.integrationSettings(forPlugin: self) else { return } self.settings = settings var environment = ADJEnvironmentSandbox if let _ = settings.setEnvironmentProduction { environment = ADJEnvironmentProduction } let adjustConfig = ADJConfig(appToken: settings.appToken, environment: environment) if let bufferingEnabled = settings.setEventBufferingEnabled { adjustConfig?.eventBufferingEnabled = bufferingEnabled } if let _ = settings.trackAttributionData { adjustConfig?.delegate = self } if let useDelay = settings.setDelay, useDelay == true, let delayTime = settings.delayTime { adjustConfig?.delayStart = delayTime } Adjust.appDidLaunch(adjustConfig) } public func identify(event: IdentifyEvent) -> IdentifyEvent? { if let userId = event.userId, userId.count > 0 { Adjust.addSessionPartnerParameter("user_id", value: userId) } if let anonId = event.anonymousId, anonId.count > 0 { Adjust.addSessionPartnerParameter("anonymous_id", value: anonId) } return event } public func track(event: TrackEvent) -> TrackEvent? { if let anonId = event.anonymousId, anonId.count > 0 { Adjust.addSessionPartnerParameter("anonymous_id", value: anonId) } if let token = mappedCustomEventToken(eventName: event.event) { let adjEvent = ADJEvent(eventToken: token) let properties = event.properties?.dictionaryValue if let properties = properties { for (key, value) in properties { adjEvent?.addCallbackParameter(key, value: "\(value)") } } let revenue: Double? = extract(key: "revenue", from: properties) let currency: String? = extract(key: "currency", from: properties, withDefault: "USD") let orderId: String? = extract(key: "orderId", from: properties) if let revenue = revenue, let currency = currency { adjEvent?.setRevenue(revenue, currency: currency) } if let orderId = orderId { adjEvent?.setTransactionId(orderId) } } return event } public func reset() { Adjust.resetSessionPartnerParameters() } public func registeredForRemoteNotifications(deviceToken: Data) { Adjust.setDeviceToken(deviceToken) } } // MARK: - Adjust Delegate conformance extension AdjustDestination: AdjustDelegate { public func adjustAttributionChanged(_ attribution: ADJAttribution?) { let campaign: [String: Any] = [ "source": attribution?.network ?? NSNull(), "name": attribution?.campaign ?? NSNull(), "content": attribution?.clickLabel ?? NSNull(), "adCreative": attribution?.creative ?? NSNull(), "adGroup": attribution?.adgroup ?? NSNull() ] let properties: [String: Any] = [ "provider": "Adjust", "trackerToken": attribution?.trackerToken ?? NSNull(), "trackerName": attribution?.trackerName ?? NSNull(), "campaign": campaign ] analytics?.track(name: "Install Attributed", properties: properties) } } // MARK: - Support methods extension AdjustDestination { internal func mappedCustomEventToken(eventName: String) -> String? { var result: String? = nil if let tokens = settings?.customEvents?.dictionaryValue { result = tokens[eventName] as? String } return result } internal func extract<T>(key: String, from properties: [String: Any]?, withDefault value: T? = nil) -> T? { var result: T? = value guard let properties = properties else { return result } for (propKey, propValue) in properties { // not sure if this comparison is actually necessary, // but existed in the old destination so ... if key.lowercased() == propKey.lowercased() { if let value = propValue as? T { result = value break } } } return result } } private struct AdjustSettings: Codable { let appToken: String let setEnvironmentProduction: Bool? let setEventBufferingEnabled: Bool? let trackAttributionData: Bool? let setDelay: Bool? let customEvents: JSON? let delayTime: Double? }
mit
f585e6e6123ca0b7f0bf11265482d332
35.508021
111
0.629413
4.879914
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Nodes/Effects/Filters/High Pass Butterworth Filter/AKHighPassButterworthFilter.swift
1
3851
// // AKHighPassButterworthFilter.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// These filters are Butterworth second-order IIR filters. They offer an almost /// flat passband and very good precision and stopband attenuation. /// /// - Parameters: /// - input: Input node to process /// - cutoffFrequency: Cutoff frequency. (in Hertz) /// public class AKHighPassButterworthFilter: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKHighPassButterworthFilterAudioUnit? internal var token: AUParameterObserverToken? private var cutoffFrequencyParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Cutoff frequency. (in Hertz) public var cutoffFrequency: Double = 500.0 { willSet { if cutoffFrequency != newValue { if internalAU!.isSetUp() { cutoffFrequencyParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.cutoffFrequency = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this filter node /// /// - Parameters: /// - input: Input node to process /// - cutoffFrequency: Cutoff frequency. (in Hertz) /// public init( _ input: AKNode, cutoffFrequency: Double = 500.0) { self.cutoffFrequency = cutoffFrequency var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = fourCC("bthp") description.componentManufacturer = fourCC("AuKt") description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKHighPassButterworthFilterAudioUnit.self, asComponentDescription: description, name: "Local AKHighPassButterworthFilter", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKHighPassButterworthFilterAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } cutoffFrequencyParameter = tree.valueForKey("cutoffFrequency") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.cutoffFrequencyParameter!.address { self.cutoffFrequency = Double(value) } } } internalAU?.cutoffFrequency = Float(cutoffFrequency) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
5afe9ba61358ebb11c1f483d8dfd1c41
30.308943
100
0.627629
5.509299
false
false
false
false
ashfurrow/RxSwift
RxExample/RxExample/Examples/WikipediaImageSearch/WikipediaAPI/WikipediaSearchResult.swift
2
1811
// // WikipediaSearchResult.swift // Example // // Created by Krunoslav Zaher on 3/28/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif struct WikipediaSearchResult: CustomDebugStringConvertible { let title: String let description: String let URL: NSURL init(title: String, description: String, URL: NSURL) { self.title = title self.description = description self.URL = URL } // tedious parsing part static func parseJSON(json: [AnyObject]) throws -> [WikipediaSearchResult] { let rootArrayTyped = json.map { $0 as? [AnyObject] } .filter { $0 != nil } .map { $0! } if rootArrayTyped.count != 3 { throw WikipediaParseError } let titleAndDescription = Array(Swift.zip(rootArrayTyped[0], rootArrayTyped[1])) let titleDescriptionAndUrl: [((AnyObject, AnyObject), AnyObject)] = Array(Swift.zip(titleAndDescription, rootArrayTyped[2])) let searchResults: [WikipediaSearchResult] = try titleDescriptionAndUrl.map ( { result -> WikipediaSearchResult in let (first, url) = result let (title, description) = first guard let titleString = title as? String, let descriptionString = description as? String, let urlString = url as? String, let URL = NSURL(string: urlString) else { throw WikipediaParseError } return WikipediaSearchResult(title: titleString, description: descriptionString, URL: URL) }) return searchResults } } extension WikipediaSearchResult { var debugDescription: String { return "[\(title)](\(URL))" } }
mit
3729961e88330c3768decabac7b1bf3c
29.2
132
0.623412
4.716146
false
false
false
false
Cessation/even.tr
Pods/ALCameraViewController/ALCameraViewController/Utilities/SingleImageFetcher.swift
3
2847
// // SingleImageFetcher.swift // ALCameraViewController // // Created by Alex Littlejohn on 2016/02/16. // Copyright © 2016 zero. All rights reserved. // import UIKit import Photos public typealias SingleImageFetcherSuccess = (image: UIImage) -> Void public typealias SingleImageFetcherFailure = (error: NSError) -> Void public class SingleImageFetcher { private let errorDomain = "com.zero.singleImageSaver" private var success: SingleImageFetcherSuccess? private var failure: SingleImageFetcherFailure? private var asset: PHAsset? private var targetSize = PHImageManagerMaximumSize private var cropRect: CGRect? public init() { } public func onSuccess(success: SingleImageFetcherSuccess) -> Self { self.success = success return self } public func onFailure(failure: SingleImageFetcherFailure) -> Self { self.failure = failure return self } public func setAsset(asset: PHAsset) -> Self { self.asset = asset return self } public func setTargetSize(targetSize: CGSize) -> Self { self.targetSize = targetSize return self } public func setCropRect(cropRect: CGRect) -> Self { self.cropRect = cropRect return self } public func fetch() -> Self { _ = PhotoLibraryAuthorizer { error in if error == nil { self._fetch() } else { self.failure?(error: error!) } } return self } private func _fetch() { guard let asset = asset else { let error = errorWithKey("error.cant-fetch-photo", domain: errorDomain) failure?(error: error) return } let options = PHImageRequestOptions() options.deliveryMode = .HighQualityFormat options.networkAccessAllowed = true if let cropRect = cropRect { options.normalizedCropRect = cropRect options.resizeMode = .Exact let targetWidth = floor(CGFloat(asset.pixelWidth) * cropRect.width) let targetHeight = floor(CGFloat(asset.pixelHeight) * cropRect.height) let dimension = max(min(targetHeight, targetWidth), 1024 * scale) targetSize = CGSize(width: dimension, height: dimension) } PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: options) { image, _ in if let image = image { self.success?(image: image) } else { let error = errorWithKey("error.cant-fetch-photo", domain: self.errorDomain) self.failure?(error: error) } } } }
apache-2.0
e24493ea025615ace6ebda270b346414
28.645833
149
0.600843
5.064057
false
false
false
false
AmitaiB/TouchVisualizer
Pod/Classes/UIWindow+Swizzle.swift
1
1255
// // UIWindow+Swizzle.swift // TouchVisualizer // import UIKit extension UIWindow { public var swizzlingMessage: String { return "Method Swizzlings: sendEvent: and description" } public func swizzle() { var range = self.description.rangeOfString(swizzlingMessage, options: .LiteralSearch, range: nil, locale: nil) if (range?.startIndex != nil) { return } var sendEvent = class_getInstanceMethod(object_getClass(self), "sendEvent:") var swizzledSendEvent = class_getInstanceMethod(object_getClass(self), "swizzledSendEvent:") method_exchangeImplementations(sendEvent, swizzledSendEvent) var description: Method = class_getInstanceMethod(object_getClass(self), "description") var swizzledDescription: Method = class_getInstanceMethod(object_getClass(self), "swizzledDescription") method_exchangeImplementations(description, swizzledDescription) } public func swizzledSendEvent(event: UIEvent) { Visualizer.sharedInstance.handleEvent(event) swizzledSendEvent(event) } public func swizzledDescription() -> String { return swizzledDescription() + "; " + swizzlingMessage } }
mit
92d14a4cbd4fbc95feefde1936b7beed
33.888889
118
0.683665
5.143443
false
false
false
false
legendecas/Rocket.Chat.iOS
Rocket.Chat.Shared/Managers/Socket/SocketManager.swift
1
7726
// // SocketManager.swift // Rocket.Chat // // Created by Rafael K. Streit on 7/6/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import UIKit import Starscream import SwiftyJSON import RealmSwift public typealias RequestCompletion = (JSON?, Bool) -> Void public typealias VoidCompletion = () -> Void public typealias MessageCompletion = (SocketResponse) -> Void public typealias SocketCompletion = (WebSocket?, Bool) -> Void public typealias MessageCompletionObject <T: Object> = (T?) -> Void public typealias MessageCompletionObjectsList <T: Object> = ([T]) -> Void /// A protocol that represents a listener of socket connection events public protocol SocketConnectionHandler { /// Will be called once the socket did connect /// /// - Parameter socket: the socket manager func socketDidConnect(socket: SocketManager) /// Will be called once the socket did disconnect /// /// - Parameter socket: the socket manager func socketDidDisconnect(socket: SocketManager) } /// A manager that manages all web socket connection related actions public class SocketManager: AuthManagerInjected, AuthSettingsManagerInjected, PushManagerInjected, SubscriptionManagerInjected, UserManagerInjected { var serverURL: URL? var socket: WebSocket? var queue: [String: MessageCompletion] = [:] var events: [String: [MessageCompletion]] = [:] var internalConnectionHandler: SocketCompletion? var connectionHandlers: [String: SocketConnectionHandler] = [:] // MARK: Connection func connect(socket: WebSocket, completion: SocketCompletion? = nil) { self.serverURL = socket.currentURL self.internalConnectionHandler = completion self.socket = socket self.socket?.delegate = self self.socket?.pongDelegate = self self.socket?.headers = [ "Host": self.serverURL?.host ?? "" ] self.socket?.connect() } func connect(_ url: URL, completion: SocketCompletion? = nil) { self.serverURL = url self.internalConnectionHandler = completion self.socket = WebSocket(url: url) self.socket?.delegate = self self.socket?.pongDelegate = self self.socket?.headers = [ "Host": url.host ?? "" ] self.socket?.connect() } func disconnect(_ completion: @escaping SocketCompletion) { if !(self.socket?.isConnected ?? false) { completion(self.socket, true) return } self.internalConnectionHandler = completion self.socket?.disconnect() } /// Clear all socket connection handlers public func clear() { self.internalConnectionHandler = nil self.connectionHandlers = [:] } // MARK: Messages /// Send a given message to connected server /// /// - Parameters: /// - object: message to be sent /// - completion: will be called after response public func send(_ object: [String: Any], completion: MessageCompletion? = nil) { let identifier = String.random(50) var json = JSON(object) json["id"] = JSON(identifier) if let raw = json.rawString() { Log.debug("Socket will send message: \(raw)") self.socket?.write(string: raw) if completion != nil { self.queue[identifier] = completion } } else { Log.debug("JSON invalid: \(json)") } } /// Subscribe an event by event name and an initial message /// /// - Parameters: /// - object: initial message to subscribe /// - eventName: event to be subscribed /// - completion: will be called after every event fires public func subscribe(_ object: [String: Any], eventName: String, completion: @escaping MessageCompletion) { if var list = self.events[eventName] { list.append(completion) self.events[eventName] = list } else { self.send(object, completion: completion) self.events[eventName] = [completion] } } /// Dummy method, should be overriden for each specific usage /// /// - Parameters: /// - response: error response /// - socket: error socket public func handleError(of response: SocketResponse, socket: WebSocket) { fatalError("Not implemented.") } } // MARK: Helpers extension SocketManager { /// Reconnect to server, server settings are retrieved from auth settings public func reconnect() { guard let auth = authManager.isAuthenticated() else { return } authManager.resume(auth, completion: { (response) in guard !response.isError() else { return } self.subscriptionManager.updateSubscriptions(auth, completion: { _ in // TODO: Move it to somewhere else self.authSettingsManager.updatePublicSettings(auth, completion: { _ in }) self.userManager.userDataChanges() self.userManager.changes() self.subscriptionManager.changes(auth) self.pushManager.updateUser() }) }) } /// Get if the underlying socket is connected /// /// - Returns: `true` if connected public func isConnected() -> Bool { return self.socket?.isConnected ?? false } } // MARK: Connection handlers extension SocketManager { /// Add a socket connection handler to this socket manager /// /// - Parameters: /// - token: a unique token for this connection handler /// - handler: the connection handler public func addConnectionHandler(token: String, handler: SocketConnectionHandler) { self.connectionHandlers[token] = handler } /// Remove a connection handler by given token /// /// - Parameter token: token of the connection handler to be removed public func removeConnectionHandler(token: String) { self.connectionHandlers[token] = nil } } // MARK: WebSocketDelegate extension SocketManager: WebSocketDelegate { public func websocketDidConnect(socket: WebSocket) { Log.debug("Socket (\(socket)) did connect") let object = [ "msg": "connect", "version": "1", "support": ["1", "pre2", "pre1"] ] as [String : Any] self.send(object) } public func websocketDidDisconnect(socket: WebSocket, error: NSError?) { Log.debug("[WebSocket] did disconnect with error (\(String(describing: error)))") events = [:] queue = [:] internalConnectionHandler?(socket, socket.isConnected) internalConnectionHandler = nil for (_, handler) in connectionHandlers { handler.socketDidDisconnect(socket: self) } } public func websocketDidReceiveData(socket: WebSocket, data: Data) { Log.debug("[WebSocket] did receive data (\(data))") } public func websocketDidReceiveMessage(socket: WebSocket, text: String) { let json = JSON(parseJSON: text) // JSON is invalid guard json.exists() else { Log.debug("[WebSocket] did receive invalid JSON object: \(text)") return } if let raw = json.rawString() { Log.debug("[WebSocket] did receive JSON message: \(raw)") } self.handleMessage(json, socket: socket) } } // MARK: WebSocketPongDelegate extension SocketManager: WebSocketPongDelegate { public func websocketDidReceivePong(socket: WebSocket, data: Data?) { Log.debug("[WebSocket] did receive pong") } }
mit
7259bd04aab91909b17b6c9d1483f806
28.597701
149
0.624595
4.852387
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureKYC/Sources/FeatureKYCUI/KYCWelcomeController.swift
1
3295
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import Localization import PlatformUIKit import UIKit /// Welcome screen in KYC flow final class KYCWelcomeController: KYCBaseViewController { // MARK: - IBOutlets @IBOutlet private var imageViewMain: UIImageView! @IBOutlet private var labelMain: UILabel! @IBOutlet private var labelTermsOfService: UILabel! override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent } private let webViewService: WebViewServiceAPI = resolve() // MARK: Factory override class func make(with coordinator: KYCRouter) -> KYCWelcomeController { let controller = makeFromStoryboard(in: .module) controller.router = coordinator controller.pageType = .welcome return controller } // MARK: - UIViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() title = LocalizationConstants.KYC.welcome initMainView() initFooter() } // MARK: - Actions @IBAction func onCloseTapped(_ sender: Any) { presentingViewController?.dismiss(animated: true) } @IBAction private func onLabelTapped(_ sender: UITapGestureRecognizer) { guard let text = labelTermsOfService.text else { return } if let tosRange = text.range(of: LocalizationConstants.tos), sender.didTapAttributedText(in: labelTermsOfService, range: NSRange(tosRange, in: text)) { webViewService.openSafari(url: Constants.Url.termsOfService, from: self) } if let privacyPolicyRange = text.range(of: LocalizationConstants.privacyPolicy), sender.didTapAttributedText(in: labelTermsOfService, range: NSRange(privacyPolicyRange, in: text)) { webViewService.openSafari(url: Constants.Url.privacyPolicy, from: self) } } @IBAction private func primaryButtonTapped(_ sender: Any) { router.handle(event: .nextPageFromPageType(pageType, nil)) } // MARK: - Private Methods private func initMainView() { labelMain.text = LocalizationConstants.KYC.welcomeMainText imageViewMain.image = UIImage(named: "Welcome", in: .featureKYCUI, compatibleWith: nil) } private func initFooter() { let font = UIFont( name: Constants.FontNames.montserratRegular, size: Constants.FontSizes.ExtraExtraExtraSmall ) ?? UIFont.systemFont(ofSize: Constants.FontSizes.ExtraExtraExtraSmall) let labelAttributes = [ NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: UIColor.gray5 ] let labelText = NSMutableAttributedString( string: String( format: LocalizationConstants.KYC.termsOfServiceAndPrivacyPolicyNotice, LocalizationConstants.tos, LocalizationConstants.privacyPolicy ), attributes: labelAttributes ) labelText.addForegroundColor(UIColor.brandSecondary, to: LocalizationConstants.tos) labelText.addForegroundColor(UIColor.brandSecondary, to: LocalizationConstants.privacyPolicy) labelTermsOfService.attributedText = labelText } }
lgpl-3.0
3904c0d33c74eb9b4ae9ad3b52ff1c8b
33.673684
109
0.680631
5.278846
false
false
false
false
huonw/swift
test/decl/init/failable.swift
1
8343
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop import Foundation struct S0 { init!(int: Int) { } init! (uint: UInt) { } init !(float: Float) { } init?(string: String) { } init ?(double: Double) { } init ? (char: Character) { } } struct S1<T> { init?(value: T) { } } class DuplicateDecls { init!() { } // expected-note{{'init()' previously declared here}} init?() { } // expected-error{{invalid redeclaration of 'init()'}} init!(string: String) { } // expected-note{{'init(string:)' previously declared here}} init(string: String) { } // expected-error{{invalid redeclaration of 'init(string:)'}} init(double: Double) { } // expected-note{{'init(double:)' previously declared here}} init?(double: Double) { } // expected-error{{invalid redeclaration of 'init(double:)'}} } // Construct via a failable initializer. func testConstruction(_ i: Int, s: String) { let s0Opt = S0(string: s) assert(s0Opt != nil) var _: S0 = s0Opt // expected-error{{value of optional type 'S0?' not unwrapped; did you mean to use '!' or '?'?}} {{20-20=!}} let s0IUO = S0(int: i) assert(s0IUO != nil) _ = s0IUO } // ---------------------------------------------------------------------------- // Superclass initializer chaining // ---------------------------------------------------------------------------- class Super { init?(fail: String) { } init!(failIUO: String) { } init() { } // expected-note 2{{non-failable initializer 'init()' overridden here}} } class Sub : Super { override init() { super.init() } // okay, never fails init(nonfail: Int) { // expected-note{{propagate the failure with 'init?'}}{{7-7=?}} super.init(fail: "boom") // expected-error{{a non-failable initializer cannot chain to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{29-29=!}} } convenience init(forceNonfail: Int) { self.init(nonfail: forceNonfail)! // expected-error{{cannot force unwrap value of non-optional type '()'}} {{37-38=}} } init(nonfail2: Int) { // okay, traps on nil super.init(failIUO: "boom") } init(nonfail3: Int) { super.init(fail: "boom")! } override init?(fail: String) { super.init(fail: fail) // okay, propagates ? } init?(fail2: String) { // okay, propagates ! as ? super.init(failIUO: fail2) } init?(fail3: String) { // okay, can introduce its own failure super.init() } override init!(failIUO: String) { super.init(failIUO: failIUO) // okay, propagates ! } init!(failIUO2: String) { // okay, propagates ? as ! super.init(fail: failIUO2) } init!(failIUO3: String) { // okay, can introduce its own failure super.init() } } // ---------------------------------------------------------------------------- // Initializer delegation // ---------------------------------------------------------------------------- extension Super { convenience init(convenienceNonFailNonFail: String) { // okay, non-failable self.init() } convenience init(convenienceNonFailFail: String) { // expected-note{{propagate the failure with 'init?'}}{{19-19=?}} self.init(fail: convenienceNonFailFail) // expected-error{{a non-failable initializer cannot delegate to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{44-44=!}} } convenience init(convenienceNonFailFailForce: String) { self.init(fail: convenienceNonFailFailForce)! } convenience init(convenienceNonFailFailIUO: String) { // okay, trap on failure self.init(failIUO: convenienceNonFailFailIUO) } convenience init?(convenienceFailNonFail: String) { self.init() // okay, can introduce its own failure } convenience init?(convenienceFailFail: String) { self.init(fail: convenienceFailFail) // okay, propagates ? } convenience init?(convenienceFailFailIUO: String) { // okay, propagates ! as ? self.init(failIUO: convenienceFailFailIUO) } convenience init!(convenienceFailIUONonFail: String) { self.init() // okay, can introduce its own failure } convenience init!(convenienceFailIUOFail: String) { self.init(fail: convenienceFailIUOFail) // okay, propagates ? as ! } convenience init!(convenienceFailIUOFailIUO: String) { // okay, propagates ! self.init(failIUO: convenienceFailIUOFailIUO) } } struct SomeStruct { init(nonFail: Int) { // expected-note{{propagate the failure with 'init?'}}{{8-8=?}} self.init(fail: nonFail) // expected-error{{a non-failable initializer cannot delegate to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{29-29=!}} } init(nonFail2: Int) { self.init(fail: nonFail2)! } init?(fail: Int) {} } // ---------------------------------------------------------------------------- // Initializer overriding // ---------------------------------------------------------------------------- class Sub2 : Super { override init!(fail: String) { // okay to change ? to ! super.init(fail: fail) } override init?(failIUO: String) { // okay to change ! to ? super.init(failIUO: failIUO) } override init() { super.init() } // no change } // Dropping optionality class Sub3 : Super { override init(fail: String) { // okay, strengthened result type super.init() } override init(failIUO: String) { // okay, strengthened result type super.init() } override init() { } // no change } // Adding optionality class Sub4 : Super { override init?(fail: String) { super.init() } override init!(failIUO: String) { super.init() } override init?() { // expected-error{{failable initializer 'init()' cannot override a non-failable initializer}} super.init() } } class Sub5 : Super { override init?(fail: String) { super.init() } override init!(failIUO: String) { super.init() } override init!() { // expected-error{{failable initializer 'init()' cannot override a non-failable initializer}} super.init() } } // ---------------------------------------------------------------------------- // Initializer conformances // ---------------------------------------------------------------------------- protocol P1 { init(string: String) } @objc protocol P1_objc { init(string: String) } protocol P2 { init?(fail: String) } protocol P3 { init!(failIUO: String) } class C1a : P1 { required init?(string: String) { } // expected-error{{non-failable initializer requirement 'init(string:)' cannot be satisfied by a failable initializer ('init?')}} } class C1b : P1 { required init!(string: String) { } // okay } class C1b_objc : P1_objc { @objc required init!(string: String) { } // expected-error{{non-failable initializer requirement 'init(string:)' in Objective-C protocol cannot be satisfied by a failable initializer ('init!')}} } class C1c { required init?(string: String) { } // expected-note {{'init(string:)' declared here}} } extension C1c: P1 {} // expected-error{{non-failable initializer requirement 'init(string:)' cannot be satisfied by a failable initializer ('init?')}} class C2a : P2 { required init(fail: String) { } // okay to remove failability } class C2b : P2 { required init?(fail: String) { } // okay, ? matches } class C2c : P2 { required init!(fail: String) { } // okay to satisfy init? with init! } class C3a : P3 { required init(failIUO: String) { } // okay to remove failability } class C3b : P3 { required init?(failIUO: String) { } // okay to satisfy ! with ? } class C3c : P3 { required init!(failIUO: String) { } // okay, ! matches } // ---------------------------------------------------------------------------- // Initiating failure // ---------------------------------------------------------------------------- struct InitiateFailureS { init(string: String) { // expected-note{{use 'init?' to make the initializer 'init(string:)' failable}}{{7-7=?}} return (nil) // expected-error{{only a failable initializer can return 'nil'}} } init(int: Int) { return 0 // expected-error{{'nil' is the only return value permitted in an initializer}} } init?(double: Double) { return nil // ok } init!(char: Character) { return nil // ok } }
apache-2.0
e4b18b5fd1d2450979c6396df4880359
28.585106
196
0.598106
3.952155
false
false
false
false
FitnessKit/DataDecoder
Tests/DataDecoderTests/DataDecoderTests.swift
1
5630
import XCTest @testable import DataDecoder class DataDecoderTests: XCTestCase { let deadBeefData: Data = Data([0xEF, 0xBE, 0xAD, 0xDE]) let beefData: Data = Data([0xEF, 0xBE, 0xAD, 0xDE]) let DEADBEEF: UInt32 = 3735928559 let DEAD: UInt16 = 57005 let BEEF: UInt16 = 48879 static var allTests : [(String, (DataDecoderTests) -> () throws -> Void)] { return [ ("testDataExtensionDouble", testDataExtensionDouble), ("testDataExtensionFloat", testDataExtensionFloat), ("testDataExtensionUInt16", testDataExtensionUInt16), ("testDataExtensionUInt32", testDataExtensionUInt32), ("testDataDecode", testDataDecode), ("testSimpleDecodes", testSimpleDecodes), ("testUInt24", testUInt24), ("testUInt48", testUInt48), ("testIPAddress", testIPAddress), ("testMACAddress", testMACAddress), ] } } extension Data { /// Returns a `0x` prefixed, space-separated, hex-encoded string for this `Data`. public var hexDebug: String { return "0x" + map { String(format: "%02X", $0) }.joined(separator: " ") } } // MARK: Zero Copy extension DataDecoderTests { func testDataExtensionDouble() { let value: Double = 1.56 XCTAssertEqual(Data(from: value).to(type: Double.self), value) } func testDataExtensionFloat() { let value: Float = 2.5585 XCTAssertEqual(Data(from: value).to(type: Float.self), value) } func testDataExtensionUInt16() { XCTAssertEqual(beefData.to(type: UInt16.self), BEEF) } func testDataExtensionUInt32() { XCTAssertEqual(deadBeefData.to(type: UInt32.self), DEADBEEF) XCTAssertEqual(deadBeefData.scanValue(start: 0, type: UInt16.self), BEEF) XCTAssertEqual(deadBeefData.scanValue(start: 2, type: UInt16.self), DEAD) } func testDataDecode() { let ipData: Data = Data([0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5]) var decoder = DecodeData() let size = decoder.decodeUInt8(ipData) let value = decoder.decodeDataIfPresent(ipData, length: Int(size)) if let value = value { if value.count != size { XCTFail() } var decoder = DecodeData() let value = decoder.decodeData(ipData, length: ipData.count + 1) if value.count != 0 { XCTFail() } } else { } } func testSimpleDecodes() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let sensorData: Data = Data([0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5]) let DEADBEEF: UInt32 = 3735928559 var decoder = DecodeData() guard let height = decoder.decodeUInt8IfPresent(sensorData) else { XCTFail() return } let weight = decoder.decodeUInt16(sensorData) let beef = decoder.decodeUInt32(sensorData) let nib = decoder.decodeNibble(sensorData) let novalue = decoder.decodeNibble(sensorData) if height != 2 { XCTFail() } if weight != UInt16.max - 1 { XCTFail() } if beef != DEADBEEF { XCTFail() } if nib.lower != 5 && nib.upper != 10 { XCTFail() } if novalue.uint8Value != 0 { XCTFail() } } func testUInt24() { let ipData: Data = Data([0xFF, 0xFF, 0xFF]) var decoder = DecodeData() let value = decoder.decodeUInt24(ipData) if value != 0xFFFFFF { XCTFail() } } func testUInt48() { let ipData: Data = Data([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) var decoder = DecodeData() let value = decoder.decodeUInt48(ipData) if value != 0xFFFFFFFFFFFF { XCTFail() } } func testIPAddress() { let ipData: Data = Data([ 0xAD, 0xA5, 0xEE, 0xB2]) var decoder = DecodeData() let ipaddress = decoder.decodeIPAddress(ipData) if ipaddress != "173.165.238.178" { XCTFail() } } func testMACAddress() { let ipData: Data = Data([ 0x00, 0x50, 0xC2, 0x34, 0xF7, 0x11]) var decoder = DecodeData() let macaddress = decoder.decodeMACAddress(ipData) if macaddress.stringValue != "00:50:C2:34:F7:11" { XCTFail() } } } // MARK: Performance extension DataDecoderTests { func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. let sensorData: Data = Data([0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5, 0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5, 0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5, 0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5, 0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5, 0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5, 0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5, 0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5, 0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5, 0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5, 0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5, 0x02, 0xFE, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xA5]) var tester = DecodeData() for _ in sensorData { let _ = tester.decodeInt8(sensorData) } } } }
mit
e5ee8645e1967016eed29bf577d3b2c0
28.322917
617
0.579218
3.576874
false
true
false
false
RoverPlatform/rover-ios
Sources/UI/Services/ImageStore/ImageOptimization.swift
1
3740
// // ImageOptimization.swift // RoverUI // // Created by Sean Rucker on 2018-04-11. // Copyright © 2018 Rover Labs Inc. All rights reserved. // import UIKit public enum ImageOptimization { var queryItems: [URLQueryItem] { switch self { case .fill(let bounds): let w = bounds.width * UIScreen.main.scale let h = bounds.height * UIScreen.main.scale return [URLQueryItem(name: "fit", value: "min"), URLQueryItem(name: "w", value: w.paramValue), URLQueryItem(name: "h", value: h.paramValue)] case .fit(let bounds): let w = bounds.width * UIScreen.main.scale let h = bounds.height * UIScreen.main.scale return [URLQueryItem(name: "fit", value: "max"), URLQueryItem(name: "w", value: w.paramValue), URLQueryItem(name: "h", value: h.paramValue)] case let .stretch(bounds, originalSize): let w = min(bounds.width * UIScreen.main.scale, originalSize.width) let h = min(bounds.height * UIScreen.main.scale, originalSize.height) return [URLQueryItem(name: "w", value: w.paramValue), URLQueryItem(name: "h", value: h.paramValue)] case let .original(bounds, originalSize, originalScale): let width = min(bounds.width * originalScale, originalSize.width) let height = min(bounds.height * originalScale, originalSize.height) let x = (originalSize.width - width) / 2 let y = (originalSize.height - height) / 2 let value = [x.paramValue, y.paramValue, width.paramValue, height.paramValue].joined(separator: ",") var queryItems = [URLQueryItem(name: "rect", value: value)] if UIScreen.main.scale < originalScale { let w = width / originalScale * UIScreen.main.scale let h = height / originalScale * UIScreen.main.scale queryItems.append(contentsOf: [URLQueryItem(name: "w", value: w.paramValue), URLQueryItem(name: "h", value: h.paramValue)]) } return queryItems case let .tile(bounds, originalSize, originalScale): let width = min(bounds.width * originalScale, originalSize.width) let height = min(bounds.height * originalScale, originalSize.height) let value = ["0", "0", width.paramValue, height.paramValue].joined(separator: ",") var queryItems = [URLQueryItem(name: "rect", value: value)] if UIScreen.main.scale < originalScale { let w = width / originalScale * UIScreen.main.scale let h = height / originalScale * UIScreen.main.scale queryItems.append(contentsOf: [URLQueryItem(name: "w", value: w.paramValue), URLQueryItem(name: "h", value: h.paramValue)]) } return queryItems } } var scale: CGFloat { switch self { case .original(_, _, let originalScale): return UIScreen.main.scale < originalScale ? UIScreen.main.scale : originalScale case .tile(_, _, let originalScale): return UIScreen.main.scale < originalScale ? UIScreen.main.scale : originalScale default: return 1 } } case fill(bounds: CGRect) case fit(bounds: CGRect) case stretch(bounds: CGRect, originalSize: CGSize) case original(bounds: CGRect, originalSize: CGSize, originalScale: CGFloat) case tile(bounds: CGRect, originalSize: CGSize, originalScale: CGFloat) } // MARK: CGFloat fileprivate extension CGFloat { var paramValue: String { let rounded = self.rounded() let int = Int(rounded) return int.description } }
apache-2.0
df1535d190300558c695d631fe2d2fec
44.048193
152
0.6138
4.337587
false
false
false
false
coach-plus/ios
Pods/JWTDecode/JWTDecode/JWTDecode.swift
2
5052
// JWTDecode.swift // // Copyright (c) 2015 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** Decodes a JWT token into an object that holds the decoded body (along with token header and signature parts). If the token cannot be decoded a `NSError` will be thrown. - parameter jwt: jwt string value to decode - throws: an error if the JWT cannot be decoded - returns: a decoded token as an instance of JWT */ public func decode(jwt: String) throws -> JWT { return try DecodedJWT(jwt: jwt) } struct DecodedJWT: JWT { let header: [String: Any] let body: [String: Any] let signature: String? let string: String init(jwt: String) throws { let parts = jwt.components(separatedBy: ".") guard parts.count == 3 else { throw DecodeError.invalidPartCount(jwt, parts.count) } self.header = try decodeJWTPart(parts[0]) self.body = try decodeJWTPart(parts[1]) self.signature = parts[2] self.string = jwt } var expiresAt: Date? { return claim(name: "exp").date } var issuer: String? { return claim(name: "iss").string } var subject: String? { return claim(name: "sub").string } var audience: [String]? { return claim(name: "aud").array } var issuedAt: Date? { return claim(name: "iat").date } var notBefore: Date? { return claim(name: "nbf").date } var identifier: String? { return claim(name: "jti").string } var expired: Bool { guard let date = self.expiresAt else { return false } return date.compare(Date()) != ComparisonResult.orderedDescending } } /** * JWT Claim */ public struct Claim { /// raw value of the claim let value: Any? /// original claim value public var rawValue: Any? { return self.value } /// value of the claim as `String` public var string: String? { return self.value as? String } /// value of the claim as `Double` public var double: Double? { let double: Double? if let string = self.string { double = Double(string) } else { double = self.value as? Double } return double } /// value of the claim as `Int` public var integer: Int? { let integer: Int? if let string = self.string { integer = Int(string) } else if let double = self.value as? Double { integer = Int(double) } else { integer = self.value as? Int } return integer } /// value of the claim as `NSDate` public var date: Date? { guard let timestamp: TimeInterval = self.double else { return nil } return Date(timeIntervalSince1970: timestamp) } /// value of the claim as `[String]` public var array: [String]? { if let array = value as? [String] { return array } if let value = self.string { return [value] } return nil } } private func base64UrlDecode(_ value: String) -> Data? { var base64 = value .replacingOccurrences(of: "-", with: "+") .replacingOccurrences(of: "_", with: "/") let length = Double(base64.lengthOfBytes(using: String.Encoding.utf8)) let requiredLength = 4 * ceil(length / 4.0) let paddingLength = requiredLength - length if paddingLength > 0 { let padding = "".padding(toLength: Int(paddingLength), withPad: "=", startingAt: 0) base64 += padding } return Data(base64Encoded: base64, options: .ignoreUnknownCharacters) } private func decodeJWTPart(_ value: String) throws -> [String: Any] { guard let bodyData = base64UrlDecode(value) else { throw DecodeError.invalidBase64Url(value) } guard let json = try? JSONSerialization.jsonObject(with: bodyData, options: []), let payload = json as? [String: Any] else { throw DecodeError.invalidJSON(value) } return payload }
mit
b1ef00796171efee89f1da9e2adb9551
30.974684
128
0.641132
4.220551
false
false
false
false
ujell/IceAndFireLoader
IceAndFireLoader/main.swift
1
1158
// // main.swift // IceAndFireLoader // // Created by Yücel Uzun on 14/02/16. // Copyright © 2016 Yücel Uzun. All rights reserved. // import Foundation // Some simple examples; IceAndFire.load(583) { (character: IceAndFireCharacter?, error) in guard error == nil else { print (error!) return } if character != nil { print (character!.name!) } } IceAndFire.load(1) { (book: IceAndFireBook?, error) in guard error == nil else { print (error!) return } if book != nil { print (book!.name) } } IceAndFire.load(10) { (house: IceAndFireHouse?, error) in guard error == nil else { print (error!) return } if house != nil { print (house!.name!) } } // Bulk loading: IceAndFire.load(5, pageSize: 10) { (characters:[IceAndFireCharacter]?, error) in guard error == nil else { print (error!) return } if characters != nil { for character in characters! where character.name != nil { print (character.name) } } } // Main normaly ends without waiting closures to run. sleep(50)
mit
677693f4ca059fd9ce228e00721341c4
18.931034
80
0.578355
3.564815
false
false
false
false
wssj/ShowMeThatStatus
ShowMeThatStatus/SMTSStyle.swift
1
1948
// // SMTSStyle.swift // ShowMeThatStatus // // Created by Tomasz Kopycki on 21/04/16. // Copyright © 2016 Noolis. All rights reserved. // import UIKit open class SMTSStyle: NSObject { //Colors open var backgroundColor = UIColor(red: 237.0/255.0, green: 237.0/255.0, blue: 237.0/255.0, alpha: 1.0) open var successColor = UIColor(red: 30.0/255.0, green: 205.0/255.0, blue: 151.0/255.0, alpha: 1.0) open var failureColor = UIColor(red: 194.0/255.0, green: 59.0/255.0, blue: 34.0/255.0, alpha: 1.0) open var progressColor = UIColor.gray open var defaultButtonTextColor = UIColor.white open var cancelButtonTextColor = UIColor.white open var defaultButtonBackgroundColor = UIColor(red: 162.0/255.0, green: 164.0/255.0, blue: 165.0/255.0, alpha: 1.0) open var cancelButtonBackgroundColor = UIColor(red: 162.0/255.0, green: 164.0/255.0, blue: 165.0/255.0, alpha: 1.0) //Borders open var backgroundBorderColor = UIColor.clear.cgColor open var defaultButtonBorderColor = UIColor.clear.cgColor open var cancelButtonBorderColor = UIColor.clear.cgColor //Fonts open var statusFont = UIFont.systemFont(ofSize: 17) open var progressFont = UIFont.systemFont(ofSize: 19) open var defaultButtonFont = UIFont.systemFont(ofSize: 15) open var cancelButtonFont = UIFont.boldSystemFont(ofSize: 15) //Corners open var buttonsCornerRadius: CGFloat = 4.0 open var viewCornerRadius: CGFloat = 4.0 //Size open var width = floor(UIScreen.main.bounds.size.width * 0.8) open var lineWidth: CGFloat = 6.0 open var borderWidth: CGFloat = 1.0 //Shadow open var shadowColor = UIColor.clear.cgColor open var shadowOpacity: Float = 0.5 }
mit
751b2615ec6e9365365e8046d7745707
35.735849
89
0.623523
3.832677
false
false
false
false
xocialize/Kiosk
kiosk/SettingsMenuViewController.swift
1
3935
// // SettingsMenuViewController.swift // kiosk // // Created by Dustin Nielson on 4/16/15. // Copyright (c) 2015 Dustin Nielson. All rights reserved. // import UIKit class customEventCell: UITableViewCell { @IBOutlet var settingsImage: UIImageView! @IBOutlet var settingsLabel: UILabel! } class SettingsMenuViewController: UITableViewController { var dm = DataManager() var settings:Dictionary<String,AnyObject> = [:] var menuItems = ["GitHub Repository","Password","Orientation","iBeacon","Launch Kiosk"] var menuIcons = ["settings_github.png","settings_password.png","settings_orientation.png","settings_ibeacon.png","settings_launch.png"] override func viewDidLoad() { super.viewDidLoad() settings = dm.getSettings() /* Hide empty cells var tblView = UIView(frame: CGRectZero) tableView.tableFooterView = tblView tableView.tableFooterView!.hidden = true tableView.backgroundColor = UIColor.clearColor() */ } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { loadSetting(indexPath.row) } func loadSetting(settingItem: Int){ switch settingItem { case 0: performSegueWithIdentifier("settingsToGitHubSegue", sender: self) break case 1: performSegueWithIdentifier("settingsToPasswordSettingsSegue", sender: self) break case 2: performSegueWithIdentifier("SettingsToOrientationSettingsSegue", sender: self) break case 3: performSegueWithIdentifier("settingsToBeaconSettingsSegue", sender: self) break case 4: prepareToLaunchKiosk() break default: println(settingItem) } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return menuItems.count } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100 } func prepareToLaunchKiosk(){ if dm.checkForIndex() { performSegueWithIdentifier("settingsToKioskSegue", sender: self) } else { self.view.makeToast(message: "No index.html file found", duration: 10, position: HRToastPositionTop, title: "Kiosk Launch Issue") } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! customEventCell cell.settingsLabel.text = menuItems[indexPath.row] cell.settingsImage.image = UIImage(named:menuIcons[indexPath.row]) return cell } override func prefersStatusBarHidden() -> Bool { return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
90cf71dbe5442d40fba977e2568f2493
24.063694
141
0.581957
6.026034
false
false
false
false
sacrelee/iOSDev
Notes/Swift/Coding.playground/Pages/Methods.xcplaygroundpage/Contents.swift
1
4938
/// 方法 // 实例方法和类型方法 分别相当于OC中的"-方法"和"+方法" // 方法同样有局部参数名和外部参数名 // 实例方法(OC中的 -方法) // 由特定的类、结构体、枚举的具体实例所定义的方法,来实现对应的实例任务和功能 class Computing { var num1 = 0 var num2 = 0 func sumWith( num3:Int)->Int{ return num1 + num2 + num3 } func sumWithArray(numbers num3:Int, _ num4:Int, _ num5:Int)->Int // 同函数,支持后续省略的外部名称以"_"代替 { return num1 + num2 + num3 + num4 + num5 } func averageWith(aNumber num3:Int)->Double{ // 同函数,方法同样可有外部参数名 return Double( num1 + num2 + num3) / 3.0 } } var aCom = Computing() aCom.num1 = 59 aCom.num2 = 79 aCom.sumWith(90) aCom.sumWithArray(numbers: 1, 2, 3) aCom.averageWith(aNumber:103) struct Point { var x = 0.0, y = 0.0 func isToTheRightOfX(x: Double) -> Bool { return self.x > x } } /// self属性 // 和OC中类似,是一个隐藏属性,代表实例本身 struct Counter{ var count = 50 func compare(count:Int) -> Bool{ // 使用self.count 消除歧义 return self.count > count } // 结构体和枚举中的属性是值类型,默认不允许在实例方法中被修改 // 通过在方法前加 "mutating"(变异)来修改结构体或者枚举中的属性 mutating func reset(){ // 仅能修改变量,常量不允许被修改 count = 0 } func printResult(){ print("The Count is:\(count)") } mutating func aNewSelf(){ // 给self一个全新的实例,这个实例中count的初始值是500 self = Counter(count: 500) } } var c = Counter() c.compare(100) c.compare(-100) c.printResult() c.reset() c.aNewSelf() // 获取新的self实例 c.count // count已被修改为500 // 枚举中的变异方法可以设置self为不同的成员 enum SwitchStatus{ case Off, Low, High mutating func next(){ switch self{ case Off: self = Low case Low: self = High case High: self = Off } } } var ss = SwitchStatus.Off // 使用next方法使开关状态不断切换 ss.next() ss.next() ss.next() // 类型方法(OC中的 +方法 ) // 这是一个成绩处理类,可以获取总成绩,最高最低分,平均分,以及学生人数 class scoreHandler{ static var sum = 0.0, count = 0, max = 0.0, min = 101.0, average = 0.0 static var maxStu = "", minStu = "" static func addScore(student stu:Student){ sum += stu.score count++ average = sum / Double(count) if max < stu.score{ max = stu.score maxStu = stu.name } if min > stu.score{ min = stu.score minStu = stu.name } Student.setScore(highestScore: max, name: maxStu, lowestScore: min, name: minStu) } static func sumScore() -> Double{ return sum } static func averageScore() -> Double{ return average } static func maxScore() -> Double{ return max } static func minScore() -> Double{ return min } static func studentCount() -> Int{ return count } } struct Student { // 学生结构体,存储学生姓名,成绩以及当前班级中的最高最低分 var name:String var score:Double static var highestScore = 0.0, lowestScore = 0.0, highestStu = "", lowestStu = "" static func setScore(highestScore max:Double,name highestName:String,lowestScore min:Double, name lowestName:String){ // 设定最高最低分 highestScore = max lowestScore = min highestStu = highestName lowestStu = lowestName } } var stu = Student(name: "🐠", score: 10) scoreHandler.addScore(student: stu) print("highest:\(Student.highestScore), lowest:\(scoreHandler.minScore()), aver:\(scoreHandler.averageScore()), count:\(scoreHandler.studentCount())") stu = Student(name: "🐤", score: 20) // 添加学生及其成绩 scoreHandler.addScore(student: stu) scoreHandler.addScore(student: Student(name: "🐶", score: 100)) scoreHandler.addScore(student: Student(name: "🐱", score: 59)) scoreHandler.addScore(student: Student(name: "🐷", score: 67)) scoreHandler.addScore(student: Student(name: "🐻", score: 67)) scoreHandler.addScore(student: Student(name: "🐔", score: 99)) print("The Highest Score:\(Student.highestStu) (\(scoreHandler.maxScore()))") // 取最高分及这个学生 print("The Lowest Score:\(Student.lowestStu)(\(scoreHandler.minScore()))") // 最低分及这个学生 print("The Average:\(scoreHandler.averageScore())") // 获取平均分 print("The number Of Students:\(scoreHandler.studentCount())") // 获取学生数
apache-2.0
7c520c2fbdaa2e6a704c4149c9f278d0
22.241573
150
0.612521
3.197063
false
false
false
false
Eonil/HomeworkApp1
Modules/Monolith/CancellableBlockingIO/InternalTests/main.swift
3
1002
// // main.swift // InternalTests // // Created by Hoon H. on 11/7/14. // Copyright (c) 2014 Eonil. All rights reserved. // import Foundation //let s1 = Semaphore() //let s2 = Semaphore() // //background { // s1.wait() // println("A") //} //background { // s2.wait() // println("B") // s2.wait() // println("C") //} // //sleep(1) //s1.signal() //sleep(1) //s2.signal() //sleep(1) //s2.signal() //sleep(1) // //let s1 = Semaphore() //let s2 = Semaphore() // //background { // s2.wait() // s1.wait() // println("A") //} // //sleep(1) //s1.signal() //s2.signal() //sleep(1) // //var countner1 = 0 //func spawn1() { // let n = ++countner1 // println("start = \(n)") // if n < 100 { // Fiber.spawn(spawn1) // } // println("end = \(n)") //} // //let s1 = Semaphore() // // //background { // spawn1() // // s1.wait() // println("DONE!") //} // // //sleep(100) //testAtomicTransmission() //testProgressiveDownload() testProgressiveDownload1() //testProgressiveDownload2()
mit
97a821158fd14ad32f5e9065fff778e0
8.823529
50
0.547904
2.352113
false
false
false
false
tubikstudio/PizzaAnimation
PizzaAnimation/UI/MenuTVC/TSMenuViewController.swift
1
10403
// // MenuTableViewController.swift // PizzaAnimation // // Created by Tubik Studio on 8/4/16. // Copyright © 2016 Tubik Studio. All rights reserved. // import UIKit let kFoodItemCellIdentifier = "FoodItemCell" let kAnimationDuration = 0.5 let kPizzaRowIndex = 2 struct SubTableViewSettings { var maxRowHeight: CGFloat = 88 var minRowHeight: CGFloat = 44 var horizontalOffset: CGFloat = 20 var makeSmaller = false } class TSMenuViewController: UIViewController { //MARK: vars var subTableSettings = SubTableViewSettings() @IBOutlet private weak var mainTableView: UITableView! private var subTableView: UITableView? private var categories = [TSFoodCategory]() private var dataProvider = DataProvider() private var selectedIndexPath: NSIndexPath? //MARK: view life override func viewDidLoad() { super.viewDidLoad() categories = dataProvider.mockedCategories() mainTableView.registerNib(UINib(nibName: String(TSFoodCategoryTableViewCell), bundle: NSBundle.mainBundle()), forCellReuseIdentifier: String(TSFoodCategoryTableViewCell)) mainTableView.registerNib(UINib(nibName: String(TSPizzaTableViewCell), bundle: NSBundle.mainBundle()), forCellReuseIdentifier: String(TSPizzaTableViewCell)) let navigationBar = navigationController?.navigationBar navigationBar?.setBackgroundImage(UIImage(named: "nav_bar"), forBarMetrics: .Default) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() categories.removeAll() } // MARK: - SubTable funcs private func hideSubTable() { guard let subTableView = subTableView else { return } navigationController?.setNavigationBarHidden(false, animated: true) if selectedIndexPath != nil { let cell = mainTableView.cellForRowAtIndexPath(selectedIndexPath!) as? TSFoodCategoryTableViewCell cell?.closeButton.hidden = true mainTableView.beginUpdates() selectedIndexPath = nil mainTableView.endUpdates() self.view.sendSubviewToBack(subTableView) UIView.animateWithDuration(kAnimationDuration, animations: { self.subTableView?.center.y = -subTableView.frame.height }) { ended in if ended { self.subTableView?.removeFromSuperview() } } } } private func showSubTable(forIndexPath indexPath: NSIndexPath) { subTableSettings.makeSmaller = false navigationController?.setNavigationBarHidden(true, animated: false) mainTableView.beginUpdates() selectedIndexPath = indexPath mainTableView.endUpdates() let category = categories[selectedIndexPath!.row] addSubTable(hidden: true, andFoodItems: category.foodItems) guard let subTableView = subTableView else { return } UIView.animateWithDuration(kAnimationDuration, animations: { subTableView.center.y = subTableView.frame.height/2.0 + kActionButtonHeight self.mainTableView.contentOffset = CGPointZero }) { ended in if ended { subTableView.beginUpdates() self.subTableSettings.makeSmaller = true subTableView.endUpdates() self.view.bringSubviewToFront(subTableView) } } } private func addSubTable(hidden hidden: Bool, andFoodItems foodItems: [FoodItem]) { if subTableView?.superview != nil { subTableView?.removeFromSuperview() } let maxSubTableHeight = view.frame.size.height - mainTableView.rowHeight let subTableHeight = min(CGFloat(foodItems.count) * subTableSettings.minRowHeight, maxSubTableHeight) let frame = CGRect(x: subTableSettings.horizontalOffset , y: hidden ? -subTableHeight : kActionButtonHeight , width: view.frame.width - 2*subTableSettings.horizontalOffset , height: subTableHeight) subTableView = UITableView(frame: frame) subTableView?.delegate = self subTableView?.dataSource = self subTableView?.separatorStyle = .None subTableView?.scrollEnabled = subTableView?.frame.height == maxSubTableHeight view.insertSubview(subTableView!, belowSubview: mainTableView) } } extension TSMenuViewController: UITableViewDelegate, UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == subTableView { guard let selectedIndexPath = selectedIndexPath else { return 0 } let category = categories[selectedIndexPath.row] return category.foodItems.count } return categories.count + 1 //we should change content size for table view } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if tableView == subTableView { guard let selectedIndexPath = selectedIndexPath else { return UITableViewCell() } let category = categories[selectedIndexPath.row] let foodItem = category.foodItems[indexPath.row] var cell = tableView.dequeueReusableCellWithIdentifier(kFoodItemCellIdentifier) if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: kFoodItemCellIdentifier) cell?.accessoryType = .DisclosureIndicator cell?.textLabel?.textColor = UIColor.lightGrayColor() } cell?.textLabel?.text = foodItem.title return cell! } else { if indexPath.row >= categories.count { //empty cell (for changing table view content size) let cell = UITableViewCell(style: .Default, reuseIdentifier: "emptyCell") cell.backgroundColor = UIColor.clearColor() cell.selectionStyle = .None return cell } var cell: TSFoodCategoryTableViewCell if indexPath.row == kPizzaRowIndex { cell = tableView.dequeueReusableCellWithIdentifier(String(TSPizzaTableViewCell), forIndexPath: indexPath) as! TSPizzaTableViewCell } else { cell = tableView.dequeueReusableCellWithIdentifier(String(TSFoodCategoryTableViewCell), forIndexPath: indexPath) as! TSFoodCategoryTableViewCell } //refactor let rectOfCellInSuperview = mainTableView.convertRect(cell.frame, toView: view) let minY = mainTableView.rowHeight let maxY = view.frame.height/2.0 let currentY = CGRectGetMaxY(rectOfCellInSuperview) let offset = abs(min(currentY - minY, maxY))/maxY cell.animate(offset: 1 - offset) cell.delegate = self cell.closeButton.hidden = indexPath.row != selectedIndexPath?.row || selectedIndexPath == nil let category = categories[indexPath.row] cell.customizeCell(withCategory: category) return cell } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if tableView == subTableView { if subTableSettings.makeSmaller { return subTableSettings.minRowHeight } return subTableSettings.maxRowHeight } guard selectedIndexPath != nil else { if indexPath.row == categories.count { //fake cell return 0 } return tableView.rowHeight } if indexPath.row < selectedIndexPath?.row || (indexPath.row == categories.count && selectedIndexPath?.row != categories.count - 1) { return 0.0 } else if indexPath.row == selectedIndexPath?.row { return kActionButtonHeight } else { return view.frame.height } } } extension TSMenuViewController: TSFoodCategoryTableViewCellDelegate { func foodCategoryTableViewCellDidPressCloseButton(cell: TSFoodCategoryTableViewCell) { hideSubTable() cell.closeButton.hidden = true } func foodCategoryTableViewCellDidPressActionButton(cell: TSFoodCategoryTableViewCell) { cell.closeButton.hidden = false guard let indexPath = mainTableView.indexPathForCell(cell) else { return } showSubTable(forIndexPath: indexPath) } } extension TSMenuViewController: UIScrollViewDelegate { func scrollViewWillBeginDragging(scrollView: UIScrollView) { if scrollView == subTableView || selectedIndexPath == nil { return } hideSubTable() } func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView == subTableView { return } if selectedIndexPath != nil { mainTableView.contentOffset = CGPointZero return } guard let indexPathsForVisibleRows = mainTableView.indexPathsForVisibleRows else { return } for indexPath in indexPathsForVisibleRows { let cell = mainTableView.cellForRowAtIndexPath(indexPath) as? TSFoodCategoryTableViewCell if let cell = cell { let rectOfCellInSuperview = mainTableView.convertRect(cell.frame, toView: view) let minY = mainTableView.rowHeight let maxY = view.frame.height/2.0 var currentY = CGRectGetMaxY(rectOfCellInSuperview) if let navBar = navigationController?.navigationBar { currentY -= navBar.frame.height } let offset = abs(min(currentY - minY, maxY))/maxY cell.animate(offset: 1 - offset) } } } }
mit
665d3787f6184d76a6f80767a649a15a
37.525926
123
0.620554
5.866892
false
false
false
false
Brightify/Cuckoo
OCMock/ObjectiveMatchers.swift
2
4253
// // ObjectiveMatchers.swift // Cuckoo-iOS // // Created by Matyáš Kříž on 28/05/2019. // import Foundation /// Used as an Objective-C matcher matching any Objective-C closure. public func objcAny<T: NSObject>() -> T { return TrustMe<T>.onThis(OCMArg.any() as Any) } /// Used as an Objective-C matcher matching any Objective-C closure. public func objcAny() -> String { return TrustMe<NSString>.onThis(StringProxy(constraint: OCMArg.any() as Any) as Any) as String } /// Used as an Objective-C matcher matching any Objective-C closure. public func objcAnyClosure<IN1, OUT>() -> (IN1) -> OUT { let closure = TrustHim.onThis(OCMArg.check { a in return true } as Any) return closure.assumingMemoryBound(to: ((IN1) -> OUT).self).pointee } /// Used as an Objective-C matcher matching any Objective-C closure. public func objcAnyClosure<IN1, IN2, OUT>() -> (IN1, IN2) -> OUT { let closure = TrustHim.onThis(OCMArg.check { a in return true } as Any) return closure.assumingMemoryBound(to: ((IN1, IN2) -> OUT).self).pointee } /// Used as an Objective-C matcher matching any Objective-C closure. public func objcAnyClosure<IN1, IN2, IN3, OUT>() -> (IN1, IN2, IN3) -> OUT { let closure = TrustHim.onThis(OCMArg.check { a in return true } as Any) return closure.assumingMemoryBound(to: ((IN1, IN2, IN3) -> OUT).self).pointee } /// Used as an Objective-C matcher matching any Objective-C closure. public func objcAnyClosure<IN1, IN2, IN3, IN4, OUT>() -> (IN1, IN2, IN3, IN4) -> OUT { let closure = TrustHim.onThis(OCMArg.check { a in return true } as Any) return closure.assumingMemoryBound(to: ((IN1, IN2, IN3, IN4) -> OUT).self).pointee } /// Used as an Objective-C matcher matching any Objective-C closure. public func objcAnyClosure<IN1, IN2, IN3, IN4, IN5, OUT>() -> (IN1, IN2, IN3, IN4, IN5) -> OUT { let closure = TrustHim.onThis(OCMArg.check { a in return true } as Any) return closure.assumingMemoryBound(to: ((IN1, IN2, IN3, IN4, IN5) -> OUT).self).pointee } /// Used as an Objective-C matcher matching any Objective-C closure. public func objcAnyClosure<IN1, IN2, IN3, IN4, IN5, IN6, OUT>() -> (IN1, IN2, IN3, IN4, IN5, IN6) -> OUT { let closure = TrustHim.onThis(OCMArg.check { a in return true } as Any) return closure.assumingMemoryBound(to: ((IN1, IN2, IN3, IN4, IN5, IN6) -> OUT).self).pointee } /// Used as an Objective-C matcher matching any Objective-C closure. public func objcAnyClosure<IN1, IN2, IN3, IN4, IN5, IN6, IN7, OUT>() -> (IN1, IN2, IN3, IN4, IN5, IN6, IN7) -> OUT { let closure = TrustHim.onThis(OCMArg.check { a in return true } as Any) return closure.assumingMemoryBound(to: ((IN1, IN2, IN3, IN4, IN5, IN6, IN7) -> OUT).self).pointee } /// Used as an Objective-C matcher matching any nil value. public func objcIsNil<T: NSObject>() -> T? { return TrustMe<T>.onThis(OCMArg.isNil() as Any) } /// Used as an Objective-C matcher matching any nil value. public func objcIsNil() -> String? { return TrustMe<NSString>.onThis(StringProxy(constraint: OCMArg.isNil() as Any) as Any) as String } /// Used as an Objective-C matcher matching any non-nil value. public func objcIsNotNil<T: NSObject>() -> T? { return TrustMe<T>.onThis(OCMArg.isNotNil() as Any) } /// Used as an Objective-C matcher matching any non-nil value. public func objcIsNotNil() -> String? { return TrustMe<NSString>.onThis(StringProxy(constraint: OCMArg.isNotNil() as Any) as Any) as String } /// Used as an Objective-C equality matcher. public func objcIsEqual<T: NSObject>(to object: T) -> T { return TrustMe<T>.onThis(OCMArg.isEqual(object) as Any) } /// Used as an Objective-C equality matcher. public func objcIsEqual(to string: String) -> String { return TrustMe<NSString>.onThis(StringProxy(constraint: OCMArg.isEqual(string) as Any) as Any) as String } /// Used as an Objective-C inequality matcher. public func objcIsNotEqual<T: NSObject>(to object: T) -> T? { return TrustMe<T>.onThis(OCMArg.isNotEqual(object) as Any) } /// Used as an Objective-C inequality matcher. public func objcIsNotEqual(to string: String) -> String? { return TrustMe<NSString>.onThis(StringProxy(constraint: OCMArg.isNotEqual(string) as Any) as Any) as String }
mit
ea6a93334d99108e7b0f79d3981c6077
41.48
116
0.7008
3.132743
false
false
false
false
ydi-core/nucleus-ios
Nucleus/CustomUIView.swift
1
2572
// // CustomUIView.swift // Nucleus // // Created by Bezaleel Ashefor on 27/10/2017. // Copyright © 2017 Ephod. All rights reserved. // import UIKit class CustomUIView: UIView { let gradientLayer = CAGradientLayer() override func layoutSubviews() { // resize your layers based on the view's new frame super.layoutSubviews() gradientLayer.frame = self.bounds let color1 = hexStringToUIColor(hex: "498207").cgColor //UIColor(red: 0.00392157, green: 0.862745, blue: 0.384314, alpha: 1).cgColor let color2 = hexStringToUIColor(hex: "3D3D3D").cgColor//UIColor(red: 0.0470588, green: 0.486275, blue: 0.839216, alpha: 1).cgColor gradientLayer.colors = [color1, color2] gradientLayer.locations = [0.0, 0.8] gradientLayer.startPoint = CGPoint(x: 0, y: 0) gradientLayer.endPoint = CGPoint(x: 1, y: 1) self.layer.insertSublayer(gradientLayer, at: 0) //self.layer.addSublayer(gradientLayer) } func hexStringToUIColor (hex:String) -> UIColor { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } if ((cString.count) != 6) { return UIColor.gray } var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(0.6) ) } func UIColorFromRGB(color: String) -> UIColor { return UIColorFromRGB(color: color, alpha: 1.0) } func UIColorFromRGB(color: String, alpha: Double) -> UIColor { assert(alpha <= 1.0, "The alpha channel cannot be above 1") assert(alpha >= 0, "The alpha channel cannot be below 0") var rgbValue : UInt32 = 0 let scanner = Scanner(string: color) scanner.scanLocation = 1 if scanner.scanHexInt32(&rgbValue) { let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0 let green = CGFloat((rgbValue & 0xFF00) >> 8) / 255.0 let blue = CGFloat(rgbValue & 0xFF) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: CGFloat(alpha)) } return UIColor.black } }
bsd-2-clause
4b813f20e81b1ef0e47a4769ed4a857e
32.38961
140
0.58382
4.068038
false
false
false
false
cabarique/TheProposalGame
MyProposalGame/Libraries/SG-Engine/IOS_Responder.swift
1
2161
/* * Copyright (c) 2015 Neil North. * * 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 SpriteKit extension SGScene { /** Handle screen touch events. */ override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch: AnyObject in touches { let location = touch.locationInNode(self) screenInteractionStarted(location) } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch: AnyObject in touches { let location = touch.locationInNode(self) screenInteractionMoved(location) } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch: AnyObject in touches { let location = touch.locationInNode(self) screenInteractionEnded(location) } } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { if let actualTouches = touches { for touch: AnyObject in actualTouches { let location = touch.locationInNode(self) screenInteractionEnded(location) } } } }
mit
71e89c1a5ac546c3a516f6fbbb996128
31.757576
85
0.723739
4.667387
false
false
false
false
leo150/Pelican
Sources/Pelican/Session/Modules/Queue/Queue.swift
1
6996
// // ChatSessionActions.swift // Pelican // // Created by Takanu Kyriako on 27/03/2017. // // import Foundation import Vapor /** Defines a class that acts as a proxy for the Pelican-managed Schedule class, thats used to delay the execution of functions. This class includes many helper and convenience functions to make */ public class ChatSessionQueue { /// DATA /// The chat ID of the session this queue belongs to. public var chatID: Int /// A callback to the Pelican `sendRequest` method, enabling the class to send it's own requests. public var tag: SessionTag // CALLBACKS /// A callback to Schedule, to add an event to the queue public var addEvent: (ScheduleEvent) -> () public var removeEvent: (ScheduleEvent) -> () /** Copies of the ScheduleEvents that are generated to submit to the schedule, in case this class needs to remove any events already in the schedule. */ public var eventHistory: [ScheduleEvent] = [] /// The point at which the last addition to the queue is set to play, relative to the current time value. var lastEventTime: Double = 0 /// The last event "view time" request, used to calculate when the next event should be queued at. var lastEventViewTime: Double = 0 /** Initialises the Queue class with a Pelican-derived Schedule. */ init(chatID: Int, schedule: Schedule, tag: SessionTag) { self.chatID = chatID self.tag = tag self.addEvent = schedule.add(_:) self.removeEvent = schedule.remove(_:) } /** Adds an action to the session queue, that allows an enclosure to be executed at a later time, with the included session. - parameter byDelay: The time this action has to wait from when the last action was executed. If queued after an action that has a defined `viewTime` thats longer than they delay, that will be used as the time that this action can be sent as one in the stack before it. - parameter viewTime: The length of the pause after this action is executed before another action in the queue can be executed. If the action next in the stack has a delay timer thats longer, that will be used instead as the pause between the two actions. - parameter name: A name for the action, that can be used to search for and edit the action later on. - parameter action: The closure to be executed when the queue executes this action. */ public func action(delay: Duration, viewTime: Duration, action: @escaping () -> ()) -> ScheduleEvent { // Calculate what kind of delay we're using let execTime = bumpEventTime(delay: delay, viewTime: viewTime) // Add it directly to the end of the stack let event = ScheduleEvent(delayUnixTime: execTime, action: action) addEvent(event) eventHistory.append(event) return event } /** A shorthand function for sending a single message in a delayed fashion, through the action system. This makes assumptions that you're sending a message with specific default parameters (no replies, no parse mode, no web preview, no notification disabling). - parameter delay: The time this action has to wait from when the last action was executed. If queued after an action that has a defined `viewTime` thats longer than they delay, that will be used as the time that this action can be sent as one in the stack before it. - parameter viewTime: The length of the pause after this action is executed before another action in the queue can be executed. If the action next in the stack has a delay timer thats longer, that will be used instead as the pause between the two actions. - parameter message: The text message you wish to send. - parameter markup: If any special message functions should be applied. */ public func message(delay: Duration, viewTime: Duration, message: String, markup: MarkupType? = nil) { // Calculate what kind of delay we're using let execTime = bumpEventTime(delay: delay, viewTime: viewTime) let event = ScheduleEvent(delayUnixTime: execTime) { let request = TelegramRequest.sendMessage(chatID: self.chatID, text: message, replyMarkup: markup ) _ = self.tag.sendRequest(request) } addEvent(event) eventHistory.append(event) } /** A function for sending a single message in a delayed fashion, through the action system. Allows configuration of all parameters. - parameter delay: The time this action has to wait from when the last action was executed. If queued after an action that has a defined `viewTime` thats longer than they delay, that will be used as the time that this action can be sent as one in the stack before it. - parameter viewTime: The length of the pause after this action is executed before another action in the queue can be executed. If the action next in the stack has a delay timer thats longer, that will be used instead as the pause between the two actions. - parameter message: The text message you wish to send. - parameter markup: If any special message functions should be applied. */ public func messageEx(delay: Duration, viewTime: Duration, message: String, markup: MarkupType? = nil, parseMode: MessageParseMode = .none, replyID: Int = 0, webPreview: Bool = false, disableNtf: Bool = false) { // Calculate what kind of delay we're using let execTime = bumpEventTime(delay: delay, viewTime: viewTime) let event = ScheduleEvent(delayUnixTime: execTime) { let request = TelegramRequest.sendMessage(chatID: self.chatID, text: message, replyMarkup: markup, parseMode: parseMode, disableWebPreview: webPreview, disableNtf: disableNtf, replyMessageID: replyID) _ = self.tag.sendRequest(request) } addEvent(event) eventHistory.append(event) } /** Used to internally bump the queue stack timer, to ensure that when actions are queued they never overlap each other. Only use this for custom functions that extend Queue, all default queue action functions already make use of this. */ public func bumpEventTime(delay: Duration, viewTime: Duration) -> Double { // Calculate what kind of delay we're using var execTime = lastEventTime // If we have a last event view time that is longer than the delay, extend the execTime by this. if (lastEventViewTime - delay.unixTime) > 0 { execTime += lastEventViewTime } // Otherwise just add the delay directly else { execTime += delay.unixTime } //print("Event time bumped - (delay \(delay) | viewTime \(viewTime)) (LETime- \(lastEventTime) | LEViewTime - \(lastEventViewTime)) \(execTime) seconds, ") // Set the new last timer values lastEventTime = execTime lastEventViewTime = viewTime.unixTime return execTime } /** Removes a scheduled event from being executed. */ public func remove(_ event: ScheduleEvent) { removeEvent(event) } /** Clears all actions in the queue. */ public func clear() { lastEventTime = 0 lastEventViewTime = 0 //print("Event queue cleared.") for event in eventHistory { _ = removeEvent(event) } eventHistory.removeAll() } }
mit
c203f031e047eef89b5932ed4c6cd534
37.651934
212
0.735277
3.981787
false
false
false
false
BenziAhamed/Nevergrid
NeverGrid/Source/SKTEffect.swift
1
7141
// // SKTEffect.swift // gettingthere // // Created by Benzi on 15/07/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // import Foundation import SpriteKit import UIKit //typedef float (^SKTTimingFunction)(float y); typealias SKTTimingFunction=(CGFloat)->CGFloat struct SKTTimingFunctions { static let Linear:SKTTimingFunction = { return $0 } static let SmoothStep:SKTTimingFunction = { return $0*$0*(3-2*$0) } static let QuadraticEaseIn:SKTTimingFunction = { return $0*$0 } static let QuadraticEaseOut:SKTTimingFunction = { return $0*(2.0-$0) } static let QuadraticEaseInOut:SKTTimingFunction = { (t) in if t < 0.5 { return 2.0 * t * t } else { let f = t - 1.0 return 1.0 - 2.0 * f * f } } static let CubicEaseIn:SKTTimingFunction = { return $0*$0*$0 } static let CubicEaseOut:SKTTimingFunction = { (t) in let f = t - 1.0 return 1.0 + f * f * f } static let CubicEaseInOut:SKTTimingFunction = { (t) in if (t < 0.5) { return 4.0 * t * t * t; } else { let f = t - 1.0; return 1.0 + 4.0 * f * f * f; } } // static let QuarticEaseIn:SKTTimingFunction = { return $0*$0*$0*$0 } // static let QuarticEaseOut:SKTTimingFunction = { (t) in // let f = t - 1.0; // return 1.0 - f * f * f * f; // } // static let QuarticEaseInOut:SKTTimingFunction = { (t) in // if (t < 0.5) { // return 8.0 * t * t * t * t; // } else { // let f = t - 1.0; // return 1.0 - 8.0 * f * f * f * f; // } // } // // // static let SineEaseIn:SKTTimingFunction = { (t) in // return sin((t - 1.0) * M_PI_2) + 1.0; // } // static let SineEaseOut:SKTTimingFunction = { (t) in // return sin(t * M_PI_2) // } // static let SineEaseInOut:SKTTimingFunction = { (t) in // return 0.5 * (1.0 - cos(t * M_PI)) // } // // // static let CircularEaseIn:SKTTimingFunction = { (t) in // return 1.0 - sqrt(1.0 - t * t) // } // static let CircularEaseOut:SKTTimingFunction = { (t) in // return sqrt((2.0 - t) * t) // } // static let CircularEaseInOut:SKTTimingFunction = { (t) in // if (t < 0.5) { // return 0.5 * (1.0 - sqrt(1.0 - 4.0 * t * t)); // } else { // return 0.5 * sqrt(-4.0 * t * t + 8.0 * t - 3.0) + 0.5; // } // } // // // // static let ExponentialEaseIn:SKTTimingFunction = { (t) in // return (t == 0.0) ? t : pow(2.0, 10.0 * (t - 1.0)) // } // static let ExponentialEaseOut:SKTTimingFunction = { (t) in // return (t == 1.0) ? t : 1.0 - pow(2.0, -10.0 * t) // } // static let ExponentialEaseInOut:SKTTimingFunction = { (t) in // if (t == 0.0 || t == 1.0) { // return t; // } else if (t < 0.5) { // return 0.5 * pow(2.0, 20.0 * t - 10.0); // } else { // return 1.0 - 0.5 * pow(2.0, -20.0 * t + 10.0); // } // } // // // static let ElasticEaseIn:SKTTimingFunction = { (t) in // return sin(13.0 * M_PI_2 * t) * pow(2.0, 10.0 * (t - 1.0)) // } // static let ElasticEaseOut:SKTTimingFunction = { (t) in // return sin(-13.0 * M_PI_2 * (t + 1.0)) * pow(2.0, -10.0 * t) + 1.0 // } // static let ElasticEaseInOut:SKTTimingFunction = { (t) in // if (t < 0.5) { // return 0.5 * sin(13.0 * M_PI * t) * pow(2.0, 20.0 * t - 10.0); // } else { // return 0.5 * sin(-13.0 * M_PI * t) * pow(2.0, -20.0 * t + 10.0) + 1.0; // } // } // // // static let BackEaseIn:SKTTimingFunction = { (t) in // let s = 1.70158 // return ((s + 1.0) * t - s) * t * t // } // static let BackEaseOut:SKTTimingFunction = { (t) in // let s = 1.70158 // let f = 1.0 - t // return 1.0 - ((s + 1.0) * f - s) * f * f // } // static let BackEaseInOut:SKTTimingFunction = { (t) in // let s = 1.70158 // if (t < 0.5) { // let f = 2.0 * t // return 0.5 * ((s + 1.0) * f - s) * f * f; // } else { // let f = 2.0 * (1.0 - t) // return 1.0 - 0.5 * ((s + 1.0) * f - s) * f * f; // } // } // // // static let BounceEaseIn:SKTTimingFunction = { (t) in // return 1.0 - BounceEaseOut(1.0 - t) // } // static let BounceEaseOut:SKTTimingFunction = { (t) in // if (t < 1.0 / 2.75) { // return 7.5625 * t * t // } else if (t < 2.0 / 2.75) { // var t1 = t - (1.5 / 2.75) // return 7.5625 * t1 * t1 + 0.75 // } else if (t < 2.5 / 2.75) { // var t1 = t - (2.25 / 2.75) // return 7.5625 * t1 * t1 + 0.9375 // } else { // var t1 = t - (2.625 / 2.75) // return 7.5625 * t1 * t1 + 0.984375 // } // } // static let BounceEaseInOut:SKTTimingFunction = { (t) in // if (t < 0.5) { // return 0.5 * BounceEaseIn(t * 2.0) // } else { // return 0.5 * BounceEaseOut(t * 2.0 - 1.0) + 0.5 // } // } // // static let EaseIn:SKTTimingFunction = { (t) in // // } // static let EaseOut:SKTTimingFunction = { (t) in // // } // static let EaseInOut:SKTTimingFunction = { (t) in // // } } class SKTEffect { weak var node:SKNode? var duration:CGFloat var timingFunction:SKTTimingFunction init(node:SKNode,duration:CGFloat){ self.node = node self.duration = duration self.timingFunction = SKTTimingFunctions.Linear } func update(t:CGFloat) {} func toAction() -> SKAction { return SKAction.actionWithEffect(self) } } class SKTMoveEffect:SKTEffect { var startPos:CGPoint var prevPos:CGPoint var delta:CGPoint init(node: SKNode, duration: CGFloat, startPos:CGPoint, endPos:CGPoint) { self.startPos = startPos self.prevPos = node.position self.delta = endPos.subtract(startPos) super.init(node: node, duration: duration) } override func update(t: CGFloat) { let newPos = startPos.add(delta.multiply(t)) let diff = newPos.subtract(prevPos) prevPos = newPos node!.position = node!.position.add(diff) } } class SKTScaleEffect:SKTEffect { var startScale:CGPoint var prevScale:CGPoint var delta:CGPoint init(node: SKNode, duration: CGFloat, startScale:CGPoint, endScale:CGPoint) { self.startScale = startScale self.prevScale = CGPointMake(node.xScale, node.yScale) self.delta = endScale.subtract(startScale) super.init(node: node, duration: duration) } override func update(t: CGFloat) { let newScale = startScale.add(delta.multiply(t)) let diff = newScale.divide(prevScale) prevScale = newScale; self.node!.xScale *= diff.x self.node!.yScale *= diff.y } }
isc
b5decd89a20f552354842143bb7b4cb7
28.634855
84
0.497689
3.002944
false
false
false
false
Jamnitzer/Metal_ImageProcessing
Metal_ImageProcessing/Metal_ImageProcessing/TView.swift
1
15174
//------------------------------------------------------------------------------ // Derived from Apple's WWDC example "MetalImageProcessing" // Created by Jim Wrenholt on 12/6/14. //------------------------------------------------------------------------------ import Foundation import UIKit import Metal import QuartzCore //------------------------------------------------------------------------------ // View for Metal Sample Code. Manages screen drawable framebuffers and // expects a delegate to repond to render commands to perform drawing. //------------------------------------------------------------------------------ @objc protocol TViewDelegate { func render(metalView : TView) func reshape(metalView : TView) } //------------------------------------------------------------------------------ class TView : UIView { //------------------------------------------------------ override class func layerClass() -> AnyClass { return CAMetalLayer.self } //------------------------------------------------------ @IBOutlet weak var delegate: TViewDelegate! //------------------------------------------------------ // view has a handle to the metal device when created //------------------------------------------------------ var device:MTLDevice? //------------------------------------------------------ // the current drawable created within the view's CAMetalLayer //------------------------------------------------------ var _currentDrawable:CAMetalDrawable? //------------------------------------------------------ // The current framebuffer can be read by delegate during // -[MetalViewDelegate render:] // This call may block until the framebuffer is available. //------------------------------------------------------ var _renderPassDescriptor:MTLRenderPassDescriptor? //------------------------------------------------------ // set these pixel formats to have the main drawable // framebuffer get created // with depth and/or stencil attachments //------------------------------------------------------ var depthPixelFormat:MTLPixelFormat? var stencilPixelFormat:MTLPixelFormat? var sampleCount:Int = 1 weak var metalLayer:CAMetalLayer? var layerSizeDidUpdate:Bool = false var _depthTex:MTLTexture? var _stencilTex:MTLTexture? var _msaaTex:MTLTexture? //------------------------------------------------------ override init(frame: CGRect) // default initializer { super.init(frame: frame) self.initCommon() } //------------------------------------------------------ required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.initCommon() } //------------------------------------------------------ func initCommon() { self.opaque = true self.backgroundColor = nil device = MTLCreateSystemDefaultDevice() metalLayer = self.layer as? CAMetalLayer if (metalLayer == nil) { print("NO metalLayer HERE") } metalLayer?.device = device // 2 metalLayer?.pixelFormat = .BGRA8Unorm // 3 metalLayer?.framebufferOnly = true // 4 //---------------------------------------------------- // this is the default but if we wanted to perform compute // on the final rendering layer we could set this to no //---------------------------------------------------- } //------------------------------------------------------ override func didMoveToWindow() { if let ns = self.window?.screen.nativeScale { self.contentScaleFactor = CGFloat(ns) } } //------------------------------------------------------ // release any color/depth/stencil resources. // view controller will call when paused. //------------------------------------------------------ func releaseTextures() { _depthTex = nil _stencilTex = nil _msaaTex = nil } //------------------------------------------------------ func renderPassDescriptor() -> MTLRenderPassDescriptor? { let drawable:CAMetalDrawable? = self.currentDrawable() if (drawable == nil) { print(">> ERROR: Failed to get a drawable!") _renderPassDescriptor = nil } else { let t1 = drawable!.texture setupRenderPassDescriptorForTexture(t1) } return _renderPassDescriptor } //------------------------------------------------------------------------- func currentDrawable() -> CAMetalDrawable? { if (_currentDrawable == nil) { _currentDrawable = metalLayer?.nextDrawable() } return _currentDrawable } //-------------------------------------------------------------- // view controller will call off the main thread //-------------------------------------------------------------- func display() { //---------------------------------------------------------- // Create autorelease pool per frame to avoid possible // deadlock situations because there are 3 CAMetalDrawables // sitting in an autorelease pool. //---------------------------------------------------------- autoreleasepool { //------------------------------------------------------ // handle display changes here //------------------------------------------------------ if (self.layerSizeDidUpdate) { //-------------------------------------------------- // set the metal layer to the drawable size // in case orientation or size changes //-------------------------------------------------- var drawableSize = self.bounds.size let sc = self.contentScaleFactor drawableSize.width *= sc drawableSize.height *= sc self.metalLayer?.drawableSize = drawableSize //-------------------------------------------------- // renderer delegate method so renderer // can resize anything if needed //-------------------------------------------------- self.delegate?.reshape(self) self.layerSizeDidUpdate = false } //------------------------------------------------------ // rendering delegate method to ask renderer to // draw this frame's content //------------------------------------------------------ self.delegate?.render(self) //------------------------------------------------------ // do not retain current drawable beyond the frame. // There should be no strong references to this object // outside of this view class //------------------------------------------------------ self._currentDrawable = nil } } //------------------------------------------------------------------------ func set_ContentScaleFactor(contentScaleFactor:CGFloat) { super.contentScaleFactor = contentScaleFactor layerSizeDidUpdate = true } //------------------------------------------------------------------------- override func layoutSubviews() { super.layoutSubviews() layerSizeDidUpdate = true } //------------------------------------------------------------------------- func setupRenderPassDescriptorForTexture(texture:MTLTexture) { //---------------------------------------------------------- // create lazily //---------------------------------------------------------- if (_renderPassDescriptor == nil) { _renderPassDescriptor = MTLRenderPassDescriptor() } //---------------------------------------------------------- // create a color attachment every frame since we have to // recreate the texture every frame //---------------------------------------------------------- let colorAttachment:MTLRenderPassColorAttachmentDescriptor? = _renderPassDescriptor!.colorAttachments[0]! colorAttachment?.texture = texture //---------------------------------------------------------- // make sure to clear every frame for best performance //---------------------------------------------------------- colorAttachment?.loadAction = MTLLoadAction.Clear colorAttachment?.clearColor = MTLClearColorMake(0.65, 0.65, 0.65, 1.0) //---------------------------------------------------------- // if sample count is greater than 1, render into using MSAA, // then resolve into our color texture //---------------------------------------------------------- if (sampleCount > 1) { let doUpdate:Bool = (_msaaTex!.width != texture.width || _msaaTex!.height != texture.height || _msaaTex!.sampleCount != sampleCount) let hasMSAA:Bool = (_msaaTex != nil) if(!hasMSAA || (hasMSAA && doUpdate)) { let desc = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( MTLPixelFormat.BGRA8Unorm, width: texture.width, height: texture.height, mipmapped: false) desc.textureType = MTLTextureType.Type2DMultisample //-------------------------------------------------- // sample count was specified to the view by the renderer. // this must match the sample count given to any pipeline // state using this render pass descriptor //-------------------------------------------------- desc.sampleCount = sampleCount _msaaTex = device?.newTextureWithDescriptor(desc) } //---------------------------------------------------------- // When multisampling, perform rendering to _msaaTex, then resolve // to 'texture' at the end of the scene //---------------------------------------------------------- colorAttachment?.texture = _msaaTex colorAttachment?.resolveTexture = texture //---------------------------------------------------------- // set store action to resolve in this case //---------------------------------------------------------- colorAttachment?.storeAction = MTLStoreAction.MultisampleResolve } else { //---------------------------------------------------------- // store only attachments that will be presented // to the screen, as in this case //---------------------------------------------------------- colorAttachment?.storeAction = MTLStoreAction.Store } // color0 //---------------------------------------------------------- // Now create the depth and stencil attachments //---------------------------------------------------------- if (depthPixelFormat != MTLPixelFormat.Invalid) { //---------------------------------------------------------- var doUpdate:Bool = false if (_depthTex != nil) { doUpdate = (_depthTex!.width != texture.width || _depthTex!.height != texture.height || _depthTex!.sampleCount != sampleCount) } else { doUpdate = true } //---------------------------------------------------------- if(_depthTex == nil || doUpdate) { //-------------------------------------------------- // If we need a depth texture and don't have one, // or if the depth texture we have is the wrong size // Then allocate one of the proper size //-------------------------------------------------- let desc = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( depthPixelFormat!, width: texture.width, height: texture.height, mipmapped: false) desc.textureType = (sampleCount > 1) ? MTLTextureType.Type2DMultisample : MTLTextureType.Type2D desc.sampleCount = sampleCount _depthTex = device?.newTextureWithDescriptor(desc) let depthAttachment:MTLRenderPassDepthAttachmentDescriptor = _renderPassDescriptor!.depthAttachment depthAttachment.texture = _depthTex depthAttachment.loadAction = MTLLoadAction.Clear depthAttachment.storeAction = MTLStoreAction.DontCare depthAttachment.clearDepth = 1.0 } } // depth //---------------------------------------------------------- if (stencilPixelFormat != MTLPixelFormat.Invalid) { let doUpdate:Bool = (_stencilTex!.width != texture.width || _stencilTex!.height != texture.height || _stencilTex!.sampleCount != sampleCount) if (_stencilTex == nil || doUpdate) { //-------------------------------------------------- // If we need a stencil texture and don't have one, // or if the depth texture we have is the wrong size // Then allocate one of the proper size //-------------------------------------------------- let desc = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( stencilPixelFormat!, width: texture.width, height: texture.height, mipmapped: false) desc.textureType = (sampleCount > 1) ? MTLTextureType.Type2DMultisample : MTLTextureType.Type2D desc.sampleCount = sampleCount _stencilTex = device?.newTextureWithDescriptor(desc) let stencilAttachment:MTLRenderPassStencilAttachmentDescriptor = _renderPassDescriptor!.stencilAttachment stencilAttachment.texture = _stencilTex stencilAttachment.loadAction = MTLLoadAction.Clear stencilAttachment.storeAction = MTLStoreAction.DontCare stencilAttachment.clearStencil = 0 } } //stencil } //-------------------------------------------------------------------------- } //------------------------------------------------------------------------------
bsd-2-clause
4ae02e13066152065626fe40c672d8b3
40.121951
83
0.40141
7.177862
false
false
false
false
PonyGroup/PonyChatUI-Swift
PonyChatUI/Classes/Application Logic/Configable.swift
1
3193
// // Configable.swift // PonyChatUIProject // // Created by 崔 明辉 on 15/10/27. // // import Foundation extension PonyChatUI.UserInterface { public struct LongPressEntity { public let title: String public let executingBlock: (message: PonyChatUI.Entity.Message, chatViewController: PonyChatUI.UserInterface.MainViewController?) -> Void public init(title: String, executingBlock: (message: PonyChatUI.Entity.Message, chatViewController: PonyChatUI.UserInterface.MainViewController?) -> Void) { self.title = title self.executingBlock = executingBlock } } public struct Configure { public static var sharedConfigure: Configure = Configure() public var cellGaps: CGFloat = 8.0 public var nicknameShow: Bool = false public var nicknameStyle = [String: AnyObject]() public var nicknameEdge = UIEdgeInsets(top: 4, left: 10, bottom: 2, right: 10) public var avatarSize = CGSize(width: CGFloat(40.0), height: CGFloat(40.0)) public var avatarEdge = UIEdgeInsets(top: 5, left: 10, bottom: 0, right: 10) public var avatarCornerRadius: CGFloat = 0.0 public var textStyle = [String: AnyObject]() public var textEdge = UIEdgeInsets(top: 14, left: 18, bottom: 11, right: 18) public var textBackgroundSender = UIImage(named: "SenderTextNodeBkg", inBundle: NSBundle(forClass: PonyChatUICore.self), compatibleWithTraitCollection: nil)!.resizableImageWithCapInsets(UIEdgeInsets(top: 28, left: 20, bottom: 15, right: 20), resizingMode: .Stretch) public var textBackgroundReceiver = UIImage(named: "ReceiverTextNodeBkg", inBundle: NSBundle(forClass: PonyChatUICore.self), compatibleWithTraitCollection: nil)!.resizableImageWithCapInsets(UIEdgeInsets(top: 28, left: 20, bottom: 15, right: 20), resizingMode: .Stretch) public var longPressItems = [LongPressEntity]() public var systemTextStyle = [String: AnyObject]() init() { textStyle = defaultTextStyle() nicknameStyle = defaultNicknameStyle() systemTextStyle = defaultSystemTextStyle() } func defaultTextStyle() -> [String: AnyObject] { let font = UIFont.systemFontOfSize(16) let pStyle = NSMutableParagraphStyle() pStyle.paragraphSpacing = 0.25 * font.lineHeight pStyle.lineSpacing = 6.0 pStyle.hyphenationFactor = 1.0 return [NSFontAttributeName: font, NSParagraphStyleAttributeName: pStyle] } func defaultNicknameStyle() -> [String: AnyObject] { let font = UIFont.systemFontOfSize(13) let color = UIColor.grayColor() return [NSFontAttributeName: font, NSForegroundColorAttributeName: color] } func defaultSystemTextStyle() -> [String: AnyObject] { let font = UIFont.systemFontOfSize(14) let color = UIColor.whiteColor() return [NSFontAttributeName: font, NSForegroundColorAttributeName: color] } } }
mit
163a18ff579c4d70b54b556e92496b5e
42.081081
277
0.648572
5.066773
false
true
false
false
YinSiQian/SQAutoScrollView
SQAutoScrollView/Source/SQDotView.swift
1
1725
// // SQDotView.swift // SQAutoScrollView // // Created by ysq on 2017/10/11. // Copyright © 2017年 ysq. All rights reserved. // import UIKit public enum SQDotState { case normal case selected } public class SQDotView: UIView { private var normalColor: UIColor? { willSet { guard newValue != nil else { return } backgroundColor = newValue! } } private var selectedColor: UIColor? { willSet { guard newValue != nil else { return } backgroundColor = newValue! } } public var isSelected: Bool = false { didSet { assert(selectedColor != nil || normalColor != nil, "please set color value") if isSelected { backgroundColor = selectedColor! } else { backgroundColor = normalColor! } } } public var style: SQPageControlStyle = .round { didSet { switch style { case .round: layer.cornerRadius = bounds.size.width / 2 case .rectangle: layer.cornerRadius = 0 } } } override public init(frame: CGRect) { super.init(frame: frame) } public func set(fillColor: UIColor, state: SQDotState) { switch state { case .normal: self.normalColor = fillColor case .selected: self.selectedColor = fillColor } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
0a9ebc234022e62a213965d56d3d7e22
21.363636
88
0.507549
5.079646
false
false
false
false
nfls/nflsers
app/AppDelegate.swift
1
2422
// // AppDelegate.swift // general // // Created by 胡清阳 on 17/2/3. // Copyright © 2017年 胡清阳. All rights reserved. // import UIKit import IQKeyboardManagerSwift import UserNotifications import Alamofire import AlamofireNetworkActivityIndicator import QuickLook import Sentry @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var token:String = "" var isLaunched = false var isOn = true var time = Date().timeIntervalSince1970 //var theme = ThemeManager() var url:String? = nil var isUnityRunning = false var application: UIApplication? var enableAllOrientation = true func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { self.application = application IQKeyboardManager.shared.enable = true NetworkActivityIndicatorManager.shared.isEnabled = true NetworkActivityIndicatorManager.shared.completionDelay = 0.5 UMAnalyticsConfig.sharedInstance().appKey = "59c733a1c895764c1100001c" UMAnalyticsConfig.sharedInstance().channelId = "App Store" MobClick.start(withConfigure: UMAnalyticsConfig.sharedInstance()) let version = Bundle.main.infoDictionary!["CFBundleShortVersionString"] MobClick.setAppVersion(version as! String) MobClick.setEncryptEnabled(true) MobClick.setLogEnabled(true) do { Client.shared = try Client(dsn: "https://9fa2ea4914b74970a52473d16f103cfb:[email protected]/282832") try Client.shared?.startCrashHandler() } catch let error { print("\(error)") // Wrong DSN or KSCrash not installed } return true } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print(error) } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let provider = DeviceProvider() provider.regitserDevice(token: deviceToken.hexString) } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { return true } }
apache-2.0
a7f43aa1d1cdc36b63248f494da9c8c4
31.527027
167
0.708766
4.952675
false
true
false
false
rockbruno/swiftshield
Sources/SwiftShieldCore/StringHelpers.swift
1
2544
import Foundation typealias RegexClosure = ((NSTextCheckingResult) -> String?) func firstMatch(for regex: String, in text: String) -> String? { matches(for: regex, in: text).first } func matches(for regex: String, in text: String) -> [String] { do { let regex = try NSRegularExpression(pattern: regex) let nsString = text as NSString let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length)) return results.map { nsString.substring(with: $0.range) } } catch { print("invalid regex: \(error.localizedDescription)") return [] } } extension String { func match(regex: String) -> [NSTextCheckingResult] { let regex = try! NSRegularExpression(pattern: regex, options: [.caseInsensitive]) let nsString = self as NSString return regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length)) } } extension String { static var storyboardClassNameRegex: String { "((?<=customClass=\").*?(?=\" customModule)|(?<=action selector=\").*?(?=:\"))" } } extension String { var removingParameterInformation: String { components(separatedBy: "(").first ?? self } } extension String { private var spacedFolderPlaceholder: String { "\u{0}" } var replacingEscapedSpaces: String { replacingOccurrences(of: "\\ ", with: spacedFolderPlaceholder) } var removeEscapedSpaces: String { replacingOccurrences(of: "\\ ", with: " ") } var removingPlaceholder: String { replacingOccurrences(of: spacedFolderPlaceholder, with: " ") } } extension NSTextCheckingResult { func captureGroup(_ index: Int, originalString: String) -> String { let range = captureGroupRange(index, originalString: originalString) let substring = originalString[range] return String(substring) } func captureGroupRange(_ index: Int, originalString: String) -> Range<String.Index> { let groupRange = range(at: index) let groupStartIndex = originalString.index(originalString.startIndex, offsetBy: groupRange.location) let groupEndIndex = originalString.index(groupStartIndex, offsetBy: groupRange.length) return groupStartIndex ..< groupEndIndex } } extension String { /// Considers emoji scalars when counting. var utf8Count: Int { return utf8.count } }
gpl-3.0
44b2f478cc5a758408112ba90977fd89
30.407407
99
0.632862
4.608696
false
false
false
false
nerdyc/SwiftEmoji
SwiftEmojiTests/SwiftEmojiTests.swift
1
3500
// // SwiftEmojiTests.swift // SwiftEmojiTests // // Created by Christian Niles on 4/25/16. // Copyright © 2016 Christian Niles. All rights reserved. // import XCTest import SwiftEmoji class SwiftEmojiTests: XCTestCase { func test_SingleEmoji() { let matches = Emoji.SingleEmojiRegex.extractMatchesInString( "simple: 👍; fitzpatrick: 👎🏼 flag: 🇨🇦 keycap: 9️⃣0️⃣ sequence 👨‍👩‍👧‍👧 sequence with combining mark: 👨‍👩‍👧‍👦⃠" ) XCTAssertEqual(matches, ["👍", "👎🏼", "🇨🇦", "9️⃣", "0️⃣", "👨‍👩‍👧‍👧", "👨‍👩‍👧‍👦⃠"]) } func test_MultiEmoji() { let matches = Emoji.MultiEmojiRegex.extractMatchesInString( "simple: 👍 👎🏼😳 flag: 🇨🇦 keycap: 9️⃣0️⃣ sequence 👨‍👩‍👧‍👧 sequence with combining mark: 👨‍👩‍👧‍👦⃠" ) XCTAssertEqual(matches, ["👍", "👎🏼😳", "🇨🇦", "9️⃣0️⃣", "👨‍👩‍👧‍👧", "👨‍👩‍👧‍👦⃠"]) } func test_MultiEmojiAndWhitespace() { let matches = Emoji.MultiEmojiAndWhitespaceRegex.extractMatchesInString( "simple: 👍 👎🏼😳 flag: 🇨🇦 keycap: 9️⃣0️⃣ no key caps: 90 sequence: 👨‍👩‍👧‍👧 sequence with combining mark: 👨‍👩‍👧‍👦⃠" ) // note that whitespace is also included XCTAssertEqual(matches, [" 👍 👎🏼😳 ", " 🇨🇦 ", " 9️⃣0️⃣ ", " 👨‍👩‍👧‍👧 ", " 👨‍👩‍👧‍👦⃠"]) } func test_isPureEmojiString() { // TEST: Single character emoji XCTAssertTrue(Emoji.isPureEmojiString("😔")) XCTAssertTrue(Emoji.isPureEmojiString("🇨🇦")) // flag sequence XCTAssertTrue(Emoji.isPureEmojiString("👨‍👨‍👧‍👧")) // family sequence XCTAssertTrue(Emoji.isPureEmojiString("0️⃣")) // keycap sequence XCTAssertTrue(Emoji.isPureEmojiString("👶🏿")) // skin tone sequence XCTAssertTrue(Emoji.isPureEmojiString("👨‍👩‍👧‍👦⃠")) // sequence with combining mark // TEST: Multiple character emoji XCTAssertTrue(Emoji.isPureEmojiString("😔😔")) // TEST: Whitespace is ignored XCTAssertTrue(Emoji.isPureEmojiString(" 😔 😔 ")) // TEST: A mix of emoji and text returns false XCTAssertFalse(Emoji.isPureEmojiString("👌 job!")) // TEST: No emoji at all XCTAssertFalse(Emoji.isPureEmojiString("Nice job!")) // TEST: Emoji without modifiers XCTAssertFalse(Emoji.isPureEmojiString("#")) XCTAssertFalse(Emoji.isPureEmojiString("0")) } func test_Emoji30() { XCTAssertTrue(Emoji.isPureEmojiString("🕵🏾")) XCTAssertTrue(Emoji.isPureEmojiString("🤰")) // pregnant woman, unicode 9.0 } } // ================================================================================================= // MARK:- Test Helpers extension NSRegularExpression { func extractMatchesInString(_ string:String) -> [String] { let range = NSRange(location: 0, length: string.utf16.count) return matches(in: string, options: [], range: range).map() { result in (string as NSString).substring(with: result.range) } } }
mit
493abe7c1260b540473b1b7719cc1243
36.073171
124
0.559211
4.064171
false
true
false
false
hyouuu/Centa
Sources/App/Middleware/CorsMiddleware.swift
1
926
// // CorsMiddleware.swift // Centa // // Created by Shawn Gong on 11/15/16. // // import Foundation import HTTP final class CorsMiddleware: Middleware { func respond(to request: Request, chainingTo next: Responder) throws -> Response { let response: Response if request.isPreflight { response = "".makeResponse() } else { response = try next.respond(to: request) } response.headers["Access-Control-Allow-Origin"] = request.headers["Origin"] ?? "*"; response.headers["Access-Control-Allow-Headers"] = "X-Requested-With, Origin, Content-Type, Accept" response.headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, OPTIONS, DELETE, PATCH" return response } } extension Request { var isPreflight: Bool { return method == .options && headers["Access-Control-Request-Method"] != nil } }
mit
cb06ca25dc3f65495cee205ab2594aca
27.060606
107
0.62095
4.026087
false
false
false
false
barbrobmich/linkbase
LinkBase/LinkBase/ResultsDetailViewController.swift
1
4059
// // ResultsDetailViewController.swift // LinkBase // // Created by Barbara Ristau on 3/27/17. // Copyright © 2017 barbrobmich. All rights reserved. // import UIKit class ResultsDetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var challengeGame: ScoreCard! var resultsView: String! override func viewDidLoad() { super.viewDidLoad() let appDelegate = UIApplication.shared.delegate as! AppDelegate challengeGame = appDelegate.challengeGame tableView.dataSource = self tableView.delegate = self } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var count: Int = 0 if resultsView == "Tech" { count = challengeGame.techQuestionsAnswered.count } else if resultsView == "Comms" { count = challengeGame.commsQuestionsAnswered.count } return count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ResultsCell", for: indexPath) as! ResultsCell if resultsView == "Tech" { if challengeGame.techQuestionsAnswered.count != 0{ let question = challengeGame.techQuestionsAnswered[indexPath.row] cell.questionLabel.text = String(describing: question.question) cell.dateLabel.text = String(describing: question.date!) cell.scoreLabel.text = String(describing: question.points) cell.pendingReviewLabel.isHidden = true cell.overallTextLabel.isHidden = true cell.overallScoreLabel.isHidden = true cell.styleTextLabel.isHidden = true cell.styleScoreLabel.isHidden = true cell.relevanceTextLabel.isHidden = true cell.relevanceScoreLabel.isHidden = true } // else - display an alert stating that there are no questions } else if resultsView == "Comms" { if challengeGame.commsQuestionsAnswered.count != 0 { let question = challengeGame.commsQuestionsAnswered[indexPath.row] cell.questionLabel.text = String(describing: question.question) cell.dateLabel.text = String(describing: question.date!) cell.scoreLabel.text = String(describing: question.points.submit + question.points.overall + question.points.style + question.points.relevance) if question.points.overall == 0 { cell.pendingReviewLabel.text = "Grades not yet available" cell.overallTextLabel.isHidden = true cell.overallScoreLabel.isHidden = true cell.styleTextLabel.isHidden = true cell.styleScoreLabel.isHidden = true cell.relevanceTextLabel.isHidden = true cell.relevanceScoreLabel.isHidden = true } else { cell.overallScoreLabel.text = String(describing: question.points.overall) cell.styleScoreLabel.text = String(describing: question.points.style) cell.relevanceScoreLabel.text = String(describing: question.points.relevance) } } // else - display an alert stating that there are no questions } return cell } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
74c99c0963320f18cff80012249db6d0
37.647619
159
0.612617
5.469003
false
false
false
false
lumenlunae/SwiftSpriter
SwiftSpriter/Classes/Model/SpriterConstants.swift
1
1081
// // SpriterConstants.swift // SwiftSpriter // // Created by Matt on 8/27/16. // Copyright © 2016 BiminiRoad. All rights reserved. // import Foundation import UIKit let SpriterRefNoParentValue: Int = -1 let SpriterObjectNoPivotValue: CGFloat = CGFloat.leastNormalMagnitude enum SpriterObjectType: String { case sprite case bone case box case point case sound case entity case variable } enum SpriterSpinType: Int { case none = 0 case counterClockwise = -1 case clockwise = 1 } enum SpriterCurveType: Int { case instant = 0 case linear case quadratic case cubic init?(string: String) { switch string.lowercased() { case "instant": self = .instant case "linear": self = .linear case "quadratic": self = .quadratic case "cubic": self = .cubic default: return nil } } } enum SpriterSpatialType: Int { case sprite = 0 case node case collisionBox case point case sound } protocol SpriterParseable { init?(data: AnyObject) }
mit
ea0715e6c2c33358c1fc98322dc60e7e
17.62069
69
0.644444
3.857143
false
false
false
false
LinShiwei/WeatherDemo
Carthage/Checkouts/Alamofire/Tests/MultipartFormDataTests.swift
1
38297
// // MultipartFormDataTests.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Alamofire import Foundation import XCTest struct EncodingCharacters { static let crlf = "\r\n" } struct BoundaryGenerator { enum BoundaryType { case initial, encapsulated, final } static func boundary(forBoundaryType boundaryType: BoundaryType, boundaryKey: String) -> String { let boundary: String switch boundaryType { case .initial: boundary = "--\(boundaryKey)\(EncodingCharacters.crlf)" case .encapsulated: boundary = "\(EncodingCharacters.crlf)--\(boundaryKey)\(EncodingCharacters.crlf)" case .final: boundary = "\(EncodingCharacters.crlf)--\(boundaryKey)--\(EncodingCharacters.crlf)" } return boundary } static func boundaryData(boundaryType: BoundaryType, boundaryKey: String) -> Data { return BoundaryGenerator.boundary( forBoundaryType: boundaryType, boundaryKey: boundaryKey ).data(using: String.Encoding.utf8, allowLossyConversion: false)! } } private func temporaryFileURL() -> URL { let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.test/multipart.form.data") let fileManager = FileManager.default do { try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) } catch { // No-op - will cause tests to fail, not crash } let fileName = UUID().uuidString let fileURL = directoryURL.appendingPathComponent(fileName) return fileURL } // MARK: - class MultipartFormDataPropertiesTestCase: BaseTestCase { func testThatContentTypeContainsBoundary() { // Given let multipartFormData = MultipartFormData() // When let boundary = multipartFormData.boundary // Then let expectedContentType = "multipart/form-data; boundary=\(boundary)" XCTAssertEqual(multipartFormData.contentType, expectedContentType, "contentType should match expected value") } func testThatContentLengthMatchesTotalBodyPartSize() { // Given let multipartFormData = MultipartFormData() let data1 = "Lorem ipsum dolor sit amet.".data(using: String.Encoding.utf8, allowLossyConversion: false)! let data2 = "Vim at integre alterum.".data(using: String.Encoding.utf8, allowLossyConversion: false)! // When multipartFormData.append(data1, withName: "data1") multipartFormData.append(data2, withName: "data2") // Then let expectedContentLength = UInt64(data1.count + data2.count) XCTAssertEqual(multipartFormData.contentLength, expectedContentLength, "content length should match expected value") } } // MARK: - class MultipartFormDataEncodingTestCase: BaseTestCase { let crlf = EncodingCharacters.crlf func testEncodingDataBodyPart() { // Given let multipartFormData = MultipartFormData() let data = "Lorem ipsum dolor sit amet.".data(using: String.Encoding.utf8, allowLossyConversion: false)! multipartFormData.append(data, withName: "data") var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary let expectedData = ( BoundaryGenerator.boundary(forBoundaryType: .initial, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"data\"\(crlf)\(crlf)" + "Lorem ipsum dolor sit amet." + BoundaryGenerator.boundary(forBoundaryType: .final, boundaryKey: boundary) ).data(using: String.Encoding.utf8, allowLossyConversion: false)! XCTAssertEqual(encodedData, expectedData, "encoded data should match expected data") } } func testEncodingMultipleDataBodyParts() { // Given let multipartFormData = MultipartFormData() let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)! let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)! let emojiData = "😃👍🏻🍻🎉".data(using: String.Encoding.utf8, allowLossyConversion: false)! multipartFormData.append(frenchData, withName: "french") multipartFormData.append(japaneseData, withName: "japanese", mimeType: "text/plain") multipartFormData.append(emojiData, withName: "emoji", mimeType: "text/plain") var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary let expectedData = ( BoundaryGenerator.boundary(forBoundaryType: .initial, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"french\"\(crlf)\(crlf)" + "français" + BoundaryGenerator.boundary(forBoundaryType: .encapsulated, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"japanese\"\(crlf)" + "Content-Type: text/plain\(crlf)\(crlf)" + "日本語" + BoundaryGenerator.boundary(forBoundaryType: .encapsulated, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"emoji\"\(crlf)" + "Content-Type: text/plain\(crlf)\(crlf)" + "😃👍🏻🍻🎉" + BoundaryGenerator.boundary(forBoundaryType: .final, boundaryKey: boundary) ).data(using: String.Encoding.utf8, allowLossyConversion: false)! XCTAssertEqual(encodedData, expectedData, "encoded data should match expected data") } } func testEncodingFileBodyPart() { // Given let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") multipartFormData.append(unicornImageURL, withName: "unicorn") var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary var expectedData = Data() expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedData.append(( "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + "Content-Type: image/png\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedData.append(try! Data(contentsOf: unicornImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(encodedData, expectedData, "data should match expected data") } } func testEncodingMultipleFileBodyParts() { // Given let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") multipartFormData.append(unicornImageURL, withName: "unicorn") multipartFormData.append(rainbowImageURL, withName: "rainbow") var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary var expectedData = Data() expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedData.append(( "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + "Content-Type: image/png\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedData.append(try! Data(contentsOf: unicornImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedData.append(( "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)" + "Content-Type: image/jpeg\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedData.append(try! Data(contentsOf: rainbowImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(encodedData, expectedData, "data should match expected data") } } func testEncodingStreamBodyPart() { // Given let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let unicornDataLength = UInt64((try! Data(contentsOf: unicornImageURL)).count) let unicornStream = InputStream(url: unicornImageURL)! multipartFormData.append( unicornStream, withLength: unicornDataLength, name: "unicorn", fileName: "unicorn.png", mimeType: "image/png" ) var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary var expectedData = Data() expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedData.append(( "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + "Content-Type: image/png\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedData.append(try! Data(contentsOf: unicornImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(encodedData, expectedData, "data should match expected data") } } func testEncodingMultipleStreamBodyParts() { // Given let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let unicornDataLength = UInt64((try! Data(contentsOf: unicornImageURL)).count) let unicornStream = InputStream(url: unicornImageURL)! let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") let rainbowDataLength = UInt64((try! Data(contentsOf: rainbowImageURL)).count) let rainbowStream = InputStream(url: rainbowImageURL)! multipartFormData.append( unicornStream, withLength: unicornDataLength, name: "unicorn", fileName: "unicorn.png", mimeType: "image/png" ) multipartFormData.append( rainbowStream, withLength: rainbowDataLength, name: "rainbow", fileName: "rainbow.jpg", mimeType: "image/jpeg" ) var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary var expectedData = Data() expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedData.append(( "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + "Content-Type: image/png\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedData.append(try! Data(contentsOf: unicornImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedData.append(( "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)" + "Content-Type: image/jpeg\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedData.append(try! Data(contentsOf: rainbowImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(encodedData, expectedData, "data should match expected data") } } func testEncodingMultipleBodyPartsWithVaryingTypes() { // Given let multipartFormData = MultipartFormData() let loremData = "Lorem ipsum.".data(using: String.Encoding.utf8, allowLossyConversion: false)! let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") let rainbowDataLength = UInt64((try! Data(contentsOf: rainbowImageURL)).count) let rainbowStream = InputStream(url: rainbowImageURL)! multipartFormData.append(loremData, withName: "lorem") multipartFormData.append(unicornImageURL, withName: "unicorn") multipartFormData.append( rainbowStream, withLength: rainbowDataLength, name: "rainbow", fileName: "rainbow.jpg", mimeType: "image/jpeg" ) var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary var expectedData = Data() expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedData.append(( "Content-Disposition: form-data; name=\"lorem\"\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedData.append(loremData) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedData.append(( "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + "Content-Type: image/png\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedData.append(try! Data(contentsOf: unicornImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedData.append(( "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)" + "Content-Type: image/jpeg\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedData.append(try! Data(contentsOf: rainbowImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(encodedData, expectedData, "data should match expected data") } } } // MARK: - class MultipartFormDataWriteEncodedDataToDiskTestCase: BaseTestCase { let crlf = EncodingCharacters.crlf func testWritingEncodedDataBodyPartToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let data = "Lorem ipsum dolor sit amet.".data(using: String.Encoding.utf8, allowLossyConversion: false)! multipartFormData.append(data, withName: "data") var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary let expectedFileData = ( BoundaryGenerator.boundary(forBoundaryType: .initial, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"data\"\(crlf)\(crlf)" + "Lorem ipsum dolor sit amet." + BoundaryGenerator.boundary(forBoundaryType: .final, boundaryKey: boundary) ).data(using: String.Encoding.utf8, allowLossyConversion: false)! XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } func testWritingMultipleEncodedDataBodyPartsToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let frenchData = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)! let japaneseData = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)! let emojiData = "😃👍🏻🍻🎉".data(using: String.Encoding.utf8, allowLossyConversion: false)! multipartFormData.append(frenchData, withName: "french") multipartFormData.append(japaneseData, withName: "japanese") multipartFormData.append(emojiData, withName: "emoji") var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary let expectedFileData = ( BoundaryGenerator.boundary(forBoundaryType: .initial, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"french\"\(crlf)\(crlf)" + "français" + BoundaryGenerator.boundary(forBoundaryType: .encapsulated, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"japanese\"\(crlf)\(crlf)" + "日本語" + BoundaryGenerator.boundary(forBoundaryType: .encapsulated, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"emoji\"\(crlf)\(crlf)" + "😃👍🏻🍻🎉" + BoundaryGenerator.boundary(forBoundaryType: .final, boundaryKey: boundary) ).data(using: String.Encoding.utf8, allowLossyConversion: false)! XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } func testWritingEncodedFileBodyPartToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") multipartFormData.append(unicornImageURL, withName: "unicorn") var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary var expectedFileData = Data() expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedFileData.append(( "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + "Content-Type: image/png\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedFileData.append(try! Data(contentsOf: unicornImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } func testWritingMultipleEncodedFileBodyPartsToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") multipartFormData.append(unicornImageURL, withName: "unicorn") multipartFormData.append(rainbowImageURL, withName: "rainbow") var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary var expectedFileData = Data() expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedFileData.append(( "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + "Content-Type: image/png\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedFileData.append(try! Data(contentsOf: unicornImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedFileData.append(( "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)" + "Content-Type: image/jpeg\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedFileData.append(try! Data(contentsOf: rainbowImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } func testWritingEncodedStreamBodyPartToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let unicornDataLength = UInt64((try! Data(contentsOf: unicornImageURL)).count) let unicornStream = InputStream(url: unicornImageURL)! multipartFormData.append( unicornStream, withLength: unicornDataLength, name: "unicorn", fileName: "unicorn.png", mimeType: "image/png" ) var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary var expectedFileData = Data() expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedFileData.append(( "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + "Content-Type: image/png\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedFileData.append(try! Data(contentsOf: unicornImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } func testWritingMultipleEncodedStreamBodyPartsToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let unicornDataLength = UInt64((try! Data(contentsOf: unicornImageURL)).count) let unicornStream = InputStream(url: unicornImageURL)! let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") let rainbowDataLength = UInt64((try! Data(contentsOf: rainbowImageURL)).count) let rainbowStream = InputStream(url: rainbowImageURL)! multipartFormData.append( unicornStream, withLength: unicornDataLength, name: "unicorn", fileName: "unicorn.png", mimeType: "image/png" ) multipartFormData.append( rainbowStream, withLength: rainbowDataLength, name: "rainbow", fileName: "rainbow.jpg", mimeType: "image/jpeg" ) var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary var expectedFileData = Data() expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedFileData.append(( "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + "Content-Type: image/png\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedFileData.append(try! Data(contentsOf: unicornImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedFileData.append(( "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)" + "Content-Type: image/jpeg\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedFileData.append(try! Data(contentsOf: rainbowImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } func testWritingMultipleEncodedBodyPartsWithVaryingTypesToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let loremData = "Lorem ipsum.".data(using: String.Encoding.utf8, allowLossyConversion: false)! let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") let rainbowDataLength = UInt64((try! Data(contentsOf: rainbowImageURL)).count) let rainbowStream = InputStream(url: rainbowImageURL)! multipartFormData.append(loremData, withName: "lorem") multipartFormData.append(unicornImageURL, withName: "unicorn") multipartFormData.append( rainbowStream, withLength: rainbowDataLength, name: "rainbow", fileName: "rainbow.jpg", mimeType: "image/jpeg" ) var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary var expectedFileData = Data() expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedFileData.append(( "Content-Disposition: form-data; name=\"lorem\"\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedFileData.append(loremData) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedFileData.append(( "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + "Content-Type: image/png\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedFileData.append(try! Data(contentsOf: unicornImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedFileData.append(( "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)" + "Content-Type: image/jpeg\(crlf)\(crlf)" ).data(using: String.Encoding.utf8, allowLossyConversion: false)! ) expectedFileData.append(try! Data(contentsOf: rainbowImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } } // MARK: - class MultipartFormDataFailureTestCase: BaseTestCase { func testThatAppendingFileBodyPartWithInvalidLastPathComponentReturnsError() { // Given let fileURL = NSURL(string: "") as! URL let multipartFormData = MultipartFormData() multipartFormData.append(fileURL, withName: "empty_data") var encodingError: Error? // When do { _ = try multipartFormData.encode() } catch { encodingError = error } // Then XCTAssertNotNil(encodingError, "encoding error should not be nil") if let error = encodingError as? AFError { XCTAssertTrue(error.isBodyPartFilenameInvalid) let expectedFailureReason = "The URL provided does not have a valid filename: \(fileURL)" XCTAssertEqual(error.localizedDescription, expectedFailureReason, "failure reason does not match expected value") } else { XCTFail("Error should be AFError.") } } func testThatAppendingFileBodyPartThatIsNotFileURLReturnsError() { // Given let fileURL = URL(string: "https://example.com/image.jpg")! let multipartFormData = MultipartFormData() multipartFormData.append(fileURL, withName: "empty_data") var encodingError: Error? // When do { _ = try multipartFormData.encode() } catch { encodingError = error } // Then XCTAssertNotNil(encodingError, "encoding error should not be nil") if let error = encodingError as? AFError { XCTAssertTrue(error.isBodyPartURLInvalid) let expectedFailureReason = "The URL provided is not a file URL: \(fileURL)" XCTAssertEqual(error.localizedDescription, expectedFailureReason, "error failure reason does not match expected value") } else { XCTFail("Error should be AFError.") } } func testThatAppendingFileBodyPartThatIsNotReachableReturnsError() { // Given let filePath = (NSTemporaryDirectory() as NSString).appendingPathComponent("does_not_exist.jpg") let fileURL = URL(fileURLWithPath: filePath) let multipartFormData = MultipartFormData() multipartFormData.append(fileURL, withName: "empty_data") var encodingError: Error? // When do { _ = try multipartFormData.encode() } catch { encodingError = error } // Then XCTAssertNotNil(encodingError, "encoding error should not be nil") if let error = encodingError as? AFError { XCTAssertTrue(error.isBodyPartFileNotReachableWithError) } else { XCTFail("Error should be AFError.") } } func testThatAppendingFileBodyPartThatIsDirectoryReturnsError() { // Given let directoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) let multipartFormData = MultipartFormData() multipartFormData.append(directoryURL, withName: "empty_data", fileName: "empty", mimeType: "application/octet") var encodingError: Error? // When do { _ = try multipartFormData.encode() } catch { encodingError = error } // Then XCTAssertNotNil(encodingError, "encoding error should not be nil") if let error = encodingError as? AFError { XCTAssertTrue(error.isBodyPartFileIsDirectory) let expectedFailureReason = "The URL provided is a directory: \(directoryURL)" XCTAssertEqual(error.localizedDescription, expectedFailureReason, "error failure reason does not match expected value") } else { XCTFail("Error should be AFError.") } } func testThatWritingEncodedDataToExistingFileURLFails() { // Given let fileURL = temporaryFileURL() var writerError: Error? do { try "dummy data".write(to: fileURL, atomically: true, encoding: String.Encoding.utf8) } catch { writerError = error } let multipartFormData = MultipartFormData() let data = "Lorem ipsum dolor sit amet.".data(using: String.Encoding.utf8, allowLossyConversion: false)! multipartFormData.append(data, withName: "data") var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(writerError, "writer error should be nil") XCTAssertNotNil(encodingError, "encoding error should not be nil") if let encodingError = encodingError as? AFError { XCTAssertTrue(encodingError.isOutputStreamFileAlreadyExists) } } func testThatWritingEncodedDataToBadURLFails() { // Given let fileURL = URL(string: "/this/is/not/a/valid/url")! let multipartFormData = MultipartFormData() let data = "Lorem ipsum dolor sit amet.".data(using: String.Encoding.utf8, allowLossyConversion: false)! multipartFormData.append(data, withName: "data") var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNotNil(encodingError, "encoding error should not be nil") if let encodingError = encodingError as? AFError { XCTAssertTrue(encodingError.isOutputStreamURLInvalid) } } }
mit
f9963c9d5166c5ff45b0f6cc34717697
38.068507
131
0.630768
5.180179
false
false
false
false
jeffreybergier/WaterMe2
WaterMe/WaterMe/Categories/UIAlertController+UserFacingError.swift
1
4919
// // UIAlertController+UserFacingError.swift // WaterMe // // Created by Jeffrey Bergier on 9/20/18. // Copyright © 2018 Saturday Apps. // // This file is part of WaterMe. Simple Plant Watering Reminders for iOS. // // WaterMe 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. // // WaterMe 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 WaterMe. If not, see <http://www.gnu.org/licenses/>. // import Calculate import Datum import UIKit extension UIAlertController { typealias UserSelection = (RecoveryAction) -> Void class func presentAlertVC(for error: UserFacingError, over presentingVC: UIViewController, from barButtonItem: UIBarButtonItem? = nil, completionHandler completion: UserSelection? = nil) { let recoveryActions = error.recoveryActions.map() { recoveryOption -> UIAlertAction in let action = UIAlertAction(title: recoveryOption.title, style: recoveryOption.actionStyle) { _ in recoveryOption.automaticExecution?() completion?(recoveryOption) } return action } let actionSheet: UIAlertController if let bbi = barButtonItem { actionSheet = .init(title: error.title, message: error.message, preferredStyle: .actionSheet) actionSheet.popoverPresentationController?.barButtonItem = bbi } else { actionSheet = .init(title: error.title, message: error.message, preferredStyle: .alert) } recoveryActions.forEach(actionSheet.addAction) presentingVC.present(actionSheet, animated: true, completion: nil) } } extension UIAlertController { convenience init(localizedDeleteConfirmationAlertPresentedFrom sender: PopoverSender?, userConfirmationHandler confirmed: ((Bool) -> Void)?) { let style: UIAlertController.Style = sender != nil ? .actionSheet : .alert self.init(title: nil, message: LocalizedString.deleteAlertMessage, preferredStyle: style) let delete = UIAlertAction(title: LocalizedString.buttonTitleDelete, style: .destructive) { _ in confirmed?(true) } let dont = UIAlertAction(title: LocalizedString.buttonTitleDontDelete, style: .cancel) { _ in confirmed?(false) } self.addAction(delete) self.addAction(dont) guard let sender = sender else { return } switch sender { case .right(let bbi): self.popoverPresentationController?.barButtonItem = bbi case .left(let view): self.popoverPresentationController?.sourceView = view self.popoverPresentationController?.sourceRect = view.bounds.centerRect self.popoverPresentationController?.permittedArrowDirections = [.up, .down] } } } extension UIAlertController { convenience init(localizedSiriShortcutsUnavailableAlertWithCompletionHandler completion: (() -> Void)?) { self.init(title: UserActivityConfigurator.LocalizedString.siriShortcutsUnavailableTitle, message: UserActivityConfigurator.LocalizedString.siriShortcutsUnavailableMessage, preferredStyle: .alert) let dismiss = UIAlertAction(title: LocalizedString.buttonTitleDismiss, style: .cancel) { _ in completion?() } self.addAction(dismiss) } } extension UIAlertController { class func newLocalizedDarkModeImproperlyConfigured() -> UIAlertController? { if #available(iOS 13.0, *) { return nil } else { let ud = UserDefaults.standard guard ud.darkMode != .system else { return nil } let alertVC = UIAlertController(title: LocalizedString.darkModeImproperTitle, message: LocalizedString.darkModeImproperMessage, preferredStyle: .alert) let dismiss = UIAlertAction(title: LocalizedString.buttonTitleDismiss, style: .cancel) { _ in ud.darkMode = .system } alertVC.addAction(dismiss) return alertVC } } }
gpl-3.0
5595b0c3443192f27a4e860e6838457a
40.677966
109
0.624847
5.380744
false
false
false
false
ascode/JF-Design-Patterns
JF-IOS-Swift_Design-Patterns_and_Demos/JF-IOS-Swift_Design-Patterns_and_Demos/AppDelegate.swift
1
4640
// // AppDelegate.swift // JF-IOS-Swift_Design-Patterns_and_Demos // // Created by 金飞 on 30/12/2016. // Copyright © 2016 jl. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "JF_IOS_Swift_Design_Patterns_and_Demos") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
artistic-2.0
84e3f56b7ecde39202c977965208fe17
48.83871
285
0.686516
5.736386
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/Vendor/SCSiriWaveformView.swift
1
6768
// // Wire // Copyright (C) 2020 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/. // // This module of the Wire Software uses software code from Stefan Ceriu // governed by the MIT license (https://github.com/stefanceriu/SCSiriWaveformView). // // // SCSiriWaveformView.m // SCSiriWaveformView // // Created by Stefan Ceriu on 12/04/2014. // Copyright (C) 2013 Stefan Ceriu. // Released under the MIT license. // // // Copyright (C) 2013 Stefan Ceriu // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial // portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE // AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit private let kDefaultFrequency: Float = 1.5 private let kDefaultAmplitude: Float = 1 private let kDefaultIdleAmplitude: Float = 0.01 private let kDefaultNumberOfWaves: UInt = 5 private let kDefaultPhaseShift: Float = -0.15 private let kDefaultDensity: Float = 5 private let kDefaultPrimaryLineWidth: CGFloat = 3 private let kDefaultSecondaryLineWidth: CGFloat = 1 final class SCSiriWaveformView: UIView { /* * The total number of waves * Default: 5 */ var numberOfWaves: UInt = 0 /* * Color to use when drawing the waves * Default: white */ var waveColor: UIColor = .white /* * Line width used for the proeminent wave * Default: 3f */ var primaryWaveLineWidth: CGFloat = 0 /* * Line width used for all secondary waves * Default: 1f */ var secondaryWaveLineWidth: CGFloat = 0 /* * The amplitude that is used when the incoming amplitude is near zero. * Setting a value greater 0 provides a more vivid visualization. * Default: 01 */ var idleAmplitude: Float = 0 /* * The frequency of the sinus wave. The higher the value, the more sinus wave peaks you will have. * Default: 1.5 */ var frequency: Float = 0 /* * The current amplitude */ private(set) var amplitude: Float = 0 /* * The lines are joined stepwise, the more dense you draw, the more CPU power is used. * Default: 5 */ var density: Float = 0 /* * The phase shift that will be applied with each level setting * Change this to modify the animation speed or direction * Default: -0.15 */ var phaseShift: Float = 0 private var phase: Float = 0 init() { super.init(frame: .zero) setup() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { frequency = kDefaultFrequency amplitude = kDefaultAmplitude idleAmplitude = kDefaultIdleAmplitude numberOfWaves = kDefaultNumberOfWaves phaseShift = kDefaultPhaseShift density = kDefaultDensity primaryWaveLineWidth = kDefaultPrimaryLineWidth secondaryWaveLineWidth = kDefaultSecondaryLineWidth } /* * Tells the waveform to redraw itself using the given level (normalized value) */ func update(withLevel level: Float) { phase += phaseShift amplitude = fmax(level, idleAmplitude) setNeedsDisplay() } // Thanks to Raffael Hannemann https://github.com/raffael/SISinusWaveView override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() context?.clear(bounds) backgroundColor?.set() context?.fill(rect) // We draw multiple sinus waves, with equal phases but altered amplitudes, multiplied by a parable function. let sinConst: Float = 2 * Float.pi * frequency let halfHeight: Float = Float(bounds.height) / 2 let width: Float = Float(bounds.width) let maxAmplitude: Float = halfHeight - 4 // 4 corresponds to twice the stroke width let mid: Float = width / 2 for i in 0..<numberOfWaves { let context = UIGraphicsGetCurrentContext() context?.setLineWidth((i == 0 ? primaryWaveLineWidth : secondaryWaveLineWidth)) // Progress is a value between 1 and -0.5, determined by the current wave idx, which is used to alter the wave's amplitude. let progress: Float = 1 - Float(i) / Float(numberOfWaves) let normedAmplitude: Float = (1.5 * progress - 0.5) * amplitude let multiplier: Float = min(1, (progress / 3 * 2) + 1 / 3) waveColor.withAlphaComponent(CGFloat(multiplier) * waveColor.cgColor.alpha).set() var x: Float = 0 while x < width + density { // We use a parable to scale the sinus wave, that has its peak in the middle of the view. let scaling: Float = -pow(1 / mid * (x - mid), 2) + 1 let sin: Float = sinf(sinConst * (x / width) + phase) let y: Float = scaling * maxAmplitude * normedAmplitude * sin + halfHeight let point = CGPoint(x: CGFloat(x), y: CGFloat(y)) if x == 0 { context?.move(to: point) } else { context?.addLine(to: point) } x += density } context?.strokePath() } } }
gpl-3.0
31b6d1233f92cb7b8557d305e481934d
33.707692
135
0.656472
4.411995
false
false
false
false
yuanhoujun/firefox-ios
Client/Frontend/Home/HistoryPanel.swift
4
14698
/* 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 UIKit import Shared import Storage import XCGLogger private let log = XCGLogger.defaultInstance() private func getDate(#dayOffset: Int) -> NSDate { let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let nowComponents = calendar.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay, fromDate: NSDate()) let today = calendar.dateFromComponents(nowComponents)! return calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: dayOffset, toDate: today, options: nil)! } private typealias SectionNumber = Int private typealias CategoryNumber = Int private typealias CategorySpec = (section: SectionNumber?, rows: Int, offset: Int) class HistoryPanel: SiteTableViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? = nil private let QueryLimit = 100 private let NumSections = 4 private let Today = getDate(dayOffset: 0) private let Yesterday = getDate(dayOffset: -1) private let ThisWeek = getDate(dayOffset: -7) // Category number (index) -> (UI section, row count, cursor offset). private var categories: [CategorySpec] = [CategorySpec]() // Reverse lookup from UI section to data category. private var sectionLookup = [SectionNumber: CategoryNumber]() private lazy var defaultIcon: UIImage = { return UIImage(named: "defaultFavicon")! }() var refreshControl: UIRefreshControl? init() { super.init(nibName: nil, bundle: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "firefoxAccountChanged:", name: NotificationFirefoxAccountChanged, object: nil) } override func viewDidLoad() { super.viewDidLoad() let refresh = UIRefreshControl() refresh.attributedTitle = NSAttributedString(string: NSLocalizedString("Pull to Sync", comment: "The pull-to-refresh string for syncing in the history panel.")) refresh.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) self.refreshControl = refresh self.tableView.addSubview(refresh) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) } func firefoxAccountChanged(notification: NSNotification) { if notification.name == NotificationFirefoxAccountChanged { refresh() } } @objc func refresh() { self.refreshControl?.beginRefreshing() profile.syncManager.syncHistory().uponQueue(dispatch_get_main_queue()) { result in if result.isSuccess { self.reloadData() } // Always end refreshing, even if we failed! self.refreshControl?.endRefreshing() } } private func refetchData() -> Deferred<Result<Cursor<Site>>> { return profile.history.getSitesByLastVisit(QueryLimit) } private func setData(data: Cursor<Site>) { self.data = data self.computeSectionOffsets() } override func reloadData() { self.refetchData().uponQueue(dispatch_get_main_queue()) { result in if let data = result.successValue { self.setData(data) self.tableView.reloadData() } // Always end refreshing, even if we failed! self.refreshControl?.endRefreshing() // TODO: error handling. } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) let category = self.categories[indexPath.section] if let site = data[indexPath.row + category.offset] { if let cell = cell as? TwoLineTableViewCell { cell.setLines(site.title, detailText: site.url) cell.imageView?.setIcon(site.icon, withPlaceholder: self.defaultIcon) } } return cell } private func siteForIndexPath(indexPath: NSIndexPath) -> Site? { let offset = self.categories[sectionLookup[indexPath.section]!].offset return data[indexPath.row + offset] } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let site = self.siteForIndexPath(indexPath), let url = NSURL(string: site.url) { let visitType = VisitType.Typed // Means History, too. homePanelDelegate?.homePanel(self, didSelectURL: url, visitType: visitType) return } log.warning("No site or no URL when selecting row.") } // Functions that deal with showing header rows. func numberOfSectionsInTableView(tableView: UITableView) -> Int { var count = 0 for category in self.categories { if category.rows > 0 { count++ } } return count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var title = String() switch sectionLookup[section]! { case 0: title = NSLocalizedString("Today", comment: "History tableview section header") case 1: title = NSLocalizedString("Yesterday", comment: "History tableview section header") case 2: title = NSLocalizedString("Last week", comment: "History tableview section header") case 3: title = NSLocalizedString("Last month", comment: "History tableview section header") default: assertionFailure("Invalid history section \(section)") } return title.uppercaseString } func categoryForDate(date: MicrosecondTimestamp) -> Int { let date = Double(date) if date > (1000000 * Today.timeIntervalSince1970) { return 0 } if date > (1000000 * Yesterday.timeIntervalSince1970) { return 1 } if date > (1000000 * ThisWeek.timeIntervalSince1970) { return 2 } return 3 } private func isInCategory(date: MicrosecondTimestamp, category: Int) -> Bool { return self.categoryForDate(date) == category } func computeSectionOffsets() { var counts = [Int](count: NumSections, repeatedValue: 0) // Loop over all the data. Record the start of each "section" of our list. for i in 0..<data.count { if let site = data[i] { counts[categoryForDate(site.latestVisit!.date)]++ } } var section = 0 var offset = 0 self.categories = [CategorySpec]() for i in 0..<NumSections { let count = counts[i] if count > 0 { log.debug("Category \(i) has \(count) rows, and thus is section \(section).") self.categories.append((section: section, rows: count, offset: offset)) sectionLookup[section] = i offset += count section++ } else { log.debug("Category \(i) has 0 rows, and thus has no section.") self.categories.append((section: nil, rows: 0, offset: offset)) } } } // UI sections disappear as categories empty. We need to translate back and forth. private func uiSectionToCategory(section: SectionNumber) -> CategoryNumber { for i in 0..<self.categories.count { if let s = self.categories[i].section where s == section { return i } } return 0 } private func categoryToUISection(category: CategoryNumber) -> SectionNumber? { return self.categories[category].section } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.categories[uiSectionToCategory(section)].rows } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // Intentionally blank. Required to use UITableViewRowActions } func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { let title = NSLocalizedString("Remove", tableName: "HistoryPanel", comment: "Action button for deleting history entries in the history panel.") let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: title, handler: { (action, indexPath) in if let site = self.siteForIndexPath(indexPath) { // Compute the section in advance -- if we try to do this below, naturally the category // will be empty, and so there will be no section in the CategorySpec! let category = self.categoryForDate(site.latestVisit!.date) let section = self.categoryToUISection(category)! // Why the dispatches? Because we call success and failure on the DB // queue, and so calling anything else that calls through to the DB will // deadlock. This problem will go away when the history API switches to // Deferred instead of using callbacks. self.profile.history.removeHistoryForURL(site.url) .upon { res in self.refetchData().uponQueue(dispatch_get_main_queue()) { result in // If a section will be empty after removal, we must remove the section itself. if let data = result.successValue { let oldCategories = self.categories self.data = data self.computeSectionOffsets() let sectionsToDelete = NSMutableIndexSet() var rowsToDelete = [NSIndexPath]() let sectionsToAdd = NSMutableIndexSet() var rowsToAdd = [NSIndexPath]() for (index, category) in enumerate(self.categories) { let oldCategory = oldCategories[index] // don't bother if we're not displaying this category if oldCategory.section == nil && category.section == nil { continue } // 1. add a new section if the section didn't previously exist if oldCategory.section == nil && category.section != oldCategory.section { log.debug("adding section \(category.section)") sectionsToAdd.addIndex(category.section!) } // 2. add a new row if there are more rows now than there were before if oldCategory.rows < category.rows { log.debug("adding row to \(category.section) at \(category.rows-1)") rowsToAdd.append(NSIndexPath(forRow: category.rows-1, inSection: category.section!)) } // if we're dealing with the section where the row was deleted: // 1. if the category no longer has a section, then we need to delete the entire section // 2. delete a row if the number of rows has been reduced // 3. delete the selected row and add a new one on the bottom of the section if the number of rows has stayed the same if oldCategory.section == indexPath.section { if category.section == nil { log.debug("deleting section \(indexPath.section)") sectionsToDelete.addIndex(indexPath.section) } else if oldCategory.section == category.section { if oldCategory.rows > category.rows { log.debug("deleting row from \(category.section) at \(indexPath.row)") rowsToDelete.append(indexPath) } else if category.rows == oldCategory.rows { log.debug("in section \(category.section), removing row at \(indexPath.row) and inserting row at \(category.rows-1)") rowsToDelete.append(indexPath) rowsToAdd.append(NSIndexPath(forRow: category.rows-1, inSection: indexPath.section)) } } } } tableView.beginUpdates() if sectionsToAdd.count > 0 { tableView.insertSections(sectionsToAdd, withRowAnimation: UITableViewRowAnimation.Left) } if sectionsToDelete.count > 0 { tableView.deleteSections(sectionsToDelete, withRowAnimation: UITableViewRowAnimation.Right) } if !rowsToDelete.isEmpty { tableView.deleteRowsAtIndexPaths(rowsToDelete, withRowAnimation: UITableViewRowAnimation.Right) } if !rowsToAdd.isEmpty { tableView.insertRowsAtIndexPaths(rowsToAdd, withRowAnimation: UITableViewRowAnimation.Right) } tableView.endUpdates() } } } } }) return [delete] } }
mpl-2.0
e2e72a0259782af0ba8f88ad216e8274
44.645963
168
0.57001
5.827914
false
false
false
false
mozilla-mobile/firefox-ios
Storage/SQL/SQLiteFavicons.swift
1
2041
// 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 open class SQLiteFavicons { let db: BrowserDB required public init(db: BrowserDB) { self.db = db } public func getFaviconIDQuery(url: String) -> (sql: String, args: Args?) { var args: Args = [] args.append(url) return (sql: "SELECT id FROM favicons WHERE url = ? LIMIT 1", args: args) } public func getInsertFaviconQuery(favicon: Favicon) -> (sql: String, args: Args?) { var args: Args = [] args.append(favicon.url) args.append(favicon.width) args.append(favicon.height) args.append(favicon.date) return (sql: "INSERT INTO favicons (url, width, height, type, date) VALUES (?,?,?,0,?)", args: args) } public func getUpdateFaviconQuery(favicon: Favicon) -> (sql: String, args: Args?) { var args = Args() args.append(favicon.width) args.append(favicon.height) args.append(favicon.date) args.append(favicon.url) return (sql: "UPDATE favicons SET width = ?, height = ?, date = ? WHERE url = ?", args: args) } public func getCleanupFaviconsQuery() -> (sql: String, args: Args?) { let sql = """ DELETE FROM favicons WHERE favicons.id NOT IN ( SELECT faviconID FROM favicon_sites ) """ return (sql: sql, args: nil) } public func getCleanupFaviconSiteURLsQuery() -> (sql: String, args: Args?) { let sql = """ DELETE FROM favicon_site_urls WHERE id IN ( SELECT favicon_site_urls.id FROM favicon_site_urls LEFT OUTER JOIN history ON favicon_site_urls.site_url = history.url WHERE history.id IS NULL ) """ return (sql: sql, args: nil) } }
mpl-2.0
557574aa39f2d25a4dff0ce8c3af5240
31.919355
108
0.583048
4.073852
false
false
false
false
ZekeSnider/Jared
Jared/Router.swift
1
3378
// // Router.swift // Jared // // Created by Zeke Snider on 4/20/20. // Copyright © 2020 Zeke Snider. All rights reserved. // import Foundation import JaredFramework class Router : RouterDelegate { var pluginManager: PluginManagerDelegate var messageDelegates: [MessageDelegate] init(pluginManager: PluginManagerDelegate, messageDelegates: [MessageDelegate]) { self.pluginManager = pluginManager self.messageDelegates = messageDelegates } func route(message myMessage: Message) { messageDelegates.forEach { delegate in delegate.didProcess(message: myMessage) } // Currently don't process any images guard let messageText = myMessage.body as? TextBody else { return } let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) let matches = detector.matches(in: messageText.message, options: [], range: NSMakeRange(0, messageText.message.count)) let myLowercaseMessage = messageText.message.lowercased() let defaults = UserDefaults.standard guard !defaults.bool(forKey: JaredConstants.jaredIsDisabled) || myLowercaseMessage == "/enable" else { return } RootLoop: for route in pluginManager.getAllRoutes() { guard (pluginManager.enabled(routeName: route.name)) else { break } for comparison in route.comparisons { if comparison.0 == .containsURL { for match in matches { let url = (messageText.message as NSString).substring(with: match.range) for comparisonString in comparison.1 { if url.contains(comparisonString) { let urlMessage = Message(body: TextBody(url), date: myMessage.date ?? Date(), sender: myMessage.sender, recipient: myMessage.recipient, attachments: []) route.call(urlMessage) } } } } else if comparison.0 == .startsWith { for comparisonString in comparison.1 { if myLowercaseMessage.hasPrefix(comparisonString.lowercased()) { route.call(myMessage) } } } else if comparison.0 == .contains { for comparisonString in comparison.1 { if myLowercaseMessage.contains(comparisonString.lowercased()) { route.call(myMessage) } } } else if comparison.0 == .is { for comparisonString in comparison.1 { if myLowercaseMessage == comparisonString.lowercased() { route.call(myMessage) } } } else if comparison.0 == .isReaction { if myMessage.action != nil { route.call(myMessage) } } } } } }
apache-2.0
6f05596cf005640803f770c15031866a
37.816092
184
0.510512
5.694772
false
false
false
false
sotownsend/flok-apple
Pod/Classes/Drivers/Rtc.swift
1
1075
@objc class FlokRtcModule : FlokModule { override var exports: [String] { return ["if_rtc_init:", "_if_rtc_tick_handler"] } private static var tickHelper: RtcTickHelper! func if_rtc_init(args: [AnyObject]) { self.dynamicType.tickHelper = RtcTickHelper(interval: 1) { epoch in self.engine.int_dispatch([1, "int_rtc", epoch]) } self.dynamicType.tickHelper.start() } func if_rtc() { } } @objc class RtcTickHelper : NSObject { let interval: Double let onTick: (Int) -> () init(interval: Double, onTick: (Int)->()) { self.interval = interval self.onTick = onTick } var timer: NSTimer! lazy var currentEpoch = Int(NSDate().timeIntervalSince1970) func start() { timer = NSTimer(timeInterval: interval, target: self, selector: "tick", userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes) } func tick() { onTick(currentEpoch) ++currentEpoch } }
mit
d63902cf523e7969e36ef79f478bf0eb
25.9
109
0.60186
3.923358
false
false
false
false
adrfer/swift
test/1_stdlib/tgmath.swift
13
9917
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // XFAIL: linux import Darwin.C.tgmath import CoreGraphics // verifiers func print3(op: String, _ d: Double, _ f: Float, _ g: CGFloat) { #if arch(i386) || arch(arm) if (f != Float(g) && f.isNaN != g.isNaN) { print("\(op)(CGFloat) got \(g) instead of \(f)") } #else if (d != Double(g) && d.isNaN != g.isNaN) { print("\(op)(CGFloat) got \(g) instead of \(d)") } #endif print("\(op) \(d) \(f) \(op)") } func print3(op: String, _ d: Bool, _ f: Bool, _ g: Bool) { #if arch(i386) || arch(arm) if (f != g) { print("\(op)(CGFloat) got \(g) instead of \(f)") } #else if (d != g) { print("\(op)(CGFloat) got \(g) instead of \(d)") } #endif print("\(op) \(d) \(f) \(op)") } func print3(op: String, _ d: Int, _ f: Int, _ g: Int) { #if arch(i386) || arch(arm) if (f != g) { print("\(op)(CGFloat) got \(g) instead of \(f)") } #else if (d != g) { print("\(op)(CGFloat) got \(g) instead of \(d)") } #endif print("\(op) \(d) \(f) \(op)") } func print6(op: String, _ d1: Double, _ d2: Double, _ f1: Float, _ f2: Float, _ g1: CGFloat, _ g2: CGFloat) { #if arch(i386) || arch(arm) if (f1 != Float(g1) || f2 != Float(g2)) { print("\(op)(CGFloat) got \(g1),\(g2) instead of \(f1),\(f2)") } #else if (d1 != Double(g1) || d2 != Double(g2)) { print("\(op)(CGFloat) got \(g1),\(g2) instead of \(d1),\(d2)") } #endif print("\(op) \(d1),\(d2) \(f1),\(f2) \(op)") } func print6(op: String, _ d1: Double, _ di: Int, _ f1: Float, _ fi: Int, _ g1: CGFloat, _ gi: Int) { #if arch(i386) || arch(arm) if (f1 != Float(g1) || fi != gi) { print("\(op)(CGFloat) got \(g1),\(gi) instead of \(f1),\(fi)") } #else if (d1 != Double(g1) || di != gi) { print("\(op)(CGFloat) got \(g1),\(gi) instead of \(d1),\(di)") } #endif print("\(op) \(d1),\(di) \(f1),\(fi) \(op)") } // inputs let dx = Double(0.1) let dy = Double(2.2) let dz = Double(3.3) let fx = Float(0.1) let fy = Float(2.2) let fz = Float(3.3) let gx = CGFloat(0.1) let gy = CGFloat(2.2) let gz = CGFloat(3.3) let ix = Int(11) // outputs var d1, d2: Double var f1, f2: Float var g1, g2: CGFloat var i1, i2, i3: Int var b1, b2, b3: Bool // The order of these tests matches tgmath.swift.gyb. print("Shopping is hard, let's do math") // CHECK: Shopping is hard, let's do math // Unary functions d1 = acos(dx) f1 = acos(fx) g1 = acos(gx) print3("acos", d1, f1, g1) // CHECK-NEXT: acos 1.47062890563334 1.47063 acos d1 = asin(dx) f1 = asin(fx) g1 = asin(gx) print3("asin", d1, f1, g1) // CHECK-NEXT: asin 0.10016742116156 0.100167 asin d1 = atan(dx) f1 = atan(fx) g1 = atan(gx) print3("atan", d1, f1, g1) // CHECK-NEXT: atan 0.099668652491162 0.0996687 atan d1 = cos(dx) f1 = cos(fx) g1 = cos(gx) print3("cos", d1, f1, g1) // CHECK-NEXT: cos 0.995004165278026 0.995004 cos d1 = sin(dx) f1 = sin(fx) g1 = sin(gx) print3("sin", d1, f1, g1) // CHECK-NEXT: sin 0.0998334166468282 0.0998334 sin d1 = tan(dx) f1 = tan(fx) g1 = tan(gx) print3("tan", d1, f1, g1) // CHECK-NEXT: tan 0.100334672085451 0.100335 tan d1 = acosh(dx) f1 = acosh(fx) g1 = acosh(gx) print3("acosh", d1, f1, g1) // CHECK-NEXT: acosh nan nan acosh d1 = asinh(dx) f1 = asinh(fx) g1 = asinh(gx) print3("asinh", d1, f1, g1) // CHECK-NEXT: asinh 0.0998340788992076 0.0998341 asinh d1 = atanh(dx) f1 = atanh(fx) g1 = atanh(gx) print3("atanh", d1, f1, g1) // CHECK-NEXT: atanh 0.100335347731076 0.100335 atanh d1 = cosh(dx) f1 = cosh(fx) g1 = cosh(gx) print3("cosh", d1, f1, g1) // CHECK-NEXT: cosh 1.0050041680558 1.005 cosh d1 = sinh(dx) f1 = sinh(fx) g1 = sinh(gx) print3("sinh", d1, f1, g1) // CHECK-NEXT: sinh 0.100166750019844 0.100167 sinh d1 = tanh(dx) f1 = tanh(fx) g1 = tanh(gx) print3("tanh", d1, f1, g1) // CHECK-NEXT: tanh 0.0996679946249558 0.099668 tanh d1 = exp(dx) f1 = exp(fx) g1 = exp(gx) print3("exp", d1, f1, g1) // CHECK-NEXT: exp 1.10517091807565 1.10517 exp d1 = exp2(dx) f1 = exp2(fx) g1 = exp2(gx) print3("exp2", d1, f1, g1) // CHECK-NEXT: exp2 1.07177346253629 1.07177 exp2 d1 = expm1(dx) f1 = expm1(fx) g1 = expm1(gx) print3("expm1", d1, f1, g1) // CHECK-NEXT: expm1 0.105170918075648 0.105171 expm1 d1 = log(dx) f1 = log(fx) g1 = log(gx) print3("log", d1, f1, g1) // CHECK-NEXT: log -2.30258509299405 -2.30259 log d1 = log10(dx) f1 = log10(fx) g1 = log10(gx) print3("log10", d1, f1, g1) // CHECK-NEXT: log10 -1.0 -1.0 log10 d1 = log2(dx) f1 = log2(fx) g1 = log2(gx) print3("log2", d1, f1, g1) // CHECK-NEXT: log2 -3.32192809488736 -3.32193 log2 d1 = log1p(dx) f1 = log1p(fx) g1 = log1p(gx) print3("log1p", d1, f1, g1) // CHECK-NEXT: log1p 0.0953101798043249 0.0953102 log1p d1 = logb(dx) f1 = logb(fx) g1 = logb(gx) print3("logb", d1, f1, g1) // CHECK-NEXT: logb -4.0 -4.0 logb d1 = fabs(dx) f1 = fabs(fx) g1 = fabs(gx) print3("fabs", d1, f1, g1) // CHECK-NEXT: fabs 0.1 0.1 fabs d1 = cbrt(dx) f1 = cbrt(fx) g1 = cbrt(gx) print3("cbrt", d1, f1, g1) // CHECK-NEXT: cbrt 0.464158883361278 0.464159 cbrt d1 = sqrt(dx) f1 = sqrt(fx) g1 = sqrt(gx) print3("sqrt", d1, f1, g1) // CHECK-NEXT: sqrt 0.316227766016838 0.316228 sqrt d1 = erf(dx) f1 = erf(fx) g1 = erf(gx) print3("erf", d1, f1, g1) // CHECK-NEXT: erf 0.112462916018285 0.112463 erf d1 = erfc(dx) f1 = erfc(fx) g1 = erfc(gx) print3("erfc", d1, f1, g1) // CHECK-NEXT: erfc 0.887537083981715 0.887537 erfc d1 = tgamma(dx) f1 = tgamma(fx) g1 = tgamma(gx) print3("tgamma", d1, f1, g1) // CHECK-NEXT: tgamma 9.51350769866873 9.51351 tgamma d1 = ceil(dx) f1 = ceil(fx) g1 = ceil(gx) print3("ceil", d1, f1, g1) // CHECK-NEXT: ceil 1.0 1.0 ceil d1 = floor(dx) f1 = floor(fx) g1 = floor(gx) print3("floor", d1, f1, g1) // CHECK-NEXT: floor 0.0 0.0 floor d1 = nearbyint(dx) f1 = nearbyint(fx) g1 = nearbyint(gx) print3("nearbyint", d1, f1, g1) // CHECK-NEXT: nearbyint 0.0 0.0 nearbyint d1 = rint(dx) f1 = rint(fx) g1 = rint(gx) print3("rint", d1, f1, g1) // CHECK-NEXT: rint 0.0 0.0 rint d1 = round(dx) f1 = round(fx) g1 = round(gx) print3("round", d1, f1, g1) // CHECK-NEXT: round 0.0 0.0 round d1 = trunc(dx) f1 = trunc(fx) g1 = trunc(gx) print3("trunc", d1, f1, g1) // CHECK-NEXT: trunc 0.0 0.0 trunc // Binary functions d1 = atan2(dx, dy) f1 = atan2(fx, fy) g1 = atan2(gx, gy) print3("atan2", d1, f1, g1) // CHECK-NEXT: atan2 0.045423279421577 0.0454233 atan2 d1 = hypot(dx, dy) f1 = hypot(fx, fy) g1 = hypot(gx, gy) print3("hypot", d1, f1, g1) // CHECK-NEXT: hypot 2.20227155455452 2.20227 hypot d1 = pow(dx, dy) f1 = pow(fx, fy) g1 = pow(gx, gy) print3("pow", d1, f1, g1) // CHECK-NEXT: pow 0.00630957344480193 0.00630957 pow d1 = fmod(dx, dy) f1 = fmod(fx, fy) g1 = fmod(gx, gy) print3("fmod", d1, f1, g1) // CHECK-NEXT: fmod 0.1 0.1 fmod d1 = remainder(dx, dy) f1 = remainder(fx, fy) g1 = remainder(gx, gy) print3("remainder", d1, f1, g1) // CHECK-NEXT: remainder 0.1 0.1 remainder d1 = copysign(dx, dy) f1 = copysign(fx, fy) g1 = copysign(gx, gy) print3("copysign", d1, f1, g1) // CHECK-NEXT: copysign 0.1 0.1 copysign d1 = nextafter(dx, dy) f1 = nextafter(fx, fy) g1 = nextafter(gx, gy) print3("nextafter", d1, f1, g1) // CHECK-NEXT: nextafter 0.1 0.1 nextafter d1 = fdim(dx, dy) f1 = fdim(fx, fy) g1 = fdim(gx, gy) print3("fdim", d1, f1, g1) // CHECK-NEXT: fdim 0.0 0.0 fdim d1 = fmax(dx, dy) f1 = fmax(fx, fy) g1 = fmax(gx, gy) print3("fmax", d1, f1, g1) // CHECK-NEXT: fmax 2.2 2.2 fmax d1 = fmin(dx, dy) f1 = fmin(fx, fy) g1 = fmin(gx, gy) print3("fmin", d1, f1, g1) // CHECK-NEXT: fmin 0.1 0.1 fmin // Other functions i1 = fpclassify(dx) i2 = fpclassify(fx) i3 = fpclassify(gx) print3("fpclassify", i1, i2, i3) // CHECK-NEXT: fpclassify 4 4 fpclassify b1 = isnormal(dx) b2 = isnormal(fx) b3 = isnormal(gx) print3("isnormal", b1, b2, b3) // CHECK-NEXT: isnormal true true isnormal b1 = isfinite(dx) b2 = isfinite(fx) b3 = isfinite(gx) print3("isfinite", b1, b2, b3) // CHECK-NEXT: isfinite true true isfinite b1 = isinf(dx) b2 = isinf(fx) b3 = isinf(gx) print3("isinf", b1, b2, b3) // CHECK-NEXT: isinf false false isinf b1 = isnan(dx) b2 = isnan(fx) b3 = isnan(gx) print3("isnan", b1, b2, b3) // CHECK-NEXT: isnan false false isnan i1 = signbit(dx) i2 = signbit(fx) i3 = signbit(gx) print3("signbit", i1, i2, i3) // CHECK-NEXT: signbit 0 0 signbit (d1, d2) = modf(dy) (f1, f2) = modf(fy) (g1, g2) = modf(gy) print6("modf", d1,d2, f1,f2, g1,g2) // CHECK-NEXT: modf 2.0,0.2 2.0,0.2 modf d1 = ldexp(dx, ix) f1 = ldexp(fx, ix) g1 = ldexp(gx, ix) print3("ldexp", d1, f1, g1) // CHECK-NEXT: ldexp 204.8 204.8 ldexp (d1, i1) = frexp(dy) (f1, i2) = frexp(fy) (g1, i3) = frexp(gy) print6("frexp", d1,i1, f1,i2, g1,i3) // CHECK-NEXT: frexp 0.55,2 0.55,2 frexp i1 = ilogb(dy) i2 = ilogb(fy) i3 = ilogb(gy) print3("ilogb", i1, i2, i3) // CHECK-NEXT: ilogb 1 1 ilogb d1 = scalbn(dx, ix) f1 = scalbn(fx, ix) g1 = scalbn(gx, ix) print3("scalbn", d1, f1, g1) // CHECK-NEXT: scalbn 204.8 204.8 scalbn (d1, i1) = lgamma(dx) (f1, i2) = lgamma(fx) (g1, i3) = lgamma(gx) print6("lgamma", d1,i1, f1,i2, g1,i3) // CHECK-NEXT: lgamma 2.25271265173421,1 2.25271,1 lgamma (d1, i1) = remquo(dz, dy) (f1, i2) = remquo(fz, fy) (g1, i3) = remquo(gz, gy) print6("remquo", d1,i1, f1,i2, g1,i3) // CHECK-NEXT: remquo 1.1,1 1.1,1 remquo d1 = nan("12345") f1 = nan("12345") g1 = nan("12345") print3("nan", d1, f1, g1) // CHECK-NEXT: nan nan nan nan d1 = fma(dx, dy, dz) f1 = fma(fx, fy, fz) g1 = fma(gx, gy, gz) print3("fma", d1, f1, g1) // CHECK-NEXT: fma 3.52 3.52 fma d1 = j0(dx) print("j0 \(d1) j0") // CHECK-NEXT: j0 0.99750156206604 j0 d1 = j1(dx) print("j1 \(d1) j1") // CHECK-NEXT: j1 0.049937526036242 j1 d1 = jn(ix, dx) print("jn \(d1) jn") // CHECK-NEXT: jn 1.22299266103565e-22 jn d1 = y0(dx) print("y0 \(d1) y0") // CHECK-NEXT: y0 -1.53423865135037 y0 d1 = y1(dx) print("y1 \(d1) y1") // CHECK-NEXT: y1 -6.45895109470203 y1 d1 = yn(ix, dx) print("yn \(d1) yn") // CHECK-NEXT: yn -2.36620129448696e+20 yn
apache-2.0
57afe0cffa9d534c624cbc9d5f56b8cf
19.40535
66
0.610164
2.093519
false
false
false
false
andrebocchini/SwiftChattyOSX
SwiftChattyOSX/Compose Post/ComposePostReplyViewController.swift
1
2349
// // ComposePostReplyViewController.swift // SwiftChattyOSX // // Created by Andre Bocchini on 2/14/16. // Copyright © 2016 Andre Bocchini. All rights reserved. // import Cocoa import SwiftChatty protocol ComposePostReplyViewControllerDelegate { func composePostReplyViewControllerDidPostReply(viewController: ComposePostReplyViewController) } class ComposePostReplyViewController: NSViewController, ProgressIndicating, Alerting { // MARK: Outlets @IBOutlet private weak var authorLabel: NSTextField! @IBOutlet private weak var previewLabel: NSTextField! @IBOutlet private var replyTextView: NSTextView! @IBOutlet private weak var cancelButton: NSButton! @IBOutlet private weak var replyButton: NSButton! @IBOutlet internal weak var progressIndicatorLabel: NSTextField! @IBOutlet internal weak var progressIndicator: NSProgressIndicator! // MARK: Variables var delegate: ComposePostReplyViewControllerDelegate? var post: Post = Post() override func viewDidLoad() { super.viewDidLoad() // Do view setup here. self.authorLabel.stringValue = post.author displayPostPreview(post) } private func displayPostPreview(post: Post) { let htmlManipulator = HtmlManipulator() self.previewLabel.stringValue = htmlManipulator.stripHtml(post.body) } // MARK: Actions @IBAction private func cancelButtonClicked(sender: AnyObject) { self.dismissController(self) } @IBAction private func postButtonClicked(sender: AnyObject) { enableProgressIndicator() var account = Account() account.loadFromUserDefaults() account.loadFromKeyChain() if let postText = replyTextView.textStorage?.string { ChattyService.post(account, parentId: post.id, text: postText, success: { () -> Void in self.disableProgressIndicator() self.delegate?.composePostReplyViewControllerDidPostReply(self) self.dismissController(self) }) { (error) -> Void in self.disableProgressIndicator() self.displayErrorAlert(NSLocalizedString("Error", comment: ""), informativeText: NSLocalizedString("Failed to post reply: ", comment: "") + "\(error)") } } } }
mit
8e708b71c47fcc9f05bacac88b848932
32.542857
171
0.688245
5.137856
false
false
false
false
yrchen/edx-app-ios
Source/ProfileAPI.swift
1
3003
// // ProfileHelper.swift // edX // // Created by Michael Katz on 9/18/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation public class ProfileAPI: NSObject { private static var currentUserFeed = [String: Feed<UserProfile>]() private static func profileDeserializer(response : NSHTTPURLResponse, json : JSON) -> Result<UserProfile> { return UserProfile(json: json).toResult() } private static func imageResponseDeserializer(response : NSHTTPURLResponse) -> Result<()> { return Success() } private class func path(username:String) -> String { return "/api/user/v1/accounts/{username}".oex_formatWithParameters(["username": username]) } class func profileRequest(username: String) -> NetworkRequest<UserProfile> { return NetworkRequest( method: HTTPMethod.GET, path : path(username), requiresAuth : true, deserializer: .JSONResponse(profileDeserializer)) } class func getProfile(username: String, networkManager: NetworkManager, handler: (profile: NetworkResult<UserProfile>) -> ()) { let request = profileRequest(username) networkManager.taskForRequest(request, handler: handler) } class func getProfile(username: String, networkManager: NetworkManager) -> Stream<UserProfile> { let request = profileRequest(username) return networkManager.streamForRequest(request) } class func profileUpdateRequest(profile: UserProfile) -> NetworkRequest<UserProfile> { let json = JSON(profile.updateDictionary) let request = NetworkRequest(method: HTTPMethod.PATCH, path: path(profile.username!), requiresAuth: true, body: RequestBody.JSONBody(json), headers: ["Content-Type": "application/merge-patch+json"], //should push this to a lower level once all our PATCHs support this content-type deserializer: .JSONResponse(profileDeserializer)) return request } class func uploadProfilePhotoRequest(username: String, imageData: NSData) -> NetworkRequest<()> { let path = "/api/user/v1/accounts/{username}/image".oex_formatWithParameters(["username" : username]) return NetworkRequest(method: HTTPMethod.POST, path: path, requiresAuth: true, body: RequestBody.DataBody(data: imageData, contentType: "image/jpeg"), headers: ["Content-Disposition":"attachment;filename=filename.jpg"], deserializer: .NoContent(imageResponseDeserializer)) } class func deleteProfilePhotoRequest(username: String) -> NetworkRequest<()> { let path = "/api/user/v1/accounts/{username}/image".oex_formatWithParameters(["username" : username]) return NetworkRequest(method: HTTPMethod.DELETE, path: path, requiresAuth: true, deserializer: .NoContent(imageResponseDeserializer)) } }
apache-2.0
b8b1433bf9708d29da9bef42bdb974a6
40.136986
152
0.668332
4.996672
false
false
false
false
lizhaoLoveIT/sinaWeiBo
sinaWeiBo/sinaWeiBo/AppDelegate.swift
1
3475
// // AppDelegate.swift // sinaWeiBo // // Created by 李朝 on 16/6/3. // Copyright © 2016年 IFengXY. All rights reserved. // import UIKit import QorumLogs //@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? override class func initialize() { setupAppearance() } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { QorumLogs.minimumLogLevelShown = 1 // QorumLogs.onlyShowThisFile(ViewController) QorumLogs.enabled = true // QL1(1) // debug // QL2(2) // info // QL3(3) // warning // QL4(4) // error // QLPlusLine() // QLShortLine() // 1.创建 window window = UIWindow(frame: UIScreen.mainScreen().bounds) // 2.设置 window.rootVc window?.rootViewController = TabBarController() // 3.显示 window window?.makeKeyAndVisible() // 设置全局属性 setupAppearance() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } /** * 全局函数,自定义 Log * swift 3 #file = __FILE__ * #function = __FUNCTION__ * #line = __LINE__ * 泛型函数,泛型可以实现调用者传递什么类型就是什么类型 */ func AMLog<T>(message: T, file: String = #file, method: String = #function, line: Int = #line ) { #if AM_DEBUG // 1.处理文件名称 let fileName = (file as NSString).pathComponents.last! // 2.按照指定格式数据日志 文件名称-方法名称[行号]:输出内容 print("\(fileName)-\(method)[\(line)]:\(message)") #endif } /** * 设置全局属性 */ func setupAppearance() { }
mit
0cc35226476bf93056348c84c1b424f6
33.051546
285
0.665354
4.710414
false
false
false
false
kongtomorrow/ProjectEuler-Swift
ProjectEuler/p47.swift
1
1677
// // p47.swift // ProjectEuler // // Created by Ken Ferry on 8/14/14. // Copyright (c) 2014 Understudy. All rights reserved. // import Foundation extension Problems { func p47() -> Int { /* Distinct primes factors Problem 47 Published on 04 July 2003 at 06:00 pm [Server Time] The first two consecutive numbers to have two distinct prime factors are: 14 = 2 × 7 15 = 3 × 5 The first three consecutive numbers to have three distinct prime factors are: 644 = 2² × 7 × 23 645 = 3 × 5 × 43 646 = 2 × 17 × 19. Find the first four consecutive integers to have four distinct prime factors. What is the first of these numbers? */ let numFactors = 4 for i in 1..<Int.max { let probe = i*numFactors if factor(probe).count == numFactors { var last = probe var first = probe for next in probe+1...probe+numFactors-1 { if factor(next).count == numFactors { last++ } else { break } } for prev in stride(from: probe-1, through: probe-3, by: -1) { if factor(prev).count == numFactors { first-- } else { break } } if last-first >= numFactors-1 { return first // 134043 } } } return 0 } }
mit
753f039b4935f16c4bb13de380559860
27.271186
121
0.446643
4.848837
false
false
false
false
tripleCC/GanHuoCode
GanHuo/Util/TPCVersionUtil.swift
1
2303
// // TPCVersionUtil.swift // GanHuo // // Created by tripleCC on 15/12/19. // Copyright © 2015年 tripleCC. All rights reserved. // import Foundation let TPCAppID = "1064034435" let TPCVersionNotificationHadShowedKey = "TPCVersionNotificationHadShowed" let TPCNextVersionKey = "TPCNextVersion" class TPCVersionUtil { static var versionInfo: TPCVersionInfo? { didSet { let curVesion = TPCCurrentVersion shouldUpdate = versionInfo?.version != curVesion let nextVersion = TPCStorageUtil.objectForKey(TPCNextVersionKey) as? String debugPrint(curVesion, nextVersion, versionInfo?.version) if versionInfo?.version > curVesion && versionInfo?.version != nil { shouldUpdate = true // 每个版本更新,都通知一次 if nextVersion != versionInfo?.version { hadShowed = false } TPCStorageUtil.setObject(versionInfo?.version, forKey: TPCNextVersionKey) } else { shouldUpdate = false } } } static var shouldUpdate: Bool = false static var _hadShowed: Bool = TPCStorageUtil.boolForKey(TPCVersionNotificationHadShowedKey) static var hadShowed: Bool { get { return _hadShowed } set(new) { _hadShowed = new TPCStorageUtil.setBool(hadShowed, forKey: TPCVersionNotificationHadShowedKey) } } static func showUpdateMessage() { guard !hadShowed else { return } dispatchGlobal { let n = UILocalNotification() n.fireDate = NSDate(timeIntervalSinceNow:3) n.timeZone = NSTimeZone.defaultTimeZone() n.alertBody = versionInfo?.updateInfo ?? "新版幹貨出炉啦!去AppStore吃了这盘新鲜的干货吧!" n.alertAction = "升级" n.soundName = "" hadShowed = true UIApplication.sharedApplication().scheduleLocalNotification(n) debugPrint("发送更新本地通知") } } static func openUpdateLink() { let url = NSURL(string: "itms-apps://itunes.apple.com/app/id\(TPCAppID)") UIApplication.sharedApplication().openURL(url!) } }
mit
7160bc8d1b6f3db3dbbca0c8865acbe2
33.640625
95
0.611462
4.655462
false
false
false
false
dasdom/Swiftandpainless
SwiftAndPainless_2.playground/Resources/Functions - Returning A Function.xcplaygroundpage/Contents.swift
2
670
import Foundation /*: [⬅️](@previous) [➡️](@next) # Functions: Returning A Function */ func urlMaker(base base: String) -> ([String:String]) -> NSURL? { func url(parameter: [String:String]) -> NSURL? { var paramString = "" for (key, value) in parameter { let prefix = paramString.characters.count > 0 ? "&" : "" paramString += prefix + "\(key)=\(value)" } return NSURL(string: "\(base)?\(paramString)&site=stackoverflow") } return url } let userURLMaker = urlMaker(base: "http://api.stackexchange.com/2.2/users") userURLMaker.dynamicType let userURL = userURLMaker(["order":"desc","sort":"reputation"]) print(userURL)
mit
fd4cdfb3a8963aa0c1c56beb5a3863bd
27.782609
75
0.638973
3.677778
false
false
false
false
gnachman/iTerm2
BetterFontPicker/BetterFontPicker/FavoritesDataSource.swift
2
3118
// // FavoritesDataSource.swift // BetterFontPicker // // Created by George Nachman on 4/7/19. // Copyright © 2019 George Nachman. All rights reserved. // import Cocoa protocol FavoritesDataSourceDelegate: AnyObject { func favoritesDataSource(_ dataSource: FavoritesDataSource, didInsertRowAtIndex index: Int) func favoritesDataSource(_ dataSource: FavoritesDataSource, didDeleteRowAtIndex index: Int, name: String) } @objc(BFPFavoritesDataSource) class FavoritesDataSource: NSObject, FontListDataSource { private let userDefaultsKey = "NoSyncBFPFavorites" weak var delegate: FavoritesDataSourceDelegate? var names: [String] { return filteredFavoriteNames } var isSeparator: Bool { return false } private var filteredFavoriteNames: Array<String> { let queryTokens = filter.normalizedTokens return persistentFavoriteNames.filter { return $0.matchesTableViewSearchQueryTokens(queryTokens) && fontFamilyExists($0) } } private var cachedNames: [String]? = nil private var persistentFavoriteNames: [String] { set { UserDefaults.standard.set(newValue, forKey: userDefaultsKey) cachedNames = newValue } get { if let cachedNames = cachedNames { return cachedNames } let names = UserDefaults.standard.object(forKey: userDefaultsKey) as? [String] ?? [] cachedNames = names return names } } private var unfilteredFavoriteNames: [String] { get { return persistentFavoriteNames } set { persistentFavoriteNames = newValue } } var filter: String = "" func makeFavorite(_ name: String) { guard !unfilteredFavoriteNames.contains(name) else { return } persistentFavoriteNames = persistentFavoriteNames + [name] guard let index = filteredFavoriteNames.firstIndex(of: name) else { return } delegate?.favoritesDataSource(self, didInsertRowAtIndex: index) } func removeFavorite(_ name: String) { let maybeTableIndex = filteredFavoriteNames.firstIndex(of: name) guard let index = unfilteredFavoriteNames.firstIndex(of: name) else { return } var temp = unfilteredFavoriteNames temp.remove(at: index) unfilteredFavoriteNames = temp guard let tableIndex = maybeTableIndex else { return } delegate?.favoritesDataSource(self, didDeleteRowAtIndex: tableIndex, name: name) } func toggleFavorite(_ name: String) { if unfilteredFavoriteNames.contains(name) { removeFavorite(name) } else { makeFavorite(name) } } func reload() { cachedNames = nil } private func fontFamilyExists(_ name: String) -> Bool { return NSFontManager.shared.availableFontFamilies.contains(name) } }
gpl-2.0
2ad0599157a995da5e308180d78e9dd9
29.861386
96
0.623356
4.9872
false
false
false
false
mpangburn/RayTracer
RayTracer/Models/RayTracer.swift
1
7048
// // RayTracer.swift // RayTracer // // Created by Michael Pangburn on 6/26/17. // Copyright © 2017 Michael Pangburn. All rights reserved. // import Foundation import CoreData /// Stores data for and performs ray tracing. final class RayTracer { /// The shared RayTracer instance. static let shared = RayTracer() /// The spheres to cast rays on. var spheres: [Sphere] = { let context = PersistenceManager.shared.persistentContainer.viewContext let fetchRequest: NSFetchRequest<Sphere> = Sphere.fetchRequest() let dateSortDescriptor = NSSortDescriptor(key: "creationDate", ascending: true) fetchRequest.sortDescriptors = [dateSortDescriptor] var spheres = (try? context.fetch(fetchRequest)) ?? [] if spheres.isEmpty { spheres.append(Sphere(string: "1.0 1.0 0.0 2.0 1.0 0.0 1.0 0.2 0.4 0.5 0.05", context: context)!) spheres.append(Sphere(string: "8.0 -10.0 100.0 90.0 0.2 0.2 0.6 0.4 0.8 0.0 0.05", context: context)!) } return spheres }() { didSet { sceneNeedsRendering = true } } /// The ray tracing settings to be used in creating the scene. var settings = UserDefaults.standard.rayTracerSettings ?? RayTracerSettings() { didSet { sceneNeedsRendering = true } } /// Represents whether changes have been made to the scene since its last render. var sceneNeedsRendering = true // Prevents access to any tracer other than the shared instance. private init() { } /** Casts all rays on the scene. - Returns: The image produced by casting all rays. */ func castAllRays() -> Image { sceneNeedsRendering = false var pixels: [Color.PixelData] = [] let frame = settings.sceneFrame var width = frame.width var height = frame.height let dx = (frame.maxX - frame.minX) / Double(width) let dy = (frame.maxY - frame.minY) / Double(height) var y = frame.maxY while y > frame.minY { var x = frame.minX while x < frame.maxX { let direction = Vector(from: settings.eyePoint, to: Point(x: x, y: y, z: frame.zPlane)) let ray = Ray(initial: settings.eyePoint, direction: direction) let pixelData = cast(ray: ray) pixels.append(pixelData) x += dx } y -= dy } // Accounting for rounding errors. Marginally affects image size. let roundingError = pixels.count - (width * height) if roundingError == width { height += 1 } else if roundingError == height { width += 1 } else if roundingError > 0 { width += 1 height += 1 } return Image(pixelData: pixels, width: width, height: height) } /** Casts the ray on the scene. - Parameter ray: The ray to cast. - Returns: The pixel data for the color produced when casting the ray on the scene. */ func cast(ray: Ray) -> Color.PixelData { guard let intersection = ray.closestIntersection(with: spheres) else { return settings.backgroundColor.pixelData } let closestSphere = intersection.sphere let ambient = closestSphere.finish.ambient let diffuse = computeDiffuseComponents(at: intersection) let specular = computeSpecularComponents(at: intersection) let red = closestSphere.color.red * (settings.ambience.red * ambient) + diffuse.red + specular.red let green = closestSphere.color.green * (settings.ambience.green * ambient) + diffuse.green + specular.green let blue = closestSphere.color.blue * (settings.ambience.blue * ambient) + diffuse.blue + specular.blue return Color(red: red, green: green, blue: blue).pixelData } /// Computes the additive diffuse components for the color produced when casting a ray. private func computeDiffuseComponents(at intersection: Ray.Intersection) -> Color { let (sphere, intersectionPoint) = intersection let normalToSphere = sphere.normal(at: intersectionPoint) let pointJustOffSphere = intersectionPoint.translate(by: normalToSphere * 0.01) let light = settings.light let vectorFromPointJustOffSphereToLight = Vector(from: pointJustOffSphere, to: light.position) let lightDirection = vectorFromPointJustOffSphereToLight.normalized() let rayToLight = Ray(initial: pointJustOffSphere, direction: lightDirection) let distanceToLight = vectorFromPointJustOffSphereToLight.length let rayToLightIntersections = rayToLight.intersections(with: spheres) var lightIsObscured = false for intersection in rayToLightIntersections { let distanceToSphere = intersection.point.distance(from: rayToLight.initial) if distanceToSphere < distanceToLight { lightIsObscured = true break } } let dotProduct = normalToSphere • lightDirection if lightIsObscured || dotProduct <= 0 { return Color.black } else { let base = dotProduct * sphere.finish.diffuse let redDiffuse = light.effectiveColor.red * sphere.color.red * base let greenDiffuse = light.effectiveColor.green * sphere.color.green * base let blueDiffuse = light.effectiveColor.blue * sphere.color.blue * base return Color(red: redDiffuse, green: greenDiffuse, blue: blueDiffuse) } } /// Computes the additive specular components for the color produced when casting a ray. private func computeSpecularComponents(at intersection: Ray.Intersection) -> Color { let (sphere, intersectionPoint) = intersection let normalToSphere = sphere.normal(at: intersectionPoint) let pointJustOffSphere = intersectionPoint.translate(by: normalToSphere * 0.01) let light = settings.light let vectorFromPointJustOffSphereToLight = Vector(from: pointJustOffSphere, to: light.position) let lightDirection = vectorFromPointJustOffSphereToLight.normalized() let dotProduct = normalToSphere • lightDirection let reflectionVector = lightDirection - 2 * dotProduct * normalToSphere let eyePointDirection = Vector(from: settings.eyePoint, to: pointJustOffSphere).normalized() let specularIntensity = reflectionVector • eyePointDirection if specularIntensity <= 0 { return Color.black } else { let base = sphere.finish.specular * pow(specularIntensity, 1 / sphere.finish.roughness) let redSpecular = light.effectiveColor.red * base let greenSpecular = light.effectiveColor.green * base let blueSpecular = light.effectiveColor.blue * base return Color(red: redSpecular, green: greenSpecular, blue: blueSpecular) } } }
mit
b9a2faf181f716adb74685d0eea805cd
40.662722
116
0.646641
4.456329
false
false
false
false
ello/ello-ios
Sources/Model/Comment.swift
1
3884
//// /// Comment.swift // import SwiftyJSON let CommentVersion = 1 @objc(ElloComment) final class ElloComment: Model, Authorable { let id: String let createdAt: Date let authorId: String let postId: String var content: [Regionable] var body: [Regionable] var summary: [Regionable] var assets: [Asset] { return getLinkArray("assets") } var author: User? { return getLinkObject("author") } var parentPost: Post? { return getLinkObject("parent_post") } var loadedFromPost: Post? { return getLinkObject("loaded_from_post") ?? parentPost } // to show hide in the stream, and for comment replies var loadedFromPostId: String { didSet { addLinkObject("loaded_from_post", id: loadedFromPostId, type: .postsType) } } init( id: String, createdAt: Date, authorId: String, postId: String, content: [Regionable], body: [Regionable], summary: [Regionable] ) { self.id = id self.createdAt = createdAt self.authorId = authorId self.postId = postId self.loadedFromPostId = postId self.content = content self.body = body self.summary = summary super.init(version: CommentVersion) addLinkObject("parent_post", id: postId, type: .postsType) addLinkObject("loaded_from_post", id: postId, type: .postsType) addLinkObject("author", id: authorId, type: .usersType) } required init(coder: NSCoder) { let decoder = Coder(coder) self.id = decoder.decodeKey("id") self.createdAt = decoder.decodeKey("createdAt") self.authorId = decoder.decodeKey("authorId") self.postId = decoder.decodeKey("postId") self.content = decoder.decodeKey("content") self.loadedFromPostId = decoder.decodeKey("loadedFromPostId") self.body = decoder.decodeOptionalKey("body") ?? [] self.summary = decoder.decodeOptionalKey("summary") ?? [] super.init(coder: coder) } override func encode(with encoder: NSCoder) { let coder = Coder(encoder) coder.encodeObject(id, forKey: "id") coder.encodeObject(createdAt, forKey: "createdAt") coder.encodeObject(authorId, forKey: "authorId") coder.encodeObject(postId, forKey: "postId") coder.encodeObject(content, forKey: "content") coder.encodeObject(loadedFromPostId, forKey: "loadedFromPostId") coder.encodeObject(body, forKey: "body") coder.encodeObject(summary, forKey: "summary") super.encode(with: coder.coder) } class func fromJSON(_ data: [String: Any]) -> ElloComment { let json = JSON(data) let comment = ElloComment( id: json["id"].idValue, createdAt: json["created_at"].dateValue, authorId: json["author_id"].stringValue, postId: json["post_id"].stringValue, content: RegionParser.jsonRegions(json: json["content"]), body: RegionParser.jsonRegions(json: json["body"]), summary: RegionParser.jsonRegions(json: json["summary"]) ) comment.mergeLinks(data["links"] as? [String: Any]) comment.addLinkObject("author", id: comment.authorId, type: .usersType) comment.addLinkObject("parent_post", id: comment.postId, type: .postsType) return comment } class func newCommentForPost(_ post: Post, currentUser: User) -> ElloComment { return ElloComment( id: UUID().uuidString, createdAt: Globals.now, authorId: currentUser.id, postId: post.id, content: [], body: [], summary: [] ) } } extension ElloComment: JSONSaveable { var uniqueId: String? { return "ElloComment-\(id)" } var tableId: String? { return id } }
mit
50a93eb4cd3165a6dd6f2dc01560dd2d
32.482759
92
0.618177
4.230937
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/Sku/Views/VariantFlowLayout.swift
1
3909
// // VariantFlowLayout.swift // UIScrollViewDemo // // Created by 黄渊 on 2022/10/28. // Copyright © 2022 伯驹 黄. All rights reserved. // import Foundation class VariantFlowLayout: UICollectionViewFlowLayout { override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributesCopy: [UICollectionViewLayoutAttributes] = [] if let attributes = super.layoutAttributesForElements(in: rect) { for attribute in attributes { if let a = attribute.copy() as? UICollectionViewLayoutAttributes { attributesCopy.append(a) } } } for attributes in attributesCopy where attributes.representedElementKind == nil { let indexpath = attributes.indexPath if let attr = layoutAttributesForItem(at: indexpath) { attributes.frame = attr.frame } } return attributesCopy } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if let currentItemAttributes = super.layoutAttributesForItem(at: indexPath as IndexPath)?.copy() as? UICollectionViewLayoutAttributes, let collection = collectionView { let sectionInset = evaluatedSectionInsetForItem(at: indexPath.section) let isFirstItemInSection = indexPath.item == 0 let layoutWidth = collection.frame.width - sectionInset.left - sectionInset.right guard !isFirstItemInSection else { currentItemAttributes.leftAlignFrame(with: sectionInset) return currentItemAttributes } let previousIndexPath = IndexPath(item: indexPath.item - 1, section: indexPath.section) let previousFrame = layoutAttributesForItem(at: previousIndexPath)?.frame ?? CGRect.zero let previousFrameRightPoint = previousFrame.origin.x + previousFrame.width let currentFrame = currentItemAttributes.frame let strecthedCurrentFrame = CGRect(x: sectionInset.left, y: currentFrame.origin.y, width: layoutWidth, height: currentFrame.size.height) let isFirstItemInRow = !previousFrame.intersects(strecthedCurrentFrame) guard !isFirstItemInRow else { currentItemAttributes.leftAlignFrame(with: sectionInset) return currentItemAttributes } var frame = currentItemAttributes.frame frame.origin.x = previousFrameRightPoint + evaluatedMinimumInteritemSpacing(at: indexPath.section) currentItemAttributes.frame = frame return currentItemAttributes } return nil } } private extension VariantFlowLayout { func evaluatedMinimumInteritemSpacing(at sectionIndex: Int) -> CGFloat { if let delegate = collectionView?.delegate as? UICollectionViewDelegateFlowLayout, let collection = collectionView { let inteitemSpacing = delegate.collectionView?(collection, layout: self, minimumInteritemSpacingForSectionAt: sectionIndex) if let inteitemSpacing = inteitemSpacing { return inteitemSpacing } } return minimumInteritemSpacing } func evaluatedSectionInsetForItem(at index: Int) -> UIEdgeInsets { if let delegate = collectionView?.delegate as? UICollectionViewDelegateFlowLayout, let collection = collectionView { let insetForSection = delegate.collectionView?(collection, layout: self, insetForSectionAt: index) if let insetForSectionAt = insetForSection { return insetForSectionAt } } return sectionInset } } private extension UICollectionViewLayoutAttributes { func leftAlignFrame(with sectionInset: UIEdgeInsets) { frame.origin.x = sectionInset.left } }
mit
4b9407f4c65c6b2b656800b91ad35586
44.325581
176
0.680862
5.924012
false
false
false
false
cloudinary/cloudinary_ios
Example/Tests/UploadWidgetTests/UploaderWidgetPreviewTests/UploaderWidgetPreviewViewControllerTests.swift
1
8563
// // UploaderWidgetPreviewViewControllerTests.swift // // Copyright (c) 2020 Cloudinary (http://cloudinary.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // @testable import Cloudinary import Foundation import XCTest class UploaderWidgetPreviewViewControllerTests: WidgetBaseTest, CLDWidgetPreviewDelegate { var sut: CLDWidgetPreviewViewController! // MARK: - setup and teardown override func setUp() { super.setUp() } override func tearDown() { sut = nil super.tearDown() } // MARK: - delegate func widgetPreviewViewController(_ controller: CLDWidgetPreviewViewController, didFinishEditing assets: [CLDWidgetAssetContainer]) {} func widgetPreviewViewController(_ controller: CLDWidgetPreviewViewController, didSelect asset: CLDWidgetAssetContainer) {} func widgetPreviewViewControllerDidCancel(_ controller: CLDWidgetPreviewViewController) {} // MARK: - test init func test_init_emptyArray_shouldCreateObject() { // Given let assets: [CLDWidgetAssetContainer] = [] // When sut = CLDWidgetPreviewViewController(assets: assets) // Then XCTAssertNotNil(sut, "object should be initialized") } func test_init_emptyDelegate_shouldCreateObject() { // Given let assets = createMixAssetContainers() // When sut = CLDWidgetPreviewViewController(assets: assets, delegate: nil) // Then XCTAssertNotNil(sut, "object should be initialized") } func test_init_mixAssetsAndDelegate_shouldCreateObjectWithProperties() { // Given let assetContainers = createMixAssetContainers() // When sut = CLDWidgetPreviewViewController(assets: assetContainers, delegate: self) // Then XCTAssertNotNil(sut, "object should be initialized") XCTAssertNotNil(sut.delegate, "delegate should be initialized") XCTAssertEqual (sut.assets, assetContainers, "objects should be equal") XCTAssertEqual (sut.selectedIndex, 0, "selectedIndex should be created with default value of 0") } func test_init_imageAssetsAndDelegate_shouldCreateObjectWithProperties() { // Given let assetContainers = createImageOnlyAssetContainers() // When sut = CLDWidgetPreviewViewController(assets: assetContainers, delegate: self) // Then XCTAssertNotNil(sut, "object should be initialized") XCTAssertNotNil(sut.delegate, "delegate should be initialized") XCTAssertEqual (sut.assets, assetContainers, "objects should be equal") XCTAssertEqual (sut.selectedIndex, 0, "selectedIndex should be created with default value of 0") } func test_init_videoAssetsAndDelegate_shouldCreateObjectWithProperties() { // Given let assetContainers = createVideoOnlyAssetContainers() // When sut = CLDWidgetPreviewViewController(assets: assetContainers, delegate: self) // Then XCTAssertNotNil(sut, "object should be initialized") XCTAssertNotNil(sut.delegate, "delegate should be initialized") XCTAssertEqual (sut.assets, assetContainers, "objects should be equal") XCTAssertEqual (sut.selectedIndex, 0, "selectedIndex should be created with default value of 0") } func test_init_delegateAfterInit_shouldCreateObjectWithDelegate() { // Given let assetContainers = createMixAssetContainers() // When sut = CLDWidgetPreviewViewController(assets: assetContainers, delegate: nil) sut.delegate = self // Then XCTAssertNotNil(sut, "object should be initialized") XCTAssertNotNil(sut.delegate, "delegate should be initialized") } func test_createView_shouldCreateObjectWithUIElements() { // Given let assetContainers = createMixAssetContainers() // When sut = CLDWidgetPreviewViewController(assets: assetContainers, delegate: self) let _ = sut.view // Then XCTAssertNotNil(sut, "object should be initialized") XCTAssertNotNil(sut.collectionView, "object should be initialized") XCTAssertNotNil(sut.mainImageView, "object should be initialized") XCTAssertNotNil(sut.videoView, "object should be initialized") XCTAssertNotNil(sut.uploadButton, "object should be initialized") } func test_initWithAssetsAndCreateView_shouldCreateCollectionWithSpecificCellCount() { // Given let assetContainers = createMixAssetContainers() // When sut = CLDWidgetPreviewViewController(assets: assetContainers, delegate: self) let _ = sut.view // Then XCTAssertNotNil(sut, "object should be initialized") XCTAssertNotNil(sut.delegate, "object should be initialized") XCTAssertEqual (sut.collectionView.numberOfItems(inSection: 0),assetContainers.count, "objects should be equal") } func test_initWithMixAssetsAndCreateView_shouldCreateImageViewWithSpecificImage() { // Given let assetContainers = createMixAssetContainers() // When sut = CLDWidgetPreviewViewController(assets: assetContainers, delegate: self) let _ = sut.view // Then XCTAssertNotNil(sut, "object should be initialized") XCTAssertNotNil(sut.delegate, "object should be initialized") XCTAssertEqual (sut.mainImageView.image, assetContainers[0].presentationImage, "objects should be equal") } func test_initWithImageAssetsAndCreateView_shouldCreateImageViewWithSpecificImage() { // Given let assetContainers = createImageOnlyAssetContainers() // When sut = CLDWidgetPreviewViewController(assets: assetContainers, delegate: self) let _ = sut.view // Then XCTAssertNotNil(sut, "object should be initialized") XCTAssertNotNil(sut.delegate, "object should be initialized") XCTAssertEqual (sut.mainImageView.image, assetContainers[0].presentationImage, "objects should be equal") } func test_initWithVideoAssetsAndCreateView_shouldCreateImageViewWithSpecificImage() { // Given let assetContainers = createVideoOnlyAssetContainers() // When sut = CLDWidgetPreviewViewController(assets: assetContainers, delegate: self) let _ = sut.view // Then XCTAssertNotNil(sut, "object should be initialized") XCTAssertNotNil(sut.delegate, "object should be initialized") XCTAssertEqual (sut.videoView.player.currentItem, assetContainers[0].originalVideo, "objects should be equal") } func test_initWithAssetsAndCreateView_shouldCreateUploadButtonWithSpecificType() { // Given let assetContainers = createMixAssetContainers() // When sut = CLDWidgetPreviewViewController(assets: assetContainers, delegate: self) let _ = sut.view // Then XCTAssertNotNil(sut, "object should be initialized") XCTAssertNotNil(sut.delegate, "object should be initialized") XCTAssertEqual (sut.uploadButton.buttonType, .custom, "objects should be equal") } }
mit
f0e585f6b372fd9be351d3a756b74e9b
39.582938
137
0.678267
5.315332
false
true
false
false
SmallElephant/FEAlgorithm-Swift
11-GoldenInterview/11-GoldenInterview/String/MyString.swift
1
7062
// // MyString.swift // 11-GoldenInterview // // Created by keso on 2017/4/15. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation class MyString { // 1.1 字符串中的字符是否完全相同 func isUniqueChar(str:String)->Bool { if str.characters.count > 256 { return false } var chars:[Bool] = [Bool].init(repeating: false, count: 256) for i in 0..<str.characters.count { let temp:String = str[i] as String let index:Int = temp.toInt() if chars[index] { return false } chars[index] = true } return true } // 1.2 字符串反转 func reverseString(str:String) -> String { var arr = Array(str.characters) let count:Int = arr.count for i in 0..<count / 2 { swap(&arr[i], &arr[count - i - 1]) } return String(arr) } // 1.3 是否是变位词 func permutation(strA:String,strB:String) -> Bool { if strA.characters.count != strB.characters.count { return false } var arr:[Int] = [Int].init(repeating: 0, count: 256) for i in 0..<strA.characters.count { let temp:String = strA[i] as String let index:Int = temp.toInt() arr[index] = arr[index] + 1 } for i in 0..<strB.characters.count { let temp:String = strA[i] as String let index:Int = temp.toInt() if arr[index] - 1 < 0 { return false } } return true } // 1.4 空格替换 func replaceSpaces(str:String) -> String { var result:String = "" for i in 0..<str.characters.count { if str[i] == " " { result.append("%20") } else { result.append(str[i] as Character) } } return result } func replaceSpaces1(str:String) -> String { var spaceCount:Int = 0 let count:Int = str.characters.count for i in 0..<count { if (str[i] as Character) == " " { spaceCount += 1 } } let charCount:Int = count + spaceCount * 2 var chars:[Character] = [Character].init(repeating: " ", count: charCount) var index:Int = charCount - 1 for i in stride(from: count - 1, to: -1, by: -1) { if (str[i] as Character) == " " { chars[index] = "0" chars[index - 1] = "2" chars[index-2] = "%" index -= 3 } else { chars[index] = str[i] as Character index -= 1 } } return String(chars) } // 1.5 字符串压缩 func compressBetter(str:String) -> String { let count:Int = str.characters.count if count == 0 { return "" } var result:String = "" var last:Character = str[0] as Character var charCount:Int = 0 for i in 0..<count { let temp:Character = str[i] as Character if temp == last { charCount += 1 } else { result.append(last) result.append("\(charCount)") last = temp charCount = 1 } } result.append(last) result.append("\(charCount)") if result.characters.count >= count { return str } return result } // 1.6 给定一个N*N矩阵表示的推向,数组旋转90度 func rotate(data:inout [[Int]],n:Int) { for layer in 0..<n / 2 { let first:Int = layer let last:Int = n - 1 - first for i in first..<last { let offset:Int = i - first let top:Int = data[first][i] // top 数值 data[first][i] = data[last - offset][first] // 从左到上 data[last - offset][first] = data[last][last - offset] // 从下到左 data[last][last - offset] = data[i][last] // 从右到下 data[i][last] = top // 从上到右 } } } // 1.7 如果某个元素为0,那么所在的行列都清零 func clearZero(data:inout [[Int]]) { var rows:[Bool] = [Bool].init(repeating: false, count: data.count) var cols:[Bool] = [Bool].init(repeating: false, count: data[0].count) for i in 0..<rows.count { for j in 0..<cols.count { if data[i][j] == 0 { rows[i] = true cols[j] = true } } } for i in 0..<rows.count { for j in 0..<cols.count { if rows[i] || cols[j] { data[i][j] = 0 } } } } // 1.8 字符串旋转判断 func isRotation(orginal:String,rotation:String) -> Bool { let len:Int = orginal.characters.count if len > 0 && len == rotation.characters.count { let mergeStr:String = orginal + orginal return mergeStr.contains(rotation) } return false } // 句子翻转 func reverseSentence(sentence:String) -> String { if sentence.characters.count == 0 { return sentence } var strArr:[Character] = [] for char in sentence.characters { strArr.append(char) } reverseArr(strArr: &strArr, start: 0, end:strArr.count - 1) var start:Int = 0 var end:Int = 0 while end < strArr.count { if strArr[start] == " " { start += 1 end += 1 } else if strArr[end] == " " { reverseArr(strArr: &strArr, start:start, end:end - 1) start = end } else { end += 1 } } return String(strArr) } private func reverseArr(strArr:inout [Character],start:Int,end:Int) { var low:Int = start var high:Int = end while low < high { swap(&strArr[low], &strArr[high]) low += 1 high -= 1 } } }
mit
3f7bacb0a264a1ab922545b20824389b
23.172535
82
0.414421
4.40629
false
false
false
false
BlueCocoa/Maria
Maria/QuickSettingsViewController.swift
2
1803
// // QuickSettingsViewController.swift // Maria // // Created by ShinCurry on 2016/10/6. // Copyright © 2016年 ShinCurry. All rights reserved. // import Cocoa import Aria2RPC import SwiftyUserDefaults class QuickSettingsViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do view setup here. userDefaultsInit() } let defaults = MariaUserDefault.auto let maria = Maria.shared @IBOutlet weak var limitModeDownloadRate: NSTextField! @IBOutlet weak var limitModeUploadRate: NSTextField! } extension QuickSettingsViewController { @IBAction func finishEditing(_ sender: NSTextField) { var key = DefaultsKeys.limitModeDownloadRate switch sender { case limitModeDownloadRate: key = .limitModeDownloadRate case limitModeUploadRate: key = .limitModeUploadRate default: break } if let intValue = Int(sender.stringValue) { defaults[key] = intValue defaults.synchronize() } else { sender.stringValue = "\(defaults[key])" } if defaults[.enableLowSpeedMode] { if sender == limitModeDownloadRate || sender == limitModeUploadRate { let downloadSpeed = defaults[.limitModeDownloadRate] let uploadSpeed = defaults[.limitModeUploadRate] maria.rpc?.lowSpeedLimit(download: downloadSpeed, upload: uploadSpeed) } } } } extension QuickSettingsViewController { func userDefaultsInit() { limitModeDownloadRate.stringValue = "\(defaults[.limitModeDownloadRate])" limitModeUploadRate.stringValue = "\(defaults[.limitModeUploadRate])" } }
gpl-3.0
1fffa22b519e6b67e13efedb9d38f684
27.571429
86
0.64
4.891304
false
false
false
false
lucdion/aide-devoir
sources/AideDevoir/Classes/UI/Common/ActivityIndicator.swift
1
2044
// // ActivityIndicator.swift // LuxuryRetreats // // Created by Luc Dion on 2016-06-29. // Copyright © 2016 Mirego. All rights reserved. // import UIKit class ActivityIndicator: UIView { fileprivate static let defaultDelay: Float = 0 fileprivate let indicatorView: UIActivityIndicatorView fileprivate var timer: Timer? fileprivate var isAnimated = false init(activityIndicatorStyle style: UIActivityIndicatorViewStyle) { indicatorView = UIActivityIndicatorView(activityIndicatorStyle: style) super.init(frame: indicatorView.frame) indicatorView.hidesWhenStopped = true addSubview(indicatorView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() size = indicatorView.size indicatorView.setPosition(.positionCenters) } func start(_ afterDelay: Float = ActivityIndicator.defaultDelay, animate: Bool = true) { cancelTimer() isAnimated = true // timer = Timer.schedule(delay: TimeInterval(afterDelay)) { [weak self] (timer) -> Void in // guard let strongSelf = self , strongSelf.isAnimated else { return } // // if animate { // strongSelf.alpha = 0 // strongSelf.fadeIn(0.2, delay: 0, completion: nil) // } // // strongSelf.indicatorView.startAnimating() // } } func stop(_ animate: Bool = true) { cancelTimer() isAnimated = false if animate { fadeOut(0.1, delay: 0, completion: { [weak self] (_) in guard let strongSelf = self else { return } if !strongSelf.isAnimated { strongSelf.indicatorView.stopAnimating() } }) } else { indicatorView.stopAnimating() } } fileprivate func cancelTimer() { timer?.invalidate() timer = nil } }
apache-2.0
b90875b92765a3d19f0f09870ced548f
26.986301
98
0.604503
5.007353
false
false
false
false
mattiaberretti/MBDesign
MBDesign/Classes/Testo/MaterialTextField.swift
1
1426
// // MaterialTextField.swift // MaterialDesign // // Created by Mattia on 29/05/18. // import UIKit @IBDesignable public class MaterialTextField: BaseTextField { @IBInspectable public var DisableColore : UIColor = UIColor.lightGray @IBInspectable public var EnableColor : UIColor = UIColor.blue @IBInspectable public var UnderlineSize : CGFloat = 2 func setUp(){ self.borderStyle = .none self.layer.shadowColor = DisableColore.cgColor self.layer.shadowOffset = CGSize(width: 0, height: 1) self.layer.shadowOpacity = 1 self.layer.shadowRadius = 0 self.layer.masksToBounds = false self.layer.backgroundColor = UIColor.white.cgColor } public override func becomeFirstResponder() -> Bool { self.layer.shadowColor = EnableColor.cgColor return super.becomeFirstResponder() } public override func resignFirstResponder() -> Bool { self.layer.shadowColor = DisableColore.cgColor return super.resignFirstResponder() } override init(frame: CGRect) { super.init(frame: frame) self.setUp() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setUp() } override public func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() self.setUp() } }
mit
90b24f26c58c5e82cd029c4ec9d8c7bb
24.464286
61
0.649369
4.785235
false
false
false
false
yarshure/Surf
Surf/BarChatsCell.swift
1
4868
// // BarChatsCell.swift // Surf // // Created by yarshure on 2018/1/16. // Copyright © 2018年 A.BIG.T. All rights reserved. // import UIKit import Charts import XRuler class BarChatsCell: UIView,ChartViewDelegate { @IBOutlet weak var chartView:Charts.BarChartView? override func awakeFromNib(){ if let chartView = chartView { chartView.chartDescription?.enabled = false chartView.dragEnabled = true chartView.setScaleEnabled(true) chartView.pinchZoomEnabled = false // ChartYAxis *leftAxis = chartView.leftAxis; let xAxis = chartView.xAxis xAxis.labelPosition = .bottom chartView.rightAxis.enabled = false chartView.delegate = self chartView.drawBarShadowEnabled = false chartView.drawValueAboveBarEnabled = false chartView.maxVisibleCount = 60 xAxis.labelPosition = .bottom xAxis.labelFont = .systemFont(ofSize: 10) xAxis.granularity = 1 xAxis.labelCount = 7 //xAxis.valueFormatter = DayAxisValueFormatter(chart: chartView) let leftAxisFormatter = NumberFormatter() leftAxisFormatter.minimumFractionDigits = 0 leftAxisFormatter.maximumFractionDigits = 1 leftAxisFormatter.negativeSuffix = " $" leftAxisFormatter.positiveSuffix = " $" let leftAxis = chartView.leftAxis leftAxis.labelFont = .systemFont(ofSize: 10) leftAxis.labelCount = 8 leftAxis.valueFormatter = DefaultAxisValueFormatter(formatter: leftAxisFormatter) leftAxis.labelPosition = .outsideChart leftAxis.spaceTop = 0.15 leftAxis.axisMinimum = 0 // FIXME: HUH?? this replaces startAtZero = YES let rightAxis = chartView.rightAxis rightAxis.enabled = true rightAxis.labelFont = .systemFont(ofSize: 10) rightAxis.labelCount = 8 rightAxis.valueFormatter = leftAxis.valueFormatter rightAxis.spaceTop = 0.15 rightAxis.axisMinimum = 0 let l = chartView.legend l.horizontalAlignment = .left l.verticalAlignment = .bottom l.orientation = .horizontal l.drawInside = false l.form = .circle l.formSize = 9 l.font = UIFont(name: "HelveticaNeue-Light", size: 11)! l.xEntrySpace = 4 // chartView.legend = l // let marker = XYMarkerView(color: UIColor(white: 180/250, alpha: 1), // font: .systemFont(ofSize: 12), // textColor: .white, // insets: UIEdgeInsets(top: 8, left: 8, bottom: 20, right: 8), // xAxisValueFormatter: chartView.xAxis.valueFormatter!) // marker.chartView = chartView // marker.minimumSize = CGSize(width: 80, height: 40) // chartView.marker = marker // slidersValueChanged(nil) } } func updateChartData() { self.setDataCount(60, range: UInt32(1000)) } func setDataCount(_ count: Int, range: UInt32) { guard let chartView = chartView else { return } let start = 1 let yVals = (start..<start+count+1).map { (i) -> BarChartDataEntry in let mult = range + 1 let val = Double(arc4random_uniform(mult)) if arc4random_uniform(100) < 25 { return BarChartDataEntry(x: Double(i), y: val, icon: UIImage(named: "icon")) } else { return BarChartDataEntry(x: Double(i), y: val) } } var set1: BarChartDataSet! = nil if let set = chartView.data?.dataSets.first as? BarChartDataSet { set1 = set //set1.values = yVals chartView.data?.notifyDataChanged() chartView.notifyDataSetChanged() } else { set1 = BarChartDataSet(entries: yVals, label: "The year 2017") set1.colors = ChartColorTemplates.material() set1.drawValuesEnabled = false let data = BarChartData(dataSet: set1) data.setValueFont(UIFont(name: "HelveticaNeue-Light", size: 10)!) data.barWidth = 0.9 chartView.data = data } // chartView.setNeedsDisplay() } func updateFlow(_ flow:NetFlow) { updateChartData() } }
bsd-3-clause
28d6054dfcc104c0471d46b9895bc2ea
35.037037
100
0.540391
5.405556
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Blog/Site Settings/HomepageSettingsViewController.swift
1
13381
import UIKit import WordPressFlux import WordPressShared @objc open class HomepageSettingsViewController: UITableViewController { fileprivate enum PageSelectionType { case homepage case postsPage var title: String { switch self { case .homepage: return Strings.homepage case .postsPage: return Strings.postsPage } } var pickerTitle: String { switch self { case .homepage: return Strings.homepagePicker case .postsPage: return Strings.postsPagePicker } } var publishedPostsOnly: Bool { switch self { case .homepage: return true case .postsPage: return false } } } fileprivate lazy var handler: ImmuTableViewHandler = { return ImmuTableViewHandler(takeOver: self) }() /// Designated Initializer /// /// - Parameter blog: The blog for which we want to configure Homepage settings /// @objc public convenience init(blog: Blog) { self.init(style: .grouped) self.blog = blog let context = blog.managedObjectContext ?? ContextManager.shared.mainContext postService = PostService(managedObjectContext: context) } open override func viewDidLoad() { super.viewDidLoad() title = Strings.title clearsSelectionOnViewWillAppear = false // Setup tableView WPStyleGuide.configureColors(view: view, tableView: tableView) WPStyleGuide.configureAutomaticHeightRows(for: tableView) ImmuTable.registerRows([CheckmarkRow.self, NavigationItemRow.self, ActivityIndicatorRow.self], tableView: tableView) reloadViewModel() fetchAllPages() } private func fetchAllPages() { let options = PostServiceSyncOptions() options.number = 20 postService.syncPosts(ofType: .page, with: options, for: blog, success: { [weak self] posts in self?.reloadViewModel() }, failure: { _ in }) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) animateDeselectionInteractively() } // MARK: - Model fileprivate func reloadViewModel() { handler.viewModel = tableViewModel } fileprivate var tableViewModel: ImmuTable { guard let homepageType = blog.homepageType else { return ImmuTable(sections: []) } let homepageRows: [ImmuTableRow] if case .homepageType = inProgressChange { homepageRows = updatingHomepageTypeRows } else { homepageRows = homepageTypeRows } let changeTypeSection = ImmuTableSection(headerText: nil, rows: homepageRows, footerText: Strings.footerText) let choosePagesSection = ImmuTableSection(headerText: Strings.choosePagesHeaderText, rows: selectedPagesRows) var sections = [changeTypeSection] if homepageType == .page { sections.append(choosePagesSection) } return ImmuTable(sections: sections) } // MARK: - Table Rows var updatingHomepageTypeRows: [ImmuTableRow] { guard let homepageType = blog.homepageType else { return [] } return [ ActivityIndicatorRow(title: HomepageType.posts.title, animating: homepageType == .posts, action: nil), ActivityIndicatorRow(title: HomepageType.page.title, animating: homepageType == .page, action: nil) ] } var homepageTypeRows: [ImmuTableRow] { guard let homepageType = blog.homepageType else { return [] } return [ CheckmarkRow(title: HomepageType.posts.title, checked: homepageType == .posts, action: { [weak self] _ in if self?.inProgressChange == nil { self?.update(with: .homepageType(.posts)) } }), CheckmarkRow(title: HomepageType.page.title, checked: homepageType == .page, action: { [weak self] _ in if self?.inProgressChange == nil { self?.update(with: .homepageType(.page)) } }) ] } var selectedPagesRows: [ImmuTableRow] { let homepageID = blog.homepagePageID let homepage = homepageID.flatMap { postService.findPost(withID: NSNumber(value: $0), in: blog) } let homepageTitle = homepage?.titleForDisplay() ?? "" let postsPageID = blog.homepagePostsPageID let postsPage = postsPageID.flatMap { postService.findPost(withID: NSNumber(value: $0), in: blog) } let postsPageTitle = postsPage?.titleForDisplay() ?? "" let homepageRow = pageSelectionRow(selectionType: .homepage, detail: homepageTitle, selectedPostID: blog?.homepagePageID, hiddenPostID: blog?.homepagePostsPageID, isInProgress: HomepageChange.isSelectedHomepage, changeForPost: { .selectedHomepage($0) }) let postsPageRow = pageSelectionRow(selectionType: .postsPage, detail: postsPageTitle, selectedPostID: blog?.homepagePostsPageID, hiddenPostID: blog?.homepagePageID, isInProgress: HomepageChange.isSelectedPostsPage, changeForPost: { .selectedPostsPage($0) }) return [homepageRow, postsPageRow] } private func pageSelectionRow(selectionType: PageSelectionType, detail: String, selectedPostID: Int?, hiddenPostID: Int?, isInProgress: (HomepageChange) -> Bool, changeForPost: @escaping (Int) -> HomepageChange) -> ImmuTableRow { if let inProgressChange = inProgressChange, isInProgress(inProgressChange) { return ActivityIndicatorRow(title: selectionType.title, animating: true, action: nil) } else { return NavigationItemRow(title: selectionType.title, detail: detail, action: { [weak self] _ in self?.showPageSelection(selectionType: selectionType, selectedPostID: selectedPostID, hiddenPostID: hiddenPostID, change: changeForPost) }) } } // MARK: - Page Selection Navigation private func showPageSelection(selectionType: PageSelectionType, selectedPostID: Int?, hiddenPostID: Int?, change: @escaping (Int) -> HomepageChange) { pushPageSelection(selectionType: selectionType, selectedPostID: selectedPostID, hiddenPostID: hiddenPostID) { [weak self] selected in if let postID = selected.postID?.intValue { self?.update(with: change(postID)) } } } fileprivate func pushPageSelection(selectionType: PageSelectionType, selectedPostID: Int?, hiddenPostID: Int?, _ completion: @escaping (Page) -> Void) { let hiddenPosts: [Int] if let postID = hiddenPostID { hiddenPosts = [postID] } else { hiddenPosts = [] } let viewController = SelectPostViewController(blog: blog, isSelectedPost: { $0.postID?.intValue == selectedPostID }, showsPostType: false, entityName: Page.entityName(), hiddenPosts: hiddenPosts, publishedOnly: selectionType.publishedPostsOnly, callback: { [weak self] (post) in if let page = post as? Page { completion(page) } self?.navigationController?.popViewController(animated: true) }) viewController.title = selectionType.pickerTitle navigationController?.pushViewController(viewController, animated: true) } // MARK: - Remote Updating /// The options for changing a homepage /// Note: This is mapped to the actual property changes in `update(with change:)` private enum HomepageChange { case homepageType(HomepageType) case selectedHomepage(Int) case selectedPostsPage(Int) static func isHomepageType(_ change: HomepageChange) -> Bool { if case .homepageType = change { return true } else { return false } } static func isSelectedHomepage(_ change: HomepageChange) -> Bool { if case .selectedHomepage = change { return true } else { return false } } static func isSelectedPostsPage(_ change: HomepageChange) -> Bool { if case .selectedPostsPage = change { return true } else { return false } } } /// Sends the remote service call to update `blog` homepage settings properties. /// - Parameter change: The change to update for `blog`. private func update(with change: HomepageChange) { guard inProgressChange == nil else { return } /// Configure `blog` properties for the remote call let homepageType: HomepageType var homepagePostsPageID = blog.homepagePostsPageID var homepagePageID = blog.homepagePageID switch change { case .homepageType(let type): homepageType = type case .selectedPostsPage(let id): homepageType = .page homepagePostsPageID = id case .selectedHomepage(let id): homepageType = .page homepagePageID = id } /// If the blog hasn't changed, don't waste time saving it. guard blog.homepageType != homepageType || blog.homepagePostsPageID != homepagePostsPageID || blog.homepagePageID != homepagePageID else { return } inProgressChange = change /// If there is already an in progress change (i.e. bad network), don't push the view controller and deselect the selection immediately. tableView.allowsSelection = false /// Send the remove service call let service = HomepageSettingsService(blog: blog, context: blog.managedObjectContext!) service?.setHomepageType(homepageType, withPostsPageID: homepagePostsPageID, homePageID: homepagePageID, success: { [weak self] in self?.endUpdating() }, failure: { [weak self] error in self?.endUpdating() let notice = Notice(title: Strings.updateErrorTitle, message: Strings.updateErrorMessage, feedbackType: .error) ActionDispatcher.global.dispatch(NoticeAction.post(notice)) }) reloadViewModel() } fileprivate func endUpdating() { inProgressChange = nil tableView.allowsSelection = true reloadViewModel() } // MARK: - Private Properties fileprivate var blog: Blog! fileprivate var postService: PostService! /// Are we currently updating the homepage type? private var inProgressChange: HomepageChange? = nil fileprivate enum Strings { static let title = NSLocalizedString("Homepage Settings", comment: "Title for the Homepage Settings screen") static let footerText = NSLocalizedString("Choose from a homepage that displays your latest posts (classic blog) or a fixed / static page.", comment: "Explanatory text for Homepage Settings homepage type selection.") static let homepage = NSLocalizedString("Homepage", comment: "Title for setting which shows the current page assigned as a site's homepage") static let homepagePicker = NSLocalizedString("Choose Homepage", comment: "Title for selecting a new homepage") static let postsPage = NSLocalizedString("Posts Page", comment: "Title for setting which shows the current page assigned as a site's posts page") static let postsPagePicker = NSLocalizedString("Choose Posts Page", comment: "Title for selecting a new posts page") static let choosePagesHeaderText = NSLocalizedString("Choose Pages", comment: "Title for settings section which allows user to select their home page and posts page") static let updateErrorTitle = NSLocalizedString("Unable to update homepage settings", comment: "Error informing the user that their homepage settings could not be updated") static let updateErrorMessage = NSLocalizedString("Please try again later.", comment: "Prompt for the user to retry a failed action again later") } }
gpl-2.0
52cdc454be19d8c38fee08c3efefd544
40.685358
224
0.591959
5.587056
false
false
false
false
kalvish21/AndroidMessenger
AndroidMessengerMacDesktopClient/AndroidMessenger/Classes/NSColor-Extension.swift
1
1583
// // NSColor-Extension.swift // AndroidMessenger // // Created by Kalyan Vishnubhatla on 3/26/16. // Copyright © 2016 Kalyan Vishnubhatla. All rights reserved. // import Foundation import Cocoa extension NSColor { static func NSColorFromRGB(rgbValue: UInt) -> NSColor { return NSColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } static func NSColorFromHex(hexValue: String) -> NSColor { var result : NSColor? = nil var colorCode : UInt32 = 0 var redByte, greenByte, blueByte : UInt8 // these two lines are for web color strings that start with a # // -- as in #ABCDEF; remove if you don't have # in the string let index1 = hexValue.endIndex.advancedBy(-6) let substring1 = hexValue.substringFromIndex(index1) let scanner = NSScanner(string: substring1) let success = scanner.scanHexInt(&colorCode) if success == true { redByte = UInt8.init(truncatingBitPattern: (colorCode >> 16)) greenByte = UInt8.init(truncatingBitPattern: (colorCode >> 8)) blueByte = UInt8.init(truncatingBitPattern: colorCode) // masks off high bits result = NSColor(calibratedRed: CGFloat(redByte) / 0xff, green: CGFloat(greenByte) / 0xff, blue: CGFloat(blueByte) / 0xff, alpha: 1.0) } return result! } }
mit
ee050340f78e75b81066faf1c27e6e8d
34.155556
146
0.609355
4.087855
false
false
false
false
jriehn/swift-2.0
Swift20.playground/Pages/Pyramid of Doom.xcplaygroundpage/Contents.swift
1
563
//: # Pyramid of Doom import Foundation func getJsonResponse(response: NSObject?) { if let response = response { if let dict = response as? Dictionary<String, NSObject> { if let user = dict["user"] as? Dictionary<String, NSObject> { if let adress = user["adress"] as? Dictionary<String, NSObject> { if let country = adress["country"] as? String { print(country) } } } } } } //: [Previous](@previous) | [Next](@next)
gpl-3.0
455bf728bad14a4f53701b76c8623d56
28.631579
81
0.509769
4.468254
false
false
false
false
arcontrerasa/SwiftParseRestClient
ParseRestClient/Operation.swift
1
3849
// // Operation.swift // Pods // // Created by Armando Contreras on 9/15/15. // // import Foundation import UIKit class Operation: NSOperation { // use the KVO mechanism to indicate that changes to "state" affect other properties as well class func keyPathsForValuesAffectingIsReady() -> Set<NSObject> { return ["state"] } class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> { return ["state"] } class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> { return ["state"] } class func keyPathsForValuesAffectingIsCancelled() -> Set<NSObject> { return ["state"] } // MARK: State Management private enum State: Int, Comparable { /// The initial state of an `Operation`. case Initialized /// The `Operation` is ready to begin evaluating conditions. case Pending /// The `Operation` is evaluating conditions. case EvaluatingConditions /** The `Operation`'s conditions have all been satisfied, and it is ready to execute. */ case Ready /// The `Operation` is executing. case Executing /** Execution of the `Operation` has finished, but it has not yet notified the queue of this. */ case Finishing /// The `Operation` has finished executing. case Finished /// The `Operation` has been cancelled. case Cancelled } func execute() { print("\(self.dynamicType) must override `execute()`.") finish() } /** Indicates that the Operation can now begin to evaluate readiness conditions, if appropriate. */ func willEnqueue() { state = .Pending } /// Private storage for the `state` property that will be KVO observed. private var _state = State.Initialized private var state: State { get { return _state } set(newState) { // Manually fire the KVO notifications for state change, since this is "private". willChangeValueForKey("state") switch (_state, newState) { case (.Cancelled, _): break // cannot leave the cancelled state case (.Finished, _): break // cannot leave the finished state default: assert(_state != newState, "Performing invalid cyclic state transition.") _state = newState } didChangeValueForKey("state") } } private var _internalErrors = [NSError]() override func cancel() { cancelWithError() } func cancelWithError(error: NSError? = nil) { if let error = error { _internalErrors.append(error) } state = .Cancelled } private(set) var observers = [OperationObserver]() func addObserver(observer: OperationObserver) { assert(state < .Executing, "Cannot modify observers after execution has begun.") observers.append(observer) } private var hasFinishedAlready = false final func finish(errors: [NSError] = []) { if !hasFinishedAlready { hasFinishedAlready = true state = .Finishing state = .Finished } } } // Simple operator functions to simplify the assertions used above. private func <(lhs: Operation.State, rhs: Operation.State) -> Bool { return lhs.rawValue < rhs.rawValue } private func ==(lhs: Operation.State, rhs: Operation.State) -> Bool { return lhs.rawValue == rhs.rawValue }
mit
2d5fbae050e52586ae4a8d7e64555d6b
25.013514
96
0.564302
5.301653
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
RxSwiftGuideRead/RxSwift-master/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift
3
4241
// // GitHubSearchRepositoriesViewController.swift // RxExample // // Created by Yoshinori Sano on 9/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import UIKit import RxSwift import RxCocoa extension UIScrollView { func isNearBottomEdge(edgeOffset: CGFloat = 20.0) -> Bool { return self.contentOffset.y + self.frame.size.height + edgeOffset > self.contentSize.height } } class GitHubSearchRepositoriesViewController: ViewController, UITableViewDelegate { static let startLoadingOffset: CGFloat = 20.0 @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Repository>>( configureCell: { (_, tv, ip, repository: Repository) in let cell = tv.dequeueReusableCell(withIdentifier: "Cell")! cell.textLabel?.text = repository.name cell.detailTextLabel?.text = repository.url.absoluteString return cell }, titleForHeaderInSection: { dataSource, sectionIndex in let section = dataSource[sectionIndex] return section.items.count > 0 ? "Repositories (\(section.items.count))" : "No repositories found" } ) override func viewDidLoad() { super.viewDidLoad() let tableView: UITableView = self.tableView let loadNextPageTrigger: (Driver<GitHubSearchRepositoriesState>) -> Signal<()> = { state in tableView.rx.contentOffset.asDriver() .withLatestFrom(state) .flatMap { state in return tableView.isNearBottomEdge(edgeOffset: 20.0) && !state.shouldLoadNextPage ? Signal.just(()) : Signal.empty() } } let activityIndicator = ActivityIndicator() let searchBar: UISearchBar = self.searchBar let state = githubSearchRepositories( searchText: searchBar.rx.text.orEmpty.changed.asSignal().throttle(.milliseconds(300)), loadNextPageTrigger: loadNextPageTrigger, performSearch: { URL in GitHubSearchRepositoriesAPI.sharedAPI.loadSearchURL(URL) .trackActivity(activityIndicator) }) state .map { $0.isOffline } .drive(navigationController!.rx.isOffline) .disposed(by: disposeBag) state .map { $0.repositories } .distinctUntilChanged() .map { [SectionModel(model: "Repositories", items: $0.value)] } .drive(tableView.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) tableView.rx.modelSelected(Repository.self) .subscribe(onNext: { repository in UIApplication.shared.openURL(repository.url) }) .disposed(by: disposeBag) state .map { $0.isLimitExceeded } .distinctUntilChanged() .filter { $0 } .drive(onNext: { n in showAlert("Exceeded limit of 10 non authenticated requests per minute for GitHub API. Please wait a minute. :(\nhttps://developer.github.com/v3/#rate-limiting") }) .disposed(by: disposeBag) tableView.rx.contentOffset .subscribe { _ in if searchBar.isFirstResponder { _ = searchBar.resignFirstResponder() } } .disposed(by: disposeBag) // so normal delegate customization can also be used tableView.rx.setDelegate(self) .disposed(by: disposeBag) // activity indicator in status bar // { activityIndicator .drive(UIApplication.shared.rx.isNetworkActivityIndicatorVisible) .disposed(by: disposeBag) // } } // MARK: Table view delegate func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } deinit { // I know, I know, this isn't a good place of truth, but it's no self.navigationController?.navigationBar.backgroundColor = nil } }
mit
90ec5ca2c96bd78edff36981ef4632a4
34.041322
177
0.609198
5.3
false
false
false
false
ethan605/SwiftVD
swiftvd/swiftvd/ServerHelper.swift
1
4233
// // ServerHelper.swift // swiftvd // // Created by Ethan Nguyen on 6/7/14. // Copyright (c) 2014 Volcano. All rights reserved. // import Foundation let kServerUrl = "http://open-api.depvd.com" let kServerApiKey = "8FDON-OH3JX-H4XYF-TBFGV-YFNGR" struct SingletonServerHelper { static var sharedInstance: ServerHelper? = nil static var token: dispatch_once_t = 0 } class ServerHelper: AFHTTPSessionManager { class func sharedHelper() -> ServerHelper { dispatch_once(&SingletonServerHelper.token, { SingletonServerHelper.sharedInstance = ServerHelper(baseURL: NSURL(string: kServerUrl)) }) return SingletonServerHelper.sharedInstance! } func verifyKey(completionBlock: (success: Bool, errorMessage: String?) -> Void) { NSLog("Verify API with key \(kServerApiKey)") self.GET("VerifyKey", parameters: ["key" : kServerApiKey], success: { (task: NSURLSessionDataTask!, responseObject: AnyObject!) -> Void in self.handleResponse(response: responseObject) { (authenticated: Bool, errorMessage: String?) -> Void in if errorMessage { completionBlock(success: false, errorMessage: errorMessage) } else if !authenticated { completionBlock(success: false, errorMessage: "Authentication failed!") } else { completionBlock(success: true, errorMessage: nil) } } }, failure: { (task: NSURLSessionDataTask!, error: NSError!) -> Void in completionBlock(success: false, errorMessage: "\(error.localizedDescription)") }) } func getNewTopics(atPage page: Int, callback block: (data: MTopic[]?, errorMessage: String?) -> Void) { self.GET("Topic/GetNewTopics", parameters: ["page" : page], success: { (task: NSURLSessionDataTask!, responseObject: AnyObject!) -> Void in self.handleResponse(response: responseObject) { (authenticated: Bool, errorMessage: String?) -> Void in if errorMessage { block(data: nil, errorMessage: errorMessage) } else if authenticated { var allTopics = MTopic[]() if let content = responseObject.valueForKey("content") as NSDictionary! { if let topics = content["topics"] as NSArray! { for dict : AnyObject in topics { var mTopic = MTopic(dictionary: dict as NSDictionary) allTopics += mTopic } block(data: allTopics, errorMessage: nil) } else { block(data: nil, errorMessage: "Invalid response format \(content)") } } else { block(data: nil, errorMessage: "Invalid response format") } } else { self.verifyKey() { (success: Bool, errorMessage: String?) -> Void in if success { self.getNewTopics(atPage: page, callback: block) } else { block(data: nil, errorMessage: errorMessage) } } } } }, failure: { (task: NSURLSessionDataTask!, error: NSError!) -> Void in block(data: nil, errorMessage: "\(error.localizedDescription)") }) } func handleResponse(response responseObject: AnyObject!, callback block:(authenticated: Bool, errorMessage: String?) -> Void) { if let codeNumber = responseObject.valueForKey("code") as NSNumber! { if let code = codeNumber.integerValue as Int! { switch code { case 200: block(authenticated: true, errorMessage: nil) break case 401: block(authenticated: false, errorMessage: nil) break default: block(authenticated: false, errorMessage: "Invalid response code: \(code)") break } } else { block(authenticated: false, errorMessage: "Invalid response code format: \(codeNumber)") } } else { block(authenticated: false, errorMessage: "Invalid response body: \(responseObject)") } } }
mit
b99d05d715ee3c9d9feb23a0bb287e30
33.414634
129
0.586345
4.871116
false
false
false
false
luckymore0520/GreenTea
Loyalty/Activity/ViewModels/CommentViewModel.swift
1
897
// // CommentViewModel.swift // Loyalty // // Created by WangKun on 16/5/21. // Copyright © 2016年 WangKun. All rights reserved. // import Foundation typealias CommmentPresentable = protocol<TitlePresentable,WebIconPresentable,HasHiddenComponent,StarPresentable,DetailPresentable> struct CommentViewModel:CommmentPresentable { var iconName: String var title: String var detail: String var shouldHidden: Bool var starCount: Double init(comment:Comment) { self.iconName = comment.userIcon?.url ?? "" self.title = comment.userNickname if let replyName = comment.replyName { self.detail = "\(replyName.length > 0 ? "回复\(replyName):" : "") \(comment.content)" } else { self.detail = comment.content } self.shouldHidden = comment.rate == 0 self.starCount = Double(comment.rate) } }
mit
e2d62b6323b104500a0bde8f0779b4a0
28.666667
130
0.665169
4.045455
false
false
false
false
bppr/Swiftest
src/Swiftest/Core/Expectations/Matchers/VoidMatcher.swift
1
3930
public protocol Numeric: Equatable { func +(lhs: Self, rhs: Self) -> Self } extension Double : Numeric {} extension Float : Numeric {} extension Int : Numeric {} extension Int8 : Numeric {} extension Int16 : Numeric {} extension Int32 : Numeric {} extension Int64 : Numeric {} extension UInt : Numeric {} extension UInt8 : Numeric {} extension UInt16 : Numeric {} extension UInt32 : Numeric {} extension UInt64 : Numeric {} public class ThrowableVoidPredicate<T:Equatable> { var initialVal : T let subject: Void throws -> Void let fn: Void -> T var parent: ThrowableVoidMatcher public init(fn: Void -> T, subject: Void throws -> Void, parent: ThrowableVoidMatcher) { self.parent = parent self.subject = subject self.initialVal = fn() self.fn = fn } public func from(expected: T) -> ThrowableVoidPredicate { _assert( initialVal == expected, msg: "expected an original value of \(expected), but was \(initialVal)" ) return self } public func to(expected: T) throws { try subject() _assert( fn() == expected, msg: "expected \(initialVal) to change to \(expected), " + "changed to \(fn())" ) } public func _assert(cond: Bool, msg: String) { parent.core.assert(fn: { return cond }, msg: msg) } } public class VoidPredicate<T:Equatable> { var initialVal : T let subject: Void -> Void let fn: Void -> T var parent: VoidMatcher public init(fn: Void -> T, subject: Void -> Void, parent: VoidMatcher) { self.parent = parent self.subject = subject self.initialVal = fn() self.fn = fn } public func from(expected: T) -> VoidPredicate { _assert( initialVal == expected, msg: "expected an original value of \(expected), but was \(initialVal)" ) return self } public func to(expected: T) { subject() _assert( fn() == expected, msg: "expected \(initialVal) to change to \(expected), " + "changed to \(fn())" ) } public func _assert(cond: Bool, msg: String) { parent.core.assert(fn: { return cond }, msg: msg) } } extension VoidPredicate where T:Numeric { public func by(delta: T) { let oldVal = initialVal subject() _assert( fn() == oldVal + delta, msg: "expected change (by \(delta)) from \(initialVal) to " + "\(oldVal + delta), changed to \(fn())" ) } } public class ThrowableVoidMatcher : Matcher { public typealias SubjectType = (Void throws -> Void) let subject: SubjectType? let core: MatcherCore required public init(subject: SubjectType?, callback: AssertionBlock, reverse: Bool) { self.subject = subject self.core = MatcherCore(callback: callback, reverse: reverse) } public func throwError() { do { try subject!() core.assert(fn: { return false }, msg: "throw error") } catch { core.assert(fn: { return true }, msg: "throw error") } } public func throwError<T:ErrorProtocol>(type: T) { do { try subject!() core.assert( fn: { return false }, msg: "throw \(type) error, but no error was thrown" ) } catch let err as T where "\(err)" == "\(type)" { core.assert( fn: { return true }, msg: "throw \(type) error" ) } catch let err { core.assert( fn: { return false }, msg: "throw \(type) error, got \(err.dynamicType).\(err)" ) } } } public class VoidMatcher: Matcher { public typealias SubjectType = (Void -> Void) let subject: SubjectType? let core: MatcherCore required public init(subject: SubjectType?, callback: AssertionBlock, reverse: Bool) { self.subject = subject self.core = MatcherCore(callback: callback, reverse: reverse) } public func change<T:Equatable>(fn: (Void -> T)) -> VoidPredicate<T> { return VoidPredicate(fn: fn, subject: subject!, parent: self) } }
mit
68c6d3d295528c7fb5080aeba8b407bc
22.963415
90
0.61883
3.819242
false
false
false
false
powerytg/Accented
Accented/UI/User/ViewModels/UserStreamViewController.swift
1
1635
// // UserStreamViewController.swift // Accented // // User stream controller // // Created by Tiangong You on 5/31/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit class UserStreamViewController: StreamViewController { var user : UserModel var displayStyle : StreamDisplayStyle init(user : UserModel, stream: StreamModel, style : StreamDisplayStyle) { self.displayStyle = style self.user = user super.init(stream) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func createViewModel() { if displayStyle == .group { viewModel = UserStreamViewModel(user : user, stream: stream, collectionView: collectionView, flowLayoutDelegate: self) } else if displayStyle == .card { viewModel = UserStreamCardViewModel(user : user, stream: stream, collectionView: collectionView, flowLayoutDelegate: self) } } override func streamDidUpdate(_ notification : Notification) -> Void { let streamId = notification.userInfo![StorageServiceEvents.streamId] as! String let page = notification.userInfo![StorageServiceEvents.page] as! Int guard streamId == stream.streamId else { return } // Get a new copy of the stream let userModel = stream as! UserStreamModel stream = StorageService.sharedInstance.getUserStream(userId: userModel.userId) if let vm = streamViewModel { vm.collecitonDidUpdate(collection: stream, page: page) } } }
mit
0bbb840cb11eae88837047250059ed06
32.346939
134
0.664627
4.848665
false
false
false
false
krzysztofzablocki/Sourcery
SourceryRuntime/Sources/AST/Subscript.swift
1
7406
import Foundation /// Describes subscript @objcMembers public final class Subscript: NSObject, SourceryModel, Annotated, Documented, Definition { /// Method parameters public var parameters: [MethodParameter] /// Return value type name used in declaration, including generic constraints, i.e. `where T: Equatable` public var returnTypeName: TypeName /// Actual return value type name if declaration uses typealias, otherwise just a `returnTypeName` public var actualReturnTypeName: TypeName { return returnTypeName.actualTypeName ?? returnTypeName } // sourcery: skipEquality, skipDescription /// Actual return value type, if known public var returnType: Type? // sourcery: skipEquality, skipDescription /// Whether return value type is optional public var isOptionalReturnType: Bool { return returnTypeName.isOptional } // sourcery: skipEquality, skipDescription /// Whether return value type is implicitly unwrapped optional public var isImplicitlyUnwrappedOptionalReturnType: Bool { return returnTypeName.isImplicitlyUnwrappedOptional } // sourcery: skipEquality, skipDescription /// Return value type name without attributes and optional type information public var unwrappedReturnTypeName: String { return returnTypeName.unwrappedTypeName } /// Whether method is final public var isFinal: Bool { modifiers.contains { $0.name == "final" } } /// Variable read access level, i.e. `internal`, `private`, `fileprivate`, `public`, `open` public let readAccess: String /// Variable write access, i.e. `internal`, `private`, `fileprivate`, `public`, `open`. /// For immutable variables this value is empty string public var writeAccess: String /// Whether variable is mutable or not public var isMutable: Bool { return writeAccess != AccessLevel.none.rawValue } /// Annotations, that were created with // sourcery: annotation1, other = "annotation value", alterantive = 2 public let annotations: Annotations public let documentation: Documentation /// Reference to type name where the method is defined, /// nil if defined outside of any `enum`, `struct`, `class` etc public let definedInTypeName: TypeName? /// Reference to actual type name where the method is defined if declaration uses typealias, otherwise just a `definedInTypeName` public var actualDefinedInTypeName: TypeName? { return definedInTypeName?.actualTypeName ?? definedInTypeName } // sourcery: skipEquality, skipDescription /// Reference to actual type where the object is defined, /// nil if defined outside of any `enum`, `struct`, `class` etc or type is unknown public var definedInType: Type? /// Method attributes, i.e. `@discardableResult` public let attributes: AttributeList /// Method modifiers, i.e. `private` public let modifiers: [SourceryModifier] // Underlying parser data, never to be used by anything else // sourcery: skipEquality, skipDescription, skipCoding, skipJSExport /// :nodoc: public var __parserData: Any? /// :nodoc: public init(parameters: [MethodParameter] = [], returnTypeName: TypeName, accessLevel: (read: AccessLevel, write: AccessLevel) = (.internal, .internal), attributes: AttributeList = [:], modifiers: [SourceryModifier] = [], annotations: [String: NSObject] = [:], documentation: [String] = [], definedInTypeName: TypeName? = nil) { self.parameters = parameters self.returnTypeName = returnTypeName self.readAccess = accessLevel.read.rawValue self.writeAccess = accessLevel.write.rawValue self.attributes = attributes self.modifiers = modifiers self.annotations = annotations self.documentation = documentation self.definedInTypeName = definedInTypeName } // sourcery:inline:Subscript.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let parameters: [MethodParameter] = aDecoder.decode(forKey: "parameters") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["parameters"])); fatalError() }; self.parameters = parameters guard let returnTypeName: TypeName = aDecoder.decode(forKey: "returnTypeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["returnTypeName"])); fatalError() }; self.returnTypeName = returnTypeName self.returnType = aDecoder.decode(forKey: "returnType") guard let readAccess: String = aDecoder.decode(forKey: "readAccess") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["readAccess"])); fatalError() }; self.readAccess = readAccess guard let writeAccess: String = aDecoder.decode(forKey: "writeAccess") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["writeAccess"])); fatalError() }; self.writeAccess = writeAccess guard let annotations: Annotations = aDecoder.decode(forKey: "annotations") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["annotations"])); fatalError() }; self.annotations = annotations guard let documentation: Documentation = aDecoder.decode(forKey: "documentation") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["documentation"])); fatalError() }; self.documentation = documentation self.definedInTypeName = aDecoder.decode(forKey: "definedInTypeName") self.definedInType = aDecoder.decode(forKey: "definedInType") guard let attributes: AttributeList = aDecoder.decode(forKey: "attributes") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["attributes"])); fatalError() }; self.attributes = attributes guard let modifiers: [SourceryModifier] = aDecoder.decode(forKey: "modifiers") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["modifiers"])); fatalError() }; self.modifiers = modifiers } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.parameters, forKey: "parameters") aCoder.encode(self.returnTypeName, forKey: "returnTypeName") aCoder.encode(self.returnType, forKey: "returnType") aCoder.encode(self.readAccess, forKey: "readAccess") aCoder.encode(self.writeAccess, forKey: "writeAccess") aCoder.encode(self.annotations, forKey: "annotations") aCoder.encode(self.documentation, forKey: "documentation") aCoder.encode(self.definedInTypeName, forKey: "definedInTypeName") aCoder.encode(self.definedInType, forKey: "definedInType") aCoder.encode(self.attributes, forKey: "attributes") aCoder.encode(self.modifiers, forKey: "modifiers") } // sourcery:end }
mit
0a15c68ce1a7b5f2dac877e0130fa240
51.9
279
0.693357
5.079561
false
false
false
false
tjw/swift
test/Compatibility/accessibility.swift
1
39476
// RUN: %target-typecheck-verify-swift -swift-version 4 public protocol PublicProto { func publicReq() } // expected-note@+1 * {{type declared here}} internal protocol InternalProto { func internalReq() } fileprivate protocol FilePrivateProto { func filePrivateReq() } // expected-note@+1 * {{type declared here}} private protocol PrivateProto { func privateReq() } public struct PublicStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto { private func publicReq() {} // expected-error {{method 'publicReq()' must be declared public because it matches a requirement in public protocol 'PublicProto'}} {{3-10=public}} private func internalReq() {} // expected-error {{method 'internalReq()' must be declared internal because it matches a requirement in internal protocol 'InternalProto'}} {{3-10=internal}} private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{3-10=fileprivate}} private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{3-10=fileprivate}} public var publicVar = 0 } // expected-note@+1 * {{type declared here}} internal struct InternalStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto { private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{3-10=internal}} private func internalReq() {} // expected-error {{method 'internalReq()' must be declared internal because it matches a requirement in internal protocol 'InternalProto'}} {{3-10=internal}} private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{3-10=fileprivate}} private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{3-10=fileprivate}} public var publicVar = 0 } // expected-note@+1 * {{type declared here}} fileprivate struct FilePrivateStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto { private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{3-10=fileprivate}} private func internalReq() {} // expected-error {{method 'internalReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'InternalProto'}} {{3-10=fileprivate}} private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{3-10=fileprivate}} private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{3-10=fileprivate}} public var publicVar = 0 } // expected-note@+1 * {{type declared here}} private struct PrivateStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto { private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{3-10=fileprivate}} private func internalReq() {} // expected-error {{method 'internalReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'InternalProto'}} {{3-10=fileprivate}} private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{3-10=fileprivate}} private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{3-10=fileprivate}} public var publicVar = 0 } extension PublicStruct { public init(x: Int) { self.init() } } extension InternalStruct { public init(x: Int) { self.init() } } extension FilePrivateStruct { public init(x: Int) { self.init() } } extension PrivateStruct { public init(x: Int) { self.init() } } public extension PublicStruct { public func extMemberPublic() {} private func extImplPublic() {} } internal extension PublicStruct { public func extMemberInternal() {} // expected-warning {{declaring a public instance method in an internal extension}} {{3-9=internal}} private func extImplInternal() {} } private extension PublicStruct { public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}} private func extImplPrivate() {} } fileprivate extension PublicStruct { public func extMemberFilePrivate() {} // expected-warning {{declaring a public instance method in a fileprivate extension}} {{3-9=fileprivate}} private func extImplFilePrivate() {} } public extension InternalStruct { // expected-error {{extension of internal struct cannot be declared public}} {{1-8=}} public func extMemberPublic() {} private func extImplPublic() {} } internal extension InternalStruct { public func extMemberInternal() {} // expected-warning {{declaring a public instance method in an internal extension}} {{3-9=internal}} private func extImplInternal() {} } fileprivate extension InternalStruct { public func extMemberFilePrivate() {} // expected-warning {{declaring a public instance method in a fileprivate extension}} {{3-9=fileprivate}} private func extImplFilePrivate() {} } private extension InternalStruct { public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}} private func extImplPrivate() {} } public extension FilePrivateStruct { // expected-error {{extension of fileprivate struct cannot be declared public}} {{1-8=}} public func extMemberPublic() {} private func extImplPublic() {} } internal extension FilePrivateStruct { // expected-error {{extension of fileprivate struct cannot be declared internal}} {{1-10=}} public func extMemberInternal() {} // expected-warning {{declaring a public instance method in an internal extension}} {{3-9=internal}} private func extImplInternal() {} } fileprivate extension FilePrivateStruct { public func extMemberFilePrivate() {} // expected-warning {{declaring a public instance method in a fileprivate extension}} {{3-9=fileprivate}} private func extImplFilePrivate() {} } private extension FilePrivateStruct { public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}} private func extImplPrivate() {} } public extension PrivateStruct { // expected-error {{extension of private struct cannot be declared public}} {{1-8=}} public func extMemberPublic() {} private func extImplPublic() {} } internal extension PrivateStruct { // expected-error {{extension of private struct cannot be declared internal}} {{1-10=}} public func extMemberInternal() {} // expected-warning {{declaring a public instance method in an internal extension}} {{3-9=internal}} private func extImplInternal() {} } fileprivate extension PrivateStruct { // expected-error {{extension of private struct cannot be declared fileprivate}} {{1-13=}} public func extMemberFilePrivate() {} // expected-warning {{declaring a public instance method in a fileprivate extension}} {{3-9=fileprivate}} private func extImplFilePrivate() {} } private extension PrivateStruct { public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}} private func extImplPrivate() {} } public struct PublicStructDefaultMethods: PublicProto, InternalProto, PrivateProto { func publicReq() {} // expected-error {{method 'publicReq()' must be declared public because it matches a requirement in public protocol 'PublicProto'}} {{3-3=public }} func internalReq() {} func privateReq() {} } public class Base { required public init() {} // expected-note@+1 * {{overridden declaration is here}} public func foo() {} // expected-note@+1 * {{overridden declaration is here}} public internal(set) var bar: Int = 0 // expected-note@+1 * {{overridden declaration is here}} public subscript () -> () { return () } } public extension Base { open func extMemberPublic() {} // expected-warning {{declaring open instance method in public extension}} } internal extension Base { open func extMemberInternal() {} // expected-warning {{declaring open instance method in an internal extension}} } public class PublicSub: Base { private required init() {} // expected-error {{'required' initializer must be accessible wherever class 'PublicSub' can be subclassed}} {{3-10=internal}} override func foo() {} // expected-error {{overriding instance method must be as accessible as the declaration it overrides}} {{12-12=public }} override var bar: Int { // expected-error {{overriding var must be as accessible as the declaration it overrides}} {{12-12=public }} get { return 0 } set {} } override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as the declaration it overrides}} {{12-12=public }} } public class PublicSubGood: Base { required init() {} // okay } internal class InternalSub: Base { required private init() {} // expected-error {{'required' initializer must be accessible wherever class 'InternalSub' can be subclassed}} {{12-19=internal}} private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=internal}} private override var bar: Int { // expected-error {{overriding var must be as accessible as its enclosing type}} {{3-10=internal}} get { return 0 } set {} } private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=internal}} } internal class InternalSubGood: Base { required init() {} // no-warning override func foo() {} override var bar: Int { get { return 0 } set {} } override subscript () -> () { return () } } internal class InternalSubPrivateSet: Base { required init() {} private(set) override var bar: Int { // expected-error {{overriding var must be as accessible as its enclosing type}} {{3-16=}} get { return 0 } set {} } private(set) override subscript () -> () { // okay; read-only in base class get { return () } set {} } } fileprivate class FilePrivateSub: Base { required private init() {} // expected-error {{'required' initializer must be accessible wherever class 'FilePrivateSub' can be subclassed}} {{12-19=fileprivate}} private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=fileprivate}} private override var bar: Int { // expected-error {{overriding var must be as accessible as its enclosing type}} {{3-10=fileprivate}} get { return 0 } set {} } private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=fileprivate}} } fileprivate class FilePrivateSubGood: Base { required init() {} // no-warning override func foo() {} override var bar: Int { get { return 0 } set {} } override subscript () -> () { return () } } fileprivate class FilePrivateSubGood2: Base { fileprivate required init() {} // no-warning fileprivate override func foo() {} fileprivate override var bar: Int { get { return 0 } set {} } fileprivate override subscript () -> () { return () } } fileprivate class FilePrivateSubPrivateSet: Base { required init() {} private(set) override var bar: Int { // expected-error {{overriding var must be as accessible as its enclosing type}} {{3-10=fileprivate}} get { return 0 } set {} } private(set) override subscript () -> () { // okay; read-only in base class get { return () } set {} } } private class PrivateSub: Base { required private init() {} // expected-error {{'required' initializer must be accessible wherever class 'PrivateSub' can be subclassed}} {{12-19=fileprivate}} private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=fileprivate}} private override var bar: Int { // expected-error {{overriding var must be as accessible as its enclosing type}} {{3-10=fileprivate}} get { return 0 } set {} } private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=fileprivate}} } private class PrivateSubGood: Base { required fileprivate init() {} fileprivate override func foo() {} fileprivate override var bar: Int { get { return 0 } set {} } fileprivate override subscript () -> () { return () } } private class PrivateSubPrivateSet: Base { required fileprivate init() {} fileprivate override func foo() {} private(set) override var bar: Int { // expected-error {{setter of overriding var must be as accessible as its enclosing type}} get { return 0 } set {} } private(set) override subscript () -> () { // okay; read-only in base class get { return () } set {} } } public typealias PublicTA1 = PublicStruct public typealias PublicTA2 = InternalStruct // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}} public typealias PublicTA3 = FilePrivateStruct // expected-error {{type alias cannot be declared public because its underlying type uses a fileprivate type}} public typealias PublicTA4 = PrivateStruct // expected-error {{type alias cannot be declared public because its underlying type uses a private type}} // expected-note@+1 {{type declared here}} internal typealias InternalTA1 = PublicStruct internal typealias InternalTA2 = InternalStruct internal typealias InternalTA3 = FilePrivateStruct // expected-error {{type alias cannot be declared internal because its underlying type uses a fileprivate type}} internal typealias InternalTA4 = PrivateStruct // expected-error {{type alias cannot be declared internal because its underlying type uses a private type}} public typealias PublicFromInternal = InternalTA1 // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}} typealias FunctionType1 = (PrivateStruct) -> PublicStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}} typealias FunctionType2 = (PublicStruct) -> PrivateStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}} typealias FunctionType3 = (PrivateStruct) -> PrivateStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}} typealias ArrayType = [PrivateStruct] // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}} typealias DictType = [String : PrivateStruct] // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}} typealias GenericArgs = Optional<PrivateStruct> // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}} public protocol HasAssocType { associatedtype Inferred func test(input: Inferred) } public struct AssocTypeImpl: HasAssocType { public func test(input: Bool) {} } public let _: AssocTypeImpl.Inferred? public let x: PrivateStruct = PrivateStruct() // expected-error {{constant cannot be declared public because its type uses a private type}} public var a: PrivateStruct?, b: PrivateStruct? // expected-error 2 {{variable cannot be declared public because its type uses a private type}} public var (c, d): (PrivateStruct?, PrivateStruct?) // expected-error {{variable cannot be declared public because its type uses a private type}} var internalVar: PrivateStruct? // expected-error {{variable must be declared private or fileprivate because its type uses a private type}} let internalConstant = PrivateStruct() // expected-error {{constant must be declared private or fileprivate because its type 'PrivateStruct' uses a private type}} public let publicConstant = [InternalStruct]() // expected-error {{constant cannot be declared public because its type '[InternalStruct]' uses an internal type}} public struct Properties { public let x: PrivateStruct = PrivateStruct() // expected-error {{property cannot be declared public because its type uses a private type}} public var a: PrivateStruct?, b: PrivateStruct? // expected-error 2 {{property cannot be declared public because its type uses a private type}} public var (c, d): (PrivateStruct?, PrivateStruct?) // expected-error {{property cannot be declared public because its type uses a private type}} let y = PrivateStruct() // expected-error {{property must be declared fileprivate because its type 'PrivateStruct' uses a private type}} } public struct Subscripts { subscript (a: PrivateStruct) -> Int { return 0 } // expected-error {{subscript must be declared fileprivate because its index uses a private type}} subscript (a: Int) -> PrivateStruct { return PrivateStruct() } // expected-error {{subscript must be declared fileprivate because its element type uses a private type}} public subscript (a: PrivateStruct, b: Int) -> Int { return 0 } // expected-error {{subscript cannot be declared public because its index uses a private type}} public subscript (a: Int, b: PrivateStruct) -> Int { return 0 } // expected-error {{subscript cannot be declared public because its index uses a private type}} public subscript (a: InternalStruct, b: PrivateStruct) -> InternalStruct { return InternalStruct() } // expected-error {{subscript cannot be declared public because its index uses a private type}} public subscript (a: PrivateStruct, b: InternalStruct) -> PrivateStruct { return PrivateStruct() } // expected-error {{subscript cannot be declared public because its index uses a private type}} public subscript (a: Int, b: Int) -> InternalStruct { return InternalStruct() } // expected-error {{subscript cannot be declared public because its element type uses an internal type}} } public struct Methods { func foo(a: PrivateStruct) -> Int { return 0 } // expected-error {{method must be declared fileprivate because its parameter uses a private type}} func bar(a: Int) -> PrivateStruct { return PrivateStruct() } // expected-error {{method must be declared fileprivate because its result uses a private type}} public func a(a: PrivateStruct, b: Int) -> Int { return 0 } // expected-error {{method cannot be declared public because its parameter uses a private type}} public func b(a: Int, b: PrivateStruct) -> Int { return 0 } // expected-error {{method cannot be declared public because its parameter uses a private type}} public func c(a: InternalStruct, b: PrivateStruct) -> InternalStruct { return InternalStruct() } // expected-error {{method cannot be declared public because its parameter uses a private type}} public func d(a: PrivateStruct, b: InternalStruct) -> PrivateStruct { return PrivateStruct() } // expected-error {{method cannot be declared public because its parameter uses a private type}} public func e(a: Int, b: Int) -> InternalStruct { return InternalStruct() } // expected-error {{method cannot be declared public because its result uses an internal type}} } func privateParam(a: PrivateStruct) {} // expected-error {{function must be declared private or fileprivate because its parameter uses a private type}} public struct Initializers { init(a: PrivateStruct) {} // expected-error {{initializer must be declared fileprivate because its parameter uses a private type}} public init(a: PrivateStruct, b: Int) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}} public init(a: Int, b: PrivateStruct) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}} public init(a: InternalStruct, b: PrivateStruct) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}} public init(a: PrivateStruct, b: InternalStruct) { } // expected-error {{initializer cannot be declared public because its parameter uses a private type}} } public class PublicClass {} // expected-note@+2 * {{type declared here}} // expected-note@+1 * {{superclass is declared here}} internal class InternalClass {} // expected-note@+1 * {{type declared here}} private class PrivateClass {} public protocol AssocTypes { associatedtype Foo associatedtype Internal: InternalClass // expected-error {{associated type in a public protocol uses an internal type in its requirement}} associatedtype InternalConformer: InternalProto // expected-error {{associated type in a public protocol uses an internal type in its requirement}} associatedtype PrivateConformer: PrivateProto // expected-error {{associated type in a public protocol uses a private type in its requirement}} associatedtype PI: PrivateProto, InternalProto // expected-error {{associated type in a public protocol uses a private type in its requirement}} associatedtype IP: InternalProto, PrivateProto // expected-error {{associated type in a public protocol uses a private type in its requirement}} associatedtype PrivateDefault = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its default definition}} associatedtype PublicDefault = PublicStruct associatedtype PrivateDefaultConformer: PublicProto = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its default definition}} associatedtype PublicDefaultConformer: PrivateProto = PublicStruct // expected-error {{associated type in a public protocol uses a private type in its requirement}} associatedtype PrivatePrivateDefaultConformer: PrivateProto = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its requirement}} associatedtype PublicPublicDefaultConformer: PublicProto = PublicStruct } public protocol RequirementTypes { var x: PrivateStruct { get } // expected-error {{property cannot be declared public because its type uses a private type}} subscript(x: Int) -> InternalStruct { get set } // expected-error {{subscript cannot be declared public because its element type uses an internal type}} func foo() -> PrivateStruct // expected-error {{method cannot be declared public because its result uses a private type}} init(x: PrivateStruct) // expected-error {{initializer cannot be declared public because its parameter uses a private type}} } protocol DefaultRefinesPrivate : PrivateProto {} // expected-error {{protocol must be declared private or fileprivate because it refines a private protocol}} public protocol PublicRefinesPrivate : PrivateProto {} // expected-error {{public protocol cannot refine a private protocol}} public protocol PublicRefinesInternal : InternalProto {} // expected-error {{public protocol cannot refine an internal protocol}} public protocol PublicRefinesPI : PrivateProto, InternalProto {} // expected-error {{public protocol cannot refine a private protocol}} public protocol PublicRefinesIP : InternalProto, PrivateProto {} // expected-error {{public protocol cannot refine a private protocol}} // expected-note@+1 * {{type declared here}} private typealias PrivateInt = Int enum DefaultRawPrivate : PrivateInt { // expected-error {{enum must be declared private or fileprivate because its raw type uses a private type}} case A } public enum PublicRawPrivate : PrivateInt { // expected-error {{enum cannot be declared public because its raw type uses a private type}} case A } public enum MultipleConformance : PrivateProto, PrivateInt { // expected-error {{enum cannot be declared public because its raw type uses a private type}} expected-error {{must appear first}} {{35-35=PrivateInt, }} {{47-59=}} case A func privateReq() {} } open class OpenSubclassInternal : InternalClass {} // expected-error {{class cannot be declared open because its superclass is internal}} expected-error {{superclass 'InternalClass' of open class must be open}} public class PublicSubclassPublic : PublicClass {} public class PublicSubclassInternal : InternalClass {} // expected-error {{class cannot be declared public because its superclass is internal}} public class PublicSubclassPrivate : PrivateClass {} // expected-error {{class cannot be declared public because its superclass is private}} class DefaultSubclassPublic : PublicClass {} class DefaultSubclassInternal : InternalClass {} class DefaultSubclassPrivate : PrivateClass {} // expected-error {{class must be declared private or fileprivate because its superclass is private}} public class PublicGenericClass<T> {} // expected-note@+2 * {{type declared here}} // expected-note@+1 * {{superclass is declared here}} internal class InternalGenericClass<T> {} // expected-note@+1 * {{type declared here}} private class PrivateGenericClass<T> {} open class OpenConcreteSubclassInternal : InternalGenericClass<Int> {} // expected-warning {{class should not be declared open because its superclass is internal}} expected-error {{superclass 'InternalGenericClass<Int>' of open class must be open}} public class PublicConcreteSubclassPublic : PublicGenericClass<Int> {} public class PublicConcreteSubclassInternal : InternalGenericClass<Int> {} // expected-warning {{class should not be declared public because its superclass is internal}} public class PublicConcreteSubclassPrivate : PrivateGenericClass<Int> {} // expected-warning {{class should not be declared public because its superclass is private}} public class PublicConcreteSubclassPublicPrivateArg : PublicGenericClass<PrivateStruct> {} // expected-warning {{class should not be declared public because its superclass is private}} open class OpenGenericSubclassInternal<T> : InternalGenericClass<T> {} // expected-warning {{class should not be declared open because its superclass is internal}} expected-error {{superclass 'InternalGenericClass<T>' of open class must be open}} public class PublicGenericSubclassPublic<T> : PublicGenericClass<T> {} public class PublicGenericSubclassInternal<T> : InternalGenericClass<T> {} // expected-warning {{class should not be declared public because its superclass is internal}} public class PublicGenericSubclassPrivate<T> : PrivateGenericClass<T> {} // expected-warning {{class should not be declared public because its superclass is private}} public enum PublicEnumPrivate { case A(PrivateStruct) // expected-error {{enum case in a public enum uses a private type}} } enum DefaultEnumPrivate { case A(PrivateStruct) // expected-error {{enum case in an internal enum uses a private type}} } public enum PublicEnumPI { case A(InternalStruct) // expected-error {{enum case in a public enum uses an internal type}} case B(PrivateStruct, InternalStruct) // expected-error {{enum case in a public enum uses a private type}} expected-error {{enum case in a public enum uses an internal type}} case C(InternalStruct, PrivateStruct) // expected-error {{enum case in a public enum uses a private type}} expected-error {{enum case in a public enum uses an internal type}} } enum DefaultEnumPublic { case A(PublicStruct) // no-warning } struct DefaultGeneric<T> {} struct DefaultGenericPrivate<T: PrivateProto> {} // expected-error {{generic struct must be declared private or fileprivate because its generic parameter uses a private type}} struct DefaultGenericPrivate2<T: PrivateClass> {} // expected-error {{generic struct must be declared private or fileprivate because its generic parameter uses a private type}} struct DefaultGenericPrivateReq<T> where T == PrivateClass {} // expected-error {{same-type requirement makes generic parameter 'T' non-generic}} // expected-error@-1 {{generic struct must be declared private or fileprivate because its generic requirement uses a private type}} struct DefaultGenericPrivateReq2<T> where T: PrivateProto {} // expected-error {{generic struct must be declared private or fileprivate because its generic requirement uses a private type}} public struct PublicGenericInternal<T: InternalProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses an internal type}} public struct PublicGenericPI<T: PrivateProto, U: InternalProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}} public struct PublicGenericIP<T: InternalProto, U: PrivateProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}} public struct PublicGenericPIReq<T: PrivateProto> where T: InternalProto {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}} public struct PublicGenericIPReq<T: InternalProto> where T: PrivateProto {} // expected-error {{generic struct cannot be declared public because its generic requirement uses a private type}} public func genericFunc<T: InternalProto>(_: T) {} // expected-error {{function cannot be declared public because its generic parameter uses an internal type}} {} public class GenericClass<T: InternalProto> { // expected-error {{generic class cannot be declared public because its generic parameter uses an internal type}} public init<T: PrivateProto>(_: T) {} // expected-error {{initializer cannot be declared public because its generic parameter uses a private type}} public func genericMethod<T: PrivateProto>(_: T) {} // expected-error {{instance method cannot be declared public because its generic parameter uses a private type}} } public enum GenericEnum<T: InternalProto> { // expected-error {{generic enum cannot be declared public because its generic parameter uses an internal type}} case A } public protocol PublicMutationOperations { var size: Int { get set } subscript (_: Int) -> Int { get set } } internal protocol InternalMutationOperations { var size: Int { get set } subscript (_: Int) -> Int { get set } } public struct AccessorsControl : InternalMutationOperations { private var size = 0 // expected-error {{property 'size' must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{3-10=internal}} private subscript (_: Int) -> Int { // expected-error {{subscript must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{3-10=internal}} get { return 42 } set {} } } public struct PrivateSettersPublic : InternalMutationOperations { // Please don't change the formatting here; it's a precise fix-it test. public private(set) var size = 0 // expected-error {{setter for property 'size' must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{10-17=internal}} public private(set) subscript (_: Int) -> Int { // expected-error {{subscript setter must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{10-17=internal}} get { return 42 } set {} } } internal struct PrivateSettersInternal : PublicMutationOperations { // Please don't change the formatting here; it's a precise fix-it test. private(set)var size = 0 // expected-error {{setter for property 'size' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicMutationOperations'}} {{3-15=}} internal private(set)subscript (_: Int) -> Int { // expected-error {{subscript setter must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicMutationOperations'}} {{12-24=}} get { return 42 } set {} } } public protocol PublicReadOnlyOperations { var size: Int { get } subscript (_: Int) -> Int { get } } internal struct PrivateSettersForReadOnlyInternal : PublicReadOnlyOperations { public private(set) var size = 0 internal private(set) subscript (_: Int) -> Int { // no-warning get { return 42 } set {} } } public struct PrivateSettersForReadOnlyPublic : PublicReadOnlyOperations { public private(set) var size = 0 // no-warning internal private(set) subscript (_: Int) -> Int { // expected-error {{subscript must be declared public because it matches a requirement in public protocol 'PublicReadOnlyOperations'}} {{3-11=public}} get { return 42 } set {} } } public protocol PublicOperatorProto { static prefix func !(_: Self) -> Self } internal protocol InternalOperatorProto { static prefix func !(_: Self) -> Self } fileprivate protocol FilePrivateOperatorProto { static prefix func !(_: Self) -> Self } private protocol PrivateOperatorProto { static prefix func !(_: Self) -> Self } public struct PublicOperatorAdopter : PublicOperatorProto { fileprivate struct Inner : PublicOperatorProto { } } private prefix func !(input: PublicOperatorAdopter) -> PublicOperatorAdopter { // expected-error {{method '!' must be declared public because it matches a requirement in public protocol 'PublicOperatorProto'}} {{1-8=public}} return input } private prefix func !(input: PublicOperatorAdopter.Inner) -> PublicOperatorAdopter.Inner { return input } public struct InternalOperatorAdopter : InternalOperatorProto { fileprivate struct Inner : InternalOperatorProto { } } private prefix func !(input: InternalOperatorAdopter) -> InternalOperatorAdopter { // expected-error {{method '!' must be declared internal because it matches a requirement in internal protocol 'InternalOperatorProto'}} {{1-8=internal}} return input } private prefix func !(input: InternalOperatorAdopter.Inner) -> InternalOperatorAdopter.Inner { return input } public struct FilePrivateOperatorAdopter : FilePrivateOperatorProto { fileprivate struct Inner : FilePrivateOperatorProto { } } private prefix func !(input: FilePrivateOperatorAdopter) -> FilePrivateOperatorAdopter { return input } private prefix func !(input: FilePrivateOperatorAdopter.Inner) -> FilePrivateOperatorAdopter.Inner { return input } public struct PrivateOperatorAdopter : PrivateOperatorProto { fileprivate struct Inner : PrivateOperatorProto { } } private prefix func !(input: PrivateOperatorAdopter) -> PrivateOperatorAdopter { return input } private prefix func !(input: PrivateOperatorAdopter.Inner) -> PrivateOperatorAdopter.Inner { return input } public protocol Equatablish { static func ==(lhs: Self, rhs: Self) /* -> bool */ // expected-note {{protocol requires function '=='}} } fileprivate struct EquatablishOuter { internal struct Inner : Equatablish {} } private func ==(lhs: EquatablishOuter.Inner, rhs: EquatablishOuter.Inner) {} // expected-note@-1 {{candidate has non-matching type}} fileprivate struct EquatablishOuter2 { internal struct Inner : Equatablish { fileprivate static func ==(lhs: Inner, rhs: Inner) {} // expected-note@-1 {{candidate has non-matching type}} } } fileprivate struct EquatablishOuterProblem { internal struct Inner : Equatablish { // expected-error {{type 'EquatablishOuterProblem.Inner' does not conform to protocol 'Equatablish'}} private static func ==(lhs: Inner, rhs: Inner) {} } } internal struct EquatablishOuterProblem2 { public struct Inner : Equatablish { fileprivate static func ==(lhs: Inner, rhs: Inner) {} // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{5-16=internal}} // expected-note@-1 {{candidate has non-matching type}} } } internal struct EquatablishOuterProblem3 { public struct Inner : Equatablish { } } private func ==(lhs: EquatablishOuterProblem3.Inner, rhs: EquatablishOuterProblem3.Inner) {} // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{1-8=internal}} // expected-note@-1 {{candidate has non-matching type}} public protocol AssocTypeProto { associatedtype Assoc } fileprivate struct AssocTypeOuter { internal struct Inner : AssocTypeProto { fileprivate typealias Assoc = Int } } fileprivate struct AssocTypeOuterProblem { internal struct Inner : AssocTypeProto { private typealias Assoc = Int // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{5-12=fileprivate}} } } internal struct AssocTypeOuterProblem2 { public struct Inner : AssocTypeProto { fileprivate typealias Assoc = Int // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{5-16=internal}} } } internal typealias InternalComposition = PublicClass & PublicProto // expected-note {{declared here}} public class DerivedFromInternalComposition : InternalComposition { // expected-error {{class cannot be declared public because its superclass is internal}} public func publicReq() {} } internal typealias InternalGenericComposition<T> = PublicGenericClass<T> & PublicProto // expected-note {{declared here}} public class DerivedFromInternalGenericComposition : InternalGenericComposition<Int> { // expected-warning {{class should not be declared public because its superclass is internal}} public func publicReq() {} } internal typealias InternalConcreteGenericComposition = PublicGenericClass<Int> & PublicProto // expected-note {{declared here}} public class DerivedFromInternalConcreteGenericComposition : InternalConcreteGenericComposition { // expected-warning {{class should not be declared public because its superclass is internal}} public func publicReq() {} } public typealias BadPublicComposition1 = InternalClass & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}} public typealias BadPublicComposition2 = PublicClass & InternalProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}} public typealias BadPublicComposition3<T> = InternalGenericClass<T> & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}} public typealias BadPublicComposition4 = InternalGenericClass<Int> & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}} public typealias BadPublicComposition5 = PublicGenericClass<InternalStruct> & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
apache-2.0
c636c35b1e3f1127611eb91252c3823b
55.963925
248
0.753977
4.946867
false
true
false
false
nagyistoce/Kingfisher
Kingfisher/KingfisherManager.swift
1
9690
// // KingfisherManager.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2015 Wei Wang <[email protected]> // // 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 public typealias DownloadProgressBlock = ((receivedSize: Int64, totalSize: Int64) -> ()) public typealias CompletionHandler = ((image: UIImage?, error: NSError?, cacheType: CacheType, imageURL: NSURL?) -> ()) /** * RetrieveImageTask represents a task of image retrieving process. * It contains an async task of getting image from disk and from network. */ public class RetrieveImageTask { var diskRetrieveTask: RetrieveImageDiskTask? var downloadTask: RetrieveImageDownloadTask? /** Cancel current task. If this task does not begin or already done, do nothing. */ public func cancel() { if let diskRetrieveTask = diskRetrieveTask { dispatch_block_cancel(diskRetrieveTask) } if let downloadTask = downloadTask { downloadTask.cancel() } } } public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error" private let instance = KingfisherManager() /** * Main manager class of Kingfisher */ public class KingfisherManager { /** * Options to control some downloader and cache behaviors. */ public typealias Options = (forceRefresh: Bool, lowPriority: Bool, cacheMemoryOnly: Bool, shouldDecode: Bool, queue: dispatch_queue_t!) /// A preset option tuple with all value set to `false`. public static var OptionsNone: Options = { return (forceRefresh: false, lowPriority: false, cacheMemoryOnly: false, shouldDecode: false, queue: dispatch_get_main_queue()) }() /// Shared manager used by the extensions across Kingfisher. public class var sharedManager: KingfisherManager { return instance } /// Cache used by this manager public var cache: ImageCache /// Downloader used by this manager public var downloader: ImageDownloader /** Default init method :returns: A Kingfisher manager object with default cache and default downloader. */ public init() { cache = ImageCache.defaultCache downloader = ImageDownloader.defaultDownloader } /** Get an image with URL as the key. If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first. If not found, it will download the image at URL and cache it. These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more. :param: URL The image URL. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :param: progressBlock Called every time downloaded data changed. This could be used as a progress UI. :param: completionHandler Called when the whole retriving process finished. :returns: A `RetrieveImageTask` task object. You can use this object to cancel the task. */ public func retrieveImageWithURL(URL: NSURL, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { func parseOptionsInfo(optionsInfo: KingfisherOptionsInfo?) -> (Options, ImageCache, ImageDownloader) { let options: Options if let optionsInOptionsInfo = optionsInfo?[.Options] as? KingfisherOptions { options = (forceRefresh: (optionsInOptionsInfo & KingfisherOptions.ForceRefresh) != KingfisherOptions.None, lowPriority: (optionsInOptionsInfo & KingfisherOptions.LowPriority) != KingfisherOptions.None, cacheMemoryOnly: (optionsInOptionsInfo & KingfisherOptions.CacheMemoryOnly) != KingfisherOptions.None, shouldDecode: (optionsInOptionsInfo & KingfisherOptions.BackgroundDecode) != KingfisherOptions.None, queue: dispatch_get_main_queue()) } else { options = (forceRefresh: false, lowPriority: false, cacheMemoryOnly: false, shouldDecode: false, queue: dispatch_get_main_queue() ) } let targetCache = optionsInfo?[.TargetCache] as? ImageCache ?? self.cache let usedDownloader = optionsInfo?[.Downloader] as? ImageDownloader ?? self.downloader return (options, targetCache, usedDownloader) } let task = RetrieveImageTask() // There is a bug in Swift compiler which prevents to write `let (options, targetCache) = parseOptionsInfo(optionsInfo)` // It will cause a compiler error. let parsedOptions = parseOptionsInfo(optionsInfo) let (options, targetCache, downloader) = (parsedOptions.0, parsedOptions.1, parsedOptions.2) if let key = URL.absoluteString { if options.forceRefresh { downloadAndCacheImageWithURL(URL, forKey: key, retrieveImageTask: task, progressBlock: progressBlock, completionHandler: completionHandler, options: options, targetCache: targetCache, downloader: downloader) } else { let diskTask = targetCache.retrieveImageForKey(key, options: options, completionHandler: { (image, cacheType) -> () in if image != nil { completionHandler?(image: image, error: nil, cacheType:cacheType, imageURL: URL) } else { self.downloadAndCacheImageWithURL(URL, forKey: key, retrieveImageTask: task, progressBlock: progressBlock, completionHandler: completionHandler, options: options, targetCache: targetCache, downloader: downloader) } }) task.diskRetrieveTask = diskTask } } return task } func downloadAndCacheImageWithURL(URL: NSURL, forKey key: String, retrieveImageTask: RetrieveImageTask, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?, options: Options, targetCache: ImageCache, downloader: ImageDownloader) { downloader.downloadImageWithURL(URL, retrieveImageTask: retrieveImageTask, options: options, progressBlock: { (receivedSize, totalSize) -> () in progressBlock?(receivedSize: receivedSize, totalSize: totalSize) return }) { (image, error, imageURL) -> () in if let error = error where error.code == KingfisherError.NotModified.rawValue { // Not modified. Try to find the image from cache. // (The image should be in cache. It should be ensured by the framework users.) targetCache.retrieveImageForKey(key, options: options, completionHandler: { (cacheImage, cacheType) -> () in completionHandler?(image: cacheImage, error: nil, cacheType: cacheType, imageURL: URL) }) return } if let image = image { targetCache.storeImage(image, forKey: key, toDisk: !options.cacheMemoryOnly, completionHandler: nil) } completionHandler?(image: image, error: error, cacheType: .None, imageURL: URL) } } } // MARK: - Deprecated public extension KingfisherManager { @availability(*, deprecated=1.2, message="Use -retrieveImageWithURL:optionsInfo:progressBlock:completionHandler: instead.") public func retrieveImageWithURL(URL: NSURL, options: KingfisherOptions, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return retrieveImageWithURL(URL, optionsInfo: [.Options : options], progressBlock: progressBlock, completionHandler: completionHandler) } }
mit
9941cfac862163b2fef09ff5ddbb9889
43.246575
152
0.623942
5.68662
false
false
false
false
Onetaway/iOS8-day-by-day
19-core-image-kernels/FilterBuilder/FilterBuilder/SobelViewController.swift
3
1408
// // Copyright 2014 Scott Logic // // 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 class SobelViewController: UIViewController { // MARK: - Properties let filter = SobelFilter() // MARK: - IBOutlets @IBOutlet weak var outputImageView: UIImageView! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. setupFilter() updateOutputImage() } // MARK: - Utility methods private func updateOutputImage() { outputImageView.image = filteredImage() } private func filteredImage() -> UIImage { let outputImage = filter.outputImage return UIImage(CIImage: outputImage) } private func setupFilter() { // Need an input image let inputImage = UIImage(named: "flowers") filter.inputImage = CIImage(image: inputImage) } }
apache-2.0
c251957d348637cd955ed382b776ba1e
26.076923
76
0.705966
4.498403
false
false
false
false
ultimecia7/BestGameEver
Stick-Hero/ContactViewController.swift
1
3067
// // ContactViewController.swift // Stick-Hero // // Created by 徐静恺 on 12/21/15. // Copyright © 2015 koofrank. All rights reserved. // import UIKit import SpriteKit import AVFoundation import SwiftHTTP import JSONJoy class ContactViewController: UITableViewController { struct ArrayResponse: JSONJoy{ let friendList: Array<JSONDecoder>? init(_ decoder: JSONDecoder) { friendList = decoder["friendList"].array } } struct ArrayElement: JSONJoy{ let username : String? let highscore: String? let speed_highscore: String? let online: String? let last_login_time: String? init(_ decoder: JSONDecoder) { username = decoder["username"].string highscore = decoder["highscore"].string speed_highscore = decoder["speed_highscore"].string online = decoder["online"].string last_login_time = decoder["last_login_time"].string } } var friends = [ArrayElement]() var test : [String] = ["aaa","bbbb"] required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)!; let params = ["username":"root"] do { let opt = try HTTP.POST("http://192.168.1.107/friend_info.php", parameters: params, requestSerializer: JSONParameterSerializer()) opt.start { response in print(response.description) if let error = response.error { print("got an error: \(error)") return } let resp = ArrayResponse(JSONDecoder(response.data)) for var friend in resp.friendList!{ self.friends.append(ArrayElement(friend)) } self.tableView.reloadData() print(self.friends) } } catch let error { print("got an error creating the request: \(error)") } } override func viewDidLoad() { self.tableView.reloadData() super.viewDidLoad() print("asdhjashdkashdkashdkjhas") print(self.friends.count) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.friends.count; //return test.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier("myCustomCell", forIndexPath: indexPath) as! ContactTableViewCell ///* let friend = self.friends[indexPath.row] cell.user.text = friend.username! cell.normalhigh.text = friend.highscore! cell.speedhigh.text = friend.speed_highscore! //*/ /* let testcell = test[indexPath.row] cell.user.text = testcell */ print("asdasdasdcxvegfdgdfgfdgxcvw") return cell } }
mit
064a8c744f1dce519972cb0ddc36f48a
28.142857
141
0.580392
4.849445
false
false
false
false
morgz/SwiftGoal
SwiftGoal/ViewModels/RankingsViewModel.swift
1
3314
// // RankingsViewModel.swift // SwiftGoal // // Created by Martin Richter on 23/07/15. // Copyright (c) 2015 Martin Richter. All rights reserved. // import ReactiveCocoa class RankingsViewModel { typealias RankingChangeset = Changeset<Ranking> // Inputs let active = MutableProperty(false) let refreshObserver: Observer<Void, NoError> // Outputs let title: String let contentChangesSignal: Signal<RankingChangeset, NoError> let isLoading: MutableProperty<Bool> let alertMessageSignal: Signal<String, NoError> private let store: StoreType private let contentChangesObserver: Observer<RankingChangeset, NoError> private let alertMessageObserver: Observer<String, NoError> private var rankings: [Ranking] // MARK: Lifecycle init(store: StoreType) { self.title = "Rankings" self.store = store self.rankings = [] let (refreshSignal, refreshObserver) = SignalProducer<Void, NoError>.buffer() self.refreshObserver = refreshObserver let (contentChangesSignal, contentChangesObserver) = Signal<RankingChangeset, NoError>.pipe() self.contentChangesSignal = contentChangesSignal self.contentChangesObserver = contentChangesObserver let isLoading = MutableProperty(false) self.isLoading = isLoading let (alertMessageSignal, alertMessageObserver) = Signal<String, NoError>.pipe() self.alertMessageSignal = alertMessageSignal self.alertMessageObserver = alertMessageObserver active.producer .filter { $0 } .map { _ in () } .start(refreshObserver) refreshSignal .on(next: { _ in isLoading.value = true }) .flatMap(.Latest, transform: { _ in return store.fetchRankings() .flatMapError { error in alertMessageObserver.sendNext(error.localizedDescription) return SignalProducer(value: []) } }) .on(next: { _ in isLoading.value = false }) .combinePrevious([]) // Preserve history to calculate changeset .startWithNext({ [weak self] (oldRankings, newRankings) in self?.rankings = newRankings if let observer = self?.contentChangesObserver { let changeset = Changeset( oldItems: oldRankings, newItems: newRankings, contentMatches: Ranking.contentMatches ) observer.sendNext(changeset) } }) } // MARK: Data Source func numberOfSections() -> Int { return 1 } func numberOfRankingsInSection(section: Int) -> Int { return rankings.count } func playerNameAtIndexPath(indexPath: NSIndexPath) -> String { return rankingAtIndexPath(indexPath).player.name } func ratingAtIndexPath(indexPath: NSIndexPath) -> String { let rating = rankingAtIndexPath(indexPath).rating return String(format: "%.2f", rating) } // MARK: Internal Helpers private func rankingAtIndexPath(indexPath: NSIndexPath) -> Ranking { return rankings[indexPath.row] } }
mit
2fcb9b89c11e956ce74f9498ca8edf21
30.561905
101
0.620398
5.251981
false
false
false
false
freshOS/ws
Sources/ws/WSRequest.swift
2
9503
// // WSRequest.swift // ws // // Created by Sacha Durand Saint Omer on 06/04/16. // Copyright © 2016 s4cha. All rights reserved. // import Alamofire import Arrow import Foundation import Then public struct WSMultiPartData { public var multipartData = Data() public var multipartName = "" public var multipartFileName = "photo.jpg" public var multipartMimeType = "image/*" public init() { } public init(multipartData: Data, multipartName: String, multipartFileName: String? = nil, multipartMimeType: String) { self.multipartData = multipartData self.multipartName = multipartName self.multipartFileName = multipartFileName ?? self.multipartFileName self.multipartMimeType = multipartMimeType } } open class WSRequest { var isMultipart = false var multiPartData = [WSMultiPartData]() open var baseURL = "" open var URL = "" open var httpVerb = WSHTTPVerb.get open var params = [String: Any]() open var returnsJSON = true open var headers = [String: String]() open var fullURL: String { return baseURL + URL } open var timeout: TimeInterval? open var logLevels: WSLogLevel { get { return logger.logLevels } set { logger.logLevels = newValue } } open var postParameterEncoding: ParameterEncoding = URLEncoding() open var showsNetworkActivityIndicator = true open var errorHandler: ((JSON) -> Error?)? open var requestAdapter: RequestAdapter? open var requestRetrier: RequestRetrier? open var sessionManager: SessionManager? private let logger = WSLogger() fileprivate var req: DataRequest?//Alamofire.Request? public init() {} open func cancel() { req?.cancel() } func buildRequest() -> URLRequest { let url = Foundation.URL(string: fullURL)! var r = URLRequest(url: url) r.httpMethod = httpVerb.rawValue for (key, value) in headers { r.setValue(value, forHTTPHeaderField: key) } if let t = timeout { r.timeoutInterval = t } var request: URLRequest? if httpVerb == .post || httpVerb == .put || httpVerb == .patch { request = try? postParameterEncoding.encode(r, with: params) } else { request = try? URLEncoding.default.encode(r, with: params) } return request ?? r } func wsSessionManager() -> SessionManager { let activeSessionManager = sessionManager ?? Alamofire.SessionManager.default if let adapter = requestAdapter { activeSessionManager.adapter = adapter } if let retrier = requestRetrier { activeSessionManager.retrier = retrier } return activeSessionManager } func wsRequest(_ urlRequest: URLRequestConvertible) -> DataRequest { return wsSessionManager().request(urlRequest) } func wsUpload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, with urlRequest: URLRequestConvertible, encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) { return wsSessionManager().upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, with: urlRequest, encodingCompletion: encodingCompletion ) } /// Returns Promise containing JSON open func fetch() -> Promise<JSON> { return fetch().registerThen { (_, _, json) in json } } /// Returns Promise containing response status code, headers and parsed JSON open func fetch() -> Promise<(Int, [AnyHashable: Any], JSON)> { return Promise<(Int, [AnyHashable: Any], JSON)> { resolve, reject, progress in DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { if self.showsNetworkActivityIndicator { WSNetworkIndicator.shared.startRequest() } if self.isMultipart { self.sendMultipartRequest(resolve, reject: reject, progress: progress) } else if !self.returnsJSON { self.sendRequest(resolve, reject: reject) } else { self.sendJSONRequest(resolve, reject: reject) } } } } func sendMultipartRequest(_ resolve: @escaping (_ result: (Int, [AnyHashable: Any], JSON)) -> Void, reject: @escaping (_ error: Error) -> Void, progress:@escaping (Float) -> Void) { wsUpload(multipartFormData: { formData in for (key, value) in self.params { let str: String switch value { case let opt as Any?: if let v = opt { str = "\(v)" } else { continue } default: str = "\(value)" } if let data = str.data(using: .utf8) { formData.append(data, withName: key) } } self.multiPartData.forEach { data in formData.append(data.multipartData, withName: data.multipartName, fileName: data.multipartFileName, mimeType: data.multipartMimeType) } }, with: self.buildRequest(), encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.uploadProgress { p in progress(Float(p.fractionCompleted)) }.validate().responseJSON { r in self.handleJSONResponse(r, resolve: resolve, reject: reject) } case .failure: () } }) logger.logMultipartRequest(self) } func sendRequest(_ resolve:@escaping (_ result: (Int, [AnyHashable: Any], JSON)) -> Void, reject: @escaping (_ error: Error) -> Void) { self.req = wsRequest(self.buildRequest()) logger.logRequest(self.req!) let bgQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default) req?.validate().response(queue: bgQueue) { response in WSNetworkIndicator.shared.stopRequest() self.logger.logResponse(response) if response.error == nil { resolve((response.response?.statusCode ?? 0, response.response?.allHeaderFields ?? [:], JSON(1 as AnyObject)!)) } else { self.rejectCallWithMatchingError(response.response, data: response.data, reject: reject) } } } func sendJSONRequest(_ resolve: @escaping (_ result: (Int, [AnyHashable: Any], JSON)) -> Void, reject: @escaping (_ error: Error) -> Void) { self.req = wsRequest(self.buildRequest()) logger.logRequest(self.req!) let bgQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default) req?.validate().responseJSON(queue: bgQueue) { r in self.handleJSONResponse(r, resolve: resolve, reject: reject) } } func handleJSONResponse(_ response: DataResponse<Any>, resolve: (_ result: (Int, [AnyHashable: Any], JSON)) -> Void, reject: (_ error: Error) -> Void) { WSNetworkIndicator.shared.stopRequest() logger.logResponse(response) switch response.result { case .success(let value): if let json: JSON = JSON(value as AnyObject?) { if let error = errorHandler?(json) { reject(error) return } resolve((response.response?.statusCode ?? 0, response.response?.allHeaderFields ?? [:], json)) } else { rejectCallWithMatchingError(response.response, data: response.data, reject: reject) } case .failure: rejectCallWithMatchingError(response.response, data: response.data, reject: reject) } } func rejectCallWithMatchingError(_ response: HTTPURLResponse?, data: Data? = nil, reject: (_ error: Error) -> Void) { var error = WSError(httpStatusCode: response?.statusCode ?? 0) error.responseData = data if let d = data, let json = try? JSONSerialization.jsonObject(with: d, options: JSONSerialization.ReadingOptions.allowFragments), let j = JSON(json as AnyObject?) { error.jsonPayload = j } reject(error as Error) } func methodForHTTPVerb(_ verb: WSHTTPVerb) -> HTTPMethod { switch verb { case .get: return .get case .post: return .post case .put: return .put case .patch: return .patch case .delete: return .delete } } }
mit
c3c4cb0c8ff10ae0cf7d107c22ed4a39
36.262745
115
0.55883
5.215148
false
false
false
false
VictorBX/patchwire-ios
Example/client/Message.swift
1
1800
// // Message.swift // Patchwire-iOS // // Created by Victor Noel Barrera on 9/6/15. // Copyright (c) 2015 Victor Barrera. All rights reserved. // import UIKit enum MessageType: Int { case Normal = 0, Joined, Left } class Message { var user : String var message : String var type : MessageType init(json: [NSObject: AnyObject]) { self.user = "" self.message = "" self.type = .Normal if let user = json["username"] as? String { self.user = user } if let message = json["message"] as? String { self.message = message } if let type = json["type"] as? Int { self.type = MessageType(rawValue: type) ?? .Normal } } func displayMessage() -> String { switch type { case .Normal: return self.user + " : " + self.message default: return self.message } } func attributedDisplayMessage() -> NSAttributedString { var attributeDictionary = [String: AnyObject]() switch self.type { case .Normal: attributeDictionary[NSForegroundColorAttributeName] = UIColor(red: 34.0/256, green: 38.0/255, blue: 38.0/255, alpha: 1.0) attributeDictionary[NSFontAttributeName] = UIFont.systemFontOfSize(17) default: attributeDictionary[NSForegroundColorAttributeName] = UIColor.grayColor() attributeDictionary[NSFontAttributeName] = UIFont.italicSystemFontOfSize(17) } let attributedString = NSMutableAttributedString(string: displayMessage(), attributes: attributeDictionary) return attributedString.copy() as! NSAttributedString } }
mit
7234886e1a9c248faa0ab2c1696ca974
26.692308
133
0.583333
4.74934
false
false
false
false
kickerchen/KCPutton
Putton/PuttonItem.swift
1
2327
// // PuttonItem.swift // Putton // // Created by CHENCHIAN on 7/22/15. // Copyright (c) 2015 KICKERCHEN. All rights reserved. // import UIKit protocol PuttonItemDelegate { func puttonItemTouchesBegan(item: PuttonItem); func puttonItemTouchesEnded(item:PuttonItem); } class PuttonItem: UIButton, NSCopying { var delegate: PuttonItemDelegate? var expandPoint: CGPoint! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) println("Not implemented") } override init(frame: CGRect) { super.init(frame: frame) } convenience init(image: UIImage) { self.init(frame: CGRectMake(0, 0, image.size.width, image.size.height)) setImage(image, forState: .Normal) setImage(image, forState: .Highlighted) } func copyWithZone(zone: NSZone) -> AnyObject { let copy = PuttonItem(frame: CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))) if let myImageView = self.imageView { if let myImage = myImageView.image { copy.setImage(myImageView.image, forState: .Normal) } } return copy } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { super.touchesBegan(touches, withEvent: event) // pop animation self.transform = CGAffineTransformMakeScale(0.8, 0.8) UIView.animateWithDuration(PuttonConstants.startButtonDefaultAnimationDuration, delay: 0.0, usingSpringWithDamping: 0.1, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.allZeros, animations: { self.transform = CGAffineTransformMakeScale(1.0, 1.0) }, completion: nil) self.delegate?.puttonItemTouchesBegan(self) } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { super.touchesEnded(touches, withEvent: event) self.delegate?.puttonItemTouchesEnded(self) } }
mit
092e701ab361b2188b7f237433653304
28.833333
212
0.636872
4.682093
false
false
false
false
AcroMace/receptionkit
ReceptionKit/AppDelegate.swift
1
2314
// // AppDelegate.swift // ReceptionKit // // Created by Andy Cho on 2015-04-23. // Copyright (c) 2015 Andy Cho. All rights reserved. // import UIKit var messageSender: MessageSender! var camera: Camera! var doorbell = DoorBell() @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? // swiftlint:disable weak_delegate let conversationDelegate = ConversationDelegate() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Smooch Settings let smoochSettings = SKTSettings(appId: Config.Smooch.AppID) Smooch.initWith(smoochSettings) { error, _ in guard error == nil else { Logger.error("Could not initialize Smooch") print(error as Any) return } // Setup Smooch Smooch.conversation()?.delegate = self.conversationDelegate Smooch.setUserFirstName(Config.Slack.Name, lastName: "") SKTUser.current()?.email = Config.Slack.Email } // App-wide styles UIApplication.shared.isStatusBarHidden = true UINavigationBar.appearance().barTintColor = UIColor(hex: Config.Colour.NavigationBar) // Create an instance of the Camera // Cannot create this as a declaration above since the camera will not start // recording in that case camera = Camera() // Used to send messages to Smooch messageSender = SmoochMessageSender() return true } } // Extensions for tests extension AppDelegate { /** Reset the application before starting a test */ func reset() { guard let rootVC = self.window?.rootViewController as? UINavigationController else { Logger.error("Could not get the root view controller") return } rootVC.popToRootViewController(animated: false) } /** Replace the message sender being used with the provided one Used to provide a mock message sender - parameter newMessageSender: The message sender to use */ func replaceMessageSender(_ newMessageSender: MessageSender) { messageSender = newMessageSender } }
mit
4a3d6be69223af9d4d0fd17f9053fec2
27.925
144
0.655143
4.965665
false
false
false
false
AdaptiveMe/adaptive-arp-api-lib-darwin
Pod/Classes/Sources.Api/DatabaseResultCallbackImpl.swift
1
3832
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:[email protected]> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:[email protected]> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Interface for Managing the Cloud operations Auto-generated implementation of IDatabaseResultCallback specification. */ public class DatabaseResultCallbackImpl : BaseCallbackImpl, IDatabaseResultCallback { /** Constructor with callback id. @param id The id of the callback. */ public override init(id : Int64) { super.init(id: id) } /** Result callback for error responses @param error Returned error @since v2.0 */ public func onError(error : IDatabaseResultCallbackError) { let param0 : String = "Adaptive.IDatabaseResultCallbackError.toObject(JSON.parse(\"{ \\\"value\\\": \\\"\(error.toString())\\\"}\"))" var callbackId : Int64 = -1 if (getId() != nil) { callbackId = getId()! } AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleDatabaseResultCallbackError( \(callbackId), \(param0))") } /** Result callback for correct responses @param database Returns the database @since v2.0 */ public func onResult(database : Database) { let param0 : String = "Adaptive.Database.toObject(JSON.parse(\"\(JSONUtil.escapeString(Database.Serializer.toJSON(database)))\"))" var callbackId : Int64 = -1 if (getId() != nil) { callbackId = getId()! } AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleDatabaseResultCallbackResult( \(callbackId), \(param0))") } /** Result callback for warning responses @param database Returns the database @param warning Returned Warning @since v2.0 */ public func onWarning(database : Database, warning : IDatabaseResultCallbackWarning) { let param0 : String = "Adaptive.Database.toObject(JSON.parse(\"\(JSONUtil.escapeString(Database.Serializer.toJSON(database)))\"))" let param1 : String = "Adaptive.IDatabaseResultCallbackWarning.toObject(JSON.parse(\"{ \\\"value\\\": \\\"\(warning.toString())\\\"}\"))" var callbackId : Int64 = -1 if (getId() != nil) { callbackId = getId()! } AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleDatabaseResultCallbackWarning( \(callbackId), \(param0), \(param1))") } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
80e7f3df00ebccac8450354d4227c10c
36.54902
168
0.621149
4.793492
false
false
false
false
master-nevi/UPnAtom
Source/Logging/Logger.swift
1
3911
// // Logger.swift // // Copyright (c) 2015 David Robles // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation struct LogFlag : OptionSetType { let rawValue: UInt static let Error = LogFlag(rawValue: 1 << 0) // 0...00001 static let Warning = LogFlag(rawValue: 1 << 1) // 0...00010 static let Info = LogFlag(rawValue: 1 << 2) // 0...00100 static let Debug = LogFlag(rawValue: 1 << 3) // 0...01000 static let Verbose = LogFlag(rawValue: 1 << 4) // 0...10000 } /// Debug levels extension LogFlag { static let OffLevel: LogFlag = [] static let ErrorLevel: LogFlag = [.Error] static let WarningLevel: LogFlag = [.Error, .Warning] static let InfoLevel: LogFlag = [.Error, .Warning, .Info] static let DebugLevel: LogFlag = [.Error, .Warning, .Info, .Debug] static let VerboseLevel: LogFlag = [.Error, .Warning, .Info, .Debug, .Verbose] } let defaultLogLevel = LogFlag.DebugLevel var logLevel = defaultLogLevel func resetDefaultDebugLevel() { logLevel = defaultLogLevel } func Log(isAsynchronous: Bool, level: LogFlag, flag: LogFlag, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, @autoclosure string: () -> String) { if level.contains(flag) { print(string()) } } func LogDebug(@autoclosure logText: () -> String, level: LogFlag = logLevel, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, asynchronous async: Bool = true) { Log(async, level: level, flag: .Debug, file: file, function: function, line: line, string: logText) } func LogInfo(@autoclosure logText: () -> String, level: LogFlag = logLevel, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, asynchronous async: Bool = true) { Log(async, level: level, flag: .Info, file: file, function: function, line: line, string: logText) } func LogWarn(@autoclosure logText: () -> String, level: LogFlag = logLevel, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, asynchronous async: Bool = true) { Log(async, level: level, flag: .Warning, file: file, function: function, line: line, string: logText) } func LogVerbose(@autoclosure logText: () -> String, level: LogFlag = logLevel, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, asynchronous async: Bool = true) { Log(async, level: level, flag: .Verbose, file: file, function: function, line: line, string: logText) } func LogError(@autoclosure logText: () -> String, level: LogFlag = logLevel, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, asynchronous async: Bool = false) { Log(async, level: level, flag: .Error, file: file, function: function, line: line, string: logText) }
mit
45e5098ade2243f010c2e80663bcac30
48.506329
206
0.693684
3.914915
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/CallWindowController.swift
1
59999
// // PhoneCallWindow.swift // Telegram // // Created by keepcoder on 24/04/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import ObjcUtils import Postbox import SwiftSignalKit import TgVoipWebrtc import TelegramVoip import ColorPalette private let defaultWindowSize = NSMakeSize(720, 560) extension CallState { func videoIsAvailable(_ isVideo: Bool) -> Bool { switch state { case .active: switch videoState { case .notAvailable: return false default: return true } case .ringing, .requesting, .connecting: switch videoState { case .notAvailable: return false default: if isVideo { return true } else { return false } } case .terminating, .terminated: return false default: return true } } var muteIsAvailable: Bool { switch state { case .active: return true case .ringing, .requesting, .connecting: return true case .terminating, .terminated: return false default: return true } } } extension CallSessionTerminationReason { var recall: Bool { let recall:Bool switch self { case .ended(let reason): switch reason { case .busy: recall = true default: recall = false } case .error(let reason): switch reason { case .disconnected: recall = true default: recall = false } } return recall } } private class PhoneCallWindowView : View { fileprivate let imageView:TransformImageView = TransformImageView() fileprivate let controls:View = View() fileprivate let backgroundView:Control = Control() fileprivate let settings:ImageButton = ImageButton() let acceptControl:CallControl = CallControl(frame: .zero) let declineControl:CallControl = CallControl(frame: .zero) private var tooltips: [CallTooltipView] = [] private var displayToastsAfterTimestamp: Double? let b_Mute:CallControl = CallControl(frame: .zero) let b_VideoCamera:CallControl = CallControl(frame: .zero) let b_ScreenShare:CallControl = CallControl(frame: .zero) let muteControl:ImageButton = ImageButton() private var textNameView: NSTextField = NSTextField() private var statusView: CallStatusView = CallStatusView(frame: .zero) private let secureTextView:TextView = TextView() fileprivate let incomingVideoView: IncomingVideoView fileprivate let outgoingVideoView: OutgoingVideoView private var outgoingVideoViewRequested: Bool = false private var incomingVideoViewRequested: Bool = false private var imageDimension: NSSize? = nil private var basicControls: View = View() private var state: CallState? private let fetching = MetaDisposable() var updateIncomingAspectRatio:((Float)->Void)? = nil private var outgoingAspectRatio: CGFloat = 0 required init(frame frameRect: NSRect) { outgoingVideoView = OutgoingVideoView(frame: NSMakeRect(0, 0, frameRect.width, frameRect.height)) incomingVideoView = IncomingVideoView(frame: NSMakeRect(0, 0, frameRect.width, frameRect.height)) super.init(frame: frameRect) addSubview(imageView) settings.set(image: theme.icons.call_screen_settings, for: .Normal) settings.sizeToFit() imageView.layer?.contentsGravity = .resizeAspectFill imageView.addSubview(incomingVideoView) addSubview(backgroundView) backgroundView.forceMouseDownCanMoveWindow = true addSubview(outgoingVideoView) controls.isEventLess = true basicControls.isEventLess = true let shadow = NSShadow() shadow.shadowBlurRadius = 4 shadow.shadowColor = NSColor.black.withAlphaComponent(0.6) shadow.shadowOffset = NSMakeSize(0, 0) outgoingVideoView.shadow = shadow addSubview(controls) controls.addSubview(basicControls) self.backgroundColor = NSColor(0x000000, 0.8) secureTextView.backgroundColor = .clear secureTextView.isSelectable = false secureTextView.userInteractionEnabled = false addSubview(secureTextView) backgroundView.backgroundColor = NSColor(0x000000, 0.4) backgroundView.frame = NSMakeRect(0, 0, frameRect.width, frameRect.height) self.addSubview(textNameView) self.addSubview(statusView) controls.addSubview(acceptControl) controls.addSubview(declineControl) textNameView.font = .medium(36) textNameView.drawsBackground = false textNameView.backgroundColor = .clear textNameView.textColor = nightAccentPalette.text textNameView.isSelectable = false textNameView.isEditable = false textNameView.isBordered = false textNameView.focusRingType = .none textNameView.maximumNumberOfLines = 1 textNameView.alignment = .center textNameView.cell?.truncatesLastVisibleLine = true textNameView.lineBreakMode = .byTruncatingTail imageView.setFrameSize(frameRect.size.width, frameRect.size.height) acceptControl.updateWithData(CallControlData(text: strings().callAccept, mode: .normal(.greenUI, theme.icons.callWindowAccept), iconSize: NSMakeSize(50, 50)), animated: false) declineControl.updateWithData(CallControlData(text: strings().callDecline, mode: .normal(.redUI, theme.icons.callWindowDecline), iconSize: NSMakeSize(50, 50)), animated: false) basicControls.addSubview(b_VideoCamera) basicControls.addSubview(b_ScreenShare) basicControls.addSubview(b_Mute) var start: NSPoint? = nil var resizeOutgoingVideoDirection: OutgoingVideoView.ResizeDirection? = nil outgoingVideoView.overlay.set(handler: { [weak self] control in guard let `self` = self, let window = self.window, self.outgoingVideoView.frame != self.bounds else { start = nil return } start = self.convert(window.mouseLocationOutsideOfEventStream, from: nil) resizeOutgoingVideoDirection = self.outgoingVideoView.runResizer(at: self.outgoingVideoView.convert(window.mouseLocationOutsideOfEventStream, from: nil)) }, for: .Down) outgoingVideoView.overlay.set(handler: { [weak self] control in guard let `self` = self, let window = self.window, let startPoint = start else { return } self.outgoingVideoView.isMoved = true let current = self.convert(window.mouseLocationOutsideOfEventStream, from: nil) let difference = current - startPoint if let resizeDirection = resizeOutgoingVideoDirection { let frame = self.outgoingVideoView.frame let size: NSSize let point: NSPoint let value_w = difference.x let value_h = difference.x * (frame.height / frame.width) switch resizeDirection { case .topLeft: size = NSMakeSize(frame.width - value_w, frame.height - value_h) point = NSMakePoint(frame.minX + value_w, frame.minY + value_h) case .topRight: size = NSMakeSize(frame.width + value_w, frame.height + value_h) point = NSMakePoint(frame.minX, frame.minY - value_h) case .bottomLeft: size = NSMakeSize(frame.width - value_w, frame.height - value_h) point = NSMakePoint(frame.minX + value_w, frame.minY) case .bottomRight: size = NSMakeSize(frame.width + value_w, frame.height + value_h) point = NSMakePoint(frame.minX, frame.minY) } if point.x < 20 || point.y < 20 || (self.frame.width - (point.x + size.width)) < 20 || (self.frame.height - (point.y + size.height)) < 20 || size.width > (window.frame.width - 40) || size.height > (window.frame.height - 40) { return } if size.width < 50 || size.height < 50 { return } self.outgoingVideoView.updateFrame(CGRect(origin: point, size: size), animated: false) } else { self.outgoingVideoView.setFrameOrigin(self.outgoingVideoView.frame.origin + difference) } start = current }, for: .MouseDragging) outgoingVideoView.overlay.set(handler: { [weak self] control in guard let `self` = self, let _ = start else { return } let frame = self.outgoingVideoView.frame var point = self.outgoingVideoView.frame.origin let size = frame.size if (size.width + point.x) > self.frame.width - 20 { point.x = self.frame.width - size.width - 20 } else if point.x - 20 < 0 { point.x = 20 } if (size.height + point.y) > self.frame.height - 20 { point.y = self.frame.height - size.height - 20 } else if point.y - 20 < 0 { point.y = 20 } let updatedRect = CGRect(origin: point, size: size) self.outgoingVideoView.updateFrame(updatedRect, animated: true) start = nil resizeOutgoingVideoDirection = nil }, for: .Up) outgoingVideoView.frame = NSMakeRect(frame.width - outgoingVideoView.frame.width - 20, frame.height - 140 - outgoingVideoView.frame.height, outgoingVideoView.frame.width, outgoingVideoView.frame.height) } // func updateOutgoingAspectRatio(_ aspectRatio: CGFloat, animated: Bool) { // if aspectRatio > 0, !outgoingVideoView.isEventLess, self.outgoingAspectRatio != aspectRatio { // var rect = outgoingVideoView.frame // let closest: CGFloat = 150 // rect.size = NSMakeSize(floor(closest * aspectRatio), closest) // // let dif = outgoingVideoView.frame.size - rect.size // // rect.origin = rect.origin.offsetBy(dx: dif.width / 2, dy: dif.height / 2) // // if !outgoingVideoView.isMoved { // let addition = max(0, CGFloat(tooltips.count) * 40 - 5) // rect.origin = NSMakePoint(frame.width - rect.width - 20, frame.height - 140 - rect.height - addition) // } // // outgoingVideoView.updateFrame(rect, animated: animated) // } // self.outgoingAspectRatio = aspectRatio // } // private func mainControlY(_ control: NSView) -> CGFloat { return controls.frame.height - control.frame.height - 40 } private func mainControlCenter(_ control: NSView) -> CGFloat { return floorToScreenPixels(backingScaleFactor, (controls.frame.width - control.frame.width) / 2) } private var previousFrame: NSRect = .zero override func layout() { super.layout() settings.setFrameOrigin(NSMakePoint(frame.width - settings.frame.width - 5, 5)) backgroundView.frame = bounds imageView.frame = bounds incomingVideoView.frame = bounds if self.outgoingVideoView.videoView == nil { self.outgoingVideoView.frame = bounds } textNameView.setFrameSize(NSMakeSize(controls.frame.width - 40, 45)) textNameView.centerX(y: 50) statusView.setFrameSize(statusView.sizeThatFits(NSMakeSize(controls.frame.width - 40, 25))) statusView.centerX(y: textNameView.frame.maxY + 8) secureTextView.centerX(y: statusView.frame.maxY + 8) let controlsSize = NSMakeSize(frame.width, 220) controls.frame = NSMakeRect(0, frame.height - controlsSize.height, controlsSize.width, controlsSize.height) basicControls.frame = controls.bounds guard let state = self.state else { return } if !outgoingVideoView.isViewHidden { if outgoingVideoView.isEventLess { let videoFrame = bounds outgoingVideoView.updateFrame(videoFrame, animated: false) } else { var point = outgoingVideoView.frame.origin let size = outgoingVideoView.frame.size if previousFrame.size != frame.size { point.x += (frame.width - point.x) - (previousFrame.width - point.x) point.y += (frame.height - point.y) - (previousFrame.height - point.y) point.x = max(min(frame.width - size.width - 20, point.x), 20) point.y = max(min(frame.height - size.height - 20, point.y), 20) } let videoFrame = NSMakeRect(point.x, point.y, size.width, size.height) outgoingVideoView.updateFrame(videoFrame, animated: false) } } switch state.state { case .connecting, .active, .requesting, .terminating: let activeViews = self.allActiveControlsViews let restWidth = self.allControlRestWidth var x: CGFloat = floor(restWidth / 2) for activeView in activeViews { activeView.setFrameOrigin(NSMakePoint(x, mainControlY(acceptControl))) x += activeView.size.width + 45 } case let .terminated(_, reason, _): if let reason = reason, reason.recall { let activeViews = self.activeControlsViews let restWidth = self.controlRestWidth var x: CGFloat = floor(restWidth / 2) for activeView in activeViews { activeView.setFrameOrigin(NSMakePoint(x, 0)) x += activeView.size.width + 45 } acceptControl.setFrameOrigin(frame.midX + 25, mainControlY(acceptControl)) declineControl.setFrameOrigin(frame.midX - 25 - declineControl.frame.width, mainControlY(acceptControl)) } else { let activeViews = self.allActiveControlsViews let restWidth = self.allControlRestWidth var x: CGFloat = floor(restWidth / 2) for activeView in activeViews { activeView.setFrameOrigin(NSMakePoint(x, mainControlY(acceptControl))) x += activeView.size.width + 45 } } case .ringing: declineControl.setFrameOrigin(frame.midX - 25 - declineControl.frame.width, mainControlY(declineControl)) acceptControl.setFrameOrigin(frame.midX + 25, mainControlY(acceptControl)) let activeViews = self.activeControlsViews let restWidth = self.controlRestWidth var x: CGFloat = floor(restWidth / 2) for activeView in activeViews { activeView.setFrameOrigin(NSMakePoint(x, 0)) x += activeView.size.width + 45 } case .waiting: break case .reconnecting(_, _, _): break } if let dimension = imageDimension { let arguments = TransformImageArguments(corners: ImageCorners(), imageSize: dimension, boundingSize: self.imageView.frame.size, intrinsicInsets: NSEdgeInsets()) self.imageView.set(arguments: arguments) } var y: CGFloat = self.controls.frame.minY - 40 + (self.allActiveControlsViews.first?.frame.minY ?? 0) for view in tooltips { let x = focus(view.frame.size).minX view.setFrameOrigin(NSMakePoint(x, y)) y -= (view.frame.height + 10) } previousFrame = self.frame } var activeControlsViews:[CallControl] { return basicControls.subviews.filter { !$0.isHidden }.compactMap { $0 as? CallControl } } var allActiveControlsViews: [CallControl] { let values = basicControls.subviews.filter { !$0.isHidden }.compactMap { $0 as? CallControl } return values + controls.subviews.filter { $0 is CallControl && !$0.isHidden }.compactMap { $0 as? CallControl } } var controlRestWidth: CGFloat { return controls.frame.width - CGFloat(activeControlsViews.count - 1) * 45 - CGFloat(activeControlsViews.count) * 50 } var allControlRestWidth: CGFloat { return controls.frame.width - CGFloat(allActiveControlsViews.count - 1) * 45 - CGFloat(allActiveControlsViews.count) * 50 } func updateName(_ name:String) { textNameView.stringValue = name needsLayout = true } func updateControlsVisibility() { if let state = state { switch state.state { case .active: self.backgroundView.change(opacity: self.mouseInside() ? 1.0 : 0.0) self.controls.change(opacity: self.mouseInside() ? 1.0 : 0.0) self.textNameView._change(opacity: self.mouseInside() ? 1.0 : 0.0) self.secureTextView._change(opacity: self.mouseInside() ? 1.0 : 0.0) self.statusView._change(opacity: self.mouseInside() ? 1.0 : 0.0) for tooltip in tooltips { tooltip.change(opacity: self.mouseInside() ? 1.0 : 0.0) } self.settings._change(opacity: self.mouseInside() ? 1.0 : 0.0) default: self.backgroundView.change(opacity: 1.0) self.controls.change(opacity: 1.0) self.textNameView._change(opacity: 1.0) self.secureTextView._change(opacity: 1.0) self.statusView._change(opacity: 1.0) self.settings._change(opacity: 1.0) for tooltip in tooltips { tooltip.change(opacity: 1.0) } } } } func updateState(_ state:CallState, session:PCallSession, outgoingCameraInitialized: CameraState, incomingCameraInitialized: CameraState, accountPeer: Peer?, peer: TelegramUser?, animated: Bool) { var incomingCameraInitialized = incomingCameraInitialized var outgoingCameraInitialized = outgoingCameraInitialized switch state.remoteVideoState { case .active: if !self.incomingVideoViewRequested { self.incomingVideoViewRequested = true self.incomingVideoView._cameraInitialized.set(.initializing) incomingCameraInitialized = .initializing session.makeIncomingVideoView(completion: { [weak self] view in if let view = view, let `self` = self { self.incomingVideoView.videoView = view self.incomingVideoView.updateAspectRatio = self.updateIncomingAspectRatio self.incomingVideoView.firstFrameHandler = { [weak self] in self?.incomingVideoView.unhideView(animated: animated) } } }) } case .inactive, .paused: self.incomingVideoViewRequested = false self.incomingVideoView.hideView(animated: animated) self.incomingVideoView._cameraInitialized.set(.notInited) incomingCameraInitialized = .notInited } switch state.videoState { case let .active(possible): if !self.outgoingVideoViewRequested { self.outgoingVideoViewRequested = true self.outgoingVideoView._cameraInitialized.set(.initializing) outgoingCameraInitialized = .initializing session.makeOutgoingVideoView(completion: { [weak self] view in if let view = view, let `self` = self { self.outgoingVideoView.videoView = (view, possible) self.outgoingVideoView.firstFrameHandler = { [weak self] in self?.outgoingVideoView.unhideView(animated: animated) } } }) } case .inactive, .paused: self.outgoingVideoViewRequested = false self.outgoingVideoView.hideView(animated: animated) self.outgoingVideoView._cameraInitialized.set(.notInited) outgoingCameraInitialized = .notInited default: break } let isMirrored = !state.isScreenCapture self.outgoingVideoView.isMirrored = isMirrored // // self.outgoingVideoView.videoView?.0?.setOnIsMirroredUpdated = { f in // f(isMirrored) // } let inputCameraIsActive: Bool switch state.videoState { case let .active(possible): inputCameraIsActive = !state.isOutgoingVideoPaused && possible default: inputCameraIsActive = false } if outgoingCameraInitialized == .initializing { self.b_VideoCamera.updateEnabled(false, animated: animated) self.b_ScreenShare.updateEnabled(false, animated: animated) } else { self.b_VideoCamera.updateEnabled(state.videoIsAvailable(session.isVideo), animated: animated) self.b_ScreenShare.updateEnabled(state.videoIsAvailable(session.isVideo), animated: animated) } let vcBg: CallControlData.Mode if !inputCameraIsActive { vcBg = .visualEffect(inputCameraIsActive ? theme.icons.callWindowVideoActive : theme.icons.callWindowVideo) } else { vcBg = .normal(.white, inputCameraIsActive ? theme.icons.callWindowVideoActive : theme.icons.callWindowVideo) } let mBg: CallControlData.Mode if !state.isMuted { mBg = .visualEffect(state.isMuted ? theme.icons.callWindowMuteActive : theme.icons.callWindowMute) } else { mBg = .normal(.white, state.isMuted ? theme.icons.callWindowMuteActive : theme.icons.callWindowMute) } self.b_VideoCamera.updateWithData(CallControlData(text: strings().callCamera, mode: vcBg, iconSize: NSMakeSize(50, 50)), animated: false) self.b_Mute.updateWithData(CallControlData(text: strings().callMute, mode: mBg, iconSize: NSMakeSize(50, 50)), animated: false) self.b_Mute.updateEnabled(state.muteIsAvailable, animated: animated) self.b_VideoCamera.updateLoading(outgoingCameraInitialized == .initializing && !state.isScreenCapture, animated: animated) self.b_VideoCamera.isHidden = !session.isVideoPossible let ssBg: CallControlData.Mode if !state.isScreenCapture { ssBg = .visualEffect(state.isScreenCapture ? theme.icons.call_screen_sharing_active : theme.icons.call_screen_sharing) } else { ssBg = .normal(.white, state.isScreenCapture ? theme.icons.call_screen_sharing_active : theme.icons.call_screen_sharing) } self.b_ScreenShare.updateWithData(CallControlData(text: strings().callScreen, mode: ssBg, iconSize: NSMakeSize(50, 50)), animated: false) self.b_ScreenShare.updateLoading(outgoingCameraInitialized == .initializing && state.isScreenCapture, animated: animated) self.b_ScreenShare.isHidden = !session.isVideoPossible self.state = state self.statusView.status = state.state.statusText(accountPeer, state.videoState) switch state.state { case let .active(_, _, visual): let layout = TextViewLayout(.initialize(string: ObjcUtils.callEmojies(visual), color: .black, font: .normal(16.0)), alignment: .center) layout.measure(width: .greatestFiniteMagnitude) let wasEmpty = secureTextView.textLayout == nil secureTextView.update(layout) if wasEmpty { secureTextView.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) secureTextView.layer?.animateScaleSpring(from: 0.2, to: 1.0, duration: 0.4) } default: break } switch state.state { case .active, .connecting, .requesting, .reconnecting, .waiting: self.acceptControl.isHidden = true let activeViews = self.allActiveControlsViews let restWidth = self.allControlRestWidth var x: CGFloat = floor(restWidth / 2) for activeView in activeViews { activeView._change(pos: NSMakePoint(x, mainControlY(acceptControl)), animated: animated, duration: 0.3, timingFunction: .spring) x += activeView.size.width + 45 } declineControl.updateWithData(CallControlData(text: strings().callEnd, mode: .normal(.redUI, theme.icons.callWindowDeclineSmall), iconSize: NSMakeSize(50, 50)), animated: animated) case .ringing: declineControl.updateWithData(CallControlData(text: strings().callDecline, mode: .normal(.redUI, theme.icons.callWindowDeclineSmall), iconSize: NSMakeSize(50, 50)), animated: animated) case .terminated(_, let reason, _): if let reason = reason, reason.recall { self.acceptControl.isHidden = false let activeViews = self.activeControlsViews let restWidth = self.controlRestWidth var x: CGFloat = floor(restWidth / 2) for activeView in activeViews { activeView._change(pos: NSMakePoint(x, 0), animated: animated, duration: 0.3, timingFunction: .spring) x += activeView.size.width + 45 } acceptControl.updateWithData(CallControlData(text: strings().callRecall, mode: .normal(.greenUI, theme.icons.callWindowAccept), iconSize: NSMakeSize(50, 50)), animated: animated) declineControl.updateWithData(CallControlData(text: strings().callClose, mode: .normal(.redUI, theme.icons.callWindowCancel), iconSize: NSMakeSize(50, 50)), animated: animated) acceptControl.change(pos: NSMakePoint(frame.midX + 25, mainControlY(acceptControl)), animated: animated, duration: 0.3, timingFunction: .spring) declineControl.change(pos: NSMakePoint(frame.midX - 25 - declineControl.frame.width, mainControlY(acceptControl)), animated: animated, duration: 0.3, timingFunction: .spring) _ = activeControlsViews.map { $0.updateEnabled(false, animated: animated) } } else { self.acceptControl.isHidden = true declineControl.updateWithData(CallControlData(text: strings().callDecline, mode: .normal(.redUI, theme.icons.callWindowDeclineSmall), iconSize: NSMakeSize(50, 50)), animated: false) let activeViews = self.allActiveControlsViews let restWidth = self.allControlRestWidth var x: CGFloat = floor(restWidth / 2) for activeView in activeViews { activeView._change(pos: NSMakePoint(x, mainControlY(acceptControl)), animated: animated, duration: 0.3, timingFunction: .spring) x += activeView.size.width + 45 } _ = allActiveControlsViews.map { $0.updateEnabled(false, animated: animated) } } case .terminating: let activeViews = self.activeControlsViews let restWidth = self.controlRestWidth var x: CGFloat = floor(restWidth / 2) for activeView in activeViews { activeView.setFrameOrigin(NSMakePoint(x, 0)) x += activeView.size.width + 45 } acceptControl.setFrameOrigin(frame.midX + 25, mainControlY(acceptControl)) declineControl.setFrameOrigin(frame.midX - 25 - declineControl.frame.width, mainControlY(acceptControl)) _ = allActiveControlsViews.map { $0.updateEnabled(false, animated: animated) } } incomingVideoView.setIsPaused(state.remoteVideoState == .paused, peer: peer, animated: animated) let wasEventLess = outgoingVideoView.isEventLess switch state.state { case .ringing, .requesting, .terminating, .terminated: outgoingVideoView.isEventLess = true default: switch state.videoState { case .active: outgoingVideoView.isEventLess = false default: outgoingVideoView.isEventLess = true } if state.remoteVideoState == .inactive || incomingCameraInitialized == .notInited || incomingCameraInitialized == .initializing { outgoingVideoView.isEventLess = true } } var point = outgoingVideoView.frame.origin var size = outgoingVideoView.frame.size if !outgoingVideoView.isEventLess { if !self.outgoingVideoView.isMoved { if outgoingAspectRatio > 0 { size = NSMakeSize(150 * outgoingAspectRatio, 150) } else { size = OutgoingVideoView.defaultSize } let addition = max(0, CGFloat(tooltips.count) * 40 - 5) size = NSMakeSize(floor(size.width), floor(size.height)) point = NSMakePoint(frame.width - size.width - 20, frame.height - 140 - size.height - addition) } } else { self.outgoingVideoView.isMoved = false point = .zero size = frame.size } let videoFrame = CGRect(origin: point, size: size) if !outgoingVideoView.isViewHidden { outgoingVideoView.updateFrame(videoFrame, animated: animated) } if let peer = peer { updatePeerUI(peer, session: session) self.updateTooltips(state, session: session, peer: peer, animated: animated, updateOutgoingVideo: !wasEventLess && !outgoingVideoView.isEventLess) } if videoFrame == bounds { addSubview(backgroundView, positioned: .above, relativeTo: outgoingVideoView) } else { addSubview(backgroundView, positioned: .below, relativeTo: outgoingVideoView) } addSubview(settings) needsLayout = true } private func updateTooltips(_ state:CallState, session:PCallSession, peer: TelegramUser, animated: Bool, updateOutgoingVideo: Bool) { var tooltips: [CallTooltipType] = [] let maxWidth = defaultWindowSize.width - 40 if let displayToastsAfterTimestamp = self.displayToastsAfterTimestamp { if CACurrentMediaTime() > displayToastsAfterTimestamp { switch state.state { case .active: if state.remoteVideoState == .inactive { switch state.videoState { case .active: tooltips.append(.cameraOff) default: break } } if state.remoteAudioState == .muted { tooltips.append(.microOff) } if state.remoteBatteryLevel == .low { tooltips.append(.batteryLow) } default: break } } } else { switch state.state { case .active: self.displayToastsAfterTimestamp = CACurrentMediaTime() + 2.0 default: break } } let updated = self.tooltips let removeTips = updated.filter { value in if let type = value.type { return !tooltips.contains(type) } return true } let updateTips = updated.filter { value in if let type = value.type { return tooltips.contains(type) } return false } let newTips: [CallTooltipView] = tooltips.filter { tip -> Bool in for view in updated { if view.type == tip { return false } } return true }.map { tip in let view = CallTooltipView(frame: .zero) view.update(type: tip, icon: tip.icon, text: tip.text(peer.compactDisplayTitle), maxWidth: maxWidth) return view } for updated in updateTips { if let tip = updated.type { updated.update(type: tip, icon: tip.icon, text: tip.text(peer.compactDisplayTitle), maxWidth: maxWidth) } } for view in removeTips { if animated { view.layer?.animateScaleCenter(from: 1, to: 0.3, duration: 0.2) view.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, timingFunction: .spring, removeOnCompletion: false, completion: { [weak view] _ in view?.removeFromSuperview() }) } else { view.removeFromSuperview() } } var y: CGFloat = self.controls.frame.minY - 40 + (self.allActiveControlsViews.first?.frame.minY ?? 0) let sorted = (updateTips + newTips).sorted(by: { lhs, rhs in return lhs.type!.rawValue < rhs.type!.rawValue }) for view in sorted { let x = focus(view.frame.size).minX if view.superview == nil { addSubview(view) view.layer?.animateScaleSpring(from: 0.3, to: 1.0, duration: 0.2) view.layer?.animateAlpha(from: 0, to: 1, duration: 0.4, timingFunction: .spring) } else { if animated { view.change(pos: NSMakePoint(x, y), animated: animated) } } view.setFrameOrigin(NSMakePoint(x, y)) y -= (view.frame.height + 10) } self.tooltips = sorted if !outgoingVideoView.isMoved && outgoingVideoView.savedFrame != bounds { let addition = max(0, CGFloat(tooltips.count) * 40 - 5) let size = self.outgoingVideoView.frame.size let point = NSMakePoint(frame.width - size.width - 20, frame.height - 140 - size.height - addition) self.outgoingVideoView.updateFrame(CGRect(origin: point, size: size), animated: animated) } } private func updatePeerUI(_ user:TelegramUser, session: PCallSession) { let id = user.profileImageRepresentations.first?.resource.id.hashValue ?? Int(user.id.toInt64()) let media = TelegramMediaImage(imageId: MediaId(namespace: 0, id: MediaId.Id(id)), representations: user.profileImageRepresentations, immediateThumbnailData: nil, reference: nil, partialReference: nil, flags: []) if let dimension = user.profileImageRepresentations.last?.dimensions.size { self.imageDimension = dimension let arguments = TransformImageArguments(corners: ImageCorners(), imageSize: dimension, boundingSize: defaultWindowSize, intrinsicInsets: NSEdgeInsets()) self.imageView.setSignal(signal: cachedMedia(media: media, arguments: arguments, scale: self.backingScaleFactor), clearInstantly: false) self.imageView.setSignal(chatMessagePhoto(account: session.account, imageReference: ImageMediaReference.standalone(media: media), peer: user, scale: self.backingScaleFactor), clearInstantly: false, animate: true, cacheImage: { result in cacheMedia(result, media: media, arguments: arguments, scale: System.backingScale) }) self.imageView.set(arguments: arguments) if let reference = PeerReference(user) { fetching.set(fetchedMediaResource(mediaBox: session.account.postbox.mediaBox, reference: .avatar(peer: reference, resource: media.representations.last!.resource)).start()) } } else { self.imageDimension = nil self.imageView.setSignal(signal: generateEmptyRoundAvatar(self.imageView.frame.size, font: .avatar(90.0), account: session.account, peer: user) |> map { TransformImageResult($0, true) }) } self.updateName(user.displayTitle) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { fetching.dispose() } } class PhoneCallWindowController { let window:Window fileprivate var view:PhoneCallWindowView let updateLocalizationAndThemeDisposable = MetaDisposable() fileprivate var session:PCallSession! { didSet { first = false sessionDidUpdated() if let monitor = eventLocalMonitor { NSEvent.removeMonitor(monitor) } if let monitor = eventGlobalMonitor { NSEvent.removeMonitor(monitor) } eventLocalMonitor = NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved, .mouseEntered, .mouseExited, .leftMouseDown, .leftMouseUp], handler: { [weak self] event in self?.view.updateControlsVisibility() return event }) // eventGlobalMonitor = NSEvent.addGlobalMonitorForEvents(matching: [.mouseMoved, .mouseEntered, .mouseExited, .leftMouseDown, .leftMouseUp], handler: { [weak self] event in self?.view.updateControlsVisibility() }) } } var first:Bool = true private func sessionDidUpdated() { let account = session.account let accountPeer: Signal<Peer?, NoError> = session.accountContext.sharedContext.activeAccounts |> mapToSignal { accounts in if accounts.accounts.count == 1 { return .single(nil) } else { return account.postbox.loadedPeerWithId(account.peerId) |> map(Optional.init) } } let peer = session.account.viewTracker.peerView(session.peerId) |> map { return $0.peers[$0.peerId] as? TelegramUser } let outgoingCameraInitialized: Signal<CameraState, NoError> = .single(.notInited) |> then(view.outgoingVideoView.cameraInitialized) let incomingCameraInitialized: Signal<CameraState, NoError> = .single(.notInited) |> then(view.incomingVideoView.cameraInitialized) stateDisposable.set(combineLatest(queue: .mainQueue(), session.state, accountPeer, peer, outgoingCameraInitialized, incomingCameraInitialized).start(next: { [weak self] state, accountPeer, peer, outgoingCameraInitialized, incomingCameraInitialized in if let strongSelf = self { strongSelf.applyState(state, session: strongSelf.session!, outgoingCameraInitialized: outgoingCameraInitialized, incomingCameraInitialized: incomingCameraInitialized, accountPeer: accountPeer, peer: peer, animated: !strongSelf.first) strongSelf.first = false // strongSelf.updateOutgoingAspectRatio(state.remoteAspectRatio) } })) let signal = session.canBeRemoved |> deliverOnMainQueue closeDisposable.set(signal.start(next: { value in if value { closeCall() } })) } private var state:CallState? = nil private let disposable:MetaDisposable = MetaDisposable() private let stateDisposable = MetaDisposable() private let durationDisposable = MetaDisposable() private let recallDisposable = MetaDisposable() private let keyStateDisposable = MetaDisposable() private let readyDisposable = MetaDisposable() private let fullReadyDisposable = MetaDisposable() private var cameraInitialized: Promise<Bool> = Promise() private let ready: Promise<Bool> = Promise() fileprivate var eventLocalMonitor: Any? fileprivate var eventGlobalMonitor: Any? init(_ session:PCallSession) { self.session = session let size = defaultWindowSize if let screen = NSScreen.main { self.window = Window(contentRect: NSMakeRect(floorToScreenPixels(System.backingScale, (screen.frame.width - size.width) / 2), floorToScreenPixels(System.backingScale, (screen.frame.height - size.height) / 2), size.width, size.height), styleMask: [.fullSizeContentView, .borderless, .resizable, .miniaturizable, .titled], backing: .buffered, defer: true, screen: screen) self.window.minSize = NSMakeSize(400, 580) self.window.isOpaque = true self.window.backgroundColor = .black } else { fatalError("screen not found") } view = PhoneCallWindowView(frame: NSMakeRect(0, 0, size.width, size.height)) NotificationCenter.default.addObserver(self, selector: #selector(windowDidBecomeKey), name: NSWindow.didBecomeKeyNotification, object: window) NotificationCenter.default.addObserver(self, selector: #selector(windowDidResignKey), name: NSWindow.didResignKeyNotification, object: window) view.acceptControl.set(handler: { [weak self] _ in if let state = self?.state { switch state.state { case .ringing: self?.session.acceptCallSession() case .terminated(_, let reason, _): if let reason = reason, reason.recall { self?.recall() } default: break } } }, for: .Click) view.settings.set(handler: { [weak window, weak session] _ in guard let window = window, let session = session else { return } showModal(with: CallSettingsModalController(session.accountContext.sharedContext), for: window) }, for: .SingleClick) self.view.b_VideoCamera.set(handler: { [weak self] _ in if let `self` = self, let callState = self.state { switch callState.videoState { case let .active(available), let .paused(available), let .inactive(available): if available { if callState.isOutgoingVideoPaused || callState.isScreenCapture || callState.videoState == .inactive(available) { self.session.requestVideo() } else { self.session.disableVideo() } } else { confirm(for: self.window, information: strings().callCameraError, okTitle: strings().modalOK, cancelTitle: "", thridTitle: strings().requestAccesErrorConirmSettings, successHandler: { result in switch result { case .thrid: openSystemSettings(.camera) default: break } }) } default: break } } }, for: .Click) self.view.b_ScreenShare.set(handler: { [weak self] _ in guard let window = self?.window else { return } let result = self?.session.toggleScreenCapture() if let result = result { switch result { case .permission: confirm(for: window, information: strings().callScreenError, okTitle: strings().modalOK, cancelTitle: "", thridTitle: strings().requestAccesErrorConirmSettings, successHandler: { result in switch result { case .thrid: openSystemSettings(.sharing) default: break } }) } } }, for: .Click) self.view.b_Mute.set(handler: { [weak self] _ in if let session = self?.session { session.toggleMute() } }, for: .Click) view.declineControl.set(handler: { [weak self] _ in if let state = self?.state { switch state.state { case let .terminated(_, reason, _): if let reason = reason, reason.recall { self?.session.setToRemovableState() } default: _ = self?.session.hangUpCurrentCall().start() } } else { self?.session.setToRemovableState() } }, for: .Click) self.window.contentView = view self.window.titlebarAppearsTransparent = true self.window.isMovableByWindowBackground = true sessionDidUpdated() window.set(mouseHandler: { [weak self] _ -> KeyHandlerResult in guard let `self` = self else {return .rejected} self.view.updateControlsVisibility() return .rejected }, with: self.view, for: .mouseMoved) window.set(mouseHandler: { [weak self] _ -> KeyHandlerResult in guard let `self` = self else {return .rejected} self.view.updateControlsVisibility() return .rejected }, with: self.view, for: .mouseEntered) window.set(mouseHandler: { [weak self] _ -> KeyHandlerResult in guard let `self` = self else {return .rejected} self.view.updateControlsVisibility() return .rejected }, with: self.view, for: .mouseExited) window.onToggleFullScreen = { [weak self] value in self?.view.incomingVideoView.videoView?.setVideoContentMode(.resizeAspect) } self.view.backgroundView.set(handler: { [weak self] _ in self?.view.updateControlsVisibility() }, for: .Click) window.animationBehavior = .utilityWindow // updateIncomingAspectRatio(Float(System.cameraAspectRatio)) } private func recall() { recallDisposable.set((phoneCall(context: session.accountContext, peerId: session.peerId, ignoreSame: true) |> deliverOnMainQueue).start(next: { [weak self] result in switch result { case let .success(session): self?.session = session case .fail: break case .samePeer: break } })) } private var incomingAspectRatio: Float = 0 private func updateIncomingAspectRatio(_ aspectRatio: Float) { if aspectRatio > 0 && self.incomingAspectRatio != aspectRatio, let screen = window.screen { var closestSide: CGFloat if aspectRatio > 1 { closestSide = min(window.frame.width, window.frame.height) } else { closestSide = max(window.frame.width, window.frame.height) } closestSide = max(400, closestSide) var updatedSize = NSMakeSize(floor(closestSide * CGFloat(aspectRatio)), closestSide) if screen.frame.width <= updatedSize.width || screen.frame.height <= updatedSize.height { let closest = min(updatedSize.width, updatedSize.height) updatedSize = NSMakeSize(floor(closest * CGFloat(aspectRatio)), closest) } window.setFrame(CGRect(origin: window.frame.origin.offsetBy(dx: (window.frame.width - updatedSize.width) / 2, dy: (window.frame.height - updatedSize.height) / 2), size: updatedSize), display: true, animate: true) window.aspectRatio = updatedSize self.incomingAspectRatio = aspectRatio } } // private var outgoingAspectRatio: Float = 0 // private func updateOutgoingAspectRatio(_ aspectRatio: Float) { // if aspectRatio > 0 && self.outgoingAspectRatio != aspectRatio { // self.outgoingAspectRatio = aspectRatio // self.view.updateOutgoingAspectRatio(CGFloat(aspectRatio), animated: true) // } // } @objc open func windowDidBecomeKey() { keyStateDisposable.set(nil) } @objc open func windowDidResignKey() { keyStateDisposable.set((session.state |> deliverOnMainQueue).start(next: { [weak self] state in if let strongSelf = self { if case .active = state.state, !strongSelf.session.isVideo, !strongSelf.window.isKeyWindow { switch state.videoState { case .active, .paused: break default: closeCall() } } } })) } private func applyState(_ state:CallState, session: PCallSession, outgoingCameraInitialized: CameraState, incomingCameraInitialized: CameraState, accountPeer: Peer?, peer: TelegramUser?, animated: Bool) { self.state = state view.updateState(state, session: session, outgoingCameraInitialized: outgoingCameraInitialized, incomingCameraInitialized: incomingCameraInitialized, accountPeer: accountPeer, peer: peer, animated: animated) switch state.state { case .ringing: break case .connecting: break case .requesting: break case .active: break case .terminating: break case .terminated(_, let error, _): switch error { case .ended(let reason)?: break case let .error(error)?: disposable.set((session.account.postbox.loadedPeerWithId(session.peerId) |> deliverOnMainQueue).start(next: { peer in switch error { case .privacyRestricted: alert(for: self.window, info: strings().callPrivacyErrorMessage(peer.compactDisplayTitle)) case .notSupportedByPeer: alert(for: self.window, info: strings().callParticipantVersionOutdatedError(peer.compactDisplayTitle)) case .serverProvided(let serverError): alert(for: self.window, info: serverError) case .generic: alert(for: self.window, info: strings().callUndefinedError) default: break } })) case .none: break } case .waiting: break case .reconnecting: break } self.ready.set(.single(true)) switch state.state { case .terminating, .terminated: self.window.styleMask.insert(.closable) self.window.closeInterceptor = { [weak self] in self?.session.setToRemovableState() return true } case .waiting, .ringing: self.window.closeInterceptor = { [weak self] in self?.session.setToRemovableState() return true } default: self.window.styleMask.remove(.closable) } } deinit { cleanup() } fileprivate func cleanup() { disposable.dispose() stateDisposable.dispose() durationDisposable.dispose() recallDisposable.dispose() keyStateDisposable.dispose() readyDisposable.dispose() fullReadyDisposable.dispose() updateLocalizationAndThemeDisposable.dispose() NotificationCenter.default.removeObserver(self) self.window.removeAllHandlers(for: self.view) _ = enableScreenSleep() _ = self.view.allActiveControlsViews.map { $0.updateEnabled(false, animated: true) } } private var assertionID: IOPMAssertionID = 0 private var success: IOReturn? private func disableScreenSleep() -> Bool? { guard success == nil else { return nil } success = IOPMAssertionCreateWithName( kIOPMAssertionTypeNoDisplaySleep as CFString, IOPMAssertionLevel(kIOPMAssertionLevelOn), "Group Call" as CFString, &assertionID ) return success == kIOReturnSuccess } private func enableScreenSleep() -> Bool { if success != nil { success = IOPMAssertionRelease(assertionID) success = nil return true } return false } func show() { _ = self.disableScreenSleep() let ready = self.ready.get() |> filter { $0 } |> take(1) readyDisposable.set(ready.start(next: { [weak self] _ in if let `self` = self, self.window.isVisible == false { self.window.makeKeyAndOrderFront(self) self.window.orderFrontRegardless() self.window.alphaValue = 0 let fullReady: Signal<Bool, NoError> if self.session.isVideo, self.session.isVideoPossible { fullReady = self.view.outgoingVideoView.cameraInitialized |> timeout(5.0, queue: .mainQueue(), alternate: .single(.inited)) |> map { $0 == .inited } |> filter { $0 } |> take(1) } else { fullReady = .single(true) } self.fullReadyDisposable.set(fullReady.start(next: { [weak self] _ in self?.window.animator().alphaValue = 1 self?.window.orderFrontRegardless() self?.view.layer?.animateScaleSpring(from: 0.2, to: 1.0, duration: 0.4) self?.view.layer?.animateAlpha(from: 0.2, to: 1.0, duration: 0.3) })) } else { self?.window.makeKeyAndOrderFront(self) self?.window.orderFrontRegardless() } })) } } private let controller:Atomic<PhoneCallWindowController?> = Atomic(value: nil) private let closeDisposable = MetaDisposable() func makeKeyAndOrderFrontCallWindow() -> Bool { return controller.with { value in if let value = value { value.window.makeKeyAndOrderFront(nil) value.window.orderFrontRegardless() return true } else { return false } } } func showCallWindow(_ session:PCallSession) { _ = controller.modify { controller in if session.peerId != controller?.session.peerId { _ = controller?.session.hangUpCurrentCall().start() if let controller = controller { controller.session = session return controller } else { return PhoneCallWindowController(session) } } return controller } controller.with { $0?.show() } } func closeCall(minimisize: Bool = false) { _ = controller.modify { controller in if let controller = controller { controller.cleanup() let accountContext = controller.session.accountContext let isVideo = controller.session.isVideo _ = (controller.session.state |> take(1) |> deliverOnMainQueue).start(next: { state in switch state.state { case let .terminated(callId, _, report): if report, let callId = callId { showModal(with: CallRatingModalViewController(accountContext, callId: callId, userInitiated: false, isVideo: isVideo), for: accountContext.window) } default: break } }) if controller.window.isFullScreen { controller.window.toggleFullScreen(nil) delay(0.8, closure: { NSAnimationContext.runAnimationGroup({ ctx in controller.window.animator().alphaValue = 0 }, completionHandler: { controller.window.orderOut(nil) }) }) } else { NSAnimationContext.runAnimationGroup({ ctx in controller.window.animator().alphaValue = 0 }, completionHandler: { controller.window.orderOut(nil) }) } } return nil } } func applyUIPCallResult(_ context: AccountContext, _ result:PCallResult) { assertOnMainThread() switch result { case let .success(session): showCallWindow(session) case .fail: break case let .samePeer(session): if let header = context.bindings.rootNavigation().callHeader, header.needShown { showCallWindow(session) } else { controller.with { $0?.window.orderFront(nil) } } } }
gpl-2.0
46e0b863947abfef3fd6e72975dad899
39.78722
381
0.565736
5.106647
false
false
false
false
MaddTheSane/Nuke
Nuke/Source/UI/ImagePreheatingControllerForCollectionView.swift
1
4159
// The MIT License (MIT) // // Copyright (c) 2015 Alexander Grebenyuk (github.com/kean). import Foundation import UIKit public class ImagePreheatingControllerForCollectionView: ImagePreheatingController { public let collectionView: UICollectionView public var collectionViewLayout: UICollectionViewFlowLayout { return self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout } /** The proportion of the collection view size (either width or height depending on the scroll axis) used as a preheat window. */ public var preheatRectRatio: CGFloat = 1.0 /** Determines how far the user needs to refresh preheat window.. */ public var preheatRectUpdateRatio: CGFloat = 0.33 private var previousContentOffset = CGPointZero public init(collectionView: UICollectionView) { assert(collectionView.collectionViewLayout is UICollectionViewFlowLayout) self.collectionView = collectionView super.init(scrollView: collectionView) } public override var enabled: Bool { didSet { if self.enabled { self.updatePreheatRect() } else { self.previousContentOffset = CGPointZero self.updatePreheatIndexPaths([]) } } } public override func scrollViewDidScroll() { if self.enabled { self.updatePreheatRect() } } private enum ScrollDirection { case Forward, Backward } private func updatePreheatRect() { let scrollAxis = self.collectionViewLayout.scrollDirection let updateMargin = (scrollAxis == .Vertical ? CGRectGetHeight : CGRectGetWidth)(self.collectionView.bounds) * self.preheatRectUpdateRatio let contentOffset = self.collectionView.contentOffset guard distanceBetweenPoints(contentOffset, self.previousContentOffset) > updateMargin || self.previousContentOffset == CGPointZero else { return } let scrollDirection: ScrollDirection = ((scrollAxis == .Vertical ? contentOffset.y >= self.previousContentOffset.y : contentOffset.x >= self.previousContentOffset.x) || self.previousContentOffset == CGPointZero) ? .Forward : .Backward self.previousContentOffset = contentOffset let preheatRect = self.preheatRectInScrollDirection(scrollDirection) let visibleIndexPaths = self.collectionView.indexPathsForVisibleItems() let preheatIndexPaths = self.indexPathsForElementsInRect(preheatRect).subtract(visibleIndexPaths).sort { switch scrollDirection { case .Forward: return $0.section < $1.section || $0.item < $1.item case .Backward: return $0.section > $1.section || $0.item > $1.item } } self.updatePreheatIndexPaths(preheatIndexPaths) } private func preheatRectInScrollDirection(direction: ScrollDirection) -> CGRect { // UIScrollView bounds works differently from UIView bounds, it adds contentOffset let viewport = self.collectionView.bounds switch self.collectionViewLayout.scrollDirection { case .Vertical: let height = CGRectGetHeight(viewport) * self.preheatRectRatio let y = (direction == .Forward) ? CGRectGetMaxY(viewport) : CGRectGetMinY(viewport) - height return CGRectIntegral(CGRect(x: 0, y: y, width: CGRectGetWidth(viewport), height: height)) case .Horizontal: let width = CGRectGetWidth(viewport) * self.preheatRectRatio let x = (direction == .Forward) ? CGRectGetMaxX(viewport) : CGRectGetMinX(viewport) - width return CGRectIntegral(CGRect(x: x, y: 0, width: width, height: CGRectGetHeight(viewport))) } } private func indexPathsForElementsInRect(rect: CGRect) -> Set<NSIndexPath> { guard let layoutAttributes = self.collectionViewLayout.layoutAttributesForElementsInRect(rect) else { return [] } return Set(layoutAttributes.filter{ return $0.representedElementCategory == .Cell }.map{ return $0.indexPath }) } }
mit
4431d45dee6b4c4d51e22438fff84cc7
43.72043
242
0.681173
5.465177
false
false
false
false
russbishop/swift
test/IRGen/newtype.swift
1
4472
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t -I %S/../IDE/Inputs/custom-modules) %s -emit-ir -enable-swift-newtype | FileCheck %s // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t -I %S/../IDE/Inputs/custom-modules) %s -emit-ir -enable-swift-newtype -O | FileCheck %s -check-prefix=OPT import CoreFoundation import Foundation import Newtype // REQUIRES: objc_interop // Witness table for synthesized ClosedEnums : _ObjectiveCBridgeable. // CHECK: @_TWPVSC10ClosedEnums21_ObjectiveCBridgeable7Newtype = linkonce_odr // CHECK-LABEL: define %CSo8NSString* @_TF7newtype14getErrorDomainFT_VSC11ErrorDomain() public func getErrorDomain() -> ErrorDomain { // CHECK: load %CSo8NSString*, %CSo8NSString** getelementptr inbounds (%VSC11ErrorDomain, %VSC11ErrorDomain* {{.*}}@SNTErrOne return .one } // CHECK-LABEL: _TF7newtype6getFooFT_VCSo14NSNotification4Name public func getFoo() -> NSNotification.Name { return NSNotification.Name.Foo // CHECK: load {{.*}} @FooNotification // CHECK: ret } // CHECK-LABEL: _TF7newtype21getGlobalNotificationFSiSS public func getGlobalNotification(_ x: Int) -> String { switch x { case 1: return kNotification // CHECK: load {{.*}} @kNotification case 2: return Notification // CHECK: load {{.*}} @Notification case 3: return swiftNamedNotification // CHECK: load {{.*}} @kSNNotification default: return NSNotification.Name.bar.rawValue // CHECK: load {{.*}} @kBarNotification } // CHECK: ret } // CHECK-LABEL: _TF7newtype17getCFNewTypeValueFT6useVarSb_VSC9CFNewType public func getCFNewTypeValue(useVar: Bool) -> CFNewType { if (useVar) { return CFNewType.MyCFNewTypeValue // CHECK: load {{.*}} @MyCFNewTypeValue } else { return FooAudited() // CHECK: call {{.*}} @FooAudited() } // CHECK: ret } // CHECK-LABEL: _TF7newtype21getUnmanagedCFNewTypeFT6useVarSb_GVs9UnmanagedCSo8CFString_ public func getUnmanagedCFNewType(useVar: Bool) -> Unmanaged<CFString> { if (useVar) { return CFNewType.MyCFNewTypeValueUnaudited // CHECK: load {{.*}} @MyCFNewTypeValueUnaudited } else { return FooUnaudited() // CHECK: call {{.*}} @FooUnaudited() } // CHECK: ret } // Triggers instantiation of ClosedEnum : _ObjectiveCBridgeable // witness table. public func hasArrayOfClosedEnums(closed: [ClosedEnum]) { } // CHECK-LABEL: _TF7newtype11compareABIsFT_T_ public func compareABIs() { let new = getMyABINewType() let old = getMyABIOldType() takeMyABINewType(new) takeMyABIOldType(old) takeMyABINewTypeNonNull(new!) takeMyABIOldTypeNonNull(old!) let newNS = getMyABINewTypeNS() let oldNS = getMyABIOldTypeNS() takeMyABINewTypeNonNullNS(newNS!) takeMyABIOldTypeNonNullNS(oldNS!) // Make sure that the calling conventions align correctly, that is we don't // have double-indirection or anything else like that // CHECK: declare %struct.__CFString* @getMyABINewType() // CHECK: declare %struct.__CFString* @getMyABIOldType() // // CHECK: declare void @takeMyABINewType(%struct.__CFString*) // CHECK: declare void @takeMyABIOldType(%struct.__CFString*) // // CHECK: declare void @takeMyABINewTypeNonNull(%struct.__CFString*) // CHECK: declare void @takeMyABIOldTypeNonNull(%struct.__CFString*) // // CHECK: declare %0* @getMyABINewTypeNS() // CHECK: declare %0* @getMyABIOldTypeNS() // // CHECK: declare void @takeMyABINewTypeNonNullNS(%0*) // CHECK: declare void @takeMyABIOldTypeNonNullNS(%0*) } // OPT-LABEL: define i1 @_TF7newtype12compareInitsFT_Sb public func compareInits() -> Bool { let mf = MyInt(rawValue: 1) let mfNoLabel = MyInt(1) let res = mf.rawValue == MyInt.one.rawValue && mfNoLabel.rawValue == MyInt.one.rawValue // OPT: [[ONE:%.*]] = load i32, i32*{{.*}}@kMyIntOne{{.*}}, align 4 // OPT-NEXT: [[COMP:%.*]] = icmp eq i32 [[ONE]], 1 takesMyInt(mf) takesMyInt(mfNoLabel) takesMyInt(MyInt(rawValue: kRawInt)) takesMyInt(MyInt(kRawInt)) // OPT: tail call void @takesMyInt(i32 1) // OPT-NEXT: tail call void @takesMyInt(i32 1) // OPT-NEXT: [[RAWINT:%.*]] = load i32, i32*{{.*}} @kRawInt{{.*}}, align 4 // OPT-NEXT: tail call void @takesMyInt(i32 [[RAWINT]]) // OPT-NEXT: tail call void @takesMyInt(i32 [[RAWINT]]) return res // OPT-NEXT: ret i1 [[COMP]] } // CHECK-LABEL: anchor // OPT-LABEL: anchor public func anchor() -> Bool { return false }
apache-2.0
ef50b990bdd4ec4e07faf1385c5cf558
32.878788
167
0.697898
3.591968
false
false
false
false
Josscii/iOS-Demos
TabViewDemo/TabViewDemo/ViewController.swift
1
5112
// // ViewController.swift // TabViewDemo // // Created by josscii on 2018/7/18. // Copyright © 2018年 josscii. All rights reserved. // import UIKit class ViewController: UIViewController { var tabView: WYTabView! var scrollView: UIScrollView! var tabView1: TabView! override func viewDidLoad() { super.viewDidLoad() scrollView = UIScrollView(frame: CGRect(x: 0, y: 200, width: view.bounds.width, height: 200)) scrollView.contentSize = CGSize(width: view.bounds.width * CGFloat(items.count), height: 200) view.addSubview(scrollView) scrollView.isPagingEnabled = true scrollView.backgroundColor = .red // tabView = WYTabView(frame: CGRect(x: 0, y: 100, width: view.bounds.width, height: 100), coordinatedScrollView: scrollView) // tabView.delegate = self // tabView.backgroundColor = .green // tabView.itemWidth = 100 // view.addSubview(tabView) tabView1 = TabView(frame: CGRect(x: 0, y: 100, width: view.bounds.width, height: 50), coordinatedScrollView: scrollView) tabView1.delegate = self // tabView1.isItemGestureDriven = true tabView1.backgroundColor = .green tabView1.isIndicatorGestureDriven = true tabView1.widthType = .selfSizing tabView1.register(TabItemCell.self, forCellWithReuseIdentifier: TabItemCell.reuseIdentifier) view.addSubview(tabView1) } var items = ["哈哈", "嘻嘻嘻", "嗯", "不要啊啊", "确定", "来抱抱", "不行啊"] override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // tabView.reloadData() } } extension ViewController: WYTabViewDelegate { func tabView(_ tabView: WYTabView, updateIndicatorView indicatorView: UIView?, withProgress progress: CGFloat) { guard let indicatorView = indicatorView else { return } let width = 50 + (80 - 50) * progress let x = (100 - width) / 2 indicatorView.frame.size.width = width indicatorView.frame.origin.x = x } func tabView(_ tabView: WYTabView, indicatorWithSuperView superView: UIView) -> UIView { let view = UIView() view.backgroundColor = .red view.frame = CGRect(x: (100-50)/2, y: 0, width: 50, height: 2) superView.addSubview(view) return view } func tabView(_ tabView: WYTabView, didSelect itemView: WYTabItemView?, at index: Int) { } func numberOfItems(in tabView: WYTabView) -> Int { return items.count } func tabView(_ tabView: WYTabView, configureItemAt index: Int, with cell: WYTabItemCell) { if let itemView = cell.itemView as? WYSimpleTabItemView { itemView.titleLabel.text = items[index] } else { let itemView = WYSimpleTabItemView() itemView.frame = cell.contentView.bounds itemView.autoresizingMask = [.flexibleWidth, .flexibleHeight] itemView.titleLabel.text = items[index] cell.contentView.addSubview(itemView) cell.itemView = itemView } } } extension ViewController: TabViewDelegate { func tabView(_ tabView: TabView, update indicatorView: UIView?, with progress: CGFloat) { guard let indicatorView = indicatorView, let indicatorSuperView = indicatorView.superview else { return } let w = 10 + (30 - 10) * progress let centerX = indicatorSuperView.frame.width / 2 indicatorView.frame.size.width = w indicatorView.center.x = centerX } func tabView(_ tabView: TabView, indicatorViewWith superView: UIView) -> UIView? { let view = UIView() view.backgroundColor = .red view.frame = CGRect(x: (superView.bounds.width - 10)/2, y: 0, width: 10, height: 2) superView.addSubview(view) return view // let view = UIView() // view.backgroundColor = .red // view.layer.cornerRadius = 10 // view.translatesAutoresizingMaskIntoConstraints = false // superView.addSubview(view) // view.topAnchor.constraint(equalTo: superView.topAnchor).isActive = true // view.leftAnchor.constraint(equalTo: superView.leftAnchor).isActive = true // view.bottomAnchor.constraint(equalTo: superView.bottomAnchor).isActive = true // view.rightAnchor.constraint(equalTo: superView.rightAnchor).isActive = true // return view } func numberOfItems(in tabView: TabView) -> Int { return items.count } func tabView(_ tabView: TabView, cellForItemAt index: Int) -> UICollectionViewCell { let cell = tabView.dequeueReusableCell(withReuseIdentifier: TabItemCell.reuseIdentifier, for: index) as! TabItemCell cell.titleLabel.text = items[index] // cell.normalTextFont = UIFont.boldSystemFont(ofSize: 17) cell.selectedTextFont = UIFont.systemFont(ofSize: 20) return cell } }
mit
7c2857379bc5fdbd87e0be045f48cc61
35.235714
132
0.63631
4.513345
false
false
false
false
kinwahlai/YetAnotherHTTPStub
YetAnotherHTTPStub/Matchers.swift
1
2319
// // Matchers.swift // YetAnotherHTTPStub // // Created by Darren Lai on 7/9/17. // Copyright © 2017 KinWahLai. All rights reserved. // import Foundation public func everything(_ urlrequest: URLRequest) -> Bool { return true } public func nothing(_ urlrequest: URLRequest) -> Bool { return false } public func uri(_ uri:String) -> (_ urlrequest: URLRequest) -> Bool { return { (_ urlrequest: URLRequest) -> Bool in guard let urlstring = urlrequest.url?.absoluteString, let _ = urlrequest.url?.path else { return false } guard var encodedUri = uri.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { return false } //restore wildcard backslashes that were encoded encodedUri = encodedUri.replacingOccurrences(of: "%5C", with: "\\") encodedUri = encodedUri.replacingOccurrences(of: "%7B", with: "{") encodedUri = encodedUri.replacingOccurrences(of: "%7D", with: "}") //escape regex characters encodedUri = encodedUri.replacingOccurrences(of: "?", with: "\\?") encodedUri = encodedUri.replacingOccurrences(of: "+", with: "\\+") let predicate = NSPredicate(format: "SELF MATCHES %@", encodedUri) if predicate.evaluate(with: urlstring) { return true } if let path = urlrequest.url?.path { var pathWithQuery = path if let query = urlrequest.url?.query { pathWithQuery = "\(path)?\(query)" } if predicate.evaluate(with: pathWithQuery) { return true } } return false } } public enum HTTPMethod: String { case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" } public func http(_ method: HTTPMethod, uri: String) -> (_ urlrequest: URLRequest) -> Bool { return { (_ urlrequest: URLRequest) -> Bool in guard let requestMethod = urlrequest.httpMethod else { return false } if (requestMethod == method.rawValue && YetAnotherHTTPStub.uri(uri)(urlrequest)) { return true } return false } }
mit
dabb3b982e9587ba46a1eadb0a2e67a0
31.194444
116
0.606557
4.365348
false
false
false
false
JGiola/swift-package-manager
Tests/SourceControlTests/GitRepositoryTests.swift
2
30603
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import Basic import SourceControl import Utility import TestSupport @testable import class SourceControl.GitRepository class GitRepositoryTests: XCTestCase { /// Test the basic provider functions. func testRepositorySpecifier() { let a = RepositorySpecifier(url: "a") let b = RepositorySpecifier(url: "b") let a2 = RepositorySpecifier(url: "a") XCTAssertEqual(a, a) XCTAssertNotEqual(a, b) XCTAssertEqual(a, a2) XCTAssertEqual(Set([a]), Set([a2])) } /// Test the basic provider functions. func testProvider() throws { mktmpdir { path in let testRepoPath = path.appending(component: "test-repo") try! makeDirectories(testRepoPath) initGitRepo(testRepoPath, tag: "1.2.3") // Test the provider. let testCheckoutPath = path.appending(component: "checkout") let provider = GitRepositoryProvider() XCTAssertTrue(try provider.checkoutExists(at: testRepoPath)) let repoSpec = RepositorySpecifier(url: testRepoPath.asString) try! provider.fetch(repository: repoSpec, to: testCheckoutPath) // Verify the checkout was made. XCTAssert(exists(testCheckoutPath)) // Test the repository interface. let repository = provider.open(repository: repoSpec, at: testCheckoutPath) let tags = repository.tags XCTAssertEqual(repository.tags, ["1.2.3"]) let revision = try repository.resolveRevision(tag: tags.first ?? "<invalid>") // FIXME: It would be nice if we had a deterministic hash here... XCTAssertEqual(revision.identifier, try Process.popen( args: Git.tool, "-C", testRepoPath.asString, "rev-parse", "--verify", "1.2.3").utf8Output().spm_chomp()) if let revision = try? repository.resolveRevision(tag: "<invalid>") { XCTFail("unexpected resolution of invalid tag to \(revision)") } let master = try repository.resolveRevision(identifier: "master") XCTAssertEqual(master.identifier, try Process.checkNonZeroExit( args: Git.tool, "-C", testRepoPath.asString, "rev-parse", "--verify", "master").spm_chomp()) // Check that git hashes resolve to themselves. let masterIdentifier = try repository.resolveRevision(identifier: master.identifier) XCTAssertEqual(master.identifier, masterIdentifier.identifier) // Check that invalid identifier doesn't resolve. if let revision = try? repository.resolveRevision(identifier: "invalid") { XCTFail("unexpected resolution of invalid identifier to \(revision)") } } } /// Check hash validation. func testGitRepositoryHash() throws { let validHash = "0123456789012345678901234567890123456789" XCTAssertNotEqual(GitRepository.Hash(validHash), nil) let invalidHexHash = validHash + "1" XCTAssertEqual(GitRepository.Hash(invalidHexHash), nil) let invalidNonHexHash = "012345678901234567890123456789012345678!" XCTAssertEqual(GitRepository.Hash(invalidNonHexHash), nil) } /// Check raw repository facilities. /// /// In order to be stable, this test uses a static test git repository in /// `Inputs`, which has known commit hashes. See the `construct.sh` script /// contained within it for more information. func testRawRepository() throws { mktmpdir { path in // Unarchive the static test repository. let inputArchivePath = AbsolutePath(#file).parentDirectory.appending(components: "Inputs", "TestRepo.tgz") try systemQuietly(["tar", "-x", "-v", "-C", path.asString, "-f", inputArchivePath.asString]) let testRepoPath = path.appending(component: "TestRepo") // Check hash resolution. let repo = GitRepository(path: testRepoPath) XCTAssertEqual(try repo.resolveHash(treeish: "1.0", type: "commit"), try repo.resolveHash(treeish: "master")) // Get the initial commit. let initialCommitHash = try repo.resolveHash(treeish: "a8b9fcb") XCTAssertEqual(initialCommitHash, GitRepository.Hash("a8b9fcbf893b3b02c0196609059ebae37aeb7f0b")) // Check commit loading. let initialCommit = try repo.read(commit: initialCommitHash) XCTAssertEqual(initialCommit.hash, initialCommitHash) XCTAssertEqual(initialCommit.tree, GitRepository.Hash("9d463c3b538619448c5d2ecac379e92f075a8976")) // Check tree loading. let initialTree = try repo.read(tree: initialCommit.tree) XCTAssertEqual(initialTree.hash, initialCommit.tree) XCTAssertEqual(initialTree.contents.count, 1) guard let readmeEntry = initialTree.contents.first else { return XCTFail() } XCTAssertEqual(readmeEntry.hash, GitRepository.Hash("92513075b3491a54c45a880be25150d92388e7bc")) XCTAssertEqual(readmeEntry.type, .blob) XCTAssertEqual(readmeEntry.name, "README.txt") // Check loading of odd names. // // This is a commit which has a subdirectory 'funny-names' with // paths with special characters. let funnyNamesCommit = try repo.read(commit: repo.resolveHash(treeish: "a7b19a7")) let funnyNamesRoot = try repo.read(tree: funnyNamesCommit.tree) XCTAssertEqual(funnyNamesRoot.contents.map{ $0.name }, ["README.txt", "funny-names", "subdir"]) guard funnyNamesRoot.contents.count == 3 else { return XCTFail() } // FIXME: This isn't yet supported. let funnyNamesSubdirEntry = funnyNamesRoot.contents[1] XCTAssertEqual(funnyNamesSubdirEntry.type, .tree) if let _ = try? repo.read(tree: funnyNamesSubdirEntry.hash) { XCTFail("unexpected success reading tree with funny names") } } } func testSubmoduleRead() throws { mktmpdir { path in let testRepoPath = path.appending(component: "test-repo") try makeDirectories(testRepoPath) initGitRepo(testRepoPath) let repoPath = path.appending(component: "repo") try makeDirectories(repoPath) initGitRepo(repoPath) try Process.checkNonZeroExit( args: Git.tool, "-C", repoPath.asString, "submodule", "add", testRepoPath.asString) let repo = GitRepository(path: repoPath) try repo.stageEverything() try repo.commit() // We should be able to read a repo which as a submdoule. _ = try repo.read(tree: try repo.resolveHash(treeish: "master")) } } /// Test the Git file system view. func testGitFileView() throws { mktmpdir { path in let testRepoPath = path.appending(component: "test-repo") try makeDirectories(testRepoPath) initGitRepo(testRepoPath) // Add a few files and a directory. let test1FileContents: ByteString = "Hello, world!" let test2FileContents: ByteString = "Hello, happy world!" let test3FileContents: ByteString = """ #!/bin/sh set -e exit 0 """ try localFileSystem.writeFileContents(testRepoPath.appending(component: "test-file-1.txt"), bytes: test1FileContents) try localFileSystem.createDirectory(testRepoPath.appending(component: "subdir")) try localFileSystem.writeFileContents(testRepoPath.appending(components: "subdir", "test-file-2.txt"), bytes: test2FileContents) try localFileSystem.writeFileContents(testRepoPath.appending(component: "test-file-3.sh"), bytes: test3FileContents) try! Process.checkNonZeroExit(args: "chmod", "+x", testRepoPath.appending(component: "test-file-3.sh").asString) let testRepo = GitRepository(path: testRepoPath) try testRepo.stage(files: "test-file-1.txt", "subdir/test-file-2.txt", "test-file-3.sh") try testRepo.commit() try testRepo.tag(name: "test-tag") // Get the the repository via the provider. the provider. let testClonePath = path.appending(component: "clone") let provider = GitRepositoryProvider() let repoSpec = RepositorySpecifier(url: testRepoPath.asString) try provider.fetch(repository: repoSpec, to: testClonePath) let repository = provider.open(repository: repoSpec, at: testClonePath) // Get and test the file system view. let view = try repository.openFileView(revision: repository.resolveRevision(tag: "test-tag")) // Check basic predicates. XCTAssert(view.isDirectory(AbsolutePath("/"))) XCTAssert(view.isDirectory(AbsolutePath("/subdir"))) XCTAssert(!view.isDirectory(AbsolutePath("/does-not-exist"))) XCTAssert(view.exists(AbsolutePath("/test-file-1.txt"))) XCTAssert(!view.exists(AbsolutePath("/does-not-exist"))) XCTAssert(view.isFile(AbsolutePath("/test-file-1.txt"))) XCTAssert(!view.isSymlink(AbsolutePath("/test-file-1.txt"))) XCTAssert(!view.isExecutableFile(AbsolutePath("/does-not-exist"))) XCTAssert(view.isExecutableFile(AbsolutePath("/test-file-3.sh"))) // Check read of a directory. XCTAssertEqual(try view.getDirectoryContents(AbsolutePath("/")).sorted(), ["file.swift", "subdir", "test-file-1.txt", "test-file-3.sh"]) XCTAssertEqual(try view.getDirectoryContents(AbsolutePath("/subdir")).sorted(), ["test-file-2.txt"]) XCTAssertThrows(FileSystemError.isDirectory) { _ = try view.readFileContents(AbsolutePath("/subdir")) } // Check read versus root. XCTAssertThrows(FileSystemError.isDirectory) { _ = try view.readFileContents(AbsolutePath("/")) } // Check read through a non-directory. XCTAssertThrows(FileSystemError.notDirectory) { _ = try view.getDirectoryContents(AbsolutePath("/test-file-1.txt")) } XCTAssertThrows(FileSystemError.notDirectory) { _ = try view.readFileContents(AbsolutePath("/test-file-1.txt/thing")) } // Check read/write into a missing directory. XCTAssertThrows(FileSystemError.noEntry) { _ = try view.getDirectoryContents(AbsolutePath("/does-not-exist")) } XCTAssertThrows(FileSystemError.noEntry) { _ = try view.readFileContents(AbsolutePath("/does/not/exist")) } // Check read of a file. XCTAssertEqual(try view.readFileContents(AbsolutePath("/test-file-1.txt")), test1FileContents) XCTAssertEqual(try view.readFileContents(AbsolutePath("/subdir/test-file-2.txt")), test2FileContents) } } /// Test the handling of local checkouts. func testCheckouts() throws { mktmpdir { path in // Create a test repository. let testRepoPath = path.appending(component: "test-repo") try makeDirectories(testRepoPath) initGitRepo(testRepoPath, tag: "initial") let initialRevision = try GitRepository(path: testRepoPath).getCurrentRevision() // Add a couple files and a directory. try localFileSystem.writeFileContents(testRepoPath.appending(component: "test.txt"), bytes: "Hi") let testRepo = GitRepository(path: testRepoPath) try testRepo.stage(file: "test.txt") try testRepo.commit() try testRepo.tag(name: "test-tag") let currentRevision = try GitRepository(path: testRepoPath).getCurrentRevision() // Fetch the repository using the provider. let testClonePath = path.appending(component: "clone") let provider = GitRepositoryProvider() let repoSpec = RepositorySpecifier(url: testRepoPath.asString) try provider.fetch(repository: repoSpec, to: testClonePath) // Clone off a checkout. let checkoutPath = path.appending(component: "checkout") try provider.cloneCheckout(repository: repoSpec, at: testClonePath, to: checkoutPath, editable: false) // The remote of this checkout should point to the clone. XCTAssertEqual(try GitRepository(path: checkoutPath).remotes()[0].url, testClonePath.asString) let editsPath = path.appending(component: "edit") try provider.cloneCheckout(repository: repoSpec, at: testClonePath, to: editsPath, editable: true) // The remote of this checkout should point to the original repo. XCTAssertEqual(try GitRepository(path: editsPath).remotes()[0].url, testRepoPath.asString) // Check the working copies. for path in [checkoutPath, editsPath] { let workingCopy = try provider.openCheckout(at: path) try workingCopy.checkout(tag: "test-tag") XCTAssertEqual(try workingCopy.getCurrentRevision(), currentRevision) XCTAssert(localFileSystem.exists(path.appending(component: "test.txt"))) try workingCopy.checkout(tag: "initial") XCTAssertEqual(try workingCopy.getCurrentRevision(), initialRevision) XCTAssert(!localFileSystem.exists(path.appending(component: "test.txt"))) } } } func testFetch() throws { mktmpdir { path in // Create a repo. let testRepoPath = path.appending(component: "test-repo") try makeDirectories(testRepoPath) initGitRepo(testRepoPath, tag: "1.2.3") let repo = GitRepository(path: testRepoPath) XCTAssertEqual(repo.tags, ["1.2.3"]) // Clone it somewhere. let testClonePath = path.appending(component: "clone") let provider = GitRepositoryProvider() let repoSpec = RepositorySpecifier(url: testRepoPath.asString) try provider.fetch(repository: repoSpec, to: testClonePath) let clonedRepo = provider.open(repository: repoSpec, at: testClonePath) XCTAssertEqual(clonedRepo.tags, ["1.2.3"]) // Clone off a checkout. let checkoutPath = path.appending(component: "checkout") try provider.cloneCheckout(repository: repoSpec, at: testClonePath, to: checkoutPath, editable: false) let checkoutRepo = try provider.openCheckout(at: checkoutPath) XCTAssertEqual(checkoutRepo.tags, ["1.2.3"]) // Add a new file to original repo. try localFileSystem.writeFileContents(testRepoPath.appending(component: "test.txt"), bytes: "Hi") let testRepo = GitRepository(path: testRepoPath) try testRepo.stage(file: "test.txt") try testRepo.commit() try testRepo.tag(name: "2.0.0") // Update the cloned repo. try clonedRepo.fetch() XCTAssertEqual(clonedRepo.tags.sorted(), ["1.2.3", "2.0.0"]) // Update the checkout. try checkoutRepo.fetch() XCTAssertEqual(checkoutRepo.tags.sorted(), ["1.2.3", "2.0.0"]) } } func testHasUnpushedCommits() throws { mktmpdir { path in // Create a repo. let testRepoPath = path.appending(component: "test-repo") try makeDirectories(testRepoPath) initGitRepo(testRepoPath) // Create a bare clone it somewhere because we want to later push into the repo. let testBareRepoPath = path.appending(component: "test-repo-bare") try systemQuietly([Git.tool, "clone", "--bare", testRepoPath.asString, testBareRepoPath.asString]) // Clone it somewhere. let testClonePath = path.appending(component: "clone") let provider = GitRepositoryProvider() let repoSpec = RepositorySpecifier(url: testBareRepoPath.asString) try provider.fetch(repository: repoSpec, to: testClonePath) // Clone off a checkout. let checkoutPath = path.appending(component: "checkout") try provider.cloneCheckout(repository: repoSpec, at: testClonePath, to: checkoutPath, editable: true) let checkoutRepo = try provider.openCheckout(at: checkoutPath) XCTAssertFalse(try checkoutRepo.hasUnpushedCommits()) // Add a new file to checkout. try localFileSystem.writeFileContents(checkoutPath.appending(component: "test.txt"), bytes: "Hi") let checkoutTestRepo = GitRepository(path: checkoutPath) try checkoutTestRepo.stage(file: "test.txt") try checkoutTestRepo.commit() // We should have commits which are not pushed. XCTAssert(try checkoutRepo.hasUnpushedCommits()) // Push the changes and check again. try checkoutTestRepo.push(remote: "origin", branch: "master") XCTAssertFalse(try checkoutRepo.hasUnpushedCommits()) } } func testSetRemote() { mktmpdir { path in // Create a repo. let testRepoPath = path.appending(component: "test-repo") try makeDirectories(testRepoPath) initGitRepo(testRepoPath) let repo = GitRepository(path: testRepoPath) // There should be no remotes currently. XCTAssert(try repo.remotes().isEmpty) // Add a remote via git cli. try systemQuietly([Git.tool, "-C", testRepoPath.asString, "remote", "add", "origin", "../foo"]) // Test if it was added. XCTAssertEqual(Dictionary(items: try repo.remotes().map { ($0.0, $0.1) }), ["origin": "../foo"]) // Change remote. try repo.setURL(remote: "origin", url: "../bar") XCTAssertEqual(Dictionary(items: try repo.remotes().map { ($0.0, $0.1) }), ["origin": "../bar"]) // Try changing remote of non-existant remote. do { try repo.setURL(remote: "fake", url: "../bar") XCTFail("unexpected success") } catch ProcessResult.Error.nonZeroExit {} } } func testUncommitedChanges() throws { mktmpdir { path in // Create a repo. let testRepoPath = path.appending(component: "test-repo") try makeDirectories(testRepoPath) initGitRepo(testRepoPath) // Create a file (which we will modify later). try localFileSystem.writeFileContents(testRepoPath.appending(component: "test.txt"), bytes: "Hi") let repo = GitRepository(path: testRepoPath) XCTAssert(repo.hasUncommittedChanges()) try repo.stage(file: "test.txt") XCTAssert(repo.hasUncommittedChanges()) try repo.commit() XCTAssertFalse(repo.hasUncommittedChanges()) // Modify the file in the repo. try localFileSystem.writeFileContents(repo.path.appending(component: "test.txt"), bytes: "Hello") XCTAssert(repo.hasUncommittedChanges()) } } func testBranchOperations() throws { mktmpdir { path in // Create a repo. let testRepoPath = path.appending(component: "test-repo") try makeDirectories(testRepoPath) initGitRepo(testRepoPath) let repo = GitRepository(path: testRepoPath) var currentRevision = try repo.getCurrentRevision() // This is the default branch of a new repo. XCTAssert(repo.exists(revision: Revision(identifier: "master"))) // Check a non existent revision. XCTAssertFalse(repo.exists(revision: Revision(identifier: "nonExistent"))) // Checkout a new branch using command line. try systemQuietly([Git.tool, "-C", testRepoPath.asString, "checkout", "-b", "TestBranch1"]) XCTAssert(repo.exists(revision: Revision(identifier: "TestBranch1"))) XCTAssertEqual(try repo.getCurrentRevision(), currentRevision) // Make sure we're on the new branch right now. XCTAssertEqual(try repo.currentBranch(), "TestBranch1") // Checkout new branch using our API. currentRevision = try repo.getCurrentRevision() try repo.checkout(newBranch: "TestBranch2") XCTAssert(repo.exists(revision: Revision(identifier: "TestBranch2"))) XCTAssertEqual(try repo.getCurrentRevision(), currentRevision) XCTAssertEqual(try repo.currentBranch(), "TestBranch2") } } func testCheckoutRevision() throws { mktmpdir { path in // Create a repo. let testRepoPath = path.appending(component: "test-repo") try makeDirectories(testRepoPath) initGitRepo(testRepoPath) let repo = GitRepository(path: testRepoPath) func createAndStageTestFile() throws { try localFileSystem.writeFileContents(testRepoPath.appending(component: "test.txt"), bytes: "Hi") try repo.stage(file: "test.txt") } try repo.checkout(revision: Revision(identifier: "master")) // Current branch must be master. XCTAssertEqual(try repo.currentBranch(), "master") // Create a new branch. try repo.checkout(newBranch: "TestBranch") XCTAssertEqual(try repo.currentBranch(), "TestBranch") // Create some random file. try createAndStageTestFile() XCTAssert(repo.hasUncommittedChanges()) // Checkout current revision again, the test file should go away. let currentRevision = try repo.getCurrentRevision() try repo.checkout(revision: currentRevision) XCTAssertFalse(repo.hasUncommittedChanges()) // We should be on detached head. XCTAssertEqual(try repo.currentBranch(), "HEAD") // Try again and checkout to a previous branch. try createAndStageTestFile() XCTAssert(repo.hasUncommittedChanges()) try repo.checkout(revision: Revision(identifier: "TestBranch")) XCTAssertFalse(repo.hasUncommittedChanges()) XCTAssertEqual(try repo.currentBranch(), "TestBranch") do { try repo.checkout(revision: Revision(identifier: "nonExistent")) XCTFail("Unexpected checkout success on non existent branch") } catch {} } } func testSubmodules() throws { mktmpdir { path in let provider = GitRepositoryProvider() // Create repos: foo and bar, foo will have bar as submodule and then later // the submodule ref will be updated in foo. let fooPath = path.appending(component: "foo-original") let fooSpecifier = RepositorySpecifier(url: fooPath.asString) let fooRepoPath = path.appending(component: "foo-repo") let fooWorkingPath = path.appending(component: "foo-working") let barPath = path.appending(component: "bar-original") let bazPath = path.appending(component: "baz-original") // Create the repos and add a file. for path in [fooPath, barPath, bazPath] { try makeDirectories(path) initGitRepo(path) try localFileSystem.writeFileContents(path.appending(component: "hello.txt"), bytes: "hello") let repo = GitRepository(path: path) try repo.stageEverything() try repo.commit() } let foo = GitRepository(path: fooPath) let bar = GitRepository(path: barPath) // The tag 1.0.0 does not contain the submodule. try foo.tag(name: "1.0.0") // Fetch and clone repo foo. try provider.fetch(repository: fooSpecifier, to: fooRepoPath) try provider.cloneCheckout(repository: fooSpecifier, at: fooRepoPath, to: fooWorkingPath, editable: false) let fooRepo = GitRepository(path: fooRepoPath, isWorkingRepo: false) let fooWorkingRepo = GitRepository(path: fooWorkingPath) // Checkout the first tag which doesn't has submodule. try fooWorkingRepo.checkout(tag: "1.0.0") XCTAssertFalse(exists(fooWorkingPath.appending(component: "bar"))) // Add submodule to foo and tag it as 1.0.1 try foo.checkout(newBranch: "submodule") try systemQuietly([Git.tool, "-C", fooPath.asString, "submodule", "add", barPath.asString, "bar"]) try foo.stageEverything() try foo.commit() try foo.tag(name: "1.0.1") // Update our bare and working repos. try fooRepo.fetch() try fooWorkingRepo.fetch() // Checkout the tag with submodule and expect submodules files to be present. try fooWorkingRepo.checkout(tag: "1.0.1") XCTAssertTrue(exists(fooWorkingPath.appending(components: "bar", "hello.txt"))) // Checkout the tag without submodule and ensure that the submodule files are gone. try fooWorkingRepo.checkout(tag: "1.0.0") XCTAssertFalse(exists(fooWorkingPath.appending(components: "bar"))) // Add something to bar. try localFileSystem.writeFileContents(barPath.appending(component: "bar.txt"), bytes: "hello") // Add a submodule too to check for recusive submodules. try systemQuietly([Git.tool, "-C", barPath.asString, "submodule", "add", bazPath.asString, "baz"]) try bar.stageEverything() try bar.commit() // Update the ref of bar in foo and tag as 1.0.2 try systemQuietly([Git.tool, "-C", fooPath.appending(component: "bar").asString, "pull"]) try foo.stageEverything() try foo.commit() try foo.tag(name: "1.0.2") try fooRepo.fetch() try fooWorkingRepo.fetch() // We should see the new file we added in the submodule. try fooWorkingRepo.checkout(tag: "1.0.2") XCTAssertTrue(exists(fooWorkingPath.appending(components: "bar", "hello.txt"))) XCTAssertTrue(exists(fooWorkingPath.appending(components: "bar", "bar.txt"))) XCTAssertTrue(exists(fooWorkingPath.appending(components: "bar", "baz", "hello.txt"))) // Sanity check. try fooWorkingRepo.checkout(tag: "1.0.0") XCTAssertFalse(exists(fooWorkingPath.appending(components: "bar"))) } } func testAlternativeObjectStoreValidation() throws { mktmpdir { path in // Create a repo. let testRepoPath = path.appending(component: "test-repo") try makeDirectories(testRepoPath) initGitRepo(testRepoPath, tag: "1.2.3") let repo = GitRepository(path: testRepoPath) XCTAssertEqual(repo.tags, ["1.2.3"]) // Clone it somewhere. let testClonePath = path.appending(component: "clone") let provider = GitRepositoryProvider() let repoSpec = RepositorySpecifier(url: testRepoPath.asString) try provider.fetch(repository: repoSpec, to: testClonePath) let clonedRepo = provider.open(repository: repoSpec, at: testClonePath) XCTAssertEqual(clonedRepo.tags, ["1.2.3"]) // Clone off a checkout. let checkoutPath = path.appending(component: "checkout") try provider.cloneCheckout(repository: repoSpec, at: testClonePath, to: checkoutPath, editable: false) let checkoutRepo = try provider.openCheckout(at: checkoutPath) // The object store should be valid. XCTAssertTrue(checkoutRepo.isAlternateObjectStoreValid()) // Delete the clone (alternative object store). try localFileSystem.removeFileTree(testClonePath) XCTAssertFalse(checkoutRepo.isAlternateObjectStoreValid()) } } func testAreIgnored() throws { mktmpdir { path in // Create a repo. let testRepoPath = path.appending(component: "test_repo") try makeDirectories(testRepoPath) initGitRepo(testRepoPath) let repo = GitRepository(path: testRepoPath) // Add a .gitignore try localFileSystem.writeFileContents(testRepoPath.appending(component: ".gitignore"), bytes: "ignored_file1\nignored file2") let ignored = try repo.areIgnored([testRepoPath.appending(component: "ignored_file1"), testRepoPath.appending(component: "ignored file2"), testRepoPath.appending(component: "not ignored")]) XCTAssertTrue(ignored[0]) XCTAssertTrue(ignored[1]) XCTAssertFalse(ignored[2]) let notIgnored = try repo.areIgnored([testRepoPath.appending(component: "not_ignored")]) XCTAssertFalse(notIgnored[0]) } } func testAreIgnoredWithSpaceInRepoPath() throws { mktmpdir { path in // Create a repo. let testRepoPath = path.appending(component: "test repo") try makeDirectories(testRepoPath) initGitRepo(testRepoPath) let repo = GitRepository(path: testRepoPath) // Add a .gitignore try localFileSystem.writeFileContents(testRepoPath.appending(component: ".gitignore"), bytes: "ignored_file1") let ignored = try repo.areIgnored([testRepoPath.appending(component: "ignored_file1")]) XCTAssertTrue(ignored[0]) } } }
apache-2.0
30cb8423aaa5f2acbd045099757d68cd
46.520186
201
0.623632
4.684372
false
true
false
false